From b11d3cee50560a81befff998a1a196f8511aaccd Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:16:52 +0530 Subject: [PATCH 01/85] Clean up RuboCop config --- .rubocop.yml => .rubocop.yml.erb | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) rename .rubocop.yml => .rubocop.yml.erb (89%) diff --git a/.rubocop.yml b/.rubocop.yml.erb similarity index 89% rename from .rubocop.yml rename to .rubocop.yml.erb index 7cf5f3c079..84bde1cead 100644 --- a/.rubocop.yml +++ b/.rubocop.yml.erb @@ -1,12 +1,12 @@ AllCops: - Exclude: - - 'test/**/*' - - 'tmp/**/*' - - 'tools/**/*' - - 'doc/**/*' TargetRubyVersion: <%= File.read(".ruby-version").strip[/^(\d+\.\d+)/, 1] || raise("Ruby version not found") %> + NewCops: enable + Exclude: + - "tools/**/*" + - "test/**/*" + Layout/LineLength: Enabled: true Max: 180 @@ -20,6 +20,9 @@ Metrics/BlockLength: Metrics/ClassLength: Enabled: false +Metrics/CyclomaticComplexity: + Enabled: false + Metrics/MethodLength: Enabled: false @@ -29,14 +32,11 @@ Metrics/ModuleLength: Metrics/PerceivedComplexity: Enabled: false -Metrics/CyclomaticComplexity: - Enabled: false - Naming/ClassAndModuleCamelCase: Enabled: false -Style/FrozenStringLiteralComment: +Style/Documentation: Enabled: false -Style/Documentation: +Style/FrozenStringLiteralComment: Enabled: false From 2ecca88a22589300bf39af6f848eaa363f52e8ab Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:19:40 +0530 Subject: [PATCH 02/85] rubocop --only Layout/EmptyLineAfterGuardClause -a --- core/main/autorun_engine/parser.rb | 2 ++ core/main/configuration.rb | 1 + core/main/rest/handlers/autorun_engine.rb | 2 ++ core/module.rb | 2 ++ extensions/admin_ui/api/handler.rb | 2 ++ extensions/dns/dns.rb | 1 + extensions/qrcode/qrcode.rb | 1 + spec/beef/core/modules_spec.rb | 2 ++ spec/spec_helper.rb | 2 ++ spec/support/ui_support.rb | 1 + tools/maintenance/copyright_update.rb | 1 + tools/rest_api_examples/browser-details | 3 +++ tools/rest_api_examples/command-modules | 2 ++ tools/rest_api_examples/export-logs | 3 +++ tools/rest_api_examples/metasploit | 1 + tools/rest_api_examples/network | 4 ++++ tools/rest_api_examples/remove-offline-browsers | 1 + tools/rest_api_examples/webrtc | 1 + tools/rest_api_examples/xssrays | 4 ++++ 19 files changed, 36 insertions(+) diff --git a/core/main/autorun_engine/parser.rb b/core/main/autorun_engine/parser.rb index 93a4c34b9e..3a83eb6385 100644 --- a/core/main/autorun_engine/parser.rb +++ b/core/main/autorun_engine/parser.rb @@ -28,11 +28,13 @@ def parse(name, author, browser, browser_version, os, os_version, modules, execu unless modules.size == execution_delay.size raise ArgumentError, "Number of execution_delay values (#{execution_delay.size}) must be consistent with number of modules (#{modules.size})" end + execution_delay.each { |delay| raise TypeError, "Invalid execution_delay value: #{delay}. Values must be Integers." unless delay.is_a?(Integer) } unless modules.size == execution_order.size raise ArgumentError, "Number of execution_order values (#{execution_order.size}) must be consistent with number of modules (#{modules.size})" end + execution_order.each { |order| raise TypeError, "Invalid execution_order value: #{order}. Values must be Integers." unless order.is_a?(Integer) } # if multiple browsers were specified, check each browser diff --git a/core/main/configuration.rb b/core/main/configuration.rb index e3a37144c1..e84a21c40d 100644 --- a/core/main/configuration.rb +++ b/core/main/configuration.rb @@ -42,6 +42,7 @@ def initialize(config) # @return [Hash] YAML formatted hash def load(file) return nil unless File.exist?(file) + YAML.safe_load(File.binread(file)) end diff --git a/core/main/rest/handlers/autorun_engine.rb b/core/main/rest/handlers/autorun_engine.rb index 24b73b02e7..b30026f548 100644 --- a/core/main/rest/handlers/autorun_engine.rb +++ b/core/main/rest/handlers/autorun_engine.rb @@ -73,6 +73,7 @@ class AutorunEngine < BeEF::Core::Router::Router rule_id = params[:rule_id] rule = BeEF::Core::Models::Rule.find(rule_id) raise InvalidParameterError, 'id' if rule.nil? + rule.destroy { 'success' => true }.to_json @@ -91,6 +92,7 @@ class AutorunEngine < BeEF::Core::Router::Router rule_id = params[:rule_id] rule = BeEF::Core::Models::Rule.find(rule_id) raise InvalidParameterError, 'id' if rule.nil? + data = JSON.parse request.body.read rloader = BeEF::Core::AutorunEngine::RuleLoader.instance rloader.update_rule_json(rule_id, data) diff --git a/core/module.rb b/core/module.rb index a6b29fc950..eb9dff7122 100644 --- a/core/module.rb +++ b/core/module.rb @@ -230,10 +230,12 @@ def self.support(mod, opts) if opts.key?('ver') if subv.key?('min_ver') break unless subv['min_ver'].is_a?(Integer) && opts['ver'].to_i >= subv['min_ver'] + rating += 1 end if subv.key?('max_ver') break unless (subv['max_ver'].is_a?(Integer) && opts['ver'].to_i <= subv['max_ver']) || subv['max_ver'] == 'latest' + rating += 1 end end diff --git a/extensions/admin_ui/api/handler.rb b/extensions/admin_ui/api/handler.rb index c220af8ba0..d042b0f4be 100644 --- a/extensions/admin_ui/api/handler.rb +++ b/extensions/admin_ui/api/handler.rb @@ -119,6 +119,7 @@ def self.build_javascript_ui unless web_ui_all raise StandardError, "[AdminUI] evaluate_and_minify JavaScript failed: web_ui_all JavaScript is empty" end + write_minified_js('web_ui_all.js', web_ui_all) auth_js_file = "#{File.binread("#{File.dirname(__FILE__)}/../media/javascript/ui/authentication.js")}\n\n" @@ -126,6 +127,7 @@ def self.build_javascript_ui unless web_ui_auth raise StandardError, "[AdminUI] evaluate_and_minify JavaScript failed: web_ui_auth JavaScript is empty" end + write_minified_js('web_ui_auth.js', web_ui_auth) rescue => e raise StandardError, "Building Admin UI JavaScript failed: #{e.message}" diff --git a/extensions/dns/dns.rb b/extensions/dns/dns.rb index ccddb45130..5a8583d676 100644 --- a/extensions/dns/dns.rb +++ b/extensions/dns/dns.rb @@ -121,6 +121,7 @@ def run(options = {}) Thread.new do EventMachine.next_tick do next if @server_started # Check if the server was already started + upstream = options[:upstream] || nil listen = options[:listen] || nil diff --git a/extensions/qrcode/qrcode.rb b/extensions/qrcode/qrcode.rb index 6f4df29019..1358de4a41 100644 --- a/extensions/qrcode/qrcode.rb +++ b/extensions/qrcode/qrcode.rb @@ -37,6 +37,7 @@ def self.pre_http_start(_http_hook_server) interfaces.each do |int| # Skip the loop iteration if the interface address is '0.0.0.0' (which generally represents all IPv4 addresses on the local machine) next if int == '0.0.0.0' + # Construct full URLs using the network interface address, and add them to the fullurls array # The URL is composed of the BeEF protocol, interface address, BeEF port, and the target path fullurls << "#{beef_proto}://#{int}:#{beef_port}#{target}" diff --git a/spec/beef/core/modules_spec.rb b/spec/beef/core/modules_spec.rb index f9cb319375..0d2e581664 100644 --- a/spec/beef/core/modules_spec.rb +++ b/spec/beef/core/modules_spec.rb @@ -26,6 +26,7 @@ it 'safe client debug log' do Dir['../../modules/**/*.js'].each do |path| next unless File.file?(path) + File.open(path) do |f| f.grep(/\bconsole\.log\W*\(/m) do |line| fail "Function 'console.log' instead of 'beef.debug' inside\n Path: #{path}\nLine: #{line}" @@ -37,6 +38,7 @@ it 'safe variable decleration' do Dir['../../modules/**/*.js'].each do |path| next unless File.file?(path) + File.open(path) do |f| f.grep(/\blet\W+[a-zA-Z0-9_\.]+\W*=/) do |line| fail "Variable declared with 'let' instead of 'var' inside\n Path: #{path}\nLine: #{line}" diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index aa23cbfbb7..9cc0c508ab 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -89,6 +89,7 @@ def level def method_missing(m, *args, &blk) lg = (self.logger ||= Logger.new($stdout)) return lg.public_send(m, *args, &blk) if lg.respond_to?(m) + super end def respond_to_missing?(m, include_priv = false) @@ -115,6 +116,7 @@ def level def method_missing(m, *args, &blk) lg = (self.logger ||= Logger.new($stdout)) return lg.public_send(m, *args, &blk) if lg.respond_to?(m) + super end def respond_to_missing?(m, include_priv = false) diff --git a/spec/support/ui_support.rb b/spec/support/ui_support.rb index e350d9bfa5..0311202067 100644 --- a/spec/support/ui_support.rb +++ b/spec/support/ui_support.rb @@ -67,6 +67,7 @@ def expand_category_tree(session, category, module_name = nil) begin element_text = element.text next unless element_text.start_with?(category_name) + match_data = element_text.match(/\A([\w\s]+)\s\((\d+)\)\z/) next unless match_data diff --git a/tools/maintenance/copyright_update.rb b/tools/maintenance/copyright_update.rb index 95cb45016d..3471ba4619 100644 --- a/tools/maintenance/copyright_update.rb +++ b/tools/maintenance/copyright_update.rb @@ -38,6 +38,7 @@ def update_copyright(file_path, old_copyright, new_copyright) Dir.glob("../../**/*.{rb,js,yaml,html,md,txt,css,c,nasm,java,php,as}").each do |file| next if File.basename(file) == 'copyright_update.rb' # Skip this file + update_copyright(file, old_copyright, new_copyright) end diff --git a/tools/rest_api_examples/browser-details b/tools/rest_api_examples/browser-details index cdd18943bb..f99979bd1f 100755 --- a/tools/rest_api_examples/browser-details +++ b/tools/rest_api_examples/browser-details @@ -74,6 +74,7 @@ print_debug hooks # Retrieve hooked browser details hooks.each do |hook| next if hook['id'].nil? + print_status "Retrieving details for browser [id: #{hook['id']}]" details = @api.browser_details(hook['session']) print_debug details @@ -83,11 +84,13 @@ end # Retrieve hooked browser logs hooks.each do |hook| next if hook['id'].nil? + print_status "Retrieving logs for browser [id: #{hook['id']}]" logs = @api.browser_logs(hook['session']) print_debug logs logs['logs'].each do |log| next if log['id'].nil? + print_verbose "#{log['date']} - #{log['event']}" end end diff --git a/tools/rest_api_examples/command-modules b/tools/rest_api_examples/command-modules index 3629af685c..c5a6735e3b 100755 --- a/tools/rest_api_examples/command-modules +++ b/tools/rest_api_examples/command-modules @@ -77,6 +77,7 @@ print_debug modules # Retrieve module details modules.each do |m| next if m['id'].nil? + print_status "Retrieving module details [id: #{m['id']}]" details = @api.module_details(m['id']) print_debug details @@ -91,6 +92,7 @@ print_debug hooks mod_id = @api.get_module_id "Alert_dialog" hooks.each do |hook| next if hook['id'].nil? + print_status "Executing module [id: #{mod_id}, browser: #{hook['id']}]" result = @api.execute_module(hook['session'], mod_id, { "text" => "hello!" }) print_debug result diff --git a/tools/rest_api_examples/export-logs b/tools/rest_api_examples/export-logs index e26f15d7e0..a46a771329 100755 --- a/tools/rest_api_examples/export-logs +++ b/tools/rest_api_examples/export-logs @@ -71,6 +71,7 @@ logs = @api.logs print_debug logs logs['logs'].each do |log| next if log['id'].nil? + print_verbose "#{log['date']} - #{log['event']}" end @@ -82,11 +83,13 @@ print_debug hooks # Retrieve hooked browser logs hooks.each do |hook| next if hook['id'].nil? + print_status "Retrieving logs for browser [id: #{hook['id']}]" logs = @api.browser_logs(hook['session']) print_debug logs logs['logs'].each do |log| next if log['id'].nil? + print_verbose "#{log['date']} - #{log['event']}" end end diff --git a/tools/rest_api_examples/metasploit b/tools/rest_api_examples/metasploit index c7127da370..b504d2f9c0 100755 --- a/tools/rest_api_examples/metasploit +++ b/tools/rest_api_examples/metasploit @@ -86,6 +86,7 @@ print_debug jobs # Retrieve msf job details jobs.each do |job_id,job_name| next if job_id !~ /\A\d+\Z/ + print_status "Retrieving details for Metasploit job [id: #{job_id}] [#{job_name}]" details = @api.msf_job_info(job_id) print_debug details diff --git a/tools/rest_api_examples/network b/tools/rest_api_examples/network index 329f862301..75f83834fa 100755 --- a/tools/rest_api_examples/network +++ b/tools/rest_api_examples/network @@ -82,11 +82,13 @@ print_debug hooks # Retrieve network hosts for each hooked browser hooks.each do |hook| next if hook['id'].nil? + print_status "Retrieving network hosts for browser [id: #{hook['id']}]" hosts = @api.network_hosts(hook['session']) print_debug hosts hosts['hosts'].each do |host| next if host['id'].nil? + print_verbose "#{host['ip']}" + (" - #{host['type']}" unless host['type'].nil?).to_s end end @@ -94,11 +96,13 @@ end # Retrieve network services for each hooked browser hooks.each do |hook| next if hook['id'].nil? + print_status "Retrieving network services for browser [id: #{hook['id']}]" services = @api.network_services(hook['session']) print_debug services services['services'].each do |service| next if service['id'].nil? + print_verbose "#{service['ip']}:#{service['port']}" + (" - #{service['type']}" unless service['type'].nil?).to_s end end diff --git a/tools/rest_api_examples/remove-offline-browsers b/tools/rest_api_examples/remove-offline-browsers index ab5641048d..fe3b8c50d8 100644 --- a/tools/rest_api_examples/remove-offline-browsers +++ b/tools/rest_api_examples/remove-offline-browsers @@ -74,6 +74,7 @@ print_debug hooks # Remove each offline browser hooks.each do |hook| next if hook['id'].nil? + print_status "Removing hooked browser [id: #{hook['id']}]" details = @api.delete_browser(hook['session']) print_debug details diff --git a/tools/rest_api_examples/webrtc b/tools/rest_api_examples/webrtc index e69bb073fc..f2983f654b 100755 --- a/tools/rest_api_examples/webrtc +++ b/tools/rest_api_examples/webrtc @@ -74,6 +74,7 @@ print_debug hooks # Retrieve hooked browser details hooks.each do |hook| next if hook['id'].nil? + print_status "Retrieving WebRTC status for browser [id: #{hook['id']}]" details = @api.webrtc_status(hook['id']) print_debug details diff --git a/tools/rest_api_examples/xssrays b/tools/rest_api_examples/xssrays index ca955c2d3d..3e4b0c7567 100755 --- a/tools/rest_api_examples/xssrays +++ b/tools/rest_api_examples/xssrays @@ -81,11 +81,13 @@ print_debug hooks # Retrieve rays for each hooked browser hooks.each do |hook| next if hook['id'].nil? + print_status "Retrieving rays for browser [id: #{hook['id']}]" rays = @api.xssrays_rays(hook['session']) print_debug rays rays['rays'].each do |ray| next if ray['id'].nil? + print_verbose "#{ray['vector_name']} (#{ray['vector_method']})" end end @@ -93,11 +95,13 @@ end # Retrieve scans for each hooked browser hooks.each do |hook| next if hook['id'].nil? + print_status "Retrieving scans for browser [id: #{hook['id']}]" scans = @api.xssrays_scans(hook['session']) print_debug scans scans['scans'].each do |scan| next if scan['id'].nil? + print_verbose "Scan [#{scan['id']}] on domain #{scan['domain']}" end end From d1a46883be51ae0fd11c13fe732fff83b028052d Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:20:40 +0530 Subject: [PATCH 03/85] be rubocop --only Style/StringLiterals -a --- Rakefile | 30 +++++------ beef | 8 +-- core/main/handlers/browserdetails.rb | 4 +- core/main/handlers/commands.rb | 2 +- extensions/admin_ui/api/handler.rb | 4 +- extensions/webrtc/api/hook.rb | 10 ++-- extensions/webrtc/handlers.rb | 46 ++++++++--------- extensions/webrtc/models/rtcmanage.rb | 4 +- spec/beef/api/auth_rate_spec.rb | 22 ++++---- spec/beef/core/filter/filters_spec.rb | 42 ++++++++-------- .../handlers/dynamic_reconstruction_spec.rb | 6 +-- .../network_stack/handlers/redirector_spec.rb | 8 +-- spec/beef/extensions/adminui_spec.rb | 24 ++++----- .../extensions/social_engineering_spec.rb | 4 +- spec/beef/security_checks_spec.rb | 2 +- spec/features/all_modules_spec.rb | 4 +- spec/features/debug_modules_spec.rb | 4 +- spec/requests/login_spec.rb | 2 +- spec/spec_helper.rb | 12 ++--- spec/support/ui_support.rb | 6 +-- test/integration/tc_debug_modules.rb | 26 +++++----- test/integration/tc_dns_rest.rb | 2 +- test/integration/tc_network_rest.rb | 6 +-- .../integration/tc_social_engineering_rest.rb | 4 +- test/integration/tc_webrtc_rest.rb | 50 +++++++++---------- test/integration/ts_integration.rb | 2 +- test/thirdparty/msf/unit/tc_metasploit.rb | 2 +- test/thirdparty/msf/unit/ts_metasploit.rb | 4 +- tools/csrf_to_beef/csrf_to_beef | 40 +++++++-------- tools/csrf_to_beef/lib/module.rb | 4 +- tools/maintenance/copyright_update.rb | 8 +-- tools/rest_api_examples/autorun | 18 +++---- tools/rest_api_examples/browser-details | 6 +-- tools/rest_api_examples/clone_page | 6 +-- tools/rest_api_examples/command-modules | 10 ++-- tools/rest_api_examples/dns | 12 ++--- tools/rest_api_examples/export-logs | 6 +-- tools/rest_api_examples/lib/beef_rest_api.rb | 38 +++++++------- tools/rest_api_examples/metasploit | 6 +-- tools/rest_api_examples/network | 6 +-- .../rest_api_examples/remove-offline-browsers | 6 +-- tools/rest_api_examples/webrtc | 6 +-- tools/rest_api_examples/xssrays | 6 +-- 43 files changed, 259 insertions(+), 259 deletions(-) diff --git a/Rakefile b/Rakefile index 258b392ba6..f3581cf1c3 100644 --- a/Rakefile +++ b/Rakefile @@ -5,7 +5,7 @@ # require 'rspec/core/rake_task' -task :default => ["short"] +task :default => ['short'] RSpec::Core::RakeTask.new(:short) do |task| task.rspec_opts = ['--tag ~run_on_browserstack', '--tag ~run_on_long_tests'] @@ -27,7 +27,7 @@ RSpec::Core::RakeTask.new(:browserstack) do |task| end RSpec::Core::RakeTask.new(:bs) do |task| - configs = Dir["spec/support/browserstack/**/*.yml"] + configs = Dir['spec/support/browserstack/**/*.yml'] configs.each do |config| config = config.split('spec/support/browserstack')[1] ENV['CONFIG_FILE'] = config @@ -48,7 +48,7 @@ namespace :ssl do puts 'Certificate already exists. Replace? [Y/n]' confirm = STDIN.getch.chomp unless confirm.eql?('') || confirm.downcase.eql?('y') - puts "Aborted" + puts 'Aborted' exit 1 end end @@ -62,7 +62,7 @@ namespace :ssl do elsif File.file?('/usr/bin/openssl') path = '/usr/bin/openssl' else - puts "[-] Error: could not find openssl" + puts '[-] Error: could not find openssl' exit 1 end IO.popen([path, 'req', '-new', '-newkey', 'rsa:4096', '-sha256', '-x509', '-days', '3650', '-nodes', '-out', 'beef_cert.pem', '-keyout', 'beef_key.pem', '-subj', '/CN=localhost'], 'r+').read.to_s @@ -101,8 +101,8 @@ end @xserver_process_id = nil; task :xserver_start do - printf "Starting X11 Server (wait 10 seconds)..." - @xserver_process_id = IO.popen("/usr/bin/Xvfb :0 -screen 0 1024x768x24 2> /dev/null", "w+") + printf 'Starting X11 Server (wait 10 seconds)...' + @xserver_process_id = IO.popen('/usr/bin/Xvfb :0 -screen 0 1024x768x24 2> /dev/null', 'w+') delays = [2, 2, 1, 1, 1, 0.5, 0.5, 0.5, 0.3, 0.2, 0.1, 0.1, 0.1, 0.05, 0.05] delays.each do |i| # delay for 10 seconds printf '.' @@ -140,8 +140,8 @@ task :beef_start => 'beef' do config = nil puts "Using config file: #{@beef_config_file}\n" - printf "Starting BeEF (wait a few seconds)..." - @beef_process_id = IO.popen("ruby ./beef -c #{@beef_config_file} -x 2> /dev/null", "w+") + printf 'Starting BeEF (wait a few seconds)...' + @beef_process_id = IO.popen("ruby ./beef -c #{@beef_config_file} -x 2> /dev/null", 'w+') delays = [5, 5, 5, 4, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1] delays.each do |i| # delay for a few seconds printf '.' @@ -168,8 +168,8 @@ end @msf_process_id = nil; task :msf_start => '/tmp/msf-test/msfconsole' do - printf "Starting MSF (wait 45 seconds)..." - @msf_process_id = IO.popen("/tmp/msf-test/msfconsole -r test/thirdparty/msf/unit/BeEF.rc 2> /dev/null", "w+") + printf 'Starting MSF (wait 45 seconds)...' + @msf_process_id = IO.popen('/tmp/msf-test/msfconsole -r test/thirdparty/msf/unit/BeEF.rc 2> /dev/null', 'w+') delays = [10, 7, 6, 5, 4, 3, 2, 2, 1, 1, 1, 0.5, 0.5, 0.5, 0.3, 0.2, 0.1, 0.1, 0.1, 0.05, 0.05] delays.each do |i| # delay for 45 seconds printf '.' @@ -180,7 +180,7 @@ end task :msf_stop do puts "\nShutting down MSF...\n" - @msf_process_id.puts "quit" + @msf_process_id.puts 'quit' end task :msf_install => '/tmp/msf-test/msfconsole' do @@ -188,18 +188,18 @@ task :msf_install => '/tmp/msf-test/msfconsole' do end task :msf_update => '/tmp/msf-test/msfconsole' do - sh "cd /tmp/msf-test;git pull" + sh 'cd /tmp/msf-test;git pull' end file '/tmp/msf-test/msfconsole' do - puts "Installing MSF" - sh "cd test;git clone https://github.com/rapid7/metasploit-framework.git /tmp/msf-test" + puts 'Installing MSF' + sh 'cd test;git clone https://github.com/rapid7/metasploit-framework.git /tmp/msf-test' end ################################ # ActiveRecord namespace :db do task :environment do - require_relative "beef" + require_relative 'beef' end end diff --git a/beef b/beef index e0d9375a6e..674151cc66 100755 --- a/beef +++ b/beef @@ -123,9 +123,9 @@ end # # @note Exit on default credentials # -if config.get("beef.credentials.user").eql?('beef') && config.get("beef.credentials.passwd").eql?('beef') - print_error "ERROR: Default username and password in use!" - print_more "Change the beef.credentials.passwd in config.yaml" +if config.get('beef.credentials.user').eql?('beef') && config.get('beef.credentials.passwd').eql?('beef') + print_error 'ERROR: Default username and password in use!' + print_more 'Change the beef.credentials.passwd in config.yaml' exit 1 end @@ -270,7 +270,7 @@ BeEF::Core::AutorunEngine::RuleLoader.instance.load_directory # # @note Start the WebSocket server # -if config.get("beef.http.websocket.enable") +if config.get('beef.http.websocket.enable') BeEF::Core::Websocket::Websocket.instance BeEF::Core::Console::Banners.print_websocket_servers end diff --git a/core/main/handlers/browserdetails.rb b/core/main/handlers/browserdetails.rb index f69eef9480..4e401cc89c 100644 --- a/core/main/handlers/browserdetails.rb +++ b/core/main/handlers/browserdetails.rb @@ -400,8 +400,8 @@ def setup browser_plugins = get_param(@data['results'], 'browser.plugins') if BeEF::Filters.is_valid_browser_plugins?(browser_plugins) BD.set(session_id, 'browser.plugins', browser_plugins) - elsif browser_plugins == "[]" - err_msg "No browser plugins detected." + elsif browser_plugins == '[]' + err_msg 'No browser plugins detected.' else err_msg "Invalid browser plugins returned from the hook browser's initial connection." end diff --git a/core/main/handlers/commands.rb b/core/main/handlers/commands.rb index 8d033b9e76..736338c8bf 100644 --- a/core/main/handlers/commands.rb +++ b/core/main/handlers/commands.rb @@ -39,7 +39,7 @@ def setup # @note get and check command id from the request command_id = get_param(@data, 'cid') unless command_id.is_a?(Integer) - print_error("Command ID is invalid") + print_error('Command ID is invalid') return end diff --git a/extensions/admin_ui/api/handler.rb b/extensions/admin_ui/api/handler.rb index d042b0f4be..04a387c2cd 100644 --- a/extensions/admin_ui/api/handler.rb +++ b/extensions/admin_ui/api/handler.rb @@ -117,7 +117,7 @@ def self.build_javascript_ui web_ui_all = evaluate_and_minify(admin_ui_js, params) unless web_ui_all - raise StandardError, "[AdminUI] evaluate_and_minify JavaScript failed: web_ui_all JavaScript is empty" + raise StandardError, '[AdminUI] evaluate_and_minify JavaScript failed: web_ui_all JavaScript is empty' end write_minified_js('web_ui_all.js', web_ui_all) @@ -125,7 +125,7 @@ def self.build_javascript_ui auth_js_file = "#{File.binread("#{File.dirname(__FILE__)}/../media/javascript/ui/authentication.js")}\n\n" web_ui_auth = evaluate_and_minify(auth_js_file, params) unless web_ui_auth - raise StandardError, "[AdminUI] evaluate_and_minify JavaScript failed: web_ui_auth JavaScript is empty" + raise StandardError, '[AdminUI] evaluate_and_minify JavaScript failed: web_ui_auth JavaScript is empty' end write_minified_js('web_ui_auth.js', web_ui_auth) diff --git a/extensions/webrtc/api/hook.rb b/extensions/webrtc/api/hook.rb index c7dff31555..8aac01bf68 100644 --- a/extensions/webrtc/api/hook.rb +++ b/extensions/webrtc/api/hook.rb @@ -29,17 +29,17 @@ def requester_run(hb, body) rtcmanagementoutput = [] # Get all RTCSignals for this browser - BeEF::Core::Models::RtcSignal.where(:target_hooked_browser_id => hb.id, :has_sent => "waiting").each { |h| + BeEF::Core::Models::RtcSignal.where(:target_hooked_browser_id => hb.id, :has_sent => 'waiting').each { |h| # output << self.requester_parse_db_request(h) rtcsignaloutput << h.signal - h.has_sent = "sent" + h.has_sent = 'sent' h.save } # Get all RTCManagement messages for this browser - BeEF::Core::Models::RtcManage.where(:hooked_browser_id => hb.id, :has_sent => "waiting").each {|h| + BeEF::Core::Models::RtcManage.where(:hooked_browser_id => hb.id, :has_sent => 'waiting').each {|h| rtcmanagementoutput << h.message - h.has_sent = "sent" + h.has_sent = 'sent' h.save } @@ -53,7 +53,7 @@ def requester_run(hb, body) #todo antisnatchor: remove this gsub crap adding some hook packing. # The below is how antisnatchor was managing insertion of messages dependent on WebSockets or not # Hopefully this still works - if config.get("beef.http.websocket.enable") && ws.getsocket(hb.session) + if config.get('beef.http.websocket.enable') && ws.getsocket(hb.session) rtcsignaloutput.each {|o| add_rtcsignal_to_body o diff --git a/extensions/webrtc/handlers.rb b/extensions/webrtc/handlers.rb index 7c9f97d87f..7617d0a6a5 100644 --- a/extensions/webrtc/handlers.rb +++ b/extensions/webrtc/handlers.rb @@ -24,23 +24,23 @@ def setup() # validates the hook token beef_hook = @data['beefhook'] || nil - (print_error "beefhook is null";return) if beef_hook.nil? + (print_error 'beefhook is null';return) if beef_hook.nil? # validates the target hook token target_beef_id = @data['results']['targetbeefid'] || nil - (print_error "targetbeefid is null";return) if target_beef_id.nil? + (print_error 'targetbeefid is null';return) if target_beef_id.nil? # validates the signal signal = @data['results']['signal'] || nil - (print_error "Signal is null";return) if signal.nil? + (print_error 'Signal is null';return) if signal.nil? # validates that a hooked browser with the beef_hook token exists in the db zombie_db = Z.first(:session => beef_hook) || nil - (print_error "Invalid beefhook id: the hooked browser cannot be found in the database";return) if zombie_db.nil? + (print_error 'Invalid beefhook id: the hooked browser cannot be found in the database';return) if zombie_db.nil? # validates that a target browser with the target_beef_token exists in the db target_zombie_db = Z.first(:id => target_beef_id) || nil - (print_error "Invalid targetbeefid: the target hooked browser cannot be found in the database";return) if target_zombie_db.nil? + (print_error 'Invalid targetbeefid: the target hooked browser cannot be found in the database';return) if target_zombie_db.nil? # save the results in the database signal = R.new( @@ -68,83 +68,83 @@ def initialize(data) def setup() # validates the hook token beef_hook = @data['beefhook'] || nil - (print_error "beefhook is null";return) if beef_hook.nil? + (print_error 'beefhook is null';return) if beef_hook.nil? # validates the target hook token peer_id = @data['results']['peerid'] || nil - (print_error "peerid is null";return) if peer_id.nil? + (print_error 'peerid is null';return) if peer_id.nil? # validates the message message = @data['results']['message'] || nil - (print_error "Message is null";return) if message.nil? + (print_error 'Message is null';return) if message.nil? # validates that a hooked browser with the beef_hook token exists in the db zombie_db = Z.first(:session => beef_hook) || nil - (print_error "Invalid beefhook id: the hooked browser cannot be found in the database";return) if zombie_db.nil? + (print_error 'Invalid beefhook id: the hooked browser cannot be found in the database';return) if zombie_db.nil? # validates that a browser with the peerid exists in the db peer_zombie_db = Z.first(:id => peer_id) || nil - (print_error "Invalid peer_id: the peer hooked browser cannot be found in the database";return) if peer_zombie_db.nil? + (print_error 'Invalid peer_id: the peer hooked browser cannot be found in the database';return) if peer_zombie_db.nil? # Writes the event into the BeEF Logger BeEF::Core::Logger.instance.register('WebRTC', "Browser:#{zombie_db.id} received message from Browser:#{peer_zombie_db.id}: #{message}") # Perform logic depending on message (updating database) puts "message = '" + message + "'" - if (message == "ICE Status: connected") + if (message == 'ICE Status: connected') # Find existing status message stat = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => zombie_db.id, :target_hooked_browser_id => peer_zombie_db.id) || nil unless stat.nil? - stat.status = "Connected" + stat.status = 'Connected' stat.updated_at = Time.now stat.save end stat2 = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => peer_zombie_db.id, :target_hooked_browser_id => zombie_db.id) || nil unless stat2.nil? - stat2.status = "Connected" + stat2.status = 'Connected' stat2.updated_at = Time.now stat2.save end - elsif (message.end_with?("disconnected")) + elsif (message.end_with?('disconnected')) stat = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => zombie_db.id, :target_hooked_browser_id => peer_zombie_db.id) || nil unless stat.nil? - stat.status = "Disconnected" + stat.status = 'Disconnected' stat.updated_at = Time.now stat.save end stat2 = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => peer_zombie_db.id, :target_hooked_browser_id => zombie_db.id) || nil unless stat2.nil? - stat2.status = "Disconnected" + stat2.status = 'Disconnected' stat2.updated_at = Time.now stat2.save end - elsif (message == "Stayin alive") + elsif (message == 'Stayin alive') stat = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => zombie_db.id, :target_hooked_browser_id => peer_zombie_db.id) || nil unless stat.nil? - stat.status = "Stealthed!!" + stat.status = 'Stealthed!!' stat.updated_at = Time.now stat.save end stat2 = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => peer_zombie_db.id, :target_hooked_browser_id => zombie_db.id) || nil unless stat2.nil? - stat2.status = "Peer-controlled stealth-mode" + stat2.status = 'Peer-controlled stealth-mode' stat2.updated_at = Time.now stat2.save end - elsif (message == "Coming out of stealth...") + elsif (message == 'Coming out of stealth...') stat = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => zombie_db.id, :target_hooked_browser_id => peer_zombie_db.id) || nil unless stat.nil? - stat.status = "Connected" + stat.status = 'Connected' stat.updated_at = Time.now stat.save end stat2 = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => peer_zombie_db.id, :target_hooked_browser_id => zombie_db.id) || nil unless stat2.nil? - stat2.status = "Connected" + stat2.status = 'Connected' stat2.updated_at = Time.now stat2.save end - elsif (message.start_with?("execcmd")) + elsif (message.start_with?('execcmd')) mod = /\(\/command\/(.*)\.js\)/.match(message)[1] resp = /Result:.(.*)/.match(message)[1] stat = BeEF::Core::Models::Rtcmodulestatus.new(:hooked_browser_id => zombie_db.id, diff --git a/extensions/webrtc/models/rtcmanage.rb b/extensions/webrtc/models/rtcmanage.rb index 04e5a55ffb..085e5ee7b0 100644 --- a/extensions/webrtc/models/rtcmanage.rb +++ b/extensions/webrtc/models/rtcmanage.rb @@ -13,8 +13,8 @@ class RtcManage < BeEF::Core::Model # Starts the RTCPeerConnection process, establishing a WebRTC connection between the caller and the receiver def self.initiate(caller, receiver, verbosity = false) - stunservers = BeEF::Core::Configuration.instance.get("beef.extension.webrtc.stunservers") - turnservers = BeEF::Core::Configuration.instance.get("beef.extension.webrtc.turnservers") + stunservers = BeEF::Core::Configuration.instance.get('beef.extension.webrtc.stunservers') + turnservers = BeEF::Core::Configuration.instance.get('beef.extension.webrtc.turnservers') # Add the beef.webrtc.start() JavaScript call into the RtcManage table - this will be picked up by the browser on next hook.js poll # This is for the Receiver diff --git a/spec/beef/api/auth_rate_spec.rb b/spec/beef/api/auth_rate_spec.rb index 77ff65a606..1ba7b7002b 100644 --- a/spec/beef/api/auth_rate_spec.rb +++ b/spec/beef/api/auth_rate_spec.rb @@ -14,7 +14,7 @@ after(:each) do # Shutting down server - Process.kill("KILL", @pid) unless @pid.nil? + Process.kill('KILL', @pid) unless @pid.nil? Process.wait(@pid) unless @pid.nil? # Ensure the process has exited and the port is released @pid = nil end @@ -23,31 +23,31 @@ test_api = BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, @password) expect(@config.get('beef.credentials.user')).to eq('beef') expect(@config.get('beef.credentials.passwd')).to eq('beef') - expect(test_api.auth()[:payload]).not_to eql("401 Unauthorized") - expect(test_api.auth()[:payload]["success"]).to be(true) # valid pass should succeed + expect(test_api.auth()[:payload]).not_to eql('401 Unauthorized') + expect(test_api.auth()[:payload]['success']).to be(true) # valid pass should succeed end it 'confirm incorrect creds are unsuccessful' do sleep 0.5 - test_api = BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, "wrong_passowrd") - expect(test_api.auth()[:payload]).to eql("401 Unauthorized") # all (unless the valid is first 1 in 10 chance) + test_api = BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, 'wrong_passowrd') + expect(test_api.auth()[:payload]).to eql('401 Unauthorized') # all (unless the valid is first 1 in 10 chance) end it 'adheres to 9 bad passwords then 1 correct auth rate limits' do # create api structures with bad passwords and one good - passwds = (1..9).map { |i| "bad_password"} # incorrect password + passwds = (1..9).map { |i| 'bad_password'} # incorrect password passwds.push @password # correct password apis = passwds.map { |pswd| BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, pswd) } (0..apis.length-1).each do |i| test_api = apis[i] - expect(test_api.auth()[:payload]).to eql("401 Unauthorized") # all (unless the valid is first 1 in 10 chance) + expect(test_api.auth()[:payload]).to eql('401 Unauthorized') # all (unless the valid is first 1 in 10 chance) end end it 'adheres to random bad passords and 1 correct auth rate limits' do # create api structures with bad passwords and one good - passwds = (1..9).map { |i| "bad_password"} # incorrect password + passwds = (1..9).map { |i| 'bad_password'} # incorrect password passwds.push @password # correct password apis = passwds.map { |pswd| BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, pswd) } @@ -60,10 +60,10 @@ sleep 0.5 expect(@config.get('beef.credentials.user')).to eq('beef') expect(@config.get('beef.credentials.passwd')).to eq('beef') - expect(test_api.auth()[:payload]).not_to eql("401 Unauthorized") - expect(test_api.auth()[:payload]["success"]).to be(true) # valid pass should succeed + expect(test_api.auth()[:payload]).not_to eql('401 Unauthorized') + expect(test_api.auth()[:payload]['success']).to be(true) # valid pass should succeed else - expect(test_api.auth()[:payload]).to eql("401 Unauthorized") + expect(test_api.auth()[:payload]).to eql('401 Unauthorized') end end end diff --git a/spec/beef/core/filter/filters_spec.rb b/spec/beef/core/filter/filters_spec.rb index 353c350dee..2e9c567d16 100644 --- a/spec/beef/core/filter/filters_spec.rb +++ b/spec/beef/core/filter/filters_spec.rb @@ -11,7 +11,7 @@ end it 'Empty String' do - expect(BeEF::Filters::is_non_empty_string?("")).to be(false) + expect(BeEF::Filters::is_non_empty_string?('')).to be(false) end it 'null' do @@ -19,19 +19,19 @@ end it 'First char is num' do - expect(BeEF::Filters::is_non_empty_string?("0")).to be(true) + expect(BeEF::Filters::is_non_empty_string?('0')).to be(true) end it 'First char is alpha' do - expect(BeEF::Filters::is_non_empty_string?("A")).to be(true) + expect(BeEF::Filters::is_non_empty_string?('A')).to be(true) end it 'Four num chars' do - expect(BeEF::Filters::is_non_empty_string?("3333")).to be(true) + expect(BeEF::Filters::is_non_empty_string?('3333')).to be(true) end it 'Four num chars begining with alpha' do - expect(BeEF::Filters::is_non_empty_string?("A3333")).to be(true) + expect(BeEF::Filters::is_non_empty_string?('A3333')).to be(true) end it 'Four num chars begining with null' do @@ -69,7 +69,7 @@ context 'false with' do it 'general' do - chars = [nil, "", "\x01", "\xFF", "A", "A3333", "0", "}", ".", "+", "-", "-1", "0.A", "3333", "33 33", " AAAAA", "AAAAAA "] + chars = [nil, '', "\x01", "\xFF", 'A', 'A3333', '0', '}', '.', '+', '-', '-1', '0.A', '3333', '33 33', ' AAAAA', 'AAAAAA '] chars.each do |c| expect(BeEF::Filters::has_null?(c)).to be(false) end @@ -120,7 +120,7 @@ context 'false with' do it 'general' do - chars = [nil, "", "A", "A3333", "0", "}", ".", "+", "-", "-1", "0.A", "3333", " 0AAAAA", " 0AAA "] + chars = [nil, '', 'A', 'A3333', '0', '}', '.', '+', '-', '-1', '0.A', '3333', ' 0AAAAA', ' 0AAA '] chars.each do |c| expect(BeEF::Filters::has_non_printable_char?(c)).to be(false) end @@ -171,14 +171,14 @@ context 'nums_only?' do it 'false with general' do - chars = [nil, 1, "", "A", "A3333", "\x003333", "}", ".", "+", "-", "-1"] + chars = [nil, 1, '', 'A', 'A3333', "\x003333", '}', '.', '+', '-', '-1'] chars.each do |c| expect(BeEF::Filters::nums_only?(c)).to be(false) end end it 'true with general' do - chars = ["0", "333"] + chars = ['0', '333'] chars.each do |c| expect(BeEF::Filters::nums_only?(c)).to be(true) end @@ -189,14 +189,14 @@ context 'is_valid_float?' do it 'false with general' do - chars = [nil, 1, "", "A", "A3333", "\x003333", "}", ".", "+", "-", "-1", "0", "333", "0.A"] + chars = [nil, 1, '', 'A', 'A3333', "\x003333", '}', '.', '+', '-', '-1', '0', '333', '0.A'] chars.each do |c| expect(BeEF::Filters::is_valid_float?(c)).to be(false) end end it 'true with general' do - chars = ["33.33", "0.0", "1.0", "0.1"] + chars = ['33.33', '0.0', '1.0', '0.1'] chars.each do |c| expect(BeEF::Filters::is_valid_float?(c)).to be(true) end @@ -207,14 +207,14 @@ context 'hexs_only?' do it 'false with general' do - chars = [nil, 1, "", "\x003333", "}", ".", "+", "-", "-1", "0.A", "33.33", "0.0", "1.0", "0.1"] + chars = [nil, 1, '', "\x003333", '}', '.', '+', '-', '-1', '0.A', '33.33', '0.0', '1.0', '0.1'] chars.each do |c| expect(BeEF::Filters::hexs_only?(c)).to be(false) end end it 'true with general' do - chars = ["0123456789ABCDEFabcdef", "0", "333", "A33333", "A"] + chars = ['0123456789ABCDEFabcdef', '0', '333', 'A33333', 'A'] chars.each do |c| expect(BeEF::Filters::hexs_only?(c)).to be(true) end @@ -225,14 +225,14 @@ context 'first_char_is_num?' do it 'false with general' do - chars = ["", "A", "A33333", "\x0033333"] + chars = ['', 'A', 'A33333', "\x0033333"] chars.each do |c| expect(BeEF::Filters::first_char_is_num?(c)).to be(false) end end it 'true with general' do - chars = ["333", "0AAAAAA", "0"] + chars = ['333', '0AAAAAA', '0'] chars.each do |c| expect(BeEF::Filters::first_char_is_num?(c)).to be(true) end @@ -243,14 +243,14 @@ context 'has_whitespace_char?' do it 'false with general' do - chars = ["", "A", "A33333", "\x0033333", "0", "}", ".", "+", "-", "-1", "0.A"] + chars = ['', 'A', 'A33333', "\x0033333", '0', '}', '.', '+', '-', '-1', '0.A'] chars.each do |c| expect(BeEF::Filters::has_whitespace_char?(c)).to be(false) end end it 'true with general' do - chars = ["33 33", " ", " ", " 0AAAAAAA", " 0AAAAAAA ", "\t0AAAAAAA", "\n0AAAAAAAA"] + chars = ['33 33', ' ', ' ', ' 0AAAAAAA', ' 0AAAAAAA ', "\t0AAAAAAA", "\n0AAAAAAAA"] chars.each do |c| expect(BeEF::Filters::has_whitespace_char?(c)).to be(true) end @@ -263,7 +263,7 @@ context 'false with' do it 'general' do - chars = [nil, "", "\n", "\r", "\x01", "}", ".", "+", "-", "-1", "ee-!@$%^&*}=0.A", "33 33", " AAAA", "AAA "] + chars = [nil, '', "\n", "\r", "\x01", '}', '.', '+', '-', '-1', 'ee-!@$%^&*}=0.A', '33 33', ' AAAA', 'AAA '] chars.each do |c| expect(BeEF::Filters::alphanums_only?(c)).to be(false) end @@ -308,7 +308,7 @@ context 'true with' do it 'general' do - chars = ["A", "A3333", "0", "3333"] + chars = ['A', 'A3333', '0', '3333'] chars.each do |c| expect(BeEF::Filters::alphanums_only?(c)).to be(true) end @@ -339,14 +339,14 @@ context 'has_valid_param_chars?' do it 'false' do - chars = [nil, "", "+"] + chars = [nil, '', '+'] chars.each do |c| expect(BeEF::Filters::has_valid_param_chars?(c)).to be(false) end end it 'true' do - expect(BeEF::Filters::has_valid_param_chars?("A")).to be(true) + expect(BeEF::Filters::has_valid_param_chars?('A')).to be(true) end end diff --git a/spec/beef/core/main/network_stack/handlers/dynamic_reconstruction_spec.rb b/spec/beef/core/main/network_stack/handlers/dynamic_reconstruction_spec.rb index 3cfd652feb..140bb2f130 100644 --- a/spec/beef/core/main/network_stack/handlers/dynamic_reconstruction_spec.rb +++ b/spec/beef/core/main/network_stack/handlers/dynamic_reconstruction_spec.rb @@ -10,8 +10,8 @@ @rackApp = Rack::URLMap.new(@mounts) Thin::Logging.silent = true @server = Thin::Server.new('127.0.0.1', @port.to_s, @rackApp) - trap("INT") { @server.stop } - trap("TERM") { @server.stop } + trap('INT') { @server.stop } + trap('TERM') { @server.stop } # ***** IMPORTANT: close any and all AR/OTR connections before forking ***** disconnect_all_active_record! @@ -24,7 +24,7 @@ end after(:all) do - Process.kill("INT",@pid) + Process.kill('INT',@pid) end it 'delete' do diff --git a/spec/beef/core/main/network_stack/handlers/redirector_spec.rb b/spec/beef/core/main/network_stack/handlers/redirector_spec.rb index e172931273..4967f33af2 100644 --- a/spec/beef/core/main/network_stack/handlers/redirector_spec.rb +++ b/spec/beef/core/main/network_stack/handlers/redirector_spec.rb @@ -10,8 +10,8 @@ @rackApp = Rack::URLMap.new(@mounts) Thin::Logging.silent = true @server = Thin::Server.new('127.0.0.1', @port.to_s, @rackApp) - trap("INT") { @server.stop } - trap("TERM") { @server.stop } + trap('INT') { @server.stop } + trap('TERM') { @server.stop } # ***** IMPORTANT: close any and all AR/OTR connections before forking ***** @@ -25,13 +25,13 @@ end after(:all) do - Process.kill("INT",@pid) + Process.kill('INT',@pid) end it 'redirects' do response = Curl::Easy.http_get("http://127.0.0.1:#{@port}/test/") expect(response.response_code).to eql(302) - expect(response.body_str).to eql("302 found") + expect(response.body_str).to eql('302 found') expect(response.header_str).to match(/Location: http:\/\/www.beefproject\.com/) end diff --git a/spec/beef/extensions/adminui_spec.rb b/spec/beef/extensions/adminui_spec.rb index 64891c0a88..e5679d669c 100644 --- a/spec/beef/extensions/adminui_spec.rb +++ b/spec/beef/extensions/adminui_spec.rb @@ -14,7 +14,7 @@ end after(:all) do - @config.set('beef.restrictions.permitted_ui_subnet',["0.0.0.0/0", "::/0"]) + @config.set('beef.restrictions.permitted_ui_subnet',['0.0.0.0/0', '::/0']) end it 'loads configuration' do @@ -23,31 +23,31 @@ it 'confirms that any ip address is permitted to view the admin ui' do ui = BeEF::Extension::AdminUI::HttpController.new - expect(@config.set('beef.restrictions.permitted_ui_subnet',["0.0.0.0/0", "::/0"])).to eq true - expect(ui.authenticate_request("8.8.8.8")).to eq true + expect(@config.set('beef.restrictions.permitted_ui_subnet',['0.0.0.0/0', '::/0'])).to eq true + expect(ui.authenticate_request('8.8.8.8')).to eq true end it 'confirms that an ip address is permitted to view the admin ui' do ui = BeEF::Extension::AdminUI::HttpController.new - expect(@config.set('beef.restrictions.permitted_ui_subnet',["192.168.10.1"])).to eq true - expect(ui.authenticate_request("192.168.10.1")).to eq true + expect(@config.set('beef.restrictions.permitted_ui_subnet',['192.168.10.1'])).to eq true + expect(ui.authenticate_request('192.168.10.1')).to eq true end it 'confirms that an ip address is not permitted to view the admin ui' do ui = BeEF::Extension::AdminUI::HttpController.new - expect(@config.set('beef.restrictions.permitted_ui_subnet',["10.10.10.1"])).to eq true - expect(ui.authenticate_request("8.8.8.8")).to eq false + expect(@config.set('beef.restrictions.permitted_ui_subnet',['10.10.10.1'])).to eq true + expect(ui.authenticate_request('8.8.8.8')).to eq false end it 'confirms that X-Forwarded-For cant be spoofed when reverse proxy is disabled' do ui = BeEF::Extension::AdminUI::HttpController.new - expect(@config.set('beef.restrictions.permitted_ui_subnet',["192.168.0.10"])).to eq true + expect(@config.set('beef.restrictions.permitted_ui_subnet',['192.168.0.10'])).to eq true expect(@config.set('beef.http.allow_reverse_proxy',false)).to eq true - env = { "REQUEST_METHOD" => "GET", "PATH_INFO" => "/ui/authentication" } + env = { 'REQUEST_METHOD' => 'GET', 'PATH_INFO' => '/ui/authentication' } request = Rack::Request.new(env) - request.add_header("HTTP_X_FORWARDED_FOR","192.168.0.10") - request.add_header("REMOTE_ADDR","192.168.0.20") - expect(ui.get_ip(request)).to eq "192.168.0.20" + request.add_header('HTTP_X_FORWARDED_FOR','192.168.0.10') + request.add_header('REMOTE_ADDR','192.168.0.20') + expect(ui.get_ip(request)).to eq '192.168.0.20' end end \ No newline at end of file diff --git a/spec/beef/extensions/social_engineering_spec.rb b/spec/beef/extensions/social_engineering_spec.rb index 7543b2f264..90f6a07982 100644 --- a/spec/beef/extensions/social_engineering_spec.rb +++ b/spec/beef/extensions/social_engineering_spec.rb @@ -22,13 +22,13 @@ xit 'clone web page', if: !`which wget`.empty? do expect { BeEF::Core::Server.instance.prepare - BeEF::Extension::SocialEngineering::WebCloner.instance.clone_page("https://www.google.com", "/", nil, nil) + BeEF::Extension::SocialEngineering::WebCloner.instance.clone_page('https://www.google.com', '/', nil, nil) }.to_not raise_error end it 'persistence web cloner', if: !`which wget`.empty? do expect { - BeEF::Core::Models::WebCloner.create(uri: "example.com", mount: "/") + BeEF::Core::Models::WebCloner.create(uri: 'example.com', mount: '/') }.to_not raise_error end end diff --git a/spec/beef/security_checks_spec.rb b/spec/beef/security_checks_spec.rb index c058323119..77865e4d5c 100644 --- a/spec/beef/security_checks_spec.rb +++ b/spec/beef/security_checks_spec.rb @@ -8,7 +8,7 @@ f.grep(/\Weval\W/im) do |line| # check if comment starting with the '#' character - clean_line = line.downcase.gsub(/[ ]/, "") + clean_line = line.downcase.gsub(/[ ]/, '') if clean_line[0] != '#' # check first non-whitespace position raise "Illegal use of 'eval' found in\n Path: #{path}\nLine: #{line}" end diff --git a/spec/features/all_modules_spec.rb b/spec/features/all_modules_spec.rb index 8112d46c9b..8a522dd9a9 100644 --- a/spec/features/all_modules_spec.rb +++ b/spec/features/all_modules_spec.rb @@ -17,9 +17,9 @@ stop_beef_and_unhook_browser(@pid, @beef_session, @hooked_browser) end - it "Load all modules" do + it 'Load all modules' do - Dir.glob("modules/**/config.yaml").each do |file| + Dir.glob('modules/**/config.yaml').each do |file| module_yaml_data = YAML.load_file(file) module_yaml_data['beef']['module'].each do |module_key, module_value| diff --git a/spec/features/debug_modules_spec.rb b/spec/features/debug_modules_spec.rb index e3eae3e0e7..c171223c16 100644 --- a/spec/features/debug_modules_spec.rb +++ b/spec/features/debug_modules_spec.rb @@ -24,8 +24,8 @@ expect(@beef_session).to have_content('Debug Message:', wait: PAGE_LOAD_TIMEOUT) end - it "Load all debug modules" do - Dir.glob("modules/debug/**/config.yaml").each do |file| + it 'Load all debug modules' do + Dir.glob('modules/debug/**/config.yaml').each do |file| module_yaml_data = YAML.load_file(file) module_yaml_data['beef']['module'].each do |module_key, module_value| diff --git a/spec/requests/login_spec.rb b/spec/requests/login_spec.rb index 22be46cd4a..a930c35212 100644 --- a/spec/requests/login_spec.rb +++ b/spec/requests/login_spec.rb @@ -80,7 +80,7 @@ expect(attacker).to have_content('Logout', wait: 10) expect(attacker).to have_content(VICTIM_DOMAIN, wait: 10) - attacker.click_on("127.0.0.1", match: :first) + attacker.click_on('127.0.0.1', match: :first) expect(attacker).to have_content('Details') expect(attacker).to have_content('Commands') diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 9cc0c508ab..58a37815e0 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -192,8 +192,8 @@ def configure_beef # Reset or re-initialise the configuration to a default state @config = BeEF::Core::Configuration.instance - @config.set('beef.credentials.user', "beef") - @config.set('beef.credentials.passwd', "beef") + @config.set('beef.credentials.user', 'beef') + @config.set('beef.credentials.passwd', 'beef') @config.set('beef.http.https.enable', false) end @@ -220,7 +220,7 @@ def disconnect_all_active_record! handler.connection_pools.each_value { |pool| pool.disconnect! } end else - print_info "ActiveRecord::Base not defined" + print_info 'ActiveRecord::Base not defined' end end @@ -303,14 +303,14 @@ def wait_for_beef_server_to_start(uri_str, timeout: 5) end def start_beef_server_and_wait - puts "Starting BeEF server" + puts 'Starting BeEF server' pid = start_beef_server puts "BeEF server started with PID: #{pid}" if wait_for_beef_server_to_start('http://localhost:3000', timeout: SERVER_START_TIMEOUT) # print_info "Server started successfully." else - print_error "Server failed to start within timeout." + print_error 'Server failed to start within timeout.' end pid @@ -319,7 +319,7 @@ def start_beef_server_and_wait def stop_beef_server(pid) exit if pid.nil? # Shutting down server - Process.kill("KILL", pid) unless pid.nil? + Process.kill('KILL', pid) unless pid.nil? Process.wait(pid) unless pid.nil? # Ensure the process has exited and the port is released pid = nil end diff --git a/spec/support/ui_support.rb b/spec/support/ui_support.rb index 0311202067..2d89bef09a 100644 --- a/spec/support/ui_support.rb +++ b/spec/support/ui_support.rb @@ -56,7 +56,7 @@ def navigate_to_category(session, category_name = nil) session.click_on('Commands') expect(session).to have_content(category_name, wait: PAGE_LOAD_TIMEOUT) - session.first(:link_or_button, category_name + " ").click + session.first(:link_or_button, category_name + ' ').click end def expand_category_tree(session, category, module_name = nil) @@ -96,11 +96,11 @@ def collapse_category_tree(session, category) category.reverse.each do |category_name| # Collapse the sub-folder session.scroll_to(category_name) - session.first(:link_or_button, category_name + " ").click + session.first(:link_or_button, category_name + ' ').click end else session.scroll_to(category) - session.first(:link_or_button, category + " ").click + session.first(:link_or_button, category + ' ').click end end diff --git a/test/integration/tc_debug_modules.rb b/test/integration/tc_debug_modules.rb index eda7f642e2..e8c28dbf21 100644 --- a/test/integration/tc_debug_modules.rb +++ b/test/integration/tc_debug_modules.rb @@ -46,7 +46,7 @@ def test_2_restful_hooks assert_equal 200, response.code assert_not_nil response.body result = JSON.parse(response.body) - @@hb_session = result["hooked-browsers"]["online"]["0"]["session"] + @@hb_session = result['hooked-browsers']['online']['0']['session'] assert_not_nil @@hb_session end @@ -57,13 +57,13 @@ def test_3_restful_modules assert_not_nil response.body result = JSON.parse(response.body) result.each do |mod| - case mod[1]["class"] - when "Test_return_long_string" - @@mod_debug_long_string = mod[1]["id"] - when "Test_return_ascii_chars" - @@mod_debug_ascii_chars = mod[1]["id"] - when "Test_network_request" - @@mod_debug_test_network = mod[1]["id"] + case mod[1]['class'] + when 'Test_return_long_string' + @@mod_debug_long_string = mod[1]['id'] + when 'Test_return_ascii_chars' + @@mod_debug_ascii_chars = mod[1]['id'] + when 'Test_network_request' + @@mod_debug_test_network = mod[1]['id'] end end assert_not_nil @@mod_debug_long_string @@ -73,7 +73,7 @@ def test_3_restful_modules # ## Test debug module "Test_return_long_string" using the RESTful API def test_return_long_string - repeat_string = "BeEF" + repeat_string = 'BeEF' repeat_count = 20 response = RestClient.post "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_debug_long_string}?token=#{@@token}", @@ -133,7 +133,7 @@ def test_return_ascii_chars result = JSON.parse(response.body) data = JSON.parse(result['0']['data'])['data'] assert_not_nil data - ascii_chars = "" + ascii_chars = '' (32..127).each do |i| ascii_chars << i.chr end assert_equal ascii_chars,data end @@ -144,7 +144,7 @@ def test_return_network_request # Test same-origin request (response code and content of secret_page.html) response = RestClient.post "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_debug_test_network}?token=#{@@token}", #override only a few parameters, the other ones will have default values from modules's module.rb definition - {"domain" => ATTACK_DOMAIN, "port" => "3000", "path" => "/demos/secret_page.html"}.to_json, + {'domain' => ATTACK_DOMAIN, 'port' => '3000', 'path' => '/demos/secret_page.html'}.to_json, :content_type => :json, :accept => :json assert_equal 200, response.code @@ -169,8 +169,8 @@ def test_return_network_request result = JSON.parse(response.body) data = JSON.parse(result['0']['data'])['data'] assert_not_nil data - assert_equal 200, JSON.parse(data)["status_code"] - assert JSON.parse(data)["port_status"].include?("open") + assert_equal 200, JSON.parse(data)['status_code'] + assert JSON.parse(data)['port_status'].include?('open') end end diff --git a/test/integration/tc_dns_rest.rb b/test/integration/tc_dns_rest.rb index 6ce656ca9d..f8664300f5 100644 --- a/test/integration/tc_dns_rest.rb +++ b/test/integration/tc_dns_rest.rb @@ -381,7 +381,7 @@ def check_dns_response(regex, type, pattern) address = @@config.get('beef.extension.dns.address') port = @@config.get('beef.extension.dns.port') - dig_output = IO.popen(["dig", "@#{address}", "-p", "#{port}", "-t", "#{type}", "#{pattern}"], 'r+').read + dig_output = IO.popen(['dig', "@#{address}", '-p', "#{port}", '-t', "#{type}", "#{pattern}"], 'r+').read assert_match(regex, dig_output) end diff --git a/test/integration/tc_network_rest.rb b/test/integration/tc_network_rest.rb index 799b2b1578..cd04957359 100644 --- a/test/integration/tc_network_rest.rb +++ b/test/integration/tc_network_rest.rb @@ -32,14 +32,14 @@ def startup sleep 5.0 response = RestClient.get "#{RESTAPI_HOOKS}", {:params => {:token => @@token}} result = JSON.parse(response.body) - @@hb_session = result["hooked-browsers"]["online"]["0"]["session"] + @@hb_session = result['hooked-browsers']['online']['0']['session'] # Retrieve Port Scanner module command ID response = RestClient.get "#{RESTAPI_MODULES}", {:params => {:token => @@token}} result = JSON.parse(response.body) result.each do |mod| if mod[1]['class'] == 'Port_scanner' - @@mod_port_scanner = mod[1]["id"] + @@mod_port_scanner = mod[1]['id'] break end end @@ -72,7 +72,7 @@ def test_port_scanner_results rest_response = RestClient.get "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_port_scanner}/#{@@cmd_id}?token=#{@@token}" check_rest_response(rest_response) result = JSON.parse(rest_response.body) - raise "Port Scanner module failed to identify any open ports" unless result.to_s =~ /Port 3000 is OPEN/ + raise 'Port Scanner module failed to identify any open ports' unless result.to_s =~ /Port 3000 is OPEN/ end # Tests GET /api/network/hosts handler diff --git a/test/integration/tc_social_engineering_rest.rb b/test/integration/tc_social_engineering_rest.rb index 9bf75ea93b..59c6fc92b0 100644 --- a/test/integration/tc_social_engineering_rest.rb +++ b/test/integration/tc_social_engineering_rest.rb @@ -61,8 +61,8 @@ def test_1_dns_spoof # Send DNS request to server to verify that a new rule was added dns_address = @@config.get('beef.extension.dns.address') dns_port = @@config.get('beef.extension.dns.port') - dig_output = IO.popen(["dig", "@#{dns_address}", "-p", "#{dns_port}", "-t", - "A", "+short", "#{domain}"], 'r+').read.strip! + dig_output = IO.popen(['dig', "@#{dns_address}", '-p', "#{dns_port}", '-t', + 'A', '+short', "#{domain}"], 'r+').read.strip! foundmatch = false diff --git a/test/integration/tc_webrtc_rest.rb b/test/integration/tc_webrtc_rest.rb index 1c5f9bac09..5576af404e 100644 --- a/test/integration/tc_webrtc_rest.rb +++ b/test/integration/tc_webrtc_rest.rb @@ -47,13 +47,13 @@ def startup rest_response = RestClient.get "#{RESTAPI_HOOKS}", {:params => { :token => @@token}} result = JSON.parse(rest_response.body) - browsers = result["hooked-browsers"]["online"] + browsers = result['hooked-browsers']['online'] browsers.each_with_index do |elem, index| if index == browsers.length - 1 - @@victim2id = browsers["#{index}"]["id"].to_s + @@victim2id = browsers["#{index}"]['id'].to_s end if index == browsers.length - 2 - @@victim1id = browsers["#{index}"]["id"].to_s + @@victim1id = browsers["#{index}"]['id'].to_s end end @@ -77,7 +77,7 @@ def test_1_webrtc_check_for_two_hooked_browsers end check_rest_response(rest_response) result = JSON.parse(rest_response.body) - browsers = result["hooked-browsers"]["online"] + browsers = result['hooked-browsers']['online'] assert_not_nil browsers assert_operator browsers.length, :>=, 2 end @@ -88,12 +88,12 @@ def test_2_webrtc_establishing_p2p rest_response = nil assert_nothing_raised do rest_response = RestClient.post("#{RESTAPI_WEBRTC}/go?token=#{@@token}", - {:from => @@victim1id, :to => @@victim2id, :verbose => "true"}.to_json, + {:from => @@victim1id, :to => @@victim2id, :verbose => 'true'}.to_json, @@headers) end check_rest_response(rest_response) result = JSON.parse(rest_response.body) - assert_equal true, result["success"] + assert_equal true, result['success'] sleep 30.0 @@ -106,14 +106,14 @@ def test_2_webrtc_establishing_p2p result = JSON.parse(rest_response.body) loghitcount = 0 - result["logs"].reverse.each {|l| + result['logs'].reverse.each {|l| # Using free-space matching mode /x below to wrap regex. # therefore need to escape spaces I want to check, hence the \ regex = Regexp.new(/Browser:(#{@@victim1id}|#{@@victim2id})\ received\ message\ from\ Browser:(#{@@victim1id}|#{@@victim2id}) :\ ICE\ Status:\ connected/x) - loghitcount += 1 if (not regex.match(l["event"]).nil?) and - (l["type"].to_s.eql?("WebRTC")) + loghitcount += 1 if (not regex.match(l['event']).nil?) and + (l['type'].to_s.eql?('WebRTC')) } assert_equal 2, loghitcount end @@ -125,12 +125,12 @@ def test_3_webrtc_send_msg # assumes test 2 has run assert_nothing_raised do rest_response = RestClient.post("#{RESTAPI_WEBRTC}/msg?token=#{@@token}", {:from => @@victim1id, :to => @@victim2id, - :message => "RTC test message"}.to_json, + :message => 'RTC test message'}.to_json, @@headers) end check_rest_response(rest_response) result = JSON.parse(rest_response.body) - assert_equal true, result["success"] + assert_equal true, result['success'] sleep 10.0 @@ -143,15 +143,15 @@ def test_3_webrtc_send_msg # assumes test 2 has run result = JSON.parse(rest_response.body) assert_block do - result["logs"].reverse.each {|l| + result['logs'].reverse.each {|l| # Using free-space matching mode /x below to wrap regex. # therefore need to escape spaces I want to check, hence the \ regex = Regexp.new(/Browser:(#{@@victim1id}|#{@@victim2id})\ received\ message\ from\ Browser: (#{@@victim1id}|#{@@victim2id}) :\ RTC\ test\ message/x) - return true if (not regex.match(l["event"]).nil?) and - (l["type"].to_s.eql?("WebRTC")) + return true if (not regex.match(l['event']).nil?) and + (l['type'].to_s.eql?('WebRTC')) } end end @@ -167,15 +167,15 @@ def test_4_webrtc_stealthmode # assumes test 2 has run end check_rest_response(rest_response) result = JSON.parse(rest_response.body) - online = result["hooked-browsers"]["online"] + online = result['hooked-browsers']['online'] assert_block do online.each {|hb| - return true if hb[1]["id"].eql?(@@victim1id) + return true if hb[1]['id'].eql?(@@victim1id) } end assert_block do online.each {|hb| - return true if hb[1]["id"].eql?(@@victim2id) + return true if hb[1]['id'].eql?(@@victim2id) } end @@ -185,12 +185,12 @@ def test_4_webrtc_stealthmode # assumes test 2 has run assert_nothing_raised do rest_response = RestClient.post("#{RESTAPI_WEBRTC}/msg?token=#{@@token}", {:from => @@victim1id, :to => @@victim2id, - :message => "!gostealth"}.to_json, + :message => '!gostealth'}.to_json, @@headers) end check_rest_response(rest_response) result = JSON.parse(rest_response.body) - assert_equal true, result["success"] + assert_equal true, result['success'] sleep 40.0 #Wait until that browser is offline. @@ -202,10 +202,10 @@ def test_4_webrtc_stealthmode # assumes test 2 has run end check_rest_response(rest_response) result = JSON.parse(rest_response.body) - offline = result["hooked-browsers"]["offline"] + offline = result['hooked-browsers']['offline'] assert_block do offline.each {|hb| - return true if hb[1]["id"].eql?(@@victim2id) + return true if hb[1]['id'].eql?(@@victim2id) } end @@ -214,12 +214,12 @@ def test_4_webrtc_stealthmode # assumes test 2 has run assert_nothing_raised do rest_response = RestClient.post("#{RESTAPI_WEBRTC}/msg?token=#{@@token}", {:from => @@victim1id, :to => @@victim2id, - :message => "!endstealth"}.to_json, + :message => '!endstealth'}.to_json, @@headers) end check_rest_response(rest_response) result = JSON.parse(rest_response.body) - assert_equal true, result["success"] + assert_equal true, result['success'] sleep 10.0 # Wait until browser comes back @@ -231,10 +231,10 @@ def test_4_webrtc_stealthmode # assumes test 2 has run end check_rest_response(rest_response) result = JSON.parse(rest_response.body) - online = result["hooked-browsers"]["online"] + online = result['hooked-browsers']['online'] assert_block do online.each {|hb| - return true if hb[1]["id"].eql?(@@victim2id) + return true if hb[1]['id'].eql?(@@victim2id) } end diff --git a/test/integration/ts_integration.rb b/test/integration/ts_integration.rb index bc415b46bc..5dead34497 100644 --- a/test/integration/ts_integration.rb +++ b/test/integration/ts_integration.rb @@ -28,7 +28,7 @@ class TS_BeefIntegrationTests def self.suite - suite = Test::Unit::TestSuite.new(name="BeEF Integration Test Suite") + suite = Test::Unit::TestSuite.new(name='BeEF Integration Test Suite') suite << TC_CheckEnvironment.suite suite << TC_Login.suite suite << TC_DebugModules.suite diff --git a/test/thirdparty/msf/unit/tc_metasploit.rb b/test/thirdparty/msf/unit/tc_metasploit.rb index 0bd2bd0291..0db779b40a 100644 --- a/test/thirdparty/msf/unit/tc_metasploit.rb +++ b/test/thirdparty/msf/unit/tc_metasploit.rb @@ -9,7 +9,7 @@ class TC_Metasploit < Test::Unit::TestCase def setup - $root_dir="../../../../" + $root_dir='../../../../' $:.unshift File.join( %w{ ../../../../ } ) require 'core/loader' end diff --git a/test/thirdparty/msf/unit/ts_metasploit.rb b/test/thirdparty/msf/unit/ts_metasploit.rb index 52f4d2db8c..dc16af3f45 100644 --- a/test/thirdparty/msf/unit/ts_metasploit.rb +++ b/test/thirdparty/msf/unit/ts_metasploit.rb @@ -11,7 +11,7 @@ require 'msfrpc-client' rescue LoadError puts "The following instruction failed: require 'msfrpc-client'" - puts "Please run: sudo gem install msfrpc-client" + puts 'Please run: sudo gem install msfrpc-client' exit end @@ -21,7 +21,7 @@ class TS_BeefTests def self.suite - suite = Test::Unit::TestSuite.new(name="BeEF Metasploit Test Suite") + suite = Test::Unit::TestSuite.new(name='BeEF Metasploit Test Suite') suite << TC_CheckEnvironment.suite suite << TC_Metasploit.suite diff --git a/tools/csrf_to_beef/csrf_to_beef b/tools/csrf_to_beef/csrf_to_beef index ec8017bfd0..0d00aea5c5 100755 --- a/tools/csrf_to_beef/csrf_to_beef +++ b/tools/csrf_to_beef/csrf_to_beef @@ -7,7 +7,7 @@ $VERSION = '0.0.3' # @note Ruby version check # if RUBY_VERSION =~ /^1\.[0-8]/ - puts "Ruby version " + RUBY_VERSION + " is not supported. Please use Ruby 1.9 or newer." + puts 'Ruby version ' + RUBY_VERSION + ' is not supported. Please use Ruby 1.9 or newer.' exit 1 end @@ -25,27 +25,27 @@ require './lib/module' def usage puts "CSRF to BeEF module tool v#{$VERSION}, create a BeEF CSRF module from file or URL." puts - puts "Usage: ./csrf_to_beef [options] --name <--url=URL|--file=FILE>" + puts 'Usage: ./csrf_to_beef [options] --name <--url=URL|--file=FILE>' puts - puts "Options:" - puts " -h, --help Help" - puts " -v, --verbose Verbose output" - puts " -n, --name NAME BeEF module name" - puts " -u, --url URL CSRF URL" - puts " -m, --method METHOD CSRF HTTP method (GET/POST)" - puts " -d, --post-data DATA CSRF HTTP POST data" - puts " -f, --file FILE Burp CSRF PoC file" + puts 'Options:' + puts ' -h, --help Help' + puts ' -v, --verbose Verbose output' + puts ' -n, --name NAME BeEF module name' + puts ' -u, --url URL CSRF URL' + puts ' -m, --method METHOD CSRF HTTP method (GET/POST)' + puts ' -d, --post-data DATA CSRF HTTP POST data' + puts ' -f, --file FILE Burp CSRF PoC file' puts - puts "Example Usage:" + puts 'Example Usage:' puts - puts " CSRF URL:" - puts " ./csrf_to_beef --name \"example csrf\" --url \"http://example.com/index.html?param=value\"" + puts ' CSRF URL:' + puts ' ./csrf_to_beef --name "example csrf" --url "http://example.com/index.html?param=value"' puts - puts " CSRF URL (POST):" - puts " ./csrf_to_beef --name \"example csrf\" --url \"http://example.com/index.html\" --method POST --post-data \"param1=value¶m2=value\"" + puts ' CSRF URL (POST):' + puts ' ./csrf_to_beef --name "example csrf" --url "http://example.com/index.html" --method POST --post-data "param1=value¶m2=value"' puts - puts " Burp Suite CSRF PoC file:" - puts " ./csrf_to_beef --name \"example csrf\" --file sample.html" + puts ' Burp Suite CSRF PoC file:' + puts ' ./csrf_to_beef --name "example csrf" --file sample.html' puts exit 1 end @@ -176,10 +176,10 @@ def get_options_from_burp_file(fname, mname) # parse PoC file if html.to_s =~ /var xhr = new XMLHttpRequest/ - print_error "Could not parse PoC file - XMLHttpRequest is not yet supported." + print_error 'Could not parse PoC file - XMLHttpRequest is not yet supported.' exit 1 elsif html.to_s !~ /
' },\n" end diff --git a/tools/maintenance/copyright_update.rb b/tools/maintenance/copyright_update.rb index 3471ba4619..a58a4689a1 100644 --- a/tools/maintenance/copyright_update.rb +++ b/tools/maintenance/copyright_update.rb @@ -36,19 +36,19 @@ def update_copyright(file_path, old_copyright, new_copyright) old_copyright = 'Copyright (c) 2006-2024' new_copyright = 'Copyright (c) 2006-2025' -Dir.glob("../../**/*.{rb,js,yaml,html,md,txt,css,c,nasm,java,php,as}").each do |file| +Dir.glob('../../**/*.{rb,js,yaml,html,md,txt,css,c,nasm,java,php,as}').each do |file| next if File.basename(file) == 'copyright_update.rb' # Skip this file update_copyright(file, old_copyright, new_copyright) end # Handle files without extensions, excluding copyright_update.rb -Dir.glob("../../**/*").reject { |f| +Dir.glob('../../**/*').reject { |f| File.directory?(f) || File.extname(f) != '' || File.basename(f) == 'copyright_update.rb' }.each do |file| update_copyright(file, old_copyright, new_copyright) end -@log.info("Copyright update process completed.") -@log_file_logger.info("Copyright update process completed.") +@log.info('Copyright update process completed.') +@log_file_logger.info('Copyright update process completed.') log_file.close \ No newline at end of file diff --git a/tools/rest_api_examples/autorun b/tools/rest_api_examples/autorun index d38b96b5f7..a9828f8434 100644 --- a/tools/rest_api_examples/autorun +++ b/tools/rest_api_examples/autorun @@ -13,9 +13,9 @@ require './lib/beef_rest_api' if ARGV.length == 0 puts "#{$0}:" - puts "| Example BeEF RESTful API script" - puts "| Use --help for help" - puts "|_ Use verbose mode (-v) and debug mode (-d) for more output" + puts '| Example BeEF RESTful API script' + puts '| Use --help for help' + puts '|_ Use verbose mode (-v) and debug mode (-d) for more output' exit 1 end @@ -66,20 +66,20 @@ print_status "Authenticating to: #{proto}://#{host}:#{port}" # Retrieve BeEF version @api.version -print_status("Retrieving Autorun rules") +print_status('Retrieving Autorun rules') rules = @api.autorun_rules print_debug(rules) -print_status("Adding a rule") +print_status('Adding a rule') res = @api.autorun_add_rule({ - "name": "Say Hello", - "author": "REST API", + "name": 'Say Hello', + "author": 'REST API', "modules": [ { - "name": "alert_dialog", + "name": 'alert_dialog', "options": { - "text":"Hello from REST API" + "text":'Hello from REST API' } } ], diff --git a/tools/rest_api_examples/browser-details b/tools/rest_api_examples/browser-details index f99979bd1f..6f78a388a8 100755 --- a/tools/rest_api_examples/browser-details +++ b/tools/rest_api_examples/browser-details @@ -13,9 +13,9 @@ require './lib/beef_rest_api' if ARGV.length == 0 puts "#{$0}:" - puts "| Example BeEF RESTful API script" - puts "| Use --help for help" - puts "|_ Use verbose mode (-v) and debug mode (-d) for more output" + puts '| Example BeEF RESTful API script' + puts '| Use --help for help' + puts '|_ Use verbose mode (-v) and debug mode (-d) for more output' exit 1 end diff --git a/tools/rest_api_examples/clone_page b/tools/rest_api_examples/clone_page index 610c7f8d45..a2df80209f 100755 --- a/tools/rest_api_examples/clone_page +++ b/tools/rest_api_examples/clone_page @@ -13,9 +13,9 @@ require './lib/beef_rest_api' # API if ARGV.length == 0 puts "#{$0}:" - puts "| Example BeEF RESTful API script" - puts "| Use --help for help" - puts "|_ Use verbose mode (-v) and debug mode (-d) for more output" + puts '| Example BeEF RESTful API script' + puts '| Use --help for help' + puts '|_ Use verbose mode (-v) and debug mode (-d) for more output' exit 1 end diff --git a/tools/rest_api_examples/command-modules b/tools/rest_api_examples/command-modules index c5a6735e3b..ea668b505b 100755 --- a/tools/rest_api_examples/command-modules +++ b/tools/rest_api_examples/command-modules @@ -13,9 +13,9 @@ require './lib/beef_rest_api' if ARGV.length == 0 puts "#{$0}:" - puts "| Example BeEF RESTful API script" - puts "| Use --help for help" - puts "|_ Use verbose mode (-v) and debug mode (-d) for more output" + puts '| Example BeEF RESTful API script' + puts '| Use --help for help' + puts '|_ Use verbose mode (-v) and debug mode (-d) for more output' exit 1 end @@ -89,12 +89,12 @@ exit 1 if hooks.empty? print_debug hooks # Execute alert dialog on all online browsers -mod_id = @api.get_module_id "Alert_dialog" +mod_id = @api.get_module_id 'Alert_dialog' hooks.each do |hook| next if hook['id'].nil? print_status "Executing module [id: #{mod_id}, browser: #{hook['id']}]" - result = @api.execute_module(hook['session'], mod_id, { "text" => "hello!" }) + result = @api.execute_module(hook['session'], mod_id, { 'text' => 'hello!' }) print_debug result end diff --git a/tools/rest_api_examples/dns b/tools/rest_api_examples/dns index ee48a292a6..920bceb3c7 100755 --- a/tools/rest_api_examples/dns +++ b/tools/rest_api_examples/dns @@ -13,9 +13,9 @@ require './lib/beef_rest_api' if ARGV.length == 0 puts "#{$0}:" - puts "| Example BeEF RESTful API script" - puts "| Use --help for help" - puts "|_ Use verbose mode (-v) and debug mode (-d) for more output" + puts '| Example BeEF RESTful API script' + puts '| Use --help for help' + puts '|_ Use verbose mode (-v) and debug mode (-d) for more output' exit 1 end @@ -67,7 +67,7 @@ print_status "Authenticating to: #{proto}://#{host}:#{port}" @api.version # Add a rule -print_status "Adding a DNS rule" +print_status 'Adding a DNS rule' pattern = 'beefproject.com' resource = 'A' response = ['127.0.0.1', '127.0.0.2'] @@ -76,7 +76,7 @@ print_debug result id = result['id'] # Retrieve ruleset -print_status "Retrieving DNS rule set" +print_status 'Retrieving DNS rule set' rules = @api.dns_ruleset print_debug rules @@ -90,7 +90,7 @@ result = @api.dns_delete_rule(id) print_debug result # Retrieve ruleset -print_status "Retrieving DNS rule set" +print_status 'Retrieving DNS rule set' rules = @api.dns_ruleset print_debug rules diff --git a/tools/rest_api_examples/export-logs b/tools/rest_api_examples/export-logs index a46a771329..a48fca9e72 100755 --- a/tools/rest_api_examples/export-logs +++ b/tools/rest_api_examples/export-logs @@ -13,9 +13,9 @@ require './lib/beef_rest_api' if ARGV.length == 0 puts "#{$0}:" - puts "| Example BeEF RESTful API script" - puts "| Use --help for help" - puts "|_ Use verbose mode (-v) and debug mode (-d) for more output" + puts '| Example BeEF RESTful API script' + puts '| Use --help for help' + puts '|_ Use verbose mode (-v) and debug mode (-d) for more output' exit 1 end diff --git a/tools/rest_api_examples/lib/beef_rest_api.rb b/tools/rest_api_examples/lib/beef_rest_api.rb index b3705c0894..4b14d90bb8 100644 --- a/tools/rest_api_examples/lib/beef_rest_api.rb +++ b/tools/rest_api_examples/lib/beef_rest_api.rb @@ -14,7 +14,7 @@ def initialize proto = 'https', host = '127.0.0.1', port = '3000', user = 'beef' # authenticate and get API token def auth - print_verbose "Retrieving authentication token" + print_verbose 'Retrieving authentication token' begin response = RestClient.post "#{@url}admin/login", { 'username' => "#{@user}", @@ -56,10 +56,10 @@ def mounts # get online hooked browsers def online_browsers begin - print_verbose "Retrieving online browsers" + print_verbose 'Retrieving online browsers' response = RestClient.get "#{@url}hooks", {:params => {:token => @token}} result = JSON.parse(response.body) - browsers = result["hooked-browsers"]["online"] + browsers = result['hooked-browsers']['online'] print_good "Retrieved online browser list [#{browsers.size} online]" browsers rescue => e @@ -70,10 +70,10 @@ def online_browsers # get offline hooked browsers def offline_browsers begin - print_verbose "Retrieving offline browsers" + print_verbose 'Retrieving offline browsers' response = RestClient.get "#{@url}hooks", {:params => {:token => @token}} result = JSON.parse(response.body) - browsers = result["hooked-browsers"]["offline"] + browsers = result['hooked-browsers']['offline'] print_good "Retrieved offline browser list [#{browsers.size} offline]" browsers rescue => e @@ -110,7 +110,7 @@ def delete_browser session # get BeEF logs def logs begin - print_verbose "Retrieving logs" + print_verbose 'Retrieving logs' response = RestClient.get "#{@url}logs", {:params => {:token => @token}} logs = JSON.parse(response.body) print_good "Retrieved #{logs['logs_count']} log entries" @@ -140,7 +140,7 @@ def browser_logs session # get command module categories def categories begin - print_verbose "Retrieving module categories" + print_verbose 'Retrieving module categories' response = RestClient.get "#{@url}categories", {:params => {:token => @token}} categories = JSON.parse(response.body) print_good "Retrieved #{categories.size} module categories" @@ -153,7 +153,7 @@ def categories # get command modules def modules begin - print_verbose "Retrieving modules" + print_verbose 'Retrieving modules' response = RestClient.get "#{@url}modules", {:params => {:token => @token}} @modules = JSON.parse(response.body) print_good "Retrieved #{@modules.size} available command modules" @@ -168,12 +168,12 @@ def get_module_id mod_name print_verbose "Retrieving id for module [name: #{mod_name}]" @modules.each do |mod| # normal modules - if mod_name.capitalize == mod[1]["class"] - return mod[1]["id"] + if mod_name.capitalize == mod[1]['class'] + return mod[1]['id'] break # metasploit modules - elsif mod[1]["class"] == "Msf_module" && mod_name.capitalize == mod[1]["name"] - return mod[1]["id"] + elsif mod[1]['class'] == 'Msf_module' && mod_name.capitalize == mod[1]['name'] + return mod[1]['id'] break end end @@ -265,7 +265,7 @@ def msf_handler options result = JSON.parse(response.body) job_id = result['id'] if job_id.nil? - print_error "Could not start payload handler: Job id is nil" + print_error 'Could not start payload handler: Job id is nil' else print_good "Started payload handler [id: #{job_id}]" end @@ -300,7 +300,7 @@ def msf_job_stop id # get all network hosts def network_hosts_all begin - print_verbose "Retrieving all network hosts" + print_verbose 'Retrieving all network hosts' response = RestClient.get "#{@url}network/hosts", {:params => {:token => @token}} details = JSON.parse(response.body) print_good "Retrieved #{details['count']} network hosts" @@ -313,7 +313,7 @@ def network_hosts_all # get all network services def network_services_all begin - print_verbose "Retrieving all network services" + print_verbose 'Retrieving all network services' response = RestClient.get "#{@url}network/services", {:params => {:token => @token}} details = JSON.parse(response.body) print_good "Retrieved #{details['count']} network services" @@ -356,7 +356,7 @@ def network_services session # get all rays def xssrays_rays_all - print_verbose "Retrieving all rays" + print_verbose 'Retrieving all rays' response = RestClient.get "#{@url}xssrays/rays", {:params => {:token => @token}} details = JSON.parse(response.body) print_good "Retrieved #{details['count']} rays" @@ -378,7 +378,7 @@ def xssrays_rays session # get all scans def xssrays_scans_all - print_verbose "Retrieving all scans" + print_verbose 'Retrieving all scans' response = RestClient.get "#{@url}xssrays/scans", {:params => {:token => @token}} details = JSON.parse(response.body) print_good "Retrieved #{details['count']} scans" @@ -407,7 +407,7 @@ def xssrays_scans session # get ruleset def dns_ruleset begin - print_verbose "Retrieving DNS ruleset" + print_verbose 'Retrieving DNS ruleset' response = RestClient.get "#{@url}dns/ruleset", {:params => {:token => @token}} details = JSON.parse(response.body) print_good "Retrieved #{details['count']} rules" @@ -470,7 +470,7 @@ def dns_delete_rule(id) ################################################################################ def autorun_rules - print_verbose "Retrieving Autorun rules" + print_verbose 'Retrieving Autorun rules' response = RestClient.get "#{@url}autorun/rules", {:params => {:token => @token}} details = JSON.parse(response.body) print_good("Retrieved #{details['count']} rules") diff --git a/tools/rest_api_examples/metasploit b/tools/rest_api_examples/metasploit index b504d2f9c0..f26fb6c42b 100755 --- a/tools/rest_api_examples/metasploit +++ b/tools/rest_api_examples/metasploit @@ -15,9 +15,9 @@ require './lib/beef_rest_api' # API if ARGV.length == 0 puts "#{$0}:" - puts "| Example BeEF RESTful API script" - puts "| Use --help for help" - puts "|_ Use verbose mode (-v) and debug mode (-d) for more output" + puts '| Example BeEF RESTful API script' + puts '| Use --help for help' + puts '|_ Use verbose mode (-v) and debug mode (-d) for more output' exit 1 end diff --git a/tools/rest_api_examples/network b/tools/rest_api_examples/network index 75f83834fa..3f7a048f4e 100755 --- a/tools/rest_api_examples/network +++ b/tools/rest_api_examples/network @@ -13,9 +13,9 @@ require './lib/beef_rest_api' if ARGV.length == 0 puts "#{$0}:" - puts "| Example BeEF RESTful API script" - puts "| Use --help for help" - puts "|_ Use verbose mode (-v) and debug mode (-d) for more output" + puts '| Example BeEF RESTful API script' + puts '| Use --help for help' + puts '|_ Use verbose mode (-v) and debug mode (-d) for more output' exit 1 end diff --git a/tools/rest_api_examples/remove-offline-browsers b/tools/rest_api_examples/remove-offline-browsers index fe3b8c50d8..2e26bd6039 100644 --- a/tools/rest_api_examples/remove-offline-browsers +++ b/tools/rest_api_examples/remove-offline-browsers @@ -13,9 +13,9 @@ require './lib/beef_rest_api' if ARGV.length == 0 puts "#{$0}:" - puts "| Example BeEF RESTful API script" - puts "| Use --help for help" - puts "|_ Use verbose mode (-v) and debug mode (-d) for more output" + puts '| Example BeEF RESTful API script' + puts '| Use --help for help' + puts '|_ Use verbose mode (-v) and debug mode (-d) for more output' exit 1 end diff --git a/tools/rest_api_examples/webrtc b/tools/rest_api_examples/webrtc index f2983f654b..cde93ba63d 100755 --- a/tools/rest_api_examples/webrtc +++ b/tools/rest_api_examples/webrtc @@ -13,9 +13,9 @@ require './lib/beef_rest_api' if ARGV.length == 0 puts "#{$0}:" - puts "| Example BeEF RESTful API script" - puts "| Use --help for help" - puts "|_ Use verbose mode (-v) and debug mode (-d) for more output" + puts '| Example BeEF RESTful API script' + puts '| Use --help for help' + puts '|_ Use verbose mode (-v) and debug mode (-d) for more output' exit 1 end diff --git a/tools/rest_api_examples/xssrays b/tools/rest_api_examples/xssrays index 3e4b0c7567..d7fd0130fd 100755 --- a/tools/rest_api_examples/xssrays +++ b/tools/rest_api_examples/xssrays @@ -12,9 +12,9 @@ require './lib/beef_rest_api' if ARGV.length == 0 puts "#{$0}:" - puts "| Example BeEF RESTful API script" - puts "| Use --help for help" - puts "|_ Use verbose mode (-v) and debug mode (-d) for more output" + puts '| Example BeEF RESTful API script' + puts '| Use --help for help' + puts '|_ Use verbose mode (-v) and debug mode (-d) for more output' exit 1 end From bff2a703cda630a3d28ac488e7b47d4046b0a323 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:22:27 +0530 Subject: [PATCH 04/85] rubocop --only Layout/SpaceInsideHashLiteralBraces -a --- spec/beef/extensions/requester_spec.rb | 2 +- test/integration/tc_debug_modules.rb | 10 ++-- test/integration/tc_dns_rest.rb | 8 +-- test/integration/tc_network_rest.rb | 26 ++++----- .../integration/tc_social_engineering_rest.rb | 6 +- test/integration/tc_webrtc_rest.rb | 46 +++++++-------- test/thirdparty/msf/unit/tc_metasploit.rb | 2 +- tools/csrf_to_beef/csrf_to_beef | 4 +- tools/csrf_to_beef/lib/output.rb | 2 +- tools/rest_api_examples/lib/beef_rest_api.rb | 58 +++++++++---------- tools/rest_api_examples/metasploit | 8 +-- 11 files changed, 86 insertions(+), 86 deletions(-) diff --git a/spec/beef/extensions/requester_spec.rb b/spec/beef/extensions/requester_spec.rb index 8aabfbd236..b96340d920 100644 --- a/spec/beef/extensions/requester_spec.rb +++ b/spec/beef/extensions/requester_spec.rb @@ -56,7 +56,7 @@ response = api.auth() @token = response[:token] - while (response = RestClient.get("#{RESTAPI_HOOKS}", {params: {token: @token}})) && + while (response = RestClient.get("#{RESTAPI_HOOKS}", { params: { token: @token } })) && (hb_details = JSON.parse(response.body)) && hb_details['hooked-browsers']['online'].empty? sleep 2 diff --git a/test/integration/tc_debug_modules.rb b/test/integration/tc_debug_modules.rb index e8c28dbf21..9cd04c23ae 100644 --- a/test/integration/tc_debug_modules.rb +++ b/test/integration/tc_debug_modules.rb @@ -27,7 +27,7 @@ class TC_DebugModules < Test::Unit::TestCase def test_1_restful_auth response = RestClient.post "#{RESTAPI_ADMIN}/login", { 'username' => "#{BEEF_USER}", - 'password' => "#{BEEF_PASSWD}"}.to_json, + 'password' => "#{BEEF_PASSWD}" }.to_json, :content_type => :json, :accept => :json assert_equal 200, response.code @@ -42,7 +42,7 @@ def test_1_restful_auth def test_2_restful_hooks BeefTest.new_victim sleep 5.0 - response = RestClient.get "#{RESTAPI_HOOKS}", {:params => {:token => @@token}} + response = RestClient.get "#{RESTAPI_HOOKS}", { :params => { :token => @@token } } assert_equal 200, response.code assert_not_nil response.body result = JSON.parse(response.body) @@ -52,7 +52,7 @@ def test_2_restful_hooks # Test RESTful API modules handler, retrieving the IDs of the 3 debug modules currently in the framework def test_3_restful_modules - response = RestClient.get "#{RESTAPI_MODULES}", {:params => {:token => @@token}} + response = RestClient.get "#{RESTAPI_MODULES}", { :params => { :token => @@token } } assert_equal 200, response.code assert_not_nil response.body result = JSON.parse(response.body) @@ -78,7 +78,7 @@ def test_return_long_string response = RestClient.post "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_debug_long_string}?token=#{@@token}", { 'repeat_string' => repeat_string, - 'repeat' => repeat_count}.to_json, + 'repeat' => repeat_count }.to_json, :content_type => :json, :accept => :json assert_equal 200, response.code @@ -144,7 +144,7 @@ def test_return_network_request # Test same-origin request (response code and content of secret_page.html) response = RestClient.post "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_debug_test_network}?token=#{@@token}", #override only a few parameters, the other ones will have default values from modules's module.rb definition - {'domain' => ATTACK_DOMAIN, 'port' => '3000', 'path' => '/demos/secret_page.html'}.to_json, + { 'domain' => ATTACK_DOMAIN, 'port' => '3000', 'path' => '/demos/secret_page.html' }.to_json, :content_type => :json, :accept => :json assert_equal 200, response.code diff --git a/test/integration/tc_dns_rest.rb b/test/integration/tc_dns_rest.rb index f8664300f5..866c2f89f2 100644 --- a/test/integration/tc_dns_rest.rb +++ b/test/integration/tc_dns_rest.rb @@ -13,8 +13,8 @@ class TC_DnsRest < Test::Unit::TestCase class << self def startup - json = {:username => BEEF_USER, :password => BEEF_PASSWD}.to_json - @@headers = {:content_type => :json, :accept => :json} + json = { :username => BEEF_USER, :password => BEEF_PASSWD }.to_json + @@headers = { :content_type => :json, :accept => :json } response = RestClient.post("#{RESTAPI_ADMIN}/login", json, @@ -46,7 +46,7 @@ def test_1_add_rule_good resource = 'A' dns_response = ['1.2.3.4'] - json = {:pattern => pattern, :resource => resource, :response => dns_response}.to_json + json = { :pattern => pattern, :resource => resource, :response => dns_response }.to_json rest_response = RestClient.post("#{RESTAPI_DNS}/rule?token=#{@@token}", json, @@ -76,7 +76,7 @@ def test_2_add_rule_bad resource = 'A' dns_response = ['1.1.1.1'] - hash = {:pattern => pattern, :resource => resource, :response => dns_response} + hash = { :pattern => pattern, :resource => resource, :response => dns_response } # Test that an empty "pattern" key returns 400 assert_raise RestClient::BadRequest do diff --git a/test/integration/tc_network_rest.rb b/test/integration/tc_network_rest.rb index cd04957359..8cbe3fd5ca 100644 --- a/test/integration/tc_network_rest.rb +++ b/test/integration/tc_network_rest.rb @@ -17,8 +17,8 @@ def startup $:.unshift($root_dir) # login and get api token - json = {:username => BEEF_USER, :password => BEEF_PASSWD}.to_json - @@headers = {:content_type => :json, :accept => :json} + json = { :username => BEEF_USER, :password => BEEF_PASSWD }.to_json + @@headers = { :content_type => :json, :accept => :json } response = RestClient.post("#{RESTAPI_ADMIN}/login", json, @@ -30,12 +30,12 @@ def startup # create hooked browser and get session id BeefTest.new_victim sleep 5.0 - response = RestClient.get "#{RESTAPI_HOOKS}", {:params => {:token => @@token}} + response = RestClient.get "#{RESTAPI_HOOKS}", { :params => { :token => @@token } } result = JSON.parse(response.body) @@hb_session = result['hooked-browsers']['online']['0']['session'] # Retrieve Port Scanner module command ID - response = RestClient.get "#{RESTAPI_MODULES}", {:params => {:token => @@token}} + response = RestClient.get "#{RESTAPI_MODULES}", { :params => { :token => @@token } } result = JSON.parse(response.body) result.each do |mod| if mod[1]['class'] == 'Port_scanner' @@ -52,7 +52,7 @@ def startup 'closetimeout' => 1100, 'opentimeout' => 2500, 'delay' => 600, - 'debug' => false}.to_json, + 'debug' => false }.to_json, :content_type => :json, :accept => :json result = JSON.parse(response.body) @@ -89,7 +89,7 @@ def test_get_all_hosts def test_get_hosts_valid_session rest_response = nil assert_nothing_raised do - rest_response = RestClient.get("#{RESTAPI_NETWORK}/hosts/#{@@hb_session}", :params => {:token => @@token}) + rest_response = RestClient.get("#{RESTAPI_NETWORK}/hosts/#{@@hb_session}", :params => { :token => @@token }) end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -107,7 +107,7 @@ def test_get_hosts_invalid_session session_id = 'z' rest_response = nil assert_nothing_raised do - rest_response = RestClient.get("#{RESTAPI_NETWORK}/hosts/#{session_id}", :params => {:token => @@token}) + rest_response = RestClient.get("#{RESTAPI_NETWORK}/hosts/#{session_id}", :params => { :token => @@token }) end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -120,7 +120,7 @@ def test_get_host_valid_id id = 1 rest_response = nil assert_nothing_raised do - rest_response = RestClient.get("#{RESTAPI_NETWORK}/host/#{id}", :params => {:token => @@token}) + rest_response = RestClient.get("#{RESTAPI_NETWORK}/host/#{id}", :params => { :token => @@token }) end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -132,7 +132,7 @@ def test_get_host_valid_id def test_get_hosts_invalid_id id = 'z' assert_raise RestClient::ResourceNotFound do - RestClient.get("#{RESTAPI_NETWORK}/host/#{id}", :params => {:token => @@token}) + RestClient.get("#{RESTAPI_NETWORK}/host/#{id}", :params => { :token => @@token }) end end @@ -151,7 +151,7 @@ def test_get_all_services def test_get_services_valid_session rest_response = nil assert_nothing_raised do - rest_response = RestClient.get("#{RESTAPI_NETWORK}/services/#{@@hb_session}", :params => {:token => @@token}) + rest_response = RestClient.get("#{RESTAPI_NETWORK}/services/#{@@hb_session}", :params => { :token => @@token }) end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -169,7 +169,7 @@ def test_get_services_invalid_session session_id = 'z' rest_response = nil assert_nothing_raised do - rest_response = RestClient.get("#{RESTAPI_NETWORK}/services/#{session_id}", :params => {:token => @@token}) + rest_response = RestClient.get("#{RESTAPI_NETWORK}/services/#{session_id}", :params => { :token => @@token }) end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -182,7 +182,7 @@ def test_get_service_valid_id id = 1 rest_response = nil assert_nothing_raised do - rest_response = RestClient.get("#{RESTAPI_NETWORK}/service/#{id}", :params => {:token => @@token}) + rest_response = RestClient.get("#{RESTAPI_NETWORK}/service/#{id}", :params => { :token => @@token }) end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -194,7 +194,7 @@ def test_get_service_valid_id def test_get_services_invalid_id id = 'z' assert_raise RestClient::ResourceNotFound do - RestClient.get("#{RESTAPI_NETWORK}/service/#{id}", :params => {:token => @@token}) + RestClient.get("#{RESTAPI_NETWORK}/service/#{id}", :params => { :token => @@token }) end end diff --git a/test/integration/tc_social_engineering_rest.rb b/test/integration/tc_social_engineering_rest.rb index 59c6fc92b0..cf6d670586 100644 --- a/test/integration/tc_social_engineering_rest.rb +++ b/test/integration/tc_social_engineering_rest.rb @@ -15,8 +15,8 @@ class << self # Login to API before performing any tests def startup - json = {:username => BEEF_USER, :password => BEEF_PASSWD}.to_json - @@headers = {:content_type => :json, :accept => :json} + json = { :username => BEEF_USER, :password => BEEF_PASSWD }.to_json + @@headers = { :content_type => :json, :accept => :json } response = RestClient.post("#{RESTAPI_ADMIN}/login", json, @@ -48,7 +48,7 @@ def test_1_dns_spoof mount = '/beefproject' dns_spoof = true - json = {:url => url, :mount => mount, :dns_spoof => dns_spoof}.to_json + json = { :url => url, :mount => mount, :dns_spoof => dns_spoof }.to_json domain = url.gsub(%r{^https?://}, '') diff --git a/test/integration/tc_webrtc_rest.rb b/test/integration/tc_webrtc_rest.rb index 5576af404e..ff80c67f85 100644 --- a/test/integration/tc_webrtc_rest.rb +++ b/test/integration/tc_webrtc_rest.rb @@ -15,8 +15,8 @@ class << self # Login to API before performing any tests - and fetch config too def startup - json = {:username => BEEF_USER, :password => BEEF_PASSWD}.to_json - @@headers = {:content_type => :json, :accept => :json} + json = { :username => BEEF_USER, :password => BEEF_PASSWD }.to_json + @@headers = { :content_type => :json, :accept => :json } response = RestClient.post("#{RESTAPI_ADMIN}/login", json, @@ -44,8 +44,8 @@ def startup sleep 8.0 # Fetch last online browsers' ids - rest_response = RestClient.get "#{RESTAPI_HOOKS}", {:params => { - :token => @@token}} + rest_response = RestClient.get "#{RESTAPI_HOOKS}", { :params => { + :token => @@token } } result = JSON.parse(rest_response.body) browsers = result['hooked-browsers']['online'] browsers.each_with_index do |elem, index| @@ -72,8 +72,8 @@ def test_1_webrtc_check_for_two_hooked_browsers rest_response = nil assert_nothing_raised do - rest_response = RestClient.get "#{RESTAPI_HOOKS}", {:params => { - :token => @@token}} + rest_response = RestClient.get "#{RESTAPI_HOOKS}", { :params => { + :token => @@token } } end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -88,7 +88,7 @@ def test_2_webrtc_establishing_p2p rest_response = nil assert_nothing_raised do rest_response = RestClient.post("#{RESTAPI_WEBRTC}/go?token=#{@@token}", - {:from => @@victim1id, :to => @@victim2id, :verbose => 'true'}.to_json, + { :from => @@victim1id, :to => @@victim2id, :verbose => 'true' }.to_json, @@headers) end check_rest_response(rest_response) @@ -99,8 +99,8 @@ def test_2_webrtc_establishing_p2p rest_response = nil assert_nothing_raised do - rest_response = RestClient.get "#{RESTAPI_LOGS}", {:params => { - :token => @@token}} + rest_response = RestClient.get "#{RESTAPI_LOGS}", { :params => { + :token => @@token } } end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -124,8 +124,8 @@ def test_3_webrtc_send_msg # assumes test 2 has run rest_response = nil assert_nothing_raised do rest_response = RestClient.post("#{RESTAPI_WEBRTC}/msg?token=#{@@token}", - {:from => @@victim1id, :to => @@victim2id, - :message => 'RTC test message'}.to_json, + { :from => @@victim1id, :to => @@victim2id, + :message => 'RTC test message' }.to_json, @@headers) end check_rest_response(rest_response) @@ -136,8 +136,8 @@ def test_3_webrtc_send_msg # assumes test 2 has run rest_response = nil assert_nothing_raised do - rest_response = RestClient.get "#{RESTAPI_LOGS}", {:params => { - :token => @@token}} + rest_response = RestClient.get "#{RESTAPI_LOGS}", { :params => { + :token => @@token } } end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -162,8 +162,8 @@ def test_4_webrtc_stealthmode # assumes test 2 has run # Test our two browsers are still online rest_response = nil assert_nothing_raised do - rest_response = RestClient.get "#{RESTAPI_HOOKS}", {:params => { - :token => @@token}} + rest_response = RestClient.get "#{RESTAPI_HOOKS}", { :params => { + :token => @@token } } end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -184,8 +184,8 @@ def test_4_webrtc_stealthmode # assumes test 2 has run rest_response = nil assert_nothing_raised do rest_response = RestClient.post("#{RESTAPI_WEBRTC}/msg?token=#{@@token}", - {:from => @@victim1id, :to => @@victim2id, - :message => '!gostealth'}.to_json, + { :from => @@victim1id, :to => @@victim2id, + :message => '!gostealth' }.to_json, @@headers) end check_rest_response(rest_response) @@ -197,8 +197,8 @@ def test_4_webrtc_stealthmode # assumes test 2 has run # Test that the browser is now offline rest_response = nil assert_nothing_raised do - rest_response = RestClient.get "#{RESTAPI_HOOKS}", {:params => { - :token => @@token}} + rest_response = RestClient.get "#{RESTAPI_HOOKS}", { :params => { + :token => @@token } } end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -213,8 +213,8 @@ def test_4_webrtc_stealthmode # assumes test 2 has run rest_response = nil assert_nothing_raised do rest_response = RestClient.post("#{RESTAPI_WEBRTC}/msg?token=#{@@token}", - {:from => @@victim1id, :to => @@victim2id, - :message => '!endstealth'}.to_json, + { :from => @@victim1id, :to => @@victim2id, + :message => '!endstealth' }.to_json, @@headers) end check_rest_response(rest_response) @@ -226,8 +226,8 @@ def test_4_webrtc_stealthmode # assumes test 2 has run # Test that the browser is now online rest_response = nil assert_nothing_raised do - rest_response = RestClient.get "#{RESTAPI_HOOKS}", {:params => { - :token => @@token}} + rest_response = RestClient.get "#{RESTAPI_HOOKS}", { :params => { + :token => @@token } } end check_rest_response(rest_response) result = JSON.parse(rest_response.body) diff --git a/test/thirdparty/msf/unit/tc_metasploit.rb b/test/thirdparty/msf/unit/tc_metasploit.rb index 0db779b40a..b33bc79d8e 100644 --- a/test/thirdparty/msf/unit/tc_metasploit.rb +++ b/test/thirdparty/msf/unit/tc_metasploit.rb @@ -123,7 +123,7 @@ def test_payloads def test_launch_exploit new_api @api.login - opts = { 'PAYLOAD' => 'windows/meterpreter/bind_tcp', 'URIPATH' => '/test1','SRVPORT' => 8080} + opts = { 'PAYLOAD' => 'windows/meterpreter/bind_tcp', 'URIPATH' => '/test1','SRVPORT' => 8080 } ret = nil assert_nothing_raised do ret = @api.launch_exploit('windows/browser/adobe_utilprintf',opts) diff --git a/tools/csrf_to_beef/csrf_to_beef b/tools/csrf_to_beef/csrf_to_beef index 0d00aea5c5..743e65f020 100755 --- a/tools/csrf_to_beef/csrf_to_beef +++ b/tools/csrf_to_beef/csrf_to_beef @@ -156,7 +156,7 @@ def get_options_from_url(url, method, postdata, mname) end end end - return {:target_url=>target_url, :method=>method, :enctype=>enctype, :options=>options} + return { :target_url=>target_url, :method=>method, :enctype=>enctype, :options=>options } end # @@ -224,7 +224,7 @@ def get_options_from_burp_file(fname, mname) end end end - return {:target_url=>target_url, :method=>method, :enctype=>enctype, :options=>options} + return { :target_url=>target_url, :method=>method, :enctype=>enctype, :options=>options } end # diff --git a/tools/csrf_to_beef/lib/output.rb b/tools/csrf_to_beef/lib/output.rb index fe3066bc61..b2d33d65a2 100644 --- a/tools/csrf_to_beef/lib/output.rb +++ b/tools/csrf_to_beef/lib/output.rb @@ -6,7 +6,7 @@ def colorize(color_code) "\e[#{color_code}m#{self}\e[0m" end - {:red => 31, + { :red => 31, :green => 32, :yellow => 33, :blue => 34, diff --git a/tools/rest_api_examples/lib/beef_rest_api.rb b/tools/rest_api_examples/lib/beef_rest_api.rb index 4b14d90bb8..602154bb77 100644 --- a/tools/rest_api_examples/lib/beef_rest_api.rb +++ b/tools/rest_api_examples/lib/beef_rest_api.rb @@ -32,7 +32,7 @@ def auth # get BeEF version def version begin - response = RestClient.get "#{@url}server/version", {:params => {:token => @token}} + response = RestClient.get "#{@url}server/version", { :params => { :token => @token } } result = JSON.parse(response.body) print_good "Retrieved BeEF version: #{result['version']}" result['version'] @@ -44,7 +44,7 @@ def version # get server mounts def mounts begin - response = RestClient.get "#{@url}server/mounts", {:params => {:token => @token}} + response = RestClient.get "#{@url}server/mounts", { :params => { :token => @token } } result = JSON.parse(response.body) print_good "Retrieved BeEF server mounts: #{result['mounts']}" result['mounts'] @@ -57,7 +57,7 @@ def mounts def online_browsers begin print_verbose 'Retrieving online browsers' - response = RestClient.get "#{@url}hooks", {:params => {:token => @token}} + response = RestClient.get "#{@url}hooks", { :params => { :token => @token } } result = JSON.parse(response.body) browsers = result['hooked-browsers']['online'] print_good "Retrieved online browser list [#{browsers.size} online]" @@ -71,7 +71,7 @@ def online_browsers def offline_browsers begin print_verbose 'Retrieving offline browsers' - response = RestClient.get "#{@url}hooks", {:params => {:token => @token}} + response = RestClient.get "#{@url}hooks", { :params => { :token => @token } } result = JSON.parse(response.body) browsers = result['hooked-browsers']['offline'] print_good "Retrieved offline browser list [#{browsers.size} offline]" @@ -85,7 +85,7 @@ def offline_browsers def browser_details session begin print_verbose "Retrieving browser details for hooked browser [session: #{session}]" - response = RestClient.get "#{@url}browserdetails/#{session}", {:params => {:token => @token}} + response = RestClient.get "#{@url}browserdetails/#{session}", { :params => { :token => @token } } result = JSON.parse(response.body) details = result['details'] print_good "Retrieved #{details.size} browser details" @@ -99,7 +99,7 @@ def browser_details session def delete_browser session begin print_verbose "Removing hooked browser [session: #{session}]" - response = RestClient.get "#{@url}hooks/#{session}/delete", {:params => {:token => @token}} + response = RestClient.get "#{@url}hooks/#{session}/delete", { :params => { :token => @token } } print_good "Removed browser [session: #{session}]" if response.code == 200 response rescue => e @@ -111,7 +111,7 @@ def delete_browser session def logs begin print_verbose 'Retrieving logs' - response = RestClient.get "#{@url}logs", {:params => {:token => @token}} + response = RestClient.get "#{@url}logs", { :params => { :token => @token } } logs = JSON.parse(response.body) print_good "Retrieved #{logs['logs_count']} log entries" logs @@ -124,7 +124,7 @@ def logs def browser_logs session begin print_verbose "Retrieving browser logs [session: #{session}]" - response = RestClient.get "#{@url}logs/#{session}", {:params => {:token => @token}} + response = RestClient.get "#{@url}logs/#{session}", { :params => { :token => @token } } logs = JSON.parse(response.body) print_good "Retrieved #{logs['logs'].size} browser logs" logs @@ -141,7 +141,7 @@ def browser_logs session def categories begin print_verbose 'Retrieving module categories' - response = RestClient.get "#{@url}categories", {:params => {:token => @token}} + response = RestClient.get "#{@url}categories", { :params => { :token => @token } } categories = JSON.parse(response.body) print_good "Retrieved #{categories.size} module categories" categories @@ -154,7 +154,7 @@ def categories def modules begin print_verbose 'Retrieving modules' - response = RestClient.get "#{@url}modules", {:params => {:token => @token}} + response = RestClient.get "#{@url}modules", { :params => { :token => @token } } @modules = JSON.parse(response.body) print_good "Retrieved #{@modules.size} available command modules" @modules @@ -184,7 +184,7 @@ def get_module_id mod_name def module_details id begin print_verbose "Retrieving details for command module [id: #{id}]" - response = RestClient.get "#{@url}modules/#{id}", {:params => {:token => @token}} + response = RestClient.get "#{@url}modules/#{id}", { :params => { :token => @token } } details = JSON.parse(response.body) print_good "Retrieved details for module [#{details['name']}]" details @@ -220,7 +220,7 @@ def execute_module session, mod_id, options # get metasploit version def msf_version begin - response = RestClient.get "#{@url}msf/version", {:params => {:token => @token}} + response = RestClient.get "#{@url}msf/version", { :params => { :token => @token } } result = JSON.parse(response.body) version = result['version']['version'] print_good "Retrieved Metasploit version: #{version}" @@ -233,7 +233,7 @@ def msf_version # get metasploit jobs def msf_jobs begin - response = RestClient.get "#{@url}msf/jobs", {:params => {:token => @token}} + response = RestClient.get "#{@url}msf/jobs", { :params => { :token => @token } } result = JSON.parse(response.body) jobs = result['jobs'] print_good "Retrieved job list [#{jobs.size} jobs]" @@ -246,7 +246,7 @@ def msf_jobs # get metasploit job info def msf_job_info id begin - response = RestClient.get "#{@url}msf/job/#{id}/info", {:params => {:token => @token}} + response = RestClient.get "#{@url}msf/job/#{id}/info", { :params => { :token => @token } } details = JSON.parse(response.body) print_good "Retrieved job information [id: #{id}]" details @@ -279,7 +279,7 @@ def msf_handler options def msf_job_stop id print_verbose "Stopping Metasploit job [id: #{id}]" begin - response = RestClient.get "#{@url}msf/job/#{id}/stop", {:params => {:token => @token}} + response = RestClient.get "#{@url}msf/job/#{id}/stop", { :params => { :token => @token } } result = JSON.parse(response.body) if result['success'].nil? print_error "Could not stop Metasploit job [id: #{id}]: No such job ?" @@ -301,7 +301,7 @@ def msf_job_stop id def network_hosts_all begin print_verbose 'Retrieving all network hosts' - response = RestClient.get "#{@url}network/hosts", {:params => {:token => @token}} + response = RestClient.get "#{@url}network/hosts", { :params => { :token => @token } } details = JSON.parse(response.body) print_good "Retrieved #{details['count']} network hosts" details @@ -314,7 +314,7 @@ def network_hosts_all def network_services_all begin print_verbose 'Retrieving all network services' - response = RestClient.get "#{@url}network/services", {:params => {:token => @token}} + response = RestClient.get "#{@url}network/services", { :params => { :token => @token } } details = JSON.parse(response.body) print_good "Retrieved #{details['count']} network services" details @@ -327,7 +327,7 @@ def network_services_all def network_hosts session begin print_verbose "Retrieving network hosts for hooked browser [session: #{session}]" - response = RestClient.get "#{@url}network/hosts/#{session}", {:params => {:token => @token}} + response = RestClient.get "#{@url}network/hosts/#{session}", { :params => { :token => @token } } details = JSON.parse(response.body) print_good "Retrieved #{details['count']} network hosts" details @@ -340,7 +340,7 @@ def network_hosts session def network_services session begin print_verbose "Retrieving network services for hooked browser [session: #{session}]" - response = RestClient.get "#{@url}network/services/#{session}", {:params => {:token => @token}} + response = RestClient.get "#{@url}network/services/#{session}", { :params => { :token => @token } } details = JSON.parse(response.body) print_good "Retrieved #{details['count']} network services" details @@ -357,7 +357,7 @@ def network_services session # get all rays def xssrays_rays_all print_verbose 'Retrieving all rays' - response = RestClient.get "#{@url}xssrays/rays", {:params => {:token => @token}} + response = RestClient.get "#{@url}xssrays/rays", { :params => { :token => @token } } details = JSON.parse(response.body) print_good "Retrieved #{details['count']} rays" details @@ -368,7 +368,7 @@ def xssrays_rays_all # get rays by session def xssrays_rays session print_verbose "Retrieving rays for hooked browser [session: #{session}]" - response = RestClient.get "#{@url}xssrays/rays/#{session}", {:params => {:token => @token}} + response = RestClient.get "#{@url}xssrays/rays/#{session}", { :params => { :token => @token } } details = JSON.parse(response.body) print_good "Retrieved #{details['count']} rays" details @@ -379,7 +379,7 @@ def xssrays_rays session # get all scans def xssrays_scans_all print_verbose 'Retrieving all scans' - response = RestClient.get "#{@url}xssrays/scans", {:params => {:token => @token}} + response = RestClient.get "#{@url}xssrays/scans", { :params => { :token => @token } } details = JSON.parse(response.body) print_good "Retrieved #{details['count']} scans" details @@ -390,7 +390,7 @@ def xssrays_scans_all # get scans by session def xssrays_scans session print_verbose "Retrieving scans for hooked browser [session: #{session}]" - response = RestClient.get "#{@url}xssrays/scans/#{session}", {:params => {:token => @token}} + response = RestClient.get "#{@url}xssrays/scans/#{session}", { :params => { :token => @token } } details = JSON.parse(response.body) print_good "Retrieved #{details['count']} scans" details @@ -408,7 +408,7 @@ def xssrays_scans session def dns_ruleset begin print_verbose 'Retrieving DNS ruleset' - response = RestClient.get "#{@url}dns/ruleset", {:params => {:token => @token}} + response = RestClient.get "#{@url}dns/ruleset", { :params => { :token => @token } } details = JSON.parse(response.body) print_good "Retrieved #{details['count']} rules" details @@ -445,7 +445,7 @@ def dns_add_rule(dns_pattern, dns_resource, dns_response) def dns_get_rule(id) begin print_verbose "Retrieving DNS rule details [id: #{id}]" - response = RestClient.get "#{@url}dns/rule/#{id}", {:params => {:token => @token}} + response = RestClient.get "#{@url}dns/rule/#{id}", { :params => { :token => @token } } details = JSON.parse(response.body) print_good "Retrieved rule [id: #{details['id']}]" details @@ -471,7 +471,7 @@ def dns_delete_rule(id) def autorun_rules print_verbose 'Retrieving Autorun rules' - response = RestClient.get "#{@url}autorun/rules", {:params => {:token => @token}} + response = RestClient.get "#{@url}autorun/rules", { :params => { :token => @token } } details = JSON.parse(response.body) print_good("Retrieved #{details['count']} rules") details @@ -511,7 +511,7 @@ def autorun_add_rule(data) def autorun_run_rule_on_all_browsers(rule_id) print_verbose "Running Autorun rule #{rule_id} on all browsers" - response = RestClient.get "#{@url}autorun/run/#{rule_id}", {:params => {:token => @token}} + response = RestClient.get "#{@url}autorun/run/#{rule_id}", { :params => { :token => @token } } details = JSON.parse(response.body) print_debug details print_good('Done') @@ -522,7 +522,7 @@ def autorun_run_rule_on_all_browsers(rule_id) def autorun_run_rule_on_browser(rule_id, hb_id) print_verbose "Running Autorun rule #{rule_id} on browser #{hb_id}" - response = RestClient.get "#{@url}autorun/run/#{rule_id}/#{hb_id}", {:params => {:token => @token}} + response = RestClient.get "#{@url}autorun/run/#{rule_id}/#{hb_id}", { :params => { :token => @token } } details = JSON.parse(response.body) print_good('Done') details @@ -539,7 +539,7 @@ def autorun_run_rule_on_browser(rule_id, hb_id) def webrtc_status id begin print_verbose "Retrieving status for hooked browser [id: #{id}]" - response = RestClient.get "#{@url}webrtc/status/#{id}", {:params => {:token => @token}} + response = RestClient.get "#{@url}webrtc/status/#{id}", { :params => { :token => @token } } details = JSON.parse(response.body) print_good "Retrieved status for hooked browser [id: #{id}]" details diff --git a/tools/rest_api_examples/metasploit b/tools/rest_api_examples/metasploit index f26fb6c42b..433bde97cf 100755 --- a/tools/rest_api_examples/metasploit +++ b/tools/rest_api_examples/metasploit @@ -73,10 +73,10 @@ print_status "Authenticating to: #{proto}://#{host}:#{port}" # Start payload handlers handlers = [ - @api.msf_handler( {'PAYLOAD'=>'generic/shell_reverse_tcp', 'LPORT' => '6666', 'LHOST' => host} ), - @api.msf_handler( {'PAYLOAD'=>'cmd/unix/reverse', 'LPORT' => '6010', 'LHOST' => host} ), - @api.msf_handler( {'PAYLOAD'=>'linux/x86/meterpreter/reverse_tcp', 'LPORT' => '6020', 'LHOST'=> host} ), - @api.msf_handler( {'PAYLOAD'=>'windows/meterpreter/reverse_tcp', 'LPORT' => '6030', 'LHOST'=> host} ) + @api.msf_handler( { 'PAYLOAD'=>'generic/shell_reverse_tcp', 'LPORT' => '6666', 'LHOST' => host } ), + @api.msf_handler( { 'PAYLOAD'=>'cmd/unix/reverse', 'LPORT' => '6010', 'LHOST' => host } ), + @api.msf_handler( { 'PAYLOAD'=>'linux/x86/meterpreter/reverse_tcp', 'LPORT' => '6020', 'LHOST'=> host } ), + @api.msf_handler( { 'PAYLOAD'=>'windows/meterpreter/reverse_tcp', 'LPORT' => '6030', 'LHOST'=> host } ) ] # Retrieve msf jobs From f4a120209e14c80550f6ffe64b0f2e7b209e9deb Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:23:04 +0530 Subject: [PATCH 05/85] rubocop --only Layout/EmptyLineBetweenDefs -a --- modules/browser/webcam_html5/module.rb | 1 + spec/spec_helper.rb | 6 ++++++ test/integration/tc_debug_modules.rb | 2 ++ tools/rest_api_examples/lib/print.rb | 4 ++++ 4 files changed, 13 insertions(+) diff --git a/modules/browser/webcam_html5/module.rb b/modules/browser/webcam_html5/module.rb index 62c755c2a8..479dae1226 100644 --- a/modules/browser/webcam_html5/module.rb +++ b/modules/browser/webcam_html5/module.rb @@ -11,6 +11,7 @@ def self.options 'store_data' => [['320x240'], ['640x480'], ['Full']], 'valueField' => 'choice', 'value' => '320x240', editable: false, 'displayField' => 'choice', 'mode' => 'local', 'autoWidth' => true }, ] end + def post_execute content = {} content['result'] = @datastore['result'] unless @datastore['result'].nil? diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 58a37815e0..4b0ee09156 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -82,9 +82,11 @@ class << self def level=(val) (self.logger ||= Logger.new($stdout)).level = val end + def level (self.logger ||= Logger.new($stdout)).level end + # Proxy common logger methods if called directly (info, warn, error, etc.) def method_missing(m, *args, &blk) lg = (self.logger ||= Logger.new($stdout)) @@ -92,6 +94,7 @@ def method_missing(m, *args, &blk) super end + def respond_to_missing?(m, include_priv = false) (self.logger ||= Logger.new($stdout)).respond_to?(m, include_priv) || super end @@ -109,9 +112,11 @@ class << self def level=(val) (self.logger ||= Logger.new($stdout)).level = val end + def level (self.logger ||= Logger.new($stdout)).level end + # Proxy to logger for typical logging calls def method_missing(m, *args, &blk) lg = (self.logger ||= Logger.new($stdout)) @@ -119,6 +124,7 @@ def method_missing(m, *args, &blk) super end + def respond_to_missing?(m, include_priv = false) (self.logger ||= Logger.new($stdout)).respond_to?(m, include_priv) || super end diff --git a/test/integration/tc_debug_modules.rb b/test/integration/tc_debug_modules.rb index 9cd04c23ae..bc7ec5c821 100644 --- a/test/integration/tc_debug_modules.rb +++ b/test/integration/tc_debug_modules.rb @@ -70,6 +70,7 @@ def test_3_restful_modules assert_not_nil @@mod_debug_ascii_chars assert_not_nil @@mod_debug_test_network end + # ## Test debug module "Test_return_long_string" using the RESTful API def test_return_long_string @@ -105,6 +106,7 @@ def test_return_long_string assert_not_nil data assert_equal (repeat_string * repeat_count),data end + # ## Test debug module "Test_return_ascii_chars" using the RESTful API def test_return_ascii_chars diff --git a/tools/rest_api_examples/lib/print.rb b/tools/rest_api_examples/lib/print.rb index 00a1b951ea..6ea5ca8f81 100644 --- a/tools/rest_api_examples/lib/print.rb +++ b/tools/rest_api_examples/lib/print.rb @@ -2,15 +2,19 @@ def print_debug s pp s if @debug end + def print_verbose s puts "[*] #{s}".gray if @verbose end + def print_status s puts "[*] #{s}".blue end + def print_good s puts "[+] #{s}".green end + def print_error s puts "[!] Error: #{s}".red end From e91ff471124034c16891d07bb6e67eda995d68d1 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:23:37 +0530 Subject: [PATCH 06/85] rubocop --only Layout/EmptyLines -a --- extensions/notifications/notifications.rb | 1 - spec/beef/core/main/autorun_engine/autorun_engine_spec.rb | 1 - .../core/main/network_stack/handlers/redirector_spec.rb | 1 - spec/beef/extensions/dns_spec.rb | 4 ---- spec/beef/extensions/websocket_hooked_browser_spec.rb | 1 - spec/beef/modules/debug/test_beef_debugs_spec.rb | 1 - tools/rest_api_examples/lib/beef_rest_api.rb | 7 ------- 7 files changed, 16 deletions(-) diff --git a/extensions/notifications/notifications.rb b/extensions/notifications/notifications.rb index b42179b406..d332c828f6 100644 --- a/extensions/notifications/notifications.rb +++ b/extensions/notifications/notifications.rb @@ -9,7 +9,6 @@ require 'extensions/notifications/channels/slack_workspace' require 'extensions/notifications/channels/ntfy' - module BeEF module Extension module Notifications diff --git a/spec/beef/core/main/autorun_engine/autorun_engine_spec.rb b/spec/beef/core/main/autorun_engine/autorun_engine_spec.rb index 02258042db..ac8051afc3 100644 --- a/spec/beef/core/main/autorun_engine/autorun_engine_spec.rb +++ b/spec/beef/core/main/autorun_engine/autorun_engine_spec.rb @@ -42,7 +42,6 @@ print_info 'Modules already loaded' end - # Load up DB and migrate if necessary ActiveRecord::Base.logger = nil OTR::ActiveRecord.configure_from_hash!(adapter: 'sqlite3', database: db_file) diff --git a/spec/beef/core/main/network_stack/handlers/redirector_spec.rb b/spec/beef/core/main/network_stack/handlers/redirector_spec.rb index 4967f33af2..17fbc81722 100644 --- a/spec/beef/core/main/network_stack/handlers/redirector_spec.rb +++ b/spec/beef/core/main/network_stack/handlers/redirector_spec.rb @@ -13,7 +13,6 @@ trap('INT') { @server.stop } trap('TERM') { @server.stop } - # ***** IMPORTANT: close any and all AR/OTR connections before forking ***** disconnect_all_active_record! diff --git a/spec/beef/extensions/dns_spec.rb b/spec/beef/extensions/dns_spec.rb index a1aed66e12..75fdac3147 100644 --- a/spec/beef/extensions/dns_spec.rb +++ b/spec/beef/extensions/dns_spec.rb @@ -149,7 +149,6 @@ # expect(id).to match(/^\h{8}$/) # end - it 'get good rule' do pattern = 'be.ef' response = '1.1.1.1' @@ -248,9 +247,6 @@ end - - - # Tests each supported type of query failure # def test_13_failure_types # begin diff --git a/spec/beef/extensions/websocket_hooked_browser_spec.rb b/spec/beef/extensions/websocket_hooked_browser_spec.rb index 34156645ed..f60509dd3f 100644 --- a/spec/beef/extensions/websocket_hooked_browser_spec.rb +++ b/spec/beef/extensions/websocket_hooked_browser_spec.rb @@ -67,7 +67,6 @@ # Generate a token for the server to respond with @token = BeEF::Core::Crypto.api_token - # ***** IMPORTANT: close any and all AR/OTR connections before forking ***** disconnect_all_active_record! diff --git a/spec/beef/modules/debug/test_beef_debugs_spec.rb b/spec/beef/modules/debug/test_beef_debugs_spec.rb index 075d13490a..6c6e85c5e9 100644 --- a/spec/beef/modules/debug/test_beef_debugs_spec.rb +++ b/spec/beef/modules/debug/test_beef_debugs_spec.rb @@ -41,7 +41,6 @@ print_info 'Modules already loaded' end - # Load up DB and migrate if necessary ActiveRecord::Base.logger = nil OTR::ActiveRecord.configure_from_hash!(adapter: 'sqlite3', database: db_file) diff --git a/tools/rest_api_examples/lib/beef_rest_api.rb b/tools/rest_api_examples/lib/beef_rest_api.rb index 602154bb77..5c5b9ea6c6 100644 --- a/tools/rest_api_examples/lib/beef_rest_api.rb +++ b/tools/rest_api_examples/lib/beef_rest_api.rb @@ -212,7 +212,6 @@ def execute_module session, mod_id, options end end - ################################################################################ ### Metasploit API ################################################################################ @@ -292,7 +291,6 @@ def msf_job_stop id end end - ################################################################################ ### Network API ################################################################################ @@ -349,7 +347,6 @@ def network_services session end end - ################################################################################ ### XssRays API ################################################################################ @@ -398,8 +395,6 @@ def xssrays_scans session print_error "Could not retrieve scans: #{e.message}" end - - ################################################################################ ### DNS API ################################################################################ @@ -464,7 +459,6 @@ def dns_delete_rule(id) print_error "Could not delete DNS rule: #{e.message}" end - ################################################################################ ### Autorun ################################################################################ @@ -530,7 +524,6 @@ def autorun_run_rule_on_browser(rule_id, hb_id) print_error "Could not run Autorun rule #{rule_id}: #{e.message}" end - ################################################################################ ### WebRTC ################################################################################ From fc1d4a728515e99a93a14931fa0336345f366cb6 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:24:18 +0530 Subject: [PATCH 07/85] rubocop --only Layout/IndentationWidth -a --- core/main/autorun_engine/engine.rb | 2 +- extensions/webrtc/api.rb | 56 +- extensions/webrtc/extension.rb | 18 +- extensions/webrtc/handlers.rb | 16 +- extensions/webrtc/models/rtcmanage.rb | 70 +- extensions/webrtc/models/rtcmodulestatus.rb | 28 +- extensions/webrtc/models/rtcsignal.rb | 20 +- extensions/webrtc/models/rtcstatus.rb | 26 +- spec/beef/api/auth_rate_spec.rb | 28 +- spec/beef/extensions/dns_spec.rb | 16 +- spec/beef/extensions/websocket_spec.rb | 2 +- spec/features/all_modules_spec.rb | 86 +- spec/features/debug_modules_spec.rb | 96 +- spec/requests/beef_test_spec.rb | 136 +-- spec/spec_helper.rb | 10 +- spec/support/ui_support.rb | 82 +- test/integration/tc_debug_modules.rb | 18 +- .../integration/tc_social_engineering_rest.rb | 10 +- test/integration/tc_webrtc_rest.rb | 4 +- tools/rest_api_examples/lib/beef_rest_api.rb | 860 +++++++++--------- tools/rest_api_examples/lib/string.rb | 36 +- 21 files changed, 810 insertions(+), 810 deletions(-) diff --git a/core/main/autorun_engine/engine.rb b/core/main/autorun_engine/engine.rb index 6bd17625b4..c7df6df45d 100644 --- a/core/main/autorun_engine/engine.rb +++ b/core/main/autorun_engine/engine.rb @@ -158,7 +158,7 @@ def zombie_browser_matches_rule?(browser, browser_version, rule) # check if rule specifies multiple browsers if rule.browser =~ /\A[A-Z]+\Z/ - return false unless rule.browser == 'ALL' || browser == rule.browser + return false unless rule.browser == 'ALL' || browser == rule.browser # check if the browser version matches browser_version_match = compare_versions(browser_version.to_s, b_ver_cond, b_ver.to_s) diff --git a/extensions/webrtc/api.rb b/extensions/webrtc/api.rb index d227734f54..2003e7dc0c 100644 --- a/extensions/webrtc/api.rb +++ b/extensions/webrtc/api.rb @@ -4,38 +4,38 @@ # See the file 'doc/COPYING' for copying permission # module BeEF -module Extension -module WebRTC - - module RegisterHttpHandler - - BeEF::API::Registrar.instance.register(BeEF::Extension::WebRTC::RegisterHttpHandler, BeEF::API::Server, 'mount_handler') - - # We register the http handler for the WebRTC signalling extension. - # This http handler will handle WebRTC signals from browser to browser + module Extension + module WebRTC + + module RegisterHttpHandler + + BeEF::API::Registrar.instance.register(BeEF::Extension::WebRTC::RegisterHttpHandler, BeEF::API::Server, 'mount_handler') + + # We register the http handler for the WebRTC signalling extension. + # This http handler will handle WebRTC signals from browser to browser - # We also define an rtc message handler, so that the beefwebrtc object can send messages back into BeEF - def self.mount_handler(beef_server) - beef_server.mount('/rtcsignal', BeEF::Extension::WebRTC::SignalHandler) - beef_server.mount('/rtcmessage', BeEF::Extension::WebRTC::MessengeHandler) - beef_server.mount('/api/webrtc', BeEF::Extension::WebRTC::WebRTCRest.new) - end - - end + # We also define an rtc message handler, so that the beefwebrtc object can send messages back into BeEF + def self.mount_handler(beef_server) + beef_server.mount('/rtcsignal', BeEF::Extension::WebRTC::SignalHandler) + beef_server.mount('/rtcmessage', BeEF::Extension::WebRTC::MessengeHandler) + beef_server.mount('/api/webrtc', BeEF::Extension::WebRTC::WebRTCRest.new) + end + + end - module RegisterPreHookCallback + module RegisterPreHookCallback - BeEF::API::Registrar.instance.register(BeEF::Extension::WebRTC::RegisterPreHookCallback, BeEF::API::Server::Hook, 'pre_hook_send') + BeEF::API::Registrar.instance.register(BeEF::Extension::WebRTC::RegisterPreHookCallback, BeEF::API::Server::Hook, 'pre_hook_send') - # We register this pre hook action to ensure that signals going to a browser are included back in the hook.js polling - # This is also used so that BeEF can send RTCManagement messages to the hooked browser too - def self.pre_hook_send(hooked_browser, body, params, request, response) - dhook = BeEF::Extension::WebRTC::API::Hook.new - dhook.requester_run(hooked_browser, body) - end + # We register this pre hook action to ensure that signals going to a browser are included back in the hook.js polling + # This is also used so that BeEF can send RTCManagement messages to the hooked browser too + def self.pre_hook_send(hooked_browser, body, params, request, response) + dhook = BeEF::Extension::WebRTC::API::Hook.new + dhook.requester_run(hooked_browser, body) + end + end + + end end - -end -end end diff --git a/extensions/webrtc/extension.rb b/extensions/webrtc/extension.rb index afc1e47881..6e1bfb140d 100644 --- a/extensions/webrtc/extension.rb +++ b/extensions/webrtc/extension.rb @@ -4,17 +4,17 @@ # See the file 'doc/COPYING' for copying permission # module BeEF -module Extension -module WebRTC + module Extension + module WebRTC - extend BeEF::API::Extension + extend BeEF::API::Extension - @short_name = 'webrtc' - @full_name = 'WebRTC' - @description = 'WebRTC extension to all browsers to connect to each other (P2P) with WebRTC' - -end -end + @short_name = 'webrtc' + @full_name = 'WebRTC' + @description = 'WebRTC extension to all browsers to connect to each other (P2P) with WebRTC' + + end + end end require 'extensions/webrtc/models/rtcsignal' diff --git a/extensions/webrtc/handlers.rb b/extensions/webrtc/handlers.rb index 7617d0a6a5..e1b525866b 100644 --- a/extensions/webrtc/handlers.rb +++ b/extensions/webrtc/handlers.rb @@ -95,52 +95,52 @@ def setup() # Find existing status message stat = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => zombie_db.id, :target_hooked_browser_id => peer_zombie_db.id) || nil unless stat.nil? - stat.status = 'Connected' + stat.status = 'Connected' stat.updated_at = Time.now stat.save end stat2 = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => peer_zombie_db.id, :target_hooked_browser_id => zombie_db.id) || nil unless stat2.nil? - stat2.status = 'Connected' + stat2.status = 'Connected' stat2.updated_at = Time.now stat2.save end elsif (message.end_with?('disconnected')) stat = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => zombie_db.id, :target_hooked_browser_id => peer_zombie_db.id) || nil unless stat.nil? - stat.status = 'Disconnected' + stat.status = 'Disconnected' stat.updated_at = Time.now stat.save end stat2 = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => peer_zombie_db.id, :target_hooked_browser_id => zombie_db.id) || nil unless stat2.nil? - stat2.status = 'Disconnected' + stat2.status = 'Disconnected' stat2.updated_at = Time.now stat2.save end elsif (message == 'Stayin alive') stat = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => zombie_db.id, :target_hooked_browser_id => peer_zombie_db.id) || nil unless stat.nil? - stat.status = 'Stealthed!!' + stat.status = 'Stealthed!!' stat.updated_at = Time.now stat.save end stat2 = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => peer_zombie_db.id, :target_hooked_browser_id => zombie_db.id) || nil unless stat2.nil? - stat2.status = 'Peer-controlled stealth-mode' + stat2.status = 'Peer-controlled stealth-mode' stat2.updated_at = Time.now stat2.save end elsif (message == 'Coming out of stealth...') stat = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => zombie_db.id, :target_hooked_browser_id => peer_zombie_db.id) || nil unless stat.nil? - stat.status = 'Connected' + stat.status = 'Connected' stat.updated_at = Time.now stat.save end stat2 = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => peer_zombie_db.id, :target_hooked_browser_id => zombie_db.id) || nil unless stat2.nil? - stat2.status = 'Connected' + stat2.status = 'Connected' stat2.updated_at = Time.now stat2.save end diff --git a/extensions/webrtc/models/rtcmanage.rb b/extensions/webrtc/models/rtcmanage.rb index 085e5ee7b0..458ea4fbd0 100644 --- a/extensions/webrtc/models/rtcmanage.rb +++ b/extensions/webrtc/models/rtcmanage.rb @@ -4,44 +4,44 @@ # See the file 'doc/COPYING' for copying permission # module BeEF -module Core -module Models - # - # Table stores the queued up JS commands for managing the client-side webrtc logic. - # - class RtcManage < BeEF::Core::Model - - # Starts the RTCPeerConnection process, establishing a WebRTC connection between the caller and the receiver - def self.initiate(caller, receiver, verbosity = false) - stunservers = BeEF::Core::Configuration.instance.get('beef.extension.webrtc.stunservers') - turnservers = BeEF::Core::Configuration.instance.get('beef.extension.webrtc.turnservers') - - # Add the beef.webrtc.start() JavaScript call into the RtcManage table - this will be picked up by the browser on next hook.js poll - # This is for the Receiver - r = BeEF::Core::Models::RtcManage.new(:hooked_browser_id => receiver, :message => "beef.webrtc.start(0,#{caller},JSON.stringify(#{turnservers}),JSON.stringify(#{stunservers}),#{verbosity});") - r.save! + module Core + module Models + # + # Table stores the queued up JS commands for managing the client-side webrtc logic. + # + class RtcManage < BeEF::Core::Model - # This is the same beef.webrtc.start() JS call, but for the Caller - r = BeEF::Core::Models::RtcManage.new(:hooked_browser_id => caller, :message => "beef.webrtc.start(1,#{receiver},JSON.stringify(#{turnservers}),JSON.stringify(#{stunservers}),#{verbosity});") - r.save! - end + # Starts the RTCPeerConnection process, establishing a WebRTC connection between the caller and the receiver + def self.initiate(caller, receiver, verbosity = false) + stunservers = BeEF::Core::Configuration.instance.get('beef.extension.webrtc.stunservers') + turnservers = BeEF::Core::Configuration.instance.get('beef.extension.webrtc.turnservers') - # Advises a browser to send an RTCDataChannel message to its peer - # Similar to the initiate method, this loads up a JavaScript call to the beefrtcs[peerid].sendPeerMsg() function call - def self.sendmsg(from, to, message) - r = BeEF::Core::Models::RtcManage.new(:hooked_browser_id => from, :message => "beefrtcs[#{to}].sendPeerMsg('#{message}');") - r.save! - end + # Add the beef.webrtc.start() JavaScript call into the RtcManage table - this will be picked up by the browser on next hook.js poll + # This is for the Receiver + r = BeEF::Core::Models::RtcManage.new(:hooked_browser_id => receiver, :message => "beef.webrtc.start(0,#{caller},JSON.stringify(#{turnservers}),JSON.stringify(#{stunservers}),#{verbosity});") + r.save! + + # This is the same beef.webrtc.start() JS call, but for the Caller + r = BeEF::Core::Models::RtcManage.new(:hooked_browser_id => caller, :message => "beef.webrtc.start(1,#{receiver},JSON.stringify(#{turnservers}),JSON.stringify(#{stunservers}),#{verbosity});") + r.save! + end - # Gets the browser to run the beef.webrtc.status() JavaScript function - # This JS function will return it's values to the /rtcmessage handler - def self.status(id) - r = BeEF::Core::Models::RtcManage.new(:hooked_browser_id => id, :message => "beef.webrtc.status(#{id});") - r.save! - end + # Advises a browser to send an RTCDataChannel message to its peer + # Similar to the initiate method, this loads up a JavaScript call to the beefrtcs[peerid].sendPeerMsg() function call + def self.sendmsg(from, to, message) + r = BeEF::Core::Models::RtcManage.new(:hooked_browser_id => from, :message => "beefrtcs[#{to}].sendPeerMsg('#{message}');") + r.save! + end + + # Gets the browser to run the beef.webrtc.status() JavaScript function + # This JS function will return it's values to the /rtcmessage handler + def self.status(id) + r = BeEF::Core::Models::RtcManage.new(:hooked_browser_id => id, :message => "beef.webrtc.status(#{id});") + r.save! + end + end + + end end - -end -end end diff --git a/extensions/webrtc/models/rtcmodulestatus.rb b/extensions/webrtc/models/rtcmodulestatus.rb index b1f64c26be..bd91cec1c1 100644 --- a/extensions/webrtc/models/rtcmodulestatus.rb +++ b/extensions/webrtc/models/rtcmodulestatus.rb @@ -5,22 +5,22 @@ # module BeEF -module Core -module Models - # - # Table stores the webrtc status information - # This includes things like connection status, and executed modules etc - # - + module Core + module Models + # + # Table stores the webrtc status information + # This includes things like connection status, and executed modules etc + # + - class Rtcmodulestatus < BeEF::Core::Model + class Rtcmodulestatus < BeEF::Core::Model + + belongs_to :hooked_browser + belongs_to :command_module - belongs_to :hooked_browser - belongs_to :command_module - + end + + end end - -end -end end diff --git a/extensions/webrtc/models/rtcsignal.rb b/extensions/webrtc/models/rtcsignal.rb index 41cb6513a2..c11e0a10fa 100644 --- a/extensions/webrtc/models/rtcsignal.rb +++ b/extensions/webrtc/models/rtcsignal.rb @@ -4,17 +4,17 @@ # See the file 'doc/COPYING' for copying permission # module BeEF -module Core -module Models - # - # Table stores the webrtc signals from a hooked_browser, directed to a target_hooked_browser - # - class RtcSignal < BeEF::Core::Model + module Core + module Models + # + # Table stores the webrtc signals from a hooked_browser, directed to a target_hooked_browser + # + class RtcSignal < BeEF::Core::Model - belongs_to :hooked_browser + belongs_to :hooked_browser + end + + end end - -end -end end diff --git a/extensions/webrtc/models/rtcstatus.rb b/extensions/webrtc/models/rtcstatus.rb index 0a0a21ec03..bf29bf4db7 100644 --- a/extensions/webrtc/models/rtcstatus.rb +++ b/extensions/webrtc/models/rtcstatus.rb @@ -5,20 +5,20 @@ # module BeEF -module Core -module Models - # - # Table stores the webrtc status information - # This includes things like connection status, and executed modules etc - # - + module Core + module Models + # + # Table stores the webrtc status information + # This includes things like connection status, and executed modules etc + # + - class Rtcstatus < BeEF::Core::Model - - belongs_to :hooked_browser + class Rtcstatus < BeEF::Core::Model + + belongs_to :hooked_browser + end + + end end - -end -end end diff --git a/spec/beef/api/auth_rate_spec.rb b/spec/beef/api/auth_rate_spec.rb index 1ba7b7002b..ef92f43634 100644 --- a/spec/beef/api/auth_rate_spec.rb +++ b/spec/beef/api/auth_rate_spec.rb @@ -6,21 +6,21 @@ RSpec.describe 'BeEF API Rate Limit', run_on_long_tests: true do - before(:each) do - @pid = start_beef_server_and_wait - @username = @config.get('beef.credentials.user') - @password = @config.get('beef.credentials.passwd') - end + before(:each) do + @pid = start_beef_server_and_wait + @username = @config.get('beef.credentials.user') + @password = @config.get('beef.credentials.passwd') + end after(:each) do # Shutting down server - Process.kill('KILL', @pid) unless @pid.nil? + Process.kill('KILL', @pid) unless @pid.nil? Process.wait(@pid) unless @pid.nil? # Ensure the process has exited and the port is released @pid = nil end it 'confirm correct creds are successful' do - test_api = BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, @password) + test_api = BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, @password) expect(@config.get('beef.credentials.user')).to eq('beef') expect(@config.get('beef.credentials.passwd')).to eq('beef') expect(test_api.auth()[:payload]).not_to eql('401 Unauthorized') @@ -28,26 +28,26 @@ end it 'confirm incorrect creds are unsuccessful' do - sleep 0.5 + sleep 0.5 test_api = BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, 'wrong_passowrd') expect(test_api.auth()[:payload]).to eql('401 Unauthorized') # all (unless the valid is first 1 in 10 chance) end it 'adheres to 9 bad passwords then 1 correct auth rate limits' do # create api structures with bad passwords and one good - passwds = (1..9).map { |i| 'bad_password'} # incorrect password + passwds = (1..9).map { |i| 'bad_password'} # incorrect password passwds.push @password # correct password apis = passwds.map { |pswd| BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, pswd) } (0..apis.length-1).each do |i| - test_api = apis[i] + test_api = apis[i] expect(test_api.auth()[:payload]).to eql('401 Unauthorized') # all (unless the valid is first 1 in 10 chance) end end it 'adheres to random bad passords and 1 correct auth rate limits' do # create api structures with bad passwords and one good - passwds = (1..9).map { |i| 'bad_password'} # incorrect password + passwds = (1..9).map { |i| 'bad_password'} # incorrect password passwds.push @password # correct password apis = passwds.map { |pswd| BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, pswd) } @@ -55,15 +55,15 @@ apis = apis.reverse if (apis[0].is_pass?(@password)) # prevent the first from having valid passwd (0..apis.length-1).each do |i| - test_api = apis[i] + test_api = apis[i] if (test_api.is_pass?(@password)) - sleep 0.5 + sleep 0.5 expect(@config.get('beef.credentials.user')).to eq('beef') expect(@config.get('beef.credentials.passwd')).to eq('beef') expect(test_api.auth()[:payload]).not_to eql('401 Unauthorized') expect(test_api.auth()[:payload]['success']).to be(true) # valid pass should succeed else - expect(test_api.auth()[:payload]).to eql('401 Unauthorized') + expect(test_api.auth()[:payload]).to eql('401 Unauthorized') end end end diff --git a/spec/beef/extensions/dns_spec.rb b/spec/beef/extensions/dns_spec.rb index 75fdac3147..2937575925 100644 --- a/spec/beef/extensions/dns_spec.rb +++ b/spec/beef/extensions/dns_spec.rb @@ -47,7 +47,7 @@ :pattern => 'foo.bar', :resource => IN::A, :response => [response] ) do |transaction| - transaction.respond!(response) + transaction.respond!(response) end }.to_not raise_error expect(id).to_not be_nil @@ -61,7 +61,7 @@ :pattern => %r{i\.(love|hate)\.beef\.com?}, :resource => IN::A, :response => [response] ) do |transaction| - transaction.respond!(response) + transaction.respond!(response) end }.to_not raise_error expect(id).to_not be_nil @@ -81,7 +81,7 @@ :pattern => %r{i\.(love|hate)\.beef\.com?}, :resource => IN::A, :response => [response] ) do |transaction| - transaction.respond!(response) + transaction.respond!(response) end }.to_not raise_error expect(id).to_not be_nil @@ -102,7 +102,7 @@ :pattern => pattern, :resource => IN::A, :response => [response] ) do |transaction| - transaction.respond!(response) + transaction.respond!(response) end }.to_not raise_error @@ -111,7 +111,7 @@ :pattern => pattern, :resource => IN::A, :response => [response] ) do |transaction| - transaction.respond!(response) + transaction.respond!(response) end }.to_not raise_error @@ -120,7 +120,7 @@ :pattern => pattern, :resource => IN::A, :response => [response] ) do |transaction| - transaction.respond!(response) + transaction.respond!(response) end }.to_not raise_error @@ -159,7 +159,7 @@ :pattern => pattern, :resource => IN::A, :response => [response] ) do |transaction| - transaction.respond!(response) + transaction.respond!(response) end }.to_not raise_error @@ -194,7 +194,7 @@ :pattern => pattern, :resource => IN::A, :response => [response] ) do |transaction| - transaction.respond!(response) + transaction.respond!(response) end }.to_not raise_error diff --git a/spec/beef/extensions/websocket_spec.rb b/spec/beef/extensions/websocket_spec.rb index 8f3d71b1ee..6a41db81e5 100644 --- a/spec/beef/extensions/websocket_spec.rb +++ b/spec/beef/extensions/websocket_spec.rb @@ -23,7 +23,7 @@ end it 'confirms that a websocket server has been started' do - expect(@ws).to be_a_kind_of(BeEF::Core::Websocket::Websocket) + expect(@ws).to be_a_kind_of(BeEF::Core::Websocket::Websocket) end it 'confirms that a secure websocket server has been started' do diff --git a/spec/features/all_modules_spec.rb b/spec/features/all_modules_spec.rb index 8a522dd9a9..1a9f109072 100644 --- a/spec/features/all_modules_spec.rb +++ b/spec/features/all_modules_spec.rb @@ -9,55 +9,55 @@ require 'spec/support/ui_support.rb' RSpec.describe 'Load All Modules Integration', run_on_long_tests: true do - before(:each) do - @pid, @beef_session, @hooked_browser = start_beef_and_hook_browser - end + before(:each) do + @pid, @beef_session, @hooked_browser = start_beef_and_hook_browser + end after(:each) do - stop_beef_and_unhook_browser(@pid, @beef_session, @hooked_browser) + stop_beef_and_unhook_browser(@pid, @beef_session, @hooked_browser) end it 'Load all modules' do - Dir.glob('modules/**/config.yaml').each do |file| - module_yaml_data = YAML.load_file(file) - - module_yaml_data['beef']['module'].each do |module_key, module_value| - next if rand(50) != 0 # for testing purposes only - - next if not module_value['enable'] # skip disabled modules - - module_name = module_value['name'] - module_category = module_value['category'] # can be an array or a string - module_description_sub = module_value['description'][0, 15] # descriptions including html cause errors - - expect(module_category).not_to be_nil - expect(module_name).not_to be_nil - - expect(@beef_session).to have_content(module_category, wait: PAGE_LOAD_TIMEOUT) if module_category.is_a?(String) - - expect(module_name).to be_a(String) - expect(module_description_sub).not_to be_nil - expect(module_description_sub).to be_a(String) - - # print the category and module name - if module_category.is_a?(Array) - category_tree_text = module_category.join(' > ') - else - category_tree_text = module_category - end - print_info "Category: #{category_tree_text}, Module: #{module_name}" - - # click on the module then expect the description and execute button to be visible - click_on_module(@beef_session, module_category, module_name) - - # expect the module description and the execute button to be visible - expect(@beef_session).to have_content(module_description_sub, wait: PAGE_LOAD_TIMEOUT) - expect(@beef_session).to have_content('Execute', wait: PAGE_LOAD_TIMEOUT) + Dir.glob('modules/**/config.yaml').each do |file| + module_yaml_data = YAML.load_file(file) + + module_yaml_data['beef']['module'].each do |module_key, module_value| + next if rand(50) != 0 # for testing purposes only + + next if not module_value['enable'] # skip disabled modules + + module_name = module_value['name'] + module_category = module_value['category'] # can be an array or a string + module_description_sub = module_value['description'][0, 15] # descriptions including html cause errors + + expect(module_category).not_to be_nil + expect(module_name).not_to be_nil + + expect(@beef_session).to have_content(module_category, wait: PAGE_LOAD_TIMEOUT) if module_category.is_a?(String) + + expect(module_name).to be_a(String) + expect(module_description_sub).not_to be_nil + expect(module_description_sub).to be_a(String) + + # print the category and module name + if module_category.is_a?(Array) + category_tree_text = module_category.join(' > ') + else + category_tree_text = module_category + end + print_info "Category: #{category_tree_text}, Module: #{module_name}" + + # click on the module then expect the description and execute button to be visible + click_on_module(@beef_session, module_category, module_name) + + # expect the module description and the execute button to be visible + expect(@beef_session).to have_content(module_description_sub, wait: PAGE_LOAD_TIMEOUT) + expect(@beef_session).to have_content('Execute', wait: PAGE_LOAD_TIMEOUT) - # tidy up and collapse the category tree - collapse_category_tree(@beef_session, module_category) - end - end + # tidy up and collapse the category tree + collapse_category_tree(@beef_session, module_category) + end + end end end \ No newline at end of file diff --git a/spec/features/debug_modules_spec.rb b/spec/features/debug_modules_spec.rb index c171223c16..cc313bec39 100644 --- a/spec/features/debug_modules_spec.rb +++ b/spec/features/debug_modules_spec.rb @@ -9,66 +9,66 @@ require 'spec/support/ui_support.rb' RSpec.describe 'Debug Modules Integration', run_on_long_tests: true do - before(:each) do - @pid, @beef_session, @hooked_browser = start_beef_and_hook_browser - end + before(:each) do + @pid, @beef_session, @hooked_browser = start_beef_and_hook_browser + end after(:each) do - stop_beef_and_unhook_browser(@pid, @beef_session, @hooked_browser) + stop_beef_and_unhook_browser(@pid, @beef_session, @hooked_browser) end it 'Test beef.debug module' do - click_on_module(@beef_session, 'Debug', 'Test beef.debug') + click_on_module(@beef_session, 'Debug', 'Test beef.debug') expect(@beef_session).to have_content('Execute', wait: PAGE_LOAD_TIMEOUT) expect(@beef_session).to have_content('244', wait: PAGE_LOAD_TIMEOUT) # Module ID expect(@beef_session).to have_content('Debug Message:', wait: PAGE_LOAD_TIMEOUT) end it 'Load all debug modules' do - Dir.glob('modules/debug/**/config.yaml').each do |file| - module_yaml_data = YAML.load_file(file) - - module_yaml_data['beef']['module'].each do |module_key, module_value| - module_category = module_value['category'] - module_name = module_value['name'] - # some descriptions are too long and include html tags - module_description_sub = module_value['description'][0, 20] - - expect(@beef_session).to have_content(module_category, wait: PAGE_LOAD_TIMEOUT) - expect(module_category).not_to be_nil - expect(module_category).to be_a(String) - expect(module_name).not_to be_nil - expect(module_name).to be_a(String) - expect(module_description_sub).not_to be_nil - expect(module_description_sub).to be_a(String) - - click_on_module(@beef_session, 'Debug', module_name) - - expect(@beef_session).to have_content(module_description_sub, wait: PAGE_LOAD_TIMEOUT) - expect(@beef_session).to have_content('Execute', wait: PAGE_LOAD_TIMEOUT) - - # execute the module - @beef_session.click_on('Execute') - - # expect the module to make command output visible - expect(@beef_session).to have_content('command 1', wait: PAGE_LOAD_TIMEOUT) - - # click on the command section to display the output - @beef_session.all('div.x-grid3-cell-inner').each do |div| - if div.text == 'command 1' - div.click - break - end - end - - if module_name == 'Return Image' # this module returns an image not a string - image_selector = "img[src^='data:image/png;base64,iVBORw0KGgo']" - expect(@beef_session).to have_css(image_selector, wait: PAGE_LOAD_TIMEOUT) - else - expect(@beef_session).to have_content('data: ', wait: PAGE_LOAD_TIMEOUT) + Dir.glob('modules/debug/**/config.yaml').each do |file| + module_yaml_data = YAML.load_file(file) + + module_yaml_data['beef']['module'].each do |module_key, module_value| + module_category = module_value['category'] + module_name = module_value['name'] + # some descriptions are too long and include html tags + module_description_sub = module_value['description'][0, 20] + + expect(@beef_session).to have_content(module_category, wait: PAGE_LOAD_TIMEOUT) + expect(module_category).not_to be_nil + expect(module_category).to be_a(String) + expect(module_name).not_to be_nil + expect(module_name).to be_a(String) + expect(module_description_sub).not_to be_nil + expect(module_description_sub).to be_a(String) + + click_on_module(@beef_session, 'Debug', module_name) + + expect(@beef_session).to have_content(module_description_sub, wait: PAGE_LOAD_TIMEOUT) + expect(@beef_session).to have_content('Execute', wait: PAGE_LOAD_TIMEOUT) + + # execute the module + @beef_session.click_on('Execute') + + # expect the module to make command output visible + expect(@beef_session).to have_content('command 1', wait: PAGE_LOAD_TIMEOUT) + + # click on the command section to display the output + @beef_session.all('div.x-grid3-cell-inner').each do |div| + if div.text == 'command 1' + div.click + break end - end - end + end + + if module_name == 'Return Image' # this module returns an image not a string + image_selector = "img[src^='data:image/png;base64,iVBORw0KGgo']" + expect(@beef_session).to have_css(image_selector, wait: PAGE_LOAD_TIMEOUT) + else + expect(@beef_session).to have_content('data: ', wait: PAGE_LOAD_TIMEOUT) + end + end + end end end \ No newline at end of file diff --git a/spec/requests/beef_test_spec.rb b/spec/requests/beef_test_spec.rb index 9ab0bdaf32..ac30d2caa0 100644 --- a/spec/requests/beef_test_spec.rb +++ b/spec/requests/beef_test_spec.rb @@ -9,32 +9,32 @@ RSpec.describe BeefTest, run_on_long_tests: true do - before(:each) do - @pid = start_beef_server_and_wait - end + before(:each) do + @pid = start_beef_server_and_wait + end after(:each) do - stop_beef_server(@pid) + stop_beef_server(@pid) end describe '.login' do - it 'logs in successfully' do - expect(port_available?) # Check if the tcp port is open - session = BeefTest.login() - expect(session).not_to be_nil - expect(session.has_content?('Hooked Browsers', wait: 10)) - end + it 'logs in successfully' do + expect(port_available?) # Check if the tcp port is open + session = BeefTest.login() + expect(session).not_to be_nil + expect(session.has_content?('Hooked Browsers', wait: 10)) + end end describe '.logout' do - before(:each) do - expect(port_available?) # # Check if the tcp port is open - @session = BeefTest.login() # Ensure login before each '.logout' test - expect(@session.has_content?('Hooked Browsers', wait: 10)) - end + before(:each) do + expect(port_available?) # # Check if the tcp port is open + @session = BeefTest.login() # Ensure login before each '.logout' test + expect(@session.has_content?('Hooked Browsers', wait: 10)) + end it 'logs out successfully' do - expect(port_available?) # # Check if the tcp port is open + expect(port_available?) # # Check if the tcp port is open expect(@session.has_content?('Hooked Browsers', wait: 10)) # Log out of the session @@ -46,66 +46,66 @@ end describe '.save_screenshot' do - it 'saves a screenshot' do - session = Capybara::Session.new(:selenium_headless) if session.nil? - - # Ensure the new directory does not exist - outputDir = '/tmp' - directory = "#{outputDir}/#{SecureRandom.hex}/" - expect(File.directory?(directory)).to be false - - # Save the screenshot - BeefTest.save_screenshot(session, directory) - - # Ensure the screenshot was saved - expect(File.directory?(directory)).to be true - screenshot_files = Dir.glob("#{directory}/*.png") - expect(screenshot_files.empty?).to be false - - # Ensure the screenshot file is not empty and clean up - screenshot_files.each do |file| - expect(File.size(file)).to be > 0 - File.delete(file) - end - expect(Dir.glob("#{directory}/*.png").empty?).to be true - - # Remove the directory - Dir.delete(directory) - expect(File.directory?(directory)).to be false - end + it 'saves a screenshot' do + session = Capybara::Session.new(:selenium_headless) if session.nil? + + # Ensure the new directory does not exist + outputDir = '/tmp' + directory = "#{outputDir}/#{SecureRandom.hex}/" + expect(File.directory?(directory)).to be false + + # Save the screenshot + BeefTest.save_screenshot(session, directory) + + # Ensure the screenshot was saved + expect(File.directory?(directory)).to be true + screenshot_files = Dir.glob("#{directory}/*.png") + expect(screenshot_files.empty?).to be false + + # Ensure the screenshot file is not empty and clean up + screenshot_files.each do |file| + expect(File.size(file)).to be > 0 + File.delete(file) + end + expect(Dir.glob("#{directory}/*.png").empty?).to be true + + # Remove the directory + Dir.delete(directory) + expect(File.directory?(directory)).to be false + end end let(:session) { Capybara::Session.new(:selenium_headless) } let(:victim) { Capybara::Session.new(:selenium_headless) } describe '.new_attacker' do - it 'creates a new attacker session' do - # # Test setup - expect(session).not_to be_nil - - result = BeefTest.new_attacker(session) - - # Test assertions - expect(result).to eq(session) - expect(session.has_no_content?('Authentication', wait: 10)) - expect(session.has_content?('Hooked Browsers', wait: 10)) - session.reset_session! - end + it 'creates a new attacker session' do + # # Test setup + expect(session).not_to be_nil + + result = BeefTest.new_attacker(session) + + # Test assertions + expect(result).to eq(session) + expect(session.has_no_content?('Authentication', wait: 10)) + expect(session.has_content?('Hooked Browsers', wait: 10)) + session.reset_session! + end end describe '.new_victim' do - it 'creates a new victim session' do - # Test setup - allow(victim).to receive(:visit) - expect(victim).not_to be_nil - - # Test execution - result = BeefTest.new_victim(victim) - - # Test assertions - expect(victim).to have_received(:visit).with(VICTIM_URL) - expect(result).to eq(victim) - victim.reset_session! - end + it 'creates a new victim session' do + # Test setup + allow(victim).to receive(:visit) + expect(victim).not_to be_nil + + # Test execution + result = BeefTest.new_victim(victim) + + # Test assertions + expect(victim).to have_received(:visit).with(VICTIM_URL) + expect(result).to eq(victim) + victim.reset_session! + end end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 4b0ee09156..b738213ec2 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -175,10 +175,10 @@ def server_teardown(webdriver, server_pid, server_pids) def reset_beef_db begin - db_file = BeEF::Core::Configuration.instance.get('beef.database.file') - File.delete(db_file) if File.exist?(db_file) - rescue => e - print_error("Could not remove '#{db_file}' database file: #{e.message}") + db_file = BeEF::Core::Configuration.instance.get('beef.database.file') + File.delete(db_file) if File.exist?(db_file) +rescue => e + print_error("Could not remove '#{db_file}' database file: #{e.message}") end end @@ -206,7 +206,7 @@ def configure_beef # Load the server def load_beef_extensions_and_modules # Load BeEF extensions - BeEF::Extensions.load + BeEF::Extensions.load # Load BeEF modules only if they are not already loaded BeEF::Modules.load if @config.get('beef.module').nil? diff --git a/spec/support/ui_support.rb b/spec/support/ui_support.rb index 2d89bef09a..eb9fafe7c2 100644 --- a/spec/support/ui_support.rb +++ b/spec/support/ui_support.rb @@ -8,7 +8,7 @@ require 'spec/support/constants.rb' def start_beef_and_hook_browser() - reset_beef_db + reset_beef_db pid = start_beef_server_and_wait beef_session = BeefTest.login hooked_browser = BeefTest.new_victim @@ -30,13 +30,13 @@ def start_beef_and_hook_browser() end def stop_beef_and_unhook_browser(pid, beef_session, hooked_browser) - stop_beef_server(pid) + stop_beef_server(pid) beef_session.driver.browser.close hooked_browser.driver.browser.close end def navigate_to_hooked_browser(session, hooked_browser_text = nil) - expect(session).to have_content('Hooked Browsers', wait: PAGE_LOAD_TIMEOUT) + expect(session).to have_content('Hooked Browsers', wait: PAGE_LOAD_TIMEOUT) hooked_browser_text = '127.0.0.1' if hooked_browser_text.nil? expect(session).to have_content(hooked_browser_text, wait: BROWSER_HOOKING_TIMEOUT) @@ -47,7 +47,7 @@ def navigate_to_hooked_browser(session, hooked_browser_text = nil) end def navigate_to_category(session, category_name = nil) - expect(category_name).not_to be_nil + expect(category_name).not_to be_nil expect(category_name).to be_a(String) navigate_to_hooked_browser unless session.has_content?('Current Browser') @@ -60,53 +60,53 @@ def navigate_to_category(session, category_name = nil) end def expand_category_tree(session, category, module_name = nil) - if category.is_a?(Array) - category.each do |category_name| - # find the category element and scroll to it - session.all('div', text: category_name).each do |element| - begin - element_text = element.text - next unless element_text.start_with?(category_name) - - match_data = element_text.match(/\A([\w\s]+)\s\((\d+)\)\z/) - next unless match_data - - # scroll to the element - session.scroll_to(element) - rescue Selenium::WebDriver::Error::StaleElementReferenceError => e - - puts "StaleElementReferenceError: #{element_text}" - puts e.message - next - end - end - - expect(session).to have_content(category_name, wait: PAGE_LOAD_TIMEOUT) - navigate_to_category(session, category_name) unless session.has_content?(module_name) + if category.is_a?(Array) + category.each do |category_name| + # find the category element and scroll to it + session.all('div', text: category_name).each do |element| + begin + element_text = element.text + next unless element_text.start_with?(category_name) + + match_data = element_text.match(/\A([\w\s]+)\s\((\d+)\)\z/) + next unless match_data + + # scroll to the element + session.scroll_to(element) + rescue Selenium::WebDriver::Error::StaleElementReferenceError => e + + puts "StaleElementReferenceError: #{element_text}" + puts e.message + next end - else - navigate_to_category(session, category) unless session.has_content?(module_name) - expect(session).to have_content(category, wait: PAGE_LOAD_TIMEOUT) + end + + expect(session).to have_content(category_name, wait: PAGE_LOAD_TIMEOUT) + navigate_to_category(session, category_name) unless session.has_content?(module_name) end + else + navigate_to_category(session, category) unless session.has_content?(module_name) + expect(session).to have_content(category, wait: PAGE_LOAD_TIMEOUT) + end expect(session).to have_content(module_name, wait: PAGE_LOAD_TIMEOUT) end def collapse_category_tree(session, category) - if category.is_a?(Array) - category.reverse.each do |category_name| - # Collapse the sub-folder - session.scroll_to(category_name) - session.first(:link_or_button, category_name + ' ').click - end - else - session.scroll_to(category) - session.first(:link_or_button, category + ' ').click - end + if category.is_a?(Array) + category.reverse.each do |category_name| + # Collapse the sub-folder + session.scroll_to(category_name) + session.first(:link_or_button, category_name + ' ').click + end + else + session.scroll_to(category) + session.first(:link_or_button, category + ' ').click + end end def click_on_module(session, category, module_name) # expand the category tree to make the module visible - expand_category_tree(session, category, module_name) + expand_category_tree(session, category, module_name) # click on the module in the expanded tree session.scroll_to(module_name) diff --git a/test/integration/tc_debug_modules.rb b/test/integration/tc_debug_modules.rb index bc7ec5c821..e9d53464ec 100644 --- a/test/integration/tc_debug_modules.rb +++ b/test/integration/tc_debug_modules.rb @@ -57,14 +57,14 @@ def test_3_restful_modules assert_not_nil response.body result = JSON.parse(response.body) result.each do |mod| - case mod[1]['class'] - when 'Test_return_long_string' - @@mod_debug_long_string = mod[1]['id'] - when 'Test_return_ascii_chars' - @@mod_debug_ascii_chars = mod[1]['id'] - when 'Test_network_request' - @@mod_debug_test_network = mod[1]['id'] - end + case mod[1]['class'] + when 'Test_return_long_string' + @@mod_debug_long_string = mod[1]['id'] + when 'Test_return_ascii_chars' + @@mod_debug_ascii_chars = mod[1]['id'] + when 'Test_network_request' + @@mod_debug_test_network = mod[1]['id'] + end end assert_not_nil @@mod_debug_long_string assert_not_nil @@mod_debug_ascii_chars @@ -126,7 +126,7 @@ def test_return_ascii_chars #TODO if the response is empty, the body size is 2, basically an empty Hash. # don't know why empty?, nil and other checks are not working. while(response.body.size <= 2 && count < 10) - response = RestClient.get "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_debug_ascii_chars}/#{cmd_id}?token=#{@@token}" + response = RestClient.get "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_debug_ascii_chars}/#{cmd_id}?token=#{@@token}" sleep 2 count += 1 end diff --git a/test/integration/tc_social_engineering_rest.rb b/test/integration/tc_social_engineering_rest.rb index cf6d670586..132b07c78c 100644 --- a/test/integration/tc_social_engineering_rest.rb +++ b/test/integration/tc_social_engineering_rest.rb @@ -69,11 +69,11 @@ def test_1_dns_spoof # Iterate local IPs (excluding loopbacks) to find a match to the 'dig' # output assert_block do - Socket.ip_address_list.each { |i| - if !(i.ipv4_loopback? || i.ipv6_loopback?) - return true if i.ip_address.to_s.eql?(dig_output.to_s) - end - } + Socket.ip_address_list.each { |i| + if !(i.ipv4_loopback? || i.ipv6_loopback?) + return true if i.ip_address.to_s.eql?(dig_output.to_s) + end + } end # assert(foundmatch) diff --git a/test/integration/tc_webrtc_rest.rb b/test/integration/tc_webrtc_rest.rb index ff80c67f85..e6dbd974f3 100644 --- a/test/integration/tc_webrtc_rest.rb +++ b/test/integration/tc_webrtc_rest.rb @@ -50,10 +50,10 @@ def startup browsers = result['hooked-browsers']['online'] browsers.each_with_index do |elem, index| if index == browsers.length - 1 - @@victim2id = browsers["#{index}"]['id'].to_s + @@victim2id = browsers["#{index}"]['id'].to_s end if index == browsers.length - 2 - @@victim1id = browsers["#{index}"]['id'].to_s + @@victim1id = browsers["#{index}"]['id'].to_s end end diff --git a/tools/rest_api_examples/lib/beef_rest_api.rb b/tools/rest_api_examples/lib/beef_rest_api.rb index 5c5b9ea6c6..3f00767130 100644 --- a/tools/rest_api_examples/lib/beef_rest_api.rb +++ b/tools/rest_api_examples/lib/beef_rest_api.rb @@ -1,580 +1,580 @@ class BeefRestAPI # initialize -def initialize proto = 'https', host = '127.0.0.1', port = '3000', user = 'beef', pass = 'beef' - @user = user - @pass = pass - @url = "#{proto}://#{host}:#{port}/api/" - @token = nil -end + def initialize proto = 'https', host = '127.0.0.1', port = '3000', user = 'beef', pass = 'beef' + @user = user + @pass = pass + @url = "#{proto}://#{host}:#{port}/api/" + @token = nil + end ################################################################################ ### BeEF core API ################################################################################ # authenticate and get API token -def auth - print_verbose 'Retrieving authentication token' - begin - response = RestClient.post "#{@url}admin/login", - { 'username' => "#{@user}", - 'password' => "#{@pass}" }.to_json, - :content_type => :json, - :accept => :json - result = JSON.parse(response.body) - @token = result['token'] - print_good "Retrieved RESTful API token: #{@token}" - rescue => e - print_error "Could not retrieve RESTful API token: #{e.message}" + def auth + print_verbose 'Retrieving authentication token' + begin + response = RestClient.post "#{@url}admin/login", + { 'username' => "#{@user}", + 'password' => "#{@pass}" }.to_json, + :content_type => :json, + :accept => :json + result = JSON.parse(response.body) + @token = result['token'] + print_good "Retrieved RESTful API token: #{@token}" + rescue => e + print_error "Could not retrieve RESTful API token: #{e.message}" + end end -end # get BeEF version -def version - begin - response = RestClient.get "#{@url}server/version", { :params => { :token => @token } } - result = JSON.parse(response.body) - print_good "Retrieved BeEF version: #{result['version']}" - result['version'] - rescue => e - print_error "Could not retrieve BeEF version: #{e.message}" + def version + begin + response = RestClient.get "#{@url}server/version", { :params => { :token => @token } } + result = JSON.parse(response.body) + print_good "Retrieved BeEF version: #{result['version']}" + result['version'] + rescue => e + print_error "Could not retrieve BeEF version: #{e.message}" + end end -end # get server mounts -def mounts - begin - response = RestClient.get "#{@url}server/mounts", { :params => { :token => @token } } - result = JSON.parse(response.body) - print_good "Retrieved BeEF server mounts: #{result['mounts']}" - result['mounts'] - rescue => e - print_error "Could not retrieve BeEF version: #{e.message}" + def mounts + begin + response = RestClient.get "#{@url}server/mounts", { :params => { :token => @token } } + result = JSON.parse(response.body) + print_good "Retrieved BeEF server mounts: #{result['mounts']}" + result['mounts'] + rescue => e + print_error "Could not retrieve BeEF version: #{e.message}" + end end -end # get online hooked browsers -def online_browsers - begin - print_verbose 'Retrieving online browsers' - response = RestClient.get "#{@url}hooks", { :params => { :token => @token } } - result = JSON.parse(response.body) - browsers = result['hooked-browsers']['online'] - print_good "Retrieved online browser list [#{browsers.size} online]" - browsers - rescue => e - print_error "Could not retrieve browser details: #{e.message}" + def online_browsers + begin + print_verbose 'Retrieving online browsers' + response = RestClient.get "#{@url}hooks", { :params => { :token => @token } } + result = JSON.parse(response.body) + browsers = result['hooked-browsers']['online'] + print_good "Retrieved online browser list [#{browsers.size} online]" + browsers + rescue => e + print_error "Could not retrieve browser details: #{e.message}" + end end -end # get offline hooked browsers -def offline_browsers - begin - print_verbose 'Retrieving offline browsers' - response = RestClient.get "#{@url}hooks", { :params => { :token => @token } } - result = JSON.parse(response.body) - browsers = result['hooked-browsers']['offline'] - print_good "Retrieved offline browser list [#{browsers.size} offline]" - browsers - rescue => e - print_error "Could not retrieve browser details: #{e.message}" + def offline_browsers + begin + print_verbose 'Retrieving offline browsers' + response = RestClient.get "#{@url}hooks", { :params => { :token => @token } } + result = JSON.parse(response.body) + browsers = result['hooked-browsers']['offline'] + print_good "Retrieved offline browser list [#{browsers.size} offline]" + browsers + rescue => e + print_error "Could not retrieve browser details: #{e.message}" + end end -end # get hooked browser details by session -def browser_details session - begin - print_verbose "Retrieving browser details for hooked browser [session: #{session}]" - response = RestClient.get "#{@url}browserdetails/#{session}", { :params => { :token => @token } } - result = JSON.parse(response.body) - details = result['details'] - print_good "Retrieved #{details.size} browser details" - details - rescue => e - print_error "Could not retrieve browser details: #{e.message}" + def browser_details session + begin + print_verbose "Retrieving browser details for hooked browser [session: #{session}]" + response = RestClient.get "#{@url}browserdetails/#{session}", { :params => { :token => @token } } + result = JSON.parse(response.body) + details = result['details'] + print_good "Retrieved #{details.size} browser details" + details + rescue => e + print_error "Could not retrieve browser details: #{e.message}" + end end -end # delete a browser by session -def delete_browser session - begin - print_verbose "Removing hooked browser [session: #{session}]" - response = RestClient.get "#{@url}hooks/#{session}/delete", { :params => { :token => @token } } - print_good "Removed browser [session: #{session}]" if response.code == 200 - response - rescue => e - print_error "Could not delete hooked browser: #{e.message}" + def delete_browser session + begin + print_verbose "Removing hooked browser [session: #{session}]" + response = RestClient.get "#{@url}hooks/#{session}/delete", { :params => { :token => @token } } + print_good "Removed browser [session: #{session}]" if response.code == 200 + response + rescue => e + print_error "Could not delete hooked browser: #{e.message}" + end end -end # get BeEF logs -def logs - begin - print_verbose 'Retrieving logs' - response = RestClient.get "#{@url}logs", { :params => { :token => @token } } - logs = JSON.parse(response.body) - print_good "Retrieved #{logs['logs_count']} log entries" - logs - rescue => e - print_error "Could not retrieve logs: #{e.message}" + def logs + begin + print_verbose 'Retrieving logs' + response = RestClient.get "#{@url}logs", { :params => { :token => @token } } + logs = JSON.parse(response.body) + print_good "Retrieved #{logs['logs_count']} log entries" + logs + rescue => e + print_error "Could not retrieve logs: #{e.message}" + end end -end # get hooked browser logs by session -def browser_logs session - begin - print_verbose "Retrieving browser logs [session: #{session}]" - response = RestClient.get "#{@url}logs/#{session}", { :params => { :token => @token } } - logs = JSON.parse(response.body) - print_good "Retrieved #{logs['logs'].size} browser logs" - logs - rescue => e - print_error "Could not retrieve browser logs: #{e.message}" + def browser_logs session + begin + print_verbose "Retrieving browser logs [session: #{session}]" + response = RestClient.get "#{@url}logs/#{session}", { :params => { :token => @token } } + logs = JSON.parse(response.body) + print_good "Retrieved #{logs['logs'].size} browser logs" + logs + rescue => e + print_error "Could not retrieve browser logs: #{e.message}" + end end -end ################################################################################ ### command module API ################################################################################ # get command module categories -def categories - begin - print_verbose 'Retrieving module categories' - response = RestClient.get "#{@url}categories", { :params => { :token => @token } } - categories = JSON.parse(response.body) - print_good "Retrieved #{categories.size} module categories" - categories - rescue => e - print_error "Could not retrieve logs: #{e.message}" + def categories + begin + print_verbose 'Retrieving module categories' + response = RestClient.get "#{@url}categories", { :params => { :token => @token } } + categories = JSON.parse(response.body) + print_good "Retrieved #{categories.size} module categories" + categories + rescue => e + print_error "Could not retrieve logs: #{e.message}" + end end -end # get command modules -def modules - begin - print_verbose 'Retrieving modules' - response = RestClient.get "#{@url}modules", { :params => { :token => @token } } - @modules = JSON.parse(response.body) - print_good "Retrieved #{@modules.size} available command modules" - @modules - rescue => e - print_error "Could not retrieve modules: #{e.message}" + def modules + begin + print_verbose 'Retrieving modules' + response = RestClient.get "#{@url}modules", { :params => { :token => @token } } + @modules = JSON.parse(response.body) + print_good "Retrieved #{@modules.size} available command modules" + @modules + rescue => e + print_error "Could not retrieve modules: #{e.message}" + end end -end # get module id by module short name -def get_module_id mod_name - print_verbose "Retrieving id for module [name: #{mod_name}]" - @modules.each do |mod| - # normal modules - if mod_name.capitalize == mod[1]['class'] - return mod[1]['id'] - break - # metasploit modules - elsif mod[1]['class'] == 'Msf_module' && mod_name.capitalize == mod[1]['name'] - return mod[1]['id'] - break + def get_module_id mod_name + print_verbose "Retrieving id for module [name: #{mod_name}]" + @modules.each do |mod| + # normal modules + if mod_name.capitalize == mod[1]['class'] + return mod[1]['id'] + break + # metasploit modules + elsif mod[1]['class'] == 'Msf_module' && mod_name.capitalize == mod[1]['name'] + return mod[1]['id'] + break + end end + nil end - nil -end # get command module details -def module_details id - begin - print_verbose "Retrieving details for command module [id: #{id}]" - response = RestClient.get "#{@url}modules/#{id}", { :params => { :token => @token } } - details = JSON.parse(response.body) - print_good "Retrieved details for module [#{details['name']}]" - details - rescue => e - print_error "Could not retrieve modules: #{e.message}" + def module_details id + begin + print_verbose "Retrieving details for command module [id: #{id}]" + response = RestClient.get "#{@url}modules/#{id}", { :params => { :token => @token } } + details = JSON.parse(response.body) + print_good "Retrieved details for module [#{details['name']}]" + details + rescue => e + print_error "Could not retrieve modules: #{e.message}" + end end -end # execute module -def execute_module session, mod_id, options - print_verbose "Executing module [id: #{mod_id}, #{options}]" - begin - response = RestClient.post "#{@url}modules/#{session}/#{mod_id}?token=#{@token}", options.to_json, - :content_type => :json, - :accept => :json - result = JSON.parse(response.body) - if result['success'] == 'true' - print_good "Executed module [id: #{mod_id}]" - else - print_error "Could not execute module [id: #{mod_id}]" + def execute_module session, mod_id, options + print_verbose "Executing module [id: #{mod_id}, #{options}]" + begin + response = RestClient.post "#{@url}modules/#{session}/#{mod_id}?token=#{@token}", options.to_json, + :content_type => :json, + :accept => :json + result = JSON.parse(response.body) + if result['success'] == 'true' + print_good "Executed module [id: #{mod_id}]" + else + print_error "Could not execute module [id: #{mod_id}]" + end + result + rescue => e + print_error "Could not start payload handler: #{e.message}" end - result - rescue => e - print_error "Could not start payload handler: #{e.message}" end -end ################################################################################ ### Metasploit API ################################################################################ # get metasploit version -def msf_version - begin - response = RestClient.get "#{@url}msf/version", { :params => { :token => @token } } - result = JSON.parse(response.body) - version = result['version']['version'] - print_good "Retrieved Metasploit version: #{version}" - version - rescue => e - print_error "Could not retrieve Metasploit version: #{e.message}" + def msf_version + begin + response = RestClient.get "#{@url}msf/version", { :params => { :token => @token } } + result = JSON.parse(response.body) + version = result['version']['version'] + print_good "Retrieved Metasploit version: #{version}" + version + rescue => e + print_error "Could not retrieve Metasploit version: #{e.message}" + end end -end # get metasploit jobs -def msf_jobs - begin - response = RestClient.get "#{@url}msf/jobs", { :params => { :token => @token } } - result = JSON.parse(response.body) - jobs = result['jobs'] - print_good "Retrieved job list [#{jobs.size} jobs]" - jobs - rescue => e - print_error "Could not retrieve Metasploit job list: #{e.message}" + def msf_jobs + begin + response = RestClient.get "#{@url}msf/jobs", { :params => { :token => @token } } + result = JSON.parse(response.body) + jobs = result['jobs'] + print_good "Retrieved job list [#{jobs.size} jobs]" + jobs + rescue => e + print_error "Could not retrieve Metasploit job list: #{e.message}" + end end -end # get metasploit job info -def msf_job_info id - begin - response = RestClient.get "#{@url}msf/job/#{id}/info", { :params => { :token => @token } } - details = JSON.parse(response.body) - print_good "Retrieved job information [id: #{id}]" - details - rescue => e - print_error "Could not retrieve job info: #{e.message}" + def msf_job_info id + begin + response = RestClient.get "#{@url}msf/job/#{id}/info", { :params => { :token => @token } } + details = JSON.parse(response.body) + print_good "Retrieved job information [id: #{id}]" + details + rescue => e + print_error "Could not retrieve job info: #{e.message}" + end end -end # start metasploit payload handler -def msf_handler options - print_verbose "Starting Metasploit payload handler [#{options}]" - begin - response = RestClient.post "#{@url}msf/handler?token=#{@token}", options.to_json, - :content_type => :json, - :accept => :json - result = JSON.parse(response.body) - job_id = result['id'] - if job_id.nil? - print_error 'Could not start payload handler: Job id is nil' - else - print_good "Started payload handler [id: #{job_id}]" + def msf_handler options + print_verbose "Starting Metasploit payload handler [#{options}]" + begin + response = RestClient.post "#{@url}msf/handler?token=#{@token}", options.to_json, + :content_type => :json, + :accept => :json + result = JSON.parse(response.body) + job_id = result['id'] + if job_id.nil? + print_error 'Could not start payload handler: Job id is nil' + else + print_good "Started payload handler [id: #{job_id}]" + end + job_id + rescue => e + print_error "Could not start payload handler: #{e.message}" end - job_id - rescue => e - print_error "Could not start payload handler: #{e.message}" end -end # stop metasploit job -def msf_job_stop id - print_verbose "Stopping Metasploit job [id: #{id}]" - begin - response = RestClient.get "#{@url}msf/job/#{id}/stop", { :params => { :token => @token } } - result = JSON.parse(response.body) - if result['success'].nil? - print_error "Could not stop Metasploit job [id: #{id}]: No such job ?" - else - print_good "Stopped job [id: #{id}]" + def msf_job_stop id + print_verbose "Stopping Metasploit job [id: #{id}]" + begin + response = RestClient.get "#{@url}msf/job/#{id}/stop", { :params => { :token => @token } } + result = JSON.parse(response.body) + if result['success'].nil? + print_error "Could not stop Metasploit job [id: #{id}]: No such job ?" + else + print_good "Stopped job [id: #{id}]" + end + result + rescue => e + print_error "Could not stop Metasploit job [id: #{id}]: #{e.message}" end - result - rescue => e - print_error "Could not stop Metasploit job [id: #{id}]: #{e.message}" end -end ################################################################################ ### Network API ################################################################################ # get all network hosts -def network_hosts_all - begin - print_verbose 'Retrieving all network hosts' - response = RestClient.get "#{@url}network/hosts", { :params => { :token => @token } } - details = JSON.parse(response.body) - print_good "Retrieved #{details['count']} network hosts" - details - rescue => e - print_error "Could not retrieve network hosts: #{e.message}" + def network_hosts_all + begin + print_verbose 'Retrieving all network hosts' + response = RestClient.get "#{@url}network/hosts", { :params => { :token => @token } } + details = JSON.parse(response.body) + print_good "Retrieved #{details['count']} network hosts" + details + rescue => e + print_error "Could not retrieve network hosts: #{e.message}" + end end -end # get all network services -def network_services_all - begin - print_verbose 'Retrieving all network services' - response = RestClient.get "#{@url}network/services", { :params => { :token => @token } } - details = JSON.parse(response.body) - print_good "Retrieved #{details['count']} network services" - details - rescue => e - print_error "Could not retrieve network services: #{e.message}" + def network_services_all + begin + print_verbose 'Retrieving all network services' + response = RestClient.get "#{@url}network/services", { :params => { :token => @token } } + details = JSON.parse(response.body) + print_good "Retrieved #{details['count']} network services" + details + rescue => e + print_error "Could not retrieve network services: #{e.message}" + end end -end # get network hosts by session -def network_hosts session - begin - print_verbose "Retrieving network hosts for hooked browser [session: #{session}]" - response = RestClient.get "#{@url}network/hosts/#{session}", { :params => { :token => @token } } - details = JSON.parse(response.body) - print_good "Retrieved #{details['count']} network hosts" - details - rescue => e - print_error "Could not retrieve network hosts: #{e.message}" + def network_hosts session + begin + print_verbose "Retrieving network hosts for hooked browser [session: #{session}]" + response = RestClient.get "#{@url}network/hosts/#{session}", { :params => { :token => @token } } + details = JSON.parse(response.body) + print_good "Retrieved #{details['count']} network hosts" + details + rescue => e + print_error "Could not retrieve network hosts: #{e.message}" + end end -end # get network services by session -def network_services session - begin - print_verbose "Retrieving network services for hooked browser [session: #{session}]" - response = RestClient.get "#{@url}network/services/#{session}", { :params => { :token => @token } } - details = JSON.parse(response.body) - print_good "Retrieved #{details['count']} network services" - details - rescue => e - print_error "Could not retrieve network services: #{e.message}" + def network_services session + begin + print_verbose "Retrieving network services for hooked browser [session: #{session}]" + response = RestClient.get "#{@url}network/services/#{session}", { :params => { :token => @token } } + details = JSON.parse(response.body) + print_good "Retrieved #{details['count']} network services" + details + rescue => e + print_error "Could not retrieve network services: #{e.message}" + end end -end ################################################################################ ### XssRays API ################################################################################ # get all rays -def xssrays_rays_all - print_verbose 'Retrieving all rays' - response = RestClient.get "#{@url}xssrays/rays", { :params => { :token => @token } } - details = JSON.parse(response.body) - print_good "Retrieved #{details['count']} rays" - details -rescue => e - print_error "Could not retrieve rays: #{e.message}" -end + def xssrays_rays_all + print_verbose 'Retrieving all rays' + response = RestClient.get "#{@url}xssrays/rays", { :params => { :token => @token } } + details = JSON.parse(response.body) + print_good "Retrieved #{details['count']} rays" + details + rescue => e + print_error "Could not retrieve rays: #{e.message}" + end # get rays by session -def xssrays_rays session - print_verbose "Retrieving rays for hooked browser [session: #{session}]" - response = RestClient.get "#{@url}xssrays/rays/#{session}", { :params => { :token => @token } } - details = JSON.parse(response.body) - print_good "Retrieved #{details['count']} rays" - details -rescue => e - print_error "Could not retrieve rays: #{e.message}" -end + def xssrays_rays session + print_verbose "Retrieving rays for hooked browser [session: #{session}]" + response = RestClient.get "#{@url}xssrays/rays/#{session}", { :params => { :token => @token } } + details = JSON.parse(response.body) + print_good "Retrieved #{details['count']} rays" + details + rescue => e + print_error "Could not retrieve rays: #{e.message}" + end # get all scans -def xssrays_scans_all - print_verbose 'Retrieving all scans' - response = RestClient.get "#{@url}xssrays/scans", { :params => { :token => @token } } - details = JSON.parse(response.body) - print_good "Retrieved #{details['count']} scans" - details -rescue => e - print_error "Could not retrieve scans: #{e.message}" -end + def xssrays_scans_all + print_verbose 'Retrieving all scans' + response = RestClient.get "#{@url}xssrays/scans", { :params => { :token => @token } } + details = JSON.parse(response.body) + print_good "Retrieved #{details['count']} scans" + details + rescue => e + print_error "Could not retrieve scans: #{e.message}" + end # get scans by session -def xssrays_scans session - print_verbose "Retrieving scans for hooked browser [session: #{session}]" - response = RestClient.get "#{@url}xssrays/scans/#{session}", { :params => { :token => @token } } - details = JSON.parse(response.body) - print_good "Retrieved #{details['count']} scans" - details -rescue => e - print_error "Could not retrieve scans: #{e.message}" -end + def xssrays_scans session + print_verbose "Retrieving scans for hooked browser [session: #{session}]" + response = RestClient.get "#{@url}xssrays/scans/#{session}", { :params => { :token => @token } } + details = JSON.parse(response.body) + print_good "Retrieved #{details['count']} scans" + details + rescue => e + print_error "Could not retrieve scans: #{e.message}" + end ################################################################################ ### DNS API ################################################################################ # get ruleset -def dns_ruleset - begin - print_verbose 'Retrieving DNS ruleset' - response = RestClient.get "#{@url}dns/ruleset", { :params => { :token => @token } } + def dns_ruleset + begin + print_verbose 'Retrieving DNS ruleset' + response = RestClient.get "#{@url}dns/ruleset", { :params => { :token => @token } } + details = JSON.parse(response.body) + print_good "Retrieved #{details['count']} rules" + details + rescue => e + print_error "Could not retrieve DNS ruleset: #{e.message}" + end + end + +# add a rule + def dns_add_rule(dns_pattern, dns_resource, dns_response) + dns_response = [dns_response] if dns_response.is_a?(String) + print_verbose "Adding DNS rule [pattern: #{dns_pattern}, resource: #{dns_resource}, response: #{dns_response}]" + response = RestClient.post "#{@url}dns/rule?token=#{@token}", { + 'pattern' => dns_pattern, + 'resource' => dns_resource, + 'response' => dns_response }.to_json, + :content_type => :json, + :accept => :json details = JSON.parse(response.body) - print_good "Retrieved #{details['count']} rules" + rule_id = details['id'] + + if rule_id.nil? + print_error("Could not add DNS rule: #{details['error']}") + return details + end + + print_good "Added rule [id: #{details['id']}]" details rescue => e - print_error "Could not retrieve DNS ruleset: #{e.message}" + print_error "Could not add DNS rule: #{e.message}" end -end - -# add a rule -def dns_add_rule(dns_pattern, dns_resource, dns_response) - dns_response = [dns_response] if dns_response.is_a?(String) - print_verbose "Adding DNS rule [pattern: #{dns_pattern}, resource: #{dns_resource}, response: #{dns_response}]" - response = RestClient.post "#{@url}dns/rule?token=#{@token}", { - 'pattern' => dns_pattern, - 'resource' => dns_resource, - 'response' => dns_response }.to_json, - :content_type => :json, - :accept => :json - details = JSON.parse(response.body) - rule_id = details['id'] - - if rule_id.nil? - print_error("Could not add DNS rule: #{details['error']}") - return details - end - - print_good "Added rule [id: #{details['id']}]" - details -rescue => e - print_error "Could not add DNS rule: #{e.message}" -end # get rule details -def dns_get_rule(id) - begin - print_verbose "Retrieving DNS rule details [id: #{id}]" - response = RestClient.get "#{@url}dns/rule/#{id}", { :params => { :token => @token } } + def dns_get_rule(id) + begin + print_verbose "Retrieving DNS rule details [id: #{id}]" + response = RestClient.get "#{@url}dns/rule/#{id}", { :params => { :token => @token } } + details = JSON.parse(response.body) + print_good "Retrieved rule [id: #{details['id']}]" + details + rescue => e + print_error "Could not retrieve DNS rule: #{e.message}" + end + end + +# delete a rule + def dns_delete_rule(id) + response = RestClient.delete "#{@url}dns/rule/#{id}?token=#{@token}" details = JSON.parse(response.body) - print_good "Retrieved rule [id: #{details['id']}]" + print_good "Deleted rule [id: #{id}]" details rescue => e - print_error "Could not retrieve DNS rule: #{e.message}" + print_error "Could not delete DNS rule: #{e.message}" end -end - -# delete a rule -def dns_delete_rule(id) - response = RestClient.delete "#{@url}dns/rule/#{id}?token=#{@token}" - details = JSON.parse(response.body) - print_good "Deleted rule [id: #{id}]" - details -rescue => e - print_error "Could not delete DNS rule: #{e.message}" -end ################################################################################ ### Autorun ################################################################################ -def autorun_rules - print_verbose 'Retrieving Autorun rules' - response = RestClient.get "#{@url}autorun/rules", { :params => { :token => @token } } - details = JSON.parse(response.body) - print_good("Retrieved #{details['count']} rules") - details -rescue => e - print_error("Could not retrieve Autorun rules: #{e.message}") -end + def autorun_rules + print_verbose 'Retrieving Autorun rules' + response = RestClient.get "#{@url}autorun/rules", { :params => { :token => @token } } + details = JSON.parse(response.body) + print_good("Retrieved #{details['count']} rules") + details + rescue => e + print_error("Could not retrieve Autorun rules: #{e.message}") + end -def autorun_delete_rule(id) - print_verbose "Deleting Autorun rule with ID: #{id}" - response = RestClient.delete "#{@url}autorun/rule/#{id}?token=#{@token}" - details = JSON.parse(response.body) - print_good("Deleted rule [id: #{id}]") - details -rescue => e - print_error("Could not delete Autorun rule: #{e.message}") -end + def autorun_delete_rule(id) + print_verbose "Deleting Autorun rule with ID: #{id}" + response = RestClient.delete "#{@url}autorun/rule/#{id}?token=#{@token}" + details = JSON.parse(response.body) + print_good("Deleted rule [id: #{id}]") + details + rescue => e + print_error("Could not delete Autorun rule: #{e.message}") + end -def autorun_add_rule(data) - print_verbose "Adding Autorun rule: #{data}" - response = RestClient.post "#{@url}autorun/rule/add?token=#{@token}", - data.to_json, - :content_type => :json, - :accept => :json - details = JSON.parse(response.body) - rule_id = details['rule_id'] + def autorun_add_rule(data) + print_verbose "Adding Autorun rule: #{data}" + response = RestClient.post "#{@url}autorun/rule/add?token=#{@token}", + data.to_json, + :content_type => :json, + :accept => :json + details = JSON.parse(response.body) + rule_id = details['rule_id'] - if rule_id.nil? - print_error("Could not add Autorun rule: #{details['error']}") - return details - end + if rule_id.nil? + print_error("Could not add Autorun rule: #{details['error']}") + return details + end - print_good("Added rule [id: #{details['id']}]") - details -rescue => e - print_error("Could not add Autorun rule: #{e.message}") -end + print_good("Added rule [id: #{details['id']}]") + details + rescue => e + print_error("Could not add Autorun rule: #{e.message}") + end -def autorun_run_rule_on_all_browsers(rule_id) - print_verbose "Running Autorun rule #{rule_id} on all browsers" - response = RestClient.get "#{@url}autorun/run/#{rule_id}", { :params => { :token => @token } } - details = JSON.parse(response.body) - print_debug details - print_good('Done') - details -rescue => e - print_error "Could not run Autorun rule #{rule_id}: #{e.message}" -end + def autorun_run_rule_on_all_browsers(rule_id) + print_verbose "Running Autorun rule #{rule_id} on all browsers" + response = RestClient.get "#{@url}autorun/run/#{rule_id}", { :params => { :token => @token } } + details = JSON.parse(response.body) + print_debug details + print_good('Done') + details + rescue => e + print_error "Could not run Autorun rule #{rule_id}: #{e.message}" + end -def autorun_run_rule_on_browser(rule_id, hb_id) - print_verbose "Running Autorun rule #{rule_id} on browser #{hb_id}" - response = RestClient.get "#{@url}autorun/run/#{rule_id}/#{hb_id}", { :params => { :token => @token } } - details = JSON.parse(response.body) - print_good('Done') - details -rescue => e - print_error "Could not run Autorun rule #{rule_id}: #{e.message}" -end + def autorun_run_rule_on_browser(rule_id, hb_id) + print_verbose "Running Autorun rule #{rule_id} on browser #{hb_id}" + response = RestClient.get "#{@url}autorun/run/#{rule_id}/#{hb_id}", { :params => { :token => @token } } + details = JSON.parse(response.body) + print_good('Done') + details + rescue => e + print_error "Could not run Autorun rule #{rule_id}: #{e.message}" + end ################################################################################ ### WebRTC ################################################################################ # get webrtc status for hooked browser by session -def webrtc_status id - begin - print_verbose "Retrieving status for hooked browser [id: #{id}]" - response = RestClient.get "#{@url}webrtc/status/#{id}", { :params => { :token => @token } } - details = JSON.parse(response.body) - print_good "Retrieved status for hooked browser [id: #{id}]" - details - rescue => e - print_error "Could not retrieve status: #{e.message}" + def webrtc_status id + begin + print_verbose "Retrieving status for hooked browser [id: #{id}]" + response = RestClient.get "#{@url}webrtc/status/#{id}", { :params => { :token => @token } } + details = JSON.parse(response.body) + print_good "Retrieved status for hooked browser [id: #{id}]" + details + rescue => e + print_error "Could not retrieve status: #{e.message}" + end end -end ################################################################################ ### Social Engineering ################################################################################ # bind dropper to path -def bind(fname, path) - print_verbose "Binding 'extensions/social_engineering/droppers/#{fname}' to '#{path}'" - begin - response = RestClient.post "#{@url}/server/bind?token=#{@token}", - { 'mount' => "#{path}", - 'local_file' => "#{fname}" }.to_json, - :content_type => :json, - :accept => :json - print_good "Bound '#{fname}' successfully" if response.code == 200 - rescue => e - print_error "Could not bind file #{fname}: #{e.message}" + def bind(fname, path) + print_verbose "Binding 'extensions/social_engineering/droppers/#{fname}' to '#{path}'" + begin + response = RestClient.post "#{@url}/server/bind?token=#{@token}", + { 'mount' => "#{path}", + 'local_file' => "#{fname}" }.to_json, + :content_type => :json, + :accept => :json + print_good "Bound '#{fname}' successfully" if response.code == 200 + rescue => e + print_error "Could not bind file #{fname}: #{e.message}" + end end -end # clone page and bind to path -def clone_page(url, path, use_existing, dns_spoof) - print_verbose "Binding '#{url}' to '#{path}'" - begin - response = RestClient.post "#{@url}/seng/clone_page?token=#{@token}", - { 'mount' => "#{path}", - 'url' => "#{url}", - 'use_existing' => use_existing, - 'dns_spoof' => dns_spoof }.to_json, - :content_type => :json, - :accept => :json - print_good "Bound '#{url}' successfully" if response.code == 200 - rescue => e - print_error "Could not bind URL #{url}: #{e.message}" + def clone_page(url, path, use_existing, dns_spoof) + print_verbose "Binding '#{url}' to '#{path}'" + begin + response = RestClient.post "#{@url}/seng/clone_page?token=#{@token}", + { 'mount' => "#{path}", + 'url' => "#{url}", + 'use_existing' => use_existing, + 'dns_spoof' => dns_spoof }.to_json, + :content_type => :json, + :accept => :json + print_good "Bound '#{url}' successfully" if response.code == 200 + rescue => e + print_error "Could not bind URL #{url}: #{e.message}" + end end -end end diff --git a/tools/rest_api_examples/lib/string.rb b/tools/rest_api_examples/lib/string.rb index fdff7af31b..b5b00c82f5 100644 --- a/tools/rest_api_examples/lib/string.rb +++ b/tools/rest_api_examples/lib/string.rb @@ -1,22 +1,22 @@ # colorise # https://stackoverflow.com/questions/1489183/colorized-ruby-output class String -def black; "\033[30m#{self}\033[0m" end -def red; "\033[31m#{self}\033[0m" end -def green; "\033[32m#{self}\033[0m" end -def brown; "\033[33m#{self}\033[0m" end -def blue; "\033[34m#{self}\033[0m" end -def magenta; "\033[35m#{self}\033[0m" end -def cyan; "\033[36m#{self}\033[0m" end -def gray; "\033[37m#{self}\033[0m" end -def bg_black; "\033[40m#{self}\033[0m" end -def bg_red; "\033[41m#{self}\033[0m" end -def bg_green; "\033[42m#{self}\033[0m" end -def bg_brown; "\033[43m#{self}\033[0m" end -def bg_blue; "\033[44m#{self}\033[0m" end -def bg_magenta; "\033[45m#{self}\033[0m" end -def bg_cyan; "\033[46m#{self}\033[0m" end -def bg_gray; "\033[47m#{self}\033[0m" end -def bold; "\033[1m#{self}\033[22m" end -def reverse_color; "\033[7m#{self}\033[27m" end + def black; "\033[30m#{self}\033[0m" end + def red; "\033[31m#{self}\033[0m" end + def green; "\033[32m#{self}\033[0m" end + def brown; "\033[33m#{self}\033[0m" end + def blue; "\033[34m#{self}\033[0m" end + def magenta; "\033[35m#{self}\033[0m" end + def cyan; "\033[36m#{self}\033[0m" end + def gray; "\033[37m#{self}\033[0m" end + def bg_black; "\033[40m#{self}\033[0m" end + def bg_red; "\033[41m#{self}\033[0m" end + def bg_green; "\033[42m#{self}\033[0m" end + def bg_brown; "\033[43m#{self}\033[0m" end + def bg_blue; "\033[44m#{self}\033[0m" end + def bg_magenta; "\033[45m#{self}\033[0m" end + def bg_cyan; "\033[46m#{self}\033[0m" end + def bg_gray; "\033[47m#{self}\033[0m" end + def bold; "\033[1m#{self}\033[22m" end + def reverse_color; "\033[7m#{self}\033[27m" end end From 8ba21fbe74aa519187d6553dc479463b66100829 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:24:59 +0530 Subject: [PATCH 08/85] rubocop --only Layout/SpaceInsideParens -a --- spec/beef/extensions/dns_spec.rb | 16 ++++++++-------- test/thirdparty/msf/unit/tc_metasploit.rb | 12 ++++++------ tools/rest_api_examples/metasploit | 8 ++++---- 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/spec/beef/extensions/dns_spec.rb b/spec/beef/extensions/dns_spec.rb index 2937575925..26d1898294 100644 --- a/spec/beef/extensions/dns_spec.rb +++ b/spec/beef/extensions/dns_spec.rb @@ -46,7 +46,7 @@ id = @dns.add_rule( :pattern => 'foo.bar', :resource => IN::A, - :response => [response] ) do |transaction| + :response => [response]) do |transaction| transaction.respond!(response) end }.to_not raise_error @@ -60,7 +60,7 @@ id = @dns.add_rule( :pattern => %r{i\.(love|hate)\.beef\.com?}, :resource => IN::A, - :response => [response] ) do |transaction| + :response => [response]) do |transaction| transaction.respond!(response) end }.to_not raise_error @@ -80,7 +80,7 @@ id = @dns.add_rule( :pattern => %r{i\.(love|hate)\.beef\.com?}, :resource => IN::A, - :response => [response] ) do |transaction| + :response => [response]) do |transaction| transaction.respond!(response) end }.to_not raise_error @@ -101,7 +101,7 @@ id = @dns.add_rule( :pattern => pattern, :resource => IN::A, - :response => [response] ) do |transaction| + :response => [response]) do |transaction| transaction.respond!(response) end }.to_not raise_error @@ -110,7 +110,7 @@ same_id = @dns.add_rule( :pattern => pattern, :resource => IN::A, - :response => [response] ) do |transaction| + :response => [response]) do |transaction| transaction.respond!(response) end }.to_not raise_error @@ -119,7 +119,7 @@ same_id = @dns.add_rule( :pattern => pattern, :resource => IN::A, - :response => [response] ) do |transaction| + :response => [response]) do |transaction| transaction.respond!(response) end }.to_not raise_error @@ -158,7 +158,7 @@ id = @dns.add_rule( :pattern => pattern, :resource => IN::A, - :response => [response] ) do |transaction| + :response => [response]) do |transaction| transaction.respond!(response) end }.to_not raise_error @@ -193,7 +193,7 @@ id = @dns.add_rule( :pattern => pattern, :resource => IN::A, - :response => [response] ) do |transaction| + :response => [response]) do |transaction| transaction.respond!(response) end }.to_not raise_error diff --git a/test/thirdparty/msf/unit/tc_metasploit.rb b/test/thirdparty/msf/unit/tc_metasploit.rb index b33bc79d8e..0119f2f1a2 100644 --- a/test/thirdparty/msf/unit/tc_metasploit.rb +++ b/test/thirdparty/msf/unit/tc_metasploit.rb @@ -10,7 +10,7 @@ class TC_Metasploit < Test::Unit::TestCase def setup $root_dir='../../../../' - $:.unshift File.join( %w{ ../../../../ } ) + $:.unshift File.join(%w{ ../../../../ }) require 'core/loader' end @@ -97,7 +97,7 @@ def test_exploit_info assert_nothing_raised do info = @api.get_exploit_info('windows/dcerpc/ms03_026_dcom') end - assert( info['name'].nil? != true) + assert(info['name'].nil? != true) end def test_get_options @@ -107,7 +107,7 @@ def test_get_options assert_nothing_raised do info = @api.get_options('windows/dcerpc/ms03_026_dcom') end - assert( info['RHOST'].nil? != true) + assert(info['RHOST'].nil? != true) end def test_payloads @@ -117,7 +117,7 @@ def test_payloads assert_nothing_raised do payloads = @api.payloads end - assert( payloads.length > 5 ) + assert(payloads.length > 5) end def test_launch_exploit @@ -128,7 +128,7 @@ def test_launch_exploit assert_nothing_raised do ret = @api.launch_exploit('windows/browser/adobe_utilprintf',opts) end - assert(ret['job_id'] != nil ) + assert(ret['job_id'] != nil) end def test_launch_autopwn @@ -138,6 +138,6 @@ def test_launch_autopwn assert_nothing_raised do ret = @api.launch_autopwn end - assert(ret['job_id'] != nil ) + assert(ret['job_id'] != nil) end end diff --git a/tools/rest_api_examples/metasploit b/tools/rest_api_examples/metasploit index 433bde97cf..ddde752034 100755 --- a/tools/rest_api_examples/metasploit +++ b/tools/rest_api_examples/metasploit @@ -73,10 +73,10 @@ print_status "Authenticating to: #{proto}://#{host}:#{port}" # Start payload handlers handlers = [ - @api.msf_handler( { 'PAYLOAD'=>'generic/shell_reverse_tcp', 'LPORT' => '6666', 'LHOST' => host } ), - @api.msf_handler( { 'PAYLOAD'=>'cmd/unix/reverse', 'LPORT' => '6010', 'LHOST' => host } ), - @api.msf_handler( { 'PAYLOAD'=>'linux/x86/meterpreter/reverse_tcp', 'LPORT' => '6020', 'LHOST'=> host } ), - @api.msf_handler( { 'PAYLOAD'=>'windows/meterpreter/reverse_tcp', 'LPORT' => '6030', 'LHOST'=> host } ) + @api.msf_handler({ 'PAYLOAD'=>'generic/shell_reverse_tcp', 'LPORT' => '6666', 'LHOST' => host }), + @api.msf_handler({ 'PAYLOAD'=>'cmd/unix/reverse', 'LPORT' => '6010', 'LHOST' => host }), + @api.msf_handler({ 'PAYLOAD'=>'linux/x86/meterpreter/reverse_tcp', 'LPORT' => '6020', 'LHOST'=> host }), + @api.msf_handler({ 'PAYLOAD'=>'windows/meterpreter/reverse_tcp', 'LPORT' => '6030', 'LHOST'=> host }) ] # Retrieve msf jobs From c400246ea2d14b427aba5ead50458caf8ab6407a Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:25:52 +0530 Subject: [PATCH 09/85] rubocop --only Layout/IndentationConsistency -a --- core/main/autorun_engine/engine.rb | 4 +- core/main/handlers/hookedbrowsers.rb | 2 +- extensions/webrtc/api.rb | 2 +- extensions/webrtc/handlers.rb | 32 ++-- spec/beef/api/auth_rate_spec.rb | 94 +++++------ spec/features/all_modules_spec.rb | 84 +++++----- spec/features/debug_modules_spec.rb | 104 ++++++------ spec/requests/beef_test_spec.rb | 162 +++++++++---------- spec/spec_helper.rb | 18 +-- spec/support/ui_support.rb | 72 ++++----- test/integration/tc_debug_modules.rb | 4 +- tools/rest_api_examples/lib/beef_rest_api.rb | 2 +- 12 files changed, 290 insertions(+), 290 deletions(-) diff --git a/core/main/autorun_engine/engine.rb b/core/main/autorun_engine/engine.rb index c7df6df45d..1e1550d123 100644 --- a/core/main/autorun_engine/engine.rb +++ b/core/main/autorun_engine/engine.rb @@ -161,8 +161,8 @@ def zombie_browser_matches_rule?(browser, browser_version, rule) return false unless rule.browser == 'ALL' || browser == rule.browser # check if the browser version matches - browser_version_match = compare_versions(browser_version.to_s, b_ver_cond, b_ver.to_s) - return false unless browser_version_match + browser_version_match = compare_versions(browser_version.to_s, b_ver_cond, b_ver.to_s) + return false unless browser_version_match else browser_match = false rule.browser.gsub(/[^A-Z,]/i, '').split(',').each do |b| diff --git a/core/main/handlers/hookedbrowsers.rb b/core/main/handlers/hookedbrowsers.rb index ea08a6f5be..dc50bff3bc 100644 --- a/core/main/handlers/hookedbrowsers.rb +++ b/core/main/handlers/hookedbrowsers.rb @@ -128,7 +128,7 @@ def confirm_browser_user_agent(user_agent) host_name = request.host unless BeEF::Filters.is_valid_hostname?(host_name) (print_error 'Invalid host name' - return) + return) end # Generate the hook js provided to the hookwed browser (the magic happens here) diff --git a/extensions/webrtc/api.rb b/extensions/webrtc/api.rb index 2003e7dc0c..e496f65a89 100644 --- a/extensions/webrtc/api.rb +++ b/extensions/webrtc/api.rb @@ -31,7 +31,7 @@ module RegisterPreHookCallback # This is also used so that BeEF can send RTCManagement messages to the hooked browser too def self.pre_hook_send(hooked_browser, body, params, request, response) dhook = BeEF::Extension::WebRTC::API::Hook.new - dhook.requester_run(hooked_browser, body) + dhook.requester_run(hooked_browser, body) end end diff --git a/extensions/webrtc/handlers.rb b/extensions/webrtc/handlers.rb index e1b525866b..7a98bf893a 100644 --- a/extensions/webrtc/handlers.rb +++ b/extensions/webrtc/handlers.rb @@ -96,53 +96,53 @@ def setup() stat = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => zombie_db.id, :target_hooked_browser_id => peer_zombie_db.id) || nil unless stat.nil? stat.status = 'Connected' - stat.updated_at = Time.now - stat.save + stat.updated_at = Time.now + stat.save end stat2 = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => peer_zombie_db.id, :target_hooked_browser_id => zombie_db.id) || nil unless stat2.nil? stat2.status = 'Connected' - stat2.updated_at = Time.now - stat2.save + stat2.updated_at = Time.now + stat2.save end elsif (message.end_with?('disconnected')) stat = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => zombie_db.id, :target_hooked_browser_id => peer_zombie_db.id) || nil unless stat.nil? stat.status = 'Disconnected' - stat.updated_at = Time.now - stat.save + stat.updated_at = Time.now + stat.save end stat2 = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => peer_zombie_db.id, :target_hooked_browser_id => zombie_db.id) || nil unless stat2.nil? stat2.status = 'Disconnected' - stat2.updated_at = Time.now - stat2.save + stat2.updated_at = Time.now + stat2.save end elsif (message == 'Stayin alive') stat = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => zombie_db.id, :target_hooked_browser_id => peer_zombie_db.id) || nil unless stat.nil? stat.status = 'Stealthed!!' - stat.updated_at = Time.now - stat.save + stat.updated_at = Time.now + stat.save end stat2 = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => peer_zombie_db.id, :target_hooked_browser_id => zombie_db.id) || nil unless stat2.nil? stat2.status = 'Peer-controlled stealth-mode' - stat2.updated_at = Time.now - stat2.save + stat2.updated_at = Time.now + stat2.save end elsif (message == 'Coming out of stealth...') stat = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => zombie_db.id, :target_hooked_browser_id => peer_zombie_db.id) || nil unless stat.nil? stat.status = 'Connected' - stat.updated_at = Time.now - stat.save + stat.updated_at = Time.now + stat.save end stat2 = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => peer_zombie_db.id, :target_hooked_browser_id => zombie_db.id) || nil unless stat2.nil? stat2.status = 'Connected' - stat2.updated_at = Time.now - stat2.save + stat2.updated_at = Time.now + stat2.save end elsif (message.start_with?('execcmd')) mod = /\(\/command\/(.*)\.js\)/.match(message)[1] diff --git a/spec/beef/api/auth_rate_spec.rb b/spec/beef/api/auth_rate_spec.rb index ef92f43634..d7de8a69d7 100644 --- a/spec/beef/api/auth_rate_spec.rb +++ b/spec/beef/api/auth_rate_spec.rb @@ -8,64 +8,64 @@ before(:each) do @pid = start_beef_server_and_wait - @username = @config.get('beef.credentials.user') - @password = @config.get('beef.credentials.passwd') + @username = @config.get('beef.credentials.user') + @password = @config.get('beef.credentials.passwd') end - after(:each) do - # Shutting down server - Process.kill('KILL', @pid) unless @pid.nil? - Process.wait(@pid) unless @pid.nil? # Ensure the process has exited and the port is released - @pid = nil - end + after(:each) do + # Shutting down server + Process.kill('KILL', @pid) unless @pid.nil? + Process.wait(@pid) unless @pid.nil? # Ensure the process has exited and the port is released + @pid = nil + end - it 'confirm correct creds are successful' do - test_api = BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, @password) - expect(@config.get('beef.credentials.user')).to eq('beef') - expect(@config.get('beef.credentials.passwd')).to eq('beef') - expect(test_api.auth()[:payload]).not_to eql('401 Unauthorized') - expect(test_api.auth()[:payload]['success']).to be(true) # valid pass should succeed - end + it 'confirm correct creds are successful' do + test_api = BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, @password) + expect(@config.get('beef.credentials.user')).to eq('beef') + expect(@config.get('beef.credentials.passwd')).to eq('beef') + expect(test_api.auth()[:payload]).not_to eql('401 Unauthorized') + expect(test_api.auth()[:payload]['success']).to be(true) # valid pass should succeed + end - it 'confirm incorrect creds are unsuccessful' do - sleep 0.5 - test_api = BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, 'wrong_passowrd') - expect(test_api.auth()[:payload]).to eql('401 Unauthorized') # all (unless the valid is first 1 in 10 chance) - end + it 'confirm incorrect creds are unsuccessful' do + sleep 0.5 + test_api = BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, 'wrong_passowrd') + expect(test_api.auth()[:payload]).to eql('401 Unauthorized') # all (unless the valid is first 1 in 10 chance) + end - it 'adheres to 9 bad passwords then 1 correct auth rate limits' do - # create api structures with bad passwords and one good + it 'adheres to 9 bad passwords then 1 correct auth rate limits' do + # create api structures with bad passwords and one good passwds = (1..9).map { |i| 'bad_password'} # incorrect password - passwds.push @password # correct password - apis = passwds.map { |pswd| BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, pswd) } + passwds.push @password # correct password + apis = passwds.map { |pswd| BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, pswd) } - (0..apis.length-1).each do |i| - test_api = apis[i] - expect(test_api.auth()[:payload]).to eql('401 Unauthorized') # all (unless the valid is first 1 in 10 chance) - end - end + (0..apis.length-1).each do |i| + test_api = apis[i] + expect(test_api.auth()[:payload]).to eql('401 Unauthorized') # all (unless the valid is first 1 in 10 chance) + end + end - it 'adheres to random bad passords and 1 correct auth rate limits' do - # create api structures with bad passwords and one good + it 'adheres to random bad passords and 1 correct auth rate limits' do + # create api structures with bad passwords and one good passwds = (1..9).map { |i| 'bad_password'} # incorrect password - passwds.push @password # correct password - apis = passwds.map { |pswd| BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, pswd) } + passwds.push @password # correct password + apis = passwds.map { |pswd| BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, pswd) } - apis.shuffle! # random order for next iteration - apis = apis.reverse if (apis[0].is_pass?(@password)) # prevent the first from having valid passwd + apis.shuffle! # random order for next iteration + apis = apis.reverse if (apis[0].is_pass?(@password)) # prevent the first from having valid passwd - (0..apis.length-1).each do |i| - test_api = apis[i] - if (test_api.is_pass?(@password)) - sleep 0.5 - expect(@config.get('beef.credentials.user')).to eq('beef') - expect(@config.get('beef.credentials.passwd')).to eq('beef') - expect(test_api.auth()[:payload]).not_to eql('401 Unauthorized') - expect(test_api.auth()[:payload]['success']).to be(true) # valid pass should succeed - else - expect(test_api.auth()[:payload]).to eql('401 Unauthorized') - end + (0..apis.length-1).each do |i| + test_api = apis[i] + if (test_api.is_pass?(@password)) + sleep 0.5 + expect(@config.get('beef.credentials.user')).to eq('beef') + expect(@config.get('beef.credentials.passwd')).to eq('beef') + expect(test_api.auth()[:payload]).not_to eql('401 Unauthorized') + expect(test_api.auth()[:payload]['success']).to be(true) # valid pass should succeed + else + expect(test_api.auth()[:payload]).to eql('401 Unauthorized') end - end + end + end end diff --git a/spec/features/all_modules_spec.rb b/spec/features/all_modules_spec.rb index 1a9f109072..bd2569ee60 100644 --- a/spec/features/all_modules_spec.rb +++ b/spec/features/all_modules_spec.rb @@ -13,51 +13,51 @@ @pid, @beef_session, @hooked_browser = start_beef_and_hook_browser end - after(:each) do - stop_beef_and_unhook_browser(@pid, @beef_session, @hooked_browser) - end + after(:each) do + stop_beef_and_unhook_browser(@pid, @beef_session, @hooked_browser) + end - it 'Load all modules' do + it 'Load all modules' do + + Dir.glob('modules/**/config.yaml').each do |file| + module_yaml_data = YAML.load_file(file) - Dir.glob('modules/**/config.yaml').each do |file| - module_yaml_data = YAML.load_file(file) - - module_yaml_data['beef']['module'].each do |module_key, module_value| - next if rand(50) != 0 # for testing purposes only - - next if not module_value['enable'] # skip disabled modules - - module_name = module_value['name'] - module_category = module_value['category'] # can be an array or a string - module_description_sub = module_value['description'][0, 15] # descriptions including html cause errors - - expect(module_category).not_to be_nil - expect(module_name).not_to be_nil - - expect(@beef_session).to have_content(module_category, wait: PAGE_LOAD_TIMEOUT) if module_category.is_a?(String) - - expect(module_name).to be_a(String) - expect(module_description_sub).not_to be_nil - expect(module_description_sub).to be_a(String) - - # print the category and module name - if module_category.is_a?(Array) - category_tree_text = module_category.join(' > ') - else - category_tree_text = module_category - end - print_info "Category: #{category_tree_text}, Module: #{module_name}" - - # click on the module then expect the description and execute button to be visible - click_on_module(@beef_session, module_category, module_name) - - # expect the module description and the execute button to be visible - expect(@beef_session).to have_content(module_description_sub, wait: PAGE_LOAD_TIMEOUT) - expect(@beef_session).to have_content('Execute', wait: PAGE_LOAD_TIMEOUT) + module_yaml_data['beef']['module'].each do |module_key, module_value| + next if rand(50) != 0 # for testing purposes only + + next if not module_value['enable'] # skip disabled modules + + module_name = module_value['name'] + module_category = module_value['category'] # can be an array or a string + module_description_sub = module_value['description'][0, 15] # descriptions including html cause errors + + expect(module_category).not_to be_nil + expect(module_name).not_to be_nil + + expect(@beef_session).to have_content(module_category, wait: PAGE_LOAD_TIMEOUT) if module_category.is_a?(String) + + expect(module_name).to be_a(String) + expect(module_description_sub).not_to be_nil + expect(module_description_sub).to be_a(String) + + # print the category and module name + if module_category.is_a?(Array) + category_tree_text = module_category.join(' > ') + else + category_tree_text = module_category + end + print_info "Category: #{category_tree_text}, Module: #{module_name}" + + # click on the module then expect the description and execute button to be visible + click_on_module(@beef_session, module_category, module_name) + + # expect the module description and the execute button to be visible + expect(@beef_session).to have_content(module_description_sub, wait: PAGE_LOAD_TIMEOUT) + expect(@beef_session).to have_content('Execute', wait: PAGE_LOAD_TIMEOUT) - # tidy up and collapse the category tree - collapse_category_tree(@beef_session, module_category) - end + # tidy up and collapse the category tree + collapse_category_tree(@beef_session, module_category) end end + end end \ No newline at end of file diff --git a/spec/features/debug_modules_spec.rb b/spec/features/debug_modules_spec.rb index cc313bec39..fddfc0893c 100644 --- a/spec/features/debug_modules_spec.rb +++ b/spec/features/debug_modules_spec.rb @@ -13,62 +13,62 @@ @pid, @beef_session, @hooked_browser = start_beef_and_hook_browser end - after(:each) do - stop_beef_and_unhook_browser(@pid, @beef_session, @hooked_browser) - end + after(:each) do + stop_beef_and_unhook_browser(@pid, @beef_session, @hooked_browser) + end - it 'Test beef.debug module' do - click_on_module(@beef_session, 'Debug', 'Test beef.debug') - expect(@beef_session).to have_content('Execute', wait: PAGE_LOAD_TIMEOUT) - expect(@beef_session).to have_content('244', wait: PAGE_LOAD_TIMEOUT) # Module ID - expect(@beef_session).to have_content('Debug Message:', wait: PAGE_LOAD_TIMEOUT) - end + it 'Test beef.debug module' do + click_on_module(@beef_session, 'Debug', 'Test beef.debug') + expect(@beef_session).to have_content('Execute', wait: PAGE_LOAD_TIMEOUT) + expect(@beef_session).to have_content('244', wait: PAGE_LOAD_TIMEOUT) # Module ID + expect(@beef_session).to have_content('Debug Message:', wait: PAGE_LOAD_TIMEOUT) + end - it 'Load all debug modules' do - Dir.glob('modules/debug/**/config.yaml').each do |file| - module_yaml_data = YAML.load_file(file) - - module_yaml_data['beef']['module'].each do |module_key, module_value| - module_category = module_value['category'] - module_name = module_value['name'] - # some descriptions are too long and include html tags - module_description_sub = module_value['description'][0, 20] - - expect(@beef_session).to have_content(module_category, wait: PAGE_LOAD_TIMEOUT) - expect(module_category).not_to be_nil - expect(module_category).to be_a(String) - expect(module_name).not_to be_nil - expect(module_name).to be_a(String) - expect(module_description_sub).not_to be_nil - expect(module_description_sub).to be_a(String) - - click_on_module(@beef_session, 'Debug', module_name) - - expect(@beef_session).to have_content(module_description_sub, wait: PAGE_LOAD_TIMEOUT) - expect(@beef_session).to have_content('Execute', wait: PAGE_LOAD_TIMEOUT) - - # execute the module - @beef_session.click_on('Execute') - - # expect the module to make command output visible - expect(@beef_session).to have_content('command 1', wait: PAGE_LOAD_TIMEOUT) - - # click on the command section to display the output - @beef_session.all('div.x-grid3-cell-inner').each do |div| - if div.text == 'command 1' - div.click - break - end - end - - if module_name == 'Return Image' # this module returns an image not a string - image_selector = "img[src^='data:image/png;base64,iVBORw0KGgo']" - expect(@beef_session).to have_css(image_selector, wait: PAGE_LOAD_TIMEOUT) - else - expect(@beef_session).to have_content('data: ', wait: PAGE_LOAD_TIMEOUT) - end + it 'Load all debug modules' do + Dir.glob('modules/debug/**/config.yaml').each do |file| + module_yaml_data = YAML.load_file(file) + + module_yaml_data['beef']['module'].each do |module_key, module_value| + module_category = module_value['category'] + module_name = module_value['name'] + # some descriptions are too long and include html tags + module_description_sub = module_value['description'][0, 20] + + expect(@beef_session).to have_content(module_category, wait: PAGE_LOAD_TIMEOUT) + expect(module_category).not_to be_nil + expect(module_category).to be_a(String) + expect(module_name).not_to be_nil + expect(module_name).to be_a(String) + expect(module_description_sub).not_to be_nil + expect(module_description_sub).to be_a(String) + + click_on_module(@beef_session, 'Debug', module_name) + + expect(@beef_session).to have_content(module_description_sub, wait: PAGE_LOAD_TIMEOUT) + expect(@beef_session).to have_content('Execute', wait: PAGE_LOAD_TIMEOUT) + + # execute the module + @beef_session.click_on('Execute') + + # expect the module to make command output visible + expect(@beef_session).to have_content('command 1', wait: PAGE_LOAD_TIMEOUT) + + # click on the command section to display the output + @beef_session.all('div.x-grid3-cell-inner').each do |div| + if div.text == 'command 1' + div.click + break end + end + + if module_name == 'Return Image' # this module returns an image not a string + image_selector = "img[src^='data:image/png;base64,iVBORw0KGgo']" + expect(@beef_session).to have_css(image_selector, wait: PAGE_LOAD_TIMEOUT) + else + expect(@beef_session).to have_content('data: ', wait: PAGE_LOAD_TIMEOUT) + end end end + end end \ No newline at end of file diff --git a/spec/requests/beef_test_spec.rb b/spec/requests/beef_test_spec.rb index ac30d2caa0..25a1f9b571 100644 --- a/spec/requests/beef_test_spec.rb +++ b/spec/requests/beef_test_spec.rb @@ -13,99 +13,99 @@ @pid = start_beef_server_and_wait end - after(:each) do - stop_beef_server(@pid) - end + after(:each) do + stop_beef_server(@pid) + end - describe '.login' do - it 'logs in successfully' do - expect(port_available?) # Check if the tcp port is open - session = BeefTest.login() - expect(session).not_to be_nil - expect(session.has_content?('Hooked Browsers', wait: 10)) - end + describe '.login' do + it 'logs in successfully' do + expect(port_available?) # Check if the tcp port is open + session = BeefTest.login() + expect(session).not_to be_nil + expect(session.has_content?('Hooked Browsers', wait: 10)) end + end - describe '.logout' do - before(:each) do - expect(port_available?) # # Check if the tcp port is open - @session = BeefTest.login() # Ensure login before each '.logout' test - expect(@session.has_content?('Hooked Browsers', wait: 10)) - end + describe '.logout' do + before(:each) do + expect(port_available?) # # Check if the tcp port is open + @session = BeefTest.login() # Ensure login before each '.logout' test + expect(@session.has_content?('Hooked Browsers', wait: 10)) + end - it 'logs out successfully' do - expect(port_available?) # # Check if the tcp port is open - expect(@session.has_content?('Hooked Browsers', wait: 10)) - - # Log out of the session - @sessoin = BeefTest.logout(@session) - expect(@session.has_no_content?('Hooked Browsers', wait: 10)) - expect(@session.has_content?('Authentication', wait: 10)) - @session.reset_session! - end + it 'logs out successfully' do + expect(port_available?) # # Check if the tcp port is open + expect(@session.has_content?('Hooked Browsers', wait: 10)) + + # Log out of the session + @sessoin = BeefTest.logout(@session) + expect(@session.has_no_content?('Hooked Browsers', wait: 10)) + expect(@session.has_content?('Authentication', wait: 10)) + @session.reset_session! end + end - describe '.save_screenshot' do - it 'saves a screenshot' do - session = Capybara::Session.new(:selenium_headless) if session.nil? - - # Ensure the new directory does not exist - outputDir = '/tmp' - directory = "#{outputDir}/#{SecureRandom.hex}/" - expect(File.directory?(directory)).to be false - - # Save the screenshot - BeefTest.save_screenshot(session, directory) - - # Ensure the screenshot was saved - expect(File.directory?(directory)).to be true - screenshot_files = Dir.glob("#{directory}/*.png") - expect(screenshot_files.empty?).to be false - - # Ensure the screenshot file is not empty and clean up - screenshot_files.each do |file| - expect(File.size(file)).to be > 0 - File.delete(file) - end - expect(Dir.glob("#{directory}/*.png").empty?).to be true - - # Remove the directory - Dir.delete(directory) - expect(File.directory?(directory)).to be false + describe '.save_screenshot' do + it 'saves a screenshot' do + session = Capybara::Session.new(:selenium_headless) if session.nil? + + # Ensure the new directory does not exist + outputDir = '/tmp' + directory = "#{outputDir}/#{SecureRandom.hex}/" + expect(File.directory?(directory)).to be false + + # Save the screenshot + BeefTest.save_screenshot(session, directory) + + # Ensure the screenshot was saved + expect(File.directory?(directory)).to be true + screenshot_files = Dir.glob("#{directory}/*.png") + expect(screenshot_files.empty?).to be false + + # Ensure the screenshot file is not empty and clean up + screenshot_files.each do |file| + expect(File.size(file)).to be > 0 + File.delete(file) end + expect(Dir.glob("#{directory}/*.png").empty?).to be true + + # Remove the directory + Dir.delete(directory) + expect(File.directory?(directory)).to be false end + end - let(:session) { Capybara::Session.new(:selenium_headless) } - let(:victim) { Capybara::Session.new(:selenium_headless) } - - describe '.new_attacker' do - it 'creates a new attacker session' do - # # Test setup - expect(session).not_to be_nil - - result = BeefTest.new_attacker(session) - - # Test assertions - expect(result).to eq(session) - expect(session.has_no_content?('Authentication', wait: 10)) - expect(session.has_content?('Hooked Browsers', wait: 10)) - session.reset_session! - end + let(:session) { Capybara::Session.new(:selenium_headless) } + let(:victim) { Capybara::Session.new(:selenium_headless) } + + describe '.new_attacker' do + it 'creates a new attacker session' do + # # Test setup + expect(session).not_to be_nil + + result = BeefTest.new_attacker(session) + + # Test assertions + expect(result).to eq(session) + expect(session.has_no_content?('Authentication', wait: 10)) + expect(session.has_content?('Hooked Browsers', wait: 10)) + session.reset_session! end + end - describe '.new_victim' do - it 'creates a new victim session' do - # Test setup - allow(victim).to receive(:visit) - expect(victim).not_to be_nil + describe '.new_victim' do + it 'creates a new victim session' do + # Test setup + allow(victim).to receive(:visit) + expect(victim).not_to be_nil - # Test execution - result = BeefTest.new_victim(victim) + # Test execution + result = BeefTest.new_victim(victim) - # Test assertions - expect(victim).to have_received(:visit).with(VICTIM_URL) - expect(result).to eq(victim) - victim.reset_session! - end + # Test assertions + expect(victim).to have_received(:visit).with(VICTIM_URL) + expect(result).to eq(victim) + victim.reset_session! end + end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index b738213ec2..b10b18b781 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -173,16 +173,16 @@ def server_teardown(webdriver, server_pid, server_pids) ######################################## -def reset_beef_db - begin - db_file = BeEF::Core::Configuration.instance.get('beef.database.file') - File.delete(db_file) if File.exist?(db_file) -rescue => e - print_error("Could not remove '#{db_file}' database file: #{e.message}") + def reset_beef_db + begin + db_file = BeEF::Core::Configuration.instance.get('beef.database.file') + File.delete(db_file) if File.exist?(db_file) + rescue => e + print_error("Could not remove '#{db_file}' database file: #{e.message}") + end end -end -require 'socket' + require 'socket' def port_available? socket = TCPSocket.new(@host, @port) @@ -209,7 +209,7 @@ def load_beef_extensions_and_modules BeEF::Extensions.load # Load BeEF modules only if they are not already loaded - BeEF::Modules.load if @config.get('beef.module').nil? + BeEF::Modules.load if @config.get('beef.module').nil? end # --- HARD fork-safety: disconnect every pool/adapter we can find --- diff --git a/spec/support/ui_support.rb b/spec/support/ui_support.rb index eb9fafe7c2..195d2c1173 100644 --- a/spec/support/ui_support.rb +++ b/spec/support/ui_support.rb @@ -9,54 +9,54 @@ def start_beef_and_hook_browser() reset_beef_db - pid = start_beef_server_and_wait - beef_session = BeefTest.login - hooked_browser = BeefTest.new_victim + pid = start_beef_server_and_wait + beef_session = BeefTest.login + hooked_browser = BeefTest.new_victim - expect(hooked_browser).not_to be_nil - expect(hooked_browser).to be_a(Capybara::Session) - expect(hooked_browser).to have_content('BeEF', wait: PAGE_LOAD_TIMEOUT) + expect(hooked_browser).not_to be_nil + expect(hooked_browser).to be_a(Capybara::Session) + expect(hooked_browser).to have_content('BeEF', wait: PAGE_LOAD_TIMEOUT) - expect(beef_session).not_to be_nil - expect(beef_session).to be_a(Capybara::Session) - expect(beef_session).to have_content('Hooked Browsers', wait: PAGE_LOAD_TIMEOUT) + expect(beef_session).not_to be_nil + expect(beef_session).to be_a(Capybara::Session) + expect(beef_session).to have_content('Hooked Browsers', wait: PAGE_LOAD_TIMEOUT) - navigate_to_hooked_browser(beef_session) + navigate_to_hooked_browser(beef_session) - expect(beef_session).to have_content('Commands', wait: PAGE_LOAD_TIMEOUT) - beef_session.click_on('Commands') + expect(beef_session).to have_content('Commands', wait: PAGE_LOAD_TIMEOUT) + beef_session.click_on('Commands') - return pid, beef_session, hooked_browser + return pid, beef_session, hooked_browser end def stop_beef_and_unhook_browser(pid, beef_session, hooked_browser) stop_beef_server(pid) - beef_session.driver.browser.close - hooked_browser.driver.browser.close + beef_session.driver.browser.close + hooked_browser.driver.browser.close end def navigate_to_hooked_browser(session, hooked_browser_text = nil) expect(session).to have_content('Hooked Browsers', wait: PAGE_LOAD_TIMEOUT) - hooked_browser_text = '127.0.0.1' if hooked_browser_text.nil? - expect(session).to have_content(hooked_browser_text, wait: BROWSER_HOOKING_TIMEOUT) + hooked_browser_text = '127.0.0.1' if hooked_browser_text.nil? + expect(session).to have_content(hooked_browser_text, wait: BROWSER_HOOKING_TIMEOUT) # click on the hooked browser in the leaf - session.all('a', text: hooked_browser_text)[1].click - expect(session).to have_content('Commands', wait: PAGE_LOAD_TIMEOUT) + session.all('a', text: hooked_browser_text)[1].click + expect(session).to have_content('Commands', wait: PAGE_LOAD_TIMEOUT) end def navigate_to_category(session, category_name = nil) expect(category_name).not_to be_nil - expect(category_name).to be_a(String) + expect(category_name).to be_a(String) - navigate_to_hooked_browser unless session.has_content?('Current Browser') + navigate_to_hooked_browser unless session.has_content?('Current Browser') # ensure the command module tree is visible - session.click_on('Commands') - expect(session).to have_content(category_name, wait: PAGE_LOAD_TIMEOUT) + session.click_on('Commands') + expect(session).to have_content(category_name, wait: PAGE_LOAD_TIMEOUT) - session.first(:link_or_button, category_name + ' ').click + session.first(:link_or_button, category_name + ' ').click end def expand_category_tree(session, category, module_name = nil) @@ -76,19 +76,19 @@ def expand_category_tree(session, category, module_name = nil) rescue Selenium::WebDriver::Error::StaleElementReferenceError => e puts "StaleElementReferenceError: #{element_text}" - puts e.message - next + puts e.message + next end end - expect(session).to have_content(category_name, wait: PAGE_LOAD_TIMEOUT) - navigate_to_category(session, category_name) unless session.has_content?(module_name) + expect(session).to have_content(category_name, wait: PAGE_LOAD_TIMEOUT) + navigate_to_category(session, category_name) unless session.has_content?(module_name) end else navigate_to_category(session, category) unless session.has_content?(module_name) - expect(session).to have_content(category, wait: PAGE_LOAD_TIMEOUT) + expect(session).to have_content(category, wait: PAGE_LOAD_TIMEOUT) end - expect(session).to have_content(module_name, wait: PAGE_LOAD_TIMEOUT) + expect(session).to have_content(module_name, wait: PAGE_LOAD_TIMEOUT) end def collapse_category_tree(session, category) @@ -96,11 +96,11 @@ def collapse_category_tree(session, category) category.reverse.each do |category_name| # Collapse the sub-folder session.scroll_to(category_name) - session.first(:link_or_button, category_name + ' ').click + session.first(:link_or_button, category_name + ' ').click end else session.scroll_to(category) - session.first(:link_or_button, category + ' ').click + session.first(:link_or_button, category + ' ').click end end @@ -109,8 +109,8 @@ def click_on_module(session, category, module_name) expand_category_tree(session, category, module_name) # click on the module in the expanded tree - session.scroll_to(module_name) - expect(session).to have_content(module_name, wait: PAGE_LOAD_TIMEOUT) - modules = session.all(:link_or_button, module_name) - modules[0].click + session.scroll_to(module_name) + expect(session).to have_content(module_name, wait: PAGE_LOAD_TIMEOUT) + modules = session.all(:link_or_button, module_name) + modules[0].click end \ No newline at end of file diff --git a/test/integration/tc_debug_modules.rb b/test/integration/tc_debug_modules.rb index e9d53464ec..3ef20ee1c4 100644 --- a/test/integration/tc_debug_modules.rb +++ b/test/integration/tc_debug_modules.rb @@ -127,8 +127,8 @@ def test_return_ascii_chars # don't know why empty?, nil and other checks are not working. while(response.body.size <= 2 && count < 10) response = RestClient.get "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_debug_ascii_chars}/#{cmd_id}?token=#{@@token}" - sleep 2 - count += 1 + sleep 2 + count += 1 end assert_equal 200, response.code assert_not_nil response.body diff --git a/tools/rest_api_examples/lib/beef_rest_api.rb b/tools/rest_api_examples/lib/beef_rest_api.rb index 3f00767130..b1bf391761 100644 --- a/tools/rest_api_examples/lib/beef_rest_api.rb +++ b/tools/rest_api_examples/lib/beef_rest_api.rb @@ -554,7 +554,7 @@ def bind(fname, path) 'local_file' => "#{fname}" }.to_json, :content_type => :json, :accept => :json - print_good "Bound '#{fname}' successfully" if response.code == 200 + print_good "Bound '#{fname}' successfully" if response.code == 200 rescue => e print_error "Could not bind file #{fname}: #{e.message}" end From ed1da56d34cce620d7ab9d66f617cefd9baa6582 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:26:31 +0530 Subject: [PATCH 10/85] rubocop --only Layout/CommentIndentation -a --- Rakefile | 4 +- core/main/autorun_engine/engine.rb | 2 +- extensions/webrtc/api/hook.rb | 2 +- spec/beef/api/auth_rate_spec.rb | 2 +- spec/beef/extensions/dns_spec.rb | 2 +- spec/features/all_modules_spec.rb | 8 +- spec/features/debug_modules_spec.rb | 8 +- spec/requests/beef_test_spec.rb | 22 ++-- spec/spec_helper.rb | 6 +- spec/support/ui_support.rb | 12 +- test/integration/tc_debug_modules.rb | 2 +- tools/rest_api_examples/lib/beef_rest_api.rb | 124 +++++++++---------- 12 files changed, 97 insertions(+), 97 deletions(-) diff --git a/Rakefile b/Rakefile index f3581cf1c3..97c118847f 100644 --- a/Rakefile +++ b/Rakefile @@ -88,8 +88,8 @@ namespace :rdoc do rd.rdoc_dir = 'doc/rdocs' rd.main = 'README.mkd' rd.rdoc_files.include('core/**/*\.rb') - #'extensions/**/*\.rb' - #'modules/**/*\.rb' + #'extensions/**/*\.rb' + #'modules/**/*\.rb' rd.options << '--line-numbers' rd.options << '--all' end diff --git a/core/main/autorun_engine/engine.rb b/core/main/autorun_engine/engine.rb index 1e1550d123..3fc56a2a4e 100644 --- a/core/main/autorun_engine/engine.rb +++ b/core/main/autorun_engine/engine.rb @@ -160,7 +160,7 @@ def zombie_browser_matches_rule?(browser, browser_version, rule) if rule.browser =~ /\A[A-Z]+\Z/ return false unless rule.browser == 'ALL' || browser == rule.browser - # check if the browser version matches + # check if the browser version matches browser_version_match = compare_versions(browser_version.to_s, b_ver_cond, b_ver.to_s) return false unless browser_version_match else diff --git a/extensions/webrtc/api/hook.rb b/extensions/webrtc/api/hook.rb index 8aac01bf68..f8219a2805 100644 --- a/extensions/webrtc/api/hook.rb +++ b/extensions/webrtc/api/hook.rb @@ -63,7 +63,7 @@ def requester_run(hb, body) } unless rtcmanagementoutput.empty? # ws.send(content + @body,hb.session) ws.send(@body,hb.session) - #if we use WebSockets, just reply wih the component contents + #if we use WebSockets, just reply wih the component contents else # if we use XHR-polling, add the component to the main hook file rtcsignaloutput.each {|o| add_rtcsignal_to_body o diff --git a/spec/beef/api/auth_rate_spec.rb b/spec/beef/api/auth_rate_spec.rb index d7de8a69d7..60a07b972d 100644 --- a/spec/beef/api/auth_rate_spec.rb +++ b/spec/beef/api/auth_rate_spec.rb @@ -13,7 +13,7 @@ end after(:each) do - # Shutting down server + # Shutting down server Process.kill('KILL', @pid) unless @pid.nil? Process.wait(@pid) unless @pid.nil? # Ensure the process has exited and the port is released @pid = nil diff --git a/spec/beef/extensions/dns_spec.rb b/spec/beef/extensions/dns_spec.rb index 26d1898294..4fed5eaad5 100644 --- a/spec/beef/extensions/dns_spec.rb +++ b/spec/beef/extensions/dns_spec.rb @@ -247,7 +247,7 @@ end - # Tests each supported type of query failure +# Tests each supported type of query failure # def test_13_failure_types # begin # id = @@dns.add_rule( diff --git a/spec/features/all_modules_spec.rb b/spec/features/all_modules_spec.rb index bd2569ee60..fec3d91df0 100644 --- a/spec/features/all_modules_spec.rb +++ b/spec/features/all_modules_spec.rb @@ -40,7 +40,7 @@ expect(module_description_sub).not_to be_nil expect(module_description_sub).to be_a(String) - # print the category and module name + # print the category and module name if module_category.is_a?(Array) category_tree_text = module_category.join(' > ') else @@ -48,14 +48,14 @@ end print_info "Category: #{category_tree_text}, Module: #{module_name}" - # click on the module then expect the description and execute button to be visible + # click on the module then expect the description and execute button to be visible click_on_module(@beef_session, module_category, module_name) - # expect the module description and the execute button to be visible + # expect the module description and the execute button to be visible expect(@beef_session).to have_content(module_description_sub, wait: PAGE_LOAD_TIMEOUT) expect(@beef_session).to have_content('Execute', wait: PAGE_LOAD_TIMEOUT) - # tidy up and collapse the category tree + # tidy up and collapse the category tree collapse_category_tree(@beef_session, module_category) end end diff --git a/spec/features/debug_modules_spec.rb b/spec/features/debug_modules_spec.rb index fddfc0893c..b4d375903a 100644 --- a/spec/features/debug_modules_spec.rb +++ b/spec/features/debug_modules_spec.rb @@ -31,7 +31,7 @@ module_yaml_data['beef']['module'].each do |module_key, module_value| module_category = module_value['category'] module_name = module_value['name'] - # some descriptions are too long and include html tags + # some descriptions are too long and include html tags module_description_sub = module_value['description'][0, 20] expect(@beef_session).to have_content(module_category, wait: PAGE_LOAD_TIMEOUT) @@ -47,13 +47,13 @@ expect(@beef_session).to have_content(module_description_sub, wait: PAGE_LOAD_TIMEOUT) expect(@beef_session).to have_content('Execute', wait: PAGE_LOAD_TIMEOUT) - # execute the module + # execute the module @beef_session.click_on('Execute') - # expect the module to make command output visible + # expect the module to make command output visible expect(@beef_session).to have_content('command 1', wait: PAGE_LOAD_TIMEOUT) - # click on the command section to display the output + # click on the command section to display the output @beef_session.all('div.x-grid3-cell-inner').each do |div| if div.text == 'command 1' div.click diff --git a/spec/requests/beef_test_spec.rb b/spec/requests/beef_test_spec.rb index 25a1f9b571..f290d7cdf9 100644 --- a/spec/requests/beef_test_spec.rb +++ b/spec/requests/beef_test_spec.rb @@ -37,7 +37,7 @@ expect(port_available?) # # Check if the tcp port is open expect(@session.has_content?('Hooked Browsers', wait: 10)) - # Log out of the session + # Log out of the session @sessoin = BeefTest.logout(@session) expect(@session.has_no_content?('Hooked Browsers', wait: 10)) expect(@session.has_content?('Authentication', wait: 10)) @@ -49,27 +49,27 @@ it 'saves a screenshot' do session = Capybara::Session.new(:selenium_headless) if session.nil? - # Ensure the new directory does not exist + # Ensure the new directory does not exist outputDir = '/tmp' directory = "#{outputDir}/#{SecureRandom.hex}/" expect(File.directory?(directory)).to be false - # Save the screenshot + # Save the screenshot BeefTest.save_screenshot(session, directory) - # Ensure the screenshot was saved + # Ensure the screenshot was saved expect(File.directory?(directory)).to be true screenshot_files = Dir.glob("#{directory}/*.png") expect(screenshot_files.empty?).to be false - # Ensure the screenshot file is not empty and clean up + # Ensure the screenshot file is not empty and clean up screenshot_files.each do |file| expect(File.size(file)).to be > 0 File.delete(file) end expect(Dir.glob("#{directory}/*.png").empty?).to be true - # Remove the directory + # Remove the directory Dir.delete(directory) expect(File.directory?(directory)).to be false end @@ -80,12 +80,12 @@ describe '.new_attacker' do it 'creates a new attacker session' do - # # Test setup + # # Test setup expect(session).not_to be_nil result = BeefTest.new_attacker(session) - # Test assertions + # Test assertions expect(result).to eq(session) expect(session.has_no_content?('Authentication', wait: 10)) expect(session.has_content?('Hooked Browsers', wait: 10)) @@ -95,14 +95,14 @@ describe '.new_victim' do it 'creates a new victim session' do - # Test setup + # Test setup allow(victim).to receive(:visit) expect(victim).not_to be_nil - # Test execution + # Test execution result = BeefTest.new_victim(victim) - # Test assertions + # Test assertions expect(victim).to have_received(:visit).with(VICTIM_URL) expect(result).to eq(victim) victim.reset_session! diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index b10b18b781..af16ca546f 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -171,7 +171,7 @@ def server_teardown(webdriver, server_pid, server_pids) end end -######################################## + ######################################## def reset_beef_db begin @@ -205,10 +205,10 @@ def configure_beef # Load the server def load_beef_extensions_and_modules - # Load BeEF extensions + # Load BeEF extensions BeEF::Extensions.load - # Load BeEF modules only if they are not already loaded + # Load BeEF modules only if they are not already loaded BeEF::Modules.load if @config.get('beef.module').nil? end diff --git a/spec/support/ui_support.rb b/spec/support/ui_support.rb index 195d2c1173..19b7ae3062 100644 --- a/spec/support/ui_support.rb +++ b/spec/support/ui_support.rb @@ -41,7 +41,7 @@ def navigate_to_hooked_browser(session, hooked_browser_text = nil) hooked_browser_text = '127.0.0.1' if hooked_browser_text.nil? expect(session).to have_content(hooked_browser_text, wait: BROWSER_HOOKING_TIMEOUT) - # click on the hooked browser in the leaf + # click on the hooked browser in the leaf session.all('a', text: hooked_browser_text)[1].click expect(session).to have_content('Commands', wait: PAGE_LOAD_TIMEOUT) end @@ -52,7 +52,7 @@ def navigate_to_category(session, category_name = nil) navigate_to_hooked_browser unless session.has_content?('Current Browser') - # ensure the command module tree is visible + # ensure the command module tree is visible session.click_on('Commands') expect(session).to have_content(category_name, wait: PAGE_LOAD_TIMEOUT) @@ -62,7 +62,7 @@ def navigate_to_category(session, category_name = nil) def expand_category_tree(session, category, module_name = nil) if category.is_a?(Array) category.each do |category_name| - # find the category element and scroll to it + # find the category element and scroll to it session.all('div', text: category_name).each do |element| begin element_text = element.text @@ -94,7 +94,7 @@ def expand_category_tree(session, category, module_name = nil) def collapse_category_tree(session, category) if category.is_a?(Array) category.reverse.each do |category_name| - # Collapse the sub-folder + # Collapse the sub-folder session.scroll_to(category_name) session.first(:link_or_button, category_name + ' ').click end @@ -105,10 +105,10 @@ def collapse_category_tree(session, category) end def click_on_module(session, category, module_name) - # expand the category tree to make the module visible + # expand the category tree to make the module visible expand_category_tree(session, category, module_name) - # click on the module in the expanded tree + # click on the module in the expanded tree session.scroll_to(module_name) expect(session).to have_content(module_name, wait: PAGE_LOAD_TIMEOUT) modules = session.all(:link_or_button, module_name) diff --git a/test/integration/tc_debug_modules.rb b/test/integration/tc_debug_modules.rb index 3ef20ee1c4..c5f7ba7885 100644 --- a/test/integration/tc_debug_modules.rb +++ b/test/integration/tc_debug_modules.rb @@ -145,7 +145,7 @@ def test_return_network_request # Test same-origin request (response code and content of secret_page.html) response = RestClient.post "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_debug_test_network}?token=#{@@token}", - #override only a few parameters, the other ones will have default values from modules's module.rb definition + #override only a few parameters, the other ones will have default values from modules's module.rb definition { 'domain' => ATTACK_DOMAIN, 'port' => '3000', 'path' => '/demos/secret_page.html' }.to_json, :content_type => :json, :accept => :json diff --git a/tools/rest_api_examples/lib/beef_rest_api.rb b/tools/rest_api_examples/lib/beef_rest_api.rb index b1bf391761..10d7e86b92 100644 --- a/tools/rest_api_examples/lib/beef_rest_api.rb +++ b/tools/rest_api_examples/lib/beef_rest_api.rb @@ -1,6 +1,6 @@ class BeefRestAPI -# initialize + # initialize def initialize proto = 'https', host = '127.0.0.1', port = '3000', user = 'beef', pass = 'beef' @user = user @pass = pass @@ -8,11 +8,11 @@ def initialize proto = 'https', host = '127.0.0.1', port = '3000', user = 'beef' @token = nil end -################################################################################ -### BeEF core API -################################################################################ + ################################################################################ + ### BeEF core API + ################################################################################ -# authenticate and get API token + # authenticate and get API token def auth print_verbose 'Retrieving authentication token' begin @@ -29,7 +29,7 @@ def auth end end -# get BeEF version + # get BeEF version def version begin response = RestClient.get "#{@url}server/version", { :params => { :token => @token } } @@ -41,7 +41,7 @@ def version end end -# get server mounts + # get server mounts def mounts begin response = RestClient.get "#{@url}server/mounts", { :params => { :token => @token } } @@ -53,7 +53,7 @@ def mounts end end -# get online hooked browsers + # get online hooked browsers def online_browsers begin print_verbose 'Retrieving online browsers' @@ -67,7 +67,7 @@ def online_browsers end end -# get offline hooked browsers + # get offline hooked browsers def offline_browsers begin print_verbose 'Retrieving offline browsers' @@ -81,7 +81,7 @@ def offline_browsers end end -# get hooked browser details by session + # get hooked browser details by session def browser_details session begin print_verbose "Retrieving browser details for hooked browser [session: #{session}]" @@ -95,7 +95,7 @@ def browser_details session end end -# delete a browser by session + # delete a browser by session def delete_browser session begin print_verbose "Removing hooked browser [session: #{session}]" @@ -107,7 +107,7 @@ def delete_browser session end end -# get BeEF logs + # get BeEF logs def logs begin print_verbose 'Retrieving logs' @@ -120,7 +120,7 @@ def logs end end -# get hooked browser logs by session + # get hooked browser logs by session def browser_logs session begin print_verbose "Retrieving browser logs [session: #{session}]" @@ -133,11 +133,11 @@ def browser_logs session end end -################################################################################ -### command module API -################################################################################ + ################################################################################ + ### command module API + ################################################################################ -# get command module categories + # get command module categories def categories begin print_verbose 'Retrieving module categories' @@ -150,7 +150,7 @@ def categories end end -# get command modules + # get command modules def modules begin print_verbose 'Retrieving modules' @@ -163,7 +163,7 @@ def modules end end -# get module id by module short name + # get module id by module short name def get_module_id mod_name print_verbose "Retrieving id for module [name: #{mod_name}]" @modules.each do |mod| @@ -180,7 +180,7 @@ def get_module_id mod_name nil end -# get command module details + # get command module details def module_details id begin print_verbose "Retrieving details for command module [id: #{id}]" @@ -193,7 +193,7 @@ def module_details id end end -# execute module + # execute module def execute_module session, mod_id, options print_verbose "Executing module [id: #{mod_id}, #{options}]" begin @@ -212,11 +212,11 @@ def execute_module session, mod_id, options end end -################################################################################ -### Metasploit API -################################################################################ + ################################################################################ + ### Metasploit API + ################################################################################ -# get metasploit version + # get metasploit version def msf_version begin response = RestClient.get "#{@url}msf/version", { :params => { :token => @token } } @@ -229,7 +229,7 @@ def msf_version end end -# get metasploit jobs + # get metasploit jobs def msf_jobs begin response = RestClient.get "#{@url}msf/jobs", { :params => { :token => @token } } @@ -242,7 +242,7 @@ def msf_jobs end end -# get metasploit job info + # get metasploit job info def msf_job_info id begin response = RestClient.get "#{@url}msf/job/#{id}/info", { :params => { :token => @token } } @@ -254,7 +254,7 @@ def msf_job_info id end end -# start metasploit payload handler + # start metasploit payload handler def msf_handler options print_verbose "Starting Metasploit payload handler [#{options}]" begin @@ -274,7 +274,7 @@ def msf_handler options end end -# stop metasploit job + # stop metasploit job def msf_job_stop id print_verbose "Stopping Metasploit job [id: #{id}]" begin @@ -291,11 +291,11 @@ def msf_job_stop id end end -################################################################################ -### Network API -################################################################################ + ################################################################################ + ### Network API + ################################################################################ -# get all network hosts + # get all network hosts def network_hosts_all begin print_verbose 'Retrieving all network hosts' @@ -308,7 +308,7 @@ def network_hosts_all end end -# get all network services + # get all network services def network_services_all begin print_verbose 'Retrieving all network services' @@ -321,7 +321,7 @@ def network_services_all end end -# get network hosts by session + # get network hosts by session def network_hosts session begin print_verbose "Retrieving network hosts for hooked browser [session: #{session}]" @@ -334,7 +334,7 @@ def network_hosts session end end -# get network services by session + # get network services by session def network_services session begin print_verbose "Retrieving network services for hooked browser [session: #{session}]" @@ -347,11 +347,11 @@ def network_services session end end -################################################################################ -### XssRays API -################################################################################ + ################################################################################ + ### XssRays API + ################################################################################ -# get all rays + # get all rays def xssrays_rays_all print_verbose 'Retrieving all rays' response = RestClient.get "#{@url}xssrays/rays", { :params => { :token => @token } } @@ -362,7 +362,7 @@ def xssrays_rays_all print_error "Could not retrieve rays: #{e.message}" end -# get rays by session + # get rays by session def xssrays_rays session print_verbose "Retrieving rays for hooked browser [session: #{session}]" response = RestClient.get "#{@url}xssrays/rays/#{session}", { :params => { :token => @token } } @@ -373,7 +373,7 @@ def xssrays_rays session print_error "Could not retrieve rays: #{e.message}" end -# get all scans + # get all scans def xssrays_scans_all print_verbose 'Retrieving all scans' response = RestClient.get "#{@url}xssrays/scans", { :params => { :token => @token } } @@ -384,7 +384,7 @@ def xssrays_scans_all print_error "Could not retrieve scans: #{e.message}" end -# get scans by session + # get scans by session def xssrays_scans session print_verbose "Retrieving scans for hooked browser [session: #{session}]" response = RestClient.get "#{@url}xssrays/scans/#{session}", { :params => { :token => @token } } @@ -395,11 +395,11 @@ def xssrays_scans session print_error "Could not retrieve scans: #{e.message}" end -################################################################################ -### DNS API -################################################################################ + ################################################################################ + ### DNS API + ################################################################################ -# get ruleset + # get ruleset def dns_ruleset begin print_verbose 'Retrieving DNS ruleset' @@ -412,7 +412,7 @@ def dns_ruleset end end -# add a rule + # add a rule def dns_add_rule(dns_pattern, dns_resource, dns_response) dns_response = [dns_response] if dns_response.is_a?(String) print_verbose "Adding DNS rule [pattern: #{dns_pattern}, resource: #{dns_resource}, response: #{dns_response}]" @@ -436,7 +436,7 @@ def dns_add_rule(dns_pattern, dns_resource, dns_response) print_error "Could not add DNS rule: #{e.message}" end -# get rule details + # get rule details def dns_get_rule(id) begin print_verbose "Retrieving DNS rule details [id: #{id}]" @@ -449,7 +449,7 @@ def dns_get_rule(id) end end -# delete a rule + # delete a rule def dns_delete_rule(id) response = RestClient.delete "#{@url}dns/rule/#{id}?token=#{@token}" details = JSON.parse(response.body) @@ -459,9 +459,9 @@ def dns_delete_rule(id) print_error "Could not delete DNS rule: #{e.message}" end -################################################################################ -### Autorun -################################################################################ + ################################################################################ + ### Autorun + ################################################################################ def autorun_rules print_verbose 'Retrieving Autorun rules' @@ -524,11 +524,11 @@ def autorun_run_rule_on_browser(rule_id, hb_id) print_error "Could not run Autorun rule #{rule_id}: #{e.message}" end -################################################################################ -### WebRTC -################################################################################ + ################################################################################ + ### WebRTC + ################################################################################ -# get webrtc status for hooked browser by session + # get webrtc status for hooked browser by session def webrtc_status id begin print_verbose "Retrieving status for hooked browser [id: #{id}]" @@ -541,11 +541,11 @@ def webrtc_status id end end -################################################################################ -### Social Engineering -################################################################################ + ################################################################################ + ### Social Engineering + ################################################################################ -# bind dropper to path + # bind dropper to path def bind(fname, path) print_verbose "Binding 'extensions/social_engineering/droppers/#{fname}' to '#{path}'" begin @@ -560,7 +560,7 @@ def bind(fname, path) end end -# clone page and bind to path + # clone page and bind to path def clone_page(url, path, use_existing, dns_spoof) print_verbose "Binding '#{url}' to '#{path}'" begin From ffe79765a44f55e54dbfa1f8cfdd1ae0f61069f2 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:27:02 +0530 Subject: [PATCH 11/85] rubocop --only Style/HashSyntax -a --- Gemfile | 2 +- Rakefile | 10 +-- extensions/webrtc/api/hook.rb | 4 +- extensions/webrtc/handlers.rb | 42 ++++----- extensions/webrtc/models/rtcmanage.rb | 8 +- spec/beef/extensions/dns_spec.rb | 54 ++++++------ spec/beef/extensions/network_spec.rb | 6 +- test/integration/tc_debug_modules.rb | 20 ++--- test/integration/tc_dns_rest.rb | 8 +- test/integration/tc_network_rest.rb | 28 +++--- .../integration/tc_social_engineering_rest.rb | 6 +- test/integration/tc_webrtc_rest.rb | 46 +++++----- tools/csrf_to_beef/csrf_to_beef | 4 +- tools/csrf_to_beef/lib/output.rb | 14 +-- tools/rest_api_examples/lib/beef_rest_api.rb | 86 +++++++++---------- 15 files changed, 169 insertions(+), 169 deletions(-) diff --git a/Gemfile b/Gemfile index 99b7992618..63ebde030a 100644 --- a/Gemfile +++ b/Gemfile @@ -17,7 +17,7 @@ gem 'uglifier', '~> 4.2' gem 'mime-types', '~> 3.7' gem 'execjs', '~> 2.10' gem 'ansi', '~> 1.5' -gem 'term-ansicolor', :require => 'term/ansicolor' +gem 'term-ansicolor', require: 'term/ansicolor' gem 'rubyzip', '~> 3.2' gem 'espeak-ruby', '~> 1.1.0' # Text-to-Voice gem 'rake', '~> 13.3' diff --git a/Rakefile b/Rakefile index 97c118847f..038928da85 100644 --- a/Rakefile +++ b/Rakefile @@ -5,7 +5,7 @@ # require 'rspec/core/rake_task' -task :default => ['short'] +task default: ['short'] RSpec::Core::RakeTask.new(:short) do |task| task.rspec_opts = ['--tag ~run_on_browserstack', '--tag ~run_on_long_tests'] @@ -122,7 +122,7 @@ end @beef_process_id = nil; @beef_config_file = 'tmp/rk_beef_conf.yaml'; -task :beef_start => 'beef' do +task beef_start: 'beef' do # read environment param for creds or use bad_fred test_user = ENV['TEST_BEEF_USER'] || 'bad_fred' test_pass = ENV['TEST_BEEF_PASS'] || 'bad_fred_no_access' @@ -167,7 +167,7 @@ end @msf_process_id = nil; -task :msf_start => '/tmp/msf-test/msfconsole' do +task msf_start: '/tmp/msf-test/msfconsole' do printf 'Starting MSF (wait 45 seconds)...' @msf_process_id = IO.popen('/tmp/msf-test/msfconsole -r test/thirdparty/msf/unit/BeEF.rc 2> /dev/null', 'w+') delays = [10, 7, 6, 5, 4, 3, 2, 2, 1, 1, 1, 0.5, 0.5, 0.5, 0.3, 0.2, 0.1, 0.1, 0.1, 0.05, 0.05] @@ -183,11 +183,11 @@ task :msf_stop do @msf_process_id.puts 'quit' end -task :msf_install => '/tmp/msf-test/msfconsole' do +task msf_install: '/tmp/msf-test/msfconsole' do # Handled by the 'test/msf-test/msfconsole' task. end -task :msf_update => '/tmp/msf-test/msfconsole' do +task msf_update: '/tmp/msf-test/msfconsole' do sh 'cd /tmp/msf-test;git pull' end diff --git a/extensions/webrtc/api/hook.rb b/extensions/webrtc/api/hook.rb index f8219a2805..dab85ed9e9 100644 --- a/extensions/webrtc/api/hook.rb +++ b/extensions/webrtc/api/hook.rb @@ -29,7 +29,7 @@ def requester_run(hb, body) rtcmanagementoutput = [] # Get all RTCSignals for this browser - BeEF::Core::Models::RtcSignal.where(:target_hooked_browser_id => hb.id, :has_sent => 'waiting').each { |h| + BeEF::Core::Models::RtcSignal.where(target_hooked_browser_id: hb.id, has_sent: 'waiting').each { |h| # output << self.requester_parse_db_request(h) rtcsignaloutput << h.signal h.has_sent = 'sent' @@ -37,7 +37,7 @@ def requester_run(hb, body) } # Get all RTCManagement messages for this browser - BeEF::Core::Models::RtcManage.where(:hooked_browser_id => hb.id, :has_sent => 'waiting').each {|h| + BeEF::Core::Models::RtcManage.where(hooked_browser_id: hb.id, has_sent: 'waiting').each {|h| rtcmanagementoutput << h.message h.has_sent = 'sent' h.save diff --git a/extensions/webrtc/handlers.rb b/extensions/webrtc/handlers.rb index 7a98bf893a..fdb03e6abb 100644 --- a/extensions/webrtc/handlers.rb +++ b/extensions/webrtc/handlers.rb @@ -35,18 +35,18 @@ def setup() (print_error 'Signal is null';return) if signal.nil? # validates that a hooked browser with the beef_hook token exists in the db - zombie_db = Z.first(:session => beef_hook) || nil + zombie_db = Z.first(session: beef_hook) || nil (print_error 'Invalid beefhook id: the hooked browser cannot be found in the database';return) if zombie_db.nil? # validates that a target browser with the target_beef_token exists in the db - target_zombie_db = Z.first(:id => target_beef_id) || nil + target_zombie_db = Z.first(id: target_beef_id) || nil (print_error 'Invalid targetbeefid: the target hooked browser cannot be found in the database';return) if target_zombie_db.nil? # save the results in the database signal = R.new( - :hooked_browser_id => zombie_db.id, - :target_hooked_browser_id => target_zombie_db.id, - :signal => signal + hooked_browser_id: zombie_db.id, + target_hooked_browser_id: target_zombie_db.id, + signal: signal ) signal.save @@ -79,11 +79,11 @@ def setup() (print_error 'Message is null';return) if message.nil? # validates that a hooked browser with the beef_hook token exists in the db - zombie_db = Z.first(:session => beef_hook) || nil + zombie_db = Z.first(session: beef_hook) || nil (print_error 'Invalid beefhook id: the hooked browser cannot be found in the database';return) if zombie_db.nil? # validates that a browser with the peerid exists in the db - peer_zombie_db = Z.first(:id => peer_id) || nil + peer_zombie_db = Z.first(id: peer_id) || nil (print_error 'Invalid peer_id: the peer hooked browser cannot be found in the database';return) if peer_zombie_db.nil? # Writes the event into the BeEF Logger @@ -93,52 +93,52 @@ def setup() puts "message = '" + message + "'" if (message == 'ICE Status: connected') # Find existing status message - stat = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => zombie_db.id, :target_hooked_browser_id => peer_zombie_db.id) || nil + stat = BeEF::Core::Models::Rtcstatus.first(hooked_browser_id: zombie_db.id, target_hooked_browser_id: peer_zombie_db.id) || nil unless stat.nil? stat.status = 'Connected' stat.updated_at = Time.now stat.save end - stat2 = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => peer_zombie_db.id, :target_hooked_browser_id => zombie_db.id) || nil + stat2 = BeEF::Core::Models::Rtcstatus.first(hooked_browser_id: peer_zombie_db.id, target_hooked_browser_id: zombie_db.id) || nil unless stat2.nil? stat2.status = 'Connected' stat2.updated_at = Time.now stat2.save end elsif (message.end_with?('disconnected')) - stat = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => zombie_db.id, :target_hooked_browser_id => peer_zombie_db.id) || nil + stat = BeEF::Core::Models::Rtcstatus.first(hooked_browser_id: zombie_db.id, target_hooked_browser_id: peer_zombie_db.id) || nil unless stat.nil? stat.status = 'Disconnected' stat.updated_at = Time.now stat.save end - stat2 = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => peer_zombie_db.id, :target_hooked_browser_id => zombie_db.id) || nil + stat2 = BeEF::Core::Models::Rtcstatus.first(hooked_browser_id: peer_zombie_db.id, target_hooked_browser_id: zombie_db.id) || nil unless stat2.nil? stat2.status = 'Disconnected' stat2.updated_at = Time.now stat2.save end elsif (message == 'Stayin alive') - stat = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => zombie_db.id, :target_hooked_browser_id => peer_zombie_db.id) || nil + stat = BeEF::Core::Models::Rtcstatus.first(hooked_browser_id: zombie_db.id, target_hooked_browser_id: peer_zombie_db.id) || nil unless stat.nil? stat.status = 'Stealthed!!' stat.updated_at = Time.now stat.save end - stat2 = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => peer_zombie_db.id, :target_hooked_browser_id => zombie_db.id) || nil + stat2 = BeEF::Core::Models::Rtcstatus.first(hooked_browser_id: peer_zombie_db.id, target_hooked_browser_id: zombie_db.id) || nil unless stat2.nil? stat2.status = 'Peer-controlled stealth-mode' stat2.updated_at = Time.now stat2.save end elsif (message == 'Coming out of stealth...') - stat = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => zombie_db.id, :target_hooked_browser_id => peer_zombie_db.id) || nil + stat = BeEF::Core::Models::Rtcstatus.first(hooked_browser_id: zombie_db.id, target_hooked_browser_id: peer_zombie_db.id) || nil unless stat.nil? stat.status = 'Connected' stat.updated_at = Time.now stat.save end - stat2 = BeEF::Core::Models::Rtcstatus.first(:hooked_browser_id => peer_zombie_db.id, :target_hooked_browser_id => zombie_db.id) || nil + stat2 = BeEF::Core::Models::Rtcstatus.first(hooked_browser_id: peer_zombie_db.id, target_hooked_browser_id: zombie_db.id) || nil unless stat2.nil? stat2.status = 'Connected' stat2.updated_at = Time.now @@ -147,12 +147,12 @@ def setup() elsif (message.start_with?('execcmd')) mod = /\(\/command\/(.*)\.js\)/.match(message)[1] resp = /Result:.(.*)/.match(message)[1] - stat = BeEF::Core::Models::Rtcmodulestatus.new(:hooked_browser_id => zombie_db.id, - :target_hooked_browser_id => peer_zombie_db.id, - :command_module_id => mod, - :status => resp, - :created_at => Time.now, - :updated_at => Time.now) + stat = BeEF::Core::Models::Rtcmodulestatus.new(hooked_browser_id: zombie_db.id, + target_hooked_browser_id: peer_zombie_db.id, + command_module_id: mod, + status: resp, + created_at: Time.now, + updated_at: Time.now) stat.save end diff --git a/extensions/webrtc/models/rtcmanage.rb b/extensions/webrtc/models/rtcmanage.rb index 458ea4fbd0..06d4eaa88c 100644 --- a/extensions/webrtc/models/rtcmanage.rb +++ b/extensions/webrtc/models/rtcmanage.rb @@ -18,25 +18,25 @@ def self.initiate(caller, receiver, verbosity = false) # Add the beef.webrtc.start() JavaScript call into the RtcManage table - this will be picked up by the browser on next hook.js poll # This is for the Receiver - r = BeEF::Core::Models::RtcManage.new(:hooked_browser_id => receiver, :message => "beef.webrtc.start(0,#{caller},JSON.stringify(#{turnservers}),JSON.stringify(#{stunservers}),#{verbosity});") + r = BeEF::Core::Models::RtcManage.new(hooked_browser_id: receiver, message: "beef.webrtc.start(0,#{caller},JSON.stringify(#{turnservers}),JSON.stringify(#{stunservers}),#{verbosity});") r.save! # This is the same beef.webrtc.start() JS call, but for the Caller - r = BeEF::Core::Models::RtcManage.new(:hooked_browser_id => caller, :message => "beef.webrtc.start(1,#{receiver},JSON.stringify(#{turnservers}),JSON.stringify(#{stunservers}),#{verbosity});") + r = BeEF::Core::Models::RtcManage.new(hooked_browser_id: caller, message: "beef.webrtc.start(1,#{receiver},JSON.stringify(#{turnservers}),JSON.stringify(#{stunservers}),#{verbosity});") r.save! end # Advises a browser to send an RTCDataChannel message to its peer # Similar to the initiate method, this loads up a JavaScript call to the beefrtcs[peerid].sendPeerMsg() function call def self.sendmsg(from, to, message) - r = BeEF::Core::Models::RtcManage.new(:hooked_browser_id => from, :message => "beefrtcs[#{to}].sendPeerMsg('#{message}');") + r = BeEF::Core::Models::RtcManage.new(hooked_browser_id: from, message: "beefrtcs[#{to}].sendPeerMsg('#{message}');") r.save! end # Gets the browser to run the beef.webrtc.status() JavaScript function # This JS function will return it's values to the /rtcmessage handler def self.status(id) - r = BeEF::Core::Models::RtcManage.new(:hooked_browser_id => id, :message => "beef.webrtc.status(#{id});") + r = BeEF::Core::Models::RtcManage.new(hooked_browser_id: id, message: "beef.webrtc.status(#{id});") r.save! end diff --git a/spec/beef/extensions/dns_spec.rb b/spec/beef/extensions/dns_spec.rb index 4fed5eaad5..e92306fd08 100644 --- a/spec/beef/extensions/dns_spec.rb +++ b/spec/beef/extensions/dns_spec.rb @@ -44,9 +44,9 @@ response = '1.2.3.4' expect { id = @dns.add_rule( - :pattern => 'foo.bar', - :resource => IN::A, - :response => [response]) do |transaction| + pattern: 'foo.bar', + resource: IN::A, + response: [response]) do |transaction| transaction.respond!(response) end }.to_not raise_error @@ -58,9 +58,9 @@ response = '9.9.9.9' expect { id = @dns.add_rule( - :pattern => %r{i\.(love|hate)\.beef\.com?}, - :resource => IN::A, - :response => [response]) do |transaction| + pattern: %r{i\.(love|hate)\.beef\.com?}, + resource: IN::A, + response: [response]) do |transaction| transaction.respond!(response) end }.to_not raise_error @@ -78,9 +78,9 @@ id = nil expect { id = @dns.add_rule( - :pattern => %r{i\.(love|hate)\.beef\.com?}, - :resource => IN::A, - :response => [response]) do |transaction| + pattern: %r{i\.(love|hate)\.beef\.com?}, + resource: IN::A, + response: [response]) do |transaction| transaction.respond!(response) end }.to_not raise_error @@ -99,27 +99,27 @@ expect { id = @dns.add_rule( - :pattern => pattern, - :resource => IN::A, - :response => [response]) do |transaction| + pattern: pattern, + resource: IN::A, + response: [response]) do |transaction| transaction.respond!(response) end }.to_not raise_error expect { same_id = @dns.add_rule( - :pattern => pattern, - :resource => IN::A, - :response => [response]) do |transaction| + pattern: pattern, + resource: IN::A, + response: [response]) do |transaction| transaction.respond!(response) end }.to_not raise_error expect { same_id = @dns.add_rule( - :pattern => pattern, - :resource => IN::A, - :response => [response]) do |transaction| + pattern: pattern, + resource: IN::A, + response: [response]) do |transaction| transaction.respond!(response) end }.to_not raise_error @@ -156,9 +156,9 @@ expect { id = @dns.add_rule( - :pattern => pattern, - :resource => IN::A, - :response => [response]) do |transaction| + pattern: pattern, + resource: IN::A, + response: [response]) do |transaction| transaction.respond!(response) end }.to_not raise_error @@ -191,9 +191,9 @@ expect { id = @dns.add_rule( - :pattern => pattern, - :resource => IN::A, - :response => [response]) do |transaction| + pattern: pattern, + resource: IN::A, + response: [response]) do |transaction| transaction.respond!(response) end }.to_not raise_error @@ -219,9 +219,9 @@ rules.each do |r| @dns.add_rule( - :pattern => r[:pattern], - :resource => IN::A, - :response => r[:response] + pattern: r[:pattern], + resource: IN::A, + response: r[:response] ) end diff --git a/spec/beef/extensions/network_spec.rb b/spec/beef/extensions/network_spec.rb index be759ab9df..5265b159b0 100644 --- a/spec/beef/extensions/network_spec.rb +++ b/spec/beef/extensions/network_spec.rb @@ -10,21 +10,21 @@ it 'add good local host' do expect { - BeEF::Core::Models::NetworkHost.create(:hooked_browser_id => '1234', :ip => '127.0.0.1') + BeEF::Core::Models::NetworkHost.create(hooked_browser_id: '1234', ip: '127.0.0.1') }.to_not raise_error expect(BeEF::Core::Models::NetworkHost.where(hooked_browser_id: '1234', ip: '127.0.0.1')).to_not be_empty end it 'add good not local host' do expect { - BeEF::Core::Models::NetworkHost.create(:hooked_browser_id => '12', :ip => '192.168.1.2') + BeEF::Core::Models::NetworkHost.create(hooked_browser_id: '12', ip: '192.168.1.2') }.to_not raise_error expect(BeEF::Core::Models::NetworkHost.where(hooked_browser_id: '12', ip: '192.168.1.2')).to_not be_empty end it 'add good service' do expect { - BeEF::Core::Models::NetworkService.create(:hooked_browser_id => '1234', :proto => 'http', :ip => '127.0.0.1', :port => 80, :ntype => 'Apache') + BeEF::Core::Models::NetworkService.create(hooked_browser_id: '1234', proto: 'http', ip: '127.0.0.1', port: 80, ntype: 'Apache') }.to_not raise_error expect(BeEF::Core::Models::NetworkService.where(hooked_browser_id: '1234', ip: '127.0.0.1')).to_not be_empty diff --git a/test/integration/tc_debug_modules.rb b/test/integration/tc_debug_modules.rb index c5f7ba7885..03f389f65f 100644 --- a/test/integration/tc_debug_modules.rb +++ b/test/integration/tc_debug_modules.rb @@ -28,8 +28,8 @@ def test_1_restful_auth response = RestClient.post "#{RESTAPI_ADMIN}/login", { 'username' => "#{BEEF_USER}", 'password' => "#{BEEF_PASSWD}" }.to_json, - :content_type => :json, - :accept => :json + content_type: :json, + accept: :json assert_equal 200, response.code assert_not_nil response.body result = JSON.parse(response.body) @@ -42,7 +42,7 @@ def test_1_restful_auth def test_2_restful_hooks BeefTest.new_victim sleep 5.0 - response = RestClient.get "#{RESTAPI_HOOKS}", { :params => { :token => @@token } } + response = RestClient.get "#{RESTAPI_HOOKS}", { params: { token: @@token } } assert_equal 200, response.code assert_not_nil response.body result = JSON.parse(response.body) @@ -52,7 +52,7 @@ def test_2_restful_hooks # Test RESTful API modules handler, retrieving the IDs of the 3 debug modules currently in the framework def test_3_restful_modules - response = RestClient.get "#{RESTAPI_MODULES}", { :params => { :token => @@token } } + response = RestClient.get "#{RESTAPI_MODULES}", { params: { token: @@token } } assert_equal 200, response.code assert_not_nil response.body result = JSON.parse(response.body) @@ -80,8 +80,8 @@ def test_return_long_string response = RestClient.post "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_debug_long_string}?token=#{@@token}", { 'repeat_string' => repeat_string, 'repeat' => repeat_count }.to_json, - :content_type => :json, - :accept => :json + content_type: :json, + accept: :json assert_equal 200, response.code assert_not_nil response.body result = JSON.parse(response.body) @@ -112,8 +112,8 @@ def test_return_long_string def test_return_ascii_chars response = RestClient.post "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_debug_ascii_chars}?token=#{@@token}", {}.to_json, # module does not expect any input - :content_type => :json, - :accept => :json + content_type: :json, + accept: :json assert_equal 200, response.code assert_not_nil response.body result = JSON.parse(response.body) @@ -147,8 +147,8 @@ def test_return_network_request response = RestClient.post "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_debug_test_network}?token=#{@@token}", #override only a few parameters, the other ones will have default values from modules's module.rb definition { 'domain' => ATTACK_DOMAIN, 'port' => '3000', 'path' => '/demos/secret_page.html' }.to_json, - :content_type => :json, - :accept => :json + content_type: :json, + accept: :json assert_equal 200, response.code assert_not_nil response.body result = JSON.parse(response.body) diff --git a/test/integration/tc_dns_rest.rb b/test/integration/tc_dns_rest.rb index 866c2f89f2..4a6483ac1d 100644 --- a/test/integration/tc_dns_rest.rb +++ b/test/integration/tc_dns_rest.rb @@ -13,8 +13,8 @@ class TC_DnsRest < Test::Unit::TestCase class << self def startup - json = { :username => BEEF_USER, :password => BEEF_PASSWD }.to_json - @@headers = { :content_type => :json, :accept => :json } + json = { username: BEEF_USER, password: BEEF_PASSWD }.to_json + @@headers = { content_type: :json, accept: :json } response = RestClient.post("#{RESTAPI_ADMIN}/login", json, @@ -46,7 +46,7 @@ def test_1_add_rule_good resource = 'A' dns_response = ['1.2.3.4'] - json = { :pattern => pattern, :resource => resource, :response => dns_response }.to_json + json = { pattern: pattern, resource: resource, response: dns_response }.to_json rest_response = RestClient.post("#{RESTAPI_DNS}/rule?token=#{@@token}", json, @@ -76,7 +76,7 @@ def test_2_add_rule_bad resource = 'A' dns_response = ['1.1.1.1'] - hash = { :pattern => pattern, :resource => resource, :response => dns_response } + hash = { pattern: pattern, resource: resource, response: dns_response } # Test that an empty "pattern" key returns 400 assert_raise RestClient::BadRequest do diff --git a/test/integration/tc_network_rest.rb b/test/integration/tc_network_rest.rb index 8cbe3fd5ca..4ce3f7863f 100644 --- a/test/integration/tc_network_rest.rb +++ b/test/integration/tc_network_rest.rb @@ -17,8 +17,8 @@ def startup $:.unshift($root_dir) # login and get api token - json = { :username => BEEF_USER, :password => BEEF_PASSWD }.to_json - @@headers = { :content_type => :json, :accept => :json } + json = { username: BEEF_USER, password: BEEF_PASSWD }.to_json + @@headers = { content_type: :json, accept: :json } response = RestClient.post("#{RESTAPI_ADMIN}/login", json, @@ -30,12 +30,12 @@ def startup # create hooked browser and get session id BeefTest.new_victim sleep 5.0 - response = RestClient.get "#{RESTAPI_HOOKS}", { :params => { :token => @@token } } + response = RestClient.get "#{RESTAPI_HOOKS}", { params: { token: @@token } } result = JSON.parse(response.body) @@hb_session = result['hooked-browsers']['online']['0']['session'] # Retrieve Port Scanner module command ID - response = RestClient.get "#{RESTAPI_MODULES}", { :params => { :token => @@token } } + response = RestClient.get "#{RESTAPI_MODULES}", { params: { token: @@token } } result = JSON.parse(response.body) result.each do |mod| if mod[1]['class'] == 'Port_scanner' @@ -53,8 +53,8 @@ def startup 'opentimeout' => 2500, 'delay' => 600, 'debug' => false }.to_json, - :content_type => :json, - :accept => :json + content_type: :json, + accept: :json result = JSON.parse(response.body) success = result['success'] @@cmd_id = result['command_id'] @@ -89,7 +89,7 @@ def test_get_all_hosts def test_get_hosts_valid_session rest_response = nil assert_nothing_raised do - rest_response = RestClient.get("#{RESTAPI_NETWORK}/hosts/#{@@hb_session}", :params => { :token => @@token }) + rest_response = RestClient.get("#{RESTAPI_NETWORK}/hosts/#{@@hb_session}", params: { token: @@token }) end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -107,7 +107,7 @@ def test_get_hosts_invalid_session session_id = 'z' rest_response = nil assert_nothing_raised do - rest_response = RestClient.get("#{RESTAPI_NETWORK}/hosts/#{session_id}", :params => { :token => @@token }) + rest_response = RestClient.get("#{RESTAPI_NETWORK}/hosts/#{session_id}", params: { token: @@token }) end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -120,7 +120,7 @@ def test_get_host_valid_id id = 1 rest_response = nil assert_nothing_raised do - rest_response = RestClient.get("#{RESTAPI_NETWORK}/host/#{id}", :params => { :token => @@token }) + rest_response = RestClient.get("#{RESTAPI_NETWORK}/host/#{id}", params: { token: @@token }) end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -132,7 +132,7 @@ def test_get_host_valid_id def test_get_hosts_invalid_id id = 'z' assert_raise RestClient::ResourceNotFound do - RestClient.get("#{RESTAPI_NETWORK}/host/#{id}", :params => { :token => @@token }) + RestClient.get("#{RESTAPI_NETWORK}/host/#{id}", params: { token: @@token }) end end @@ -151,7 +151,7 @@ def test_get_all_services def test_get_services_valid_session rest_response = nil assert_nothing_raised do - rest_response = RestClient.get("#{RESTAPI_NETWORK}/services/#{@@hb_session}", :params => { :token => @@token }) + rest_response = RestClient.get("#{RESTAPI_NETWORK}/services/#{@@hb_session}", params: { token: @@token }) end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -169,7 +169,7 @@ def test_get_services_invalid_session session_id = 'z' rest_response = nil assert_nothing_raised do - rest_response = RestClient.get("#{RESTAPI_NETWORK}/services/#{session_id}", :params => { :token => @@token }) + rest_response = RestClient.get("#{RESTAPI_NETWORK}/services/#{session_id}", params: { token: @@token }) end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -182,7 +182,7 @@ def test_get_service_valid_id id = 1 rest_response = nil assert_nothing_raised do - rest_response = RestClient.get("#{RESTAPI_NETWORK}/service/#{id}", :params => { :token => @@token }) + rest_response = RestClient.get("#{RESTAPI_NETWORK}/service/#{id}", params: { token: @@token }) end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -194,7 +194,7 @@ def test_get_service_valid_id def test_get_services_invalid_id id = 'z' assert_raise RestClient::ResourceNotFound do - RestClient.get("#{RESTAPI_NETWORK}/service/#{id}", :params => { :token => @@token }) + RestClient.get("#{RESTAPI_NETWORK}/service/#{id}", params: { token: @@token }) end end diff --git a/test/integration/tc_social_engineering_rest.rb b/test/integration/tc_social_engineering_rest.rb index 132b07c78c..a37bce2174 100644 --- a/test/integration/tc_social_engineering_rest.rb +++ b/test/integration/tc_social_engineering_rest.rb @@ -15,8 +15,8 @@ class << self # Login to API before performing any tests def startup - json = { :username => BEEF_USER, :password => BEEF_PASSWD }.to_json - @@headers = { :content_type => :json, :accept => :json } + json = { username: BEEF_USER, password: BEEF_PASSWD }.to_json + @@headers = { content_type: :json, accept: :json } response = RestClient.post("#{RESTAPI_ADMIN}/login", json, @@ -48,7 +48,7 @@ def test_1_dns_spoof mount = '/beefproject' dns_spoof = true - json = { :url => url, :mount => mount, :dns_spoof => dns_spoof }.to_json + json = { url: url, mount: mount, dns_spoof: dns_spoof }.to_json domain = url.gsub(%r{^https?://}, '') diff --git a/test/integration/tc_webrtc_rest.rb b/test/integration/tc_webrtc_rest.rb index e6dbd974f3..bf2b133a01 100644 --- a/test/integration/tc_webrtc_rest.rb +++ b/test/integration/tc_webrtc_rest.rb @@ -15,8 +15,8 @@ class << self # Login to API before performing any tests - and fetch config too def startup - json = { :username => BEEF_USER, :password => BEEF_PASSWD }.to_json - @@headers = { :content_type => :json, :accept => :json } + json = { username: BEEF_USER, password: BEEF_PASSWD }.to_json + @@headers = { content_type: :json, accept: :json } response = RestClient.post("#{RESTAPI_ADMIN}/login", json, @@ -44,8 +44,8 @@ def startup sleep 8.0 # Fetch last online browsers' ids - rest_response = RestClient.get "#{RESTAPI_HOOKS}", { :params => { - :token => @@token } } + rest_response = RestClient.get "#{RESTAPI_HOOKS}", { params: { + token: @@token } } result = JSON.parse(rest_response.body) browsers = result['hooked-browsers']['online'] browsers.each_with_index do |elem, index| @@ -72,8 +72,8 @@ def test_1_webrtc_check_for_two_hooked_browsers rest_response = nil assert_nothing_raised do - rest_response = RestClient.get "#{RESTAPI_HOOKS}", { :params => { - :token => @@token } } + rest_response = RestClient.get "#{RESTAPI_HOOKS}", { params: { + token: @@token } } end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -88,7 +88,7 @@ def test_2_webrtc_establishing_p2p rest_response = nil assert_nothing_raised do rest_response = RestClient.post("#{RESTAPI_WEBRTC}/go?token=#{@@token}", - { :from => @@victim1id, :to => @@victim2id, :verbose => 'true' }.to_json, + { from: @@victim1id, to: @@victim2id, verbose: 'true' }.to_json, @@headers) end check_rest_response(rest_response) @@ -99,8 +99,8 @@ def test_2_webrtc_establishing_p2p rest_response = nil assert_nothing_raised do - rest_response = RestClient.get "#{RESTAPI_LOGS}", { :params => { - :token => @@token } } + rest_response = RestClient.get "#{RESTAPI_LOGS}", { params: { + token: @@token } } end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -124,8 +124,8 @@ def test_3_webrtc_send_msg # assumes test 2 has run rest_response = nil assert_nothing_raised do rest_response = RestClient.post("#{RESTAPI_WEBRTC}/msg?token=#{@@token}", - { :from => @@victim1id, :to => @@victim2id, - :message => 'RTC test message' }.to_json, + { from: @@victim1id, to: @@victim2id, + message: 'RTC test message' }.to_json, @@headers) end check_rest_response(rest_response) @@ -136,8 +136,8 @@ def test_3_webrtc_send_msg # assumes test 2 has run rest_response = nil assert_nothing_raised do - rest_response = RestClient.get "#{RESTAPI_LOGS}", { :params => { - :token => @@token } } + rest_response = RestClient.get "#{RESTAPI_LOGS}", { params: { + token: @@token } } end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -162,8 +162,8 @@ def test_4_webrtc_stealthmode # assumes test 2 has run # Test our two browsers are still online rest_response = nil assert_nothing_raised do - rest_response = RestClient.get "#{RESTAPI_HOOKS}", { :params => { - :token => @@token } } + rest_response = RestClient.get "#{RESTAPI_HOOKS}", { params: { + token: @@token } } end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -184,8 +184,8 @@ def test_4_webrtc_stealthmode # assumes test 2 has run rest_response = nil assert_nothing_raised do rest_response = RestClient.post("#{RESTAPI_WEBRTC}/msg?token=#{@@token}", - { :from => @@victim1id, :to => @@victim2id, - :message => '!gostealth' }.to_json, + { from: @@victim1id, to: @@victim2id, + message: '!gostealth' }.to_json, @@headers) end check_rest_response(rest_response) @@ -197,8 +197,8 @@ def test_4_webrtc_stealthmode # assumes test 2 has run # Test that the browser is now offline rest_response = nil assert_nothing_raised do - rest_response = RestClient.get "#{RESTAPI_HOOKS}", { :params => { - :token => @@token } } + rest_response = RestClient.get "#{RESTAPI_HOOKS}", { params: { + token: @@token } } end check_rest_response(rest_response) result = JSON.parse(rest_response.body) @@ -213,8 +213,8 @@ def test_4_webrtc_stealthmode # assumes test 2 has run rest_response = nil assert_nothing_raised do rest_response = RestClient.post("#{RESTAPI_WEBRTC}/msg?token=#{@@token}", - { :from => @@victim1id, :to => @@victim2id, - :message => '!endstealth' }.to_json, + { from: @@victim1id, to: @@victim2id, + message: '!endstealth' }.to_json, @@headers) end check_rest_response(rest_response) @@ -226,8 +226,8 @@ def test_4_webrtc_stealthmode # assumes test 2 has run # Test that the browser is now online rest_response = nil assert_nothing_raised do - rest_response = RestClient.get "#{RESTAPI_HOOKS}", { :params => { - :token => @@token } } + rest_response = RestClient.get "#{RESTAPI_HOOKS}", { params: { + token: @@token } } end check_rest_response(rest_response) result = JSON.parse(rest_response.body) diff --git a/tools/csrf_to_beef/csrf_to_beef b/tools/csrf_to_beef/csrf_to_beef index 743e65f020..c09ea0aadf 100755 --- a/tools/csrf_to_beef/csrf_to_beef +++ b/tools/csrf_to_beef/csrf_to_beef @@ -156,7 +156,7 @@ def get_options_from_url(url, method, postdata, mname) end end end - return { :target_url=>target_url, :method=>method, :enctype=>enctype, :options=>options } + return { target_url: target_url, method: method, enctype: enctype, options: options } end # @@ -224,7 +224,7 @@ def get_options_from_burp_file(fname, mname) end end end - return { :target_url=>target_url, :method=>method, :enctype=>enctype, :options=>options } + return { target_url: target_url, method: method, enctype: enctype, options: options } end # diff --git a/tools/csrf_to_beef/lib/output.rb b/tools/csrf_to_beef/lib/output.rb index b2d33d65a2..71f92e1583 100644 --- a/tools/csrf_to_beef/lib/output.rb +++ b/tools/csrf_to_beef/lib/output.rb @@ -6,13 +6,13 @@ def colorize(color_code) "\e[#{color_code}m#{self}\e[0m" end - { :red => 31, - :green => 32, - :yellow => 33, - :blue => 34, - :pink => 35, - :cyan => 36, - :white => 37 + { red: 31, + green: 32, + yellow: 33, + blue: 34, + pink: 35, + cyan: 36, + white: 37 }.each { |color, code| define_method(color) { colorize(code) } } diff --git a/tools/rest_api_examples/lib/beef_rest_api.rb b/tools/rest_api_examples/lib/beef_rest_api.rb index 10d7e86b92..3422a079b6 100644 --- a/tools/rest_api_examples/lib/beef_rest_api.rb +++ b/tools/rest_api_examples/lib/beef_rest_api.rb @@ -19,8 +19,8 @@ def auth response = RestClient.post "#{@url}admin/login", { 'username' => "#{@user}", 'password' => "#{@pass}" }.to_json, - :content_type => :json, - :accept => :json + content_type: :json, + accept: :json result = JSON.parse(response.body) @token = result['token'] print_good "Retrieved RESTful API token: #{@token}" @@ -32,7 +32,7 @@ def auth # get BeEF version def version begin - response = RestClient.get "#{@url}server/version", { :params => { :token => @token } } + response = RestClient.get "#{@url}server/version", { params: { token: @token } } result = JSON.parse(response.body) print_good "Retrieved BeEF version: #{result['version']}" result['version'] @@ -44,7 +44,7 @@ def version # get server mounts def mounts begin - response = RestClient.get "#{@url}server/mounts", { :params => { :token => @token } } + response = RestClient.get "#{@url}server/mounts", { params: { token: @token } } result = JSON.parse(response.body) print_good "Retrieved BeEF server mounts: #{result['mounts']}" result['mounts'] @@ -57,7 +57,7 @@ def mounts def online_browsers begin print_verbose 'Retrieving online browsers' - response = RestClient.get "#{@url}hooks", { :params => { :token => @token } } + response = RestClient.get "#{@url}hooks", { params: { token: @token } } result = JSON.parse(response.body) browsers = result['hooked-browsers']['online'] print_good "Retrieved online browser list [#{browsers.size} online]" @@ -71,7 +71,7 @@ def online_browsers def offline_browsers begin print_verbose 'Retrieving offline browsers' - response = RestClient.get "#{@url}hooks", { :params => { :token => @token } } + response = RestClient.get "#{@url}hooks", { params: { token: @token } } result = JSON.parse(response.body) browsers = result['hooked-browsers']['offline'] print_good "Retrieved offline browser list [#{browsers.size} offline]" @@ -85,7 +85,7 @@ def offline_browsers def browser_details session begin print_verbose "Retrieving browser details for hooked browser [session: #{session}]" - response = RestClient.get "#{@url}browserdetails/#{session}", { :params => { :token => @token } } + response = RestClient.get "#{@url}browserdetails/#{session}", { params: { token: @token } } result = JSON.parse(response.body) details = result['details'] print_good "Retrieved #{details.size} browser details" @@ -99,7 +99,7 @@ def browser_details session def delete_browser session begin print_verbose "Removing hooked browser [session: #{session}]" - response = RestClient.get "#{@url}hooks/#{session}/delete", { :params => { :token => @token } } + response = RestClient.get "#{@url}hooks/#{session}/delete", { params: { token: @token } } print_good "Removed browser [session: #{session}]" if response.code == 200 response rescue => e @@ -111,7 +111,7 @@ def delete_browser session def logs begin print_verbose 'Retrieving logs' - response = RestClient.get "#{@url}logs", { :params => { :token => @token } } + response = RestClient.get "#{@url}logs", { params: { token: @token } } logs = JSON.parse(response.body) print_good "Retrieved #{logs['logs_count']} log entries" logs @@ -124,7 +124,7 @@ def logs def browser_logs session begin print_verbose "Retrieving browser logs [session: #{session}]" - response = RestClient.get "#{@url}logs/#{session}", { :params => { :token => @token } } + response = RestClient.get "#{@url}logs/#{session}", { params: { token: @token } } logs = JSON.parse(response.body) print_good "Retrieved #{logs['logs'].size} browser logs" logs @@ -141,7 +141,7 @@ def browser_logs session def categories begin print_verbose 'Retrieving module categories' - response = RestClient.get "#{@url}categories", { :params => { :token => @token } } + response = RestClient.get "#{@url}categories", { params: { token: @token } } categories = JSON.parse(response.body) print_good "Retrieved #{categories.size} module categories" categories @@ -154,7 +154,7 @@ def categories def modules begin print_verbose 'Retrieving modules' - response = RestClient.get "#{@url}modules", { :params => { :token => @token } } + response = RestClient.get "#{@url}modules", { params: { token: @token } } @modules = JSON.parse(response.body) print_good "Retrieved #{@modules.size} available command modules" @modules @@ -184,7 +184,7 @@ def get_module_id mod_name def module_details id begin print_verbose "Retrieving details for command module [id: #{id}]" - response = RestClient.get "#{@url}modules/#{id}", { :params => { :token => @token } } + response = RestClient.get "#{@url}modules/#{id}", { params: { token: @token } } details = JSON.parse(response.body) print_good "Retrieved details for module [#{details['name']}]" details @@ -198,8 +198,8 @@ def execute_module session, mod_id, options print_verbose "Executing module [id: #{mod_id}, #{options}]" begin response = RestClient.post "#{@url}modules/#{session}/#{mod_id}?token=#{@token}", options.to_json, - :content_type => :json, - :accept => :json + content_type: :json, + accept: :json result = JSON.parse(response.body) if result['success'] == 'true' print_good "Executed module [id: #{mod_id}]" @@ -219,7 +219,7 @@ def execute_module session, mod_id, options # get metasploit version def msf_version begin - response = RestClient.get "#{@url}msf/version", { :params => { :token => @token } } + response = RestClient.get "#{@url}msf/version", { params: { token: @token } } result = JSON.parse(response.body) version = result['version']['version'] print_good "Retrieved Metasploit version: #{version}" @@ -232,7 +232,7 @@ def msf_version # get metasploit jobs def msf_jobs begin - response = RestClient.get "#{@url}msf/jobs", { :params => { :token => @token } } + response = RestClient.get "#{@url}msf/jobs", { params: { token: @token } } result = JSON.parse(response.body) jobs = result['jobs'] print_good "Retrieved job list [#{jobs.size} jobs]" @@ -245,7 +245,7 @@ def msf_jobs # get metasploit job info def msf_job_info id begin - response = RestClient.get "#{@url}msf/job/#{id}/info", { :params => { :token => @token } } + response = RestClient.get "#{@url}msf/job/#{id}/info", { params: { token: @token } } details = JSON.parse(response.body) print_good "Retrieved job information [id: #{id}]" details @@ -259,8 +259,8 @@ def msf_handler options print_verbose "Starting Metasploit payload handler [#{options}]" begin response = RestClient.post "#{@url}msf/handler?token=#{@token}", options.to_json, - :content_type => :json, - :accept => :json + content_type: :json, + accept: :json result = JSON.parse(response.body) job_id = result['id'] if job_id.nil? @@ -278,7 +278,7 @@ def msf_handler options def msf_job_stop id print_verbose "Stopping Metasploit job [id: #{id}]" begin - response = RestClient.get "#{@url}msf/job/#{id}/stop", { :params => { :token => @token } } + response = RestClient.get "#{@url}msf/job/#{id}/stop", { params: { token: @token } } result = JSON.parse(response.body) if result['success'].nil? print_error "Could not stop Metasploit job [id: #{id}]: No such job ?" @@ -299,7 +299,7 @@ def msf_job_stop id def network_hosts_all begin print_verbose 'Retrieving all network hosts' - response = RestClient.get "#{@url}network/hosts", { :params => { :token => @token } } + response = RestClient.get "#{@url}network/hosts", { params: { token: @token } } details = JSON.parse(response.body) print_good "Retrieved #{details['count']} network hosts" details @@ -312,7 +312,7 @@ def network_hosts_all def network_services_all begin print_verbose 'Retrieving all network services' - response = RestClient.get "#{@url}network/services", { :params => { :token => @token } } + response = RestClient.get "#{@url}network/services", { params: { token: @token } } details = JSON.parse(response.body) print_good "Retrieved #{details['count']} network services" details @@ -325,7 +325,7 @@ def network_services_all def network_hosts session begin print_verbose "Retrieving network hosts for hooked browser [session: #{session}]" - response = RestClient.get "#{@url}network/hosts/#{session}", { :params => { :token => @token } } + response = RestClient.get "#{@url}network/hosts/#{session}", { params: { token: @token } } details = JSON.parse(response.body) print_good "Retrieved #{details['count']} network hosts" details @@ -338,7 +338,7 @@ def network_hosts session def network_services session begin print_verbose "Retrieving network services for hooked browser [session: #{session}]" - response = RestClient.get "#{@url}network/services/#{session}", { :params => { :token => @token } } + response = RestClient.get "#{@url}network/services/#{session}", { params: { token: @token } } details = JSON.parse(response.body) print_good "Retrieved #{details['count']} network services" details @@ -354,7 +354,7 @@ def network_services session # get all rays def xssrays_rays_all print_verbose 'Retrieving all rays' - response = RestClient.get "#{@url}xssrays/rays", { :params => { :token => @token } } + response = RestClient.get "#{@url}xssrays/rays", { params: { token: @token } } details = JSON.parse(response.body) print_good "Retrieved #{details['count']} rays" details @@ -365,7 +365,7 @@ def xssrays_rays_all # get rays by session def xssrays_rays session print_verbose "Retrieving rays for hooked browser [session: #{session}]" - response = RestClient.get "#{@url}xssrays/rays/#{session}", { :params => { :token => @token } } + response = RestClient.get "#{@url}xssrays/rays/#{session}", { params: { token: @token } } details = JSON.parse(response.body) print_good "Retrieved #{details['count']} rays" details @@ -376,7 +376,7 @@ def xssrays_rays session # get all scans def xssrays_scans_all print_verbose 'Retrieving all scans' - response = RestClient.get "#{@url}xssrays/scans", { :params => { :token => @token } } + response = RestClient.get "#{@url}xssrays/scans", { params: { token: @token } } details = JSON.parse(response.body) print_good "Retrieved #{details['count']} scans" details @@ -387,7 +387,7 @@ def xssrays_scans_all # get scans by session def xssrays_scans session print_verbose "Retrieving scans for hooked browser [session: #{session}]" - response = RestClient.get "#{@url}xssrays/scans/#{session}", { :params => { :token => @token } } + response = RestClient.get "#{@url}xssrays/scans/#{session}", { params: { token: @token } } details = JSON.parse(response.body) print_good "Retrieved #{details['count']} scans" details @@ -403,7 +403,7 @@ def xssrays_scans session def dns_ruleset begin print_verbose 'Retrieving DNS ruleset' - response = RestClient.get "#{@url}dns/ruleset", { :params => { :token => @token } } + response = RestClient.get "#{@url}dns/ruleset", { params: { token: @token } } details = JSON.parse(response.body) print_good "Retrieved #{details['count']} rules" details @@ -420,8 +420,8 @@ def dns_add_rule(dns_pattern, dns_resource, dns_response) 'pattern' => dns_pattern, 'resource' => dns_resource, 'response' => dns_response }.to_json, - :content_type => :json, - :accept => :json + content_type: :json, + accept: :json details = JSON.parse(response.body) rule_id = details['id'] @@ -440,7 +440,7 @@ def dns_add_rule(dns_pattern, dns_resource, dns_response) def dns_get_rule(id) begin print_verbose "Retrieving DNS rule details [id: #{id}]" - response = RestClient.get "#{@url}dns/rule/#{id}", { :params => { :token => @token } } + response = RestClient.get "#{@url}dns/rule/#{id}", { params: { token: @token } } details = JSON.parse(response.body) print_good "Retrieved rule [id: #{details['id']}]" details @@ -465,7 +465,7 @@ def dns_delete_rule(id) def autorun_rules print_verbose 'Retrieving Autorun rules' - response = RestClient.get "#{@url}autorun/rules", { :params => { :token => @token } } + response = RestClient.get "#{@url}autorun/rules", { params: { token: @token } } details = JSON.parse(response.body) print_good("Retrieved #{details['count']} rules") details @@ -487,8 +487,8 @@ def autorun_add_rule(data) print_verbose "Adding Autorun rule: #{data}" response = RestClient.post "#{@url}autorun/rule/add?token=#{@token}", data.to_json, - :content_type => :json, - :accept => :json + content_type: :json, + accept: :json details = JSON.parse(response.body) rule_id = details['rule_id'] @@ -505,7 +505,7 @@ def autorun_add_rule(data) def autorun_run_rule_on_all_browsers(rule_id) print_verbose "Running Autorun rule #{rule_id} on all browsers" - response = RestClient.get "#{@url}autorun/run/#{rule_id}", { :params => { :token => @token } } + response = RestClient.get "#{@url}autorun/run/#{rule_id}", { params: { token: @token } } details = JSON.parse(response.body) print_debug details print_good('Done') @@ -516,7 +516,7 @@ def autorun_run_rule_on_all_browsers(rule_id) def autorun_run_rule_on_browser(rule_id, hb_id) print_verbose "Running Autorun rule #{rule_id} on browser #{hb_id}" - response = RestClient.get "#{@url}autorun/run/#{rule_id}/#{hb_id}", { :params => { :token => @token } } + response = RestClient.get "#{@url}autorun/run/#{rule_id}/#{hb_id}", { params: { token: @token } } details = JSON.parse(response.body) print_good('Done') details @@ -532,7 +532,7 @@ def autorun_run_rule_on_browser(rule_id, hb_id) def webrtc_status id begin print_verbose "Retrieving status for hooked browser [id: #{id}]" - response = RestClient.get "#{@url}webrtc/status/#{id}", { :params => { :token => @token } } + response = RestClient.get "#{@url}webrtc/status/#{id}", { params: { token: @token } } details = JSON.parse(response.body) print_good "Retrieved status for hooked browser [id: #{id}]" details @@ -552,8 +552,8 @@ def bind(fname, path) response = RestClient.post "#{@url}/server/bind?token=#{@token}", { 'mount' => "#{path}", 'local_file' => "#{fname}" }.to_json, - :content_type => :json, - :accept => :json + content_type: :json, + accept: :json print_good "Bound '#{fname}' successfully" if response.code == 200 rescue => e print_error "Could not bind file #{fname}: #{e.message}" @@ -569,8 +569,8 @@ def clone_page(url, path, use_existing, dns_spoof) 'url' => "#{url}", 'use_existing' => use_existing, 'dns_spoof' => dns_spoof }.to_json, - :content_type => :json, - :accept => :json + content_type: :json, + accept: :json print_good "Bound '#{url}' successfully" if response.code == 200 rescue => e print_error "Could not bind URL #{url}: #{e.message}" From 00212234446ae5440567c7a7a560b0d64d213d88 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:30:47 +0530 Subject: [PATCH 12/85] Disable Style/WordArray cop --- .rubocop.yml.erb => .rubocop.yml | 3 +++ 1 file changed, 3 insertions(+) rename .rubocop.yml.erb => .rubocop.yml (95%) diff --git a/.rubocop.yml.erb b/.rubocop.yml similarity index 95% rename from .rubocop.yml.erb rename to .rubocop.yml index 84bde1cead..8fe9500207 100644 --- a/.rubocop.yml.erb +++ b/.rubocop.yml @@ -38,5 +38,8 @@ Naming/ClassAndModuleCamelCase: Style/Documentation: Enabled: false +Style/WordArray: + Enabled: false + Style/FrozenStringLiteralComment: Enabled: false From 70fbf6044d84551f9dfe696477983cd636acb866 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:31:33 +0530 Subject: [PATCH 13/85] rubocop --only Layout/EmptyLinesAroundBlockBody -a --- spec/beef/api/auth_rate_spec.rb | 1 - spec/beef/core/extensions_spec.rb | 3 -- spec/beef/core/filter/filters_spec.rb | 36 ------------------- spec/beef/core/main/configuration_spec.rb | 1 - .../handlers/browser_details_handler_spec.rb | 1 - .../core/main/models/browser_details_spec.rb | 2 -- .../handlers/dynamic_reconstruction_spec.rb | 4 --- .../network_stack/handlers/redirector_spec.rb | 2 -- spec/beef/core/modules_spec.rb | 2 -- spec/beef/extensions/adminui_spec.rb | 1 - spec/beef/extensions/dns_spec.rb | 8 ----- spec/beef/extensions/network_spec.rb | 3 -- spec/beef/extensions/proxy_spec.rb | 2 -- spec/beef/extensions/qrcode_spec.rb | 2 -- spec/requests/beef_test_spec.rb | 1 - spec/spec_helper.rb | 1 - 16 files changed, 70 deletions(-) diff --git a/spec/beef/api/auth_rate_spec.rb b/spec/beef/api/auth_rate_spec.rb index 60a07b972d..a06bd96d3e 100644 --- a/spec/beef/api/auth_rate_spec.rb +++ b/spec/beef/api/auth_rate_spec.rb @@ -5,7 +5,6 @@ # RSpec.describe 'BeEF API Rate Limit', run_on_long_tests: true do - before(:each) do @pid = start_beef_server_and_wait @username = @config.get('beef.credentials.user') diff --git a/spec/beef/core/extensions_spec.rb b/spec/beef/core/extensions_spec.rb index b1c22544f9..a9f496f052 100644 --- a/spec/beef/core/extensions_spec.rb +++ b/spec/beef/core/extensions_spec.rb @@ -1,5 +1,4 @@ RSpec.describe 'BeEF Extensions' do - it 'loaded successfully' do expect { BeEF::Extensions.load @@ -16,7 +15,5 @@ expect(v).to have_key('loaded') expect(v['loaded']).to be(true) end - end - end diff --git a/spec/beef/core/filter/filters_spec.rb b/spec/beef/core/filter/filters_spec.rb index 2e9c567d16..f03bd8255b 100644 --- a/spec/beef/core/filter/filters_spec.rb +++ b/spec/beef/core/filter/filters_spec.rb @@ -1,7 +1,5 @@ RSpec.describe 'BeEF Filters' do - context 'is_non_empty_string?' do - it 'nil' do expect(BeEF::Filters::is_non_empty_string?(nil)).to be(false) end @@ -37,11 +35,9 @@ it 'Four num chars begining with null' do expect(BeEF::Filters::is_non_empty_string?("\x003333")).to be(true) end - end context 'only?' do - it 'success' do expect(BeEF::Filters::only?('A', 'A')).to be(true) end @@ -49,11 +45,9 @@ it 'fail' do expect(BeEF::Filters::only?('A', 'B')).to be(false) end - end context 'exists?' do - it 'success' do expect(BeEF::Filters::exists?('A', 'A')).to be(true) end @@ -61,13 +55,10 @@ it 'fail' do expect(BeEF::Filters::exists?('A', 'B')).to be(false) end - end context 'has_null?' do - context 'false with' do - it 'general' do chars = [nil, '', "\x01", "\xFF", 'A', 'A3333', '0', '}', '.', '+', '-', '-1', '0.A', '3333', '33 33', ' AAAAA', 'AAAAAA '] chars.each do |c| @@ -82,11 +73,9 @@ expect(BeEF::Filters::has_null?(str)).to be(false) end end - end context 'true with' do - it 'general' do chars = ["\x00", "A\x00", "AAAAAA\x00", "\x00A", "\x00AAAAAAAA", "A\x00A", "AAAAA\x00AAAA", "A\n\r\x00", "\x00\n\rA", "A\n\r\x00\n\rA", "\tA\x00A"] chars.each do |c| @@ -110,15 +99,11 @@ expect(BeEF::Filters::has_null?(str)).to be(true) end end - end - end context 'has_non_printable_char?' do - context 'false with' do - it 'general' do chars = [nil, '', 'A', 'A3333', '0', '}', '.', '+', '-', '-1', '0.A', '3333', ' 0AAAAA', ' 0AAA '] chars.each do |c| @@ -143,11 +128,9 @@ expect(BeEF::Filters::has_non_printable_char?(c)).to be(false) end end - end context 'true with' do - it 'general' do chars = ["\x00", "\x01", "\x02", "A\x03", "\x04A", "\x0033333", "\x00AAAAAA", " AAAAA\x00", "\t\x00AAAAA", "\n\x00AAAAA", "\n\r\x00AAAAAAAAA", "AAAAAAA\x00AAAAAAA", "\n\x00"] chars.each do |c| @@ -163,13 +146,11 @@ expect(BeEF::Filters::has_non_printable_char?(str)).to be(true) end end - end end context 'nums_only?' do - it 'false with general' do chars = [nil, 1, '', 'A', 'A3333', "\x003333", '}', '.', '+', '-', '-1'] chars.each do |c| @@ -183,11 +164,9 @@ expect(BeEF::Filters::nums_only?(c)).to be(true) end end - end context 'is_valid_float?' do - it 'false with general' do chars = [nil, 1, '', 'A', 'A3333', "\x003333", '}', '.', '+', '-', '-1', '0', '333', '0.A'] chars.each do |c| @@ -201,11 +180,9 @@ expect(BeEF::Filters::is_valid_float?(c)).to be(true) end end - end context 'hexs_only?' do - it 'false with general' do chars = [nil, 1, '', "\x003333", '}', '.', '+', '-', '-1', '0.A', '33.33', '0.0', '1.0', '0.1'] chars.each do |c| @@ -219,11 +196,9 @@ expect(BeEF::Filters::hexs_only?(c)).to be(true) end end - end context 'first_char_is_num?' do - it 'false with general' do chars = ['', 'A', 'A33333', "\x0033333"] chars.each do |c| @@ -237,11 +212,9 @@ expect(BeEF::Filters::first_char_is_num?(c)).to be(true) end end - end context 'has_whitespace_char?' do - it 'false with general' do chars = ['', 'A', 'A33333', "\x0033333", '0', '}', '.', '+', '-', '-1', '0.A'] chars.each do |c| @@ -255,13 +228,10 @@ expect(BeEF::Filters::has_whitespace_char?(c)).to be(true) end end - end context 'alphanums_only?' do - context 'false with' do - it 'general' do chars = [nil, '', "\n", "\r", "\x01", '}', '.', '+', '-', '-1', 'ee-!@$%^&*}=0.A', '33 33', ' AAAA', 'AAA '] chars.each do |c| @@ -302,11 +272,9 @@ expect(BeEF::Filters::alphanums_only?(str)).to be(false) end end - end context 'true with' do - it 'general' do chars = ['A', 'A3333', '0', '3333'] chars.each do |c| @@ -331,13 +299,11 @@ expect(BeEF::Filters::alphanums_only?(c)).to be(true) end end - end end context 'has_valid_param_chars?' do - it 'false' do chars = [nil, '', '+'] chars.each do |c| @@ -348,7 +314,5 @@ it 'true' do expect(BeEF::Filters::has_valid_param_chars?('A')).to be(true) end - end - end diff --git a/spec/beef/core/main/configuration_spec.rb b/spec/beef/core/main/configuration_spec.rb index caafdc88bc..2884707dbd 100644 --- a/spec/beef/core/main/configuration_spec.rb +++ b/spec/beef/core/main/configuration_spec.rb @@ -2,7 +2,6 @@ end RSpec.describe 'BeEF Configuration' do - before(:context) do @config_instance = BeEF::Core::Configuration.instance diff --git a/spec/beef/core/main/handlers/browser_details_handler_spec.rb b/spec/beef/core/main/handlers/browser_details_handler_spec.rb index c0c5fe9d77..dc457545fb 100644 --- a/spec/beef/core/main/handlers/browser_details_handler_spec.rb +++ b/spec/beef/core/main/handlers/browser_details_handler_spec.rb @@ -12,7 +12,6 @@ RSpec.describe 'Browser Details Handler', run_on_browserstack: true do before(:all) do - @config = BeEF::Core::Configuration.instance db_file = @config.get('beef.database.file') print_info 'Resetting the database for BeEF.' diff --git a/spec/beef/core/main/models/browser_details_spec.rb b/spec/beef/core/main/models/browser_details_spec.rb index dd2661f070..3e17f715bd 100644 --- a/spec/beef/core/main/models/browser_details_spec.rb +++ b/spec/beef/core/main/models/browser_details_spec.rb @@ -1,5 +1,4 @@ RSpec.describe 'BeEF BrowserDetails' do - before(:all) do @session = (0...10).map { ('a'..'z').to_a[rand(26)] }.join end @@ -28,5 +27,4 @@ expect(BeEF::Core::Models::BrowserDetails.get(@session, key_name)).to_not eql(original_key_value) expect(BeEF::Core::Models::BrowserDetails.get(@session, key_name)).to eql(new_key_value) end - end diff --git a/spec/beef/core/main/network_stack/handlers/dynamic_reconstruction_spec.rb b/spec/beef/core/main/network_stack/handlers/dynamic_reconstruction_spec.rb index 140bb2f130..c58afab362 100644 --- a/spec/beef/core/main/network_stack/handlers/dynamic_reconstruction_spec.rb +++ b/spec/beef/core/main/network_stack/handlers/dynamic_reconstruction_spec.rb @@ -1,5 +1,4 @@ RSpec.describe 'BeEF Dynamic Reconsturction' do - before(:all) do @port = 2001 config = {} @@ -43,7 +42,6 @@ end context 'get' do - it 'no params' do response = Curl::Easy.http_get("http://127.0.0.1:#{@port}/test") expect(response.response_code).to eql(404) @@ -80,7 +78,5 @@ expect(response.response_code).to eql(200) expect(response.body_str).to be_empty end - end - end diff --git a/spec/beef/core/main/network_stack/handlers/redirector_spec.rb b/spec/beef/core/main/network_stack/handlers/redirector_spec.rb index 17fbc81722..f711ff60fe 100644 --- a/spec/beef/core/main/network_stack/handlers/redirector_spec.rb +++ b/spec/beef/core/main/network_stack/handlers/redirector_spec.rb @@ -1,5 +1,4 @@ RSpec.describe 'BeEF Redirector' do - before(:all) do @port = 2002 config = {} @@ -33,5 +32,4 @@ expect(response.body_str).to eql('302 found') expect(response.header_str).to match(/Location: http:\/\/www.beefproject\.com/) end - end diff --git a/spec/beef/core/modules_spec.rb b/spec/beef/core/modules_spec.rb index 0d2e581664..f75b9bf87c 100644 --- a/spec/beef/core/modules_spec.rb +++ b/spec/beef/core/modules_spec.rb @@ -1,5 +1,4 @@ RSpec.describe 'BeEF Modules' do - it 'loaded successfully' do expect { BeEF::Modules.load if BeEF::Core::Configuration.instance.get('beef.module').nil? @@ -46,5 +45,4 @@ end end end - end diff --git a/spec/beef/extensions/adminui_spec.rb b/spec/beef/extensions/adminui_spec.rb index e5679d669c..9010e52280 100644 --- a/spec/beef/extensions/adminui_spec.rb +++ b/spec/beef/extensions/adminui_spec.rb @@ -49,5 +49,4 @@ request.add_header('REMOTE_ADDR','192.168.0.20') expect(ui.get_ip(request)).to eq '192.168.0.20' end - end \ No newline at end of file diff --git a/spec/beef/extensions/dns_spec.rb b/spec/beef/extensions/dns_spec.rb index e92306fd08..7cbc177466 100644 --- a/spec/beef/extensions/dns_spec.rb +++ b/spec/beef/extensions/dns_spec.rb @@ -7,7 +7,6 @@ require 'extensions/dns/extension.rb' RSpec.describe 'BeEF Extension DNS' do - IN = Resolv::DNS::Resource::IN before(:all) do @@ -38,7 +37,6 @@ end context 'add good rule' do - it '1.2.3.4' do id = nil response = '1.2.3.4' @@ -86,11 +84,9 @@ }.to_not raise_error expect(id).to_not be_nil end - end context 'add bad rule' do - it '4.2.4.2' do id = nil same_id = nil @@ -126,9 +122,7 @@ expect(id).to eql(same_id) end - end - end # it 'id format' do @@ -242,9 +236,7 @@ end it 'failure types' do - end - end # Tests each supported type of query failure diff --git a/spec/beef/extensions/network_spec.rb b/spec/beef/extensions/network_spec.rb index 5265b159b0..32e538a8dd 100644 --- a/spec/beef/extensions/network_spec.rb +++ b/spec/beef/extensions/network_spec.rb @@ -7,7 +7,6 @@ require 'extensions/network/models/network_host' RSpec.describe 'BeEF Extension Network' do - it 'add good local host' do expect { BeEF::Core::Models::NetworkHost.create(hooked_browser_id: '1234', ip: '127.0.0.1') @@ -27,7 +26,5 @@ BeEF::Core::Models::NetworkService.create(hooked_browser_id: '1234', proto: 'http', ip: '127.0.0.1', port: 80, ntype: 'Apache') }.to_not raise_error expect(BeEF::Core::Models::NetworkService.where(hooked_browser_id: '1234', ip: '127.0.0.1')).to_not be_empty - end - end diff --git a/spec/beef/extensions/proxy_spec.rb b/spec/beef/extensions/proxy_spec.rb index ff25ac1411..5460d3e5af 100644 --- a/spec/beef/extensions/proxy_spec.rb +++ b/spec/beef/extensions/proxy_spec.rb @@ -6,7 +6,6 @@ require 'extensions/proxy/extension' RSpec.describe 'BeEF Extension Proxy' do - before(:all) do @config = BeEF::Core::Configuration.instance @config.load_extensions_config @@ -20,5 +19,4 @@ expect(config).to have_key('key') expect(config).to have_key('cert') end - end diff --git a/spec/beef/extensions/qrcode_spec.rb b/spec/beef/extensions/qrcode_spec.rb index 43e990dea3..b774044362 100644 --- a/spec/beef/extensions/qrcode_spec.rb +++ b/spec/beef/extensions/qrcode_spec.rb @@ -6,7 +6,6 @@ require 'extensions/qrcode/extension' RSpec.describe 'BeEF Extension QRCode' do - before(:all) do @config = BeEF::Core::Configuration.instance @config.load_extensions_config @@ -19,5 +18,4 @@ expect(config).to have_key('qrsize') expect(config).to have_key('qrborder') end - end diff --git a/spec/requests/beef_test_spec.rb b/spec/requests/beef_test_spec.rb index f290d7cdf9..63a8c67dae 100644 --- a/spec/requests/beef_test_spec.rb +++ b/spec/requests/beef_test_spec.rb @@ -8,7 +8,6 @@ require_relative '../support/beef_test' RSpec.describe BeefTest, run_on_long_tests: true do - before(:each) do @pid = start_beef_server_and_wait end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index af16ca546f..eb79880c1f 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -329,5 +329,4 @@ def stop_beef_server(pid) Process.wait(pid) unless pid.nil? # Ensure the process has exited and the port is released pid = nil end - end \ No newline at end of file From 62fef85a57a9459e3e21275ed49ff01fb277258d Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:32:21 +0530 Subject: [PATCH 14/85] Disable Style/RescueStandardError cop --- .rubocop.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.rubocop.yml b/.rubocop.yml index 8fe9500207..6da722c053 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -38,6 +38,9 @@ Naming/ClassAndModuleCamelCase: Style/Documentation: Enabled: false +Style/RescueStandardError: + Enabled: false + Style/WordArray: Enabled: false From 16eef0c2689440472590f03b3913d195916bd27f Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:34:07 +0530 Subject: [PATCH 15/85] rubocop --only Style/RegexpLiteral -a --- extensions/webrtc/handlers.rb | 2 +- spec/beef/core/main/network_stack/handlers/redirector_spec.rb | 2 +- spec/beef/extensions/dns_spec.rb | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/extensions/webrtc/handlers.rb b/extensions/webrtc/handlers.rb index fdb03e6abb..4e3ee830ca 100644 --- a/extensions/webrtc/handlers.rb +++ b/extensions/webrtc/handlers.rb @@ -145,7 +145,7 @@ def setup() stat2.save end elsif (message.start_with?('execcmd')) - mod = /\(\/command\/(.*)\.js\)/.match(message)[1] + mod = %r{\(/command/(.*)\.js\)}.match(message)[1] resp = /Result:.(.*)/.match(message)[1] stat = BeEF::Core::Models::Rtcmodulestatus.new(hooked_browser_id: zombie_db.id, target_hooked_browser_id: peer_zombie_db.id, diff --git a/spec/beef/core/main/network_stack/handlers/redirector_spec.rb b/spec/beef/core/main/network_stack/handlers/redirector_spec.rb index f711ff60fe..12be2cb143 100644 --- a/spec/beef/core/main/network_stack/handlers/redirector_spec.rb +++ b/spec/beef/core/main/network_stack/handlers/redirector_spec.rb @@ -30,6 +30,6 @@ response = Curl::Easy.http_get("http://127.0.0.1:#{@port}/test/") expect(response.response_code).to eql(302) expect(response.body_str).to eql('302 found') - expect(response.header_str).to match(/Location: http:\/\/www.beefproject\.com/) + expect(response.header_str).to match(%r{Location: http://www.beefproject\.com}) end end diff --git a/spec/beef/extensions/dns_spec.rb b/spec/beef/extensions/dns_spec.rb index 7cbc177466..fbc60b1adc 100644 --- a/spec/beef/extensions/dns_spec.rb +++ b/spec/beef/extensions/dns_spec.rb @@ -56,7 +56,7 @@ response = '9.9.9.9' expect { id = @dns.add_rule( - pattern: %r{i\.(love|hate)\.beef\.com?}, + pattern: /i\.(love|hate)\.beef\.com?/, resource: IN::A, response: [response]) do |transaction| transaction.respond!(response) @@ -76,7 +76,7 @@ id = nil expect { id = @dns.add_rule( - pattern: %r{i\.(love|hate)\.beef\.com?}, + pattern: /i\.(love|hate)\.beef\.com?/, resource: IN::A, response: [response]) do |transaction| transaction.respond!(response) From ba1b971383cb7b7e5cff75d042aa9393434e8dfb Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:34:46 +0530 Subject: [PATCH 16/85] rubocop --only Layout/TrailingWhitespace -a --- Rakefile | 2 +- core/main/models/legacybrowseruseragents.rb | 2 +- core/module.rb | 4 ++-- .../admin_ui/controllers/modules/modules.rb | 6 ++--- extensions/dns/dns.rb | 2 +- extensions/qrcode/qrcode.rb | 2 +- extensions/webrtc/api.rb | 10 ++++---- extensions/webrtc/api/hook.rb | 6 ++--- extensions/webrtc/extension.rb | 2 +- extensions/webrtc/models/rtcmanage.rb | 6 ++--- extensions/webrtc/models/rtcmodulestatus.rb | 8 +++---- extensions/webrtc/models/rtcsignal.rb | 2 +- extensions/webrtc/models/rtcstatus.rb | 6 ++--- spec/beef/api/auth_rate_spec.rb | 20 ++++++++-------- spec/beef/core/filter/filters_spec.rb | 10 ++++---- .../autorun_engine/autorun_engine_spec.rb | 2 +- spec/beef/core/main/configuration_spec.rb | 2 +- .../handlers/browser_details_handler_spec.rb | 2 +- spec/beef/extensions/adminui_spec.rb | 2 +- spec/beef/extensions/requester_spec.rb | 2 +- .../websocket_hooked_browser_spec.rb | 4 ++-- spec/beef/security_checks_spec.rb | 2 +- spec/features/all_modules_spec.rb | 24 +++++++++---------- spec/features/debug_modules_spec.rb | 8 +++---- spec/requests/beef_test_spec.rb | 10 ++++---- spec/spec_helper.rb | 6 ++--- spec/support/beef_test.rb | 2 +- spec/support/constants.rb | 2 +- spec/support/ui_support.rb | 8 +++---- 29 files changed, 82 insertions(+), 82 deletions(-) diff --git a/Rakefile b/Rakefile index 038928da85..9a11e62098 100644 --- a/Rakefile +++ b/Rakefile @@ -54,7 +54,7 @@ namespace :ssl do end Rake::Task['ssl:replace'].invoke end - + desc 'Re-generate SSL certificate' task :replace do if File.file?('/usr/local/bin/openssl') diff --git a/core/main/models/legacybrowseruseragents.rb b/core/main/models/legacybrowseruseragents.rb index cc383fe76b..918d73d1b2 100644 --- a/core/main/models/legacybrowseruseragents.rb +++ b/core/main/models/legacybrowseruseragents.rb @@ -9,7 +9,7 @@ module Models # # Objects stores known 'legacy' browser User Agents. # - # This table is used to determine if a hooked browser is a 'legacy' + # This table is used to determine if a hooked browser is a 'legacy' # browser. # # TODO: make it an actual table diff --git a/core/module.rb b/core/module.rb index eb9dff7122..320b18b061 100644 --- a/core/module.rb +++ b/core/module.rb @@ -305,10 +305,10 @@ def self.parse_targets(mod) target_config.each do |k, v| # Convert the key to a string if it's not already one k_str = k.to_s.upcase - + # Use the adjusted string key for the rest of the process next unless BeEF::Core::Constants::CommandModule.const_defined? "VERIFIED_#{k_str}" - + key = BeEF::Core::Constants::CommandModule.const_get "VERIFIED_#{k_str}" targets[key] = [] unless targets.key? key browser = nil diff --git a/extensions/admin_ui/controllers/modules/modules.rb b/extensions/admin_ui/controllers/modules/modules.rb index 36c863fe12..291fffa53f 100644 --- a/extensions/admin_ui/controllers/modules/modules.rb +++ b/extensions/admin_ui/controllers/modules/modules.rb @@ -82,10 +82,10 @@ def set_command_module_status(mod) # @param category [Array] The category to add the leaf to # @param leaf [Hash] The leaf to add to the tree def update_command_module_tree_recurse(tree, category, leaf) - + # get a single folder from the category array working_category = category.shift - + tree.each do |t| if t['text'].eql?(working_category) && category.count > 0 # We have deeper to go @@ -242,7 +242,7 @@ def select_command_modules_tree sort_recursive_tree(tree) retitle_recursive_tree(tree) - + # return a JSON array of hashes @body = tree.to_json end diff --git a/extensions/dns/dns.rb b/extensions/dns/dns.rb index 5a8583d676..40ed48e35a 100644 --- a/extensions/dns/dns.rb +++ b/extensions/dns/dns.rb @@ -153,7 +153,7 @@ def run(options = {}) def stop return unless @server_started # Check if the server was started - + # Logic to stop the Async::DNS server puts EventMachine.stop if EventMachine.reactor_running? @server_started = false # Reset the server started flag diff --git a/extensions/qrcode/qrcode.rb b/extensions/qrcode/qrcode.rb index 1358de4a41..56774e1a78 100644 --- a/extensions/qrcode/qrcode.rb +++ b/extensions/qrcode/qrcode.rb @@ -28,7 +28,7 @@ def self.pre_http_start(_http_hook_server) fullurls << target # relative URLs else - + # Retrieve the list of network interfaces from BeEF::Core::Console::Banners interfaces = BeEF::Core::Console::Banners.interfaces diff --git a/extensions/webrtc/api.rb b/extensions/webrtc/api.rb index e496f65a89..fc6d871824 100644 --- a/extensions/webrtc/api.rb +++ b/extensions/webrtc/api.rb @@ -6,11 +6,11 @@ module BeEF module Extension module WebRTC - + module RegisterHttpHandler - + BeEF::API::Registrar.instance.register(BeEF::Extension::WebRTC::RegisterHttpHandler, BeEF::API::Server, 'mount_handler') - + # We register the http handler for the WebRTC signalling extension. # This http handler will handle WebRTC signals from browser to browser @@ -20,7 +20,7 @@ def self.mount_handler(beef_server) beef_server.mount('/rtcmessage', BeEF::Extension::WebRTC::MessengeHandler) beef_server.mount('/api/webrtc', BeEF::Extension::WebRTC::WebRTCRest.new) end - + end module RegisterPreHookCallback @@ -35,7 +35,7 @@ def self.pre_hook_send(hooked_browser, body, params, request, response) end end - + end end end diff --git a/extensions/webrtc/api/hook.rb b/extensions/webrtc/api/hook.rb index dab85ed9e9..5d0d8ad2b1 100644 --- a/extensions/webrtc/api/hook.rb +++ b/extensions/webrtc/api/hook.rb @@ -4,8 +4,8 @@ # See the file 'doc/COPYING' for copying permission # -# A lot of this logic is cloned from the requester extension, which had a sane way of sending/recvng -# JS to the clients.. +# A lot of this logic is cloned from the requester extension, which had a sane way of sending/recvng +# JS to the clients.. module BeEF module Extension @@ -54,7 +54,7 @@ def requester_run(hb, body) # The below is how antisnatchor was managing insertion of messages dependent on WebSockets or not # Hopefully this still works if config.get('beef.http.websocket.enable') && ws.getsocket(hb.session) - + rtcsignaloutput.each {|o| add_rtcsignal_to_body o } unless rtcsignaloutput.empty? diff --git a/extensions/webrtc/extension.rb b/extensions/webrtc/extension.rb index 6e1bfb140d..1f01e7ad09 100644 --- a/extensions/webrtc/extension.rb +++ b/extensions/webrtc/extension.rb @@ -12,7 +12,7 @@ module WebRTC @short_name = 'webrtc' @full_name = 'WebRTC' @description = 'WebRTC extension to all browsers to connect to each other (P2P) with WebRTC' - + end end end diff --git a/extensions/webrtc/models/rtcmanage.rb b/extensions/webrtc/models/rtcmanage.rb index 06d4eaa88c..6801af330c 100644 --- a/extensions/webrtc/models/rtcmanage.rb +++ b/extensions/webrtc/models/rtcmanage.rb @@ -10,7 +10,7 @@ module Models # Table stores the queued up JS commands for managing the client-side webrtc logic. # class RtcManage < BeEF::Core::Model - + # Starts the RTCPeerConnection process, establishing a WebRTC connection between the caller and the receiver def self.initiate(caller, receiver, verbosity = false) stunservers = BeEF::Core::Configuration.instance.get('beef.extension.webrtc.stunservers') @@ -20,7 +20,7 @@ def self.initiate(caller, receiver, verbosity = false) # This is for the Receiver r = BeEF::Core::Models::RtcManage.new(hooked_browser_id: receiver, message: "beef.webrtc.start(0,#{caller},JSON.stringify(#{turnservers}),JSON.stringify(#{stunservers}),#{verbosity});") r.save! - + # This is the same beef.webrtc.start() JS call, but for the Caller r = BeEF::Core::Models::RtcManage.new(hooked_browser_id: caller, message: "beef.webrtc.start(1,#{receiver},JSON.stringify(#{turnservers}),JSON.stringify(#{stunservers}),#{verbosity});") r.save! @@ -41,7 +41,7 @@ def self.status(id) end end - + end end end diff --git a/extensions/webrtc/models/rtcmodulestatus.rb b/extensions/webrtc/models/rtcmodulestatus.rb index bd91cec1c1..f434db933a 100644 --- a/extensions/webrtc/models/rtcmodulestatus.rb +++ b/extensions/webrtc/models/rtcmodulestatus.rb @@ -11,16 +11,16 @@ module Models # Table stores the webrtc status information # This includes things like connection status, and executed modules etc # - + class Rtcmodulestatus < BeEF::Core::Model - + belongs_to :hooked_browser belongs_to :command_module - + end - + end end end diff --git a/extensions/webrtc/models/rtcsignal.rb b/extensions/webrtc/models/rtcsignal.rb index c11e0a10fa..8a55373f65 100644 --- a/extensions/webrtc/models/rtcsignal.rb +++ b/extensions/webrtc/models/rtcsignal.rb @@ -14,7 +14,7 @@ class RtcSignal < BeEF::Core::Model belongs_to :hooked_browser end - + end end end diff --git a/extensions/webrtc/models/rtcstatus.rb b/extensions/webrtc/models/rtcstatus.rb index bf29bf4db7..506697b5fb 100644 --- a/extensions/webrtc/models/rtcstatus.rb +++ b/extensions/webrtc/models/rtcstatus.rb @@ -11,14 +11,14 @@ module Models # Table stores the webrtc status information # This includes things like connection status, and executed modules etc # - + class Rtcstatus < BeEF::Core::Model - + belongs_to :hooked_browser end - + end end end diff --git a/spec/beef/api/auth_rate_spec.rb b/spec/beef/api/auth_rate_spec.rb index a06bd96d3e..851342603a 100644 --- a/spec/beef/api/auth_rate_spec.rb +++ b/spec/beef/api/auth_rate_spec.rb @@ -14,24 +14,24 @@ after(:each) do # Shutting down server Process.kill('KILL', @pid) unless @pid.nil? - Process.wait(@pid) unless @pid.nil? # Ensure the process has exited and the port is released + Process.wait(@pid) unless @pid.nil? # Ensure the process has exited and the port is released @pid = nil end it 'confirm correct creds are successful' do - test_api = BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, @password) + test_api = BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, @password) expect(@config.get('beef.credentials.user')).to eq('beef') expect(@config.get('beef.credentials.passwd')).to eq('beef') - expect(test_api.auth()[:payload]).not_to eql('401 Unauthorized') + expect(test_api.auth()[:payload]).not_to eql('401 Unauthorized') expect(test_api.auth()[:payload]['success']).to be(true) # valid pass should succeed end - + it 'confirm incorrect creds are unsuccessful' do sleep 0.5 - test_api = BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, 'wrong_passowrd') + test_api = BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, 'wrong_passowrd') expect(test_api.auth()[:payload]).to eql('401 Unauthorized') # all (unless the valid is first 1 in 10 chance) end - + it 'adheres to 9 bad passwords then 1 correct auth rate limits' do # create api structures with bad passwords and one good passwds = (1..9).map { |i| 'bad_password'} # incorrect password @@ -43,7 +43,7 @@ expect(test_api.auth()[:payload]).to eql('401 Unauthorized') # all (unless the valid is first 1 in 10 chance) end end - + it 'adheres to random bad passords and 1 correct auth rate limits' do # create api structures with bad passwords and one good passwds = (1..9).map { |i| 'bad_password'} # incorrect password @@ -59,12 +59,12 @@ sleep 0.5 expect(@config.get('beef.credentials.user')).to eq('beef') expect(@config.get('beef.credentials.passwd')).to eq('beef') - expect(test_api.auth()[:payload]).not_to eql('401 Unauthorized') + expect(test_api.auth()[:payload]).not_to eql('401 Unauthorized') expect(test_api.auth()[:payload]['success']).to be(true) # valid pass should succeed else expect(test_api.auth()[:payload]).to eql('401 Unauthorized') end end - end - + end + end diff --git a/spec/beef/core/filter/filters_spec.rb b/spec/beef/core/filter/filters_spec.rb index f03bd8255b..3458f6c64e 100644 --- a/spec/beef/core/filter/filters_spec.rb +++ b/spec/beef/core/filter/filters_spec.rb @@ -56,7 +56,7 @@ expect(BeEF::Filters::exists?('A', 'B')).to be(false) end end - + context 'has_null?' do context 'false with' do it 'general' do @@ -147,7 +147,7 @@ end end end - + end context 'nums_only?' do @@ -213,7 +213,7 @@ end end end - + context 'has_whitespace_char?' do it 'false with general' do chars = ['', 'A', 'A33333', "\x0033333", '0', '}', '.', '+', '-', '-1', '0.A'] @@ -229,7 +229,7 @@ end end end - + context 'alphanums_only?' do context 'false with' do it 'general' do @@ -300,7 +300,7 @@ end end end - + end context 'has_valid_param_chars?' do diff --git a/spec/beef/core/main/autorun_engine/autorun_engine_spec.rb b/spec/beef/core/main/autorun_engine/autorun_engine_spec.rb index ac8051afc3..2e133bb49c 100644 --- a/spec/beef/core/main/autorun_engine/autorun_engine_spec.rb +++ b/spec/beef/core/main/autorun_engine/autorun_engine_spec.rb @@ -57,7 +57,7 @@ ActiveRecord::Migrator.new(:up, context.migrations, context.schema_migration, context.internal_metadata).migrate end end - + BeEF::Core::Migration.instance.update_db! # add AutoRunEngine rule diff --git a/spec/beef/core/main/configuration_spec.rb b/spec/beef/core/main/configuration_spec.rb index 2884707dbd..42b78f6972 100644 --- a/spec/beef/core/main/configuration_spec.rb +++ b/spec/beef/core/main/configuration_spec.rb @@ -195,7 +195,7 @@ expect(@config_instance.get('beef.http.public.host')).to eq(nil) expect(@config_instance.beef_port).to eq('80') end - + it 'should return a protocol https if https public has been enabled and public host is set' do @config_instance.set('beef.http.public.https', true) @config_instance.set('beef.http.public.host', 'public') diff --git a/spec/beef/core/main/handlers/browser_details_handler_spec.rb b/spec/beef/core/main/handlers/browser_details_handler_spec.rb index dc457545fb..329b257b5a 100644 --- a/spec/beef/core/main/handlers/browser_details_handler_spec.rb +++ b/spec/beef/core/main/handlers/browser_details_handler_spec.rb @@ -19,7 +19,7 @@ if ENV['RESET_DB'] File.delete(db_file) if File.exist?(db_file) end - + @config.set('beef.credentials.user', 'beef') @config.set('beef.credentials.passwd', 'beef') @username = @config.get('beef.credentials.user') diff --git a/spec/beef/extensions/adminui_spec.rb b/spec/beef/extensions/adminui_spec.rb index 9010e52280..a7f0a6ba01 100644 --- a/spec/beef/extensions/adminui_spec.rb +++ b/spec/beef/extensions/adminui_spec.rb @@ -44,7 +44,7 @@ expect(@config.set('beef.restrictions.permitted_ui_subnet',['192.168.0.10'])).to eq true expect(@config.set('beef.http.allow_reverse_proxy',false)).to eq true env = { 'REQUEST_METHOD' => 'GET', 'PATH_INFO' => '/ui/authentication' } - request = Rack::Request.new(env) + request = Rack::Request.new(env) request.add_header('HTTP_X_FORWARDED_FOR','192.168.0.10') request.add_header('REMOTE_ADDR','192.168.0.20') expect(ui.get_ip(request)).to eq '192.168.0.20' diff --git a/spec/beef/extensions/requester_spec.rb b/spec/beef/extensions/requester_spec.rb index b96340d920..38b71dcc59 100644 --- a/spec/beef/extensions/requester_spec.rb +++ b/spec/beef/extensions/requester_spec.rb @@ -28,7 +28,7 @@ @config = BeEF::Core::Configuration.instance @config.set('beef.credentials.user', 'beef') @config.set('beef.credentials.passwd', 'beef') - + # Generate API token BeEF::Core::Crypto::api_token diff --git a/spec/beef/extensions/websocket_hooked_browser_spec.rb b/spec/beef/extensions/websocket_hooked_browser_spec.rb index f60509dd3f..c2222fe855 100644 --- a/spec/beef/extensions/websocket_hooked_browser_spec.rb +++ b/spec/beef/extensions/websocket_hooked_browser_spec.rb @@ -22,7 +22,7 @@ if ENV['RESET_DB'] File.delete(db_file) if File.exist?(db_file) end - + @config.set('beef.credentials.user', 'beef') @config.set('beef.credentials.passwd', 'beef') @config.set('beef.http.websocket.secure', false) @@ -59,7 +59,7 @@ ActiveRecord::Migrator.new(:up, context.migrations, context.schema_migration, context.internal_metadata).migrate end end - + BeEF::Core::Migration.instance.update_db! # Spawn HTTP Server print_info 'Starting HTTP Hook Server' diff --git a/spec/beef/security_checks_spec.rb b/spec/beef/security_checks_spec.rb index 77865e4d5c..fdd31b210b 100644 --- a/spec/beef/security_checks_spec.rb +++ b/spec/beef/security_checks_spec.rb @@ -11,7 +11,7 @@ clean_line = line.downcase.gsub(/[ ]/, '') if clean_line[0] != '#' # check first non-whitespace position raise "Illegal use of 'eval' found in\n Path: #{path}\nLine: #{line}" - end + end end end end diff --git a/spec/features/all_modules_spec.rb b/spec/features/all_modules_spec.rb index fec3d91df0..4b979a315c 100644 --- a/spec/features/all_modules_spec.rb +++ b/spec/features/all_modules_spec.rb @@ -16,41 +16,41 @@ after(:each) do stop_beef_and_unhook_browser(@pid, @beef_session, @hooked_browser) end - + it 'Load all modules' do - + Dir.glob('modules/**/config.yaml').each do |file| module_yaml_data = YAML.load_file(file) - + module_yaml_data['beef']['module'].each do |module_key, module_value| next if rand(50) != 0 # for testing purposes only - + next if not module_value['enable'] # skip disabled modules - + module_name = module_value['name'] module_category = module_value['category'] # can be an array or a string module_description_sub = module_value['description'][0, 15] # descriptions including html cause errors - + expect(module_category).not_to be_nil expect(module_name).not_to be_nil - + expect(@beef_session).to have_content(module_category, wait: PAGE_LOAD_TIMEOUT) if module_category.is_a?(String) - + expect(module_name).to be_a(String) expect(module_description_sub).not_to be_nil expect(module_description_sub).to be_a(String) - + # print the category and module name - if module_category.is_a?(Array) + if module_category.is_a?(Array) category_tree_text = module_category.join(' > ') else category_tree_text = module_category end print_info "Category: #{category_tree_text}, Module: #{module_name}" - + # click on the module then expect the description and execute button to be visible click_on_module(@beef_session, module_category, module_name) - + # expect the module description and the execute button to be visible expect(@beef_session).to have_content(module_description_sub, wait: PAGE_LOAD_TIMEOUT) expect(@beef_session).to have_content('Execute', wait: PAGE_LOAD_TIMEOUT) diff --git a/spec/features/debug_modules_spec.rb b/spec/features/debug_modules_spec.rb index b4d375903a..ebf066127b 100644 --- a/spec/features/debug_modules_spec.rb +++ b/spec/features/debug_modules_spec.rb @@ -16,14 +16,14 @@ after(:each) do stop_beef_and_unhook_browser(@pid, @beef_session, @hooked_browser) end - + it 'Test beef.debug module' do click_on_module(@beef_session, 'Debug', 'Test beef.debug') expect(@beef_session).to have_content('Execute', wait: PAGE_LOAD_TIMEOUT) expect(@beef_session).to have_content('244', wait: PAGE_LOAD_TIMEOUT) # Module ID expect(@beef_session).to have_content('Debug Message:', wait: PAGE_LOAD_TIMEOUT) end - + it 'Load all debug modules' do Dir.glob('modules/debug/**/config.yaml').each do |file| module_yaml_data = YAML.load_file(file) @@ -63,12 +63,12 @@ if module_name == 'Return Image' # this module returns an image not a string image_selector = "img[src^='data:image/png;base64,iVBORw0KGgo']" - expect(@beef_session).to have_css(image_selector, wait: PAGE_LOAD_TIMEOUT) + expect(@beef_session).to have_css(image_selector, wait: PAGE_LOAD_TIMEOUT) else expect(@beef_session).to have_content('data: ', wait: PAGE_LOAD_TIMEOUT) end end end end - + end \ No newline at end of file diff --git a/spec/requests/beef_test_spec.rb b/spec/requests/beef_test_spec.rb index 63a8c67dae..5ef765fd74 100644 --- a/spec/requests/beef_test_spec.rb +++ b/spec/requests/beef_test_spec.rb @@ -35,7 +35,7 @@ it 'logs out successfully' do expect(port_available?) # # Check if the tcp port is open expect(@session.has_content?('Hooked Browsers', wait: 10)) - + # Log out of the session @sessoin = BeefTest.logout(@session) expect(@session.has_no_content?('Hooked Browsers', wait: 10)) @@ -47,7 +47,7 @@ describe '.save_screenshot' do it 'saves a screenshot' do session = Capybara::Session.new(:selenium_headless) if session.nil? - + # Ensure the new directory does not exist outputDir = '/tmp' directory = "#{outputDir}/#{SecureRandom.hex}/" @@ -66,8 +66,8 @@ expect(File.size(file)).to be > 0 File.delete(file) end - expect(Dir.glob("#{directory}/*.png").empty?).to be true - + expect(Dir.glob("#{directory}/*.png").empty?).to be true + # Remove the directory Dir.delete(directory) expect(File.directory?(directory)).to be false @@ -83,7 +83,7 @@ expect(session).not_to be_nil result = BeefTest.new_attacker(session) - + # Test assertions expect(result).to eq(session) expect(session.has_no_content?('Authentication', wait: 10)) diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index eb79880c1f..af45334214 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -241,7 +241,7 @@ def start_beef_server exit end load_beef_extensions_and_modules - + # Grab DB file and regenerate if requested db_file = @config.get('beef.database.file') @@ -326,7 +326,7 @@ def stop_beef_server(pid) exit if pid.nil? # Shutting down server Process.kill('KILL', pid) unless pid.nil? - Process.wait(pid) unless pid.nil? # Ensure the process has exited and the port is released - pid = nil + Process.wait(pid) unless pid.nil? # Ensure the process has exited and the port is released + pid = nil end end \ No newline at end of file diff --git a/spec/support/beef_test.rb b/spec/support/beef_test.rb index f54033704d..2a26b551ce 100644 --- a/spec/support/beef_test.rb +++ b/spec/support/beef_test.rb @@ -20,7 +20,7 @@ def self.save_screenshot(session, dir = nil) def self.login(session = nil) session = Capybara::Session.new(:selenium_headless) if session.nil? session.visit(ATTACK_URL) - + session.has_content?('Authentication', wait: 10) # enter the credentials diff --git a/spec/support/constants.rb b/spec/support/constants.rb index d4bfa54640..4bd7b1d9e7 100644 --- a/spec/support/constants.rb +++ b/spec/support/constants.rb @@ -30,4 +30,4 @@ # Other PAGE_LOAD_TIMEOUT = 5 SERVER_START_TIMEOUT = 5 -BROWSER_HOOKING_TIMEOUT = 10 \ No newline at end of file +BROWSER_HOOKING_TIMEOUT = 10 \ No newline at end of file diff --git a/spec/support/ui_support.rb b/spec/support/ui_support.rb index 19b7ae3062..77b90ddd2a 100644 --- a/spec/support/ui_support.rb +++ b/spec/support/ui_support.rb @@ -70,7 +70,7 @@ def expand_category_tree(session, category, module_name = nil) match_data = element_text.match(/\A([\w\s]+)\s\((\d+)\)\z/) next unless match_data - + # scroll to the element session.scroll_to(element) rescue Selenium::WebDriver::Error::StaleElementReferenceError => e @@ -90,14 +90,14 @@ def expand_category_tree(session, category, module_name = nil) end expect(session).to have_content(module_name, wait: PAGE_LOAD_TIMEOUT) end - + def collapse_category_tree(session, category) if category.is_a?(Array) category.reverse.each do |category_name| # Collapse the sub-folder session.scroll_to(category_name) session.first(:link_or_button, category_name + ' ').click - end + end else session.scroll_to(category) session.first(:link_or_button, category + ' ').click @@ -107,7 +107,7 @@ def collapse_category_tree(session, category) def click_on_module(session, category, module_name) # expand the category tree to make the module visible expand_category_tree(session, category, module_name) - + # click on the module in the expanded tree session.scroll_to(module_name) expect(session).to have_content(module_name, wait: PAGE_LOAD_TIMEOUT) From 54b6216656dc791a032a4468a13ea726a5fa16ee Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:35:25 +0530 Subject: [PATCH 17/85] rubocop --only Layout/EmptyLinesAroundAttributeAccessor -a --- spec/spec_helper.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index af45334214..bd0305420e 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -79,6 +79,7 @@ module Core module Console class << self attr_accessor :logger + def level=(val) (self.logger ||= Logger.new($stdout)).level = val end @@ -109,6 +110,7 @@ def respond_to_missing?(m, include_priv = false) module ::Console class << self attr_accessor :logger + def level=(val) (self.logger ||= Logger.new($stdout)).level = val end From 3288e922ed7723b52f578a4d33cbba2bd4a9e324 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:38:08 +0530 Subject: [PATCH 18/85] rubocop --only Style/StringConcatenation -A --- core/filters/base.rb | 2 +- core/main/autorun_engine/engine.rb | 4 ++-- core/main/command.rb | 2 +- core/main/console/banners.rb | 2 +- core/main/handlers/browserdetails.rb | 2 +- core/main/handlers/modules/beefjs.rb | 12 +++++----- core/main/handlers/modules/command.rb | 2 +- core/main/handlers/modules/legacybeefjs.rb | 12 +++++----- .../main/handlers/modules/multistagebeefjs.rb | 12 +++++----- core/main/network_stack/assethandler.rb | 8 +++---- .../handlers/dynamicreconstruction.rb | 8 +++---- core/main/rest/handlers/modules.rb | 2 +- core/ruby/print.rb | 10 ++++---- extensions/admin_ui/classes/httpcontroller.rb | 2 +- .../admin_ui/controllers/modules/modules.rb | 2 +- extensions/demos/handler.rb | 2 +- extensions/dns/model.rb | 8 +------ extensions/dns_rebinding/dns_rebinding.rb | 21 +++++++--------- extensions/webrtc/handlers.rb | 2 +- spec/support/beef_test.rb | 2 +- spec/support/constants.rb | 24 +++++++++---------- spec/support/ui_support.rb | 6 ++--- 22 files changed, 69 insertions(+), 78 deletions(-) diff --git a/core/filters/base.rb b/core/filters/base.rb index 5bf170f0d5..aeefa94717 100644 --- a/core/filters/base.rb +++ b/core/filters/base.rb @@ -21,7 +21,7 @@ def self.is_non_empty_string?(str) # @param [String] str String for testing # @return [Boolean] Whether or not the only characters in str are specified in chars def self.only?(chars, str) - regex = Regexp.new('[^' + chars + ']') + regex = Regexp.new("[^#{chars}]") regex.match(str.encode('UTF-8', invalid: :replace, undef: :replace, replace: '')).nil? end diff --git a/core/main/autorun_engine/engine.rb b/core/main/autorun_engine/engine.rb index 3fc56a2a4e..4a992343ec 100644 --- a/core/main/autorun_engine/engine.rb +++ b/core/main/autorun_engine/engine.rb @@ -504,9 +504,9 @@ def prepare_command(mod, options, hb_id, replace_input, rule_token) if config.get('beef.extension.evasion.enable') evasion = BeEF::Extension::Evasion::Evasion.instance - command_body = evasion.obfuscate(command_module.output) + "\n\n" + command_body = "#{evasion.obfuscate(command_module.output)}\n\n" else - command_body = command_module.output + "\n\n" + command_body = "#{command_module.output}\n\n" end # @note prints the event to the console diff --git a/core/main/command.rb b/core/main/command.rb index 2a68763a33..d2ce034270 100644 --- a/core/main/command.rb +++ b/core/main/command.rb @@ -226,7 +226,7 @@ def map_file_to_url(file, path = nil, extension = nil, count = 1) def use(component) return if @beefjs_components.include? component - component_path = '/' + component + component_path = "/#{component}" component_path.gsub!(/beef./, '') component_path.gsub!(/\./, '/') component_path.replace "#{$root_dir}/core/main/client/#{component_path}.js" diff --git a/core/main/console/banners.rb b/core/main/console/banners.rb index d262338133..d3f0045390 100644 --- a/core/main/console/banners.rb +++ b/core/main/console/banners.rb @@ -35,7 +35,7 @@ def print_welcome_msg # data += "Blog: http://blog.beefproject.com\n" data += "Wiki: https://github.com/beefproject/beef/wiki\n" print_more data - print_info 'Project Creator: ' + 'Wade Alcorn'.red + ' (@WadeAlcorn)' + print_info "Project Creator: #{'Wade Alcorn'.red} (@WadeAlcorn)" end # diff --git a/core/main/handlers/browserdetails.rb b/core/main/handlers/browserdetails.rb index 4e401cc89c..b5d866ee5b 100644 --- a/core/main/handlers/browserdetails.rb +++ b/core/main/handlers/browserdetails.rb @@ -458,7 +458,7 @@ def setup print_debug("Hooked browser [id:#{zombie.id}] has IP [ip: #{zombie.ip}]") if !os_name.nil? and !os_version.nil? - BeEF::Core::Models::NetworkHost.create(hooked_browser: zombie, ip: zombie.ip, ntype: 'Host', os: os_name + '-' + os_version) + BeEF::Core::Models::NetworkHost.create(hooked_browser: zombie, ip: zombie.ip, ntype: 'Host', os: "#{os_name}-#{os_version}") elsif !os_name.nil? BeEF::Core::Models::NetworkHost.create(hooked_browser: zombie, ip: zombie.ip, ntype: 'Host', os: os_name) else diff --git a/core/main/handlers/modules/beefjs.rb b/core/main/handlers/modules/beefjs.rb index 3c95cb5129..0258025a9f 100644 --- a/core/main/handlers/modules/beefjs.rb +++ b/core/main/handlers/modules/beefjs.rb @@ -46,22 +46,22 @@ def build_beefjs!(req_host) print_debug "Excluding #{ext_js_sub_file} from core files obfuscation list" # do not obfuscate the file ext_js_sub_file_path = beef_js_path + ext_js_sub_file - ext_js_to_not_obfuscate << (File.read(ext_js_sub_file_path) + "\n\n") + ext_js_to_not_obfuscate << ("#{File.read(ext_js_sub_file_path)}\n\n") else ext_js_sub_file_path = beef_js_path + ext_js_sub_file - ext_js_to_obfuscate << (File.read(ext_js_sub_file_path) + "\n\n") + ext_js_to_obfuscate << ("#{File.read(ext_js_sub_file_path)}\n\n") end else # Evasion is not enabled, do not obfuscate anything ext_js_sub_file_path = beef_js_path + ext_js_sub_file - ext_js_to_not_obfuscate << (File.read(ext_js_sub_file_path) + "\n\n") + ext_js_to_not_obfuscate << ("#{File.read(ext_js_sub_file_path)}\n\n") end end # @note construct the beef_js string from file(s) beef_js_sub_files.each do |beef_js_sub_file| beef_js_sub_file_path = beef_js_path + beef_js_sub_file - beef_js << (File.read(beef_js_sub_file_path) + "\n\n") + beef_js << ("#{File.read(beef_js_sub_file_path)}\n\n") end # @note create the config for the hooked browser session @@ -152,9 +152,9 @@ def build_missing_beefjs_components(beefjs_components) config = BeEF::Core::Configuration.instance if config.get('beef.extension.evasion.enable') evasion = BeEF::Extension::Evasion::Evasion.instance - @body << evasion.obfuscate(File.read(component_path) + "\n\n") + @body << evasion.obfuscate("#{File.read(component_path)}\n\n") else - @body << (File.read(component_path) + "\n\n") + @body << ("#{File.read(component_path)}\n\n") end # @note finally we add the component to the list of components already generated so it does not get generated numerous times. diff --git a/core/main/handlers/modules/command.rb b/core/main/handlers/modules/command.rb index 006da1c2d1..55a15b4cdb 100644 --- a/core/main/handlers/modules/command.rb +++ b/core/main/handlers/modules/command.rb @@ -79,7 +79,7 @@ def add_command_instructions(command, hooked_browser) # //', "") ws.send(@output, hooked_browser.session) else - @body << (@output + "\n\n") + @body << ("#{@output}\n\n") end # @note prints the event to the console if BeEF::Settings.console? diff --git a/core/main/handlers/modules/legacybeefjs.rb b/core/main/handlers/modules/legacybeefjs.rb index 66d59b14aa..2580db0660 100644 --- a/core/main/handlers/modules/legacybeefjs.rb +++ b/core/main/handlers/modules/legacybeefjs.rb @@ -46,22 +46,22 @@ def legacy_build_beefjs!(req_host) print_debug "Excluding #{ext_js_sub_file} from core files obfuscation list" # do not obfuscate the file ext_js_sub_file_path = beef_js_path + ext_js_sub_file - ext_js_to_not_obfuscate << (File.read(ext_js_sub_file_path) + "\n\n") + ext_js_to_not_obfuscate << ("#{File.read(ext_js_sub_file_path)}\n\n") else ext_js_sub_file_path = beef_js_path + ext_js_sub_file - ext_js_to_obfuscate << (File.read(ext_js_sub_file_path) + "\n\n") + ext_js_to_obfuscate << ("#{File.read(ext_js_sub_file_path)}\n\n") end else # Evasion is not enabled, do not obfuscate anything ext_js_sub_file_path = beef_js_path + ext_js_sub_file - ext_js_to_not_obfuscate << (File.read(ext_js_sub_file_path) + "\n\n") + ext_js_to_not_obfuscate << ("#{File.read(ext_js_sub_file_path)}\n\n") end end # @note construct the beef_js string from file(s) beef_js_sub_files.each do |beef_js_sub_file| beef_js_sub_file_path = beef_js_path + beef_js_sub_file - beef_js << (File.read(beef_js_sub_file_path) + "\n\n") + beef_js << ("#{File.read(beef_js_sub_file_path)}\n\n") end # @note create the config for the hooked browser session @@ -152,9 +152,9 @@ def legacy_build_missing_beefjs_components(beefjs_components) config = BeEF::Core::Configuration.instance if config.get('beef.extension.evasion.enable') evasion = BeEF::Extension::Evasion::Evasion.instance - @body << evasion.obfuscate(File.read(component_path) + "\n\n") + @body << evasion.obfuscate("#{File.read(component_path)}\n\n") else - @body << (File.read(component_path) + "\n\n") + @body << ("#{File.read(component_path)}\n\n") end # @note finally we add the component to the list of components already generated so it does not get generated numerous times. diff --git a/core/main/handlers/modules/multistagebeefjs.rb b/core/main/handlers/modules/multistagebeefjs.rb index 40f5901827..3a6b53fbc8 100644 --- a/core/main/handlers/modules/multistagebeefjs.rb +++ b/core/main/handlers/modules/multistagebeefjs.rb @@ -46,22 +46,22 @@ def multi_stage_beefjs!(req_host) print_debug "Excluding #{ext_js_sub_file} from core files obfuscation list" # do not obfuscate the file ext_js_sub_file_path = beef_js_path + ext_js_sub_file - ext_js_to_not_obfuscate << (File.read(ext_js_sub_file_path) + "\n\n") + ext_js_to_not_obfuscate << ("#{File.read(ext_js_sub_file_path)}\n\n") else ext_js_sub_file_path = beef_js_path + ext_js_sub_file - ext_js_to_obfuscate << (File.read(ext_js_sub_file_path) + "\n\n") + ext_js_to_obfuscate << ("#{File.read(ext_js_sub_file_path)}\n\n") end else # Evasion is not enabled, do not obfuscate anything ext_js_sub_file_path = beef_js_path + ext_js_sub_file - ext_js_to_not_obfuscate << (File.read(ext_js_sub_file_path) + "\n\n") + ext_js_to_not_obfuscate << ("#{File.read(ext_js_sub_file_path)}\n\n") end end # @note construct the beef_js string from file(s) beef_js_sub_files.each do |beef_js_sub_file| beef_js_sub_file_path = beef_js_path + beef_js_sub_file - beef_js << (File.read(beef_js_sub_file_path) + "\n\n") + beef_js << ("#{File.read(beef_js_sub_file_path)}\n\n") end # @note create the config for the hooked browser session @@ -152,9 +152,9 @@ def legacy_build_missing_beefjs_components(beefjs_components) config = BeEF::Core::Configuration.instance if config.get('beef.extension.evasion.enable') evasion = BeEF::Extension::Evasion::Evasion.instance - @body << evasion.obfuscate(File.read(component_path) + "\n\n") + @body << evasion.obfuscate("#{File.read(component_path)}\n\n") else - @body << (File.read(component_path) + "\n\n") + @body << ("#{File.read(component_path)}\n\n") end # @note finally we add the component to the list of components already generated so it does not get generated numerous times. diff --git a/core/main/network_stack/assethandler.rb b/core/main/network_stack/assethandler.rb index a0ef71c573..7052cd28be 100644 --- a/core/main/network_stack/assethandler.rb +++ b/core/main/network_stack/assethandler.rb @@ -32,7 +32,7 @@ def bind_redirect(target, path = nil) @allocations[url] = { 'target' => target } @http_server.mount(url, BeEF::Core::NetworkStack::Handlers::Redirector.new(target)) @http_server.remap - print_info 'Redirector to [' + target + '] bound to url [' + url + ']' + print_info "Redirector to [#{target}] bound to url [#{url}]" url rescue StandardError => e print_error "Failed to mount #{path} : #{e.message}" @@ -53,7 +53,7 @@ def bind_raw(status, header, body, path = nil, _count = -1) BeEF::Core::NetworkStack::Handlers::Raw.new(status, header, body) ) @http_server.remap - print_info 'Raw HTTP bound to url [' + url + ']' + print_info "Raw HTTP bound to url [#{url}]" url rescue StandardError => e print_error "Failed to mount #{path} : #{e.message}" @@ -218,8 +218,8 @@ def unbind_socket(name) # @param [Integer] length The amount of characters to be used when generating a random URL # @return [String] Generated URL def build_url(path, extension, length = 20) - url = path.nil? ? '/' + rand(36**length).to_s(36) : path - url += extension.nil? ? '' : '.' + extension + url = path.nil? ? "/#{rand(36**length).to_s(36)}" : path + url += extension.nil? ? '' : ".#{extension}" url end diff --git a/core/main/network_stack/handlers/dynamicreconstruction.rb b/core/main/network_stack/handlers/dynamicreconstruction.rb index 039e8419ae..538b5a26c0 100644 --- a/core/main/network_stack/handlers/dynamicreconstruction.rb +++ b/core/main/network_stack/handlers/dynamicreconstruction.rb @@ -51,9 +51,9 @@ class DynamicReconstruction < BeEF::Core::Router::Router def check_packets checked = [] PQ.each do |packet| - next if checked.include?(packet[:beefhook] + ':' + String(packet[:stream_id])) + next if checked.include?("#{packet[:beefhook]}:#{String(packet[:stream_id])}") - checked << (packet[:beefhook] + ':' + String(packet[:stream_id])) + checked << ("#{packet[:beefhook]}:#{String(packet[:stream_id])}") pc = 0 PQ.each do |p| pc += 1 if packet[:beefhook] == p[:beefhook] and packet[:stream_id] == p[:stream_id] @@ -78,8 +78,8 @@ def check_packets execute(res) rescue JSON::ParserError => e print_debug 'Network stack could not decode packet stream.' - print_debug 'Dumping Stream Data [base64]: ' + data - print_debug 'Dumping Stream Data: ' + b64 + print_debug "Dumping Stream Data [base64]: #{data}" + print_debug "Dumping Stream Data: #{b64}" end end end diff --git a/core/main/rest/handlers/modules.rb b/core/main/rest/handlers/modules.rb index 3ae859419c..337b58a942 100644 --- a/core/main/rest/handlers/modules.rb +++ b/core/main/rest/handlers/modules.rb @@ -145,7 +145,7 @@ class Modules < BeEF::Core::Router::Router options = [] data.each { |k, v| options.push({ 'name' => k, 'value' => v }) } exec_results = BeEF::Module.execute(modk, params[:session], options) - exec_results.nil? ? '{"success":"false"}' : '{"success":"true","command_id":"' + exec_results.to_s + '"}' + exec_results.nil? ? '{"success":"false"}' : "{\"success\":\"true\",\"command_id\":\"#{exec_results.to_s}\"}" rescue StandardError print_error "Invalid JSON input for module '#{params[:mod_id]}'" error 400 # Bad Request diff --git a/core/ruby/print.rb b/core/ruby/print.rb index fbf932ac09..582b10f237 100644 --- a/core/ruby/print.rb +++ b/core/ruby/print.rb @@ -7,14 +7,14 @@ # Function used to print errors to the console # @param [String] s String to be printed def print_error(s) - puts Time.now.localtime.strftime('[%k:%M:%S]') + '[!]' + ' ' + s.to_s + puts "#{Time.now.localtime.strftime('[%k:%M:%S]')}[!] #{s.to_s}" BeEF.logger.error s.to_s end # Function used to print information to the console # @param [String] s String to be printed def print_info(s) - puts Time.now.localtime.strftime('[%k:%M:%S]') + '[*]' + ' ' + s.to_s + puts "#{Time.now.localtime.strftime('[%k:%M:%S]')}[*] #{s.to_s}" BeEF.logger.info s.to_s end @@ -27,7 +27,7 @@ def print_status(s) # Function used to print warning information # @param [String] s String to be printed def print_warning(s) - puts Time.now.localtime.strftime('[%k:%M:%S]') + '[!]' + ' ' + s.to_s + puts "#{Time.now.localtime.strftime('[%k:%M:%S]')}[!] #{s.to_s}" BeEF.logger.warn s.to_s end @@ -38,14 +38,14 @@ def print_debug(s) config = BeEF::Core::Configuration.instance return unless config.get('beef.debug') || BeEF::Core::Console::CommandLine.parse[:verbose] - puts Time.now.localtime.strftime('[%k:%M:%S]') + '[>]' + ' ' + s.to_s + puts "#{Time.now.localtime.strftime('[%k:%M:%S]')}[>] #{s.to_s}" BeEF.logger.debug s.to_s end # Function used to print successes to the console # @param [String] s String to be printed def print_success(s) - puts Time.now.localtime.strftime('[%k:%M:%S]') + '[+]' + ' ' + s.to_s + puts "#{Time.now.localtime.strftime('[%k:%M:%S]')}[+] #{s.to_s}" BeEF.logger.info s.to_s end diff --git a/extensions/admin_ui/classes/httpcontroller.rb b/extensions/admin_ui/classes/httpcontroller.rb index 85bc91bc4f..28a30e7664 100644 --- a/extensions/admin_ui/classes/httpcontroller.rb +++ b/extensions/admin_ui/classes/httpcontroller.rb @@ -87,7 +87,7 @@ def run(request, response) return end - function = @paths[path] || @paths[path + '/'] # check hash for '' and '/' + function = @paths[path] || @paths["#{path}/"] # check hash for '' and '/' if function.nil? print_error "[Admin UI] Path does not exist: #{path}" return diff --git a/extensions/admin_ui/controllers/modules/modules.rb b/extensions/admin_ui/controllers/modules/modules.rb index 291fffa53f..bcee8ec6c9 100644 --- a/extensions/admin_ui/controllers/modules/modules.rb +++ b/extensions/admin_ui/controllers/modules/modules.rb @@ -190,7 +190,7 @@ def retitle_recursive_tree(parent) retitle_recursive_tree([c]) if c.has_key?('cls') && c['cls'] == 'folder' end num_of_command_modules = command_module_branch['children'].length + num_of_subs - command_module_branch['text'] = command_module_branch['text'] + ' (' + num_of_command_modules.to_s + ')' + command_module_branch['text'] = "#{command_module_branch['text']} (#{num_of_command_modules.to_s})" end end diff --git a/extensions/demos/handler.rb b/extensions/demos/handler.rb index d52eb18fec..0106f65194 100644 --- a/extensions/demos/handler.rb +++ b/extensions/demos/handler.rb @@ -7,7 +7,7 @@ module BeEF module Extension module Demos class Handler < BeEF::Core::Router::Router - set :public_folder, File.expand_path(File.dirname(__FILE__)) + '/html/' + set :public_folder, "#{File.expand_path(File.dirname(__FILE__))}/html/" end end end diff --git a/extensions/dns/model.rb b/extensions/dns/model.rb index 04633aa871..d05d5f7d66 100644 --- a/extensions/dns/model.rb +++ b/extensions/dns/model.rb @@ -149,13 +149,7 @@ def format_callback(resource, response) minimum: response[6] } - format "t.respond!(Resolv::DNS::Name.create('%s'), " + - "Resolv::DNS::Name.create('%s'), " + - '%d, ' + - '%d, ' + - '%d, ' + - '%d, ' + - '%d)', + format "t.respond!(Resolv::DNS::Name.create('%s'), Resolv::DNS::Name.create('%s'), %d, %d, %d, %d, %d)", data elsif (response.is_a?(Symbol) && response.to_s =~ sym_regex) || response =~ sym_regex format 't.fail!(:%s)', response.to_sym diff --git a/extensions/dns_rebinding/dns_rebinding.rb b/extensions/dns_rebinding/dns_rebinding.rb index ed6cf8cc1e..c79135a342 100644 --- a/extensions/dns_rebinding/dns_rebinding.rb +++ b/extensions/dns_rebinding/dns_rebinding.rb @@ -17,7 +17,7 @@ def self.run_server(address, port) victim_ip = socket.peeraddr[2].to_s log "-------------------------------\n" - log '[Server] Incoming request from ' + victim_ip + "(Victim)\n" + log "[Server] Incoming request from #{victim_ip}(Victim)\n" response = File.read(File.expand_path('views/index.html', __dir__)) configuration = BeEF::Core::Configuration.instance @@ -29,10 +29,7 @@ def self.run_server(address, port) response.sub!('path_to_hookjs_template', hook_uri) start_string = socket.gets - socket.print "HTTP/1.1 200 OK\r\n" + - "Content-Type: text/html\r\n" + - "Content-Length: #{response.bytesize}\r\n" + - "Connection: close\r\n" + socket.print "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: #{response.bytesize}\r\nConnection: close\r\n" socket.print "\r\n" socket.print response socket.close @@ -81,7 +78,7 @@ def self.send_http_response(socket, response, heads = {}) end headers.to_a.each do |header, value| - socket.print header + ': ' + value + "\r\n" + socket.print "#{header}: #{value}\r\n" end socket.print "\r\n" @@ -115,7 +112,7 @@ def self.read_http_message(socket) def self.handle_victim(socket, http_message) log "[Victim]request from victim\n" - log http_message['start_string'].to_s + "\n" + log "#{http_message['start_string'].to_s}\n" if http_message['start_string'].include?('POST') # Get result from POST query @@ -123,12 +120,12 @@ def self.handle_victim(socket, http_message) # Read query on which asked victim query = http_message['start_string'][/path=([^HTP]+)/, 1][0..-2] - log '[Victim]asked path: ' + query + "\n" + log "[Victim]asked path: #{query}\n" length = http_message['headers']['Content-Length'].to_i content_type = http_message['headers']['Content-Type'] - log '[Victim]Content-type: ' + content_type.to_s + "\n" - log '[Vicitm]Length: ' + length.to_s + "\n" + log "[Victim]Content-type: #{content_type.to_s}\n" + log "[Vicitm]Length: #{length.to_s}\n" response = http_message['response'] log "[Victim]Get content!\n" @@ -157,7 +154,7 @@ def self.handle_victim(socket, http_message) @mutex_queries.lock log "[Victim]Get the last query\n" last_query = @queries.pop - log '[Victim]Last query:' + last_query.to_s + "\n" + log "[Victim]Last query:#{last_query.to_s}\n" @mutex_queries.unlock response = last_query[2] @@ -175,7 +172,7 @@ def self.handle_owner(socket, http_message) if http_message['start_string'].include?('GET') unless path.nil? - log '[Owner]Need path: ' + path + "\n" + log "[Owner]Need path: #{path}\n" @queries.push(['GET', path, '']) end elsif http_message['start_string'].include?('POST') diff --git a/extensions/webrtc/handlers.rb b/extensions/webrtc/handlers.rb index 4e3ee830ca..fe4b237289 100644 --- a/extensions/webrtc/handlers.rb +++ b/extensions/webrtc/handlers.rb @@ -90,7 +90,7 @@ def setup() BeEF::Core::Logger.instance.register('WebRTC', "Browser:#{zombie_db.id} received message from Browser:#{peer_zombie_db.id}: #{message}") # Perform logic depending on message (updating database) - puts "message = '" + message + "'" + puts "message = '#{message}'" if (message == 'ICE Status: connected') # Find existing status message stat = BeEF::Core::Models::Rtcstatus.first(hooked_browser_id: zombie_db.id, target_hooked_browser_id: peer_zombie_db.id) || nil diff --git a/spec/support/beef_test.rb b/spec/support/beef_test.rb index 2a26b551ce..b8f38eeed1 100644 --- a/spec/support/beef_test.rb +++ b/spec/support/beef_test.rb @@ -13,7 +13,7 @@ class BeefTest def self.save_screenshot(session, dir = nil) outputDir = dir || BEEF_TEST_DIR Dir.mkdir(outputDir) unless File.directory?(outputDir) - filename = outputDir + Time.now.strftime('%Y-%m-%d--%H-%M-%S-%N') + '.png' + filename = "#{outputDir}#{Time.now.strftime('%Y-%m-%d--%H-%M-%S-%N')}.png" session.driver.browser.save_screenshot(filename) end diff --git a/spec/support/constants.rb b/spec/support/constants.rb index 4bd7b1d9e7..addf814413 100644 --- a/spec/support/constants.rb +++ b/spec/support/constants.rb @@ -8,24 +8,24 @@ # General constants ATTACK_DOMAIN = 'localhost'.freeze VICTIM_DOMAIN = '127.0.0.1'.freeze -ATTACK_URL = 'http://' + ATTACK_DOMAIN + ':3000/ui/panel' -VICTIM_URL = 'http://' + VICTIM_DOMAIN + ':3000/demos/basic.html' +ATTACK_URL = "http://#{ATTACK_DOMAIN}:3000/ui/panel" +VICTIM_URL = "http://#{VICTIM_DOMAIN}:3000/demos/basic.html" # Credentials BEEF_USER = ENV['TEST_BEEF_USER'] || 'beef' BEEF_PASSWD = ENV['TEST_BEEF_PASS'] || 'beef' # RESTful API root endpoints -RESTAPI_HOOKS = 'http://' + ATTACK_DOMAIN + ':3000/api/hooks' -RESTAPI_LOGS = 'http://' + ATTACK_DOMAIN + ':3000/api/logs' -RESTAPI_MODULES = 'http://' + ATTACK_DOMAIN + ':3000/api/modules' -RESTAPI_NETWORK = 'http://' + ATTACK_DOMAIN + ':3000/api/network' -RESTAPI_PROXY = 'http://' + ATTACK_DOMAIN + ':3000/api/proxy' -RESTAPI_DNS = 'http://' + ATTACK_DOMAIN + ':3000/api/dns' -RESTAPI_SENG = 'http://' + ATTACK_DOMAIN + ':3000/api/seng' -RESTAPI_ADMIN = 'http://' + ATTACK_DOMAIN + ':3000/api/admin' -RESTAPI_WEBRTC = 'http://' + ATTACK_DOMAIN + ':3000/api/webrtc' -RESTAPI_REQUESTER = 'http://' + ATTACK_DOMAIN + ':3000/api/requester' +RESTAPI_HOOKS = "http://#{ATTACK_DOMAIN}:3000/api/hooks" +RESTAPI_LOGS = "http://#{ATTACK_DOMAIN}:3000/api/logs" +RESTAPI_MODULES = "http://#{ATTACK_DOMAIN}:3000/api/modules" +RESTAPI_NETWORK = "http://#{ATTACK_DOMAIN}:3000/api/network" +RESTAPI_PROXY = "http://#{ATTACK_DOMAIN}:3000/api/proxy" +RESTAPI_DNS = "http://#{ATTACK_DOMAIN}:3000/api/dns" +RESTAPI_SENG = "http://#{ATTACK_DOMAIN}:3000/api/seng" +RESTAPI_ADMIN = "http://#{ATTACK_DOMAIN}:3000/api/admin" +RESTAPI_WEBRTC = "http://#{ATTACK_DOMAIN}:3000/api/webrtc" +RESTAPI_REQUESTER = "http://#{ATTACK_DOMAIN}:3000/api/requester" # Other PAGE_LOAD_TIMEOUT = 5 diff --git a/spec/support/ui_support.rb b/spec/support/ui_support.rb index 77b90ddd2a..5c2f1b3435 100644 --- a/spec/support/ui_support.rb +++ b/spec/support/ui_support.rb @@ -56,7 +56,7 @@ def navigate_to_category(session, category_name = nil) session.click_on('Commands') expect(session).to have_content(category_name, wait: PAGE_LOAD_TIMEOUT) - session.first(:link_or_button, category_name + ' ').click + session.first(:link_or_button, "#{category_name} ").click end def expand_category_tree(session, category, module_name = nil) @@ -96,11 +96,11 @@ def collapse_category_tree(session, category) category.reverse.each do |category_name| # Collapse the sub-folder session.scroll_to(category_name) - session.first(:link_or_button, category_name + ' ').click + session.first(:link_or_button, "#{category_name} ").click end else session.scroll_to(category) - session.first(:link_or_button, category + ' ').click + session.first(:link_or_button, "#{category} ").click end end From 705b5c203c4ee547bbb3a005060455bcf9edd51f Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:40:49 +0530 Subject: [PATCH 19/85] rubocop --only Layout/RescueEnsureAlignment -a --- spec/spec_helper.rb | 6 +++--- spec/support/ui_support.rb | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index bd0305420e..4f80f4a249 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -179,7 +179,7 @@ def reset_beef_db begin db_file = BeEF::Core::Configuration.instance.get('beef.database.file') File.delete(db_file) if File.exist?(db_file) - rescue => e + rescue => e print_error("Could not remove '#{db_file}' database file: #{e.message}") end end @@ -295,9 +295,9 @@ def beef_server_running?(uri_str) uri = URI.parse(uri_str) response = Net::HTTP.get_response(uri) response.is_a?(Net::HTTPSuccess) - rescue Errno::ECONNREFUSED + rescue Errno::ECONNREFUSED return false # Connection refused means the server is not running - rescue StandardError => e + rescue StandardError => e return false # Any other error means the server is not running end end diff --git a/spec/support/ui_support.rb b/spec/support/ui_support.rb index 5c2f1b3435..202050fde1 100644 --- a/spec/support/ui_support.rb +++ b/spec/support/ui_support.rb @@ -73,7 +73,7 @@ def expand_category_tree(session, category, module_name = nil) # scroll to the element session.scroll_to(element) - rescue Selenium::WebDriver::Error::StaleElementReferenceError => e + rescue Selenium::WebDriver::Error::StaleElementReferenceError => e puts "StaleElementReferenceError: #{element_text}" puts e.message From f4de42eab5f396444109687d3e932dae6ea551d1 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:41:26 +0530 Subject: [PATCH 20/85] rubocop --only Layout/TrailingEmptyLines -a --- spec/beef/extensions/adminui_spec.rb | 2 +- spec/features/all_modules_spec.rb | 2 +- spec/features/debug_modules_spec.rb | 2 +- spec/requests/login_spec.rb | 2 +- spec/spec_helper.rb | 2 +- spec/support/constants.rb | 2 +- spec/support/ui_support.rb | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/spec/beef/extensions/adminui_spec.rb b/spec/beef/extensions/adminui_spec.rb index a7f0a6ba01..0ccb22f7fb 100644 --- a/spec/beef/extensions/adminui_spec.rb +++ b/spec/beef/extensions/adminui_spec.rb @@ -49,4 +49,4 @@ request.add_header('REMOTE_ADDR','192.168.0.20') expect(ui.get_ip(request)).to eq '192.168.0.20' end -end \ No newline at end of file +end diff --git a/spec/features/all_modules_spec.rb b/spec/features/all_modules_spec.rb index 4b979a315c..171c131af6 100644 --- a/spec/features/all_modules_spec.rb +++ b/spec/features/all_modules_spec.rb @@ -60,4 +60,4 @@ end end end -end \ No newline at end of file +end diff --git a/spec/features/debug_modules_spec.rb b/spec/features/debug_modules_spec.rb index ebf066127b..01ac9e7f2b 100644 --- a/spec/features/debug_modules_spec.rb +++ b/spec/features/debug_modules_spec.rb @@ -71,4 +71,4 @@ end end -end \ No newline at end of file +end diff --git a/spec/requests/login_spec.rb b/spec/requests/login_spec.rb index a930c35212..88225f83cd 100644 --- a/spec/requests/login_spec.rb +++ b/spec/requests/login_spec.rb @@ -89,4 +89,4 @@ attacker.driver.browser.close victim.driver.browser.close end -end \ No newline at end of file +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 4f80f4a249..fca32abf1d 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -331,4 +331,4 @@ def stop_beef_server(pid) Process.wait(pid) unless pid.nil? # Ensure the process has exited and the port is released pid = nil end -end \ No newline at end of file +end diff --git a/spec/support/constants.rb b/spec/support/constants.rb index addf814413..b84484c139 100644 --- a/spec/support/constants.rb +++ b/spec/support/constants.rb @@ -30,4 +30,4 @@ # Other PAGE_LOAD_TIMEOUT = 5 SERVER_START_TIMEOUT = 5 -BROWSER_HOOKING_TIMEOUT = 10 \ No newline at end of file +BROWSER_HOOKING_TIMEOUT = 10 diff --git a/spec/support/ui_support.rb b/spec/support/ui_support.rb index 202050fde1..5312d223bb 100644 --- a/spec/support/ui_support.rb +++ b/spec/support/ui_support.rb @@ -113,4 +113,4 @@ def click_on_module(session, category, module_name) expect(session).to have_content(module_name, wait: PAGE_LOAD_TIMEOUT) modules = session.all(:link_or_button, module_name) modules[0].click -end \ No newline at end of file +end From 765f4d4545fec5b2652e73cb4e4fb2e966b9c6bd Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:41:52 +0530 Subject: [PATCH 21/85] rubocop --only Layout/EmptyLinesAroundExceptionHandlingKeywords -a --- spec/support/ui_support.rb | 1 - 1 file changed, 1 deletion(-) diff --git a/spec/support/ui_support.rb b/spec/support/ui_support.rb index 5312d223bb..95778e2ea9 100644 --- a/spec/support/ui_support.rb +++ b/spec/support/ui_support.rb @@ -74,7 +74,6 @@ def expand_category_tree(session, category, module_name = nil) # scroll to the element session.scroll_to(element) rescue Selenium::WebDriver::Error::StaleElementReferenceError => e - puts "StaleElementReferenceError: #{element_text}" puts e.message next From 5e5dc3edb432f5d5e9ad1e311dff99a76aed961e Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:42:20 +0530 Subject: [PATCH 22/85] rubocop --only Style/RedundantReturn -a --- core/main/router/router.rb | 6 +++--- extensions/admin_ui/api/handler.rb | 2 +- extensions/dns/api.rb | 2 +- spec/spec_helper.rb | 6 +++--- spec/support/ui_support.rb | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/core/main/router/router.rb b/core/main/router/router.rb index a91ea007ab..6ce3ca06ef 100644 --- a/core/main/router/router.rb +++ b/core/main/router/router.rb @@ -269,7 +269,7 @@ def error_page_404 case config.get('beef.http.web_server_imitation.type') when 'apache' - return <<-EOF + <<-EOF 404 Not Found @@ -282,7 +282,7 @@ def error_page_404 EOF when 'iis' - return <<-EOF + <<-EOF The page cannot be found @@ -314,7 +314,7 @@ def error_page_404 EOF when 'nginx' - return <<-EOF + <<-EOF 404 Not Found diff --git a/extensions/admin_ui/api/handler.rb b/extensions/admin_ui/api/handler.rb index 04a387c2cd..11e03d654f 100644 --- a/extensions/admin_ui/api/handler.rb +++ b/extensions/admin_ui/api/handler.rb @@ -46,7 +46,7 @@ def self.evaluate_and_minify(content, params) print_debug "[AdminUI] Minified #{evaluated.size} bytes to #{minified.size} bytes" - return minified + minified end def self.write_minified_js(name, content) diff --git a/extensions/dns/api.rb b/extensions/dns/api.rb index f4e14551c2..e2d92063fb 100644 --- a/extensions/dns/api.rb +++ b/extensions/dns/api.rb @@ -67,7 +67,7 @@ def self.get_dns_config end end - return servers, interfaces, address, port, protocol, upstream_servers + [servers, interfaces, address, port, protocol, upstream_servers] end # Mounts the handler for processing DNS RESTful API requests. diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index fca32abf1d..3013d5c283 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -287,7 +287,7 @@ def start_beef_server http_hook_server.start end - return pid + pid end def beef_server_running?(uri_str) @@ -296,9 +296,9 @@ def beef_server_running?(uri_str) response = Net::HTTP.get_response(uri) response.is_a?(Net::HTTPSuccess) rescue Errno::ECONNREFUSED - return false # Connection refused means the server is not running + false # Connection refused means the server is not running rescue StandardError => e - return false # Any other error means the server is not running + false # Any other error means the server is not running end end diff --git a/spec/support/ui_support.rb b/spec/support/ui_support.rb index 95778e2ea9..0b2a0194b5 100644 --- a/spec/support/ui_support.rb +++ b/spec/support/ui_support.rb @@ -26,7 +26,7 @@ def start_beef_and_hook_browser() expect(beef_session).to have_content('Commands', wait: PAGE_LOAD_TIMEOUT) beef_session.click_on('Commands') - return pid, beef_session, hooked_browser + [pid, beef_session, hooked_browser] end def stop_beef_and_unhook_browser(pid, beef_session, hooked_browser) From ecc9664c9fd41862240113a3069a440f356487f6 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:43:13 +0530 Subject: [PATCH 23/85] rubocop --only Style/FetchEnvVar -a --- beef | 2 +- spec/beef/core/main/autorun_engine/autorun_engine_spec.rb | 2 +- spec/beef/core/main/handlers/browser_details_handler_spec.rb | 2 +- spec/beef/extensions/websocket_hooked_browser_spec.rb | 2 +- spec/beef/modules/debug/test_beef_debugs_spec.rb | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/beef b/beef index 674151cc66..7ad1f5b067 100755 --- a/beef +++ b/beef @@ -93,7 +93,7 @@ BeEF.logger.level = config.get('beef.debug') ? Logger::DEBUG : Logger::WARN # # @note Check the system language settings for UTF-8 compatibility # -env_lang = ENV['LANG'] +env_lang = ENV.fetch('LANG', nil) if env_lang !~ /(utf8|utf-8)/i print_warning "Warning: System language $LANG '#{env_lang}' does not appear to be UTF-8 compatible." if env_lang =~ /\A([a-z]+_[a-z]+)\./i diff --git a/spec/beef/core/main/autorun_engine/autorun_engine_spec.rb b/spec/beef/core/main/autorun_engine/autorun_engine_spec.rb index 2e133bb49c..05e3721dab 100644 --- a/spec/beef/core/main/autorun_engine/autorun_engine_spec.rb +++ b/spec/beef/core/main/autorun_engine/autorun_engine_spec.rb @@ -87,7 +87,7 @@ @caps = CONFIG['common_caps'].merge(CONFIG['browser_caps'][TASK_ID]) @caps['name'] = self.class.description || ENV['name'] || 'no-name' @caps['browserstack.local'] = true - @caps['browserstack.localIdentifier'] = ENV['BROWSERSTACK_LOCAL_IDENTIFIER'] + @caps['browserstack.localIdentifier'] = ENV.fetch('BROWSERSTACK_LOCAL_IDENTIFIER', nil) @driver = Selenium::WebDriver.for(:remote, url: "http://#{CONFIG['user']}:#{CONFIG['key']}@#{CONFIG['server']}/wd/hub", diff --git a/spec/beef/core/main/handlers/browser_details_handler_spec.rb b/spec/beef/core/main/handlers/browser_details_handler_spec.rb index 329b257b5a..6c59e98dbd 100644 --- a/spec/beef/core/main/handlers/browser_details_handler_spec.rb +++ b/spec/beef/core/main/handlers/browser_details_handler_spec.rb @@ -83,7 +83,7 @@ @caps['name'] = self.class.description || ENV['name'] || 'no-name' @caps['browserstack.local'] = true @caps['browserstack.video'] = true - @caps['browserstack.localIdentifier'] = ENV['BROWSERSTACK_LOCAL_IDENTIFIER'] + @caps['browserstack.localIdentifier'] = ENV.fetch('BROWSERSTACK_LOCAL_IDENTIFIER', nil) @driver = Selenium::WebDriver.for(:remote, url: "http://#{CONFIG['user']}:#{CONFIG['key']}@#{CONFIG['server']}/wd/hub", diff --git a/spec/beef/extensions/websocket_hooked_browser_spec.rb b/spec/beef/extensions/websocket_hooked_browser_spec.rb index c2222fe855..776f6fbb8f 100644 --- a/spec/beef/extensions/websocket_hooked_browser_spec.rb +++ b/spec/beef/extensions/websocket_hooked_browser_spec.rb @@ -81,7 +81,7 @@ @caps = CONFIG['common_caps'].merge(CONFIG['browser_caps'][TASK_ID]) @caps['name'] = self.class.description || ENV['name'] || 'no-name' @caps['browserstack.local'] = true - @caps['browserstack.localIdentifier'] = ENV['BROWSERSTACK_LOCAL_IDENTIFIER'] + @caps['browserstack.localIdentifier'] = ENV.fetch('BROWSERSTACK_LOCAL_IDENTIFIER', nil) @driver = Selenium::WebDriver.for(:remote, url: "http://#{CONFIG['user']}:#{CONFIG['key']}@#{CONFIG['server']}/wd/hub", diff --git a/spec/beef/modules/debug/test_beef_debugs_spec.rb b/spec/beef/modules/debug/test_beef_debugs_spec.rb index 6c6e85c5e9..7b1def5098 100644 --- a/spec/beef/modules/debug/test_beef_debugs_spec.rb +++ b/spec/beef/modules/debug/test_beef_debugs_spec.rb @@ -81,7 +81,7 @@ @caps = CONFIG['common_caps'].merge(CONFIG['browser_caps'][TASK_ID]) @caps['name'] = self.class.description || ENV['name'] || 'no-name' @caps['browserstack.local'] = true - @caps['browserstack.localIdentifier'] = ENV['BROWSERSTACK_LOCAL_IDENTIFIER'] + @caps['browserstack.localIdentifier'] = ENV.fetch('BROWSERSTACK_LOCAL_IDENTIFIER', nil) @driver = Selenium::WebDriver.for(:remote, url: "http://#{CONFIG['user']}:#{CONFIG['key']}@#{CONFIG['server']}/wd/hub", options: @caps) From 791c4309254425487710e34f36a19f9aefa622d2 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:44:07 +0530 Subject: [PATCH 24/85] rubocop --only Style/DefWithParentheses -a --- extensions/webrtc/handlers.rb | 4 ++-- spec/support/ui_support.rb | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/webrtc/handlers.rb b/extensions/webrtc/handlers.rb index fe4b237289..95875b5b5a 100644 --- a/extensions/webrtc/handlers.rb +++ b/extensions/webrtc/handlers.rb @@ -20,7 +20,7 @@ def initialize(data) setup() end - def setup() + def setup # validates the hook token beef_hook = @data['beefhook'] || nil @@ -65,7 +65,7 @@ def initialize(data) setup() end - def setup() + def setup # validates the hook token beef_hook = @data['beefhook'] || nil (print_error 'beefhook is null';return) if beef_hook.nil? diff --git a/spec/support/ui_support.rb b/spec/support/ui_support.rb index 0b2a0194b5..0af32007c2 100644 --- a/spec/support/ui_support.rb +++ b/spec/support/ui_support.rb @@ -7,7 +7,7 @@ require 'rest-client' require 'spec/support/constants.rb' -def start_beef_and_hook_browser() +def start_beef_and_hook_browser reset_beef_db pid = start_beef_server_and_wait beef_session = BeefTest.login From c2166a973edcae8fbbca193cd3953cafe464455e Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:46:19 +0530 Subject: [PATCH 25/85] Exclude spec/**/* from cops --- .rubocop.yml | 1 + spec/beef/api/auth_rate_spec.rb | 111 ++++++------ spec/beef/core/extensions_spec.rb | 3 + spec/beef/core/filter/filters_spec.rb | 88 ++++++--- .../autorun_engine/autorun_engine_spec.rb | 5 +- spec/beef/core/main/configuration_spec.rb | 3 +- .../handlers/browser_details_handler_spec.rb | 5 +- .../core/main/models/browser_details_spec.rb | 2 + .../handlers/dynamic_reconstruction_spec.rb | 10 +- .../network_stack/handlers/redirector_spec.rb | 13 +- spec/beef/core/modules_spec.rb | 4 +- spec/beef/extensions/adminui_spec.rb | 29 +-- spec/beef/extensions/dns_spec.rb | 84 +++++---- spec/beef/extensions/network_spec.rb | 9 +- spec/beef/extensions/proxy_spec.rb | 2 + spec/beef/extensions/qrcode_spec.rb | 2 + spec/beef/extensions/requester_spec.rb | 4 +- .../extensions/social_engineering_spec.rb | 4 +- .../websocket_hooked_browser_spec.rb | 7 +- spec/beef/extensions/websocket_spec.rb | 2 +- .../modules/debug/test_beef_debugs_spec.rb | 3 +- spec/beef/security_checks_spec.rb | 4 +- spec/features/all_modules_spec.rb | 98 +++++----- spec/features/debug_modules_spec.rb | 118 ++++++------ spec/requests/beef_test_spec.rb | 171 +++++++++--------- spec/requests/login_spec.rb | 4 +- spec/spec_helper.rb | 63 +++---- spec/support/beef_test.rb | 4 +- spec/support/constants.rb | 26 +-- spec/support/ui_support.rb | 152 ++++++++-------- 30 files changed, 549 insertions(+), 482 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index 6da722c053..f6cbe8160c 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -5,6 +5,7 @@ AllCops: Exclude: - "tools/**/*" + - "spec/**/*" - "test/**/*" Layout/LineLength: diff --git a/spec/beef/api/auth_rate_spec.rb b/spec/beef/api/auth_rate_spec.rb index 851342603a..77ff65a606 100644 --- a/spec/beef/api/auth_rate_spec.rb +++ b/spec/beef/api/auth_rate_spec.rb @@ -5,66 +5,67 @@ # RSpec.describe 'BeEF API Rate Limit', run_on_long_tests: true do - before(:each) do - @pid = start_beef_server_and_wait - @username = @config.get('beef.credentials.user') - @password = @config.get('beef.credentials.passwd') - end - after(:each) do - # Shutting down server - Process.kill('KILL', @pid) unless @pid.nil? - Process.wait(@pid) unless @pid.nil? # Ensure the process has exited and the port is released - @pid = nil - end + before(:each) do + @pid = start_beef_server_and_wait + @username = @config.get('beef.credentials.user') + @password = @config.get('beef.credentials.passwd') + end - it 'confirm correct creds are successful' do - test_api = BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, @password) - expect(@config.get('beef.credentials.user')).to eq('beef') - expect(@config.get('beef.credentials.passwd')).to eq('beef') - expect(test_api.auth()[:payload]).not_to eql('401 Unauthorized') - expect(test_api.auth()[:payload]['success']).to be(true) # valid pass should succeed - end + after(:each) do + # Shutting down server + Process.kill("KILL", @pid) unless @pid.nil? + Process.wait(@pid) unless @pid.nil? # Ensure the process has exited and the port is released + @pid = nil + end - it 'confirm incorrect creds are unsuccessful' do - sleep 0.5 - test_api = BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, 'wrong_passowrd') - expect(test_api.auth()[:payload]).to eql('401 Unauthorized') # all (unless the valid is first 1 in 10 chance) - end + it 'confirm correct creds are successful' do + test_api = BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, @password) + expect(@config.get('beef.credentials.user')).to eq('beef') + expect(@config.get('beef.credentials.passwd')).to eq('beef') + expect(test_api.auth()[:payload]).not_to eql("401 Unauthorized") + expect(test_api.auth()[:payload]["success"]).to be(true) # valid pass should succeed + end + + it 'confirm incorrect creds are unsuccessful' do + sleep 0.5 + test_api = BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, "wrong_passowrd") + expect(test_api.auth()[:payload]).to eql("401 Unauthorized") # all (unless the valid is first 1 in 10 chance) + end + + it 'adheres to 9 bad passwords then 1 correct auth rate limits' do + # create api structures with bad passwords and one good + passwds = (1..9).map { |i| "bad_password"} # incorrect password + passwds.push @password # correct password + apis = passwds.map { |pswd| BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, pswd) } - it 'adheres to 9 bad passwords then 1 correct auth rate limits' do - # create api structures with bad passwords and one good - passwds = (1..9).map { |i| 'bad_password'} # incorrect password - passwds.push @password # correct password - apis = passwds.map { |pswd| BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, pswd) } - - (0..apis.length-1).each do |i| - test_api = apis[i] - expect(test_api.auth()[:payload]).to eql('401 Unauthorized') # all (unless the valid is first 1 in 10 chance) - end - end - - it 'adheres to random bad passords and 1 correct auth rate limits' do - # create api structures with bad passwords and one good - passwds = (1..9).map { |i| 'bad_password'} # incorrect password - passwds.push @password # correct password - apis = passwds.map { |pswd| BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, pswd) } + (0..apis.length-1).each do |i| + test_api = apis[i] + expect(test_api.auth()[:payload]).to eql("401 Unauthorized") # all (unless the valid is first 1 in 10 chance) + end + end + + it 'adheres to random bad passords and 1 correct auth rate limits' do + # create api structures with bad passwords and one good + passwds = (1..9).map { |i| "bad_password"} # incorrect password + passwds.push @password # correct password + apis = passwds.map { |pswd| BeefRestClient.new('http', ATTACK_DOMAIN, '3000', @username, pswd) } - apis.shuffle! # random order for next iteration - apis = apis.reverse if (apis[0].is_pass?(@password)) # prevent the first from having valid passwd + apis.shuffle! # random order for next iteration + apis = apis.reverse if (apis[0].is_pass?(@password)) # prevent the first from having valid passwd - (0..apis.length-1).each do |i| - test_api = apis[i] - if (test_api.is_pass?(@password)) - sleep 0.5 - expect(@config.get('beef.credentials.user')).to eq('beef') - expect(@config.get('beef.credentials.passwd')).to eq('beef') - expect(test_api.auth()[:payload]).not_to eql('401 Unauthorized') - expect(test_api.auth()[:payload]['success']).to be(true) # valid pass should succeed - else - expect(test_api.auth()[:payload]).to eql('401 Unauthorized') + (0..apis.length-1).each do |i| + test_api = apis[i] + if (test_api.is_pass?(@password)) + sleep 0.5 + expect(@config.get('beef.credentials.user')).to eq('beef') + expect(@config.get('beef.credentials.passwd')).to eq('beef') + expect(test_api.auth()[:payload]).not_to eql("401 Unauthorized") + expect(test_api.auth()[:payload]["success"]).to be(true) # valid pass should succeed + else + expect(test_api.auth()[:payload]).to eql("401 Unauthorized") + end end - end - end - + end + end diff --git a/spec/beef/core/extensions_spec.rb b/spec/beef/core/extensions_spec.rb index a9f496f052..b1c22544f9 100644 --- a/spec/beef/core/extensions_spec.rb +++ b/spec/beef/core/extensions_spec.rb @@ -1,4 +1,5 @@ RSpec.describe 'BeEF Extensions' do + it 'loaded successfully' do expect { BeEF::Extensions.load @@ -15,5 +16,7 @@ expect(v).to have_key('loaded') expect(v['loaded']).to be(true) end + end + end diff --git a/spec/beef/core/filter/filters_spec.rb b/spec/beef/core/filter/filters_spec.rb index 3458f6c64e..353c350dee 100644 --- a/spec/beef/core/filter/filters_spec.rb +++ b/spec/beef/core/filter/filters_spec.rb @@ -1,5 +1,7 @@ RSpec.describe 'BeEF Filters' do + context 'is_non_empty_string?' do + it 'nil' do expect(BeEF::Filters::is_non_empty_string?(nil)).to be(false) end @@ -9,7 +11,7 @@ end it 'Empty String' do - expect(BeEF::Filters::is_non_empty_string?('')).to be(false) + expect(BeEF::Filters::is_non_empty_string?("")).to be(false) end it 'null' do @@ -17,27 +19,29 @@ end it 'First char is num' do - expect(BeEF::Filters::is_non_empty_string?('0')).to be(true) + expect(BeEF::Filters::is_non_empty_string?("0")).to be(true) end it 'First char is alpha' do - expect(BeEF::Filters::is_non_empty_string?('A')).to be(true) + expect(BeEF::Filters::is_non_empty_string?("A")).to be(true) end it 'Four num chars' do - expect(BeEF::Filters::is_non_empty_string?('3333')).to be(true) + expect(BeEF::Filters::is_non_empty_string?("3333")).to be(true) end it 'Four num chars begining with alpha' do - expect(BeEF::Filters::is_non_empty_string?('A3333')).to be(true) + expect(BeEF::Filters::is_non_empty_string?("A3333")).to be(true) end it 'Four num chars begining with null' do expect(BeEF::Filters::is_non_empty_string?("\x003333")).to be(true) end + end context 'only?' do + it 'success' do expect(BeEF::Filters::only?('A', 'A')).to be(true) end @@ -45,9 +49,11 @@ it 'fail' do expect(BeEF::Filters::only?('A', 'B')).to be(false) end + end context 'exists?' do + it 'success' do expect(BeEF::Filters::exists?('A', 'A')).to be(true) end @@ -55,12 +61,15 @@ it 'fail' do expect(BeEF::Filters::exists?('A', 'B')).to be(false) end - end + end + context 'has_null?' do + context 'false with' do + it 'general' do - chars = [nil, '', "\x01", "\xFF", 'A', 'A3333', '0', '}', '.', '+', '-', '-1', '0.A', '3333', '33 33', ' AAAAA', 'AAAAAA '] + chars = [nil, "", "\x01", "\xFF", "A", "A3333", "0", "}", ".", "+", "-", "-1", "0.A", "3333", "33 33", " AAAAA", "AAAAAA "] chars.each do |c| expect(BeEF::Filters::has_null?(c)).to be(false) end @@ -73,9 +82,11 @@ expect(BeEF::Filters::has_null?(str)).to be(false) end end + end context 'true with' do + it 'general' do chars = ["\x00", "A\x00", "AAAAAA\x00", "\x00A", "\x00AAAAAAAA", "A\x00A", "AAAAA\x00AAAA", "A\n\r\x00", "\x00\n\rA", "A\n\r\x00\n\rA", "\tA\x00A"] chars.each do |c| @@ -99,13 +110,17 @@ expect(BeEF::Filters::has_null?(str)).to be(true) end end + end + end context 'has_non_printable_char?' do + context 'false with' do + it 'general' do - chars = [nil, '', 'A', 'A3333', '0', '}', '.', '+', '-', '-1', '0.A', '3333', ' 0AAAAA', ' 0AAA '] + chars = [nil, "", "A", "A3333", "0", "}", ".", "+", "-", "-1", "0.A", "3333", " 0AAAAA", " 0AAA "] chars.each do |c| expect(BeEF::Filters::has_non_printable_char?(c)).to be(false) end @@ -128,9 +143,11 @@ expect(BeEF::Filters::has_non_printable_char?(c)).to be(false) end end + end context 'true with' do + it 'general' do chars = ["\x00", "\x01", "\x02", "A\x03", "\x04A", "\x0033333", "\x00AAAAAA", " AAAAA\x00", "\t\x00AAAAA", "\n\x00AAAAA", "\n\r\x00AAAAAAAAA", "AAAAAAA\x00AAAAAAA", "\n\x00"] chars.each do |c| @@ -146,94 +163,107 @@ expect(BeEF::Filters::has_non_printable_char?(str)).to be(true) end end - end + end + end context 'nums_only?' do + it 'false with general' do - chars = [nil, 1, '', 'A', 'A3333', "\x003333", '}', '.', '+', '-', '-1'] + chars = [nil, 1, "", "A", "A3333", "\x003333", "}", ".", "+", "-", "-1"] chars.each do |c| expect(BeEF::Filters::nums_only?(c)).to be(false) end end it 'true with general' do - chars = ['0', '333'] + chars = ["0", "333"] chars.each do |c| expect(BeEF::Filters::nums_only?(c)).to be(true) end end + end context 'is_valid_float?' do + it 'false with general' do - chars = [nil, 1, '', 'A', 'A3333', "\x003333", '}', '.', '+', '-', '-1', '0', '333', '0.A'] + chars = [nil, 1, "", "A", "A3333", "\x003333", "}", ".", "+", "-", "-1", "0", "333", "0.A"] chars.each do |c| expect(BeEF::Filters::is_valid_float?(c)).to be(false) end end it 'true with general' do - chars = ['33.33', '0.0', '1.0', '0.1'] + chars = ["33.33", "0.0", "1.0", "0.1"] chars.each do |c| expect(BeEF::Filters::is_valid_float?(c)).to be(true) end end + end context 'hexs_only?' do + it 'false with general' do - chars = [nil, 1, '', "\x003333", '}', '.', '+', '-', '-1', '0.A', '33.33', '0.0', '1.0', '0.1'] + chars = [nil, 1, "", "\x003333", "}", ".", "+", "-", "-1", "0.A", "33.33", "0.0", "1.0", "0.1"] chars.each do |c| expect(BeEF::Filters::hexs_only?(c)).to be(false) end end it 'true with general' do - chars = ['0123456789ABCDEFabcdef', '0', '333', 'A33333', 'A'] + chars = ["0123456789ABCDEFabcdef", "0", "333", "A33333", "A"] chars.each do |c| expect(BeEF::Filters::hexs_only?(c)).to be(true) end end + end context 'first_char_is_num?' do + it 'false with general' do - chars = ['', 'A', 'A33333', "\x0033333"] + chars = ["", "A", "A33333", "\x0033333"] chars.each do |c| expect(BeEF::Filters::first_char_is_num?(c)).to be(false) end end it 'true with general' do - chars = ['333', '0AAAAAA', '0'] + chars = ["333", "0AAAAAA", "0"] chars.each do |c| expect(BeEF::Filters::first_char_is_num?(c)).to be(true) end end - end + end + context 'has_whitespace_char?' do + it 'false with general' do - chars = ['', 'A', 'A33333', "\x0033333", '0', '}', '.', '+', '-', '-1', '0.A'] + chars = ["", "A", "A33333", "\x0033333", "0", "}", ".", "+", "-", "-1", "0.A"] chars.each do |c| expect(BeEF::Filters::has_whitespace_char?(c)).to be(false) end end it 'true with general' do - chars = ['33 33', ' ', ' ', ' 0AAAAAAA', ' 0AAAAAAA ', "\t0AAAAAAA", "\n0AAAAAAAA"] + chars = ["33 33", " ", " ", " 0AAAAAAA", " 0AAAAAAA ", "\t0AAAAAAA", "\n0AAAAAAAA"] chars.each do |c| expect(BeEF::Filters::has_whitespace_char?(c)).to be(true) end end - end + end + context 'alphanums_only?' do + context 'false with' do + it 'general' do - chars = [nil, '', "\n", "\r", "\x01", '}', '.', '+', '-', '-1', 'ee-!@$%^&*}=0.A', '33 33', ' AAAA', 'AAA '] + chars = [nil, "", "\n", "\r", "\x01", "}", ".", "+", "-", "-1", "ee-!@$%^&*}=0.A", "33 33", " AAAA", "AAA "] chars.each do |c| expect(BeEF::Filters::alphanums_only?(c)).to be(false) end @@ -272,11 +302,13 @@ expect(BeEF::Filters::alphanums_only?(str)).to be(false) end end + end context 'true with' do + it 'general' do - chars = ['A', 'A3333', '0', '3333'] + chars = ["A", "A3333", "0", "3333"] chars.each do |c| expect(BeEF::Filters::alphanums_only?(c)).to be(true) end @@ -299,20 +331,24 @@ expect(BeEF::Filters::alphanums_only?(c)).to be(true) end end - end + end + end context 'has_valid_param_chars?' do + it 'false' do - chars = [nil, '', '+'] + chars = [nil, "", "+"] chars.each do |c| expect(BeEF::Filters::has_valid_param_chars?(c)).to be(false) end end it 'true' do - expect(BeEF::Filters::has_valid_param_chars?('A')).to be(true) + expect(BeEF::Filters::has_valid_param_chars?("A")).to be(true) end + end + end diff --git a/spec/beef/core/main/autorun_engine/autorun_engine_spec.rb b/spec/beef/core/main/autorun_engine/autorun_engine_spec.rb index 05e3721dab..02258042db 100644 --- a/spec/beef/core/main/autorun_engine/autorun_engine_spec.rb +++ b/spec/beef/core/main/autorun_engine/autorun_engine_spec.rb @@ -42,6 +42,7 @@ print_info 'Modules already loaded' end + # Load up DB and migrate if necessary ActiveRecord::Base.logger = nil OTR::ActiveRecord.configure_from_hash!(adapter: 'sqlite3', database: db_file) @@ -57,7 +58,7 @@ ActiveRecord::Migrator.new(:up, context.migrations, context.schema_migration, context.internal_metadata).migrate end end - + BeEF::Core::Migration.instance.update_db! # add AutoRunEngine rule @@ -87,7 +88,7 @@ @caps = CONFIG['common_caps'].merge(CONFIG['browser_caps'][TASK_ID]) @caps['name'] = self.class.description || ENV['name'] || 'no-name' @caps['browserstack.local'] = true - @caps['browserstack.localIdentifier'] = ENV.fetch('BROWSERSTACK_LOCAL_IDENTIFIER', nil) + @caps['browserstack.localIdentifier'] = ENV['BROWSERSTACK_LOCAL_IDENTIFIER'] @driver = Selenium::WebDriver.for(:remote, url: "http://#{CONFIG['user']}:#{CONFIG['key']}@#{CONFIG['server']}/wd/hub", diff --git a/spec/beef/core/main/configuration_spec.rb b/spec/beef/core/main/configuration_spec.rb index 42b78f6972..caafdc88bc 100644 --- a/spec/beef/core/main/configuration_spec.rb +++ b/spec/beef/core/main/configuration_spec.rb @@ -2,6 +2,7 @@ end RSpec.describe 'BeEF Configuration' do + before(:context) do @config_instance = BeEF::Core::Configuration.instance @@ -195,7 +196,7 @@ expect(@config_instance.get('beef.http.public.host')).to eq(nil) expect(@config_instance.beef_port).to eq('80') end - + it 'should return a protocol https if https public has been enabled and public host is set' do @config_instance.set('beef.http.public.https', true) @config_instance.set('beef.http.public.host', 'public') diff --git a/spec/beef/core/main/handlers/browser_details_handler_spec.rb b/spec/beef/core/main/handlers/browser_details_handler_spec.rb index 6c59e98dbd..c0c5fe9d77 100644 --- a/spec/beef/core/main/handlers/browser_details_handler_spec.rb +++ b/spec/beef/core/main/handlers/browser_details_handler_spec.rb @@ -12,6 +12,7 @@ RSpec.describe 'Browser Details Handler', run_on_browserstack: true do before(:all) do + @config = BeEF::Core::Configuration.instance db_file = @config.get('beef.database.file') print_info 'Resetting the database for BeEF.' @@ -19,7 +20,7 @@ if ENV['RESET_DB'] File.delete(db_file) if File.exist?(db_file) end - + @config.set('beef.credentials.user', 'beef') @config.set('beef.credentials.passwd', 'beef') @username = @config.get('beef.credentials.user') @@ -83,7 +84,7 @@ @caps['name'] = self.class.description || ENV['name'] || 'no-name' @caps['browserstack.local'] = true @caps['browserstack.video'] = true - @caps['browserstack.localIdentifier'] = ENV.fetch('BROWSERSTACK_LOCAL_IDENTIFIER', nil) + @caps['browserstack.localIdentifier'] = ENV['BROWSERSTACK_LOCAL_IDENTIFIER'] @driver = Selenium::WebDriver.for(:remote, url: "http://#{CONFIG['user']}:#{CONFIG['key']}@#{CONFIG['server']}/wd/hub", diff --git a/spec/beef/core/main/models/browser_details_spec.rb b/spec/beef/core/main/models/browser_details_spec.rb index 3e17f715bd..dd2661f070 100644 --- a/spec/beef/core/main/models/browser_details_spec.rb +++ b/spec/beef/core/main/models/browser_details_spec.rb @@ -1,4 +1,5 @@ RSpec.describe 'BeEF BrowserDetails' do + before(:all) do @session = (0...10).map { ('a'..'z').to_a[rand(26)] }.join end @@ -27,4 +28,5 @@ expect(BeEF::Core::Models::BrowserDetails.get(@session, key_name)).to_not eql(original_key_value) expect(BeEF::Core::Models::BrowserDetails.get(@session, key_name)).to eql(new_key_value) end + end diff --git a/spec/beef/core/main/network_stack/handlers/dynamic_reconstruction_spec.rb b/spec/beef/core/main/network_stack/handlers/dynamic_reconstruction_spec.rb index c58afab362..3cfd652feb 100644 --- a/spec/beef/core/main/network_stack/handlers/dynamic_reconstruction_spec.rb +++ b/spec/beef/core/main/network_stack/handlers/dynamic_reconstruction_spec.rb @@ -1,4 +1,5 @@ RSpec.describe 'BeEF Dynamic Reconsturction' do + before(:all) do @port = 2001 config = {} @@ -9,8 +10,8 @@ @rackApp = Rack::URLMap.new(@mounts) Thin::Logging.silent = true @server = Thin::Server.new('127.0.0.1', @port.to_s, @rackApp) - trap('INT') { @server.stop } - trap('TERM') { @server.stop } + trap("INT") { @server.stop } + trap("TERM") { @server.stop } # ***** IMPORTANT: close any and all AR/OTR connections before forking ***** disconnect_all_active_record! @@ -23,7 +24,7 @@ end after(:all) do - Process.kill('INT',@pid) + Process.kill("INT",@pid) end it 'delete' do @@ -42,6 +43,7 @@ end context 'get' do + it 'no params' do response = Curl::Easy.http_get("http://127.0.0.1:#{@port}/test") expect(response.response_code).to eql(404) @@ -78,5 +80,7 @@ expect(response.response_code).to eql(200) expect(response.body_str).to be_empty end + end + end diff --git a/spec/beef/core/main/network_stack/handlers/redirector_spec.rb b/spec/beef/core/main/network_stack/handlers/redirector_spec.rb index 12be2cb143..e172931273 100644 --- a/spec/beef/core/main/network_stack/handlers/redirector_spec.rb +++ b/spec/beef/core/main/network_stack/handlers/redirector_spec.rb @@ -1,4 +1,5 @@ RSpec.describe 'BeEF Redirector' do + before(:all) do @port = 2002 config = {} @@ -9,8 +10,9 @@ @rackApp = Rack::URLMap.new(@mounts) Thin::Logging.silent = true @server = Thin::Server.new('127.0.0.1', @port.to_s, @rackApp) - trap('INT') { @server.stop } - trap('TERM') { @server.stop } + trap("INT") { @server.stop } + trap("TERM") { @server.stop } + # ***** IMPORTANT: close any and all AR/OTR connections before forking ***** disconnect_all_active_record! @@ -23,13 +25,14 @@ end after(:all) do - Process.kill('INT',@pid) + Process.kill("INT",@pid) end it 'redirects' do response = Curl::Easy.http_get("http://127.0.0.1:#{@port}/test/") expect(response.response_code).to eql(302) - expect(response.body_str).to eql('302 found') - expect(response.header_str).to match(%r{Location: http://www.beefproject\.com}) + expect(response.body_str).to eql("302 found") + expect(response.header_str).to match(/Location: http:\/\/www.beefproject\.com/) end + end diff --git a/spec/beef/core/modules_spec.rb b/spec/beef/core/modules_spec.rb index f75b9bf87c..f9cb319375 100644 --- a/spec/beef/core/modules_spec.rb +++ b/spec/beef/core/modules_spec.rb @@ -1,4 +1,5 @@ RSpec.describe 'BeEF Modules' do + it 'loaded successfully' do expect { BeEF::Modules.load if BeEF::Core::Configuration.instance.get('beef.module').nil? @@ -25,7 +26,6 @@ it 'safe client debug log' do Dir['../../modules/**/*.js'].each do |path| next unless File.file?(path) - File.open(path) do |f| f.grep(/\bconsole\.log\W*\(/m) do |line| fail "Function 'console.log' instead of 'beef.debug' inside\n Path: #{path}\nLine: #{line}" @@ -37,7 +37,6 @@ it 'safe variable decleration' do Dir['../../modules/**/*.js'].each do |path| next unless File.file?(path) - File.open(path) do |f| f.grep(/\blet\W+[a-zA-Z0-9_\.]+\W*=/) do |line| fail "Variable declared with 'let' instead of 'var' inside\n Path: #{path}\nLine: #{line}" @@ -45,4 +44,5 @@ end end end + end diff --git a/spec/beef/extensions/adminui_spec.rb b/spec/beef/extensions/adminui_spec.rb index 0ccb22f7fb..64891c0a88 100644 --- a/spec/beef/extensions/adminui_spec.rb +++ b/spec/beef/extensions/adminui_spec.rb @@ -14,7 +14,7 @@ end after(:all) do - @config.set('beef.restrictions.permitted_ui_subnet',['0.0.0.0/0', '::/0']) + @config.set('beef.restrictions.permitted_ui_subnet',["0.0.0.0/0", "::/0"]) end it 'loads configuration' do @@ -23,30 +23,31 @@ it 'confirms that any ip address is permitted to view the admin ui' do ui = BeEF::Extension::AdminUI::HttpController.new - expect(@config.set('beef.restrictions.permitted_ui_subnet',['0.0.0.0/0', '::/0'])).to eq true - expect(ui.authenticate_request('8.8.8.8')).to eq true + expect(@config.set('beef.restrictions.permitted_ui_subnet',["0.0.0.0/0", "::/0"])).to eq true + expect(ui.authenticate_request("8.8.8.8")).to eq true end it 'confirms that an ip address is permitted to view the admin ui' do ui = BeEF::Extension::AdminUI::HttpController.new - expect(@config.set('beef.restrictions.permitted_ui_subnet',['192.168.10.1'])).to eq true - expect(ui.authenticate_request('192.168.10.1')).to eq true + expect(@config.set('beef.restrictions.permitted_ui_subnet',["192.168.10.1"])).to eq true + expect(ui.authenticate_request("192.168.10.1")).to eq true end it 'confirms that an ip address is not permitted to view the admin ui' do ui = BeEF::Extension::AdminUI::HttpController.new - expect(@config.set('beef.restrictions.permitted_ui_subnet',['10.10.10.1'])).to eq true - expect(ui.authenticate_request('8.8.8.8')).to eq false + expect(@config.set('beef.restrictions.permitted_ui_subnet',["10.10.10.1"])).to eq true + expect(ui.authenticate_request("8.8.8.8")).to eq false end it 'confirms that X-Forwarded-For cant be spoofed when reverse proxy is disabled' do ui = BeEF::Extension::AdminUI::HttpController.new - expect(@config.set('beef.restrictions.permitted_ui_subnet',['192.168.0.10'])).to eq true + expect(@config.set('beef.restrictions.permitted_ui_subnet',["192.168.0.10"])).to eq true expect(@config.set('beef.http.allow_reverse_proxy',false)).to eq true - env = { 'REQUEST_METHOD' => 'GET', 'PATH_INFO' => '/ui/authentication' } - request = Rack::Request.new(env) - request.add_header('HTTP_X_FORWARDED_FOR','192.168.0.10') - request.add_header('REMOTE_ADDR','192.168.0.20') - expect(ui.get_ip(request)).to eq '192.168.0.20' + env = { "REQUEST_METHOD" => "GET", "PATH_INFO" => "/ui/authentication" } + request = Rack::Request.new(env) + request.add_header("HTTP_X_FORWARDED_FOR","192.168.0.10") + request.add_header("REMOTE_ADDR","192.168.0.20") + expect(ui.get_ip(request)).to eq "192.168.0.20" end -end + +end \ No newline at end of file diff --git a/spec/beef/extensions/dns_spec.rb b/spec/beef/extensions/dns_spec.rb index fbc60b1adc..a1aed66e12 100644 --- a/spec/beef/extensions/dns_spec.rb +++ b/spec/beef/extensions/dns_spec.rb @@ -7,6 +7,7 @@ require 'extensions/dns/extension.rb' RSpec.describe 'BeEF Extension DNS' do + IN = Resolv::DNS::Resource::IN before(:all) do @@ -37,15 +38,16 @@ end context 'add good rule' do + it '1.2.3.4' do id = nil response = '1.2.3.4' expect { id = @dns.add_rule( - pattern: 'foo.bar', - resource: IN::A, - response: [response]) do |transaction| - transaction.respond!(response) + :pattern => 'foo.bar', + :resource => IN::A, + :response => [response] ) do |transaction| + transaction.respond!(response) end }.to_not raise_error expect(id).to_not be_nil @@ -56,10 +58,10 @@ response = '9.9.9.9' expect { id = @dns.add_rule( - pattern: /i\.(love|hate)\.beef\.com?/, - resource: IN::A, - response: [response]) do |transaction| - transaction.respond!(response) + :pattern => %r{i\.(love|hate)\.beef\.com?}, + :resource => IN::A, + :response => [response] ) do |transaction| + transaction.respond!(response) end }.to_not raise_error expect(id).to_not be_nil @@ -76,17 +78,19 @@ id = nil expect { id = @dns.add_rule( - pattern: /i\.(love|hate)\.beef\.com?/, - resource: IN::A, - response: [response]) do |transaction| - transaction.respond!(response) + :pattern => %r{i\.(love|hate)\.beef\.com?}, + :resource => IN::A, + :response => [response] ) do |transaction| + transaction.respond!(response) end }.to_not raise_error expect(id).to_not be_nil end + end context 'add bad rule' do + it '4.2.4.2' do id = nil same_id = nil @@ -95,34 +99,36 @@ expect { id = @dns.add_rule( - pattern: pattern, - resource: IN::A, - response: [response]) do |transaction| - transaction.respond!(response) + :pattern => pattern, + :resource => IN::A, + :response => [response] ) do |transaction| + transaction.respond!(response) end }.to_not raise_error expect { same_id = @dns.add_rule( - pattern: pattern, - resource: IN::A, - response: [response]) do |transaction| - transaction.respond!(response) + :pattern => pattern, + :resource => IN::A, + :response => [response] ) do |transaction| + transaction.respond!(response) end }.to_not raise_error expect { same_id = @dns.add_rule( - pattern: pattern, - resource: IN::A, - response: [response]) do |transaction| - transaction.respond!(response) + :pattern => pattern, + :resource => IN::A, + :response => [response] ) do |transaction| + transaction.respond!(response) end }.to_not raise_error expect(id).to eql(same_id) end + end + end # it 'id format' do @@ -143,6 +149,7 @@ # expect(id).to match(/^\h{8}$/) # end + it 'get good rule' do pattern = 'be.ef' response = '1.1.1.1' @@ -150,10 +157,10 @@ expect { id = @dns.add_rule( - pattern: pattern, - resource: IN::A, - response: [response]) do |transaction| - transaction.respond!(response) + :pattern => pattern, + :resource => IN::A, + :response => [response] ) do |transaction| + transaction.respond!(response) end }.to_not raise_error @@ -185,10 +192,10 @@ expect { id = @dns.add_rule( - pattern: pattern, - resource: IN::A, - response: [response]) do |transaction| - transaction.respond!(response) + :pattern => pattern, + :resource => IN::A, + :response => [response] ) do |transaction| + transaction.respond!(response) end }.to_not raise_error @@ -213,9 +220,9 @@ rules.each do |r| @dns.add_rule( - pattern: r[:pattern], - resource: IN::A, - response: r[:response] + :pattern => r[:pattern], + :resource => IN::A, + :response => r[:response] ) end @@ -236,10 +243,15 @@ end it 'failure types' do + end + end -# Tests each supported type of query failure + + + + # Tests each supported type of query failure # def test_13_failure_types # begin # id = @@dns.add_rule( diff --git a/spec/beef/extensions/network_spec.rb b/spec/beef/extensions/network_spec.rb index 32e538a8dd..be759ab9df 100644 --- a/spec/beef/extensions/network_spec.rb +++ b/spec/beef/extensions/network_spec.rb @@ -7,24 +7,27 @@ require 'extensions/network/models/network_host' RSpec.describe 'BeEF Extension Network' do + it 'add good local host' do expect { - BeEF::Core::Models::NetworkHost.create(hooked_browser_id: '1234', ip: '127.0.0.1') + BeEF::Core::Models::NetworkHost.create(:hooked_browser_id => '1234', :ip => '127.0.0.1') }.to_not raise_error expect(BeEF::Core::Models::NetworkHost.where(hooked_browser_id: '1234', ip: '127.0.0.1')).to_not be_empty end it 'add good not local host' do expect { - BeEF::Core::Models::NetworkHost.create(hooked_browser_id: '12', ip: '192.168.1.2') + BeEF::Core::Models::NetworkHost.create(:hooked_browser_id => '12', :ip => '192.168.1.2') }.to_not raise_error expect(BeEF::Core::Models::NetworkHost.where(hooked_browser_id: '12', ip: '192.168.1.2')).to_not be_empty end it 'add good service' do expect { - BeEF::Core::Models::NetworkService.create(hooked_browser_id: '1234', proto: 'http', ip: '127.0.0.1', port: 80, ntype: 'Apache') + BeEF::Core::Models::NetworkService.create(:hooked_browser_id => '1234', :proto => 'http', :ip => '127.0.0.1', :port => 80, :ntype => 'Apache') }.to_not raise_error expect(BeEF::Core::Models::NetworkService.where(hooked_browser_id: '1234', ip: '127.0.0.1')).to_not be_empty + end + end diff --git a/spec/beef/extensions/proxy_spec.rb b/spec/beef/extensions/proxy_spec.rb index 5460d3e5af..ff25ac1411 100644 --- a/spec/beef/extensions/proxy_spec.rb +++ b/spec/beef/extensions/proxy_spec.rb @@ -6,6 +6,7 @@ require 'extensions/proxy/extension' RSpec.describe 'BeEF Extension Proxy' do + before(:all) do @config = BeEF::Core::Configuration.instance @config.load_extensions_config @@ -19,4 +20,5 @@ expect(config).to have_key('key') expect(config).to have_key('cert') end + end diff --git a/spec/beef/extensions/qrcode_spec.rb b/spec/beef/extensions/qrcode_spec.rb index b774044362..43e990dea3 100644 --- a/spec/beef/extensions/qrcode_spec.rb +++ b/spec/beef/extensions/qrcode_spec.rb @@ -6,6 +6,7 @@ require 'extensions/qrcode/extension' RSpec.describe 'BeEF Extension QRCode' do + before(:all) do @config = BeEF::Core::Configuration.instance @config.load_extensions_config @@ -18,4 +19,5 @@ expect(config).to have_key('qrsize') expect(config).to have_key('qrborder') end + end diff --git a/spec/beef/extensions/requester_spec.rb b/spec/beef/extensions/requester_spec.rb index 38b71dcc59..8aabfbd236 100644 --- a/spec/beef/extensions/requester_spec.rb +++ b/spec/beef/extensions/requester_spec.rb @@ -28,7 +28,7 @@ @config = BeEF::Core::Configuration.instance @config.set('beef.credentials.user', 'beef') @config.set('beef.credentials.passwd', 'beef') - + # Generate API token BeEF::Core::Crypto::api_token @@ -56,7 +56,7 @@ response = api.auth() @token = response[:token] - while (response = RestClient.get("#{RESTAPI_HOOKS}", { params: { token: @token } })) && + while (response = RestClient.get("#{RESTAPI_HOOKS}", {params: {token: @token}})) && (hb_details = JSON.parse(response.body)) && hb_details['hooked-browsers']['online'].empty? sleep 2 diff --git a/spec/beef/extensions/social_engineering_spec.rb b/spec/beef/extensions/social_engineering_spec.rb index 90f6a07982..7543b2f264 100644 --- a/spec/beef/extensions/social_engineering_spec.rb +++ b/spec/beef/extensions/social_engineering_spec.rb @@ -22,13 +22,13 @@ xit 'clone web page', if: !`which wget`.empty? do expect { BeEF::Core::Server.instance.prepare - BeEF::Extension::SocialEngineering::WebCloner.instance.clone_page('https://www.google.com', '/', nil, nil) + BeEF::Extension::SocialEngineering::WebCloner.instance.clone_page("https://www.google.com", "/", nil, nil) }.to_not raise_error end it 'persistence web cloner', if: !`which wget`.empty? do expect { - BeEF::Core::Models::WebCloner.create(uri: 'example.com', mount: '/') + BeEF::Core::Models::WebCloner.create(uri: "example.com", mount: "/") }.to_not raise_error end end diff --git a/spec/beef/extensions/websocket_hooked_browser_spec.rb b/spec/beef/extensions/websocket_hooked_browser_spec.rb index 776f6fbb8f..34156645ed 100644 --- a/spec/beef/extensions/websocket_hooked_browser_spec.rb +++ b/spec/beef/extensions/websocket_hooked_browser_spec.rb @@ -22,7 +22,7 @@ if ENV['RESET_DB'] File.delete(db_file) if File.exist?(db_file) end - + @config.set('beef.credentials.user', 'beef') @config.set('beef.credentials.passwd', 'beef') @config.set('beef.http.websocket.secure', false) @@ -59,7 +59,7 @@ ActiveRecord::Migrator.new(:up, context.migrations, context.schema_migration, context.internal_metadata).migrate end end - + BeEF::Core::Migration.instance.update_db! # Spawn HTTP Server print_info 'Starting HTTP Hook Server' @@ -67,6 +67,7 @@ # Generate a token for the server to respond with @token = BeEF::Core::Crypto.api_token + # ***** IMPORTANT: close any and all AR/OTR connections before forking ***** disconnect_all_active_record! @@ -81,7 +82,7 @@ @caps = CONFIG['common_caps'].merge(CONFIG['browser_caps'][TASK_ID]) @caps['name'] = self.class.description || ENV['name'] || 'no-name' @caps['browserstack.local'] = true - @caps['browserstack.localIdentifier'] = ENV.fetch('BROWSERSTACK_LOCAL_IDENTIFIER', nil) + @caps['browserstack.localIdentifier'] = ENV['BROWSERSTACK_LOCAL_IDENTIFIER'] @driver = Selenium::WebDriver.for(:remote, url: "http://#{CONFIG['user']}:#{CONFIG['key']}@#{CONFIG['server']}/wd/hub", diff --git a/spec/beef/extensions/websocket_spec.rb b/spec/beef/extensions/websocket_spec.rb index 6a41db81e5..8f3d71b1ee 100644 --- a/spec/beef/extensions/websocket_spec.rb +++ b/spec/beef/extensions/websocket_spec.rb @@ -23,7 +23,7 @@ end it 'confirms that a websocket server has been started' do - expect(@ws).to be_a_kind_of(BeEF::Core::Websocket::Websocket) + expect(@ws).to be_a_kind_of(BeEF::Core::Websocket::Websocket) end it 'confirms that a secure websocket server has been started' do diff --git a/spec/beef/modules/debug/test_beef_debugs_spec.rb b/spec/beef/modules/debug/test_beef_debugs_spec.rb index 7b1def5098..075d13490a 100644 --- a/spec/beef/modules/debug/test_beef_debugs_spec.rb +++ b/spec/beef/modules/debug/test_beef_debugs_spec.rb @@ -41,6 +41,7 @@ print_info 'Modules already loaded' end + # Load up DB and migrate if necessary ActiveRecord::Base.logger = nil OTR::ActiveRecord.configure_from_hash!(adapter: 'sqlite3', database: db_file) @@ -81,7 +82,7 @@ @caps = CONFIG['common_caps'].merge(CONFIG['browser_caps'][TASK_ID]) @caps['name'] = self.class.description || ENV['name'] || 'no-name' @caps['browserstack.local'] = true - @caps['browserstack.localIdentifier'] = ENV.fetch('BROWSERSTACK_LOCAL_IDENTIFIER', nil) + @caps['browserstack.localIdentifier'] = ENV['BROWSERSTACK_LOCAL_IDENTIFIER'] @driver = Selenium::WebDriver.for(:remote, url: "http://#{CONFIG['user']}:#{CONFIG['key']}@#{CONFIG['server']}/wd/hub", options: @caps) diff --git a/spec/beef/security_checks_spec.rb b/spec/beef/security_checks_spec.rb index fdd31b210b..c058323119 100644 --- a/spec/beef/security_checks_spec.rb +++ b/spec/beef/security_checks_spec.rb @@ -8,10 +8,10 @@ f.grep(/\Weval\W/im) do |line| # check if comment starting with the '#' character - clean_line = line.downcase.gsub(/[ ]/, '') + clean_line = line.downcase.gsub(/[ ]/, "") if clean_line[0] != '#' # check first non-whitespace position raise "Illegal use of 'eval' found in\n Path: #{path}\nLine: #{line}" - end + end end end end diff --git a/spec/features/all_modules_spec.rb b/spec/features/all_modules_spec.rb index 171c131af6..8112d46c9b 100644 --- a/spec/features/all_modules_spec.rb +++ b/spec/features/all_modules_spec.rb @@ -9,55 +9,55 @@ require 'spec/support/ui_support.rb' RSpec.describe 'Load All Modules Integration', run_on_long_tests: true do - before(:each) do - @pid, @beef_session, @hooked_browser = start_beef_and_hook_browser - end - - after(:each) do - stop_beef_and_unhook_browser(@pid, @beef_session, @hooked_browser) - end - - it 'Load all modules' do - - Dir.glob('modules/**/config.yaml').each do |file| - module_yaml_data = YAML.load_file(file) - - module_yaml_data['beef']['module'].each do |module_key, module_value| - next if rand(50) != 0 # for testing purposes only - - next if not module_value['enable'] # skip disabled modules - - module_name = module_value['name'] - module_category = module_value['category'] # can be an array or a string - module_description_sub = module_value['description'][0, 15] # descriptions including html cause errors - - expect(module_category).not_to be_nil - expect(module_name).not_to be_nil - - expect(@beef_session).to have_content(module_category, wait: PAGE_LOAD_TIMEOUT) if module_category.is_a?(String) - - expect(module_name).to be_a(String) - expect(module_description_sub).not_to be_nil - expect(module_description_sub).to be_a(String) + before(:each) do + @pid, @beef_session, @hooked_browser = start_beef_and_hook_browser + end - # print the category and module name - if module_category.is_a?(Array) - category_tree_text = module_category.join(' > ') - else - category_tree_text = module_category + after(:each) do + stop_beef_and_unhook_browser(@pid, @beef_session, @hooked_browser) + end + + it "Load all modules" do + + Dir.glob("modules/**/config.yaml").each do |file| + module_yaml_data = YAML.load_file(file) + + module_yaml_data['beef']['module'].each do |module_key, module_value| + next if rand(50) != 0 # for testing purposes only + + next if not module_value['enable'] # skip disabled modules + + module_name = module_value['name'] + module_category = module_value['category'] # can be an array or a string + module_description_sub = module_value['description'][0, 15] # descriptions including html cause errors + + expect(module_category).not_to be_nil + expect(module_name).not_to be_nil + + expect(@beef_session).to have_content(module_category, wait: PAGE_LOAD_TIMEOUT) if module_category.is_a?(String) + + expect(module_name).to be_a(String) + expect(module_description_sub).not_to be_nil + expect(module_description_sub).to be_a(String) + + # print the category and module name + if module_category.is_a?(Array) + category_tree_text = module_category.join(' > ') + else + category_tree_text = module_category + end + print_info "Category: #{category_tree_text}, Module: #{module_name}" + + # click on the module then expect the description and execute button to be visible + click_on_module(@beef_session, module_category, module_name) + + # expect the module description and the execute button to be visible + expect(@beef_session).to have_content(module_description_sub, wait: PAGE_LOAD_TIMEOUT) + expect(@beef_session).to have_content('Execute', wait: PAGE_LOAD_TIMEOUT) + + # tidy up and collapse the category tree + collapse_category_tree(@beef_session, module_category) + end end - print_info "Category: #{category_tree_text}, Module: #{module_name}" - - # click on the module then expect the description and execute button to be visible - click_on_module(@beef_session, module_category, module_name) - - # expect the module description and the execute button to be visible - expect(@beef_session).to have_content(module_description_sub, wait: PAGE_LOAD_TIMEOUT) - expect(@beef_session).to have_content('Execute', wait: PAGE_LOAD_TIMEOUT) - - # tidy up and collapse the category tree - collapse_category_tree(@beef_session, module_category) - end end - end -end +end \ No newline at end of file diff --git a/spec/features/debug_modules_spec.rb b/spec/features/debug_modules_spec.rb index 01ac9e7f2b..e3eae3e0e7 100644 --- a/spec/features/debug_modules_spec.rb +++ b/spec/features/debug_modules_spec.rb @@ -9,66 +9,66 @@ require 'spec/support/ui_support.rb' RSpec.describe 'Debug Modules Integration', run_on_long_tests: true do - before(:each) do - @pid, @beef_session, @hooked_browser = start_beef_and_hook_browser - end - - after(:each) do - stop_beef_and_unhook_browser(@pid, @beef_session, @hooked_browser) - end - - it 'Test beef.debug module' do - click_on_module(@beef_session, 'Debug', 'Test beef.debug') - expect(@beef_session).to have_content('Execute', wait: PAGE_LOAD_TIMEOUT) - expect(@beef_session).to have_content('244', wait: PAGE_LOAD_TIMEOUT) # Module ID - expect(@beef_session).to have_content('Debug Message:', wait: PAGE_LOAD_TIMEOUT) - end - - it 'Load all debug modules' do - Dir.glob('modules/debug/**/config.yaml').each do |file| - module_yaml_data = YAML.load_file(file) - - module_yaml_data['beef']['module'].each do |module_key, module_value| - module_category = module_value['category'] - module_name = module_value['name'] - # some descriptions are too long and include html tags - module_description_sub = module_value['description'][0, 20] - - expect(@beef_session).to have_content(module_category, wait: PAGE_LOAD_TIMEOUT) - expect(module_category).not_to be_nil - expect(module_category).to be_a(String) - expect(module_name).not_to be_nil - expect(module_name).to be_a(String) - expect(module_description_sub).not_to be_nil - expect(module_description_sub).to be_a(String) - - click_on_module(@beef_session, 'Debug', module_name) + before(:each) do + @pid, @beef_session, @hooked_browser = start_beef_and_hook_browser + end - expect(@beef_session).to have_content(module_description_sub, wait: PAGE_LOAD_TIMEOUT) + after(:each) do + stop_beef_and_unhook_browser(@pid, @beef_session, @hooked_browser) + end + + it 'Test beef.debug module' do + click_on_module(@beef_session, 'Debug', 'Test beef.debug') expect(@beef_session).to have_content('Execute', wait: PAGE_LOAD_TIMEOUT) - - # execute the module - @beef_session.click_on('Execute') - - # expect the module to make command output visible - expect(@beef_session).to have_content('command 1', wait: PAGE_LOAD_TIMEOUT) - - # click on the command section to display the output - @beef_session.all('div.x-grid3-cell-inner').each do |div| - if div.text == 'command 1' - div.click - break - end - end - - if module_name == 'Return Image' # this module returns an image not a string - image_selector = "img[src^='data:image/png;base64,iVBORw0KGgo']" - expect(@beef_session).to have_css(image_selector, wait: PAGE_LOAD_TIMEOUT) - else - expect(@beef_session).to have_content('data: ', wait: PAGE_LOAD_TIMEOUT) + expect(@beef_session).to have_content('244', wait: PAGE_LOAD_TIMEOUT) # Module ID + expect(@beef_session).to have_content('Debug Message:', wait: PAGE_LOAD_TIMEOUT) + end + + it "Load all debug modules" do + Dir.glob("modules/debug/**/config.yaml").each do |file| + module_yaml_data = YAML.load_file(file) + + module_yaml_data['beef']['module'].each do |module_key, module_value| + module_category = module_value['category'] + module_name = module_value['name'] + # some descriptions are too long and include html tags + module_description_sub = module_value['description'][0, 20] + + expect(@beef_session).to have_content(module_category, wait: PAGE_LOAD_TIMEOUT) + expect(module_category).not_to be_nil + expect(module_category).to be_a(String) + expect(module_name).not_to be_nil + expect(module_name).to be_a(String) + expect(module_description_sub).not_to be_nil + expect(module_description_sub).to be_a(String) + + click_on_module(@beef_session, 'Debug', module_name) + + expect(@beef_session).to have_content(module_description_sub, wait: PAGE_LOAD_TIMEOUT) + expect(@beef_session).to have_content('Execute', wait: PAGE_LOAD_TIMEOUT) + + # execute the module + @beef_session.click_on('Execute') + + # expect the module to make command output visible + expect(@beef_session).to have_content('command 1', wait: PAGE_LOAD_TIMEOUT) + + # click on the command section to display the output + @beef_session.all('div.x-grid3-cell-inner').each do |div| + if div.text == 'command 1' + div.click + break + end + end + + if module_name == 'Return Image' # this module returns an image not a string + image_selector = "img[src^='data:image/png;base64,iVBORw0KGgo']" + expect(@beef_session).to have_css(image_selector, wait: PAGE_LOAD_TIMEOUT) + else + expect(@beef_session).to have_content('data: ', wait: PAGE_LOAD_TIMEOUT) + end + end end - end end - end - -end + +end \ No newline at end of file diff --git a/spec/requests/beef_test_spec.rb b/spec/requests/beef_test_spec.rb index 5ef765fd74..9ab0bdaf32 100644 --- a/spec/requests/beef_test_spec.rb +++ b/spec/requests/beef_test_spec.rb @@ -8,103 +8,104 @@ require_relative '../support/beef_test' RSpec.describe BeefTest, run_on_long_tests: true do - before(:each) do - @pid = start_beef_server_and_wait - end - - after(:each) do - stop_beef_server(@pid) - end - - describe '.login' do - it 'logs in successfully' do - expect(port_available?) # Check if the tcp port is open - session = BeefTest.login() - expect(session).not_to be_nil - expect(session.has_content?('Hooked Browsers', wait: 10)) - end - end - describe '.logout' do before(:each) do - expect(port_available?) # # Check if the tcp port is open - @session = BeefTest.login() # Ensure login before each '.logout' test - expect(@session.has_content?('Hooked Browsers', wait: 10)) + @pid = start_beef_server_and_wait end - it 'logs out successfully' do - expect(port_available?) # # Check if the tcp port is open - expect(@session.has_content?('Hooked Browsers', wait: 10)) - - # Log out of the session - @sessoin = BeefTest.logout(@session) - expect(@session.has_no_content?('Hooked Browsers', wait: 10)) - expect(@session.has_content?('Authentication', wait: 10)) - @session.reset_session! - end - end - - describe '.save_screenshot' do - it 'saves a screenshot' do - session = Capybara::Session.new(:selenium_headless) if session.nil? - - # Ensure the new directory does not exist - outputDir = '/tmp' - directory = "#{outputDir}/#{SecureRandom.hex}/" - expect(File.directory?(directory)).to be false - - # Save the screenshot - BeefTest.save_screenshot(session, directory) - - # Ensure the screenshot was saved - expect(File.directory?(directory)).to be true - screenshot_files = Dir.glob("#{directory}/*.png") - expect(screenshot_files.empty?).to be false - - # Ensure the screenshot file is not empty and clean up - screenshot_files.each do |file| - expect(File.size(file)).to be > 0 - File.delete(file) - end - expect(Dir.glob("#{directory}/*.png").empty?).to be true - - # Remove the directory - Dir.delete(directory) - expect(File.directory?(directory)).to be false + after(:each) do + stop_beef_server(@pid) end - end - let(:session) { Capybara::Session.new(:selenium_headless) } - let(:victim) { Capybara::Session.new(:selenium_headless) } + describe '.login' do + it 'logs in successfully' do + expect(port_available?) # Check if the tcp port is open + session = BeefTest.login() + expect(session).not_to be_nil + expect(session.has_content?('Hooked Browsers', wait: 10)) + end + end - describe '.new_attacker' do - it 'creates a new attacker session' do - # # Test setup - expect(session).not_to be_nil + describe '.logout' do + before(:each) do + expect(port_available?) # # Check if the tcp port is open + @session = BeefTest.login() # Ensure login before each '.logout' test + expect(@session.has_content?('Hooked Browsers', wait: 10)) + end + + it 'logs out successfully' do + expect(port_available?) # # Check if the tcp port is open + expect(@session.has_content?('Hooked Browsers', wait: 10)) + + # Log out of the session + @sessoin = BeefTest.logout(@session) + expect(@session.has_no_content?('Hooked Browsers', wait: 10)) + expect(@session.has_content?('Authentication', wait: 10)) + @session.reset_session! + end + end - result = BeefTest.new_attacker(session) + describe '.save_screenshot' do + it 'saves a screenshot' do + session = Capybara::Session.new(:selenium_headless) if session.nil? + + # Ensure the new directory does not exist + outputDir = '/tmp' + directory = "#{outputDir}/#{SecureRandom.hex}/" + expect(File.directory?(directory)).to be false + + # Save the screenshot + BeefTest.save_screenshot(session, directory) + + # Ensure the screenshot was saved + expect(File.directory?(directory)).to be true + screenshot_files = Dir.glob("#{directory}/*.png") + expect(screenshot_files.empty?).to be false + + # Ensure the screenshot file is not empty and clean up + screenshot_files.each do |file| + expect(File.size(file)).to be > 0 + File.delete(file) + end + expect(Dir.glob("#{directory}/*.png").empty?).to be true + + # Remove the directory + Dir.delete(directory) + expect(File.directory?(directory)).to be false + end + end - # Test assertions - expect(result).to eq(session) - expect(session.has_no_content?('Authentication', wait: 10)) - expect(session.has_content?('Hooked Browsers', wait: 10)) - session.reset_session! + let(:session) { Capybara::Session.new(:selenium_headless) } + let(:victim) { Capybara::Session.new(:selenium_headless) } + + describe '.new_attacker' do + it 'creates a new attacker session' do + # # Test setup + expect(session).not_to be_nil + + result = BeefTest.new_attacker(session) + + # Test assertions + expect(result).to eq(session) + expect(session.has_no_content?('Authentication', wait: 10)) + expect(session.has_content?('Hooked Browsers', wait: 10)) + session.reset_session! + end end - end - describe '.new_victim' do - it 'creates a new victim session' do - # Test setup - allow(victim).to receive(:visit) - expect(victim).not_to be_nil + describe '.new_victim' do + it 'creates a new victim session' do + # Test setup + allow(victim).to receive(:visit) + expect(victim).not_to be_nil - # Test execution - result = BeefTest.new_victim(victim) + # Test execution + result = BeefTest.new_victim(victim) - # Test assertions - expect(victim).to have_received(:visit).with(VICTIM_URL) - expect(result).to eq(victim) - victim.reset_session! + # Test assertions + expect(victim).to have_received(:visit).with(VICTIM_URL) + expect(result).to eq(victim) + victim.reset_session! + end end - end end diff --git a/spec/requests/login_spec.rb b/spec/requests/login_spec.rb index 88225f83cd..22be46cd4a 100644 --- a/spec/requests/login_spec.rb +++ b/spec/requests/login_spec.rb @@ -80,7 +80,7 @@ expect(attacker).to have_content('Logout', wait: 10) expect(attacker).to have_content(VICTIM_DOMAIN, wait: 10) - attacker.click_on('127.0.0.1', match: :first) + attacker.click_on("127.0.0.1", match: :first) expect(attacker).to have_content('Details') expect(attacker).to have_content('Commands') @@ -89,4 +89,4 @@ attacker.driver.browser.close victim.driver.browser.close end -end +end \ No newline at end of file diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 3013d5c283..aa23cbfbb7 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -79,23 +79,18 @@ module Core module Console class << self attr_accessor :logger - def level=(val) (self.logger ||= Logger.new($stdout)).level = val end - def level (self.logger ||= Logger.new($stdout)).level end - # Proxy common logger methods if called directly (info, warn, error, etc.) def method_missing(m, *args, &blk) lg = (self.logger ||= Logger.new($stdout)) return lg.public_send(m, *args, &blk) if lg.respond_to?(m) - super end - def respond_to_missing?(m, include_priv = false) (self.logger ||= Logger.new($stdout)).respond_to?(m, include_priv) || super end @@ -110,23 +105,18 @@ def respond_to_missing?(m, include_priv = false) module ::Console class << self attr_accessor :logger - def level=(val) (self.logger ||= Logger.new($stdout)).level = val end - def level (self.logger ||= Logger.new($stdout)).level end - # Proxy to logger for typical logging calls def method_missing(m, *args, &blk) lg = (self.logger ||= Logger.new($stdout)) return lg.public_send(m, *args, &blk) if lg.respond_to?(m) - super end - def respond_to_missing?(m, include_priv = false) (self.logger ||= Logger.new($stdout)).respond_to?(m, include_priv) || super end @@ -173,18 +163,18 @@ def server_teardown(webdriver, server_pid, server_pids) end end - ######################################## +######################################## - def reset_beef_db - begin +def reset_beef_db + begin db_file = BeEF::Core::Configuration.instance.get('beef.database.file') File.delete(db_file) if File.exist?(db_file) - rescue => e - print_error("Could not remove '#{db_file}' database file: #{e.message}") - end + rescue => e + print_error("Could not remove '#{db_file}' database file: #{e.message}") end +end - require 'socket' +require 'socket' def port_available? socket = TCPSocket.new(@host, @port) @@ -200,18 +190,18 @@ def configure_beef # Reset or re-initialise the configuration to a default state @config = BeEF::Core::Configuration.instance - @config.set('beef.credentials.user', 'beef') - @config.set('beef.credentials.passwd', 'beef') + @config.set('beef.credentials.user', "beef") + @config.set('beef.credentials.passwd', "beef") @config.set('beef.http.https.enable', false) end # Load the server def load_beef_extensions_and_modules - # Load BeEF extensions - BeEF::Extensions.load + # Load BeEF extensions + BeEF::Extensions.load - # Load BeEF modules only if they are not already loaded - BeEF::Modules.load if @config.get('beef.module').nil? + # Load BeEF modules only if they are not already loaded + BeEF::Modules.load if @config.get('beef.module').nil? end # --- HARD fork-safety: disconnect every pool/adapter we can find --- @@ -228,7 +218,7 @@ def disconnect_all_active_record! handler.connection_pools.each_value { |pool| pool.disconnect! } end else - print_info 'ActiveRecord::Base not defined' + print_info "ActiveRecord::Base not defined" end end @@ -243,7 +233,7 @@ def start_beef_server exit end load_beef_extensions_and_modules - + # Grab DB file and regenerate if requested db_file = @config.get('beef.database.file') @@ -287,7 +277,7 @@ def start_beef_server http_hook_server.start end - pid + return pid end def beef_server_running?(uri_str) @@ -295,10 +285,10 @@ def beef_server_running?(uri_str) uri = URI.parse(uri_str) response = Net::HTTP.get_response(uri) response.is_a?(Net::HTTPSuccess) - rescue Errno::ECONNREFUSED - false # Connection refused means the server is not running - rescue StandardError => e - false # Any other error means the server is not running + rescue Errno::ECONNREFUSED + return false # Connection refused means the server is not running + rescue StandardError => e + return false # Any other error means the server is not running end end @@ -311,14 +301,14 @@ def wait_for_beef_server_to_start(uri_str, timeout: 5) end def start_beef_server_and_wait - puts 'Starting BeEF server' + puts "Starting BeEF server" pid = start_beef_server puts "BeEF server started with PID: #{pid}" if wait_for_beef_server_to_start('http://localhost:3000', timeout: SERVER_START_TIMEOUT) # print_info "Server started successfully." else - print_error 'Server failed to start within timeout.' + print_error "Server failed to start within timeout." end pid @@ -327,8 +317,9 @@ def start_beef_server_and_wait def stop_beef_server(pid) exit if pid.nil? # Shutting down server - Process.kill('KILL', pid) unless pid.nil? - Process.wait(pid) unless pid.nil? # Ensure the process has exited and the port is released - pid = nil + Process.kill("KILL", pid) unless pid.nil? + Process.wait(pid) unless pid.nil? # Ensure the process has exited and the port is released + pid = nil end -end + +end \ No newline at end of file diff --git a/spec/support/beef_test.rb b/spec/support/beef_test.rb index b8f38eeed1..f54033704d 100644 --- a/spec/support/beef_test.rb +++ b/spec/support/beef_test.rb @@ -13,14 +13,14 @@ class BeefTest def self.save_screenshot(session, dir = nil) outputDir = dir || BEEF_TEST_DIR Dir.mkdir(outputDir) unless File.directory?(outputDir) - filename = "#{outputDir}#{Time.now.strftime('%Y-%m-%d--%H-%M-%S-%N')}.png" + filename = outputDir + Time.now.strftime('%Y-%m-%d--%H-%M-%S-%N') + '.png' session.driver.browser.save_screenshot(filename) end def self.login(session = nil) session = Capybara::Session.new(:selenium_headless) if session.nil? session.visit(ATTACK_URL) - + session.has_content?('Authentication', wait: 10) # enter the credentials diff --git a/spec/support/constants.rb b/spec/support/constants.rb index b84484c139..d4bfa54640 100644 --- a/spec/support/constants.rb +++ b/spec/support/constants.rb @@ -8,26 +8,26 @@ # General constants ATTACK_DOMAIN = 'localhost'.freeze VICTIM_DOMAIN = '127.0.0.1'.freeze -ATTACK_URL = "http://#{ATTACK_DOMAIN}:3000/ui/panel" -VICTIM_URL = "http://#{VICTIM_DOMAIN}:3000/demos/basic.html" +ATTACK_URL = 'http://' + ATTACK_DOMAIN + ':3000/ui/panel' +VICTIM_URL = 'http://' + VICTIM_DOMAIN + ':3000/demos/basic.html' # Credentials BEEF_USER = ENV['TEST_BEEF_USER'] || 'beef' BEEF_PASSWD = ENV['TEST_BEEF_PASS'] || 'beef' # RESTful API root endpoints -RESTAPI_HOOKS = "http://#{ATTACK_DOMAIN}:3000/api/hooks" -RESTAPI_LOGS = "http://#{ATTACK_DOMAIN}:3000/api/logs" -RESTAPI_MODULES = "http://#{ATTACK_DOMAIN}:3000/api/modules" -RESTAPI_NETWORK = "http://#{ATTACK_DOMAIN}:3000/api/network" -RESTAPI_PROXY = "http://#{ATTACK_DOMAIN}:3000/api/proxy" -RESTAPI_DNS = "http://#{ATTACK_DOMAIN}:3000/api/dns" -RESTAPI_SENG = "http://#{ATTACK_DOMAIN}:3000/api/seng" -RESTAPI_ADMIN = "http://#{ATTACK_DOMAIN}:3000/api/admin" -RESTAPI_WEBRTC = "http://#{ATTACK_DOMAIN}:3000/api/webrtc" -RESTAPI_REQUESTER = "http://#{ATTACK_DOMAIN}:3000/api/requester" +RESTAPI_HOOKS = 'http://' + ATTACK_DOMAIN + ':3000/api/hooks' +RESTAPI_LOGS = 'http://' + ATTACK_DOMAIN + ':3000/api/logs' +RESTAPI_MODULES = 'http://' + ATTACK_DOMAIN + ':3000/api/modules' +RESTAPI_NETWORK = 'http://' + ATTACK_DOMAIN + ':3000/api/network' +RESTAPI_PROXY = 'http://' + ATTACK_DOMAIN + ':3000/api/proxy' +RESTAPI_DNS = 'http://' + ATTACK_DOMAIN + ':3000/api/dns' +RESTAPI_SENG = 'http://' + ATTACK_DOMAIN + ':3000/api/seng' +RESTAPI_ADMIN = 'http://' + ATTACK_DOMAIN + ':3000/api/admin' +RESTAPI_WEBRTC = 'http://' + ATTACK_DOMAIN + ':3000/api/webrtc' +RESTAPI_REQUESTER = 'http://' + ATTACK_DOMAIN + ':3000/api/requester' # Other PAGE_LOAD_TIMEOUT = 5 SERVER_START_TIMEOUT = 5 -BROWSER_HOOKING_TIMEOUT = 10 +BROWSER_HOOKING_TIMEOUT = 10 \ No newline at end of file diff --git a/spec/support/ui_support.rb b/spec/support/ui_support.rb index 0af32007c2..e350d9bfa5 100644 --- a/spec/support/ui_support.rb +++ b/spec/support/ui_support.rb @@ -7,109 +7,109 @@ require 'rest-client' require 'spec/support/constants.rb' -def start_beef_and_hook_browser - reset_beef_db - pid = start_beef_server_and_wait - beef_session = BeefTest.login - hooked_browser = BeefTest.new_victim +def start_beef_and_hook_browser() + reset_beef_db + pid = start_beef_server_and_wait + beef_session = BeefTest.login + hooked_browser = BeefTest.new_victim - expect(hooked_browser).not_to be_nil - expect(hooked_browser).to be_a(Capybara::Session) - expect(hooked_browser).to have_content('BeEF', wait: PAGE_LOAD_TIMEOUT) + expect(hooked_browser).not_to be_nil + expect(hooked_browser).to be_a(Capybara::Session) + expect(hooked_browser).to have_content('BeEF', wait: PAGE_LOAD_TIMEOUT) - expect(beef_session).not_to be_nil - expect(beef_session).to be_a(Capybara::Session) - expect(beef_session).to have_content('Hooked Browsers', wait: PAGE_LOAD_TIMEOUT) + expect(beef_session).not_to be_nil + expect(beef_session).to be_a(Capybara::Session) + expect(beef_session).to have_content('Hooked Browsers', wait: PAGE_LOAD_TIMEOUT) - navigate_to_hooked_browser(beef_session) + navigate_to_hooked_browser(beef_session) - expect(beef_session).to have_content('Commands', wait: PAGE_LOAD_TIMEOUT) - beef_session.click_on('Commands') + expect(beef_session).to have_content('Commands', wait: PAGE_LOAD_TIMEOUT) + beef_session.click_on('Commands') - [pid, beef_session, hooked_browser] + return pid, beef_session, hooked_browser end def stop_beef_and_unhook_browser(pid, beef_session, hooked_browser) - stop_beef_server(pid) - beef_session.driver.browser.close - hooked_browser.driver.browser.close + stop_beef_server(pid) + beef_session.driver.browser.close + hooked_browser.driver.browser.close end def navigate_to_hooked_browser(session, hooked_browser_text = nil) - expect(session).to have_content('Hooked Browsers', wait: PAGE_LOAD_TIMEOUT) + expect(session).to have_content('Hooked Browsers', wait: PAGE_LOAD_TIMEOUT) - hooked_browser_text = '127.0.0.1' if hooked_browser_text.nil? - expect(session).to have_content(hooked_browser_text, wait: BROWSER_HOOKING_TIMEOUT) + hooked_browser_text = '127.0.0.1' if hooked_browser_text.nil? + expect(session).to have_content(hooked_browser_text, wait: BROWSER_HOOKING_TIMEOUT) - # click on the hooked browser in the leaf - session.all('a', text: hooked_browser_text)[1].click - expect(session).to have_content('Commands', wait: PAGE_LOAD_TIMEOUT) + # click on the hooked browser in the leaf + session.all('a', text: hooked_browser_text)[1].click + expect(session).to have_content('Commands', wait: PAGE_LOAD_TIMEOUT) end def navigate_to_category(session, category_name = nil) - expect(category_name).not_to be_nil - expect(category_name).to be_a(String) + expect(category_name).not_to be_nil + expect(category_name).to be_a(String) - navigate_to_hooked_browser unless session.has_content?('Current Browser') + navigate_to_hooked_browser unless session.has_content?('Current Browser') - # ensure the command module tree is visible - session.click_on('Commands') - expect(session).to have_content(category_name, wait: PAGE_LOAD_TIMEOUT) + # ensure the command module tree is visible + session.click_on('Commands') + expect(session).to have_content(category_name, wait: PAGE_LOAD_TIMEOUT) - session.first(:link_or_button, "#{category_name} ").click + session.first(:link_or_button, category_name + " ").click end def expand_category_tree(session, category, module_name = nil) - if category.is_a?(Array) - category.each do |category_name| - # find the category element and scroll to it - session.all('div', text: category_name).each do |element| - begin - element_text = element.text - next unless element_text.start_with?(category_name) - - match_data = element_text.match(/\A([\w\s]+)\s\((\d+)\)\z/) - next unless match_data - - # scroll to the element - session.scroll_to(element) - rescue Selenium::WebDriver::Error::StaleElementReferenceError => e - puts "StaleElementReferenceError: #{element_text}" - puts e.message - next + if category.is_a?(Array) + category.each do |category_name| + # find the category element and scroll to it + session.all('div', text: category_name).each do |element| + begin + element_text = element.text + next unless element_text.start_with?(category_name) + match_data = element_text.match(/\A([\w\s]+)\s\((\d+)\)\z/) + next unless match_data + + # scroll to the element + session.scroll_to(element) + rescue Selenium::WebDriver::Error::StaleElementReferenceError => e + + puts "StaleElementReferenceError: #{element_text}" + puts e.message + next + end + end + + expect(session).to have_content(category_name, wait: PAGE_LOAD_TIMEOUT) + navigate_to_category(session, category_name) unless session.has_content?(module_name) end - end - - expect(session).to have_content(category_name, wait: PAGE_LOAD_TIMEOUT) - navigate_to_category(session, category_name) unless session.has_content?(module_name) + else + navigate_to_category(session, category) unless session.has_content?(module_name) + expect(session).to have_content(category, wait: PAGE_LOAD_TIMEOUT) end - else - navigate_to_category(session, category) unless session.has_content?(module_name) - expect(session).to have_content(category, wait: PAGE_LOAD_TIMEOUT) - end - expect(session).to have_content(module_name, wait: PAGE_LOAD_TIMEOUT) + expect(session).to have_content(module_name, wait: PAGE_LOAD_TIMEOUT) end - + def collapse_category_tree(session, category) - if category.is_a?(Array) - category.reverse.each do |category_name| - # Collapse the sub-folder - session.scroll_to(category_name) - session.first(:link_or_button, "#{category_name} ").click + if category.is_a?(Array) + category.reverse.each do |category_name| + # Collapse the sub-folder + session.scroll_to(category_name) + session.first(:link_or_button, category_name + " ").click + end + else + session.scroll_to(category) + session.first(:link_or_button, category + " ").click end - else - session.scroll_to(category) - session.first(:link_or_button, "#{category} ").click - end end def click_on_module(session, category, module_name) - # expand the category tree to make the module visible - expand_category_tree(session, category, module_name) - - # click on the module in the expanded tree - session.scroll_to(module_name) - expect(session).to have_content(module_name, wait: PAGE_LOAD_TIMEOUT) - modules = session.all(:link_or_button, module_name) - modules[0].click -end + # expand the category tree to make the module visible + expand_category_tree(session, category, module_name) + + # click on the module in the expanded tree + session.scroll_to(module_name) + expect(session).to have_content(module_name, wait: PAGE_LOAD_TIMEOUT) + modules = session.all(:link_or_button, module_name) + modules[0].click +end \ No newline at end of file From e76082902258c8f2dee07e05331b7d1764aa4e53 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:46:57 +0530 Subject: [PATCH 26/85] rubocop --only Layout/LineEndStringConcatenationIndentation -a --- modules/social_engineering/gmail_phishing/module.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/social_engineering/gmail_phishing/module.rb b/modules/social_engineering/gmail_phishing/module.rb index e0c603d52a..f75d353f2c 100644 --- a/modules/social_engineering/gmail_phishing/module.rb +++ b/modules/social_engineering/gmail_phishing/module.rb @@ -17,7 +17,7 @@ def self.options [ { 'name' => 'xss_hook_url', 'description' => 'The URI including the XSS to hook a browser. If the XSS is not exploitable via an URI, ' \ - 'simply leave this field empty, but this means you will loose the hooked browser after executing this module.', + 'simply leave this field empty, but this means you will loose the hooked browser after executing this module.', 'ui_label' => 'XSS hook URI', 'value' => xss_hook_url, 'width' => '300px' }, { @@ -29,7 +29,7 @@ def self.options }, { 'name' => 'wait_seconds_before_redirect', 'description' => 'When the user submits his credentials on the phishing page, we have to wait (in ms) ' \ - 'before we redirect to the real Gmail page, so that BeEF gets the credentials in time.', + 'before we redirect to the real Gmail page, so that BeEF gets the credentials in time.', 'ui_label' => 'Redirect delay (ms)', 'value' => wait_seconds_before_redirect, 'width' => '100px' From c56cd502cedb0523c5b27cfe0f19235190576db2 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:50:09 +0530 Subject: [PATCH 27/85] Disable Style/GuardClause cop --- .rubocop.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.rubocop.yml b/.rubocop.yml index f6cbe8160c..402b3e8cab 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -39,6 +39,9 @@ Naming/ClassAndModuleCamelCase: Style/Documentation: Enabled: false +Style/GuardClause: + Enabled: false + Style/RescueStandardError: Enabled: false From 26ad668ab34f53c2f85f86751278516290c4404e Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:51:10 +0530 Subject: [PATCH 28/85] rubocop --only Layout/EmptyLinesAroundClassBody -a --- core/main/console/banners.rb | 1 - extensions/notifications/channels/ntfy.rb | 2 -- extensions/webrtc/api/hook.rb | 2 -- extensions/webrtc/handlers.rb | 3 --- extensions/webrtc/models/rtcmanage.rb | 2 -- extensions/webrtc/models/rtcmodulestatus.rb | 3 --- extensions/webrtc/models/rtcsignal.rb | 2 -- extensions/webrtc/models/rtcstatus.rb | 2 -- 8 files changed, 17 deletions(-) diff --git a/core/main/console/banners.rb b/core/main/console/banners.rb index d3f0045390..5fdbd6bf2d 100644 --- a/core/main/console/banners.rb +++ b/core/main/console/banners.rb @@ -156,7 +156,6 @@ def print_dns print_more upstream_servers unless upstream_servers.empty? end end - end end end diff --git a/extensions/notifications/channels/ntfy.rb b/extensions/notifications/channels/ntfy.rb index 343d503cdc..ad4895f1ed 100644 --- a/extensions/notifications/channels/ntfy.rb +++ b/extensions/notifications/channels/ntfy.rb @@ -6,7 +6,6 @@ module Extension module Notifications module Channels class Ntfy - # Constructor def initialize(message) @config = BeEF::Core::Configuration.instance @@ -36,7 +35,6 @@ def initialize(message) # Send request http.request(req) end - end end end diff --git a/extensions/webrtc/api/hook.rb b/extensions/webrtc/api/hook.rb index 5d0d8ad2b1..1c923ab12d 100644 --- a/extensions/webrtc/api/hook.rb +++ b/extensions/webrtc/api/hook.rb @@ -14,7 +14,6 @@ module API require 'uri' class Hook - include BeEF::Core::Handlers::Modules::BeEFJS # If the RtcSignal table contains requests that need to be sent (has_sent = waiting), retrieve @@ -102,7 +101,6 @@ def add_rtcmanagement_to_body(output) }); } end - end end end diff --git a/extensions/webrtc/handlers.rb b/extensions/webrtc/handlers.rb index 95875b5b5a..868dd96d67 100644 --- a/extensions/webrtc/handlers.rb +++ b/extensions/webrtc/handlers.rb @@ -11,7 +11,6 @@ module WebRTC # The http handler that manages the WebRTC signals sent from browsers to other browsers. # class SignalHandler - R = BeEF::Core::Models::RtcSignal Z = BeEF::Core::Models::HookedBrowser @@ -57,7 +56,6 @@ def setup # The http handler that manages the WebRTC messages sent from browsers. # class MessengeHandler - Z = BeEF::Core::Models::HookedBrowser def initialize(data) @@ -157,7 +155,6 @@ def setup end end - end end end diff --git a/extensions/webrtc/models/rtcmanage.rb b/extensions/webrtc/models/rtcmanage.rb index 6801af330c..6ef4339e39 100644 --- a/extensions/webrtc/models/rtcmanage.rb +++ b/extensions/webrtc/models/rtcmanage.rb @@ -10,7 +10,6 @@ module Models # Table stores the queued up JS commands for managing the client-side webrtc logic. # class RtcManage < BeEF::Core::Model - # Starts the RTCPeerConnection process, establishing a WebRTC connection between the caller and the receiver def self.initiate(caller, receiver, verbosity = false) stunservers = BeEF::Core::Configuration.instance.get('beef.extension.webrtc.stunservers') @@ -39,7 +38,6 @@ def self.status(id) r = BeEF::Core::Models::RtcManage.new(hooked_browser_id: id, message: "beef.webrtc.status(#{id});") r.save! end - end end diff --git a/extensions/webrtc/models/rtcmodulestatus.rb b/extensions/webrtc/models/rtcmodulestatus.rb index f434db933a..fd8b838a11 100644 --- a/extensions/webrtc/models/rtcmodulestatus.rb +++ b/extensions/webrtc/models/rtcmodulestatus.rb @@ -14,11 +14,8 @@ module Models class Rtcmodulestatus < BeEF::Core::Model - belongs_to :hooked_browser belongs_to :command_module - - end end diff --git a/extensions/webrtc/models/rtcsignal.rb b/extensions/webrtc/models/rtcsignal.rb index 8a55373f65..d522068215 100644 --- a/extensions/webrtc/models/rtcsignal.rb +++ b/extensions/webrtc/models/rtcsignal.rb @@ -10,9 +10,7 @@ module Models # Table stores the webrtc signals from a hooked_browser, directed to a target_hooked_browser # class RtcSignal < BeEF::Core::Model - belongs_to :hooked_browser - end end diff --git a/extensions/webrtc/models/rtcstatus.rb b/extensions/webrtc/models/rtcstatus.rb index 506697b5fb..839edd5a60 100644 --- a/extensions/webrtc/models/rtcstatus.rb +++ b/extensions/webrtc/models/rtcstatus.rb @@ -14,9 +14,7 @@ module Models class Rtcstatus < BeEF::Core::Model - belongs_to :hooked_browser - end end From e2849bd21dc0972d7ac58a179fab0d886d5bfbf1 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:51:36 +0530 Subject: [PATCH 29/85] rubocop --only Layout/EmptyLinesAroundModuleBody -a --- extensions/webrtc/api.rb | 6 ------ extensions/webrtc/api/hook.rb | 1 - extensions/webrtc/extension.rb | 2 -- extensions/webrtc/handlers.rb | 1 - extensions/webrtc/models/rtcmanage.rb | 1 - extensions/webrtc/models/rtcmodulestatus.rb | 1 - extensions/webrtc/models/rtcsignal.rb | 1 - extensions/webrtc/models/rtcstatus.rb | 1 - 8 files changed, 14 deletions(-) diff --git a/extensions/webrtc/api.rb b/extensions/webrtc/api.rb index fc6d871824..780f81a8bc 100644 --- a/extensions/webrtc/api.rb +++ b/extensions/webrtc/api.rb @@ -6,9 +6,7 @@ module BeEF module Extension module WebRTC - module RegisterHttpHandler - BeEF::API::Registrar.instance.register(BeEF::Extension::WebRTC::RegisterHttpHandler, BeEF::API::Server, 'mount_handler') # We register the http handler for the WebRTC signalling extension. @@ -20,11 +18,9 @@ def self.mount_handler(beef_server) beef_server.mount('/rtcmessage', BeEF::Extension::WebRTC::MessengeHandler) beef_server.mount('/api/webrtc', BeEF::Extension::WebRTC::WebRTCRest.new) end - end module RegisterPreHookCallback - BeEF::API::Registrar.instance.register(BeEF::Extension::WebRTC::RegisterPreHookCallback, BeEF::API::Server::Hook, 'pre_hook_send') # We register this pre hook action to ensure that signals going to a browser are included back in the hook.js polling @@ -33,9 +29,7 @@ def self.pre_hook_send(hooked_browser, body, params, request, response) dhook = BeEF::Extension::WebRTC::API::Hook.new dhook.requester_run(hooked_browser, body) end - end - end end end diff --git a/extensions/webrtc/api/hook.rb b/extensions/webrtc/api/hook.rb index 1c923ab12d..76aee4231e 100644 --- a/extensions/webrtc/api/hook.rb +++ b/extensions/webrtc/api/hook.rb @@ -11,7 +11,6 @@ module BeEF module Extension module WebRTC module API - require 'uri' class Hook include BeEF::Core::Handlers::Modules::BeEFJS diff --git a/extensions/webrtc/extension.rb b/extensions/webrtc/extension.rb index 1f01e7ad09..62a405ffab 100644 --- a/extensions/webrtc/extension.rb +++ b/extensions/webrtc/extension.rb @@ -6,13 +6,11 @@ module BeEF module Extension module WebRTC - extend BeEF::API::Extension @short_name = 'webrtc' @full_name = 'WebRTC' @description = 'WebRTC extension to all browsers to connect to each other (P2P) with WebRTC' - end end end diff --git a/extensions/webrtc/handlers.rb b/extensions/webrtc/handlers.rb index 868dd96d67..9af384678a 100644 --- a/extensions/webrtc/handlers.rb +++ b/extensions/webrtc/handlers.rb @@ -6,7 +6,6 @@ module BeEF module Extension module WebRTC - # # The http handler that manages the WebRTC signals sent from browsers to other browsers. # diff --git a/extensions/webrtc/models/rtcmanage.rb b/extensions/webrtc/models/rtcmanage.rb index 6ef4339e39..faeefa9cab 100644 --- a/extensions/webrtc/models/rtcmanage.rb +++ b/extensions/webrtc/models/rtcmanage.rb @@ -39,7 +39,6 @@ def self.status(id) r.save! end end - end end end diff --git a/extensions/webrtc/models/rtcmodulestatus.rb b/extensions/webrtc/models/rtcmodulestatus.rb index fd8b838a11..b9a57dd615 100644 --- a/extensions/webrtc/models/rtcmodulestatus.rb +++ b/extensions/webrtc/models/rtcmodulestatus.rb @@ -17,7 +17,6 @@ class Rtcmodulestatus < BeEF::Core::Model belongs_to :hooked_browser belongs_to :command_module end - end end end diff --git a/extensions/webrtc/models/rtcsignal.rb b/extensions/webrtc/models/rtcsignal.rb index d522068215..e9df3fd3cc 100644 --- a/extensions/webrtc/models/rtcsignal.rb +++ b/extensions/webrtc/models/rtcsignal.rb @@ -12,7 +12,6 @@ module Models class RtcSignal < BeEF::Core::Model belongs_to :hooked_browser end - end end end diff --git a/extensions/webrtc/models/rtcstatus.rb b/extensions/webrtc/models/rtcstatus.rb index 839edd5a60..034018a0e5 100644 --- a/extensions/webrtc/models/rtcstatus.rb +++ b/extensions/webrtc/models/rtcstatus.rb @@ -16,7 +16,6 @@ module Models class Rtcstatus < BeEF::Core::Model belongs_to :hooked_browser end - end end end From b258d7750c6eb9b1f7fe94a26cd91065dbd760f9 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:52:14 +0530 Subject: [PATCH 30/85] rubocop --only Lint/RedundantStringCoercion -a --- core/main/rest/handlers/modules.rb | 2 +- core/ruby/print.rb | 10 +++++----- extensions/admin_ui/controllers/modules/modules.rb | 2 +- extensions/dns_rebinding/dns_rebinding.rb | 10 +++++----- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/core/main/rest/handlers/modules.rb b/core/main/rest/handlers/modules.rb index 337b58a942..f0b5076226 100644 --- a/core/main/rest/handlers/modules.rb +++ b/core/main/rest/handlers/modules.rb @@ -145,7 +145,7 @@ class Modules < BeEF::Core::Router::Router options = [] data.each { |k, v| options.push({ 'name' => k, 'value' => v }) } exec_results = BeEF::Module.execute(modk, params[:session], options) - exec_results.nil? ? '{"success":"false"}' : "{\"success\":\"true\",\"command_id\":\"#{exec_results.to_s}\"}" + exec_results.nil? ? '{"success":"false"}' : "{\"success\":\"true\",\"command_id\":\"#{exec_results}\"}" rescue StandardError print_error "Invalid JSON input for module '#{params[:mod_id]}'" error 400 # Bad Request diff --git a/core/ruby/print.rb b/core/ruby/print.rb index 582b10f237..bab8b16763 100644 --- a/core/ruby/print.rb +++ b/core/ruby/print.rb @@ -7,14 +7,14 @@ # Function used to print errors to the console # @param [String] s String to be printed def print_error(s) - puts "#{Time.now.localtime.strftime('[%k:%M:%S]')}[!] #{s.to_s}" + puts "#{Time.now.localtime.strftime('[%k:%M:%S]')}[!] #{s}" BeEF.logger.error s.to_s end # Function used to print information to the console # @param [String] s String to be printed def print_info(s) - puts "#{Time.now.localtime.strftime('[%k:%M:%S]')}[*] #{s.to_s}" + puts "#{Time.now.localtime.strftime('[%k:%M:%S]')}[*] #{s}" BeEF.logger.info s.to_s end @@ -27,7 +27,7 @@ def print_status(s) # Function used to print warning information # @param [String] s String to be printed def print_warning(s) - puts "#{Time.now.localtime.strftime('[%k:%M:%S]')}[!] #{s.to_s}" + puts "#{Time.now.localtime.strftime('[%k:%M:%S]')}[!] #{s}" BeEF.logger.warn s.to_s end @@ -38,14 +38,14 @@ def print_debug(s) config = BeEF::Core::Configuration.instance return unless config.get('beef.debug') || BeEF::Core::Console::CommandLine.parse[:verbose] - puts "#{Time.now.localtime.strftime('[%k:%M:%S]')}[>] #{s.to_s}" + puts "#{Time.now.localtime.strftime('[%k:%M:%S]')}[>] #{s}" BeEF.logger.debug s.to_s end # Function used to print successes to the console # @param [String] s String to be printed def print_success(s) - puts "#{Time.now.localtime.strftime('[%k:%M:%S]')}[+] #{s.to_s}" + puts "#{Time.now.localtime.strftime('[%k:%M:%S]')}[+] #{s}" BeEF.logger.info s.to_s end diff --git a/extensions/admin_ui/controllers/modules/modules.rb b/extensions/admin_ui/controllers/modules/modules.rb index bcee8ec6c9..52dd9a2c73 100644 --- a/extensions/admin_ui/controllers/modules/modules.rb +++ b/extensions/admin_ui/controllers/modules/modules.rb @@ -190,7 +190,7 @@ def retitle_recursive_tree(parent) retitle_recursive_tree([c]) if c.has_key?('cls') && c['cls'] == 'folder' end num_of_command_modules = command_module_branch['children'].length + num_of_subs - command_module_branch['text'] = "#{command_module_branch['text']} (#{num_of_command_modules.to_s})" + command_module_branch['text'] = "#{command_module_branch['text']} (#{num_of_command_modules})" end end diff --git a/extensions/dns_rebinding/dns_rebinding.rb b/extensions/dns_rebinding/dns_rebinding.rb index c79135a342..bf42c681f6 100644 --- a/extensions/dns_rebinding/dns_rebinding.rb +++ b/extensions/dns_rebinding/dns_rebinding.rb @@ -5,7 +5,7 @@ module DNSRebinding class Server @debug_mode = false def self.log(msg) - warn msg.to_s if @debug_mode + warn msg if @debug_mode end def self.run_server(address, port) @@ -112,7 +112,7 @@ def self.read_http_message(socket) def self.handle_victim(socket, http_message) log "[Victim]request from victim\n" - log "#{http_message['start_string'].to_s}\n" + log "#{http_message['start_string']}\n" if http_message['start_string'].include?('POST') # Get result from POST query @@ -124,8 +124,8 @@ def self.handle_victim(socket, http_message) length = http_message['headers']['Content-Length'].to_i content_type = http_message['headers']['Content-Type'] - log "[Victim]Content-type: #{content_type.to_s}\n" - log "[Vicitm]Length: #{length.to_s}\n" + log "[Victim]Content-type: #{content_type}\n" + log "[Vicitm]Length: #{length}\n" response = http_message['response'] log "[Victim]Get content!\n" @@ -154,7 +154,7 @@ def self.handle_victim(socket, http_message) @mutex_queries.lock log "[Victim]Get the last query\n" last_query = @queries.pop - log "[Victim]Last query:#{last_query.to_s}\n" + log "[Victim]Last query:#{last_query}\n" @mutex_queries.unlock response = last_query[2] From b9e798e2e34d74f67f3b80ee523b2ef3076142f7 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:53:12 +0530 Subject: [PATCH 31/85] Disable Bundler/OrderedGems cop --- .rubocop.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.rubocop.yml b/.rubocop.yml index 402b3e8cab..f3655ca680 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -8,6 +8,9 @@ AllCops: - "spec/**/*" - "test/**/*" +Bundler/OrderedGems: + Enabled: false + Layout/LineLength: Enabled: true Max: 180 From a3e15c6d34b955bf27baebd3c7e75fbd3d34a01c Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:54:56 +0530 Subject: [PATCH 32/85] Disable Style/IfInsideElse cop --- .rubocop.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.rubocop.yml b/.rubocop.yml index f3655ca680..fd9c132bba 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -45,6 +45,9 @@ Style/Documentation: Style/GuardClause: Enabled: false +Style/IfInsideElse: + Enabled: false + Style/RescueStandardError: Enabled: false From 6abd66fa43ffc780fef8d0b5626fdbb23c3caeb3 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:55:55 +0530 Subject: [PATCH 33/85] rubocop --only Layout/MultilineOperationIndentation -a --- core/main/network_stack/handlers/dynamicreconstruction.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/main/network_stack/handlers/dynamicreconstruction.rb b/core/main/network_stack/handlers/dynamicreconstruction.rb index 538b5a26c0..d74c621c8f 100644 --- a/core/main/network_stack/handlers/dynamicreconstruction.rb +++ b/core/main/network_stack/handlers/dynamicreconstruction.rb @@ -72,8 +72,8 @@ def check_packets res['request'] = request session_key = BeEF::Core::Configuration.instance.get('beef.http.hook_session_name') res['beefsession'] = request.cookies[session_key] || - request.params[session_key] || - request.env[session_key] + request.params[session_key] || + request.env[session_key] execute(res) rescue JSON::ParserError => e From 702cd696bccdbf7cfd249fb4a9803e6371e61a59 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:56:28 +0530 Subject: [PATCH 34/85] rubocop --only Style/SuperArguments -a --- core/main/command.rb | 2 +- extensions/dns/dns.rb | 2 +- extensions/dns/model.rb | 2 +- extensions/dns/rest/dns.rb | 2 +- extensions/metasploit/rest/msf.rb | 2 +- extensions/metasploit/rpcclient.rb | 2 +- extensions/network/rest/network.rb | 2 +- extensions/proxy/rest/proxy.rb | 2 +- extensions/requester/rest/requester.rb | 2 +- extensions/s2c_dns_tunnel/dnsd.rb | 2 +- extensions/webrtc/rest/webrtc.rb | 2 +- extensions/xssrays/rest/xssrays.rb | 2 +- modules/misc/wordpress/add_user/module.rb | 2 +- modules/misc/wordpress/upload_rce_plugin/module.rb | 2 +- 14 files changed, 14 insertions(+), 14 deletions(-) diff --git a/core/main/command.rb b/core/main/command.rb index d2ce034270..4eb15fde0b 100644 --- a/core/main/command.rb +++ b/core/main/command.rb @@ -33,7 +33,7 @@ class CommandContext < Erubis::Context # @param [Hash] hash # def initialize(hash = nil) - super(hash) + super end end diff --git a/extensions/dns/dns.rb b/extensions/dns/dns.rb index 40ed48e35a..b530f36ab8 100644 --- a/extensions/dns/dns.rb +++ b/extensions/dns/dns.rb @@ -14,7 +14,7 @@ class Server < Async::DNS::Server include Singleton def initialize - super() + super logger.level = Logger::ERROR @lock = Mutex.new @database = BeEF::Core::Models::Dns::Rule diff --git a/extensions/dns/model.rb b/extensions/dns/model.rb index d05d5f7d66..1bca9c5452 100644 --- a/extensions/dns/model.rb +++ b/extensions/dns/model.rb @@ -195,7 +195,7 @@ class InvalidDnsResponseError < StandardError def initialize(message = nil) str = 'Failed to add DNS rule with invalid response for %s resource record', message message = format str, message unless message.nil? - super(message) + super end end diff --git a/extensions/dns/rest/dns.rb b/extensions/dns/rest/dns.rb index ac3f2a8313..bf5997a124 100644 --- a/extensions/dns/rest/dns.rb +++ b/extensions/dns/rest/dns.rb @@ -151,7 +151,7 @@ class InvalidParamError < StandardError def initialize(message = nil) str = 'Invalid "%s" parameter passed to /api/dns handler' message = format str, message unless message.nil? - super(message) + super end end end diff --git a/extensions/metasploit/rest/msf.rb b/extensions/metasploit/rest/msf.rb index e848e4a713..0cd24f860e 100644 --- a/extensions/metasploit/rest/msf.rb +++ b/extensions/metasploit/rest/msf.rb @@ -127,7 +127,7 @@ class InvalidParamError < StandardError def initialize(message = nil) str = 'Invalid "%s" parameter passed to /api/msf handler' message = format str, message unless message.nil? - super(message) + super end end end diff --git a/extensions/metasploit/rpcclient.rb b/extensions/metasploit/rpcclient.rb index a7502c0f90..0cd9a74f33 100644 --- a/extensions/metasploit/rpcclient.rb +++ b/extensions/metasploit/rpcclient.rb @@ -119,7 +119,7 @@ def release_lock end def call(meth, *args) - super(meth, *args) + super rescue StandardError => e print_error "[Metasploit] RPC call to '#{meth}' failed: #{e}" print_error e.backtrace diff --git a/extensions/network/rest/network.rb b/extensions/network/rest/network.rb index f5a9563b23..a7a5a53959 100644 --- a/extensions/network/rest/network.rb +++ b/extensions/network/rest/network.rb @@ -178,7 +178,7 @@ class InvalidParamError < StandardError def initialize(message = nil) message = "Invalid \"#{message}\" parameter passed to /api/network handler" unless message.nil? - super(message) + super end end end diff --git a/extensions/proxy/rest/proxy.rb b/extensions/proxy/rest/proxy.rb index 3753103dfe..952f335e89 100644 --- a/extensions/proxy/rest/proxy.rb +++ b/extensions/proxy/rest/proxy.rb @@ -73,7 +73,7 @@ class InvalidParamError < StandardError def initialize(message = nil) str = 'Invalid "%s" parameter passed to /api/proxy handler' message = format str, message unless message.nil? - super(message) + super end end end diff --git a/extensions/requester/rest/requester.rb b/extensions/requester/rest/requester.rb index 76585bddb1..a5a9408206 100644 --- a/extensions/requester/rest/requester.rb +++ b/extensions/requester/rest/requester.rb @@ -271,7 +271,7 @@ class InvalidParamError < StandardError def initialize(message = nil) str = 'Invalid "%s" parameter passed to /api/requester handler' message = format str, message unless message.nil? - super(message) + super end end end diff --git a/extensions/s2c_dns_tunnel/dnsd.rb b/extensions/s2c_dns_tunnel/dnsd.rb index aa9ef8f701..0094b22a9f 100644 --- a/extensions/s2c_dns_tunnel/dnsd.rb +++ b/extensions/s2c_dns_tunnel/dnsd.rb @@ -34,7 +34,7 @@ class Server < RubyDNS::Server attr_accessor :messages def initialize - super() + super @lock = Mutex.new end diff --git a/extensions/webrtc/rest/webrtc.rb b/extensions/webrtc/rest/webrtc.rb index 752efacd3c..86062041df 100644 --- a/extensions/webrtc/rest/webrtc.rb +++ b/extensions/webrtc/rest/webrtc.rb @@ -468,7 +468,7 @@ class InvalidParamError < StandardError def initialize(message = nil) str = 'Invalid "%s" parameter passed to /api/webrtc handler' message = format str, message unless message.nil? - super(message) + super end end end diff --git a/extensions/xssrays/rest/xssrays.rb b/extensions/xssrays/rest/xssrays.rb index 0f10ca5455..5f5a559a3c 100644 --- a/extensions/xssrays/rest/xssrays.rb +++ b/extensions/xssrays/rest/xssrays.rb @@ -204,7 +204,7 @@ class InvalidParamError < StandardError def initialize(message = nil) str = 'Invalid "%s" parameter passed to /api/xssrays handler' message = format str, message unless message.nil? - super(message) + super end end end diff --git a/modules/misc/wordpress/add_user/module.rb b/modules/misc/wordpress/add_user/module.rb index b621e35dc7..fd598063bd 100644 --- a/modules/misc/wordpress/add_user/module.rb +++ b/modules/misc/wordpress/add_user/module.rb @@ -11,7 +11,7 @@ class Wordpress_add_user < WordPressCommand def self.options - super() + [ + super + [ { 'name' => 'username', 'ui_label' => 'Username', 'value' => 'beef' }, { 'name' => 'password', 'ui_label' => 'Pwd', 'value' => SecureRandom.hex(5) }, { 'name' => 'email', 'ui_label' => 'Email', 'value' => '' }, diff --git a/modules/misc/wordpress/upload_rce_plugin/module.rb b/modules/misc/wordpress/upload_rce_plugin/module.rb index b4e3042c56..5fdbcf27db 100644 --- a/modules/misc/wordpress/upload_rce_plugin/module.rb +++ b/modules/misc/wordpress/upload_rce_plugin/module.rb @@ -42,7 +42,7 @@ def self.generate_zip_payload(auth_key) end def self.options - super() + [ + super + [ { 'name' => 'auth_key', 'ui_label' => 'Auth Key', 'value' => SecureRandom.hex(8) } ] end From 5832b8ef841cbb965595d1fc6f61b61d6bc602a4 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:57:00 +0530 Subject: [PATCH 35/85] rubocop --only Layout/EmptyLinesAfterModuleInclusion -a --- core/main/command.rb | 1 + core/main/server.rb | 1 + extensions/etag/etag.rb | 1 + extensions/s2c_dns_tunnel/extension.rb | 1 + 4 files changed, 4 insertions(+) diff --git a/core/main/command.rb b/core/main/command.rb index 4eb15fde0b..26c12a03dd 100644 --- a/core/main/command.rb +++ b/core/main/command.rb @@ -28,6 +28,7 @@ def format_multiline(text) # class CommandContext < Erubis::Context include BeEF::Core::CommandUtils + # # Constructor # @param [Hash] hash diff --git a/core/main/server.rb b/core/main/server.rb index d71c7dce19..7d28f538d9 100644 --- a/core/main/server.rb +++ b/core/main/server.rb @@ -12,6 +12,7 @@ module BeEF module Core class Server include Singleton + attr_reader :root_dir, :url, :configuration, :command_urls, :mounts, :semaphore def initialize diff --git a/extensions/etag/etag.rb b/extensions/etag/etag.rb index 51425af55b..8bb1779045 100644 --- a/extensions/etag/etag.rb +++ b/extensions/etag/etag.rb @@ -11,6 +11,7 @@ module ETag class ETagMessages include Singleton + attr_accessor :messages def initialize diff --git a/extensions/s2c_dns_tunnel/extension.rb b/extensions/s2c_dns_tunnel/extension.rb index 491963bfe1..3100675754 100644 --- a/extensions/s2c_dns_tunnel/extension.rb +++ b/extensions/s2c_dns_tunnel/extension.rb @@ -7,6 +7,7 @@ module BeEF module Extension module ServerClientDnsTunnel extend BeEF::API::Extension + @short_name = 'S2C DNS Tunnel' @full_name = 'Server-to-Client DNS Tunnel' @description = 'This extension provides a custom BeEF DNS server and HTTP server ' \ From 3ab7c25c0031da74c6bafbf32120f6c452435908 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:57:48 +0530 Subject: [PATCH 36/85] rubocop --only Style/ConditionalAssignment -a --- beef | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/beef b/beef index 7ad1f5b067..9e8f956e12 100755 --- a/beef +++ b/beef @@ -79,10 +79,10 @@ end # # @note Initialize the Configuration object. Loads a different config.yaml if -c flag was passed. # -if BeEF::Core::Console::CommandLine.parse[:ext_config].empty? - config = BeEF::Core::Configuration.new("#{$root_dir}/config.yaml") +config = if BeEF::Core::Console::CommandLine.parse[:ext_config].empty? + BeEF::Core::Configuration.new("#{$root_dir}/config.yaml") else - config = BeEF::Core::Configuration.new("#{BeEF::Core::Console::CommandLine.parse[:ext_config]}") + BeEF::Core::Configuration.new("#{BeEF::Core::Console::CommandLine.parse[:ext_config]}") end # From d1c36a4343aa061833e3402400eeba05974a6957 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:58:41 +0530 Subject: [PATCH 37/85] rubocop --only Style/Not -a --- extensions/qrcode/qrcode.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/qrcode/qrcode.rb b/extensions/qrcode/qrcode.rb index 56774e1a78..a56c0889e4 100644 --- a/extensions/qrcode/qrcode.rb +++ b/extensions/qrcode/qrcode.rb @@ -32,7 +32,7 @@ def self.pre_http_start(_http_hook_server) # Retrieve the list of network interfaces from BeEF::Core::Console::Banners interfaces = BeEF::Core::Console::Banners.interfaces - if not interfaces.nil? and not interfaces.empty? # If interfaces are available, iterate over each network interface + if !interfaces.nil? and !interfaces.empty? # If interfaces are available, iterate over each network interface # If interfaces are available, iterate over each network interface interfaces.each do |int| # Skip the loop iteration if the interface address is '0.0.0.0' (which generally represents all IPv4 addresses on the local machine) From 3b7ea2dc1ea83da6ff7deb00bd91fab1400ea59f Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:59:11 +0530 Subject: [PATCH 38/85] rubocop --only Style/RedundantRegexpArgument -a --- core/main/command.rb | 4 ++-- core/main/configuration.rb | 2 +- core/main/handlers/modules/beefjs.rb | 6 +++--- core/main/handlers/modules/legacybeefjs.rb | 6 +++--- core/main/handlers/modules/multistagebeefjs.rb | 6 +++--- extensions/requester/api/hook.rb | 8 ++++---- extensions/requester/rest/requester.rb | 2 +- modules/host/get_internal_ip_webrtc/module.rb | 2 +- modules/host/hook_default_browser/module.rb | 2 +- modules/misc/wordpress/upload_rce_plugin/module.rb | 2 +- 10 files changed, 20 insertions(+), 20 deletions(-) diff --git a/core/main/command.rb b/core/main/command.rb index 26c12a03dd..76090dc003 100644 --- a/core/main/command.rb +++ b/core/main/command.rb @@ -17,7 +17,7 @@ module CommandUtils # @return [String] Formatted string # def format_multiline(text) - text.gsub(/\n/, '\n') + text.gsub("\n", '\n') end end @@ -229,7 +229,7 @@ def use(component) component_path = "/#{component}" component_path.gsub!(/beef./, '') - component_path.gsub!(/\./, '/') + component_path.gsub!('.', '/') component_path.replace "#{$root_dir}/core/main/client/#{component_path}.js" raise "Invalid beefjs component for command module #{@path}" unless File.exist? component_path diff --git a/core/main/configuration.rb b/core/main/configuration.rb index e84a21c40d..c03253bc28 100644 --- a/core/main/configuration.rb +++ b/core/main/configuration.rb @@ -247,7 +247,7 @@ def load_extensions_config next end - y['beef']['extension'][y['beef']['extension'].keys.first]['path'] = cf.gsub(/config\.yaml/, '').gsub(%r{#{$root_dir}/}, '') + y['beef']['extension'][y['beef']['extension'].keys.first]['path'] = cf.gsub('config.yaml', '').gsub(%r{#{$root_dir}/}, '') @config = y.deep_merge(@config) end end diff --git a/core/main/handlers/modules/beefjs.rb b/core/main/handlers/modules/beefjs.rb index 0258025a9f..aaf8de6b34 100644 --- a/core/main/handlers/modules/beefjs.rb +++ b/core/main/handlers/modules/beefjs.rb @@ -74,7 +74,7 @@ def build_beefjs!(req_host) end if hook_session_config['beef_host'].eql? '0.0.0.0' hook_session_config['beef_host'] = req_host - hook_session_config['beef_url'].sub!(/0\.0\.0\.0/, req_host) + hook_session_config['beef_url'].sub!('0.0.0.0', req_host) end # @note set the XHR-polling timeout @@ -88,7 +88,7 @@ def build_beefjs!(req_host) if !hook_session_config['beef_public_port'].nil? && (hook_session_config['beef_port'] != hook_session_config['beef_public_port']) hook_session_config['beef_port'] = hook_session_config['beef_public_port'] hook_session_config['beef_url'].sub!(/#{hook_session_config['beef_port']}/, hook_session_config['beef_public_port']) - hook_session_config['beef_url'].sub!(/http:/, 'https:') if hook_session_config['beef_public_port'] == '443' + hook_session_config['beef_url'].sub!('http:', 'https:') if hook_session_config['beef_public_port'] == '443' end # @note Set some WebSocket properties @@ -121,7 +121,7 @@ def build_beefjs!(req_host) def find_beefjs_component_path(component) component_path = component component_path.gsub!(/beef./, '') - component_path.gsub!(/\./, '/') + component_path.gsub!('.', '/') component_path.replace "#{$root_dir}/core/main/client/#{component_path}.js" return false unless File.exist? component_path diff --git a/core/main/handlers/modules/legacybeefjs.rb b/core/main/handlers/modules/legacybeefjs.rb index 2580db0660..d4cda88fdf 100644 --- a/core/main/handlers/modules/legacybeefjs.rb +++ b/core/main/handlers/modules/legacybeefjs.rb @@ -74,7 +74,7 @@ def legacy_build_beefjs!(req_host) end if hook_session_config['beef_host'].eql? '0.0.0.0' hook_session_config['beef_host'] = req_host - hook_session_config['beef_url'].sub!(/0\.0\.0\.0/, req_host) + hook_session_config['beef_url'].sub!('0.0.0.0', req_host) end # @note set the XHR-polling timeout @@ -88,7 +88,7 @@ def legacy_build_beefjs!(req_host) if !hook_session_config['beef_public_port'].nil? && (hook_session_config['beef_port'] != hook_session_config['beef_public_port']) hook_session_config['beef_port'] = hook_session_config['beef_public_port'] hook_session_config['beef_url'].sub!(/#{hook_session_config['beef_port']}/, hook_session_config['beef_public_port']) - hook_session_config['beef_url'].sub!(/http:/, 'https:') if hook_session_config['beef_public_port'] == '443' + hook_session_config['beef_url'].sub!('http:', 'https:') if hook_session_config['beef_public_port'] == '443' end # @note Set some WebSocket properties @@ -121,7 +121,7 @@ def legacy_build_beefjs!(req_host) def legacy_find_beefjs_component_path(component) component_path = component component_path.gsub!(/beef./, '') - component_path.gsub!(/\./, '/') + component_path.gsub!('.', '/') component_path.replace "#{$root_dir}/core/main/client/#{component_path}.js" return false unless File.exist? component_path diff --git a/core/main/handlers/modules/multistagebeefjs.rb b/core/main/handlers/modules/multistagebeefjs.rb index 3a6b53fbc8..2797b37446 100644 --- a/core/main/handlers/modules/multistagebeefjs.rb +++ b/core/main/handlers/modules/multistagebeefjs.rb @@ -74,7 +74,7 @@ def multi_stage_beefjs!(req_host) end if hook_session_config['beef_host'].eql? '0.0.0.0' hook_session_config['beef_host'] = req_host - hook_session_config['beef_url'].sub!(/0\.0\.0\.0/, req_host) + hook_session_config['beef_url'].sub!('0.0.0.0', req_host) end # @note set the XHR-polling timeout @@ -88,7 +88,7 @@ def multi_stage_beefjs!(req_host) if !hook_session_config['beef_public_port'].nil? && (hook_session_config['beef_port'] != hook_session_config['beef_public_port']) hook_session_config['beef_port'] = hook_session_config['beef_public_port'] hook_session_config['beef_url'].sub!(/#{hook_session_config['beef_port']}/, hook_session_config['beef_public_port']) - hook_session_config['beef_url'].sub!(/http:/, 'https:') if hook_session_config['beef_public_port'] == '443' + hook_session_config['beef_url'].sub!('http:', 'https:') if hook_session_config['beef_public_port'] == '443' end # @note Set some WebSocket properties @@ -121,7 +121,7 @@ def multi_stage_beefjs!(req_host) def legacy_find_beefjs_component_path(component) component_path = component component_path.gsub!(/beef./, '') - component_path.gsub!(/\./, '/') + component_path.gsub!('.', '/') component_path.replace "#{$root_dir}/core/main/client/#{component_path}.js" return false unless File.exist? component_path diff --git a/extensions/requester/api/hook.rb b/extensions/requester/api/hook.rb index 6c3f729900..81b75b3f01 100644 --- a/extensions/requester/api/hook.rb +++ b/extensions/requester/api/hook.rb @@ -106,13 +106,13 @@ def requester_parse_db_request(http_db_object) req_parts.each_with_index do |value, index| if verb.eql?('POST') if index.positive? && (index < @post_data_index) # only add HTTP headers, not the verb/uri/version or post-data - header_key = value.split(/: /)[0] - header_value = value.split(/: /)[1] + header_key = value.split(': ')[0] + header_value = value.split(': ')[1] headers[header_key] = header_value end elsif index.positive? - header_key = value.split(/: /)[0] - header_value = value.split(/: /)[1] + header_key = value.split(': ')[0] + header_value = value.split(': ')[1] headers[header_key] = header_value # only add HTTP headers, not the verb/uri/version end end diff --git a/extensions/requester/rest/requester.rb b/extensions/requester/rest/requester.rb index a5a9408206..a206adce0a 100644 --- a/extensions/requester/rest/requester.rb +++ b/extensions/requester/rest/requester.rb @@ -160,7 +160,7 @@ class RequesterRest < BeEF::Core::Router::Router # Validate target hsot host = req_parts[4] - host_parts = host.split(/:/) + host_parts = host.split(':') host_name = host_parts[0] host_port = host_parts[1] || nil diff --git a/modules/host/get_internal_ip_webrtc/module.rb b/modules/host/get_internal_ip_webrtc/module.rb index b73273edfa..2f8f882d36 100755 --- a/modules/host/get_internal_ip_webrtc/module.rb +++ b/modules/host/get_internal_ip_webrtc/module.rb @@ -15,7 +15,7 @@ def post_execute return unless @datastore['results'] =~ /IP is ([\d.,]+)/ # save the network host - ips = Regexp.last_match(1).to_s.split(/,/) + ips = Regexp.last_match(1).to_s.split(',') session_id = @datastore['beefhook'] if !ips.nil? && !ips.empty? os = BeEF::Core::Models::BrowserDetails.get(session_id, 'host.os.name') diff --git a/modules/host/hook_default_browser/module.rb b/modules/host/hook_default_browser/module.rb index e544bbd8fa..1e63e52de1 100644 --- a/modules/host/hook_default_browser/module.rb +++ b/modules/host/hook_default_browser/module.rb @@ -31,7 +31,7 @@ def pre_send File.open('./modules/host/hook_default_browser/bounce_to_ie.pdf', 'r') do |original_hook_file| original_hook_file.each_line do |line| # If the line includes the hook token, then replace it with the actual hook URI - line = line.sub(//, hook_uri) if line.include? '' + line = line.sub('', hook_uri) if line.include? '' # write the line to a new file configured_hook_file.write(line) end diff --git a/modules/misc/wordpress/upload_rce_plugin/module.rb b/modules/misc/wordpress/upload_rce_plugin/module.rb index 5fdbcf27db..66fefaf647 100644 --- a/modules/misc/wordpress/upload_rce_plugin/module.rb +++ b/modules/misc/wordpress/upload_rce_plugin/module.rb @@ -23,7 +23,7 @@ def self.generate_zip_payload(auth_key) zio.put_next_entry('beefbind.php') file_content = File.read(File.join(File.dirname(__FILE__), 'beefbind.php')).to_s - file_content.gsub!(/#SHA1HASH#/, Digest::SHA1.hexdigest(auth_key)) + file_content.gsub!('#SHA1HASH#', Digest::SHA1.hexdigest(auth_key)) zio.write(file_content) end From 6f2659a97526b3dd485ce45238d7ed5d8c2f025a Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 09:59:40 +0530 Subject: [PATCH 39/85] rubocop --only Layout/EmptyLinesAroundMethodBody -a --- extensions/admin_ui/controllers/modules/modules.rb | 1 - extensions/notifications/notifications.rb | 1 - extensions/webrtc/api/hook.rb | 1 - extensions/webrtc/handlers.rb | 3 --- 4 files changed, 6 deletions(-) diff --git a/extensions/admin_ui/controllers/modules/modules.rb b/extensions/admin_ui/controllers/modules/modules.rb index 52dd9a2c73..9d79eba9ec 100644 --- a/extensions/admin_ui/controllers/modules/modules.rb +++ b/extensions/admin_ui/controllers/modules/modules.rb @@ -82,7 +82,6 @@ def set_command_module_status(mod) # @param category [Array] The category to add the leaf to # @param leaf [Hash] The leaf to add to the tree def update_command_module_tree_recurse(tree, category, leaf) - # get a single folder from the category array working_category = category.shift diff --git a/extensions/notifications/notifications.rb b/extensions/notifications/notifications.rb index d332c828f6..ca38d76eb9 100644 --- a/extensions/notifications/notifications.rb +++ b/extensions/notifications/notifications.rb @@ -37,7 +37,6 @@ def initialize(from, event, time_now, hb) BeEF::Extension::Notifications::Channels::SlackWorkspace.new(message) if @config.get('beef.extension.notifications.slack.enable') == true BeEF::Extension::Notifications::Channels::Ntfy.new(message) if @config.get('beef.extension.notifications.ntfy.enable') == true - end end end diff --git a/extensions/webrtc/api/hook.rb b/extensions/webrtc/api/hook.rb index 76aee4231e..7dde700652 100644 --- a/extensions/webrtc/api/hook.rb +++ b/extensions/webrtc/api/hook.rb @@ -70,7 +70,6 @@ def requester_run(hb, body) add_rtcmanagement_to_body o } unless rtcmanagementoutput.empty? end - end def add_rtcsignal_to_body(output) diff --git a/extensions/webrtc/handlers.rb b/extensions/webrtc/handlers.rb index 9af384678a..03c5c3139a 100644 --- a/extensions/webrtc/handlers.rb +++ b/extensions/webrtc/handlers.rb @@ -19,7 +19,6 @@ def initialize(data) end def setup - # validates the hook token beef_hook = @data['beefhook'] || nil (print_error 'beefhook is null';return) if beef_hook.nil? @@ -47,7 +46,6 @@ def setup signal: signal ) signal.save - end end @@ -152,7 +150,6 @@ def setup updated_at: Time.now) stat.save end - end end end From dedb90e6bf623bf769dc422f42a71b940d801e50 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 10:00:31 +0530 Subject: [PATCH 40/85] rubocop --only Layout/HeredocIndentation -a --- core/main/router/router.rb | 106 ++++++++++++++++++------------------- 1 file changed, 53 insertions(+), 53 deletions(-) diff --git a/core/main/router/router.rb b/core/main/router/router.rb index 6ce3ca06ef..34f6dfc4fb 100644 --- a/core/main/router/router.rb +++ b/core/main/router/router.rb @@ -269,61 +269,61 @@ def error_page_404 case config.get('beef.http.web_server_imitation.type') when 'apache' - <<-EOF - - -404 Not Found - -

Not Found

-

The requested URL was not found on this server.

-
-
Apache/2.2.3 (CentOS)
-#{("" if config.get('beef.http.web_server_imitation.hook_404'))} - -EOF + <<~EOF + + + 404 Not Found + +

Not Found

+

The requested URL was not found on this server.

+
+
Apache/2.2.3 (CentOS)
+ #{("" if config.get('beef.http.web_server_imitation.hook_404'))} + + EOF when 'iis' - <<-EOF - -The page cannot be found - -
-

The page cannot be found

-The page you are looking for might have been removed, had its name changed, or is temporarily unavailable. -
-

Please try the following:

-
    -
  • Make sure that the Web site address displayed in the address bar of your browser is spelled and formatted correctly.
  • -
  • If you reached this page by clicking a link, contact the Web site administrator to alert them that the link is incorrectly formatted.
  • -
  • Click the Back button to try another link.
  • -
-

HTTP Error 404 - File or directory not found.
Internet Information Services (IIS)

-
-

Technical Information (for support personnel)

-
    -
  • Go to Microsoft Product Support Services and perform a title search for the words HTTP and 404.
  • -
  • Open IIS Help, which is accessible in IIS Manager (inetmgr),and search for topics titled Web Site Setup, Common Administrative Tasks, and About Custom Error Messa -
-
-#{("" if config.get('beef.http.web_server_imitation.hook_404'))} - -EOF + <<~EOF + + The page cannot be found + +
+

The page cannot be found

+ The page you are looking for might have been removed, had its name changed, or is temporarily unavailable. +
+

Please try the following:

+
    +
  • Make sure that the Web site address displayed in the address bar of your browser is spelled and formatted correctly.
  • +
  • If you reached this page by clicking a link, contact the Web site administrator to alert them that the link is incorrectly formatted.
  • +
  • Click the Back button to try another link.
  • +
+

HTTP Error 404 - File or directory not found.
Internet Information Services (IIS)

+
+

Technical Information (for support personnel)

+
    +
  • Go to Microsoft Product Support Services and perform a title search for the words HTTP and 404.
  • +
  • Open IIS Help, which is accessible in IIS Manager (inetmgr),and search for topics titled Web Site Setup, Common Administrative Tasks, and About Custom Error Messa +
+
+ #{("" if config.get('beef.http.web_server_imitation.hook_404'))} + + EOF when 'nginx' - <<-EOF - -404 Not Found - -

404 Not Found

-
nginx
-#{("" if config.get('beef.http.web_server_imitation.hook_404'))} - - -EOF + <<~EOF + + 404 Not Found + +

404 Not Found

+
nginx
+ #{("" if config.get('beef.http.web_server_imitation.hook_404'))} + + + EOF else print_error 'Configuration error in beef.http.web_server_imitation.type!' print_more 'Supported values are: apache, iis, nginx.' From 876aa29340ea2d2cbaf98f3861a9eaadddd2e693 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 10:01:04 +0530 Subject: [PATCH 41/85] rubocop --only Style/ParenthesesAroundCondition -a --- core/main/autorun_engine/engine.rb | 2 +- extensions/requester/rest/requester.rb | 2 +- extensions/webrtc/handlers.rb | 10 +++++----- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/core/main/autorun_engine/engine.rb b/core/main/autorun_engine/engine.rb index 4a992343ec..aac492fc0d 100644 --- a/core/main/autorun_engine/engine.rb +++ b/core/main/autorun_engine/engine.rb @@ -135,7 +135,7 @@ def zombie_os_matches_rule?(os, os_version, rule) if !os_version.nil? || rule.os_version != 'ALL' os_major_version_match = compare_versions(os_ver_hook_maj.to_s, os_ver_rule_cond, os_ver_rule_maj.to_s) os_minor_version_match = compare_versions(os_ver_hook_min.to_s, os_ver_rule_cond, os_ver_rule_min.to_s) - return false unless (os_major_version_match && os_minor_version_match) + return false unless os_major_version_match && os_minor_version_match end true diff --git a/extensions/requester/rest/requester.rb b/extensions/requester/rest/requester.rb index a206adce0a..112fe023bf 100644 --- a/extensions/requester/rest/requester.rb +++ b/extensions/requester/rest/requester.rb @@ -230,7 +230,7 @@ def response2hash(http) response_data = '' unless http.response_data.nil? - if (http.response_data.length > (1024 * 100)) # more than 100K + if http.response_data.length > (1024 * 100) # more than 100K response_data = http.response_data[0..(1024 * 100)] response_data += "\n<---------- Response Data Truncated---------->" else diff --git a/extensions/webrtc/handlers.rb b/extensions/webrtc/handlers.rb index 03c5c3139a..a84fea0be3 100644 --- a/extensions/webrtc/handlers.rb +++ b/extensions/webrtc/handlers.rb @@ -86,7 +86,7 @@ def setup # Perform logic depending on message (updating database) puts "message = '#{message}'" - if (message == 'ICE Status: connected') + if message == 'ICE Status: connected' # Find existing status message stat = BeEF::Core::Models::Rtcstatus.first(hooked_browser_id: zombie_db.id, target_hooked_browser_id: peer_zombie_db.id) || nil unless stat.nil? @@ -100,7 +100,7 @@ def setup stat2.updated_at = Time.now stat2.save end - elsif (message.end_with?('disconnected')) + elsif message.end_with?('disconnected') stat = BeEF::Core::Models::Rtcstatus.first(hooked_browser_id: zombie_db.id, target_hooked_browser_id: peer_zombie_db.id) || nil unless stat.nil? stat.status = 'Disconnected' @@ -113,7 +113,7 @@ def setup stat2.updated_at = Time.now stat2.save end - elsif (message == 'Stayin alive') + elsif message == 'Stayin alive' stat = BeEF::Core::Models::Rtcstatus.first(hooked_browser_id: zombie_db.id, target_hooked_browser_id: peer_zombie_db.id) || nil unless stat.nil? stat.status = 'Stealthed!!' @@ -126,7 +126,7 @@ def setup stat2.updated_at = Time.now stat2.save end - elsif (message == 'Coming out of stealth...') + elsif message == 'Coming out of stealth...' stat = BeEF::Core::Models::Rtcstatus.first(hooked_browser_id: zombie_db.id, target_hooked_browser_id: peer_zombie_db.id) || nil unless stat.nil? stat.status = 'Connected' @@ -139,7 +139,7 @@ def setup stat2.updated_at = Time.now stat2.save end - elsif (message.start_with?('execcmd')) + elsif message.start_with?('execcmd') mod = %r{\(/command/(.*)\.js\)}.match(message)[1] resp = /Result:.(.*)/.match(message)[1] stat = BeEF::Core::Models::Rtcmodulestatus.new(hooked_browser_id: zombie_db.id, From d97c9a4253f78bb6b47c0f4cc086bdecec3209be Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 10:01:33 +0530 Subject: [PATCH 42/85] rubocop --only Layout/SpaceAfterSemicolon -a --- extensions/webrtc/handlers.rb | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/extensions/webrtc/handlers.rb b/extensions/webrtc/handlers.rb index a84fea0be3..855d95f00f 100644 --- a/extensions/webrtc/handlers.rb +++ b/extensions/webrtc/handlers.rb @@ -21,23 +21,23 @@ def initialize(data) def setup # validates the hook token beef_hook = @data['beefhook'] || nil - (print_error 'beefhook is null';return) if beef_hook.nil? + (print_error 'beefhook is null'; return) if beef_hook.nil? # validates the target hook token target_beef_id = @data['results']['targetbeefid'] || nil - (print_error 'targetbeefid is null';return) if target_beef_id.nil? + (print_error 'targetbeefid is null'; return) if target_beef_id.nil? # validates the signal signal = @data['results']['signal'] || nil - (print_error 'Signal is null';return) if signal.nil? + (print_error 'Signal is null'; return) if signal.nil? # validates that a hooked browser with the beef_hook token exists in the db zombie_db = Z.first(session: beef_hook) || nil - (print_error 'Invalid beefhook id: the hooked browser cannot be found in the database';return) if zombie_db.nil? + (print_error 'Invalid beefhook id: the hooked browser cannot be found in the database'; return) if zombie_db.nil? # validates that a target browser with the target_beef_token exists in the db target_zombie_db = Z.first(id: target_beef_id) || nil - (print_error 'Invalid targetbeefid: the target hooked browser cannot be found in the database';return) if target_zombie_db.nil? + (print_error 'Invalid targetbeefid: the target hooked browser cannot be found in the database'; return) if target_zombie_db.nil? # save the results in the database signal = R.new( @@ -63,23 +63,23 @@ def initialize(data) def setup # validates the hook token beef_hook = @data['beefhook'] || nil - (print_error 'beefhook is null';return) if beef_hook.nil? + (print_error 'beefhook is null'; return) if beef_hook.nil? # validates the target hook token peer_id = @data['results']['peerid'] || nil - (print_error 'peerid is null';return) if peer_id.nil? + (print_error 'peerid is null'; return) if peer_id.nil? # validates the message message = @data['results']['message'] || nil - (print_error 'Message is null';return) if message.nil? + (print_error 'Message is null'; return) if message.nil? # validates that a hooked browser with the beef_hook token exists in the db zombie_db = Z.first(session: beef_hook) || nil - (print_error 'Invalid beefhook id: the hooked browser cannot be found in the database';return) if zombie_db.nil? + (print_error 'Invalid beefhook id: the hooked browser cannot be found in the database'; return) if zombie_db.nil? # validates that a browser with the peerid exists in the db peer_zombie_db = Z.first(id: peer_id) || nil - (print_error 'Invalid peer_id: the peer hooked browser cannot be found in the database';return) if peer_zombie_db.nil? + (print_error 'Invalid peer_id: the peer hooked browser cannot be found in the database'; return) if peer_zombie_db.nil? # Writes the event into the BeEF Logger BeEF::Core::Logger.instance.register('WebRTC', "Browser:#{zombie_db.id} received message from Browser:#{peer_zombie_db.id}: #{message}") From 9755f84298f15ae2395c0e06aff885cf1f43fbd4 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 10:02:11 +0530 Subject: [PATCH 43/85] rubocop --only Lint/UnusedMethodArgument -a --- extensions/webrtc/api.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/webrtc/api.rb b/extensions/webrtc/api.rb index 780f81a8bc..9efc8cb32e 100644 --- a/extensions/webrtc/api.rb +++ b/extensions/webrtc/api.rb @@ -25,7 +25,7 @@ module RegisterPreHookCallback # We register this pre hook action to ensure that signals going to a browser are included back in the hook.js polling # This is also used so that BeEF can send RTCManagement messages to the hooked browser too - def self.pre_hook_send(hooked_browser, body, params, request, response) + def self.pre_hook_send(hooked_browser, body, _params, _request, _response) dhook = BeEF::Extension::WebRTC::API::Hook.new dhook.requester_run(hooked_browser, body) end From b81c7360f771aa10bd591be39e50606a26b3a3e1 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 10:02:37 +0530 Subject: [PATCH 44/85] rubocop --only Layout/SpaceInsideBlockBraces -a --- extensions/webrtc/api/hook.rb | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/extensions/webrtc/api/hook.rb b/extensions/webrtc/api/hook.rb index 7dde700652..6bcc55bd21 100644 --- a/extensions/webrtc/api/hook.rb +++ b/extensions/webrtc/api/hook.rb @@ -35,7 +35,7 @@ def requester_run(hb, body) } # Get all RTCManagement messages for this browser - BeEF::Core::Models::RtcManage.where(hooked_browser_id: hb.id, has_sent: 'waiting').each {|h| + BeEF::Core::Models::RtcManage.where(hooked_browser_id: hb.id, has_sent: 'waiting').each { |h| rtcmanagementoutput << h.message h.has_sent = 'sent' h.save @@ -53,20 +53,20 @@ def requester_run(hb, body) # Hopefully this still works if config.get('beef.http.websocket.enable') && ws.getsocket(hb.session) - rtcsignaloutput.each {|o| + rtcsignaloutput.each { |o| add_rtcsignal_to_body o } unless rtcsignaloutput.empty? - rtcmanagementoutput.each {|o| + rtcmanagementoutput.each { |o| add_rtcmanagement_to_body o } unless rtcmanagementoutput.empty? # ws.send(content + @body,hb.session) ws.send(@body,hb.session) #if we use WebSockets, just reply wih the component contents else # if we use XHR-polling, add the component to the main hook file - rtcsignaloutput.each {|o| + rtcsignaloutput.each { |o| add_rtcsignal_to_body o } unless rtcsignaloutput.empty? - rtcmanagementoutput.each {|o| + rtcmanagementoutput.each { |o| add_rtcmanagement_to_body o } unless rtcmanagementoutput.empty? end From d9257777d77755d9d14d61b6224c2620748132e1 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 10:03:30 +0530 Subject: [PATCH 45/85] rubocop --only Style/RedundantParentheses -a --- core/api.rb | 2 +- core/main/handlers/browserdetails.rb | 2 +- core/main/handlers/modules/beefjs.rb | 10 +++++----- core/main/handlers/modules/command.rb | 2 +- core/main/handlers/modules/legacybeefjs.rb | 10 +++++----- core/main/handlers/modules/multistagebeefjs.rb | 10 +++++----- .../network_stack/handlers/dynamicreconstruction.rb | 2 +- core/main/network_stack/websocket/websocket.rb | 2 +- core/main/rest/handlers/autorun_engine.rb | 2 +- core/main/rest/handlers/hookedbrowsers.rb | 8 ++++---- core/main/router/router.rb | 6 +++--- core/module.rb | 4 ++-- extensions/admin_ui/api/handler.rb | 2 +- extensions/customhook/handler.rb | 2 +- extensions/webrtc/rest/webrtc.rb | 2 +- modules/host/get_wireless_keys/module.rb | 2 +- modules/misc/wordpress/upload_rce_plugin/module.rb | 2 +- 17 files changed, 35 insertions(+), 35 deletions(-) diff --git a/core/api.rb b/core/api.rb index 0e4531aace..fef16324d0 100644 --- a/core/api.rb +++ b/core/api.rb @@ -132,7 +132,7 @@ def get_owners(clss, method, params = []) # @param [String] mthd the target method to verify # def verify_api_path(clss, mthd) - (clss.const_defined?('API_PATHS') && clss.const_get('API_PATHS').key?(mthd)) + clss.const_defined?('API_PATHS') && clss.const_get('API_PATHS').key?(mthd) end # diff --git a/core/main/handlers/browserdetails.rb b/core/main/handlers/browserdetails.rb index b5d866ee5b..3c347ea343 100644 --- a/core/main/handlers/browserdetails.rb +++ b/core/main/handlers/browserdetails.rb @@ -242,7 +242,7 @@ def setup X_FORWARDED X_FORWARDED_FOR ].each do |header| - proxy_clients << (JSON.parse(zombie.httpheaders)[header]).to_s unless JSON.parse(zombie.httpheaders)[header].nil? + proxy_clients << JSON.parse(zombie.httpheaders)[header].to_s unless JSON.parse(zombie.httpheaders)[header].nil? end # retrieve proxy server diff --git a/core/main/handlers/modules/beefjs.rb b/core/main/handlers/modules/beefjs.rb index aaf8de6b34..c381fa91c1 100644 --- a/core/main/handlers/modules/beefjs.rb +++ b/core/main/handlers/modules/beefjs.rb @@ -46,22 +46,22 @@ def build_beefjs!(req_host) print_debug "Excluding #{ext_js_sub_file} from core files obfuscation list" # do not obfuscate the file ext_js_sub_file_path = beef_js_path + ext_js_sub_file - ext_js_to_not_obfuscate << ("#{File.read(ext_js_sub_file_path)}\n\n") + ext_js_to_not_obfuscate << "#{File.read(ext_js_sub_file_path)}\n\n" else ext_js_sub_file_path = beef_js_path + ext_js_sub_file - ext_js_to_obfuscate << ("#{File.read(ext_js_sub_file_path)}\n\n") + ext_js_to_obfuscate << "#{File.read(ext_js_sub_file_path)}\n\n" end else # Evasion is not enabled, do not obfuscate anything ext_js_sub_file_path = beef_js_path + ext_js_sub_file - ext_js_to_not_obfuscate << ("#{File.read(ext_js_sub_file_path)}\n\n") + ext_js_to_not_obfuscate << "#{File.read(ext_js_sub_file_path)}\n\n" end end # @note construct the beef_js string from file(s) beef_js_sub_files.each do |beef_js_sub_file| beef_js_sub_file_path = beef_js_path + beef_js_sub_file - beef_js << ("#{File.read(beef_js_sub_file_path)}\n\n") + beef_js << "#{File.read(beef_js_sub_file_path)}\n\n" end # @note create the config for the hooked browser session @@ -154,7 +154,7 @@ def build_missing_beefjs_components(beefjs_components) evasion = BeEF::Extension::Evasion::Evasion.instance @body << evasion.obfuscate("#{File.read(component_path)}\n\n") else - @body << ("#{File.read(component_path)}\n\n") + @body << "#{File.read(component_path)}\n\n" end # @note finally we add the component to the list of components already generated so it does not get generated numerous times. diff --git a/core/main/handlers/modules/command.rb b/core/main/handlers/modules/command.rb index 55a15b4cdb..47deee9e20 100644 --- a/core/main/handlers/modules/command.rb +++ b/core/main/handlers/modules/command.rb @@ -79,7 +79,7 @@ def add_command_instructions(command, hooked_browser) # //', "") ws.send(@output, hooked_browser.session) else - @body << ("#{@output}\n\n") + @body << "#{@output}\n\n" end # @note prints the event to the console if BeEF::Settings.console? diff --git a/core/main/handlers/modules/legacybeefjs.rb b/core/main/handlers/modules/legacybeefjs.rb index d4cda88fdf..8e0f908fe0 100644 --- a/core/main/handlers/modules/legacybeefjs.rb +++ b/core/main/handlers/modules/legacybeefjs.rb @@ -46,22 +46,22 @@ def legacy_build_beefjs!(req_host) print_debug "Excluding #{ext_js_sub_file} from core files obfuscation list" # do not obfuscate the file ext_js_sub_file_path = beef_js_path + ext_js_sub_file - ext_js_to_not_obfuscate << ("#{File.read(ext_js_sub_file_path)}\n\n") + ext_js_to_not_obfuscate << "#{File.read(ext_js_sub_file_path)}\n\n" else ext_js_sub_file_path = beef_js_path + ext_js_sub_file - ext_js_to_obfuscate << ("#{File.read(ext_js_sub_file_path)}\n\n") + ext_js_to_obfuscate << "#{File.read(ext_js_sub_file_path)}\n\n" end else # Evasion is not enabled, do not obfuscate anything ext_js_sub_file_path = beef_js_path + ext_js_sub_file - ext_js_to_not_obfuscate << ("#{File.read(ext_js_sub_file_path)}\n\n") + ext_js_to_not_obfuscate << "#{File.read(ext_js_sub_file_path)}\n\n" end end # @note construct the beef_js string from file(s) beef_js_sub_files.each do |beef_js_sub_file| beef_js_sub_file_path = beef_js_path + beef_js_sub_file - beef_js << ("#{File.read(beef_js_sub_file_path)}\n\n") + beef_js << "#{File.read(beef_js_sub_file_path)}\n\n" end # @note create the config for the hooked browser session @@ -154,7 +154,7 @@ def legacy_build_missing_beefjs_components(beefjs_components) evasion = BeEF::Extension::Evasion::Evasion.instance @body << evasion.obfuscate("#{File.read(component_path)}\n\n") else - @body << ("#{File.read(component_path)}\n\n") + @body << "#{File.read(component_path)}\n\n" end # @note finally we add the component to the list of components already generated so it does not get generated numerous times. diff --git a/core/main/handlers/modules/multistagebeefjs.rb b/core/main/handlers/modules/multistagebeefjs.rb index 2797b37446..3c71f434e6 100644 --- a/core/main/handlers/modules/multistagebeefjs.rb +++ b/core/main/handlers/modules/multistagebeefjs.rb @@ -46,22 +46,22 @@ def multi_stage_beefjs!(req_host) print_debug "Excluding #{ext_js_sub_file} from core files obfuscation list" # do not obfuscate the file ext_js_sub_file_path = beef_js_path + ext_js_sub_file - ext_js_to_not_obfuscate << ("#{File.read(ext_js_sub_file_path)}\n\n") + ext_js_to_not_obfuscate << "#{File.read(ext_js_sub_file_path)}\n\n" else ext_js_sub_file_path = beef_js_path + ext_js_sub_file - ext_js_to_obfuscate << ("#{File.read(ext_js_sub_file_path)}\n\n") + ext_js_to_obfuscate << "#{File.read(ext_js_sub_file_path)}\n\n" end else # Evasion is not enabled, do not obfuscate anything ext_js_sub_file_path = beef_js_path + ext_js_sub_file - ext_js_to_not_obfuscate << ("#{File.read(ext_js_sub_file_path)}\n\n") + ext_js_to_not_obfuscate << "#{File.read(ext_js_sub_file_path)}\n\n" end end # @note construct the beef_js string from file(s) beef_js_sub_files.each do |beef_js_sub_file| beef_js_sub_file_path = beef_js_path + beef_js_sub_file - beef_js << ("#{File.read(beef_js_sub_file_path)}\n\n") + beef_js << "#{File.read(beef_js_sub_file_path)}\n\n" end # @note create the config for the hooked browser session @@ -154,7 +154,7 @@ def legacy_build_missing_beefjs_components(beefjs_components) evasion = BeEF::Extension::Evasion::Evasion.instance @body << evasion.obfuscate("#{File.read(component_path)}\n\n") else - @body << ("#{File.read(component_path)}\n\n") + @body << "#{File.read(component_path)}\n\n" end # @note finally we add the component to the list of components already generated so it does not get generated numerous times. diff --git a/core/main/network_stack/handlers/dynamicreconstruction.rb b/core/main/network_stack/handlers/dynamicreconstruction.rb index d74c621c8f..d4156936b0 100644 --- a/core/main/network_stack/handlers/dynamicreconstruction.rb +++ b/core/main/network_stack/handlers/dynamicreconstruction.rb @@ -53,7 +53,7 @@ def check_packets PQ.each do |packet| next if checked.include?("#{packet[:beefhook]}:#{String(packet[:stream_id])}") - checked << ("#{packet[:beefhook]}:#{String(packet[:stream_id])}") + checked << "#{packet[:beefhook]}:#{String(packet[:stream_id])}" pc = 0 PQ.each do |p| pc += 1 if packet[:beefhook] == p[:beefhook] and packet[:stream_id] == p[:stream_id] diff --git a/core/main/network_stack/websocket/websocket.rb b/core/main/network_stack/websocket/websocket.rb index 31fed5b2c3..7425ef1382 100644 --- a/core/main/network_stack/websocket/websocket.rb +++ b/core/main/network_stack/websocket/websocket.rb @@ -101,7 +101,7 @@ def start_websocket_server(ws_options) unless msg_hash['cookie'].nil? print_debug('[WebSocket] Browser says hello! WebSocket is running') # insert new connection in activesocket - @@activeSocket[(msg_hash['cookie']).to_s] = ws + @@activeSocket[msg_hash['cookie'].to_s] = ws print_debug("[WebSocket] activeSocket content [#{@@activeSocket}]") hb_session = msg_hash['cookie'] diff --git a/core/main/rest/handlers/autorun_engine.rb b/core/main/rest/handlers/autorun_engine.rb index b30026f548..6b7ad31bc2 100644 --- a/core/main/rest/handlers/autorun_engine.rb +++ b/core/main/rest/handlers/autorun_engine.rb @@ -113,7 +113,7 @@ class AutorunEngine < BeEF::Core::Router::Router get '/run/:rule_id' do rule_id = params[:rule_id] - online_hooks = BeEF::Core::Models::HookedBrowser.where('lastseen >= ?', (Time.new.to_i - 15)) + online_hooks = BeEF::Core::Models::HookedBrowser.where('lastseen >= ?', Time.new.to_i - 15) if online_hooks.nil? return { 'success' => false, 'error' => 'There are currently no hooked browsers online.' }.to_json diff --git a/core/main/rest/handlers/hookedbrowsers.rb b/core/main/rest/handlers/hookedbrowsers.rb index 0b504099a8..c361d04201 100644 --- a/core/main/rest/handlers/hookedbrowsers.rb +++ b/core/main/rest/handlers/hookedbrowsers.rb @@ -25,14 +25,14 @@ class HookedBrowsers < BeEF::Core::Router::Router # get '/' do if config.get('beef.http.websocket.enable') == false - online_hooks = hb_to_json(BeEF::Core::Models::HookedBrowser.where('lastseen >= ?', (Time.new.to_i - 15))) - offline_hooks = hb_to_json(BeEF::Core::Models::HookedBrowser.where('lastseen <= ?', (Time.new.to_i - 15))) + online_hooks = hb_to_json(BeEF::Core::Models::HookedBrowser.where('lastseen >= ?', Time.new.to_i - 15)) + offline_hooks = hb_to_json(BeEF::Core::Models::HookedBrowser.where('lastseen <= ?', Time.new.to_i - 15)) # If we're using websockets use the designated threshold timeout to determine live, instead of hardcoded 15 # Why is it hardcoded 15? else timeout = config.get('beef.http.websocket.ws_poll_timeout') - online_hooks = hb_to_json(BeEF::Core::Models::HookedBrowser.where('lastseen >= ?', (Time.new.to_i - timeout))) - offline_hooks = hb_to_json(BeEF::Core::Models::HookedBrowser.where('lastseen <= ?', (Time.new.to_i - timeout))) + online_hooks = hb_to_json(BeEF::Core::Models::HookedBrowser.where('lastseen >= ?', Time.new.to_i - timeout)) + offline_hooks = hb_to_json(BeEF::Core::Models::HookedBrowser.where('lastseen <= ?', Time.new.to_i - timeout)) end output = { diff --git a/core/main/router/router.rb b/core/main/router/router.rb index 34f6dfc4fb..62463e08d3 100644 --- a/core/main/router/router.rb +++ b/core/main/router/router.rb @@ -278,7 +278,7 @@ def error_page_404

The requested URL was not found on this server.


Apache/2.2.3 (CentOS)
- #{("" if config.get('beef.http.web_server_imitation.hook_404'))} + #{"" if config.get('beef.http.web_server_imitation.hook_404')} EOF when 'iis' @@ -310,7 +310,7 @@ def error_page_404
  • Open IIS Help, which is accessible in IIS Manager (inetmgr),and search for topics titled Web Site Setup, Common Administrative Tasks, and About Custom Error Messa - #{("" if config.get('beef.http.web_server_imitation.hook_404'))} + #{"" if config.get('beef.http.web_server_imitation.hook_404')} EOF when 'nginx' @@ -320,7 +320,7 @@ def error_page_404

    404 Not Found


    nginx
    - #{("" if config.get('beef.http.web_server_imitation.hook_404'))} + #{"" if config.get('beef.http.web_server_imitation.hook_404')} EOF diff --git a/core/module.rb b/core/module.rb index 320b18b061..c96552c30b 100644 --- a/core/module.rb +++ b/core/module.rb @@ -16,14 +16,14 @@ def self.is_present(mod) # @param [String] mod module key # @return [Boolean] if the module key is enabled in BeEF's configuration def self.is_enabled(mod) - (is_present(mod) && BeEF::Core::Configuration.instance.get("beef.module.#{mod}.enable") == true) + is_present(mod) && BeEF::Core::Configuration.instance.get("beef.module.#{mod}.enable") == true end # Checks to see if the module reports that it has loaded through the configuration # @param [String] mod module key # @return [Boolean] if the module key is loaded in BeEF's configuration def self.is_loaded(mod) - (is_enabled(mod) && BeEF::Core::Configuration.instance.get("beef.module.#{mod}.loaded") == true) + is_enabled(mod) && BeEF::Core::Configuration.instance.get("beef.module.#{mod}.loaded") == true end # Returns module class definition diff --git a/extensions/admin_ui/api/handler.rb b/extensions/admin_ui/api/handler.rb index 11e03d654f..c025bf24b1 100644 --- a/extensions/admin_ui/api/handler.rb +++ b/extensions/admin_ui/api/handler.rb @@ -100,7 +100,7 @@ def self.build_javascript_ui admin_ui_js = '' global_js.each do |file_name| - admin_ui_js << ("#{File.binread("#{File.dirname(__FILE__)}/../media/javascript/#{file_name}")}\n\n") + admin_ui_js << "#{File.binread("#{File.dirname(__FILE__)}/../media/javascript/#{file_name}")}\n\n" end config = BeEF::Core::Configuration.instance diff --git a/extensions/customhook/handler.rb b/extensions/customhook/handler.rb index 7803da54bc..8fed2e4a2c 100644 --- a/extensions/customhook/handler.rb +++ b/extensions/customhook/handler.rb @@ -16,7 +16,7 @@ def call(env) eruby = Erubis::FastEruby.new(File.read("#{File.dirname(__FILE__)}/html/index.html")) config.get('beef.extension.customhook.hooks').each do |h| path = config.get("beef.extension.customhook.hooks.#{h.first}.path") - next unless path == (env['REQUEST_URI']).to_s + next unless path == env['REQUEST_URI'].to_s print_info "[Custom Hook] Handling request for custom hook mounted at '#{path}'" @body << eruby.evaluate({ diff --git a/extensions/webrtc/rest/webrtc.rb b/extensions/webrtc/rest/webrtc.rb index 86062041df..6bb564bb10 100644 --- a/extensions/webrtc/rest/webrtc.rb +++ b/extensions/webrtc/rest/webrtc.rb @@ -84,7 +84,7 @@ class WebRTCRest < BeEF::Core::Router::Router return result.to_json end - if verbose.to_s =~ (/^(true|t|yes|y|1)$/i) + if verbose.to_s =~ /^(true|t|yes|y|1)$/i BeEF::Core::Models::RtcManage.initiate(fromhb.to_i, tohb.to_i, true) else BeEF::Core::Models::RtcManage.initiate(fromhb.to_i, tohb.to_i) diff --git a/modules/host/get_wireless_keys/module.rb b/modules/host/get_wireless_keys/module.rb index 30d415675e..1eca1e897c 100644 --- a/modules/host/get_wireless_keys/module.rb +++ b/modules/host/get_wireless_keys/module.rb @@ -14,7 +14,7 @@ def post_execute save content filename = "#{$home_dir}/exported_wlan_profiles_#{ip}_-_#{timestamp}_#{@datastore['cid']}.xml" f = File.open(filename, 'w+') - f.write((@datastore['results']).sub('result=', '')) + f.write(@datastore['results'].sub('result=', '')) writeToResults = {} writeToResults['data'] = "Please import #{filename} into your windows machine" BeEF::Core::Models::Command.save_result(@datastore['beefhook'], @datastore['cid'], @friendlyname, writeToResults, 0) diff --git a/modules/misc/wordpress/upload_rce_plugin/module.rb b/modules/misc/wordpress/upload_rce_plugin/module.rb index 66fefaf647..ca48cb79bf 100644 --- a/modules/misc/wordpress/upload_rce_plugin/module.rb +++ b/modules/misc/wordpress/upload_rce_plugin/module.rb @@ -35,7 +35,7 @@ def self.generate_zip_payload(auth_key) # Escape payload to be able to put it in the JS payload.each_byte do |byte| - escaped_payload << ("\\#{'x%02X' % byte}") + escaped_payload << "\\#{'x%02X' % byte}" end escaped_payload From cdc862117bd71177b99e6ea85f5e2c85ede0aeb0 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:27:51 +0530 Subject: [PATCH 46/85] Disable Style/CommentAnnotation cop --- .rubocop.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.rubocop.yml b/.rubocop.yml index fd9c132bba..9dfa276a23 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -39,6 +39,9 @@ Metrics/PerceivedComplexity: Naming/ClassAndModuleCamelCase: Enabled: false +Style/CommentAnnotation: + Enabled: false + Style/Documentation: Enabled: false From 535874692d2525637248ce24c0929c2cac258d7e Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:28:52 +0530 Subject: [PATCH 47/85] rubocop --only Style/MultilineIfModifier -a --- extensions/webrtc/api/hook.rb | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/extensions/webrtc/api/hook.rb b/extensions/webrtc/api/hook.rb index 6bcc55bd21..637c40c59a 100644 --- a/extensions/webrtc/api/hook.rb +++ b/extensions/webrtc/api/hook.rb @@ -53,22 +53,30 @@ def requester_run(hb, body) # Hopefully this still works if config.get('beef.http.websocket.enable') && ws.getsocket(hb.session) - rtcsignaloutput.each { |o| - add_rtcsignal_to_body o - } unless rtcsignaloutput.empty? - rtcmanagementoutput.each { |o| - add_rtcmanagement_to_body o - } unless rtcmanagementoutput.empty? + unless rtcsignaloutput.empty? + rtcsignaloutput.each { |o| + add_rtcsignal_to_body o + } + end + unless rtcmanagementoutput.empty? + rtcmanagementoutput.each { |o| + add_rtcmanagement_to_body o + } + end # ws.send(content + @body,hb.session) ws.send(@body,hb.session) #if we use WebSockets, just reply wih the component contents else # if we use XHR-polling, add the component to the main hook file - rtcsignaloutput.each { |o| - add_rtcsignal_to_body o - } unless rtcsignaloutput.empty? - rtcmanagementoutput.each { |o| - add_rtcmanagement_to_body o - } unless rtcmanagementoutput.empty? + unless rtcsignaloutput.empty? + rtcsignaloutput.each { |o| + add_rtcsignal_to_body o + } + end + unless rtcmanagementoutput.empty? + rtcmanagementoutput.each { |o| + add_rtcmanagement_to_body o + } + end end end From b31d0d91c7692dfe4195d6ab5e3dc29bfb8c9d8f Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:30:19 +0530 Subject: [PATCH 48/85] rubocop --only Style/Semicolon -a --- Rakefile | 8 ++++---- extensions/webrtc/handlers.rb | 30 ++++++++++++++++++++---------- 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/Rakefile b/Rakefile index 9a11e62098..4e89d160fd 100644 --- a/Rakefile +++ b/Rakefile @@ -98,7 +98,7 @@ end ################################ # X11 set up -@xserver_process_id = nil; +@xserver_process_id = nil task :xserver_start do printf 'Starting X11 Server (wait 10 seconds)...' @@ -119,8 +119,8 @@ end ################################ # BeEF environment set up -@beef_process_id = nil; -@beef_config_file = 'tmp/rk_beef_conf.yaml'; +@beef_process_id = nil +@beef_config_file = 'tmp/rk_beef_conf.yaml' task beef_start: 'beef' do # read environment param for creds or use bad_fred @@ -165,7 +165,7 @@ end ################################ # MSF environment set up -@msf_process_id = nil; +@msf_process_id = nil task msf_start: '/tmp/msf-test/msfconsole' do printf 'Starting MSF (wait 45 seconds)...' diff --git a/extensions/webrtc/handlers.rb b/extensions/webrtc/handlers.rb index 855d95f00f..bd8e217667 100644 --- a/extensions/webrtc/handlers.rb +++ b/extensions/webrtc/handlers.rb @@ -21,23 +21,28 @@ def initialize(data) def setup # validates the hook token beef_hook = @data['beefhook'] || nil - (print_error 'beefhook is null'; return) if beef_hook.nil? + (print_error 'beefhook is null' + return) if beef_hook.nil? # validates the target hook token target_beef_id = @data['results']['targetbeefid'] || nil - (print_error 'targetbeefid is null'; return) if target_beef_id.nil? + (print_error 'targetbeefid is null' + return) if target_beef_id.nil? # validates the signal signal = @data['results']['signal'] || nil - (print_error 'Signal is null'; return) if signal.nil? + (print_error 'Signal is null' + return) if signal.nil? # validates that a hooked browser with the beef_hook token exists in the db zombie_db = Z.first(session: beef_hook) || nil - (print_error 'Invalid beefhook id: the hooked browser cannot be found in the database'; return) if zombie_db.nil? + (print_error 'Invalid beefhook id: the hooked browser cannot be found in the database' + return) if zombie_db.nil? # validates that a target browser with the target_beef_token exists in the db target_zombie_db = Z.first(id: target_beef_id) || nil - (print_error 'Invalid targetbeefid: the target hooked browser cannot be found in the database'; return) if target_zombie_db.nil? + (print_error 'Invalid targetbeefid: the target hooked browser cannot be found in the database' + return) if target_zombie_db.nil? # save the results in the database signal = R.new( @@ -63,23 +68,28 @@ def initialize(data) def setup # validates the hook token beef_hook = @data['beefhook'] || nil - (print_error 'beefhook is null'; return) if beef_hook.nil? + (print_error 'beefhook is null' + return) if beef_hook.nil? # validates the target hook token peer_id = @data['results']['peerid'] || nil - (print_error 'peerid is null'; return) if peer_id.nil? + (print_error 'peerid is null' + return) if peer_id.nil? # validates the message message = @data['results']['message'] || nil - (print_error 'Message is null'; return) if message.nil? + (print_error 'Message is null' + return) if message.nil? # validates that a hooked browser with the beef_hook token exists in the db zombie_db = Z.first(session: beef_hook) || nil - (print_error 'Invalid beefhook id: the hooked browser cannot be found in the database'; return) if zombie_db.nil? + (print_error 'Invalid beefhook id: the hooked browser cannot be found in the database' + return) if zombie_db.nil? # validates that a browser with the peerid exists in the db peer_zombie_db = Z.first(id: peer_id) || nil - (print_error 'Invalid peer_id: the peer hooked browser cannot be found in the database'; return) if peer_zombie_db.nil? + (print_error 'Invalid peer_id: the peer hooked browser cannot be found in the database' + return) if peer_zombie_db.nil? # Writes the event into the BeEF Logger BeEF::Core::Logger.instance.register('WebRTC', "Browser:#{zombie_db.id} received message from Browser:#{peer_zombie_db.id}: #{message}") From d395e85e7d7ee0e1cd7fb92cfb2a4219de9df05a Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:30:55 +0530 Subject: [PATCH 49/85] rubocop --only Style/ColonMethodCall -a --- beef | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beef b/beef index 9e8f956e12..02e14c8093 100755 --- a/beef +++ b/beef @@ -250,7 +250,7 @@ BeEF::Core::Console::Banners.print_dns # # @note Prints the API key needed to use the RESTful API # -print_info "RESTful API key: #{BeEF::Core::Crypto::api_token}" +print_info "RESTful API key: #{BeEF::Core::Crypto.api_token}" # # @note Load the GeoIP database From cf8fb2391cbb3cdd329545234503aba30b8a447c Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:31:25 +0530 Subject: [PATCH 50/85] rubocop --only Layout/FirstHashElementIndentation -a --- extensions/admin_ui/controllers/modules/modules.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/admin_ui/controllers/modules/modules.rb b/extensions/admin_ui/controllers/modules/modules.rb index 9d79eba9ec..cac1fc3419 100644 --- a/extensions/admin_ui/controllers/modules/modules.rb +++ b/extensions/admin_ui/controllers/modules/modules.rb @@ -306,11 +306,11 @@ def select_command_module_commands C.where(command_module_id: command_module_id, hooked_browser_id: zombie_id).each do |command| commands.push({ - 'id' => i, + 'id' => i, 'object_id' => command.id, 'creationdate' => Time.at(command.creationdate.to_i).strftime('%Y-%m-%d %H:%M').to_s, 'label' => command.label - }) + }) i += 1 end From cdb127ca27fb04bbf508d79495f6341326ed5b39 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:31:59 +0530 Subject: [PATCH 51/85] rubocop --only Style/Dir -a --- beef | 2 +- extensions/demos/handler.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/beef b/beef index 02e14c8093..b6c3b81980 100755 --- a/beef +++ b/beef @@ -35,7 +35,7 @@ end # # @note set load path, application root directory and user preferences directory # -$root_dir = File.join(File.expand_path(File.dirname(File.realpath(__FILE__))), '.') +$root_dir = File.join(File.expand_path(__dir__), '.') $:.unshift($root_dir) $home_dir = File.expand_path("#{Dir.home}/.beef/", __FILE__).freeze diff --git a/extensions/demos/handler.rb b/extensions/demos/handler.rb index 0106f65194..41fae2df8e 100644 --- a/extensions/demos/handler.rb +++ b/extensions/demos/handler.rb @@ -7,7 +7,7 @@ module BeEF module Extension module Demos class Handler < BeEF::Core::Router::Router - set :public_folder, "#{File.expand_path(File.dirname(__FILE__))}/html/" + set :public_folder, "#{__dir__}/html/" end end end From 4562a196b66e35ecd36b477442aa5a50359fd476 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:32:30 +0530 Subject: [PATCH 52/85] rubocop --only Layout/EmptyLines -a --- extensions/webrtc/models/rtcmodulestatus.rb | 1 - extensions/webrtc/models/rtcstatus.rb | 1 - 2 files changed, 2 deletions(-) diff --git a/extensions/webrtc/models/rtcmodulestatus.rb b/extensions/webrtc/models/rtcmodulestatus.rb index b9a57dd615..c9feb23e2b 100644 --- a/extensions/webrtc/models/rtcmodulestatus.rb +++ b/extensions/webrtc/models/rtcmodulestatus.rb @@ -12,7 +12,6 @@ module Models # This includes things like connection status, and executed modules etc # - class Rtcmodulestatus < BeEF::Core::Model belongs_to :hooked_browser belongs_to :command_module diff --git a/extensions/webrtc/models/rtcstatus.rb b/extensions/webrtc/models/rtcstatus.rb index 034018a0e5..8413c4b5a1 100644 --- a/extensions/webrtc/models/rtcstatus.rb +++ b/extensions/webrtc/models/rtcstatus.rb @@ -12,7 +12,6 @@ module Models # This includes things like connection status, and executed modules etc # - class Rtcstatus < BeEF::Core::Model belongs_to :hooked_browser end From 966725ea927b81291bc9f35e6a2601c54c68ca98 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:33:02 +0530 Subject: [PATCH 53/85] rubocop --only Lint/ParenthesesAsGroupedExpression -a --- Rakefile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Rakefile b/Rakefile index 4e89d160fd..595a623566 100644 --- a/Rakefile +++ b/Rakefile @@ -106,7 +106,7 @@ task :xserver_start do delays = [2, 2, 1, 1, 1, 0.5, 0.5, 0.5, 0.3, 0.2, 0.1, 0.1, 0.1, 0.05, 0.05] delays.each do |i| # delay for 10 seconds printf '.' - sleep (i) # increase the . display rate + sleep(i) # increase the . display rate end puts '.' end @@ -145,7 +145,7 @@ task beef_start: 'beef' do delays = [5, 5, 5, 4, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1] delays.each do |i| # delay for a few seconds printf '.' - sleep (i) + sleep(i) end puts ".\n\n" end @@ -173,7 +173,7 @@ task msf_start: '/tmp/msf-test/msfconsole' do delays = [10, 7, 6, 5, 4, 3, 2, 2, 1, 1, 1, 0.5, 0.5, 0.5, 0.3, 0.2, 0.1, 0.1, 0.1, 0.05, 0.05] delays.each do |i| # delay for 45 seconds printf '.' - sleep (i) # increase the . display rate + sleep(i) # increase the . display rate end puts '.' end From f00965f60dbee47f37a29900e0feb73d11fa1c89 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:33:50 +0530 Subject: [PATCH 54/85] rubocop --only Style/MultilineIfModifier -a --- extensions/webrtc/handlers.rb | 60 +++++++++++++++++++++++------------ 1 file changed, 40 insertions(+), 20 deletions(-) diff --git a/extensions/webrtc/handlers.rb b/extensions/webrtc/handlers.rb index bd8e217667..82cd2de916 100644 --- a/extensions/webrtc/handlers.rb +++ b/extensions/webrtc/handlers.rb @@ -21,28 +21,38 @@ def initialize(data) def setup # validates the hook token beef_hook = @data['beefhook'] || nil - (print_error 'beefhook is null' - return) if beef_hook.nil? + if beef_hook.nil? + print_error 'beefhook is null' + return + end # validates the target hook token target_beef_id = @data['results']['targetbeefid'] || nil - (print_error 'targetbeefid is null' - return) if target_beef_id.nil? + if target_beef_id.nil? + print_error 'targetbeefid is null' + return + end # validates the signal signal = @data['results']['signal'] || nil - (print_error 'Signal is null' - return) if signal.nil? + if signal.nil? + print_error 'Signal is null' + return + end # validates that a hooked browser with the beef_hook token exists in the db zombie_db = Z.first(session: beef_hook) || nil - (print_error 'Invalid beefhook id: the hooked browser cannot be found in the database' - return) if zombie_db.nil? + if zombie_db.nil? + print_error 'Invalid beefhook id: the hooked browser cannot be found in the database' + return + end # validates that a target browser with the target_beef_token exists in the db target_zombie_db = Z.first(id: target_beef_id) || nil - (print_error 'Invalid targetbeefid: the target hooked browser cannot be found in the database' - return) if target_zombie_db.nil? + if target_zombie_db.nil? + print_error 'Invalid targetbeefid: the target hooked browser cannot be found in the database' + return + end # save the results in the database signal = R.new( @@ -68,28 +78,38 @@ def initialize(data) def setup # validates the hook token beef_hook = @data['beefhook'] || nil - (print_error 'beefhook is null' - return) if beef_hook.nil? + if beef_hook.nil? + print_error 'beefhook is null' + return + end # validates the target hook token peer_id = @data['results']['peerid'] || nil - (print_error 'peerid is null' - return) if peer_id.nil? + if peer_id.nil? + print_error 'peerid is null' + return + end # validates the message message = @data['results']['message'] || nil - (print_error 'Message is null' - return) if message.nil? + if message.nil? + print_error 'Message is null' + return + end # validates that a hooked browser with the beef_hook token exists in the db zombie_db = Z.first(session: beef_hook) || nil - (print_error 'Invalid beefhook id: the hooked browser cannot be found in the database' - return) if zombie_db.nil? + if zombie_db.nil? + print_error 'Invalid beefhook id: the hooked browser cannot be found in the database' + return + end # validates that a browser with the peerid exists in the db peer_zombie_db = Z.first(id: peer_id) || nil - (print_error 'Invalid peer_id: the peer hooked browser cannot be found in the database' - return) if peer_zombie_db.nil? + if peer_zombie_db.nil? + print_error 'Invalid peer_id: the peer hooked browser cannot be found in the database' + return + end # Writes the event into the BeEF Logger BeEF::Core::Logger.instance.register('WebRTC', "Browser:#{zombie_db.id} received message from Browser:#{peer_zombie_db.id}: #{message}") From 22cbe7c4161b1d5e7649ec0667149c400729f7cb Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:37:20 +0530 Subject: [PATCH 55/85] Disable Style/IfUnlessModifier cop --- .rubocop.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.rubocop.yml b/.rubocop.yml index 9dfa276a23..8fb24b73cd 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -51,6 +51,9 @@ Style/GuardClause: Style/IfInsideElse: Enabled: false +Style/IfUnlessModifier: + Enabled: false + Style/RescueStandardError: Enabled: false From 3105e11f733ce7d1e305b8e9604f2d1002f29ca4 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:39:05 +0530 Subject: [PATCH 56/85] rubocop --only Lint/UselessAssignment -a --- core/main/handlers/browserdetails.rb | 2 +- core/main/handlers/commands.rb | 2 +- core/main/network_stack/handlers/dynamicreconstruction.rb | 2 +- core/main/network_stack/handlers/raw.rb | 6 +++--- core/main/network_stack/handlers/redirector.rb | 6 +++--- core/main/rest/handlers/hookedbrowsers.rb | 2 +- extensions/admin_ui/controllers/modules/modules.rb | 4 ++-- extensions/admin_ui/handlers/ui.rb | 6 +++--- extensions/customhook/handler.rb | 8 ++++---- extensions/dns/api.rb | 4 ++-- extensions/proxy/api.rb | 2 +- extensions/social_engineering/rest/socialengineering.rb | 4 ++-- extensions/social_engineering/web_cloner/web_cloner.rb | 2 +- modules/host/hook_default_browser/module.rb | 2 +- modules/network/fetch_port_scanner/module.rb | 2 +- modules/network/get_http_servers/module.rb | 2 +- modules/network/internal_network_fingerprinting/module.rb | 2 +- 17 files changed, 29 insertions(+), 29 deletions(-) diff --git a/core/main/handlers/browserdetails.rb b/core/main/handlers/browserdetails.rb index 3c347ea343..af070b7e60 100644 --- a/core/main/handlers/browserdetails.rb +++ b/core/main/handlers/browserdetails.rb @@ -71,7 +71,7 @@ def setup # Parse http_headers. Unfortunately Rack doesn't provide a util-method to get them :( @http_headers = {} - http_header = @data['request'].env.select { |k, _v| k.to_s.start_with? 'HTTP_' } + @data['request'].env.select { |k, _v| k.to_s.start_with? 'HTTP_' } .each do |key, value| @http_headers[key.sub(/^HTTP_/, '')] = value.force_encoding('UTF-8') end diff --git a/core/main/handlers/commands.rb b/core/main/handlers/commands.rb index 736338c8bf..72ba0fc0ef 100644 --- a/core/main/handlers/commands.rb +++ b/core/main/handlers/commands.rb @@ -32,7 +32,7 @@ def initialize(data, kclass) def setup @http_params = @data['request'].params @http_header = {} - http_header = @data['request'].env.select { |k, _v| k.to_s.start_with? 'HTTP_' }.each do |key, value| + @data['request'].env.select { |k, _v| k.to_s.start_with? 'HTTP_' }.each do |key, value| @http_header[key.sub(/^HTTP_/, '')] = value.force_encoding('UTF-8') end diff --git a/core/main/network_stack/handlers/dynamicreconstruction.rb b/core/main/network_stack/handlers/dynamicreconstruction.rb index d4156936b0..e1f1a08170 100644 --- a/core/main/network_stack/handlers/dynamicreconstruction.rb +++ b/core/main/network_stack/handlers/dynamicreconstruction.rb @@ -76,7 +76,7 @@ def check_packets request.env[session_key] execute(res) - rescue JSON::ParserError => e + rescue JSON::ParserError print_debug 'Network stack could not decode packet stream.' print_debug "Dumping Stream Data [base64]: #{data}" print_debug "Dumping Stream Data: #{b64}" diff --git a/core/main/network_stack/handlers/raw.rb b/core/main/network_stack/handlers/raw.rb index b3183eabb6..622c91652f 100644 --- a/core/main/network_stack/handlers/raw.rb +++ b/core/main/network_stack/handlers/raw.rb @@ -17,9 +17,9 @@ def initialize(status, header = {}, body = nil) def call(_env) # [@status, @header, @body] @response = Rack::Response.new( - body = @body, - status = @status, - header = @header + @body, + @status, + @header ) end diff --git a/core/main/network_stack/handlers/redirector.rb b/core/main/network_stack/handlers/redirector.rb index 5265028f96..483f000c0f 100644 --- a/core/main/network_stack/handlers/redirector.rb +++ b/core/main/network_stack/handlers/redirector.rb @@ -18,9 +18,9 @@ def initialize(target) def call(_env) @response = Rack::Response.new( - body = ['302 found'], - status = 302, - header = { + ['302 found'], + 302, + { 'Content-Type' => 'text', 'Location' => @target } diff --git a/core/main/rest/handlers/hookedbrowsers.rb b/core/main/rest/handlers/hookedbrowsers.rb index c361d04201..898984d7f8 100644 --- a/core/main/rest/handlers/hookedbrowsers.rb +++ b/core/main/rest/handlers/hookedbrowsers.rb @@ -74,7 +74,7 @@ class HookedBrowsers < BeEF::Core::Router::Router xssraysdetails = BeEF::Core::Models::Xssraysdetail.where(hooked_browser_id: hb.id) xssraysdetails.destroy_all - rescue StandardError => e + rescue StandardError # @todo why is this error swallowed? # the xssraysscan module may not be enabled end diff --git a/extensions/admin_ui/controllers/modules/modules.rb b/extensions/admin_ui/controllers/modules/modules.rb index cac1fc3419..0bee004311 100644 --- a/extensions/admin_ui/controllers/modules/modules.rb +++ b/extensions/admin_ui/controllers/modules/modules.rb @@ -196,7 +196,7 @@ def retitle_recursive_tree(parent) # Returns the list of all command_modules for a TreePanel in the interface. def select_command_modules_tree blanktree = [] - tree = [] + [] # Due to the sub-folder nesting, we use some really badly hacked together recursion # Note to the bored - if someone (anyone please) wants to refactor, I'll buy you cookies. -x @@ -253,7 +253,7 @@ def select_command_module print_error 'command_module_id is nil' return end - command_module = BeEF::Core::Models::CommandModule.find(command_module_id) + BeEF::Core::Models::CommandModule.find(command_module_id) key = BeEF::Module.get_key_by_database_id(command_module_id) payload_name = @params['payload_name'] || nil diff --git a/extensions/admin_ui/handlers/ui.rb b/extensions/admin_ui/handlers/ui.rb index 208811a6cd..2c83faf2bc 100644 --- a/extensions/admin_ui/handlers/ui.rb +++ b/extensions/admin_ui/handlers/ui.rb @@ -27,9 +27,9 @@ def call(env) controller.run(@request, @response) @response = Rack::Response.new( - body = [controller.body], - status = controller.status, - header = controller.headers + [controller.body], + controller.status, + controller.headers ) end diff --git a/extensions/customhook/handler.rb b/extensions/customhook/handler.rb index 8fed2e4a2c..fc0257241c 100644 --- a/extensions/customhook/handler.rb +++ b/extensions/customhook/handler.rb @@ -11,7 +11,7 @@ def call(env) @body = '' @request = Rack::Request.new(env) @params = @request.query_string - @response = Rack::Response.new(body = [], 200, header = {}) + @response = Rack::Response.new([], 200, {}) config = BeEF::Core::Configuration.instance eruby = Erubis::FastEruby.new(File.read("#{File.dirname(__FILE__)}/html/index.html")) config.get('beef.extension.customhook.hooks').each do |h| @@ -27,9 +27,9 @@ def call(env) end @response = Rack::Response.new( - body = [@body], - status = 200, - header = { + [@body], + 200, + { 'Pragma' => 'no-cache', 'Cache-Control' => 'no-cache', 'Expires' => '0', diff --git a/extensions/dns/api.rb b/extensions/dns/api.rb index e2d92063fb..5d4ee5f3a6 100644 --- a/extensions/dns/api.rb +++ b/extensions/dns/api.rb @@ -24,7 +24,7 @@ module NameserverHandler # # @param http_hook_server [BeEF::Core::Server] HTTP server instance def self.pre_http_start(_http_hook_server) - servers, interfaces, address, port, protocol, upstream_servers = get_dns_config # get the DNS configuration + servers, interfaces, _, _, _, _ = get_dns_config # get the DNS configuration # Start the DNS server dns = BeEF::Extension::Dns::Server.instance @@ -32,7 +32,7 @@ def self.pre_http_start(_http_hook_server) end def self.print_dns_info - servers, interfaces, address, port, protocol, upstream_servers = get_dns_config # get the DNS configuration + _, _, address, port, protocol, upstream_servers = get_dns_config # get the DNS configuration # Print the DNS server information print_info "DNS Server: #{address}:#{port} (#{protocol})" diff --git a/extensions/proxy/api.rb b/extensions/proxy/api.rb index 21bdbbaa60..ddc1c1c60c 100644 --- a/extensions/proxy/api.rb +++ b/extensions/proxy/api.rb @@ -12,7 +12,7 @@ module RegisterHttpHandler BeEF::API::Registrar.instance.register(BeEF::Extension::Proxy::API::RegisterHttpHandler, BeEF::API::Server, 'mount_handler') def self.pre_http_start(http_hook_server) - config = BeEF::Core::Configuration.instance + BeEF::Core::Configuration.instance Thread.new do http_hook_server.semaphore.synchronize do BeEF::Extension::Proxy::Proxy.new diff --git a/extensions/social_engineering/rest/socialengineering.rb b/extensions/social_engineering/rest/socialengineering.rb index fad2145009..58a4d53bcf 100644 --- a/extensions/social_engineering/rest/socialengineering.rb +++ b/extensions/social_engineering/rest/socialengineering.rb @@ -52,12 +52,12 @@ class SEngRest < BeEF::Core::Router::Router success = web_cloner.clone_page(uri, mount, use_existing, dns_spoof) if success - result = { + { 'success' => true, 'mount' => mount }.to_json else - result = { + { 'success' => false }.to_json halt 500 diff --git a/extensions/social_engineering/web_cloner/web_cloner.rb b/extensions/social_engineering/web_cloner/web_cloner.rb index 67fab749d4..0d2fc05948 100644 --- a/extensions/social_engineering/web_cloner/web_cloner.rb +++ b/extensions/social_engineering/web_cloner/web_cloner.rb @@ -55,7 +55,7 @@ def clone_page(url, mount, use_existing, dns_spoof) if line.include?(' 'url', 'ui_label'=>'URL', 'type' => 'text', 'width' => '400px', 'value' => hook_uri }, diff --git a/modules/network/fetch_port_scanner/module.rb b/modules/network/fetch_port_scanner/module.rb index 9eeac586da..0432afffdf 100644 --- a/modules/network/fetch_port_scanner/module.rb +++ b/modules/network/fetch_port_scanner/module.rb @@ -20,7 +20,7 @@ def post_execute configuration = BeEF::Core::Configuration.instance return unless configuration.get('beef.extension.network.enable') == true - session_id = @datastore['beefhook'] + @datastore['beefhook'] # @todo log the network service # will need to once the datastore is confirmed. diff --git a/modules/network/get_http_servers/module.rb b/modules/network/get_http_servers/module.rb index ce5eb9e996..921510db83 100644 --- a/modules/network/get_http_servers/module.rb +++ b/modules/network/get_http_servers/module.rb @@ -28,7 +28,7 @@ def post_execute proto = Regexp.last_match(1) ip = Regexp.last_match(2) port = Regexp.last_match(3) - url = Regexp.last_match(4) + Regexp.last_match(4) session_id = @datastore['beefhook'] if !ip.nil? && BeEF::Filters.is_valid_ip?(ip) print_debug("Hooked browser found HTTP Server [proto: #{proto}, ip: #{ip}, port: #{port}]") diff --git a/modules/network/internal_network_fingerprinting/module.rb b/modules/network/internal_network_fingerprinting/module.rb index b63e9070a1..f4b3f9b8a4 100644 --- a/modules/network/internal_network_fingerprinting/module.rb +++ b/modules/network/internal_network_fingerprinting/module.rb @@ -29,7 +29,7 @@ def post_execute ip = Regexp.last_match(2) port = Regexp.last_match(3) discovered = Regexp.last_match(4) - url = Regexp.last_match(5) + Regexp.last_match(5) session_id = @datastore['beefhook'] if BeEF::Filters.is_valid_ip?(ip) print_debug("Hooked browser found '#{discovered}' [ip: #{ip}]") From 76fe850a347c7d4a89cab01b03a7da995ee9a5a4 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:43:04 +0530 Subject: [PATCH 57/85] Disable Layout/LineLength cop --- .rubocop.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index 8fb24b73cd..80bbcf135e 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -12,8 +12,7 @@ Bundler/OrderedGems: Enabled: false Layout/LineLength: - Enabled: true - Max: 180 + Enabled: false Metrics/AbcSize: Enabled: false From a1ee494635982a268742d90626903118a4cd14e4 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:43:38 +0530 Subject: [PATCH 58/85] rubocop --only Style/TrailingCommaInArrayLiteral -a --- modules/browser/webcam_html5/module.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/browser/webcam_html5/module.rb b/modules/browser/webcam_html5/module.rb index 479dae1226..9e8ec3df99 100644 --- a/modules/browser/webcam_html5/module.rb +++ b/modules/browser/webcam_html5/module.rb @@ -8,7 +8,7 @@ class Webcam_html5 < BeEF::Core::Command def self.options [ { 'name' => 'choice', 'type' => 'combobox', 'ui_label' => 'Screenshot size', 'store_type' => 'arraystore', 'store_fields' => ['choice'], - 'store_data' => [['320x240'], ['640x480'], ['Full']], 'valueField' => 'choice', 'value' => '320x240', editable: false, 'displayField' => 'choice', 'mode' => 'local', 'autoWidth' => true }, + 'store_data' => [['320x240'], ['640x480'], ['Full']], 'valueField' => 'choice', 'value' => '320x240', editable: false, 'displayField' => 'choice', 'mode' => 'local', 'autoWidth' => true } ] end From a6b986176dffb4806313a6c71550945ac4857cb1 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:44:02 +0530 Subject: [PATCH 59/85] rubocop --only Style/MethodCallWithoutArgsParentheses -a --- extensions/webrtc/handlers.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/webrtc/handlers.rb b/extensions/webrtc/handlers.rb index 82cd2de916..895f8f7954 100644 --- a/extensions/webrtc/handlers.rb +++ b/extensions/webrtc/handlers.rb @@ -15,7 +15,7 @@ class SignalHandler def initialize(data) @data = data - setup() + setup end def setup @@ -72,7 +72,7 @@ class MessengeHandler def initialize(data) @data = data - setup() + setup end def setup From a94dfd5d63e180e12019e7ade2eaa65cee49effa Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:44:32 +0530 Subject: [PATCH 60/85] rubocop --only Layout/LeadingCommentSpace -a --- Rakefile | 4 ++-- beef | 2 +- core/main/rest/handlers/modules.rb | 2 +- extensions/webrtc/api/hook.rb | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Rakefile b/Rakefile index 595a623566..3b96056c55 100644 --- a/Rakefile +++ b/Rakefile @@ -88,8 +88,8 @@ namespace :rdoc do rd.rdoc_dir = 'doc/rdocs' rd.main = 'README.mkd' rd.rdoc_files.include('core/**/*\.rb') - #'extensions/**/*\.rb' - #'modules/**/*\.rb' + # 'extensions/**/*\.rb' + # 'modules/**/*\.rb' rd.options << '--line-numbers' rd.options << '--all' end diff --git a/beef b/beef index b6c3b81980..ed53b9b7e5 100755 --- a/beef +++ b/beef @@ -196,7 +196,7 @@ end ActiveRecord::Base.logger = nil OTR::ActiveRecord.configure_from_hash!(adapter:'sqlite3', database:db_file) # otr-activerecord require you to manually establish the connection with the following line -#Also a check to confirm that the correct Gem version is installed to require it, likely easier for old systems. +# Also a check to confirm that the correct Gem version is installed to require it, likely easier for old systems. if Gem.loaded_specs['otr-activerecord'].version > Gem::Version.create('1.4.2') OTR::ActiveRecord.establish_connection! end diff --git a/core/main/rest/handlers/modules.rb b/core/main/rest/handlers/modules.rb index f0b5076226..f8602add7c 100644 --- a/core/main/rest/handlers/modules.rb +++ b/core/main/rest/handlers/modules.rb @@ -172,7 +172,7 @@ class Modules < BeEF::Core::Router::Router # curl example (alert module with custom text, 2 hooked browsers)): # # curl -H "Content-Type: application/json; charset=UTF-8" -d '{"mod_id":110,"mod_params":{"text":"mucci?"},"hb_ids":[1,2]}' - #-X POST http://127.0.0.1:3000/api/modules/multi_browser?token=2316d82702b83a293e2d46a0886a003a6be0a633 + # -X POST http://127.0.0.1:3000/api/modules/multi_browser?token=2316d82702b83a293e2d46a0886a003a6be0a633 # post '/multi_browser' do request.body.rewind diff --git a/extensions/webrtc/api/hook.rb b/extensions/webrtc/api/hook.rb index 637c40c59a..48d2a9e7e8 100644 --- a/extensions/webrtc/api/hook.rb +++ b/extensions/webrtc/api/hook.rb @@ -48,7 +48,7 @@ def requester_run(hb, body) ws = BeEF::Core::Websocket::Websocket.instance # todo antisnatchor: prevent sending "content" multiple times. Better leaving it after the first run, and don't send it again. - #todo antisnatchor: remove this gsub crap adding some hook packing. + # todo antisnatchor: remove this gsub crap adding some hook packing. # The below is how antisnatchor was managing insertion of messages dependent on WebSockets or not # Hopefully this still works if config.get('beef.http.websocket.enable') && ws.getsocket(hb.session) @@ -65,7 +65,7 @@ def requester_run(hb, body) end # ws.send(content + @body,hb.session) ws.send(@body,hb.session) - #if we use WebSockets, just reply wih the component contents + # if we use WebSockets, just reply wih the component contents else # if we use XHR-polling, add the component to the main hook file unless rtcsignaloutput.empty? rtcsignaloutput.each { |o| From 0c3574f099e3a50dffffeafafa1b9c0e7088d041 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:45:28 +0530 Subject: [PATCH 61/85] rubocop --only Layout/ExtraSpacing -a --- core/main/models/execution.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/main/models/execution.rb b/core/main/models/execution.rb index 3d4051f179..b96c519545 100644 --- a/core/main/models/execution.rb +++ b/core/main/models/execution.rb @@ -6,7 +6,7 @@ module BeEF module Core - module Models # @note Stored info about the execution of the ARE on hooked browsers. + module Models # @note Stored info about the execution of the ARE on hooked browsers. class Execution < BeEF::Core::Model end end From 843f61092af732630b35faa3be3619bbc3ceb630 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:47:03 +0530 Subject: [PATCH 62/85] be rubocop --only Style/RedundantStringEscape -a --- extensions/s2c_dns_tunnel/httpd.rb | 2 +- modules/exploits/firephp/module.rb | 2 +- modules/misc/raw_javascript/module.rb | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/s2c_dns_tunnel/httpd.rb b/extensions/s2c_dns_tunnel/httpd.rb index ef775e6cc4..add8c4c958 100644 --- a/extensions/s2c_dns_tunnel/httpd.rb +++ b/extensions/s2c_dns_tunnel/httpd.rb @@ -8,7 +8,7 @@ def initialize(domain) end get '/map' do - if request.host.match("^_ldap\._tcp\.[0-9a-z\-]+\.domains\._msdcs\.#{@domain}$") + if request.host.match("^_ldap._tcp.[0-9a-z-]+.domains._msdcs.#{@domain}$") path = File.dirname(__FILE__) send_file File.join(path, 'pixel.jpg') end diff --git a/modules/exploits/firephp/module.rb b/modules/exploits/firephp/module.rb index be470a439b..14e8861ae5 100644 --- a/modules/exploits/firephp/module.rb +++ b/modules/exploits/firephp/module.rb @@ -31,7 +31,7 @@ def pre_send '7' => rand(10).to_s, '8' => rand(10).to_s, '9' => rand(10).to_s, - "" => rand_str } }.to_json diff --git a/modules/misc/raw_javascript/module.rb b/modules/misc/raw_javascript/module.rb index 1e3cd12200..3ef49242d3 100644 --- a/modules/misc/raw_javascript/module.rb +++ b/modules/misc/raw_javascript/module.rb @@ -6,7 +6,7 @@ class Raw_javascript < BeEF::Core::Command def self.options [ - { 'name' => 'cmd', 'description' => 'Javascript Code', 'ui_label' => 'Javascript Code', 'value' => "alert(\'BeEF Raw Javascript\');\nreturn \'It worked!\';", + { 'name' => 'cmd', 'description' => 'Javascript Code', 'ui_label' => 'Javascript Code', 'value' => "alert('BeEF Raw Javascript');\nreturn 'It worked!';", 'type' => 'textarea', 'width' => '400px', 'height' => '100px' } ] end From c7ee2d0d3c4902bdb8d7a2f9c698c862bc57d133 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:48:12 +0530 Subject: [PATCH 63/85] Disable Style/BlockDelimiters cop --- .rubocop.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.rubocop.yml b/.rubocop.yml index 80bbcf135e..2eef5411f6 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -38,6 +38,9 @@ Metrics/PerceivedComplexity: Naming/ClassAndModuleCamelCase: Enabled: false +Style/BlockDelimiters: + Enabled: false + Style/CommentAnnotation: Enabled: false From d3205739ffa624efdbbec5eaed8c65b7b78e370d Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:48:50 +0530 Subject: [PATCH 64/85] rubocop --only Layout/IndentationStyle -a --- extensions/webrtc/extension.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/webrtc/extension.rb b/extensions/webrtc/extension.rb index 62a405ffab..58cf1bc60b 100644 --- a/extensions/webrtc/extension.rb +++ b/extensions/webrtc/extension.rb @@ -6,7 +6,7 @@ module BeEF module Extension module WebRTC - extend BeEF::API::Extension + extend BeEF::API::Extension @short_name = 'webrtc' @full_name = 'WebRTC' From f6dabb36251989e870601b771c6289d518d3dfed Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:49:14 +0530 Subject: [PATCH 65/85] rubocop --only Layout/MultilineMethodCallIndentation -a --- core/main/handlers/browserdetails.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/main/handlers/browserdetails.rb b/core/main/handlers/browserdetails.rb index af070b7e60..370329fdcd 100644 --- a/core/main/handlers/browserdetails.rb +++ b/core/main/handlers/browserdetails.rb @@ -72,7 +72,7 @@ def setup # Parse http_headers. Unfortunately Rack doesn't provide a util-method to get them :( @http_headers = {} @data['request'].env.select { |k, _v| k.to_s.start_with? 'HTTP_' } - .each do |key, value| + .each do |key, value| @http_headers[key.sub(/^HTTP_/, '')] = value.force_encoding('UTF-8') end zombie.httpheaders = @http_headers.to_json From e8ddc9f04cffc68a82de49d71e19b78d7dfd69c3 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:49:37 +0530 Subject: [PATCH 66/85] rubocop --only Layout/IndentationConsistency -a --- extensions/webrtc/extension.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/webrtc/extension.rb b/extensions/webrtc/extension.rb index 58cf1bc60b..11f0b1784a 100644 --- a/extensions/webrtc/extension.rb +++ b/extensions/webrtc/extension.rb @@ -8,9 +8,9 @@ module Extension module WebRTC extend BeEF::API::Extension - @short_name = 'webrtc' - @full_name = 'WebRTC' - @description = 'WebRTC extension to all browsers to connect to each other (P2P) with WebRTC' + @short_name = 'webrtc' + @full_name = 'WebRTC' + @description = 'WebRTC extension to all browsers to connect to each other (P2P) with WebRTC' end end end From 2cf4bb521d49df1baf92fd7a3079ec48df6c450e Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:50:03 +0530 Subject: [PATCH 67/85] rubocop --only Layout/HashAlignment -a --- extensions/admin_ui/controllers/modules/modules.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/admin_ui/controllers/modules/modules.rb b/extensions/admin_ui/controllers/modules/modules.rb index 0bee004311..36a4ae694e 100644 --- a/extensions/admin_ui/controllers/modules/modules.rb +++ b/extensions/admin_ui/controllers/modules/modules.rb @@ -307,9 +307,9 @@ def select_command_module_commands C.where(command_module_id: command_module_id, hooked_browser_id: zombie_id).each do |command| commands.push({ 'id' => i, - 'object_id' => command.id, - 'creationdate' => Time.at(command.creationdate.to_i).strftime('%Y-%m-%d %H:%M').to_s, - 'label' => command.label + 'object_id' => command.id, + 'creationdate' => Time.at(command.creationdate.to_i).strftime('%Y-%m-%d %H:%M').to_s, + 'label' => command.label }) i += 1 end From 863676a7422aa3518416629724b519bd0831cc7f Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:50:27 +0530 Subject: [PATCH 68/85] rubocop --only Layout/EndAlignment -a --- beef | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beef b/beef index ed53b9b7e5..c8696cd4ea 100755 --- a/beef +++ b/beef @@ -83,7 +83,7 @@ config = if BeEF::Core::Console::CommandLine.parse[:ext_config].empty? BeEF::Core::Configuration.new("#{$root_dir}/config.yaml") else BeEF::Core::Configuration.new("#{BeEF::Core::Console::CommandLine.parse[:ext_config]}") -end + end # # @note set log level From 579614ba87805debd6cd529e86e94d974aace997 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:50:55 +0530 Subject: [PATCH 69/85] rubocop --only Layout/IndentationWidth -a --- beef | 2 +- extensions/webrtc/extension.rb | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/beef b/beef index c8696cd4ea..1b532b9c75 100755 --- a/beef +++ b/beef @@ -80,7 +80,7 @@ end # @note Initialize the Configuration object. Loads a different config.yaml if -c flag was passed. # config = if BeEF::Core::Console::CommandLine.parse[:ext_config].empty? - BeEF::Core::Configuration.new("#{$root_dir}/config.yaml") + BeEF::Core::Configuration.new("#{$root_dir}/config.yaml") else BeEF::Core::Configuration.new("#{BeEF::Core::Console::CommandLine.parse[:ext_config]}") end diff --git a/extensions/webrtc/extension.rb b/extensions/webrtc/extension.rb index 11f0b1784a..d07fd53ddc 100644 --- a/extensions/webrtc/extension.rb +++ b/extensions/webrtc/extension.rb @@ -6,11 +6,11 @@ module BeEF module Extension module WebRTC - extend BeEF::API::Extension + extend BeEF::API::Extension - @short_name = 'webrtc' - @full_name = 'WebRTC' - @description = 'WebRTC extension to all browsers to connect to each other (P2P) with WebRTC' + @short_name = 'webrtc' + @full_name = 'WebRTC' + @description = 'WebRTC extension to all browsers to connect to each other (P2P) with WebRTC' end end end From b020de9fdbabc68e3a6cc8cb7e665f8feb120abb Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:52:02 +0530 Subject: [PATCH 70/85] rubocop --only Layout/SpaceAfterColon -a --- beef | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beef b/beef index 1b532b9c75..cf646b6211 100755 --- a/beef +++ b/beef @@ -194,7 +194,7 @@ end # Connect to DB ActiveRecord::Base.logger = nil -OTR::ActiveRecord.configure_from_hash!(adapter:'sqlite3', database:db_file) +OTR::ActiveRecord.configure_from_hash!(adapter: 'sqlite3', database: db_file) # otr-activerecord require you to manually establish the connection with the following line # Also a check to confirm that the correct Gem version is installed to require it, likely easier for old systems. if Gem.loaded_specs['otr-activerecord'].version > Gem::Version.create('1.4.2') From 0424d9cfcb3636706bd62c4af5d4b9fb4c27a709 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:52:30 +0530 Subject: [PATCH 71/85] rubocop --only Style/RedundantPercentQ -a --- extensions/webrtc/api/hook.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/extensions/webrtc/api/hook.rb b/extensions/webrtc/api/hook.rb index 48d2a9e7e8..df8f8e8b7a 100644 --- a/extensions/webrtc/api/hook.rb +++ b/extensions/webrtc/api/hook.rb @@ -81,7 +81,7 @@ def requester_run(hb, body) end def add_rtcsignal_to_body(output) - @body << %Q{ + @body << " beef.execute(function() { var peerid = null; for (k in beefrtcs) { @@ -97,15 +97,15 @@ def add_rtcsignal_to_body(output) ); } }); - } + " end def add_rtcmanagement_to_body(output) - @body << %Q{ + @body << " beef.execute(function() { #{output} }); - } + " end end end From 5ccc33c443ed3bad96087a091328fefc61ed0cab Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:52:53 +0530 Subject: [PATCH 72/85] rubocop --only Layout/SpaceInsideArrayLiteralBrackets -a --- core/main/models/legacybrowseruseragents.rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/core/main/models/legacybrowseruseragents.rb b/core/main/models/legacybrowseruseragents.rb index 918d73d1b2..93ec563d42 100644 --- a/core/main/models/legacybrowseruseragents.rb +++ b/core/main/models/legacybrowseruseragents.rb @@ -16,8 +16,7 @@ module Models # module LegacyBrowserUserAgents def self.user_agents - [ - ] + [] end end end From 1ef8647c0cfaf749e5c925c3924ae1fd1d33d607 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:53:20 +0530 Subject: [PATCH 73/85] rubocop --only Layout/SpaceAfterComma -a --- extensions/webrtc/api/hook.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/webrtc/api/hook.rb b/extensions/webrtc/api/hook.rb index df8f8e8b7a..1d5e84d0f4 100644 --- a/extensions/webrtc/api/hook.rb +++ b/extensions/webrtc/api/hook.rb @@ -64,7 +64,7 @@ def requester_run(hb, body) } end # ws.send(content + @body,hb.session) - ws.send(@body,hb.session) + ws.send(@body, hb.session) # if we use WebSockets, just reply wih the component contents else # if we use XHR-polling, add the component to the main hook file unless rtcsignaloutput.empty? From b6028c9c1e2d2e04a82f959b0da0a1dd92ef5417 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 15:59:06 +0530 Subject: [PATCH 74/85] rubocop --only Lint/Void -a --- core/main/command.rb | 5 ----- core/main/network_stack/assethandler.rb | 3 --- core/main/network_stack/handlers/raw.rb | 4 ---- core/main/network_stack/handlers/redirector.rb | 4 ---- core/main/server.rb | 2 +- extensions/admin_ui/classes/httpcontroller.rb | 2 -- extensions/admin_ui/classes/session.rb | 1 - extensions/admin_ui/controllers/modules/modules.rb | 1 - extensions/admin_ui/handlers/ui.rb | 3 --- extensions/customhook/handler.rb | 8 ++------ extensions/evasion/obfuscation/scramble.rb | 3 --- extensions/social_engineering/web_cloner/web_cloner.rb | 1 - modules/host/hook_default_browser/module.rb | 6 +++--- 13 files changed, 6 insertions(+), 37 deletions(-) diff --git a/core/main/command.rb b/core/main/command.rb index 76090dc003..a991b0e910 100644 --- a/core/main/command.rb +++ b/core/main/command.rb @@ -251,11 +251,6 @@ def apply_defaults opt['value'] = oc_value(opt['name']) || opt['value'] end end - - @use_template - @eruby - @update_zombie - @results end end end diff --git a/core/main/network_stack/assethandler.rb b/core/main/network_stack/assethandler.rb index 7052cd28be..109548c85e 100644 --- a/core/main/network_stack/assethandler.rb +++ b/core/main/network_stack/assethandler.rb @@ -244,9 +244,6 @@ def check(url) false end - - @http_server - @allocations end end end diff --git a/core/main/network_stack/handlers/raw.rb b/core/main/network_stack/handlers/raw.rb index 622c91652f..efce0f232e 100644 --- a/core/main/network_stack/handlers/raw.rb +++ b/core/main/network_stack/handlers/raw.rb @@ -22,10 +22,6 @@ def call(_env) @header ) end - - @request - - @response end end end diff --git a/core/main/network_stack/handlers/redirector.rb b/core/main/network_stack/handlers/redirector.rb index 483f000c0f..9fc02871b9 100644 --- a/core/main/network_stack/handlers/redirector.rb +++ b/core/main/network_stack/handlers/redirector.rb @@ -26,10 +26,6 @@ def call(_env) } ) end - - @request - - @response end end end diff --git a/core/main/server.rb b/core/main/server.rb index 7d28f538d9..0ca8c5a351 100644 --- a/core/main/server.rb +++ b/core/main/server.rb @@ -21,7 +21,7 @@ def initialize @root_dir = File.expand_path('../../../', __dir__) @command_urls = {} @mounts = {} - @rack_app + @rack_app = nil @semaphore = Mutex.new end diff --git a/extensions/admin_ui/classes/httpcontroller.rb b/extensions/admin_ui/classes/httpcontroller.rb index 28a30e7664..8f1e3bdfd9 100644 --- a/extensions/admin_ui/classes/httpcontroller.rb +++ b/extensions/admin_ui/classes/httpcontroller.rb @@ -143,8 +143,6 @@ def base_path private - @eruby - # Unescapes a URL-encoded string. def unescape(s) s.tr('+', ' ').gsub(/%([\da-f]{2})/in) { [Regexp.last_match(1)].pack('H*') } diff --git a/extensions/admin_ui/classes/session.rb b/extensions/admin_ui/classes/session.rb index d54883313f..cd47fec10a 100644 --- a/extensions/admin_ui/classes/session.rb +++ b/extensions/admin_ui/classes/session.rb @@ -100,7 +100,6 @@ def valid_session?(request) request.cookies.each do |cookie| return true if (cookie[0].to_s.eql? session_cookie_name) and (cookie[1].eql? @id) end - request # not a valid session false diff --git a/extensions/admin_ui/controllers/modules/modules.rb b/extensions/admin_ui/controllers/modules/modules.rb index 36a4ae694e..e11052461a 100644 --- a/extensions/admin_ui/controllers/modules/modules.rb +++ b/extensions/admin_ui/controllers/modules/modules.rb @@ -196,7 +196,6 @@ def retitle_recursive_tree(parent) # Returns the list of all command_modules for a TreePanel in the interface. def select_command_modules_tree blanktree = [] - [] # Due to the sub-folder nesting, we use some really badly hacked together recursion # Note to the bored - if someone (anyone please) wants to refactor, I'll buy you cookies. -x diff --git a/extensions/admin_ui/handlers/ui.rb b/extensions/admin_ui/handlers/ui.rb index 2c83faf2bc..8dec343ae3 100644 --- a/extensions/admin_ui/handlers/ui.rb +++ b/extensions/admin_ui/handlers/ui.rb @@ -32,9 +32,6 @@ def call(env) controller.headers ) end - - @request - @response end end end diff --git a/extensions/customhook/handler.rb b/extensions/customhook/handler.rb index fc0257241c..fa1638234f 100644 --- a/extensions/customhook/handler.rb +++ b/extensions/customhook/handler.rb @@ -9,8 +9,10 @@ module Customhook class Handler def call(env) @body = '' + # @note Object representing the HTTP request @request = Rack::Request.new(env) @params = @request.query_string + # @note Object representing the HTTP response @response = Rack::Response.new([], 200, {}) config = BeEF::Core::Configuration.instance eruby = Erubis::FastEruby.new(File.read("#{File.dirname(__FILE__)}/html/index.html")) @@ -39,12 +41,6 @@ def call(env) } ) end - - # @note Object representing the HTTP request - @request - - # @note Object representing the HTTP response - @response end end end diff --git a/extensions/evasion/obfuscation/scramble.rb b/extensions/evasion/obfuscation/scramble.rb index 1ebfc0ee08..1d0f215613 100644 --- a/extensions/evasion/obfuscation/scramble.rb +++ b/extensions/evasion/obfuscation/scramble.rb @@ -29,7 +29,6 @@ def execute(input, config) @output.gsub!(var, value) print_debug "[OBFUSCATION - SCRAMBLER] string [#{var}] scrambled -> [#{value}]" end - @output end if config.get('beef.extension.evasion.scramble_cookies') @@ -44,8 +43,6 @@ def execute(input, config) print_debug "[OBFUSCATION - SCRAMBLER] cookie [BEEFHOOK] scrambled -> [#{config.get('beef.http.hook_session_name')}]" end end - - @output end end end diff --git a/extensions/social_engineering/web_cloner/web_cloner.rb b/extensions/social_engineering/web_cloner/web_cloner.rb index 0d2fc05948..200471cf75 100644 --- a/extensions/social_engineering/web_cloner/web_cloner.rb +++ b/extensions/social_engineering/web_cloner/web_cloner.rb @@ -55,7 +55,6 @@ def clone_page(url, mount, use_existing, dns_spoof) if line.include?(' 'url', 'ui_label'=>'URL', 'type' => 'text', 'width' => '400px', 'value' => hook_uri }, From cb6392dac58ff8157151ec5da64a40cb239a8f7f Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 16:00:15 +0530 Subject: [PATCH 75/85] rubocop --only Layout/LineContinuationLeadingSpace -a --- core/main/router/router.rb | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/core/main/router/router.rb b/core/main/router/router.rb index 62463e08d3..aa685cc1e2 100644 --- a/core/main/router/router.rb +++ b/core/main/router/router.rb @@ -186,8 +186,8 @@ def index_page "

    \"[ \"[

    " \ '' \ '' \ - '' \ - '
    ' \ + '
    ' \ + '
    ' \ '

    About CentOS:

    The Community ENTerprise Operating System (CentOS) is an Enterprise-class Linux Distribution derived from sources freely provided to the public by a prominent North American Enterprise Linux vendor. CentOS conforms fully with the upstream vendors redistribution policy and aims to be 100% binary compatible. (CentOS mainly changes packages to remove upstream vendor branding and artwork.) The CentOS Project is the organization that builds CentOS.

    ' \ '

    For information on CentOS please visit the CentOS website.

    ' \ '

    Note:

    CentOS is an Operating System and it is used to power this website; however, the webserver is owned by the domain owner and not the CentOS Project. If you have issues with the content of this site, contact the owner of the domain, not the CentOS project.' \ @@ -235,12 +235,12 @@ def index_page "\n" \ "\n" \ "Welcome to nginx!\n" \ - "\n" \ "\n" \ "\n" \ From 23a78cbbee25bb164017c05c5169d92ce578082d Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 16:00:51 +0530 Subject: [PATCH 76/85] rubocop --only Style/TrailingUnderscoreVariable -a --- extensions/dns/api.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/dns/api.rb b/extensions/dns/api.rb index 5d4ee5f3a6..936edd1d08 100644 --- a/extensions/dns/api.rb +++ b/extensions/dns/api.rb @@ -24,7 +24,7 @@ module NameserverHandler # # @param http_hook_server [BeEF::Core::Server] HTTP server instance def self.pre_http_start(_http_hook_server) - servers, interfaces, _, _, _, _ = get_dns_config # get the DNS configuration + servers, interfaces, = get_dns_config # get the DNS configuration # Start the DNS server dns = BeEF::Extension::Dns::Server.instance From 79fa58e9b7751b4306839b8dd5a1eabaa29ffaf5 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 16:01:21 +0530 Subject: [PATCH 77/85] rubocop --only Layout/ElseAlignment -a --- beef | 2 +- core/main/autorun_engine/engine.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/beef b/beef index cf646b6211..b1435ae02b 100755 --- a/beef +++ b/beef @@ -81,7 +81,7 @@ end # config = if BeEF::Core::Console::CommandLine.parse[:ext_config].empty? BeEF::Core::Configuration.new("#{$root_dir}/config.yaml") -else + else BeEF::Core::Configuration.new("#{BeEF::Core::Console::CommandLine.parse[:ext_config]}") end diff --git a/core/main/autorun_engine/engine.rb b/core/main/autorun_engine/engine.rb index aac492fc0d..3281d087eb 100644 --- a/core/main/autorun_engine/engine.rb +++ b/core/main/autorun_engine/engine.rb @@ -163,7 +163,7 @@ def zombie_browser_matches_rule?(browser, browser_version, rule) # check if the browser version matches browser_version_match = compare_versions(browser_version.to_s, b_ver_cond, b_ver.to_s) return false unless browser_version_match - else + else browser_match = false rule.browser.gsub(/[^A-Z,]/i, '').split(',').each do |b| if b == browser || b == 'ALL' From 8bdc14ec94a0db53e88fd09346c112718bff3654 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 16:01:44 +0530 Subject: [PATCH 78/85] rubocop --only Layout/IndentationWidth -a --- beef | 2 +- core/main/autorun_engine/engine.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/beef b/beef index b1435ae02b..084a1d7849 100755 --- a/beef +++ b/beef @@ -82,7 +82,7 @@ end config = if BeEF::Core::Console::CommandLine.parse[:ext_config].empty? BeEF::Core::Configuration.new("#{$root_dir}/config.yaml") else - BeEF::Core::Configuration.new("#{BeEF::Core::Console::CommandLine.parse[:ext_config]}") + BeEF::Core::Configuration.new("#{BeEF::Core::Console::CommandLine.parse[:ext_config]}") end # diff --git a/core/main/autorun_engine/engine.rb b/core/main/autorun_engine/engine.rb index 3281d087eb..a2f6a91647 100644 --- a/core/main/autorun_engine/engine.rb +++ b/core/main/autorun_engine/engine.rb @@ -164,7 +164,7 @@ def zombie_browser_matches_rule?(browser, browser_version, rule) browser_version_match = compare_versions(browser_version.to_s, b_ver_cond, b_ver.to_s) return false unless browser_version_match else - browser_match = false + browser_match = false rule.browser.gsub(/[^A-Z,]/i, '').split(',').each do |b| if b == browser || b == 'ALL' browser_match = true From 915369f78142d8ed38a8d0d3b3828d266860312c Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 16:02:09 +0530 Subject: [PATCH 79/85] rubocop --only Layout/IndentationConsistency -a --- core/main/autorun_engine/engine.rb | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/core/main/autorun_engine/engine.rb b/core/main/autorun_engine/engine.rb index a2f6a91647..af0413c43e 100644 --- a/core/main/autorun_engine/engine.rb +++ b/core/main/autorun_engine/engine.rb @@ -165,13 +165,13 @@ def zombie_browser_matches_rule?(browser, browser_version, rule) return false unless browser_version_match else browser_match = false - rule.browser.gsub(/[^A-Z,]/i, '').split(',').each do |b| - if b == browser || b == 'ALL' - browser_match = true - break - end + rule.browser.gsub(/[^A-Z,]/i, '').split(',').each do |b| + if b == browser || b == 'ALL' + browser_match = true + break end - return false unless browser_match + end + return false unless browser_match end true From 23bdc2a20f15f573cf077f277e777fbcba6597f9 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 16:02:35 +0530 Subject: [PATCH 80/85] rubocop --only Style/RedundantSelf -a --- core/main/autorun_engine/rule_loader.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/main/autorun_engine/rule_loader.rb b/core/main/autorun_engine/rule_loader.rb index 889dcbfe35..06fd58bf87 100644 --- a/core/main/autorun_engine/rule_loader.rb +++ b/core/main/autorun_engine/rule_loader.rb @@ -202,7 +202,7 @@ def update_rule_json(id, data) # @param [String] JSON ARE ruleset file path def load_rule_file(json_rule_path) rule_file = File.open(json_rule_path, 'r:UTF-8', &:read) - self.load_rule_json(JSON.parse(rule_file)) + load_rule_json(JSON.parse(rule_file)) rescue => e print_error("[ARE] Failed to load ruleset from #{json_rule_path}: #{e.message}") end From 4586e94a9bcf16cb5ce16dadcf1241e72d632500 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 16:03:01 +0530 Subject: [PATCH 81/85] rubocop --only Style/PerlBackrefs -a --- beef | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/beef b/beef index 084a1d7849..359ded43e8 100755 --- a/beef +++ b/beef @@ -97,7 +97,7 @@ env_lang = ENV.fetch('LANG', nil) if env_lang !~ /(utf8|utf-8)/i print_warning "Warning: System language $LANG '#{env_lang}' does not appear to be UTF-8 compatible." if env_lang =~ /\A([a-z]+_[a-z]+)\./i - country = $1 + country = Regexp.last_match(1) print_more "Try: export LANG=#{country}.utf8" end end From 48bef7bab69aa460afa0d143f6e82f154edfd83b Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sat, 15 Nov 2025 16:03:25 +0530 Subject: [PATCH 82/85] rubocop --only Style/YAMLFileRead -a --- Rakefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Rakefile b/Rakefile index 3b96056c55..aad5620a44 100644 --- a/Rakefile +++ b/Rakefile @@ -128,7 +128,7 @@ task beef_start: 'beef' do test_pass = ENV['TEST_BEEF_PASS'] || 'bad_fred_no_access' # write a rake config file for beef - config = YAML.safe_load(File.read('./config.yaml')) + config = YAML.safe_load_file('./config.yaml') config['beef']['credentials']['user'] = test_user config['beef']['credentials']['passwd'] = test_pass Dir.mkdir('tmp') unless Dir.exist?('tmp') From 9769be2622b7e97e6ec55ebd9a4342ea8ed255e2 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sun, 16 Nov 2025 12:39:32 +0530 Subject: [PATCH 83/85] Address CodeQL feedback --- test/integration/ts_integration.rb | 2 +- test/thirdparty/msf/unit/ts_metasploit.rb | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/test/integration/ts_integration.rb b/test/integration/ts_integration.rb index 5dead34497..406f418b1c 100644 --- a/test/integration/ts_integration.rb +++ b/test/integration/ts_integration.rb @@ -28,7 +28,7 @@ class TS_BeefIntegrationTests def self.suite - suite = Test::Unit::TestSuite.new(name='BeEF Integration Test Suite') + suite = Test::Unit::TestSuite.new('BeEF Integration Test Suite') suite << TC_CheckEnvironment.suite suite << TC_Login.suite suite << TC_DebugModules.suite diff --git a/test/thirdparty/msf/unit/ts_metasploit.rb b/test/thirdparty/msf/unit/ts_metasploit.rb index dc16af3f45..fc936a9694 100644 --- a/test/thirdparty/msf/unit/ts_metasploit.rb +++ b/test/thirdparty/msf/unit/ts_metasploit.rb @@ -21,7 +21,7 @@ class TS_BeefTests def self.suite - suite = Test::Unit::TestSuite.new(name='BeEF Metasploit Test Suite') + suite = Test::Unit::TestSuite.new('BeEF Metasploit Test Suite') suite << TC_CheckEnvironment.suite suite << TC_Metasploit.suite @@ -30,4 +30,3 @@ def self.suite end Test::Unit::UI::Console::TestRunner.run(TS_BeefTests) - From 6601d0ccab970d694e6baca2c7e5afa14e3793f9 Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sun, 16 Nov 2025 12:17:35 +0530 Subject: [PATCH 84/85] Run RuboCop in CI --- .github/workflows/lint.yml | 36 +++++++++++++++ .../{github_actions.yml => test.yml} | 46 ++++++++++--------- Gemfile | 9 ++-- 3 files changed, 66 insertions(+), 25 deletions(-) create mode 100644 .github/workflows/lint.yml rename .github/workflows/{github_actions.yml => test.yml} (50%) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000000..c8d769bba6 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,36 @@ +name: "RuboCop" + +on: + pull_request: + branches: [master] + +jobs: + rubocop: + name: "RuboCop Analysis" + runs-on: ubuntu-latest + steps: + - name: "Checkout the repository" + uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 2 + + - name: "Update and Install Dependencies" + run: | + sudo apt update + sudo apt install libcurl4 libcurl4-openssl-dev + + - name: "Setting up Ruby" + uses: ruby/setup-ruby@v1 + with: + bundler-cache: true + + - name: "Configure Bundle testing and install gems" + run: | + bundle config unset --local without + bundle config set --local with 'development' + bundle install + + - name: "Run RuboCop" + run: | + bundle exec rubocop --display-only-safe-correctable diff --git a/.github/workflows/github_actions.yml b/.github/workflows/test.yml similarity index 50% rename from .github/workflows/github_actions.yml rename to .github/workflows/test.yml index 880302da3b..7c6e195ed8 100644 --- a/.github/workflows/github_actions.yml +++ b/.github/workflows/test.yml @@ -1,55 +1,57 @@ -name: 'BrowserStack Test' +name: "BrowserStack Test" on: pull_request_target: - branches: [ master ] - -jobs: + branches: [master] + +jobs: ubuntu-job: - name: 'BrowserStack Test on Ubuntu' - runs-on: ubuntu-latest # Can be self-hosted runner also + name: "BrowserStack Test on Ubuntu" + runs-on: ubuntu-latest # Can be self-hosted runner also environment: name: Integrate Pull Request - env: + env: GITACTIONS: true steps: - - - name: 'BrowserStack Env Setup' # Invokes the setup-env action + - name: "BrowserStack Env Setup" # Invokes the setup-env action uses: browserstack/github-actions/setup-env@master with: - username: ${{ secrets.BROWSERSTACK_USERNAME }} + username: ${{ secrets.BROWSERSTACK_USERNAME }} access-key: ${{ secrets.BROWSERSTACK_ACCESS_KEY }} - - name: 'BrowserStack Local Tunnel Setup' # Invokes the setup-local action + - name: "BrowserStack Local Tunnel Setup" # Invokes the setup-local action uses: browserstack/github-actions/setup-local@master with: local-testing: start local-identifier: random - - name: 'Checkout the repository' + - name: "Checkout the repository" uses: actions/checkout@v4 with: ref: ${{ github.event.pull_request.head.sha }} fetch-depth: 2 - - name: 'Setting up Ruby' - uses: ruby/setup-ruby@v1 - # Ruby version is defined in .ruby-version file - - - name: 'Update and Install Dependencies' + - name: "Update and Install Dependencies" run: | sudo apt update sudo apt install libcurl4 libcurl4-openssl-dev - - name: 'Configure Bundle testing and install gems' + + - name: "Setting up Ruby" + uses: ruby/setup-ruby@v1 + with: + bundler-cache: true + + - name: "Configure Bundle testing and install gems" run: | bundle config unset --local without - bundle config set --local with 'test' 'development' + bundle config set --local with 'test' bundle install - - name: 'Run BrowserStack simple verification' + + - name: "Run BrowserStack simple verification" run: | bundle exec rake browserstack --trace - - name: 'BrowserStackLocal Stop' # Terminating the BrowserStackLocal tunnel connection + - name: "BrowserStackLocal Stop" # Terminating the BrowserStackLocal tunnel connection uses: browserstack/github-actions/setup-local@master with: - local-testing: stop \ No newline at end of file + local-testing: stop diff --git a/Gemfile b/Gemfile index 63ebde030a..3771583bed 100644 --- a/Gemfile +++ b/Gemfile @@ -4,6 +4,8 @@ # See the file 'doc/COPYING' for copying permission # +source 'https://rubygems.org' + gem 'net-smtp', require: false gem 'json' @@ -24,7 +26,6 @@ gem 'rake', '~> 13.3' gem 'activerecord', '~> 8.1' gem 'otr-activerecord', '~> 2.6.0' gem 'sqlite3', '~> 2.8' -gem 'rubocop', '~> 1.81.7', require: false # Geolocation support group :geoip do @@ -59,6 +60,10 @@ group :ext_qrcode do gem 'qr4r', '~> 0.6.1' end +group :development do + gem 'rubocop', '~> 1.81.7', require: false +end + # For running unit tests group :test do gem 'test-unit-full', '~> 0.0.5' @@ -86,5 +91,3 @@ group :test do # sudo port install libxml2 libxslt gem 'capybara', '~> 3.40' end - -source 'https://rubygems.org' From 66531f066fe4069857a66b333b0d8736b70f532b Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Sun, 16 Nov 2025 20:37:04 +0530 Subject: [PATCH 85/85] Exclude vendor/**/* from RuboCop --- .rubocop.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.rubocop.yml b/.rubocop.yml index 2eef5411f6..f0c700d100 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -4,6 +4,7 @@ AllCops: NewCops: enable Exclude: + - "vendor/**/*" - "tools/**/*" - "spec/**/*" - "test/**/*"