beefproject / beef

The Browser Exploitation Framework Project
https://beefproject.com
9.74k stars 2.16k forks source link

configuration.rb:202: undefined method `[]' for nil:NilClass (NoMethodError) #2367

Closed catchmeifyoucaan closed 2 years ago

catchmeifyoucaan commented 2 years ago

Submit Issue

Verify first that your issue/request has not been posted previously:

Ensure you're using the latest version of BeEF.

Please do your best to provide as much information as possible. It will help substantially if you can enable and provide debugging logs with your issue. Instructions for enabling debugging logs are below:

  1. In the config.yaml file of your BeEF root folder set debug and client_debug (lines 11 & 13 respectively) to true
    • If using a standard installation of beef-xss the root folder will typically be /usr/share/beef-xss
  2. Reproduce your error
  3. Retrieve your client-side logs from your browser's developer console (Ctrl + Shift + I)
  4. Retrieve your server-side logs from ~/.beef/beef.log
  5. If using beef-xss: Retrieve your service logs using journalctl -u beef-xss

Thank you, this will greatly aid us in identifying the root cause of your issue :)

If we request additional information and we don't hear back from you within a week, we will be closing the ticket off. Feel free to open it back up if you continue to have issues.

Summary

Q: Please provide a brief summary of the issue that you experienced. ./beef
[22:55:32][!] Fatal Error: cannot load configuration file '/home/surprise/beef/./config.yaml' : undefined method get' for BeEF::Core::Configuration:Class Did you mean? gem [22:55:32][!] ["/home/surprise/beef/core/ruby/print.rb:39:inprint_debug'", "/home/surprise/beef/core/main/configuration.rb:49:in rescue in load'", "/home/surprise/beef/core/main/configuration.rb:43:inload'", "/home/surprise/beef/core/main/configuration.rb:28:in initialize'", "./beef:83:innew'", "./beef:83:in <main>'"] Traceback (most recent call last): 4: from ./beef:91:in

' 3: from /home/surprise/beef/core/main/configuration.rb:201:in get' 2: from /home/surprise/beef/core/main/configuration.rb:201:ininject' 1: from /home/surprise/beef/core/main/configuration.rb:201:in each' /home/surprise/beef/core/main/configuration.rb:202:inblock in get': undefined method `[]' for nil:NilClass (NoMethodError)

Environment

Please identify the environment in which your issue occurred.

  1. BeEF Version:

  2. Ruby Version: Ruby error I think

  3. Browser Details (e.g. Chrome v81.0): Firefox

  4. Operating System (e.g. OSX Catalina): Linux WSL on Windows 10

Configuration

Q: Have you made any changes to your BeEF configuration? Yes

Q: Have you enabled or disabled any BeEF extensions? A:

Expected vs. Actual Behaviour

Expected Behaviour: for beef to start up
Actual Behaviour: shows the above error

Steps to Reproduce

Please provide steps to reproduce this issue.

  1. ./beef

Additional Information

Please provide any additional information which may be useful in resolving this issue, such as debugging output and relevant screen shots. Debug output can be retrieved by following the instructions towards the top of the issue template. it was working all fine but the hook url was showing internal server erro, so i decide to use ngrok with it, this is what i have been getting please

bcoles commented 2 years ago

BeEF Version:

Which version of BeEF?

Ruby Version: Ruby error I think

Which version of Ruby?

Fatal Error: cannot load configuration file '/home/surprise/beef/./config.yaml'

This is usually caused by a malformed config file. Can you post your config file? Be sure to redact anything sensitive (like passwords and possibly hostnames) first.

catchmeifyoucaan commented 2 years ago

#

Copyright (c) 2006-2022 Wade Alcorn - wade@bindshell.net

Browser Exploitation Framework (BeEF) - http://beefproject.com

See the file 'doc/COPYING' for copying permission

#

BeEF Configuration file

beef: version: '0.5.4.0'

More verbose messages (server-side)

debug: true
# More verbose messages (client-side)
client_debug: true
# Used for generating secure tokens
crypto_default_value_length: 80

# Credentials to authenticate in BeEF.
# Used by both the RESTful API and the Admin interface
credentials:
    user:   "**"
    passwd: "**"

# Interface / IP restrictions
restrictions:
    # subnet of IP addresses that can hook to the framework
    permitted_hooking_subnet: ["10.1.0.0/16"]
    # subnet of IP addresses that can connect to the admin UI
    #permitted_ui_subnet: ["127.0.0.1/32", "::1/128"]
    permitted_ui_subnet: ["127.0.0.1/32"]
    # subnet of IP addresses that cannot be hooked by the framework
    excluded_hooking_subnet: []
    # slow API calls to 1 every  api_attempt_delay  seconds
    api_attempt_delay: "0.05"

# HTTP server 
http:
    debug: false #Thin::Logging.debug, very verbose. Prints also full exception stack trace.
    host: "0.0.0.0"
    port: "3000"

    # Decrease this setting to 1,000 (ms) if you want more responsiveness
    #  when sending modules and retrieving results.
    # NOTE: A poll timeout of less than 5,000 (ms) might impact performance
    #  when hooking lots of browsers (50+).
    # Enabling WebSockets is generally better (beef.websocket.enable)
    xhr_poll_timeout: 1000

    # Host Name / Domain Name
    # If you want BeEF to be accessible via hostname or domain name (ie, DynDNS),
    # These settings will be used to create a public facing URL
    # This public facing URL will be used for all hook related calls
    # set the public setting below:
    # public:

host: "http://7464-197-221-212-40.ngrok.io"

port: "3000" # public port will default to 80 if no https 443 if https

                  # and local if not set but there is a public host

https: true # true/false

    # Reverse Proxy / NAT
    # If you want BeEF to be accessible behind a reverse proxy or NAT,
    #   set both the publicly accessible hostname/IP address and port below:
    # NOTE: Allowing the reverse proxy will enable a vulnerability where the ui/panel can be spoofed
    #   by altering the X-FORWARDED-FOR ip address in the request header.
    allow_reverse_proxy: false

    # Hook
   dns: "localhost" #Address of DNS server
    hook_file: "/hook.js"
    hook_session_name: "BEEFHOOK"
    session_cookie_name: "BEEFESSION"

    # Allow one or multiple origins to access the RESTful API using CORS
    # For multiple origins use: "http://browserhacker.com, http://domain2.com"
    restful_api:
        allow_cors: false
        cors_allowed_domains: "http://browserhacker.com"

    # Prefer WebSockets over XHR-polling when possible.
    websocket:
        enable: false
        port: 61985 # WS: good success rate through proxies
        # Use encrypted 'WebSocketSecure'
        # NOTE: works only on HTTPS domains and with HTTPS support enabled in BeEF
        secure: true
        secure_port: 61986 # WSSecure
        ws_poll_timeout: 5000 # poll BeEF every x second, this affects how often the browser can have a command execute on it
        ws_connect_timeout: 500 # useful to help fingerprinting finish before establishing the WS channel

    # Imitate a specified web server (default root page, 404 default error page, 'Server' HTTP response header)
    web_server_imitation:
        enable: true
        type: "apache" # Supported: apache, iis, nginx
        hook_404: true # inject BeEF hook in HTTP 404 responses
        hook_root: true # inject BeEF hook in the server home page
    # Experimental HTTPS support for the hook / admin / all other Thin managed web services
    https:
        enable: false
        # Enabled this config setting if you're external facing uri is using https
        public_enabled: false
        # In production environments, be sure to use a valid certificate signed for the value
        # used in beef.http.public (the domain name of the server where you run BeEF)
        key: "beef_key.pem"
        cert: "beef_cert.pem"

database:
    file: "beef.db"

# Autorun Rule Engine
autorun:
    # this is used when rule chain_mode type is nested-forward, needed as command results are checked via setInterval
    # to ensure that we can wait for async command results. The timeout is needed to prevent infinite loops or eventually
    # continue execution regardless of results.
    # If you're chaining multiple async modules, and you expect them to complete in more than 5 seconds, increase the timeout.
    result_poll_interval: 300
    result_poll_timeout: 5000

    # If the modules doesn't return status/results and timeout exceeded, continue anyway with the chain.
    # This is useful to call modules (nested-forward chain mode) that are not returning their status/results.
    continue_after_timeout: true

# Enables DNS lookups on zombie IP addresses
dns_hostname_lookup: true

# IP Geolocation
geoip:
    enable: true
    # GeoLite2 City database created by MaxMind, available from https://www.maxmind.com
    database: '/usr/share/GeoIP/GeoLite2-City.mmdb'

# Integration with PhishingFrenzy
# If enabled BeEF will try to get the UID parameter value from the hooked URI, as this is used by PhishingFrenzy
# to uniquely identify the victims. In this way you can easily associate phishing emails with hooked browser.
integration:
    phishing_frenzy:
        enable: false

# You may override default extension configuration parameters here
# Note: additional experimental extensions are available in the 'extensions' directory
#       and can be enabled via their respective 'config.yaml' file
extension:
    admin_ui:
        enable: true
        base_path: "/ui"
    demos:
        enable: true
    events:
        enable: true
    evasion:
        enable: false
    requester:
        enable: true
    proxy:
        enable: true
    network:
        enable: true
    metasploit:
        enable: false
    social_engineering:
        enable: true
    xssrays:
        enable: true

ruby version: ruby 2.7.4p191 (2021-07-07 revision a21a3b7d23) [x86_64-linux-gnu]

latest beef version

bcoles commented 2 years ago

The config file is in YAML format. Whitespace is important.

The dns key is not vertically aligned correctly.

bcoles commented 2 years ago

Also, as far as I'm aware, the dns key does nothing. I have no idea why it is in your config file.

catchmeifyoucaan commented 2 years ago

thank u so much, i just corrected that and got this little error now [23:13:32][!] Warning: System language $LANG '' does not appear to be UTF-8 compatible.
Traceback (most recent call last):
./beef:119:in <main>': undefined methodvalidate' for BeEF::Core::Configuration:Class (NoMethodError)

catchmeifyoucaan commented 2 years ago

okay, ill remove the dns key now

catchmeifyoucaan commented 2 years ago

thank i remove the dns key but the error is still there [23:15:42][!] Warning: System language $LANG '' does not appear to be UTF-8 compatible. Traceback (most recent call last): ./beef:119:in <main>': undefined methodvalidate' for BeEF::Core::Configuration:Class (NoMethodError)

bcoles commented 2 years ago

./beef:119:in

': undefined method validate' for BeEF::Core::Configuration:Class (NoMethodError)

Strange. There's no immediately obvious reason why this would fail.

You could try removing these lines from beef, but that will likely be hiding another bug.

https://github.com/beefproject/beef/blob/5fdd96f5761dfd0bfe36b9e24ab390c29194e349/beef#L116-L121

catchmeifyoucaan commented 2 years ago

sorry, but i dont see anything like this in config.yaml, where should i make the changes, under what configuration

bcoles commented 2 years ago

sorry, but i dont see anything like this in config.yaml, where should i make the changes, under what configuration

It's code in the beef file.

catchmeifyoucaan commented 2 years ago

after i deleted those lines, it shows this again Traceback (most recent call last): 4: from ./beef:119:in <main>' 3: from /home/surprise/beef/core/main/configuration.rb:201:inget' 2: from /home/surprise/beef/core/main/configuration.rb:201:in inject' 1: from /home/surprise/beef/core/main/configuration.rb:201:ineach' /home/surprise/beef/core/main/configuration.rb:202:in block in get': undefined method[]' for nil:NilClass (NoMethodError)

bcoles commented 2 years ago

after i deleted those lines, it shows this again

Have you made any other changes to the config file apart from removing the dns key?

I'm not sure how that key ended up in your config file in the first place.

That error implies hat parsing the configuration file has failed. If you've made changes, can you post your config file again?

Admittedly the error handling sucks. There's no indication of which key is causing the error. It is possible, although unlikely, that the error is triggered by a misconfigured file for one of the extensions. Have you modified any of the config.yaml files in any of the extensions?

catchmeifyoucaan commented 2 years ago

#

Copyright (c) 2006-2022 Wade Alcorn - wade@bindshell.net

Browser Exploitation Framework (BeEF) - http://beefproject.com

See the file 'doc/COPYING' for copying permission

#

BeEF Configuration file

beef: version: '0.5.4.0'

More verbose messages (server-side)

debug: true
# More verbose messages (client-side)
client_debug: true
# Used for generating secure tokens
crypto_default_value_length: 80

# Credentials to authenticate in BeEF.
# Used by both the RESTful API and the Admin interface
credentials:
    user:   "surprise"
    passwd: "surprise"

# Interface / IP restrictions
restrictions:
    # subnet of IP addresses that can hook to the framework
    permitted_hooking_subnet: ["10.1.0.0/16"]
    # subnet of IP addresses that can connect to the admin UI
    #permitted_ui_subnet: ["127.0.0.1/32", "::1/128"]
    permitted_ui_subnet: ["127.0.0.1/32"]
    # subnet of IP addresses that cannot be hooked by the framework
    excluded_hooking_subnet: []
    # slow API calls to 1 every  api_attempt_delay  seconds
    api_attempt_delay: "0.05"

# HTTP server 
http:
    debug: false #Thin::Logging.debug, very verbose. Prints also full exception stack trace.
    host: "0.0.0.0"
    port: "3000"

    # Decrease this setting to 1,000 (ms) if you want more responsiveness
    #  when sending modules and retrieving results.
    # NOTE: A poll timeout of less than 5,000 (ms) might impact performance
    #  when hooking lots of browsers (50+).
    # Enabling WebSockets is generally better (beef.websocket.enable)
    xhr_poll_timeout: 1000

    # Host Name / Domain Name
    # If you want BeEF to be accessible via hostname or domain name (ie, DynDNS),
    # These settings will be used to create a public facing URL
    # This public facing URL will be used for all hook related calls
    # set the public setting below:
    # public:
    host: "http://7464-197-221-212-40.ngrok.io"
    port: "3000" # public port will default to 80 if no https 443 if https 
                  # and local if not set but there is a public host
    https: true # true/false

    # Reverse Proxy / NAT
    # If you want BeEF to be accessible behind a reverse proxy or NAT,
    #   set both the publicly accessible hostname/IP address and port below:
    # NOTE: Allowing the reverse proxy will enable a vulnerability where the ui/panel can be spoofed
    #   by altering the X-FORWARDED-FOR ip address in the request header.
    allow_reverse_proxy: false

    # Hook
    hook_file: "/hook.js"
    hook_session_name: "BEEFHOOK"
    session_cookie_name: "BEEFESSION"

    # Allow one or multiple origins to access the RESTful API using CORS
    # For multiple origins use: "http://browserhacker.com, http://domain2.com"
    restful_api:
        allow_cors: false
        cors_allowed_domains: "http://browserhacker.com"

    # Prefer WebSockets over XHR-polling when possible.
    websocket:
        enable: false
        port: 61985 # WS: good success rate through proxies
        # Use encrypted 'WebSocketSecure'
        # NOTE: works only on HTTPS domains and with HTTPS support enabled in BeEF
        secure: true
        secure_port: 61986 # WSSecure
        ws_poll_timeout: 5000 # poll BeEF every x second, this affects how often the browser can have a command execute on it
        ws_connect_timeout: 500 # useful to help fingerprinting finish before establishing the WS channel

    # Imitate a specified web server (default root page, 404 default error page, 'Server' HTTP response header)
    web_server_imitation:
        enable: true
        type: "apache" # Supported: apache, iis, nginx
        hook_404: true # inject BeEF hook in HTTP 404 responses
        hook_root: true # inject BeEF hook in the server home page
    # Experimental HTTPS support for the hook / admin / all other Thin managed web services
    https:
        enable: false
        # Enabled this config setting if you're external facing uri is using https
        public_enabled: false
        # In production environments, be sure to use a valid certificate signed for the value
        # used in beef.http.public (the domain name of the server where you run BeEF)
        key: "beef_key.pem"
        cert: "beef_cert.pem"

database:
    file: "beef.db"

# Autorun Rule Engine
autorun:
    # this is used when rule chain_mode type is nested-forward, needed as command results are checked via setInterval
    # to ensure that we can wait for async command results. The timeout is needed to prevent infinite loops or eventually
    # continue execution regardless of results.
    # If you're chaining multiple async modules, and you expect them to complete in more than 5 seconds, increase the timeout.
    result_poll_interval: 300
    result_poll_timeout: 5000

    # If the modules doesn't return status/results and timeout exceeded, continue anyway with the chain.
    # This is useful to call modules (nested-forward chain mode) that are not returning their status/results.
    continue_after_timeout: true

# Enables DNS lookups on zombie IP addresses
dns_hostname_lookup: true

# IP Geolocation
geoip:
    enable: true
    # GeoLite2 City database created by MaxMind, available from https://www.maxmind.com
    database: '/usr/share/GeoIP/GeoLite2-City.mmdb'

# Integration with PhishingFrenzy
# If enabled BeEF will try to get the UID parameter value from the hooked URI, as this is used by PhishingFrenzy
# to uniquely identify the victims. In this way you can easily associate phishing emails with hooked browser.
integration:
    phishing_frenzy:
        enable: false

# You may override default extension configuration parameters here
# Note: additional experimental extensions are available in the 'extensions' directory
#       and can be enabled via their respective 'config.yaml' file
extension:
    admin_ui:
        enable: true
        base_path: "/ui"
    demos:
        enable: true
    events:
        enable: true
    evasion:
        enable: false
    requester:
        enable: true
    proxy:
        enable: true
    network:
        enable: true
    metasploit:
        enable: false
    social_engineering:
        enable: true
    xssrays:
        enable: true

no, i have not made any changes after i deleted the dns, and i added it from a tutorial i saw on youtube when the hook link wasnt working, beef was working fine before all of this, just the hook. pleaswe

catchmeifyoucaan commented 2 years ago

!/usr/bin/env ruby

#

Copyright (c) 2006-2022 Wade Alcorn - wade@bindshell.net

Browser Exploitation Framework (BeEF) - http://beefproject.com

See the file 'doc/COPYING' for copying permission

#

#

@note stop Fixnum deprecation warning from being displayed

# $VERBOSE = nil

#

@note Version check to ensure BeEF is running Ruby 2.7+

# min_ruby_version = '2.7' if RUBY_VERSION < min_ruby_version puts puts "Ruby version #{RUBY_VERSION} is no longer supported. Please upgrade to Ruby version #{min_ruby_version} or later." puts exit 1 end

#

@note Platform check to ensure BeEF is not running on Windows

# if RUBY_PLATFORM.downcase.include?('mswin') || RUBY_PLATFORM.downcase.include?('mingw') puts puts "Ruby platform #{RUBY_PLATFORM} is not supported." puts exit 1 end

#

@note set load path, application root directory and user preferences directory

# $root_dir = File.join(File.expand_path(File.dirname(File.realpath(FILE))), '.') $:.unshift($root_dir) $home_dir = File.expand_path("#{Dir.home}/.beef/", FILE).freeze

#

@note Require core loader

# require 'core/loader' require 'timeout'

#

@note Ask user if they would like to update beef

# if File.exist?("#{$root_dir}git") && BeEF::Core::Console::CommandLine.parse[:update_disabled] == false if BeEF::Core::Console::CommandLine.parse[:update_auto] == true print 'Checking latest BeEF repository and updating' git pull && bundle elsif git rev-parse master != git rev-parse origin/master begin Timeout.timeout(5) do puts '-- BeEF Update Available --' print 'Would you like to update to lastest version? y/n: ' response = gets git pull && bundle if response&.strip == 'y' end rescue Timeout::Error puts "\nUpdate Skipped with input timeout" end end end

#

@note Create ~/.beef/

# begin FileUtils.mkdir_p($home_dir) unless File.directory?($home_dir) rescue => e print_error "Could not create '#{$home_dir}': #{e.message}" exit 1 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") else config = BeEF::Core::Configuration.new("#{BeEF::Core::Console::CommandLine.parse[:ext_config]}") end

#

@note set log level

# 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'] if env_lang !~ /(utf8|utf-8)/i print_warning "Warning: System language $LANG '#{env_lang}' does not appear to be UTF-8 compatible." if envlang =~ /\A([a-z]+[a-z]+)./i country = $1 print_more "Try: export LANG=#{country}.utf8" end end

#

@note Check if port and WebSocket port need to be updated from command line parameters

# unless BeEF::Core::Console::CommandLine.parse[:port].empty? config.set('beef.http.port', BeEF::Core::Console::CommandLine.parse[:port]) end

unless BeEF::Core::Console::CommandLine.parse[:ws_port].empty? config.set('beef.http.websocket.port', BeEF::Core::Console::CommandLine.parse[:ws_port]) 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" exit 1 end

#

@note Validate beef.http.public and beef.http.public_port

# unless config.get('beef.http.public.host').to_s.eql?('') || BeEF::Filters.is_valid_hostname?(config.get('beef.http.public.host')) print_error "ERROR: Invalid public hostname: #{config.get('beef.http.public.host')}" exit 1 end

unless config.get('beef.http.public.port').to_s.eql?('') || BeEF::Filters.is_valid_port?(config.get('beef.http.public.port')) print_error "ERROR: Invalid public port: #{config.get('beef.http.public.port')}" exit 1 end

#

@note After the BeEF core is loaded, bootstrap the rest of the framework internals

# require 'core/bootstrap'

#

@note Prints the BeEF ascii art if the -a flag was passed

# if BeEF::Core::Console::CommandLine.parse[:ascii_art] == true BeEF::Core::Console::Banners.print_ascii_art end

#

@note Prints BeEF welcome message

# BeEF::Core::Console::Banners.print_welcome_msg

#

@note Loads enabled extensions

# BeEF::Extensions.load

#

@note Loads enabled modules

# BeEF::Modules.load

#

@note Disable reverse DNS

# Socket.do_not_reverse_lookup = true

#

@note Database setup

# #

@note Load the database

# db_file = config.get('beef.database.file')

@note Resets the database if the -x flag was passed

if BeEF::Core::Console::CommandLine.parse[:resetdb] print_info 'Resetting the database for BeEF.' File.delete(db_file) if File.exists?(db_file) end

Connect to DB

ActiveRecord::Base.logger = nil OTR::ActiveRecord.migrations_paths = [File.join('core', 'main', 'ar-migrations')] 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') OTR::ActiveRecord.establish_connection! end

Migrate (if required)

context = ActiveRecord::Migration.new.migration_context if context.needs_migration? ActiveRecord::Migrator.new(:up, context.migrations, context.schema_migration).migrate end #

@note Extensions may take a moment to load, thus we print out a please wait message

# print_info 'BeEF is loading. Wait a few seconds...'

#

@note Execute migration procedure, checks for new modules

# BeEF::Core::Migration.instance.update_db!

#

@note Create HTTP Server and prepare it to run

# http_hook_server = BeEF::Core::Server.instance http_hook_server.prepare

#

@note Prints information back to the user before running the server

# BeEF::Core::Console::Banners.print_loaded_extensions BeEF::Core::Console::Banners.print_loaded_modules BeEF::Core::Console::Banners.print_network_interfaces_count BeEF::Core::Console::Banners.print_network_interfaces_routes

#

@note Prints the API key needed to use the RESTful API

# print_info "RESTful API key: #{BeEF::Core::Crypto::api_token}"

#

@note Load the GeoIP database

# BeEF::Core::GeoIp.instance

#

@note Call the API method 'pre_http_start'

# BeEF::API::Registrar.instance.fire(BeEF::API::Server, 'pre_http_start', http_hook_server)

#

@note Load any ARE (Autorun Rule Engine) rules scanning the /arerules/enabled directory

# BeEF::Core::AutorunEngine::RuleLoader.instance.load_directory

#

@note Start the WebSocket server

# if config.get("beef.http.websocket.enable") BeEF::Core::Websocket::Websocket.instance BeEF::Core::Console::Banners.print_websocket_servers end

#

@note Start HTTP server

# print_info 'BeEF server started (press control+c to stop)' http_hook_server.start My beef configuration, incase the error wasnt in the config file

catchmeifyoucaan commented 2 years ago

#

Copyright (c) 2006-2022 Wade Alcorn - wade@bindshell.net

Browser Exploitation Framework (BeEF) - http://beefproject.com

See the file 'doc/COPYING' for copying permission

#

module BeEF module Core class Configuration attr_accessor :config

  # antisnatchor: still a singleton, but implemented by hand because we want to have only one instance
  # of the Configuration object while having the possibility to specify a parameter to the constructor.
  # This is  why we don't use anymore the default Ruby implementation -> include Singleton
  def self.instance
    @@instance = self
  end

  # Loads the default configuration system
  # @param [String] configuration_file Configuration file to be loaded,
  #        by default loads $root_dir/config.yaml
  def initialize(config)
    raise TypeError, "'config' needs to be a string" unless config.string?
    raise TypeError, "Configuration file '#{config}' cannot be found" unless File.exist? config

    begin
      # open base config
      @config = load(config)
      # set default value if key? does not exist
      @config.default = nil
      @@config = config
    rescue StandardError => e
      print_error "Fatal Error: cannot load configuration file '#{config}' : #{e.message}"
      print_error e.backtrace
    end

    @@instance = self
  end

  # Loads yaml file
  # @param [String] file YAML file to be loaded
  # @return [Hash] YAML formatted hash
  def load (file)
    return nil unless File.exist? file

    raw = File.read file
    YAML.safe_load raw
  rescue StandardError => e
    print_debug "Unable to load configuration file '#{file}' : #{e.message}"
    print_error e.backtrace
  end

  #
  # @note balidate the configuration file
  #
  def validate
    if @config.empty?
      print_error 'Configuration file is empty'
      return
    end

    if @config['beef'].nil?
      print_error "Configuration file is malformed: 'beef' is nil"
      return
    end

    if @config['beef']['credentials'].nil?
      print_error "Configuration file is malformed: 'beef.credentials' is nil"
      return
    end

    if @config['beef']['http'].nil?
      print_error "Configuration file is malformed: 'beef.http' is nil"
      return
    end

    return unless validate_public_config_variable?(@config)

    if @config['beef']['http']['public_port']
      print_error 'Config path beef.http.public_port is deprecated.'
      print_error 'Please use the new format for public variables found'
      print_error 'https://github.com/beefproject/beef/wiki/Configuration#web-server-configuration'
      return
    end

    true
  end

  #
  # Returns the configuration value for the http server host
  # If nothing is set it should default to 0.0.0.0 (all interfaces)
  def local_host
    get('beef.http.host') || '0.0.0.0'
  end

  #
  # Returns the configuration value for the http server port
  # If nothing is set it should default to 3000
  def local_port
    get('beef.http.port') || '3000'
  end

  #
  # Return the local protocol
  # if nothing is set default to http
  def local_proto
    local_https_enabled ? 'https' : 'http'
  end

  #
  # Returns the configuration value for the local https enabled
  # If nothing is set it should default to false
  def local_https_enabled
    get('beef.http.https.enable') || false
  end

  #
  # Returns the configuration value for the http server host
  def public_host
    get('beef.http.public.host')
  end

  #
  # Returns the beef host which is used by external resources
  # e.g. hooked browsers
  def beef_host
    public_host || local_host
  end

  #
  # Returns the beef port which is used by external resource
  # e.g. hooked browsers
  def beef_port
    public_port || local_port
  end

  def public_enabled?
    !get('beef.http.public.host').nil?
  end

  #
  # Returns the beef protocol that is used by external resources
  # e.g. hooked browsers
  def beef_proto
    if public_enabled? && public_https_enabled?
      'https'
    elsif public_enabled? && !public_https_enabled?
      'http'
    elsif !public_enabled?
      local_proto
    end
  end

  #
  # Returns the beef scheme://host:port for external resources
  # e.g. hooked browsers
  def beef_url_str
    "#{beef_proto}://#{beef_host}:#{beef_port}"
  end

  # Returns the hool path value stored in the config file
  #
  # @return [String] hook file path
  def hook_file_path
    get('beef.http.hook_file') || '/hook.js'
  end

  # Returns the url to the hook file
  #
  # @return [String] the url string
  def hook_url
    "#{beef_url_str}#{hook_file_path}"
  end

  # Returns the configuration value for the http server port
  # If nothing is set it should default to 3000
  def public_port
    return get('beef.http.public.port') unless get('beef.http.public.port').nil?

    return '443' if public_https_enabled?
    return '80' unless public_host.nil?

    nil
  end

  #
  # Returns the configuration value for the local https enabled
  # If nothing is set it should default to false
  def public_https_enabled?
    get('beef.http.public.https') || false
  end

  #
  # Returns the value of a selected key in the configuration file.
  # @param [String] key Key of configuration item
  # @return [Hash|String] The resulting value stored against the 'key'
  #
  def get(key)
    subkeys = key.split('.')
    lastkey = subkeys.pop
    subhash = subkeys.inject(@config) do |hash, k|
    hash [:k]
    end
    return nil if subhash.nil?

    subhash.key?(lastkey) ? subhash [lastkey] : nil
  end

  #
  # Sets the give key value pair to the config instance
  # @param [String] key The configuration key
  # @param value The value to be stored against the 'key'
  # @return [Boolean] If the store procedure was successful
  #
  def set(key, value)
    subkeys = key.split('.').reverse
    return false if subkeys.empty?

    hash = { subkeys.shift.to_s => value }
    subkeys.each { |v| hash = { v.to_s => hash } }
    @config = @config.deep_merge hash
    true
  end

  #
  # Clears the given key hash
  # @param [String] key Configuration key to be cleared
  # @return [Boolean] If the configuration key was cleared
  #
  def clear(key)
    subkeys = key.split('.')
    return false if subkeys.empty?

    lastkey = subkeys.pop
    hash = @config
    subkeys.each { |v| hash = hash[v] }
    hash.delete(lastkey).nil? ? false : true
  end

  #
  # Load extensions configurations
  #
  def load_extensions_config
    set('beef.extension', {})
    Dir.glob("#{$root_dir}/extensions/*/config.yaml") do |cf|
      y = load(cf)
      if y.nil?
        print_error "Unable to load extension configuration '#{cf}'"
        next
      end

      y['beef']['extension'][y['beef']['extension'].keys.first]['path'] = cf.gsub(/config\.yaml/, '').gsub(%r{#{$root_dir}/}, '')
      @config = y.deep_merge(@config)
    end
  end

  #
  # Load module configurations
  #
  def load_modules_config
    set('beef.module', {})
    # support nested sub-categories, like browser/hooked_domain/ajax_fingerprint
    module_configs = File.join("#{$root_dir}/modules/**", 'config.yaml')
    Dir.glob(module_configs) do |cf|
      y = load(cf)
      if y.nil?
        print_error "Unable to load module configuration '#{cf}'"
        next
      end

      y['beef']['module'][y['beef']['module'].keys.first]['path'] = cf.gsub('config.yaml', '').gsub(%r{#{$root_dir}/}, '')
      @config = y.deep_merge @config
      # API call for post module config load
      BeEF::API::Registrar.instance.fire(
        BeEF::API::Configuration,
        'module_configuration_load',
        y['beef']['module'].keys.first
      )
    end
  end

  private

  def validate_public_config_variable?(config)
    return true if config['beef']['http']['public'].is_a?(Hash) ||
                   config['beef']['http']['public'].is_a?(NilClass)

    print_error 'Config path beef.http.public is deprecated.'
    print_error 'Please use the new format for public variables found'
    print_error 'https://github.com/beefproject/beef/wiki/Configuration#web-server-configuration'
    false
  end
end

end end

i made little changes to this configuration.rb too. please check them out, beef has been delaying my study for quite a while now

catchmeifyoucaan commented 2 years ago

I'm counting on you @bcoles

bcoles commented 2 years ago

Please use triple backticks to format code. It makes the code much easier to read.

no, i have not made any changes after i deleted the dns, and i added it from a tutorial i saw on youtube when the hook link wasnt working, beef was working fine before all of this, just the hook. pleaswe

I don't understand what that means, but if you've followed some random youtube tutorial and that broke things then that's probably the cause.

i made little changes to this configuration.rb too. please check them out, beef has been delaying my study for quite a while now

If you made "little changes" and now things are broken, and if this is really important to you and is holding you up, then I suggest cloning the repository again and making sure that works. If it works from a clean clone then the issue is clearly one of the changes you've made.

bcoles commented 2 years ago

no, i have not made any changes after i deleted the dns, and i added it from a tutorial i saw on youtube when the hook link wasnt working, beef was working fine before all of this, just the hook. pleaswe

Ok I see the problem. This wasn't in the config file the first time you posted it, but it is in your config file now:

        host: "http://7464-197-221-212-40.ngrok.io"
        port: "3000" # public port will default to 80 if no https 443 if https 
                      # and local if not set but there is a public host
        https: true # true/false

That is incorrect. The host property expects a host not a URL.

        host: "7464-197-221-212-40.ngrok.io"
        port: "3000" # public port will default to 80 if no https 443 if https 
                      # and local if not set but there is a public host
        https: true # true/false
catchmeifyoucaan commented 2 years ago

yes, thats exactly the problem, i wanted to add ngrok so the hook url can work because it shows internal server erro and doesnt hook the browser, im confused, if i want to use with ngrok, whats supposed to be in the host space? or if i have to delete those which ill do now, can you tell me how to make the hook url work pleaseeeeee

bcoles commented 2 years ago

whats supposed to be in the host space?

https://github.com/beefproject/beef/issues/2367#issuecomment-1073533292

catchmeifyoucaan commented 2 years ago

Credentials to authenticate in BeEF.

# Used by both the RESTful API and the Admin interface
credentials:
    user:   "surprise"
    passwd: "surprise"

# Interface / IP restrictions
restrictions:
    # subnet of IP addresses that can hook to the framework
    permitted_hooking_subnet: ["10.1.0.0/16"]
    # subnet of IP addresses that can connect to the admin UI
    #permitted_ui_subnet: ["127.0.0.1/32", "::1/128"]
    permitted_ui_subnet: ["127.0.0.1/32"]
    # subnet of IP addresses that cannot be hooked by the framework
    excluded_hooking_subnet: []
    # slow API calls to 1 every  api_attempt_delay  seconds
    api_attempt_delay: "0.05"

# HTTP server 
http:
    debug: false #Thin::Logging.debug, very verbose. Prints also full exception stack trace.
    host: "0.0.0.0"
    port: "3000"

    # Decrease this setting to 1,000 (ms) if you want more responsiveness
    #  when sending modules and retrieving results.
    # NOTE: A poll timeout of less than 5,000 (ms) might impact performance
    #  when hooking lots of browsers (50+).
    # Enabling WebSockets is generally better (beef.websocket.enable)
    xhr_poll_timeout: 1000

    # Host Name / Domain Name
    # If you want BeEF to be accessible via hostname or domain name (ie, DynDNS),
    # These settings will be used to create a public facing URL
    # This public facing URL will be used for all hook related calls
    # set the public setting below:
    # public:
    # host: "http://7d8b-197-221-212-40.ngrok.io"
    # port: "3000" # public port will default to 80 if no https 443 if https 
                  # and local if not set but there is a public host
    # https: true # true/false

    # Reverse Proxy / NAT
    # If you want BeEF to be accessible behind a reverse proxy or NAT,
    #   set both the publicly accessible hostname/IP address and port below:

see, i just made those lines into comments and i still have same error, since its comment now, its not supposed to have effect on the output of the code

[ 0:01:06][!] Warning: System language $LANG '' does not appear to be UTF-8 compatible. Traceback (most recent call last): 4: from ./beef:119:in <main>' 3: from /home/surprise/beef/core/main/configuration.rb:201:inget' 2: from /home/surprise/beef/core/main/configuration.rb:201:in inject' 1: from /home/surprise/beef/core/main/configuration.rb:201:ineach' /home/surprise/beef/core/main/configuration.rb:202:in block in get': undefined method[]' for nil:NilClass (NoMethodError)

catchmeifyoucaan commented 2 years ago

or do you think i should sudo rm -r beef? and start all over again, if you would be here to help, i'll do it now

bcoles commented 2 years ago

or do you think i should sudo rm -r beef? and start all over again, if you would be here to help, i'll do it now

Please format your code posts using triple backticks.

I'm not going to reverse engineer your changes.

It is really not clear what you're doing especially when you paste excerpts of configuration files, especially when the formatting of those files is important. There's way too many possibilities and it's way too hard to figure out what you've done when you've made "little changes" to core code like the configuration.rb file - suspiciously the exact file where you're getting errors - based on what some random person said in some random youtube video.

I suggest making a backup of your repo. Create a fresh clone. Make changes one by one, and when it breaks you'll know what broke it.

catchmeifyoucaan commented 2 years ago

i made changes to @@instance because it doesnt have a value so i made it @@instance = self, that was the only changes i made to the configuration file. triple back ticks you mean '''?

bcoles commented 2 years ago

if you would be here to help, i'll do it now

I'll be around intermittently for a while.

It's probably a simple issue, it's just not easy to spot with partial files in poorly formatted markdown.

i made changes to @https://github.com/instance because it doesnt have a value so i made it @https://github.com/instance = self

That... doesn't sound right.

triple back ticks you mean '''?

code

catchmeifyoucaan commented 2 years ago
#!/usr/bin/env ruby

#
# Copyright (c) 2006-2022 Wade Alcorn - wade@bindshell.net
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#

#
# @note stop Fixnum deprecation warning from being displayed
#
$VERBOSE = nil

#
# @note Version check to ensure BeEF is running Ruby 2.7+
#
min_ruby_version = '2.7'
if RUBY_VERSION < min_ruby_version
  puts
  puts "Ruby version #{RUBY_VERSION} is no longer supported. Please upgrade to Ruby version #{min_ruby_version} or later."
  puts
  exit 1
end

#
# @note Platform check to ensure BeEF is not running on Windows
#
if RUBY_PLATFORM.downcase.include?('mswin') || RUBY_PLATFORM.downcase.include?('mingw')
  puts
  puts "Ruby platform #{RUBY_PLATFORM} is not supported."
  puts
  exit 1
end

#
# @note set load path, application root directory and user preferences directory
#
$root_dir = File.join(File.expand_path(File.dirname(File.realpath(__FILE__))), '.')
$:.unshift($root_dir)
$home_dir = File.expand_path("#{Dir.home}/.beef/", __FILE__).freeze

#
# @note Require core loader
#
require 'core/loader'
require 'timeout'

#
# @note Ask user if they would like to update beef
#
if File.exist?("#{$root_dir}git") && BeEF::Core::Console::CommandLine.parse[:update_disabled] == false
  if BeEF::Core::Console::CommandLine.parse[:update_auto] == true
    print 'Checking latest BeEF repository and updating'
    `git pull && bundle`
  elsif `git rev-parse master` != `git rev-parse origin/master`
    begin
      Timeout.timeout(5) do
        puts '-- BeEF Update Available --'
        print 'Would you like to update to lastest version? y/n: '
        response = gets
        `git pull && bundle` if response&.strip == 'y'
      end
    rescue Timeout::Error
      puts "\nUpdate Skipped with input timeout"
    end
  end
end

#
# @note Create ~/.beef/
#
begin
  FileUtils.mkdir_p($home_dir) unless File.directory?($home_dir)
rescue => e
  print_error "Could not create '#{$home_dir}': #{e.message}"
  exit 1
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")
else
  config = BeEF::Core::Configuration.new("#{BeEF::Core::Console::CommandLine.parse[:ext_config]}")
end

#
# @note set log level
#
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']
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
    print_more "Try: export LANG=#{country}.utf8"
  end
end

#
# @note Check if port and WebSocket port need to be updated from command line parameters
#
unless BeEF::Core::Console::CommandLine.parse[:port].empty?
  config.set('beef.http.port', BeEF::Core::Console::CommandLine.parse[:port])
end

unless BeEF::Core::Console::CommandLine.parse[:ws_port].empty?
  config.set('beef.http.websocket.port', BeEF::Core::Console::CommandLine.parse[:ws_port])
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"
  exit 1
end

#
# @note Validate beef.http.public and beef.http.public_port
#
unless config.get('beef.http.public.host').to_s.eql?('') || BeEF::Filters.is_valid_hostname?(config.get('beef.http.public.host'))
  print_error "ERROR: Invalid public hostname: #{config.get('beef.http.public.host')}"
  exit 1
end

unless config.get('beef.http.public.port').to_s.eql?('') || BeEF::Filters.is_valid_port?(config.get('beef.http.public.port'))
  print_error "ERROR: Invalid public port: #{config.get('beef.http.public.port')}"
  exit 1
end

#
# @note After the BeEF core is loaded, bootstrap the rest of the framework internals
#
require 'core/bootstrap'

#
# @note Prints the BeEF ascii art if the -a flag was passed
#
if BeEF::Core::Console::CommandLine.parse[:ascii_art] == true
  BeEF::Core::Console::Banners.print_ascii_art
end

#
# @note Prints BeEF welcome message
#
BeEF::Core::Console::Banners.print_welcome_msg

#
# @note Loads enabled extensions
#
BeEF::Extensions.load

#
# @note Loads enabled modules
#
BeEF::Modules.load

#
# @note Disable reverse DNS
#
Socket.do_not_reverse_lookup = true

#
# @note Database setup
#
#
# @note Load the database
#
db_file = config.get('beef.database.file')
# @note Resets the database if the -x flag was passed
if BeEF::Core::Console::CommandLine.parse[:resetdb]
  print_info 'Resetting the database for BeEF.'
  File.delete(db_file) if File.exists?(db_file)
end
# Connect to DB
ActiveRecord::Base.logger = nil
OTR::ActiveRecord.migrations_paths = [File.join('core', 'main', 'ar-migrations')]
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')
  OTR::ActiveRecord.establish_connection!
end
# Migrate (if required)
context = ActiveRecord::Migration.new.migration_context
if context.needs_migration?
  ActiveRecord::Migrator.new(:up, context.migrations, context.schema_migration).migrate
end
#
# @note Extensions may take a moment to load, thus we print out a please wait message
#
print_info 'BeEF is loading. Wait a few seconds...'

#
# @note Execute migration procedure, checks for new modules
#
BeEF::Core::Migration.instance.update_db!

#
# @note Create HTTP Server and prepare it to run
#
http_hook_server = BeEF::Core::Server.instance
http_hook_server.prepare

#
# @note Prints information back to the user before running the server
#
BeEF::Core::Console::Banners.print_loaded_extensions
BeEF::Core::Console::Banners.print_loaded_modules
BeEF::Core::Console::Banners.print_network_interfaces_count
BeEF::Core::Console::Banners.print_network_interfaces_routes

#
# @note Prints the API key needed to use the RESTful API
#
print_info "RESTful API key: #{BeEF::Core::Crypto::api_token}"

#
# @note Load the GeoIP database
#
BeEF::Core::GeoIp.instance

#
# @note Call the API method 'pre_http_start'
#
BeEF::API::Registrar.instance.fire(BeEF::API::Server, 'pre_http_start', http_hook_server)

#
# @note Load any ARE (Autorun Rule Engine) rules scanning the <beef_root>/arerules/enabled directory
#
BeEF::Core::AutorunEngine::RuleLoader.instance.load_directory

#
# @note Start the WebSocket server
#
if config.get("beef.http.websocket.enable")
  BeEF::Core::Websocket::Websocket.instance
  BeEF::Core::Console::Banners.print_websocket_servers
end

#
# @note Start HTTP server
#
print_info 'BeEF server started (press control+c to stop)'
http_hook_server.start

beef configuration, complete

catchmeifyoucaan commented 2 years ago
#
# Copyright (c) 2006-2022 Wade Alcorn - wade@bindshell.net
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
# BeEF Configuration file

beef:
    version: '0.5.4.0'
    # More verbose messages (server-side)
    debug: true
    # More verbose messages (client-side)
    client_debug: true
    # Used for generating secure tokens
    crypto_default_value_length: 80

    # Credentials to authenticate in BeEF.
    # Used by both the RESTful API and the Admin interface
    credentials:
        user:   "**"
        passwd: "*"

    # Interface / IP restrictions
    restrictions:
        # subnet of IP addresses that can hook to the framework
        permitted_hooking_subnet: ["10.1.0.0/16"]
        # subnet of IP addresses that can connect to the admin UI
        #permitted_ui_subnet: ["127.0.0.1/32", "::1/128"]
        permitted_ui_subnet: ["127.0.0.1/32"]
        # subnet of IP addresses that cannot be hooked by the framework
        excluded_hooking_subnet: []
        # slow API calls to 1 every  api_attempt_delay  seconds
        api_attempt_delay: "0.05"

    # HTTP server 
    http:
        debug: false #Thin::Logging.debug, very verbose. Prints also full exception stack trace.
        host: "0.0.0.0"
        port: "3000"

        # Decrease this setting to 1,000 (ms) if you want more responsiveness
        #  when sending modules and retrieving results.
        # NOTE: A poll timeout of less than 5,000 (ms) might impact performance
        #  when hooking lots of browsers (50+).
        # Enabling WebSockets is generally better (beef.websocket.enable)
        xhr_poll_timeout: 1000

        # Host Name / Domain Name
        # If you want BeEF to be accessible via hostname or domain name (ie, DynDNS),
        # These settings will be used to create a public facing URL
        # This public facing URL will be used for all hook related calls
        # set the public setting below:
        # public:
        # host: "http://7d8b-197-221-212-40.ngrok.io"
        # port: "3000" # public port will default to 80 if no https 443 if https 
                      # and local if not set but there is a public host
        # https: true # true/false

        # Reverse Proxy / NAT
        # If you want BeEF to be accessible behind a reverse proxy or NAT,
        #   set both the publicly accessible hostname/IP address and port below:
        # NOTE: Allowing the reverse proxy will enable a vulnerability where the ui/panel can be spoofed
        #   by altering the X-FORWARDED-FOR ip address in the request header.
        allow_reverse_proxy: false

        # Hook
        hook_file: "/hook.js"
        hook_session_name: "BEEFHOOK"

        # Allow one or multiple origins to access the RESTful API using CORS
        # For multiple origins use: "http://browserhacker.com, http://domain2.com"
        restful_api:
            allow_cors: false
            cors_allowed_domains: "http://browserhacker.com"

        # Prefer WebSockets over XHR-polling when possible.
        websocket:
            enable: false
            port: 61985 # WS: good success rate through proxies
            # Use encrypted 'WebSocketSecure'
            # NOTE: works only on HTTPS domains and with HTTPS support enabled in BeEF
            secure: true
            secure_port: 61986 # WSSecure
            ws_poll_timeout: 5000 # poll BeEF every x second, this affects how often the browser can have a command execute on it
            ws_connect_timeout: 500 # useful to help fingerprinting finish before establishing the WS channel

        # Imitate a specified web server (default root page, 404 default error page, 'Server' HTTP response header)
        web_server_imitation:
            enable: true
            type: "apache" # Supported: apache, iis, nginx
            hook_404: true # inject BeEF hook in HTTP 404 responses
            hook_root: true # inject BeEF hook in the server home page
        # Experimental HTTPS support for the hook / admin / all other Thin managed web services
        https:
            enable: false
            # Enabled this config setting if you're external facing uri is using https
            public_enabled: false
            # In production environments, be sure to use a valid certificate signed for the value
            # used in beef.http.public (the domain name of the server where you run BeEF)
            key: "beef_key.pem"
            cert: "beef_cert.pem"

    database:
        file: "beef.db"

    # Autorun Rule Engine
    autorun:
        # this is used when rule chain_mode type is nested-forward, needed as command results are checked via setInterval
        # to ensure that we can wait for async command results. The timeout is needed to prevent infinite loops or eventually
        # continue execution regardless of results.
        # If you're chaining multiple async modules, and you expect them to complete in more than 5 seconds, increase the timeout.
        result_poll_interval: 300
        result_poll_timeout: 5000

        # If the modules doesn't return status/results and timeout exceeded, continue anyway with the chain.
        # This is useful to call modules (nested-forward chain mode) that are not returning their status/results.
        continue_after_timeout: true

    # Enables DNS lookups on zombie IP addresses
    dns_hostname_lookup: true

    # IP Geolocation
    geoip:
        enable: true
        # GeoLite2 City database created by MaxMind, available from https://www.maxmind.com
        database: '/usr/share/GeoIP/GeoLite2-City.mmdb'

    # Integration with PhishingFrenzy
    # If enabled BeEF will try to get the UID parameter value from the hooked URI, as this is used by PhishingFrenzy
    # to uniquely identify the victims. In this way you can easily associate phishing emails with hooked browser.
    integration:
        phishing_frenzy:
            enable: false

    # You may override default extension configuration parameters here
    # Note: additional experimental extensions are available in the 'extensions' directory
    #       and can be enabled via their respective 'config.yaml' file
    extension:
        admin_ui:
            enable: true
            base_path: "/ui"
        demos:
            enable: true
        events:
            enable: true
        evasion:
            enable: false
        requester:
            enable: true
        proxy:
            enable: true
        network:
            enable: true
        metasploit:
            enable: false
        social_engineering:
            enable: true
        xssrays:
            enable: true

config.yaml file

bcoles commented 2 years ago

beef configuration, complete

Are you using beef from git ? Can you use diff files instead? It is much easier to reverse engineer whatever insane thing you've done. You can generate a diff like this:

git diff ./beef

Also, are you starting fresh? Is it working? Or are you trying to repair the existing repo?

Also, that's the beef code, not the configuration file.

catchmeifyoucaan commented 2 years ago
#
# Copyright (c) 2006-2022 Wade Alcorn - wade@bindshell.net
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#

module BeEF
  module Core
    class Configuration
      attr_accessor :config

      # antisnatchor: still a singleton, but implemented by hand because we want to have only one instance
      # of the Configuration object while having the possibility to specify a parameter to the constructor.
      # This is  why we don't use anymore the default Ruby implementation -> include Singleton
      def self.instance
        @@instance = self (** This was initially just instance, i added self because it showed eerror**)
      end

      # Loads the default configuration system
      # @param [String] configuration_file Configuration file to be loaded,
      #        by default loads $root_dir/config.yaml
      def initialize(config)
        raise TypeError, "'config' needs to be a string" unless config.string?
        raise TypeError, "Configuration file '#{config}' cannot be found" unless File.exist? config

        begin
          # open base config
          @config = load(config)
          # set default value if key? does not exist
          @config.default = nil
          @@config = config
        rescue StandardError => e
          print_error "Fatal Error: cannot load configuration file '#{config}' : #{e.message}"
          print_error e.backtrace
        end

        @@instance = self
      end

      # Loads yaml file
      # @param [String] file YAML file to be loaded
      # @return [Hash] YAML formatted hash
      def load (file)
        return nil unless File.exist? file

        raw = File.read file
        YAML.safe_load raw
      rescue StandardError => e
        print_debug "Unable to load configuration file '#{file}' : #{e.message}"
        print_error e.backtrace
      end

      #
      # @note balidate the configuration file
      #
      def validate
        if @config.empty?
          print_error 'Configuration file is empty'
          return
        end

        if @config['beef'].nil?
          print_error "Configuration file is malformed: 'beef' is nil"
          return
        end

        if @config['beef']['credentials'].nil?
          print_error "Configuration file is malformed: 'beef.credentials' is nil"
          return
        end

        if @config['beef']['http'].nil?
          print_error "Configuration file is malformed: 'beef.http' is nil"
          return
        end

        return unless validate_public_config_variable?(@config)

        if @config['beef']['http']['public_port']
          print_error 'Config path beef.http.public_port is deprecated.'
          print_error 'Please use the new format for public variables found'
          print_error 'https://github.com/beefproject/beef/wiki/Configuration#web-server-configuration'
          return
        end

        true
      end

      #
      # Returns the configuration value for the http server host
      # If nothing is set it should default to 0.0.0.0 (all interfaces)
      def local_host
        get('beef.http.host') || '0.0.0.0'
      end

      #
      # Returns the configuration value for the http server port
      # If nothing is set it should default to 3000
      def local_port
        get('beef.http.port') || '3000'
      end

      #
      # Return the local protocol
      # if nothing is set default to http
      def local_proto
        local_https_enabled ? 'https' : 'http'
      end

      #
      # Returns the configuration value for the local https enabled
      # If nothing is set it should default to false
      def local_https_enabled
        get('beef.http.https.enable') || false
      end

      #
      # Returns the configuration value for the http server host
      def public_host
        get('beef.http.public.host')
      end

      #
      # Returns the beef host which is used by external resources
      # e.g. hooked browsers
      def beef_host
        public_host || local_host
      end

      #
      # Returns the beef port which is used by external resource
      # e.g. hooked browsers
      def beef_port
        public_port || local_port
      end

      def public_enabled?
        !get('beef.http.public.host').nil?
      end

      #
      # Returns the beef protocol that is used by external resources
      # e.g. hooked browsers
      def beef_proto
        if public_enabled? && public_https_enabled?
          'https'
        elsif public_enabled? && !public_https_enabled?
          'http'
        elsif !public_enabled?
          local_proto
        end
      end

      #
      # Returns the beef scheme://host:port for external resources
      # e.g. hooked browsers
      def beef_url_str
        "#{beef_proto}://#{beef_host}:#{beef_port}"
      end

      # Returns the hool path value stored in the config file
      #
      # @return [String] hook file path
      def hook_file_path
        get('beef.http.hook_file') || '/hook.js'
      end

      # Returns the url to the hook file
      #
      # @return [String] the url string
      def hook_url
        "#{beef_url_str}#{hook_file_path}"
      end

      # Returns the configuration value for the http server port
      # If nothing is set it should default to 3000
      def public_port
        return get('beef.http.public.port') unless get('beef.http.public.port').nil?

        return '443' if public_https_enabled?
        return '80' unless public_host.nil?

        nil
      end

      #
      # Returns the configuration value for the local https enabled
      # If nothing is set it should default to false
      def public_https_enabled?
        get('beef.http.public.https') || false
      end

      #
      # Returns the value of a selected key in the configuration file.
      # @param [String] key Key of configuration item
      # @return [Hash|String] The resulting value stored against the 'key'
      #
      def get(key)
        subkeys = key.split('.')
        lastkey = subkeys.pop
        subhash = subkeys.inject(@config) do |hash, k|
        hash [:k]
        end
        return nil if subhash.nil?

        subhash.key?(lastkey) ? subhash [lastkey] : nil
      end

      #
      # Sets the give key value pair to the config instance
      # @param [String] key The configuration key
      # @param value The value to be stored against the 'key'
      # @return [Boolean] If the store procedure was successful
      #
      def set(key, value)
        subkeys = key.split('.').reverse
        return false if subkeys.empty?

        hash = { subkeys.shift.to_s => value }
        subkeys.each { |v| hash = { v.to_s => hash } }
        @config = @config.deep_merge hash
        true
      end

      #
      # Clears the given key hash
      # @param [String] key Configuration key to be cleared
      # @return [Boolean] If the configuration key was cleared
      #
      def clear(key)
        subkeys = key.split('.')
        return false if subkeys.empty?

        lastkey = subkeys.pop
        hash = @config
        subkeys.each { |v| hash = hash[v] }
        hash.delete(lastkey).nil? ? false : true
      end

      #
      # Load extensions configurations
      #
      def load_extensions_config
        set('beef.extension', {})
        Dir.glob("#{$root_dir}/extensions/*/config.yaml") do |cf|
          y = load(cf)
          if y.nil?
            print_error "Unable to load extension configuration '#{cf}'"
            next
          end

          y['beef']['extension'][y['beef']['extension'].keys.first]['path'] = cf.gsub(/config\.yaml/, '').gsub(%r{#{$root_dir}/}, '')
          @config = y.deep_merge(@config)
        end
      end

      #
      # Load module configurations
      #
      def load_modules_config
        set('beef.module', {})
        # support nested sub-categories, like browser/hooked_domain/ajax_fingerprint
        module_configs = File.join("#{$root_dir}/modules/**", 'config.yaml')
        Dir.glob(module_configs) do |cf|
          y = load(cf)
          if y.nil?
            print_error "Unable to load module configuration '#{cf}'"
            next
          end

          y['beef']['module'][y['beef']['module'].keys.first]['path'] = cf.gsub('config.yaml', '').gsub(%r{#{$root_dir}/}, '')
          @config = y.deep_merge @config
          # API call for post module config load
          BeEF::API::Registrar.instance.fire(
            BeEF::API::Configuration,
            'module_configuration_load',
            y['beef']['module'].keys.first
          )
        end
      end

      private

      def validate_public_config_variable?(config)
        return true if config['beef']['http']['public'].is_a?(Hash) ||
                       config['beef']['http']['public'].is_a?(NilClass)

        print_error 'Config path beef.http.public is deprecated.'
        print_error 'Please use the new format for public variables found'
        print_error 'https://github.com/beefproject/beef/wiki/Configuration#web-server-configuration'
        false
      end
    end
  end
end

configuration.rb

bcoles commented 2 years ago

Ok I did a diff on your code.

diff --git a/core/main/configuration.rb b/core/main/configuration.rb
index b0e18441..7812b8a3 100644
--- a/core/main/configuration.rb
+++ b/core/main/configuration.rb
@@ -13,7 +13,7 @@ module BeEF
       # of the Configuration object while having the possibility to specify a parameter to the constructor.
       # This is  why we don't use anymore the default Ruby implementation -> include Singleton
       def self.instance
-        @@instance
+        @@instance = self (** This was initially just instance, i added self because it showed eerror**)
       end

       # Loads the default configuration system
@@ -31,8 +31,7 @@ module BeEF
           @@config = config
         rescue StandardError => e
           print_error "Fatal Error: cannot load configuration file '#{config}' : #{e.message}"
-          print_more e.backtrace
-          exit(1)
+          print_error e.backtrace
         end

         @@instance = self
@@ -41,9 +40,14 @@ module BeEF
       # Loads yaml file
       # @param [String] file YAML file to be loaded
       # @return [Hash] YAML formatted hash
-      def load(file)
-        return nil unless File.exist?(file)
-        YAML.safe_load(File.binread(file))
+      def load (file)
+        return nil unless File.exist? file
+
+        raw = File.read file
+        YAML.safe_load raw
+      rescue StandardError => e
+        print_debug "Unable to load configuration file '#{file}' : #{e.message}"
+        print_error e.backtrace
       end

       #
@@ -195,11 +199,11 @@ module BeEF
         subkeys = key.split('.')
         lastkey = subkeys.pop
         subhash = subkeys.inject(@config) do |hash, k|
-          hash[k]
+        hash [:k]
         end
         return nil if subhash.nil?

-        subhash.key?(lastkey) ? subhash[lastkey] : nil
+        subhash.key?(lastkey) ? subhash [lastkey] : nil
       end

       #

I'm pretty sure you can't have a space between a variable and the array element.

In fact none of these changes make sense. I suggest reverting them all.

catchmeifyoucaan commented 2 years ago

thank you for yur help, but i really dont understand this, yes i want beef to work and its not, ill 100% follow what u say, even if i have to purge everything and start again

bcoles commented 2 years ago

I'm on the phone and will be for a while. I'll be back in a while. I suggest making a backup then create a new fresh clone.

catchmeifyoucaan commented 2 years ago

wow, so i should remove the ones marked in red lines and replace wth the green ones? thanks ill do that now

catchmeifyoucaan commented 2 years ago

I'm on the phone and will be for a while. I'll be back in a while. I suggest making a backup then create a new fresh clone.

okay, yes i use beef from github, i think ill delete everything and start again, becaue when you used diff, i didnt change that much code and i dont if it means to change from the green lines to the red lines or vice versa

bcoles commented 2 years ago

okay, yes i use beef from github, i think ill delete everything and start again, becaue when you used diff, i didnt change that much code and i dont if it means to change from the green lines to the red lines or vice versa

It's possible that your version of BeEF is old. A couple of those changed lines were introduced a few days ago.

catchmeifyoucaan commented 2 years ago

okay @bcoles, thank you all along, so do you suggest i make the chnages myself in nano, or just redownload everything. and if i have to change the code, the red colored lines are the now correct codes, right?

bcoles commented 2 years ago

okay @bcoles, thank you all along, so do you suggest i make the chnages myself in nano, or just redownload everything. and if i have to change the code, the red colored lines are the now correct codes, right?

No. Stop breaking things.

I suggest making a backup then create a new fresh clone.

catchmeifyoucaan commented 2 years ago

okay, thank u, i dont understand making a fresh clone tho because while i try git clone at the beef folder, it says it already exist and i cant clone it because its not empty. and i dont know how to upgrade to the latest, so i will just purge out beef and start all over again, ill sure get back to you in few minutes please dont close this session.

bcoles commented 2 years ago

i dont understand making a fresh clone tho because while i try git clone at the beef folder,

mkdir /tmp/broken
mv beef /tmp/broken
git clone https://github.com/beefproject/beef
catchmeifyoucaan commented 2 years ago

appreciate you, im cloning it now inside the main beef folder, i'll let you know when its done

catchmeifyoucaan commented 2 years ago

thank you so much, @bcoles i can now log back in my beef, but i have few questions/errors

./update-beef [INFO] Updating BeEF from GitHub repository... Updating 38b7ac7c..5fdd96f5 error: Your local changes to the following files would be overwritten by merge: beef core/main/configuration.rb Please commit your changes or stash them before you merge. Aborting when i try to use the update-beef file to update the respository, it shows this.

catchmeifyoucaan commented 2 years ago

and the hook url just shows internal server error, even the demo hook url as well, this was the error i was facing before everything, please help

catchmeifyoucaan commented 2 years ago

im getting this error in the console when i use the hook url please

2022-03-21 01:25:34 - ArgumentError - invalid byte sequence in US-ASCII: /var/lib/gems/2.7.0/gems/erubis-2.7.0/lib/erubis/enhancer.rb:647:in scan' /var/lib/gems/2.7.0/gems/erubis-2.7.0/lib/erubis/enhancer.rb:647:inconvert_input' /var/lib/gems/2.7.0/gems/erubis-2.7.0/lib/erubis/converter.rb:36:in convert' /var/lib/gems/2.7.0/gems/erubis-2.7.0/lib/erubis/engine.rb:30:ininitialize' /home/surprise/beef/beef/core/main/handlers/modules/legacybeefjs.rb:107:in new' /home/surprise/beef/beef/core/main/handlers/modules/legacybeefjs.rb:107:inlegacy_build_beefjs!' /home/surprise/beef/beef/core/main/handlers/hookedbrowsers.rb:121:in block in <class:HookedBrowsers>' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:1685:incall' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:1685:in block in compile!' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:1023:inblock (3 levels) in route!' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:1042:in route_eval' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:1023:inblock (2 levels) in route!' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:1071:in block in process_route' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:1069:incatch' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:1069:in process_route' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:1021:inblock in route!' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:1018:in each' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:1018:inroute!' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:1140:in block in dispatch!' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:1112:inblock in invoke' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:1112:in catch' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:1112:ininvoke' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:1135:in dispatch!' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:949:inblock in call!' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:1112:in block in invoke' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:1112:incatch' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:1112:in invoke' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:949:incall!' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:938:in call' /var/lib/gems/2.7.0/gems/rack-2.2.3/lib/rack/null_logger.rb:11:incall' /var/lib/gems/2.7.0/gems/rack-2.2.3/lib/rack/head.rb:12:in call' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:218:incall' /var/lib/gems/2.7.0/gems/sinatra-2.2.0/lib/sinatra/base.rb:1992:in call' /var/lib/gems/2.7.0/gems/rack-2.2.3/lib/rack/urlmap.rb:74:inblock in call' /var/lib/gems/2.7.0/gems/rack-2.2.3/lib/rack/urlmap.rb:58:in each' /var/lib/gems/2.7.0/gems/rack-2.2.3/lib/rack/urlmap.rb:58:incall' /var/lib/gems/2.7.0/gems/thin-1.8.1/lib/thin/connection.rb:86:in block in pre_process' /var/lib/gems/2.7.0/gems/thin-1.8.1/lib/thin/connection.rb:84:incatch' /var/lib/gems/2.7.0/gems/thin-1.8.1/lib/thin/connection.rb:84:in pre_process' /var/lib/gems/2.7.0/gems/thin-1.8.1/lib/thin/connection.rb:53:inprocess' /var/lib/gems/2.7.0/gems/thin-1.8.1/lib/thin/connection.rb:39:in receive_data' /var/lib/gems/2.7.0/gems/eventmachine-1.2.7/lib/eventmachine.rb:195:inrun_machine' /var/lib/gems/2.7.0/gems/eventmachine-1.2.7/lib/eventmachine.rb:195:in run' /var/lib/gems/2.7.0/gems/thin-1.8.1/lib/thin/backends/base.rb:75:instart' /var/lib/gems/2.7.0/gems/thin-1.8.1/lib/thin/server.rb:162:in start' /home/surprise/beef/beef/core/main/server.rb:156:instart' ./beef:278:in `

'

bcoles commented 2 years ago

error: Your local changes to the following files would be overwritten by merge: beef core/main/configuration.rb

It looks like you're still using the broken repository.

Start fresh.

catchmeifyoucaan commented 2 years ago

thank you, i use /home/me/beef/beef to get it right and the demo url now works fine. but the hook url when i try it with another browser on same computer, it just throw a bunch of codes i dont even understand and its so much of code it may not allow me to comment it, but ill try and do that now

catchmeifyoucaan commented 2 years ago

/! jQuery v1.12.4 | (c) jQuery Foundation | jquery.org/license / !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=a.document,e=c.slice,f=c.concat,g=c.push,h=c.indexOf,i={},j=i.toString,k=i.hasOwnProperty,l={},m="1.12.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return e.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:e.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a){return n.each(this,a)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(e.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:g,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){var b=a&&a.toString();return!n.isArray(a)&&b-parseFloat(b)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!k.call(a,"constructor")&&!k.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(!l.ownFirst)for(b in a)return k.call(a,b);for(b in a);return void 0===b||k.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?i[j.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(s(a)){for(c=a.length;c>d;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):g.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(h)return h.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,g=0,h=[];if(s(a))for(d=a.length;d>g;g++)e=b(a[g],g,c),null!=e&&h.push(e);else for(g in a)e=b(a[g],g,c),null!=e&&h.push(e);return f.apply([],h)},guid:1,proxy:function(a,b){var c,d,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=e.call(arguments,2),d=function(){return a.apply(b||this,c.concat(e.call(arguments)))},d.guid=a.guid=a.guid||n.guid++,d):void 0},now:function(){return+new Date},support:l}),"function"==typeof Symbol&&(n.fn[Symbol.iterator]=c[Symbol.iterator]),n.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){i["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=!!a&&"length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1new Date,v=a.document,w=0,x=0,y=ga(),z=ga(),A=ga(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\x20\t\r\n\f]",M="(?:\\.|[\w-]|[^\x00-\xa0])+",N="\["+L+"("+M+")(?:"+L+"([^$|!~]?=)"+L+"(?:'((?:\\.|[^\\']))'|\"((?:\\.|[^\\\"]))\"|("+M+"))|)"+L+"\]",O=":("+M+")(?:\((('((?:\\.|[^\\']))'|\"((?:\\.|[^\\\"]))\")|((?:\\.|[^\\()[\]]|"+N+"))|.)\)|)",P=new RegExp(L+"+","g"),Q=new RegExp("^"+L+"+|((?:^|[^\\])(?:\\.))"+L+"+$","g"),R=new RegExp("^"+L+","+L+""),S=new RegExp("^"+L+"([>+~]|"+L+")"+L+""),T=new RegExp("="+L+"([^\]'\"]?)"+L+"\]","g"),U=new RegExp(O),V=new RegExp("^"+M+"$"),W={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\.("+M+")"),TAG:new RegExp("^("+M+"|[])"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\("+L+"(even|odd|(([+-]|)(\d)n|)"+L+"(?:([+-]|)"+L+"(\d+)|))"+L+"\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\("+L+"((?:-\d)?\d)"+L+"\)|)(?=[^-]|$)","i")},X=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+{\s[native \w/,$=/^(?:#([\w-]+)|(\w+)|.([\w-]+))$/,=/[+~]/,aa=/'|\/g,ba=new RegExp("\\([\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),ca=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},da=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(ea){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fa(a,b,d,e){var f,h,j,k,l,o,r,s,w=b&&b.ownerDocument,x=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==x&&9!==x&&11!==x)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==x&&(o=$.exec(a)))if(f=o[1]){if(9===x){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(w&&(j=w.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(o[2])return H.apply(d,b.getElementsByTagName(a)),d;if((f=o[3])&&c.getElementsByClassName&&b.getElementsByClassName)return H.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==x)w=b,s=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(aa,"\$&"):b.setAttribute("id",k=u),r=g(a),h=r.length,l=V.test(k)?"#"+k:"[id='"+k+"']";while(h--)r[h]=l+" "+qa(r[h]);s=r.join(","),w=.test(a)&&oa(b.parentNode)||b}if(s)try{return H.apply(d,w.querySelectorAll(s)),d}catch(y){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(Q,"$1"),b,d,e)}function ga(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ha(a){return a[u]=!0,a}function ia(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ja(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function ka(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function la(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function na(a){return ha(function(b){return b=+b,ha(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function oa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=fa.support={},f=fa.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fa.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ia(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ia(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("").length}),c.getElementsByClassName=Z.test(n.getElementsByClassName),c.getById=ia(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if(""===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return"undefined"!=typeof b.getElementsByClassName&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=Z.test(n.querySelectorAll))&&(ia(function(a){o.appendChild(a).innerHTML="",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[^$]="+L+"(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\["+L+"(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+").length||q.push(".#.+[+~]")}),ia(function(a){var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"[^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll(",:x"),q.push(",.:")})),(c.matchesSelector=Z.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ia(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",O)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Z.test(o.compareDocumentPosition),t=b||Z.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return ka(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?ka(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},fa.matches=function(a,b){return fa(a,null,null,b)},fa.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(T,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fa(b,n,null,[a]).length>0},fa.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fa.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fa.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fa.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fa.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fa.selectors={cacheLength:50,createPseudo:ha,match:W,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ba,ca),a[3]=(a[3]||a[4]||a[5]||"").replace(ba,ca),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fa.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fa.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return W.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&U.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ba,ca).toLowerCase();return""===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fa.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(P," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fa.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ha(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ha(function(a){var b=[],c=[],d=h(a.replace(Q,"$1"));return d[u]?ha(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ha(function(a){return function(b){return fa(a,b).length>0}}),contains:ha(function(a){return a=a.replace(ba,ca),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ha(function(a){return V.test(a||"")||fa.error("unsupported lang: "+a),a=a.replace(ba,ca).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Y.test(a.nodeName)},input:function(a){return X.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:na(function(){return[0]}),last:na(function(a,b){return[b-1]}),eq:na(function(a,b,c){return[0>c?c+b:c]}),even:na(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:na(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:na(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:na(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=la(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=ma(b);function pa(){}pa.prototype=d.filters=d.pseudos,d.setFilters=new pa,g=fa.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){c&&!(e=R.exec(h))||(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=S.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(Q," ")}),h=h.slice(c.length));for(g in d.filter)!(e=W[g].exec(h))||j[g]&&!(e=jg)||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fa.error(a):z(a,i).slice(0)};function qa(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function ra(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j,k=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(j=b[u]||(b[u]={}),i=j[b.uniqueID]||(j[b.uniqueID]={}),(h=i[d])&&h[0]===w&&h[1]===f)return k[2]=h[2];if(i[d]=k,k[2]=a(b,c,g))return!0}}}function sa(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e] @

catchmeifyoucaan commented 2 years ago

the code is way more than this, i cant paste all here, to reproduce, just use the hook url in chromium, that was why i wanted to use it with ngrok and did all the meaningless changes, please help now since we here

bcoles commented 2 years ago

the code is way more than this, i cant paste all here, to reproduce, just use the hook url in chromium, that was why i wanted to use it with ngrok and did all the meaningless changes, please help now since we here

One thing at a time.

BeEF works now, correct?

You were able to hook a browser using the demo page, correct?

bcoles commented 2 years ago

the code is way more than this, i cant paste all here, to reproduce, just use the hook url in chromium,

That is the BeEF hook JavaScript code. It won't execute by itself. Try the demo page.

catchmeifyoucaan commented 2 years ago

yes demo page works fine, but thats the code it shows for the main hook url, how can i execute it if it shows that in a suppose target browser, the demo page is good tho, but i think i need the url to work, please