Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
beefproject
GitHub Repository: beefproject/beef
Path: blob/master/core/main/crypto.rb
1154 views
1
#
2
# Copyright (c) 2006-2025 Wade Alcorn - [email protected]
3
# Browser Exploitation Framework (BeEF) - https://beefproject.com
4
# See the file 'doc/COPYING' for copying permission
5
#
6
require 'securerandom'
7
8
module BeEF
9
module Core
10
module Crypto
11
# @note the minimum length of the security token
12
TOKEN_MINIMUM_LENGTH = 15
13
14
#
15
# Generate a secure random token
16
#
17
# @param [Integer] len The length of the secure token
18
#
19
# @return [String] Security token
20
#
21
def self.secure_token(len = nil)
22
# get default length from config
23
config = BeEF::Core::Configuration.instance
24
token_length = len || config.get('beef.crypto_default_value_length').to_i
25
26
# type checking
27
raise TypeError, "Token length is less than the minimum length enforced by the framework: #{TOKEN_MINIMUM_LENGTH}" if token_length < TOKEN_MINIMUM_LENGTH
28
29
# return random hex string
30
SecureRandom.random_bytes(token_length).unpack1('H*')
31
end
32
33
#
34
# Generate a secure random token, 20 chars, used as an auth token for the RESTful API.
35
# After creation it's stored in the BeEF configuration object => conf.get('beef.api_token')
36
#
37
# @return [String] Security token
38
#
39
def self.api_token
40
config = BeEF::Core::Configuration.instance
41
token_length = 20
42
43
# return random hex string
44
token = SecureRandom.random_bytes(token_length).unpack1('H*')
45
config.set('beef.api_token', token)
46
token
47
end
48
49
#
50
# Generates a random alphanumeric string
51
# Note: this isn't securely random
52
# @todo use SecureRandom once Ruby 2.4 is EOL
53
#
54
# @param length integer length of returned string
55
#
56
def self.random_alphanum_string(length = 10)
57
raise TypeError, "'length' is #{length.class}; expected Integer" unless length.is_a?(Integer)
58
raise TypeError, "Invalid length: #{length}" unless length.positive?
59
60
[*('a'..'z'), *('A'..'Z'), *('0'..'9')].shuffle[0, length].join
61
end
62
63
#
64
# Generates a random hex string
65
#
66
# @param length integer length of returned string
67
#
68
def self.random_hex_string(length = 10)
69
raise TypeError, "'length' is #{length.class}; expected Integer" unless length.is_a?(Integer)
70
raise TypeError, "Invalid length: #{length}" unless length.positive?
71
72
SecureRandom.random_bytes(length).unpack1('H*')[0...length]
73
end
74
75
#
76
# Generates a unique identifier for DNS rules.
77
#
78
# @return [String] 8-character hex identifier
79
#
80
def self.dns_rule_id
81
id = nil
82
83
begin
84
id = random_hex_string(8)
85
BeEF::Core::Models::Dns::Rule.all.each { |rule| throw StandardError if id == rule.id }
86
rescue StandardError
87
retry
88
end
89
90
id.to_s
91
end
92
end
93
end
94
end
95
96