bro_hub 0.1.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +21 -0
  3. data/README.md +204 -87
  4. data/app/controllers/bro_hub/apm/application_controller.rb +26 -0
  5. data/app/controllers/bro_hub/apm/deploys_controller.rb +7 -0
  6. data/app/controllers/bro_hub/apm/endpoints_controller.rb +8 -0
  7. data/app/controllers/bro_hub/apm/errors_controller.rb +15 -0
  8. data/app/controllers/bro_hub/apm/findings_controller.rb +8 -0
  9. data/app/controllers/bro_hub/apm/overview_controller.rb +7 -0
  10. data/app/controllers/bro_hub/apm/queries_controller.rb +11 -0
  11. data/app/controllers/bro_hub/apm/status_controller.rb +9 -0
  12. data/app/controllers/bro_hub/application_controller.rb +16 -0
  13. data/app/controllers/bro_hub/audit_events_controller.rb +56 -0
  14. data/app/controllers/bro_hub/cache/application_controller.rb +55 -0
  15. data/app/controllers/bro_hub/cache/audit_events_controller.rb +40 -0
  16. data/app/controllers/bro_hub/cache/flushes_controller.rb +34 -0
  17. data/app/controllers/bro_hub/cache/keys_controller.rb +41 -0
  18. data/app/controllers/bro_hub/cache/purges_controller.rb +40 -0
  19. data/app/controllers/bro_hub/env/application_controller.rb +27 -0
  20. data/app/controllers/bro_hub/env/audit_controller.rb +10 -0
  21. data/app/controllers/bro_hub/env/home_controller.rb +6 -0
  22. data/app/controllers/bro_hub/env/proposals_controller.rb +86 -0
  23. data/app/controllers/bro_hub/env/reviews_controller.rb +72 -0
  24. data/app/controllers/bro_hub/feature_controller.rb +21 -0
  25. data/app/controllers/bro_hub/safe/application_controller.rb +24 -0
  26. data/app/controllers/bro_hub/safe/flagged_commands_controller.rb +14 -0
  27. data/app/controllers/bro_hub/safe/reviews_controller.rb +39 -0
  28. data/app/controllers/bro_hub/safe/rules_controller.rb +18 -0
  29. data/app/controllers/bro_hub/safe/sessions_controller.rb +63 -0
  30. data/app/controllers/bro_hub/safe/unlocks_controller.rb +14 -0
  31. data/app/helpers/bro_hub/apm/application_helper.rb +104 -0
  32. data/app/helpers/bro_hub/application_helper.rb +28 -18
  33. data/app/helpers/bro_hub/cache/application_helper.rb +63 -0
  34. data/app/helpers/bro_hub/env/application_helper.rb +67 -0
  35. data/app/helpers/bro_hub/safe/application_helper.rb +59 -0
  36. data/app/jobs/bro_hub/safe/purge_job.rb +10 -0
  37. data/app/models/bro_hub/application_record.rb +5 -0
  38. data/app/models/bro_hub/audit_event.rb +40 -0
  39. data/app/models/bro_hub/cache/audit_event.rb +15 -0
  40. data/app/models/bro_hub/env/audit_event.rb +72 -0
  41. data/app/models/bro_hub/safe/command.rb +22 -0
  42. data/app/models/bro_hub/safe/review.rb +22 -0
  43. data/app/models/bro_hub/safe/session.rb +57 -0
  44. data/app/models/bro_hub/safe/unlock.rb +15 -0
  45. data/app/views/bro_hub/apm/deploys/index.html.erb +21 -0
  46. data/app/views/bro_hub/apm/endpoints/index.html.erb +27 -0
  47. data/app/views/bro_hub/apm/errors/index.html.erb +22 -0
  48. data/app/views/bro_hub/apm/errors/not_found.html.erb +3 -0
  49. data/app/views/bro_hub/apm/errors/show.html.erb +43 -0
  50. data/app/views/bro_hub/apm/findings/index.html.erb +24 -0
  51. data/app/views/bro_hub/apm/overview/show.html.erb +59 -0
  52. data/app/views/bro_hub/apm/queries/index.html.erb +37 -0
  53. data/app/views/bro_hub/apm/shared/_page_styles.html.erb +15 -0
  54. data/app/views/bro_hub/apm/status/show.html.erb +47 -0
  55. data/app/views/bro_hub/audit_events/index.html.erb +38 -0
  56. data/app/views/bro_hub/audit_events/show.html.erb +54 -0
  57. data/app/views/bro_hub/cache/audit_events/index.html.erb +39 -0
  58. data/app/views/bro_hub/cache/audit_events/show.html.erb +48 -0
  59. data/app/views/bro_hub/cache/flushes/new.html.erb +19 -0
  60. data/app/views/bro_hub/cache/keys/index.html.erb +36 -0
  61. data/app/views/bro_hub/cache/keys/show.html.erb +57 -0
  62. data/app/views/bro_hub/cache/purges/new.html.erb +17 -0
  63. data/app/views/bro_hub/cache/purges/preview.html.erb +37 -0
  64. data/app/views/bro_hub/cache/shared/_store_tabs.html.erb +9 -0
  65. data/app/views/bro_hub/cache/shared/unsupported.html.erb +3 -0
  66. data/app/views/bro_hub/env/audit/index.html.erb +31 -0
  67. data/app/views/bro_hub/env/home/index.html.erb +25 -0
  68. data/app/views/bro_hub/env/proposals/_new_key_row.html.erb +7 -0
  69. data/app/views/bro_hub/env/proposals/new.html.erb +99 -0
  70. data/app/views/bro_hub/env/reviews/new.html.erb +29 -0
  71. data/app/views/bro_hub/env/reviews/show.html.erb +122 -0
  72. data/app/views/bro_hub/env/shared/_page_styles.html.erb +57 -0
  73. data/app/views/bro_hub/env/shared/_script.html.erb +114 -0
  74. data/app/views/bro_hub/env/shared/not_ready.html.erb +17 -0
  75. data/app/views/bro_hub/safe/flagged_commands/index.html.erb +22 -0
  76. data/app/views/bro_hub/safe/rules/show.html.erb +59 -0
  77. data/app/views/bro_hub/safe/sessions/index.html.erb +51 -0
  78. data/app/views/bro_hub/safe/sessions/show.html.erb +92 -0
  79. data/app/views/bro_hub/safe/unlocks/index.html.erb +25 -0
  80. data/app/views/bro_hub/shared/schema_missing.html.erb +25 -0
  81. data/app/views/layouts/bro_hub/application.html.erb +11 -2
  82. data/config/routes/apm.rb +10 -0
  83. data/config/routes/cache.rb +17 -0
  84. data/config/routes/env.rb +10 -0
  85. data/config/routes/safe.rb +10 -0
  86. data/config/routes.rb +12 -3
  87. data/db/migrate/20261129000000_create_bro_hub_tables.rb +85 -0
  88. data/lib/bro_hub/apm/api.rb +88 -0
  89. data/lib/bro_hub/apm/configuration.rb +58 -0
  90. data/lib/bro_hub/apm/local_status.rb +49 -0
  91. data/lib/bro_hub/apm.rb +28 -0
  92. data/lib/bro_hub/audit.rb +41 -0
  93. data/lib/bro_hub/cache/audit.rb +15 -0
  94. data/lib/bro_hub/cache/configuration.rb +105 -0
  95. data/lib/bro_hub/cache/errors.rb +26 -0
  96. data/lib/bro_hub/cache/redis_store.rb +220 -0
  97. data/lib/bro_hub/cache.rb +38 -0
  98. data/lib/bro_hub/configuration.rb +19 -4
  99. data/lib/bro_hub/controller_base.rb +3 -6
  100. data/lib/bro_hub/engine.rb +60 -1
  101. data/lib/bro_hub/env/audit.rb +17 -0
  102. data/lib/bro_hub/env/configuration.rb +72 -0
  103. data/lib/bro_hub/env/credentials.rb +135 -0
  104. data/lib/bro_hub/env/deployments.rb +45 -0
  105. data/lib/bro_hub/env/differ.rb +58 -0
  106. data/lib/bro_hub/env/editor.rb +104 -0
  107. data/lib/bro_hub/env/encrypted_blob.rb +18 -0
  108. data/lib/bro_hub/env/environment.rb +74 -0
  109. data/lib/bro_hub/env.rb +36 -0
  110. data/lib/bro_hub/features.rb +13 -0
  111. data/lib/bro_hub/layout.rb +2 -5
  112. data/lib/bro_hub/registry.rb +5 -0
  113. data/lib/bro_hub/safe/cipher.rb +46 -0
  114. data/lib/bro_hub/safe/commands.rb +25 -0
  115. data/lib/bro_hub/safe/configuration.rb +191 -0
  116. data/lib/bro_hub/safe/encrypted_type.rb +16 -0
  117. data/lib/bro_hub/safe/errors.rb +48 -0
  118. data/lib/bro_hub/safe/executor.rb +142 -0
  119. data/lib/bro_hub/safe/guards/const_guard.rb +42 -0
  120. data/lib/bro_hub/safe/guards/credentials_guard.rb +31 -0
  121. data/lib/bro_hub/safe/guards/env_guard.rb +90 -0
  122. data/lib/bro_hub/safe/guards/file_guard.rb +28 -0
  123. data/lib/bro_hub/safe/guards/guarded.rb +51 -0
  124. data/lib/bro_hub/safe/guards/irb_context.rb +23 -0
  125. data/lib/bro_hub/safe/guards/method_guard.rb +32 -0
  126. data/lib/bro_hub/safe/guards/network_guard.rb +98 -0
  127. data/lib/bro_hub/safe/guards/sql_guard.rb +26 -0
  128. data/lib/bro_hub/safe/parsed_command.rb +66 -0
  129. data/lib/bro_hub/safe/recorder.rb +82 -0
  130. data/lib/bro_hub/safe/shield.rb +83 -0
  131. data/lib/bro_hub/safe/supervisor.rb +81 -0
  132. data/lib/bro_hub/safe/terminal.rb +55 -0
  133. data/lib/bro_hub/safe/trail.rb +24 -0
  134. data/lib/bro_hub/safe/validator.rb +74 -0
  135. data/lib/bro_hub/safe.rb +134 -0
  136. data/lib/bro_hub/schema.rb +36 -0
  137. data/lib/bro_hub/section.rb +14 -10
  138. data/lib/bro_hub/testing.rb +62 -0
  139. data/lib/bro_hub/version.rb +1 -1
  140. data/lib/bro_hub.rb +32 -6
  141. data/lib/generators/bro_hub/install/install_generator.rb +93 -69
  142. data/lib/generators/bro_hub/install/templates/bro_hub.rb.tt +115 -0
  143. data/lib/generators/bro_hub/uninstall/templates/drop_bro_hub_tables.rb.tt +16 -0
  144. data/lib/generators/bro_hub/uninstall/uninstall_generator.rb +57 -0
  145. data/lib/tasks/bro_hub.rake +9 -0
  146. metadata +155 -10
  147. data/lib/bro_hub/root_middleware.rb +0 -17
  148. data/lib/generators/bro_hub/install/templates/bro_hub.rb +0 -11
  149. data/lib/generators/bro_hub/installable.rb +0 -63
@@ -0,0 +1,191 @@
1
+ module BroHub::Safe
2
+ # BroHub.config.safe. Who is signed in, how they are labelled, the parent controller and whether SSL is required
3
+ # are BroHub.config's.
4
+ class Configuration
5
+ # --- Where it runs -------------------------------------------------------------------
6
+
7
+ # The safe feature only acts on consoles started in these environments. Override with `enabled`.
8
+ attr_accessor :protected_environments
9
+
10
+ # true/false to force it on or off regardless of the environment.
11
+ attr_accessor :enabled
12
+
13
+ # Also record `rails runner` invocations as sessions.
14
+ attr_accessor :audit_runner
15
+
16
+ # --- Who is using the console --------------------------------------------------------
17
+
18
+ # -> { "name" } The identity of the person at the console. Trust this only as much as the
19
+ # layer that sets it (e.g. SSH `environment=` in authorized_keys is trustworthy, `SetEnv`
20
+ # from the client is not).
21
+ attr_accessor :username_resolver
22
+
23
+ # Ask on the terminal when the resolver returns nothing (otherwise the console refuses to start).
24
+ attr_accessor :ask_for_username_if_empty
25
+
26
+ # -> { "203.0.113.7" } Where the person connected from, stored with each session. The default reads
27
+ # CONSOLE_CLIENT_IP (set it where you trust it, e.g. your console wrapper from $SSH_CLIENT), then
28
+ # SSH_CLIENT / SSH_CONNECTION. Values that aren't an IP address are ignored.
29
+ attr_accessor :client_ip_resolver
30
+
31
+ # --- What is protected ---------------------------------------------------------------
32
+
33
+ # Which resources need unlock! (see Shield::RESOURCES).
34
+ attr_accessor :protected_resources
35
+
36
+ # URLs (https://host:port, redis://host:port, host:port) that can't be reached while locked.
37
+ attr_accessor :protected_urls
38
+
39
+ # ENV names that can't be read while locked (matched against the variable name).
40
+ attr_accessor :protected_env_patterns
41
+
42
+ # Files that can't be read from the console while locked.
43
+ attr_accessor :protected_file_patterns
44
+
45
+ # --- Guardrails ----------------------------------------------------------------------
46
+
47
+ # Classes/modules the console may not reopen (class Foo / module Foo / Foo.class_eval...).
48
+ attr_accessor :forbidden_reopening
49
+
50
+ # Constants the console may not reference. :always, or only while :locked.
51
+ attr_accessor :forbidden_constants
52
+
53
+ # "Owner#instance_method" or "Owner.singleton_method" that can't be called from the console. Blocked by name
54
+ # before the command runs, and at runtime.
55
+ attr_accessor :forbidden_methods
56
+
57
+ # Like forbidden_methods, but only blocked at runtime, when called straight from the console: for names other
58
+ # methods share (YAML.load, JSON.load and Marshal.load stay usable while Kernel#load doesn't).
59
+ attr_accessor :runtime_only_methods
60
+
61
+ # Commands containing one of these are allowed but recorded as suspicious.
62
+ attr_accessor :suspicious_terms
63
+
64
+ # Freeze the safe feature's own classes once installed so they can't be monkey patched.
65
+ attr_accessor :freeze_internals
66
+
67
+ # --- Storage and review --------------------------------------------------------------
68
+
69
+ # Keep sessions this long, nil to keep forever (see BroHub::Safe::PurgeJob / bro_hub:safe:purge).
70
+ attr_accessor :retention
71
+
72
+ # Don't purge sessions a reviewer flagged.
73
+ attr_accessor :keep_flagged
74
+
75
+ # 32 bytes (or a ->{ } returning them) used to encrypt recorded commands. Defaults to a key
76
+ # derived from the app's secret_key_base.
77
+ attr_accessor :encryption_key
78
+
79
+ # ->(user) { true/false } may this user review sessions in the UI?
80
+ attr_accessor :can_audit
81
+
82
+ # May a reviewer approve their own sessions? (compared by console_username vs session username)
83
+ attr_accessor :allow_self_audit
84
+
85
+ # ->(user) { "name" } The name this hub user goes by at the console (what username_resolver returns for them), so
86
+ # nobody reviews their own sessions. Defaults to BroHub.config.user_label, which usually is an email while
87
+ # CONSOLE_USER is a login name: map it, or self review isn't prevented (the Rules page warns about it).
88
+ attr_accessor :console_username
89
+
90
+ DEFAULT_CONSOLE_USERNAME = ->(user) { BroHub.config.user_label.call(user) }
91
+
92
+ # Texts shown in the console.
93
+ attr_accessor :welcome_message, :unlock_prompt, :unlocked_message, :locked_message
94
+
95
+ def initialize
96
+ @protected_environments = %w[ production ]
97
+ @enabled = nil
98
+ @audit_runner = false
99
+
100
+ @username_resolver = -> { ENV["CONSOLE_USER"] }
101
+ @ask_for_username_if_empty = false
102
+ @client_ip_resolver = -> { ENV["CONSOLE_CLIENT_IP"].presence || ENV["SSH_CLIENT"].to_s.split.first || ENV["SSH_CONNECTION"].to_s.split.first }
103
+
104
+ @protected_resources = %i[ encrypted_data credentials env files network ]
105
+ @protected_urls = []
106
+ @protected_env_patterns = [ /SECRET/i, /TOKEN/i, /PASSWORD/i, /PASSPHRASE/i, /CREDENTIAL/i, /API_?KEY/i, /PRIVATE/i, /MASTER_?KEY/i, /DATABASE_URL/i, /\A[A-Z_]*KEY\z/ ]
107
+ @protected_file_patterns = [ %r{config/master\.key\z}, %r{config/credentials/.+\.key\z}, %r{(\A|/)\.env(\.[^/]+)?\z} ]
108
+
109
+ @forbidden_reopening = %w[ ActiveRecord ApplicationRecord BroHub IRB ]
110
+ @forbidden_constants = {
111
+ always: %w[ BroHub IRB ObjectSpace ],
112
+ locked: %w[ ActiveRecord::Encryption Open3 PTY Fiddle ]
113
+ }
114
+ @forbidden_methods = %w[
115
+ Kernel#eval Kernel.eval BasicObject#instance_eval BasicObject#instance_exec
116
+ Module#class_eval Module#module_eval Module#class_exec Module#module_exec
117
+ Kernel#system Kernel#exec Kernel#spawn Kernel#` Kernel#fork
118
+ Kernel.system Kernel.exec Kernel.spawn Kernel.` Kernel.fork
119
+ Process.spawn Process.exec Process.fork IO.popen
120
+ Binding#eval
121
+ Method#super_method UnboundMethod#super_method
122
+ ]
123
+ @runtime_only_methods = %w[ Kernel#load Kernel.load ]
124
+ @suspicious_terms = %w[
125
+ secret credentials master.key ENV bro_hub BroHub raw_connection
126
+ instance_variable_set instance_variable_get define_singleton_method module_parent
127
+ ]
128
+ @freeze_internals = true
129
+
130
+ @retention = 90.days
131
+ @keep_flagged = true
132
+ @encryption_key = nil
133
+
134
+ @can_audit = ->(_user) { false }
135
+ @allow_self_audit = false
136
+ @console_username = DEFAULT_CONSOLE_USERNAME
137
+
138
+ @welcome_message = "You have access to production data here. That's a big deal. Everything you type is recorded and " \
139
+ "reviewed. Be careful, be brief, and don't look at data you don't need."
140
+ @unlock_prompt = "Before you access sensitive data (encrypted attributes, credentials, ENV, protected systems), " \
141
+ "say why and where we can find the consent or ticket that covers it."
142
+ @unlocked_message = "Unlocked. We pay extra close attention to everything you do now. Type lock! to protect it again."
143
+ @locked_message = "Locked again. When we review, we may reach out about what you did while unlocked."
144
+ end
145
+
146
+ def enabled?
147
+ return enabled unless enabled.nil?
148
+
149
+ protected_environments.map(&:to_s).include?(Rails.env.to_s)
150
+ end
151
+
152
+ # May this person see the section at all: only reviewers.
153
+ def allows_any?(user)
154
+ return false unless user
155
+
156
+ !!can_audit.call(user)
157
+ end
158
+
159
+ # Who may see this feature's rows in the hub's audit log.
160
+ def audit_visible?(user)
161
+ allows_any?(user)
162
+ end
163
+
164
+ # Has console_username been set to something other than the default?
165
+ def console_username_mapped?
166
+ !console_username.equal?(DEFAULT_CONSOLE_USERNAME)
167
+ end
168
+
169
+ # Self review is off but can't be enforced: console names aren't mapped to hub users.
170
+ def self_review_unguarded?
171
+ !allow_self_audit && !console_username_mapped?
172
+ end
173
+
174
+ def protected_env_name?(name)
175
+ protected_env_patterns.any? { |pattern| pattern.match?(name.to_s) }
176
+ end
177
+
178
+ # Freezes everything so it can't be altered from a console, down to the strings in the lists.
179
+ def lock_down!
180
+ protected_values.each(&:freeze)
181
+ freeze
182
+ end
183
+
184
+ # The lists this configuration holds and what is in them: what lock_down! freezes.
185
+ def protected_values
186
+ lists = [ protected_environments, protected_resources, protected_urls, protected_env_patterns, protected_file_patterns,
187
+ forbidden_reopening, forbidden_methods, runtime_only_methods, suspicious_terms, *forbidden_constants.values ]
188
+ lists.flat_map { |list| Array(list) } + lists + [ forbidden_constants ]
189
+ end
190
+ end
191
+ end
@@ -0,0 +1,16 @@
1
+ module BroHub::Safe
2
+ # ActiveRecord attribute type that stores text encrypted with BroHub::Safe::Cipher.
3
+ class EncryptedType < ActiveRecord::Type::Text
4
+ def serialize(value)
5
+ super(value.nil? ? nil : Cipher.encrypt(value))
6
+ end
7
+
8
+ def deserialize(value)
9
+ value.nil? ? nil : Cipher.decrypt(super)
10
+ end
11
+
12
+ def changed_in_place?(raw_old_value, new_value)
13
+ deserialize(raw_old_value) != new_value
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,48 @@
1
+ module BroHub::Safe
2
+ class Error < StandardError; end
3
+
4
+ # Setup problems that stop a console from starting (fail closed).
5
+ class MissingUsername < Error
6
+ def initialize(msg = "SafeBro needs to know who you are. Set CONSOLE_USER (e.g. via SSH SetEnv), or enable config.ask_for_username_if_empty.")
7
+ super
8
+ end
9
+ end
10
+
11
+ class MissingReason < Error
12
+ def initialize(msg = "SafeBro needs a reason for this session. Set CONSOLE_REASON when there is no terminal to ask on.")
13
+ super
14
+ end
15
+ end
16
+
17
+ # The console tables are missing or behind this version of the gem: the console can't record anything.
18
+ class SchemaMissing < Error
19
+ def initialize(msg = "BroHub's tables are missing or out of date. Run bin/rails g bro_hub:install, then bin/rails db:migrate.")
20
+ super
21
+ end
22
+ end
23
+
24
+ class NotInteractive < Error
25
+ def initialize(msg = "This needs an interactive terminal.")
26
+ super
27
+ end
28
+ end
29
+
30
+ # Raised when a console command is not allowed. The command is not executed.
31
+ class ForbiddenCommand < Error; end
32
+
33
+ # Raised when a command tries to change the console audit trail.
34
+ class TamperingAttempt < ForbiddenCommand; end
35
+
36
+ # Raised when a command touches a protected resource while the console is locked.
37
+ class ProtectedResource < ForbiddenCommand
38
+ attr_reader :resource
39
+
40
+ def initialize(resource, detail = nil)
41
+ @resource = resource
42
+ super([ "Access to #{resource} is protected.", detail, "Run unlock! to get access (you will be asked why)." ].compact.join(" "))
43
+ end
44
+ end
45
+
46
+ # Not blocked, but recorded as suspicious.
47
+ class SuspiciousCommand < Error; end
48
+ end
@@ -0,0 +1,142 @@
1
+ module BroHub::Safe
2
+ # Supervises every command typed into the console:
3
+ #
4
+ # * records it (before it runs, so a crash can't hide it)
5
+ # * validates it, blocking forbidden commands and flagging suspicious ones
6
+ # * runs it with the shield's protections on
7
+ # * flags attempts to reach protected resources that happen while it runs
8
+ class Executor
9
+ # console_path: the file name IRB gives the code it evaluates, e.g. "(irb)" or "(myapp)" (Rails
10
+ # names it after the app). It is how we tell typed code from library code.
11
+ def execute(commands, console_path: nil, &block)
12
+ @console_path = console_path if console_path
13
+ statements = Array(commands)
14
+ command = run_as_system { BroHub::Safe.recorder.record_command(statements) }
15
+ previous, @current_command, @reported = @current_command, command, nil
16
+
17
+ if (suspicion = validate(command, statements))
18
+ flag(command, :suspicious, suspicion.message)
19
+ end
20
+
21
+ begin
22
+ execute_in_protected_mode(&block)
23
+ rescue ForbiddenCommand => error
24
+ report(error) unless reported?(error)
25
+ raise masked(error)
26
+ rescue FrozenError => error
27
+ tampering = tampering_message(error)
28
+ flag(command, :blocked, tampering) if tampering
29
+ raise masked(error)
30
+ rescue => error
31
+ raise masked(error)
32
+ end
33
+ ensure
34
+ @current_command, @reported = previous, nil if command
35
+ end
36
+
37
+ # Flags the command being run for an attempt the runtime guards stopped, at the point they stop it: the
38
+ # command may rescue the error itself, and it is still flagged. ProtectedResource is suspicious, any other
39
+ # ForbiddenCommand blocked. Only the first attempt of a command is recorded (a later one only to escalate
40
+ # suspicious to blocked), so a loop of probes doesn't flood the trail.
41
+ def report(error)
42
+ command = @current_command or return
43
+ status = error.is_a?(ProtectedResource) ? :suspicious : :blocked
44
+ return if @reported && (@reported_status == :blocked || status == :suspicious)
45
+
46
+ @reported, @reported_status = error, status
47
+ flag(command, status, error.message)
48
+ end
49
+
50
+ # A suspicion found while the command runs (e.g. a constant built from a string), recorded like the
51
+ # validator's: the command keeps running.
52
+ def report_suspicion(reason)
53
+ command = @current_command or return
54
+ return if @reported || command.flagged?
55
+
56
+ flag(command, :suspicious, reason)
57
+ end
58
+
59
+ # Runs the block with the shield's protections on. The mode itself decides what is
60
+ # protected, depending on what is currently unlocked.
61
+ def execute_in_protected_mode(&block)
62
+ run_as_user { BroHub::Safe.shield.protect(&block) }
63
+ end
64
+
65
+ def run_as_user(&block)
66
+ run_command(true, &block)
67
+ end
68
+
69
+ def run_as_system(&block)
70
+ run_command(false, &block)
71
+ end
72
+
73
+ def executing_user_command?
74
+ @executing_user_command == true
75
+ end
76
+
77
+ # Was this method called straight from what the person typed (as opposed to from library code)?
78
+ # IRB evaluates input under a fixed file name, and C-implemented methods like send or
79
+ # instance_eval don't add frames, so the caller location is still the console.
80
+ def from_console?(locations)
81
+ executing_user_command? && locations.first&.path.to_s == (@console_path || "(irb)")
82
+ end
83
+
84
+ private
85
+ # Returns a suspicion (command still runs) or raises ForbiddenCommand (it doesn't).
86
+ def validate(command, statements)
87
+ run_as_system { BroHub::Safe.validator.validate(statements, locked: BroHub::Safe.shield.locked?) }
88
+ nil
89
+ rescue SuspiciousCommand => suspicion
90
+ suspicion
91
+ rescue ForbiddenCommand => error
92
+ flag(command, :blocked, error.message)
93
+ raise masked(error)
94
+ end
95
+
96
+ def flag(command, status, reason)
97
+ run_as_system { BroHub::Safe.recorder.flag(command, status, reason) }
98
+ Terminal.alert "#{status == :blocked ? 'blocked' : 'flagged for review'} - #{reason}"
99
+ end
100
+
101
+ def reported?(error)
102
+ @reported.equal?(error)
103
+ end
104
+
105
+ # A FrozenError is only tampering when what was frozen is BroHub's own (a class, a guard, the config). The
106
+ # message is fixed: FrozenError#message holds the receiver's inspect, which can be customer data.
107
+ def tampering_message(error)
108
+ receiver = error.receiver
109
+ "Attempt to modify protected code (#{describe(receiver)})" if BroHub::Safe.protected_object?(receiver)
110
+ rescue ArgumentError
111
+ nil # no receiver
112
+ end
113
+
114
+ def describe(receiver)
115
+ receiver.is_a?(Module) ? (receiver.name || "a BroHub guard") : receiver.class.name
116
+ end
117
+
118
+ def run_command(by_user)
119
+ original = @executing_user_command
120
+ @executing_user_command = by_user
121
+ yield
122
+ ensure
123
+ @executing_user_command = original
124
+ end
125
+
126
+ # Error messages are built lazily and IRB prints them after the command finished, i.e.
127
+ # outside the shield. Build them inside it, so they can't leak what the command couldn't read.
128
+ def masked(error)
129
+ %i[ message to_s inspect detailed_message ].each do |name|
130
+ next unless error.respond_to?(name)
131
+
132
+ original = error.method(name)
133
+ error.define_singleton_method(name) do |*args, **kwargs|
134
+ BroHub::Safe.executor.execute_in_protected_mode { original.call(*args, **kwargs) }
135
+ end
136
+ end
137
+ error
138
+ rescue FrozenError
139
+ error
140
+ end
141
+ end
142
+ end
@@ -0,0 +1,42 @@
1
+ module BroHub::Safe
2
+ module Guards
3
+ # Constants can be built from strings (Object.const_get("Bro" + "Hub"), "BroHub".constantize),
4
+ # which the validator can't see. Resolve them through the validator when asked from the console.
5
+ module ConstGuard
6
+ module Lookup
7
+ def const_get(name, *args)
8
+ ConstGuard.check!(name, caller_locations(1, 1)) if BroHub::Safe.executor.executing_user_command?
9
+ super
10
+ end
11
+ end
12
+
13
+ module StringLookup
14
+ def constantize
15
+ ConstGuard.check!(self, caller_locations(1, 1)) if BroHub::Safe.executor.executing_user_command?
16
+ super
17
+ end
18
+
19
+ def safe_constantize
20
+ ConstGuard.check!(self, caller_locations(1, 1)) if BroHub::Safe.executor.executing_user_command?
21
+ super
22
+ end
23
+ end
24
+
25
+ def self.check!(name, locations)
26
+ return unless BroHub::Safe.executor.from_console?(locations)
27
+
28
+ BroHub::Safe.executor.run_as_system { BroHub::Safe.validator.validate(name.to_s, locked: BroHub::Safe.shield.locked?) }
29
+ rescue SuspiciousCommand => suspicion
30
+ # e.g. Object.const_get("EN" + "V"): the name the command never spelled out is flagged, and it still runs.
31
+ BroHub::Safe.executor.report_suspicion(suspicion.message)
32
+ rescue ForbiddenCommand => error
33
+ BroHub::Safe.stop!(error)
34
+ end
35
+
36
+ def self.install
37
+ Module.prepend(Lookup)
38
+ String.prepend(StringLookup)
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,31 @@
1
+ module BroHub::Safe
2
+ module Guards
3
+ # Rails credentials, the keys that open them, and the secret everything is derived from.
4
+ module CredentialsGuard
5
+ # inspect prints the decrypted values once they have been loaded.
6
+ module Inspect
7
+ def inspect
8
+ if BroHub::Safe.executor.executing_user_command? && BroHub::Safe.shield.protects?(:credentials)
9
+ "#<#{self.class.name} [protected]>"
10
+ else
11
+ super
12
+ end
13
+ end
14
+ end
15
+
16
+ def self.install
17
+ if defined?(ActiveSupport::EncryptedConfiguration)
18
+ Guarded.install(ActiveSupport::EncryptedConfiguration,
19
+ %i[ read config options [] fetch dig method_missing instance_variable_get ], :credentials,
20
+ inherited: %i[ instance_variable_get ])
21
+ ActiveSupport::EncryptedConfiguration.prepend(Inspect)
22
+ end
23
+ if defined?(ActiveSupport::EncryptedFile)
24
+ Guarded.install(ActiveSupport::EncryptedFile, %i[ read write change key read_env_key read_key_file ], :credentials)
25
+ end
26
+ Guarded.install(Rails::Application, %i[ secret_key_base secrets key_generator message_verifier message_verifiers ], :credentials)
27
+ Guarded.install(Rails::Application::Configuration, %i[ secret_key_base ], :credentials)
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,90 @@
1
+ module BroHub::Safe
2
+ module Guards
3
+ # ENV holds secrets in most deployments. Reading a protected variable by name raises; dumping
4
+ # the whole thing returns it with the protected values filtered.
5
+ module EnvGuard
6
+ FILTERED = "[FILTERED]".freeze
7
+ # delete returns the value it removed.
8
+ KEYED = %i[ [] fetch delete ].freeze
9
+ MULTI = %i[ values_at fetch_values slice ].freeze
10
+ DUMPS = %i[ to_h to_hash to_a each each_pair each_value select filter reject filter_map values key assoc rassoc invert
11
+ except ].freeze
12
+ # Shown whenever the console prints a value, not only when typed directly. IRB prints with pretty_print.
13
+ DISPLAY = %i[ inspect pretty_print ].freeze
14
+ # ENV's own C methods that hand every value to a block (or swap them all out) without going through #each.
15
+ # Typed at the console while locked they raise: there is nothing to filter them to.
16
+ ITERATING = %i[ shift delete_if keep_if select! filter! reject! replace ].freeze
17
+ # Hand the old value to the block when one is given.
18
+ WITH_BLOCK = %i[ update merge! ].freeze
19
+
20
+ def self.redacted
21
+ ENV.to_h.to_h { |name, value| [ name, BroHub::Safe.config.protected_env_name?(name) ? FILTERED : value ] }
22
+ end
23
+
24
+ def self.guard_name!(name, caller_locations)
25
+ return unless BroHub::Safe.config.protected_env_name?(name)
26
+
27
+ BroHub::Safe.guard!(:env, "(#{name})", locations: caller_locations)
28
+ end
29
+
30
+ module Guard
31
+ EnvGuard::KEYED.each do |method_name|
32
+ define_method(method_name) do |name, *args, **kwargs, &block|
33
+ EnvGuard.guard_name!(name, caller_locations(1, 1)) if BroHub::Safe.executor.executing_user_command?
34
+ super(name, *args, **kwargs, &block)
35
+ end
36
+ end
37
+
38
+ EnvGuard::MULTI.each do |method_name|
39
+ define_method(method_name) do |*names, **kwargs, &block|
40
+ if BroHub::Safe.executor.executing_user_command?
41
+ locations = caller_locations(1, 1)
42
+ names.flatten.each { |name| EnvGuard.guard_name!(name, locations) }
43
+ end
44
+ super(*names, **kwargs, &block)
45
+ end
46
+ end
47
+
48
+ EnvGuard::DUMPS.each do |method_name|
49
+ define_method(method_name) do |*args, **kwargs, &block|
50
+ if BroHub::Safe.executor.executing_user_command? && BroHub::Safe.executor.from_console?(caller_locations(1, 1)) && BroHub::Safe.shield.protects?(:env)
51
+ EnvGuard.redacted.public_send(method_name, *args, **kwargs, &block)
52
+ else
53
+ super(*args, **kwargs, &block)
54
+ end
55
+ end
56
+ end
57
+
58
+ EnvGuard::ITERATING.each do |method_name|
59
+ define_method(method_name) do |*args, **kwargs, &block|
60
+ BroHub::Safe.guard!(:env, "(#{method_name})", locations: caller_locations(1, 1)) if BroHub::Safe.executor.executing_user_command?
61
+ super(*args, **kwargs, &block)
62
+ end
63
+ end
64
+
65
+ EnvGuard::WITH_BLOCK.each do |method_name|
66
+ define_method(method_name) do |*args, **kwargs, &block|
67
+ if block && BroHub::Safe.executor.executing_user_command?
68
+ BroHub::Safe.guard!(:env, "(#{method_name} with a block)", locations: caller_locations(1, 1))
69
+ end
70
+ super(*args, **kwargs, &block)
71
+ end
72
+ end
73
+
74
+ EnvGuard::DISPLAY.each do |method_name|
75
+ define_method(method_name) do |*args, **kwargs, &block|
76
+ if BroHub::Safe.executor.executing_user_command? && BroHub::Safe.shield.protects?(:env)
77
+ EnvGuard.redacted.public_send(method_name, *args, **kwargs, &block)
78
+ else
79
+ super(*args, **kwargs, &block)
80
+ end
81
+ end
82
+ end
83
+ end
84
+
85
+ def self.install
86
+ ENV.singleton_class.prepend(Guard)
87
+ end
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,28 @@
1
+ require "pathname"
2
+ require "fileutils"
3
+
4
+ module BroHub::Safe
5
+ module Guards
6
+ # Files that hold secrets (master.key, .env) can't be read from the console while locked.
7
+ module FileGuard
8
+ def self.protected_path?(path)
9
+ return false unless path.respond_to?(:to_path) || path.is_a?(String)
10
+
11
+ expanded = File.expand_path(path.respond_to?(:to_path) ? path.to_path : path)
12
+ BroHub::Safe.config.protected_file_patterns.any? { |pattern| pattern.match?(expanded) }
13
+ rescue ArgumentError, TypeError
14
+ false
15
+ end
16
+
17
+ def self.install
18
+ by_path = ->(_receiver, args) { protected_path?(args.first) }
19
+ Guarded.install(IO, %i[ read binread readlines foreach ], :files, condition: by_path, scope: :singleton)
20
+ Guarded.install(File, %i[ new open ], :files, condition: by_path, scope: :singleton, inherited: %i[ new open ])
21
+ copying = ->(_receiver, args) { Array(args.first).any? { |path| protected_path?(path) } }
22
+ Guarded.install(FileUtils, %i[ cp copy copy_file cp_r mv move install ], :files, condition: copying, scope: :singleton)
23
+ Guarded.install(Kernel, %i[ open ], :files, condition: by_path)
24
+ Guarded.install(Pathname, %i[ read binread readlines ], :files, condition: ->(receiver, _) { protected_path?(receiver) })
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,51 @@
1
+ module BroHub::Safe
2
+ module Guards
3
+ @built = []
4
+
5
+ # Every guard module built at install time (Guarded, MethodGuard), so lock_down! can freeze them.
6
+ def self.built = @built
7
+
8
+ # Builds and prepends a module that makes the given methods raise ProtectedResource when
9
+ # they are called straight from the console while the resource is locked. Library code
10
+ # calling the same methods is unaffected.
11
+ module Guarded
12
+ class << self
13
+ # condition: ->(receiver, args) { true } narrows which calls are guarded.
14
+ # inherited: names to guard even though the owner doesn't define them itself (the guard
15
+ # then sits in front of the inherited method).
16
+ def install(target, methods, resource, condition: nil, scope: :instance, inherited: [])
17
+ owner = scope == :singleton ? target.singleton_class : target
18
+ guard_module = Module.new
19
+ guarded = 0
20
+
21
+ Array(methods).each do |name|
22
+ visibility = visibility_of(owner, name) || (:public if inherited.include?(name)) or next
23
+ guard_module.define_method(name) do |*args, **kwargs, &block|
24
+ if BroHub::Safe.executor.executing_user_command? && (condition.nil? || condition.call(self, args))
25
+ BroHub::Safe.guard!(resource, "(#{name})", locations: caller_locations(1, 1))
26
+ end
27
+ super(*args, **kwargs, &block)
28
+ end
29
+ guard_module.send(visibility, name)
30
+ guarded += 1
31
+ end
32
+
33
+ return guard_module if guarded.zero?
34
+
35
+ Guards.built << guard_module
36
+ owner.prepend(guard_module)
37
+ guard_module
38
+ end
39
+
40
+ private
41
+ # Only methods the owner itself defines, so subclasses aren't guarded twice.
42
+ def visibility_of(owner, name)
43
+ if owner.public_instance_methods(false).include?(name) then :public
44
+ elsif owner.protected_instance_methods(false).include?(name) then :protected
45
+ elsif owner.private_instance_methods(false).include?(name) then :private
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,23 @@
1
+ module BroHub::Safe
2
+ module Guards
3
+ # Routes everything typed into IRB through the executor.
4
+ module IrbContext
5
+ # Printing the result of a command evaluates #inspect on it, which can read protected data.
6
+ def inspect_last_value(...)
7
+ BroHub::Safe.executor.execute_in_protected_mode { super }
8
+ end
9
+
10
+ def evaluate(statement, ...)
11
+ # irb passes an IRB::Statement; its #code is what was typed.
12
+ code = statement.respond_to?(:code) ? statement.code : statement
13
+ BroHub::Safe.executor.execute(Array(code), console_path: bro_hub_safe_console_path) { super }
14
+ end
15
+
16
+ private
17
+ # The file name the evaluated code runs under.
18
+ def bro_hub_safe_console_path
19
+ respond_to?(:eval_path) ? eval_path : irb_path
20
+ end
21
+ end
22
+ end
23
+ end