aikido-zen 1.0.1.beta.2-x86_64-linux-musl

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 (115) hide show
  1. checksums.yaml +7 -0
  2. data/.aikido +6 -0
  3. data/.ruby-version +1 -0
  4. data/.simplecov +26 -0
  5. data/.standard.yml +3 -0
  6. data/LICENSE +674 -0
  7. data/README.md +146 -0
  8. data/Rakefile +67 -0
  9. data/benchmarks/README.md +23 -0
  10. data/benchmarks/rails7.1_sql_injection.js +70 -0
  11. data/docs/banner.svg +202 -0
  12. data/docs/config.md +125 -0
  13. data/docs/rails.md +70 -0
  14. data/lib/aikido/zen/actor.rb +116 -0
  15. data/lib/aikido/zen/agent/heartbeats_manager.rb +66 -0
  16. data/lib/aikido/zen/agent.rb +179 -0
  17. data/lib/aikido/zen/api_client.rb +142 -0
  18. data/lib/aikido/zen/attack.rb +207 -0
  19. data/lib/aikido/zen/background_worker.rb +52 -0
  20. data/lib/aikido/zen/capped_collections.rb +68 -0
  21. data/lib/aikido/zen/collector/hosts.rb +15 -0
  22. data/lib/aikido/zen/collector/routes.rb +66 -0
  23. data/lib/aikido/zen/collector/sink_stats.rb +95 -0
  24. data/lib/aikido/zen/collector/stats.rb +111 -0
  25. data/lib/aikido/zen/collector/users.rb +30 -0
  26. data/lib/aikido/zen/collector.rb +144 -0
  27. data/lib/aikido/zen/config.rb +279 -0
  28. data/lib/aikido/zen/context/rack_request.rb +24 -0
  29. data/lib/aikido/zen/context/rails_request.rb +42 -0
  30. data/lib/aikido/zen/context.rb +112 -0
  31. data/lib/aikido/zen/detached_agent/agent.rb +78 -0
  32. data/lib/aikido/zen/detached_agent/front_object.rb +37 -0
  33. data/lib/aikido/zen/detached_agent/server.rb +41 -0
  34. data/lib/aikido/zen/detached_agent.rb +2 -0
  35. data/lib/aikido/zen/errors.rb +107 -0
  36. data/lib/aikido/zen/event.rb +71 -0
  37. data/lib/aikido/zen/internals.rb +102 -0
  38. data/lib/aikido/zen/libzen-v0.1.39-x86_64-linux-musl.so +0 -0
  39. data/lib/aikido/zen/middleware/check_allowed_addresses.rb +26 -0
  40. data/lib/aikido/zen/middleware/middleware.rb +11 -0
  41. data/lib/aikido/zen/middleware/rack_throttler.rb +48 -0
  42. data/lib/aikido/zen/middleware/request_tracker.rb +192 -0
  43. data/lib/aikido/zen/middleware/set_context.rb +26 -0
  44. data/lib/aikido/zen/outbound_connection.rb +45 -0
  45. data/lib/aikido/zen/outbound_connection_monitor.rb +23 -0
  46. data/lib/aikido/zen/package.rb +22 -0
  47. data/lib/aikido/zen/payload.rb +50 -0
  48. data/lib/aikido/zen/rails_engine.rb +70 -0
  49. data/lib/aikido/zen/rate_limiter/breaker.rb +61 -0
  50. data/lib/aikido/zen/rate_limiter/bucket.rb +76 -0
  51. data/lib/aikido/zen/rate_limiter/result.rb +31 -0
  52. data/lib/aikido/zen/rate_limiter.rb +50 -0
  53. data/lib/aikido/zen/request/heuristic_router.rb +115 -0
  54. data/lib/aikido/zen/request/rails_router.rb +72 -0
  55. data/lib/aikido/zen/request/schema/auth_discovery.rb +86 -0
  56. data/lib/aikido/zen/request/schema/auth_schemas.rb +54 -0
  57. data/lib/aikido/zen/request/schema/builder.rb +121 -0
  58. data/lib/aikido/zen/request/schema/definition.rb +107 -0
  59. data/lib/aikido/zen/request/schema/empty_schema.rb +28 -0
  60. data/lib/aikido/zen/request/schema.rb +87 -0
  61. data/lib/aikido/zen/request.rb +103 -0
  62. data/lib/aikido/zen/route.rb +39 -0
  63. data/lib/aikido/zen/runtime_settings/endpoints.rb +49 -0
  64. data/lib/aikido/zen/runtime_settings/ip_set.rb +36 -0
  65. data/lib/aikido/zen/runtime_settings/protection_settings.rb +62 -0
  66. data/lib/aikido/zen/runtime_settings/rate_limit_settings.rb +47 -0
  67. data/lib/aikido/zen/runtime_settings.rb +65 -0
  68. data/lib/aikido/zen/scan.rb +75 -0
  69. data/lib/aikido/zen/scanners/path_traversal/helpers.rb +65 -0
  70. data/lib/aikido/zen/scanners/path_traversal_scanner.rb +63 -0
  71. data/lib/aikido/zen/scanners/shell_injection/helpers.rb +159 -0
  72. data/lib/aikido/zen/scanners/shell_injection_scanner.rb +64 -0
  73. data/lib/aikido/zen/scanners/sql_injection_scanner.rb +93 -0
  74. data/lib/aikido/zen/scanners/ssrf/dns_lookups.rb +27 -0
  75. data/lib/aikido/zen/scanners/ssrf/private_ip_checker.rb +97 -0
  76. data/lib/aikido/zen/scanners/ssrf_scanner.rb +265 -0
  77. data/lib/aikido/zen/scanners/stored_ssrf_scanner.rb +49 -0
  78. data/lib/aikido/zen/scanners.rb +7 -0
  79. data/lib/aikido/zen/sink.rb +118 -0
  80. data/lib/aikido/zen/sinks/action_controller.rb +83 -0
  81. data/lib/aikido/zen/sinks/async_http.rb +82 -0
  82. data/lib/aikido/zen/sinks/curb.rb +115 -0
  83. data/lib/aikido/zen/sinks/em_http.rb +85 -0
  84. data/lib/aikido/zen/sinks/excon.rb +121 -0
  85. data/lib/aikido/zen/sinks/file.rb +116 -0
  86. data/lib/aikido/zen/sinks/http.rb +95 -0
  87. data/lib/aikido/zen/sinks/httpclient.rb +97 -0
  88. data/lib/aikido/zen/sinks/httpx.rb +80 -0
  89. data/lib/aikido/zen/sinks/kernel.rb +34 -0
  90. data/lib/aikido/zen/sinks/mysql2.rb +33 -0
  91. data/lib/aikido/zen/sinks/net_http.rb +103 -0
  92. data/lib/aikido/zen/sinks/patron.rb +105 -0
  93. data/lib/aikido/zen/sinks/pg.rb +74 -0
  94. data/lib/aikido/zen/sinks/resolv.rb +62 -0
  95. data/lib/aikido/zen/sinks/socket.rb +80 -0
  96. data/lib/aikido/zen/sinks/sqlite3.rb +49 -0
  97. data/lib/aikido/zen/sinks/trilogy.rb +33 -0
  98. data/lib/aikido/zen/sinks/typhoeus.rb +78 -0
  99. data/lib/aikido/zen/sinks.rb +39 -0
  100. data/lib/aikido/zen/sinks_dsl.rb +226 -0
  101. data/lib/aikido/zen/synchronizable.rb +24 -0
  102. data/lib/aikido/zen/system_info.rb +84 -0
  103. data/lib/aikido/zen/version.rb +10 -0
  104. data/lib/aikido/zen/worker.rb +87 -0
  105. data/lib/aikido/zen.rb +206 -0
  106. data/lib/aikido-zen.rb +3 -0
  107. data/placeholder/.gitignore +4 -0
  108. data/placeholder/README.md +11 -0
  109. data/placeholder/Rakefile +75 -0
  110. data/placeholder/lib/placeholder.rb.template +3 -0
  111. data/placeholder/placeholder.gemspec.template +20 -0
  112. data/tasklib/bench.rake +94 -0
  113. data/tasklib/libzen.rake +132 -0
  114. data/tasklib/wrk.rb +88 -0
  115. metadata +204 -0
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aikido::Zen
4
+ # Stores the firewall configuration sourced from the Aikido dashboard. This
5
+ # object is updated by the Agent regularly.
6
+ #
7
+ # Because the RuntimeSettings object can be modified in runtime, it implements
8
+ # the {Observable} API, allowing you to subscribe to updates. These are
9
+ # triggered whenever #update_from_json makes a change (i.e. if the settings
10
+ # don't change, no update is triggered).
11
+ #
12
+ # You can subscribe to changes with +#add_observer(object, func_name)+, which
13
+ # will call the function passing the settings as an argument.
14
+ RuntimeSettings = Struct.new(:updated_at, :heartbeat_interval, :endpoints, :blocked_user_ids, :skip_protection_for_ips, :received_any_stats) do
15
+ def initialize(*)
16
+ super
17
+ self.endpoints ||= RuntimeSettings::Endpoints.new
18
+ self.skip_protection_for_ips ||= RuntimeSettings::IPSet.new
19
+ end
20
+
21
+ # @!attribute [rw] updated_at
22
+ # @return [Time] when these settings were updated in the Aikido dashboard.
23
+
24
+ # @!attribute [rw] heartbeat_interval
25
+ # @return [Integer] duration in seconds between heartbeat requests to the
26
+ # Aikido server.
27
+
28
+ # @!attribute [rw] received_any_stats
29
+ # @return [Boolean] whether the Aikido server has received any data from
30
+ # this application.
31
+
32
+ # @!attribute [rw] endpoints
33
+ # @return [Aikido::Zen::RuntimeSettings::Endpoints]
34
+
35
+ # @!attribute [rw] blocked_user_ids
36
+ # @return [Array]
37
+
38
+ # @!attribute [rw] skip_protection_for_ips
39
+ # @return [Aikido::Zen::RuntimeSettings::IPSet]
40
+
41
+ # Parse and interpret the JSON response from the core API with updated
42
+ # settings, and apply the changes. This will also notify any subscriber
43
+ # to updates
44
+ #
45
+ # @param data [Hash] the decoded JSON payload from the /api/runtime/config
46
+ # API endpoint.
47
+ #
48
+ # @return [bool]
49
+ def update_from_json(data)
50
+ last_updated_at = updated_at
51
+
52
+ self.updated_at = Time.at(data["configUpdatedAt"].to_i / 1000)
53
+ self.heartbeat_interval = (data["heartbeatIntervalInMS"].to_i / 1000)
54
+ self.endpoints = RuntimeSettings::Endpoints.from_json(data["endpoints"])
55
+ self.blocked_user_ids = data["blockedUserIds"]
56
+ self.skip_protection_for_ips = RuntimeSettings::IPSet.from_json(data["allowedIPAddresses"])
57
+ self.received_any_stats = data["receivedAnyStats"]
58
+
59
+ updated_at != last_updated_at
60
+ end
61
+ end
62
+ end
63
+
64
+ require_relative "runtime_settings/ip_set"
65
+ require_relative "runtime_settings/endpoints"
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aikido::Zen
4
+ # Scans track information about a single call made by one of our Sinks
5
+ # including whether it was detected as an attack or how long it took.
6
+ class Scan
7
+ # @return [Aikido::Zen::Sink] the originating Sink.
8
+ attr_reader :sink
9
+
10
+ # @return [Aikido::Zen::Context] the current Context, wrapping the HTTP
11
+ # request during which this scan was performed.
12
+ attr_reader :context
13
+
14
+ # @return [Aikido::Zen::Attack, nil] a detected Attack, or
15
+ # +nil+ if the scan was considered safe.
16
+ attr_reader :attack
17
+
18
+ # @return [Float, nil] duration in (fractional) seconds of the scan.
19
+ attr_reader :duration
20
+
21
+ # @return [Array<Hash>] list of captured exceptions while scanning.
22
+ attr_reader :errors
23
+
24
+ # @param sink [Aikido::Zen::Sink]
25
+ # @param context [Aikido::Zen::Context]
26
+ def initialize(sink:, context:)
27
+ @sink = sink
28
+ @context = context
29
+ @errors = []
30
+ @performed = false
31
+ end
32
+
33
+ def performed?
34
+ @performed
35
+ end
36
+
37
+ # @return [Boolean] whether this scan detected an Attack.
38
+ def attack?
39
+ @attack != nil
40
+ end
41
+
42
+ # @return [Boolean] whether any errors were caught by this Scan.
43
+ def errors?
44
+ @errors.any?
45
+ end
46
+
47
+ # Runs a block of code, capturing its return value as the potential
48
+ # Attack object (or nil, if safe), and how long it took to run.
49
+ #
50
+ # @yieldreturn [Aikido::Zen::Attack, nil]
51
+ # @return [void]
52
+ def perform
53
+ @performed = true
54
+ started_at = monotonic_time
55
+ @attack = yield
56
+ ensure
57
+ @duration = monotonic_time - started_at
58
+ end
59
+
60
+ # Keep track of exceptions encountered during scanning.
61
+ #
62
+ # @param error [Exception]
63
+ # @param scanner [#call]
64
+ #
65
+ # @return [nil]
66
+ def track_error(error, scanner)
67
+ @errors << {error: error, scanner: scanner}
68
+ nil
69
+ end
70
+
71
+ private def monotonic_time
72
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aikido::Zen
4
+ module Scanners
5
+ module PathTraversal
6
+ DANGEROUS_PATH_PARTS = ["../", "..\\"]
7
+ LINUX_ROOT_FOLDERS = [
8
+ "/bin/",
9
+ "/boot/",
10
+ "/dev/",
11
+ "/etc/",
12
+ "/home/",
13
+ "/init/",
14
+ "/lib/",
15
+ "/media/",
16
+ "/mnt/",
17
+ "/opt/",
18
+ "/proc/",
19
+ "/root/",
20
+ "/run/",
21
+ "/sbin/",
22
+ "/srv/",
23
+ "/sys/",
24
+ "/tmp/",
25
+ "/usr/",
26
+ "/var/"
27
+ ]
28
+
29
+ DANGEROUS_PATH_STARTS = LINUX_ROOT_FOLDERS + ["c:/", "c:\\"]
30
+
31
+ module Helpers
32
+ def self.contains_unsafe_path_parts(filepath)
33
+ DANGEROUS_PATH_PARTS.each do |dangerous_part|
34
+ return true if filepath.include?(dangerous_part)
35
+ end
36
+
37
+ false
38
+ end
39
+
40
+ def self.starts_with_unsafe_path(filepath, user_input)
41
+ # Check if path is relative (not absolute or drive letter path)
42
+ # Required because `expand_path` will build absolute paths from relative paths
43
+ return false if Pathname.new(filepath).relative? || Pathname.new(user_input).relative?
44
+
45
+ normalized_path = File.expand_path__internal_for_aikido_zen(filepath).downcase
46
+ normalized_user_input = File.expand_path__internal_for_aikido_zen(user_input).downcase
47
+
48
+ DANGEROUS_PATH_STARTS.each do |dangerous_start|
49
+ if normalized_path.start_with?(dangerous_start) && normalized_path.start_with?(normalized_user_input)
50
+ # If the user input is the same as the dangerous start, we don't want to flag it
51
+ # to prevent false positives.
52
+ # e.g., if user input is /etc/ and the path is /etc/passwd, we don't want to flag it,
53
+ # as long as the user input does not contain a subdirectory or filename
54
+ if user_input == dangerous_start || user_input == dangerous_start.chomp("/")
55
+ return false
56
+ end
57
+ return true
58
+ end
59
+ end
60
+ false
61
+ end
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "path_traversal/helpers"
4
+
5
+ module Aikido::Zen
6
+ module Scanners
7
+ class PathTraversalScanner
8
+ def self.skips_on_nil_context?
9
+ true
10
+ end
11
+
12
+ # Checks if the user introduced input is trying to access other path using
13
+ # Path Traversal kind of attacks.
14
+ #
15
+ # @param filepath [String] the expanded path that is tried to be read
16
+ # @param context [Aikido::Zen::Context]
17
+ # @param sink [Aikido::Zen::Sink] the Sink that is running the scan.
18
+ # @param operation [Symbol, String] name of the method being scanned.
19
+ #
20
+ # @return [Aikido::Zen::Attacks::PathTraversalAttack, nil] an Attack if any
21
+ # user input is detected to be attempting a Path Traversal Attack, or +nil+ if not.
22
+ def self.call(filepath:, sink:, context:, operation:)
23
+ context.payloads.each do |payload|
24
+ next unless new(filepath, payload.value).attack?
25
+
26
+ return Attacks::PathTraversalAttack.new(
27
+ sink: sink,
28
+ input: payload,
29
+ filepath: filepath,
30
+ context: context,
31
+ operation: "#{sink.operation}.#{operation}"
32
+ )
33
+ end
34
+
35
+ nil
36
+ end
37
+
38
+ def initialize(filepath, input)
39
+ @filepath = filepath.downcase
40
+ @input = input.downcase
41
+ end
42
+
43
+ def attack?
44
+ # Single character are ignored because they don't pose a big threat
45
+ return false if @input.length <= 1
46
+
47
+ # We ignore cases where the user input is longer than the file path.
48
+ # Because the user input can't be part of the file path.
49
+ return false if @input.length > @filepath.length
50
+
51
+ # We ignore cases where the user input is not part of the file path.
52
+ return false unless @filepath.include?(@input)
53
+
54
+ if PathTraversal::Helpers.contains_unsafe_path_parts(@filepath) && PathTraversal::Helpers.contains_unsafe_path_parts(@input)
55
+ return true
56
+ end
57
+
58
+ # Check for absolute path traversal
59
+ PathTraversal::Helpers.starts_with_unsafe_path(@filepath, @input)
60
+ end
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,159 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aikido::Zen::Scanners::ShellInjection
4
+ module Helpers
5
+ ESCAPE_CHARS = %W[' "]
6
+ DANGEROUS_CHARS_INSIDE_DOUBLE_QUOTES = %W[$ ` \\ !]
7
+ DANGEROUS_CHARS = [
8
+ "#", "!", '"', "$", "&", "'", "(", ")", "*", ";", "<", "=", ">", "?",
9
+ "[", "\\", "]", "^", "`", "{", "|", "}", " ", "\n", "\t", "~"
10
+ ]
11
+
12
+ COMMANDS = %w[sleep shutdown reboot poweroff halt ifconfig chmod chown ping
13
+ ssh scp curl wget telnet kill killall rm mv cp touch echo cat head
14
+ tail grep find awk sed sort uniq wc ls env ps who whoami id w df du
15
+ pwd uname hostname netstat passwd arch printenv logname pstree hostnamectl
16
+ set lsattr killall5 dmesg history free uptime finger top shopt :]
17
+
18
+ PATH_PREFIXES = %w[/bin/ /sbin/ /usr/bin/ /usr/sbin/ /usr/local/bin/ /usr/local/sbin/]
19
+
20
+ SEPARATORS = [" ", "\t", "\n", ";", "&", "|", "(", ")", "<", ">"]
21
+
22
+ # @param command [string]
23
+ # @param user_input [string]
24
+ def self.is_safely_encapsulated(command, user_input)
25
+ segments = command.split(user_input)
26
+
27
+ # The next condition is merely here to be compliant with what javascript does when splitting strings:
28
+ # From js doc https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
29
+ # > If separator appears at the beginning (or end) of the string, it still has the effect of splitting,
30
+ # > resulting in an empty (i.e. zero length) string appearing at the first (or last) position of
31
+ # > the returned array.
32
+ # This is necessary because this code is ported form the firewall-node code.
33
+ if user_input.length > 1
34
+ if command.start_with? user_input
35
+ segments.unshift ""
36
+ end
37
+
38
+ if command.end_with? user_input
39
+ segments << ""
40
+ end
41
+ end
42
+
43
+ # Call the helper function to get current and next segments
44
+ get_current_and_next_segments(segments).all? do |segments_pair|
45
+ char_before_user_input = segments_pair[:current_segment][-1]
46
+ char_after_user_input = segments_pair[:next_segment][0]
47
+
48
+ # Check if the character before is an escape character
49
+ is_escape_char = ESCAPE_CHARS.include?(char_before_user_input)
50
+
51
+ unless is_escape_char
52
+ next false
53
+ end
54
+
55
+ # If characters before and after the user input do not match, return false
56
+ next false if char_before_user_input != char_after_user_input
57
+
58
+ # If user input contains the escape character, return false
59
+ next false if user_input.include?(char_before_user_input)
60
+
61
+ # Handle dangerous characters inside double quotes
62
+ if char_before_user_input == '"' && DANGEROUS_CHARS_INSIDE_DOUBLE_QUOTES.any? { |char| user_input.include?(char) }
63
+ next false
64
+ end
65
+
66
+ next true
67
+ end
68
+ end
69
+
70
+ def self.get_current_and_next_segments(segments)
71
+ segments.each_cons(2).map { |current_segment, next_segment| {current_segment: current_segment, next_segment: next_segment} }
72
+ end
73
+
74
+ # Helper function for sorting commands by length (longer commands first)
75
+ def self.by_length(a, b)
76
+ b.length - a.length
77
+ end
78
+
79
+ # Escape characters with special meaning either inside or outside character sets.
80
+ # Use a simple backslash escape when it’s always valid, and a `\xnn` escape when the simpler
81
+ # form would be disallowed by Unicode patterns’ stricter grammar.
82
+ #
83
+ # Inspired by https://github.com/sindresorhus/escape-string-regexp/
84
+ def self.escape_string_regexp(string)
85
+ string.gsub(/[|\\{}()\[\]^$+*?.]/) { "\\#{$&}" }.gsub("-", '\\x2d')
86
+ end
87
+
88
+ # Construct the regex for commands
89
+ COMMANDS_REGEX = Regexp.new(
90
+ "([/.]*((#{PATH_PREFIXES.map { |p| Helpers.escape_string_regexp(p) }.join("|")})?((#{COMMANDS.sort(&method(:by_length)).join("|")}))))",
91
+ Regexp::IGNORECASE
92
+ )
93
+
94
+ def self.contains_shell_syntax(command, user_input)
95
+ # Check if input is only whitespace
96
+ return false if user_input.strip.empty?
97
+
98
+ # Check if the user input contains any dangerous characters
99
+ if DANGEROUS_CHARS.any? { |c| user_input.include?(c) }
100
+ return true
101
+ end
102
+
103
+ # If the command is exactly the same as the user input, check if it matches the regex
104
+ if command == user_input
105
+ return match_all(command, COMMANDS_REGEX).any? do |match|
106
+ match[:match].length == command.length && match[:match] == command
107
+ end
108
+ end
109
+
110
+ # Check if the command contains a commonly used command
111
+ match_all(command, COMMANDS_REGEX).each do |match|
112
+ # We found a command like `rm` or `/sbin/shutdown` in the command
113
+ # Check if the command is the same as the user input
114
+ # If it's not the same, continue searching
115
+ next if user_input != match[:match]
116
+
117
+ # Otherwise, we'll check if the command is surrounded by separators
118
+ # These separators are used to separate commands and arguments
119
+ # e.g. `rm<space>-rf`
120
+ # e.g. `ls<newline>whoami`
121
+ # e.g. `echo<tab>hello` Check if the command is surrounded by separators
122
+ char_before = if match[:index] - 1 < 0
123
+ nil
124
+ else
125
+ command[match[:index] - 1]
126
+ end
127
+
128
+ char_after = if match[:index] + match[:match].length >= command.length
129
+ nil
130
+ else
131
+ command[match[:index] + match[:match].length]
132
+ end
133
+
134
+ # e.g. `<separator>rm<separator>`
135
+ if SEPARATORS.include?(char_before) && SEPARATORS.include?(char_after)
136
+ return true
137
+ end
138
+
139
+ # e.g. `<separator>rm`
140
+ if SEPARATORS.include?(char_before) && char_after.nil?
141
+ return true
142
+ end
143
+
144
+ # e.g. `rm<separator>`
145
+ if char_before.nil? && SEPARATORS.include?(char_after)
146
+ return true
147
+ end
148
+ end
149
+
150
+ false
151
+ end
152
+
153
+ def self.match_all(string, regex)
154
+ string.enum_for(:scan, regex).map do |match|
155
+ {match: match[0], index: $~.begin(0)}
156
+ end
157
+ end
158
+ end
159
+ end
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "shell_injection/helpers"
4
+
5
+ module Aikido::Zen
6
+ module Scanners
7
+ class ShellInjectionScanner
8
+ def self.skips_on_nil_context?
9
+ true
10
+ end
11
+
12
+ # @param command [String]
13
+ # @param sink [Aikido::Zen::Sink]
14
+ # @param context [Aikido::Zen::Context]
15
+ # @param operation [Symbol, String]
16
+ #
17
+ def self.call(command:, sink:, context:, operation:)
18
+ context.payloads.each do |payload|
19
+ next unless new(command, payload.value).attack?
20
+
21
+ return Attacks::ShellInjectionAttack.new(
22
+ sink: sink,
23
+ input: payload,
24
+ command: command,
25
+ context: context,
26
+ operation: "#{sink.operation}.#{operation}"
27
+ )
28
+ end
29
+
30
+ nil
31
+ end
32
+
33
+ # @param command [String]
34
+ # @param input [String]
35
+ def initialize(command, input)
36
+ @command = command
37
+ @input = input
38
+ end
39
+
40
+ def attack?
41
+ # Block single ~ character. For example `echo ~`
42
+ if @input == "~"
43
+ if @command.size > 1 && @command.include?("~")
44
+ return true
45
+ end
46
+ end
47
+
48
+ # we ignore single character since they don't pose a big threat.
49
+ # They are only able to crash the shell, not execute arbitraty commands.
50
+ return false if @input.size <= 1
51
+
52
+ # We ignore cases where the user input is longer than the command because
53
+ # the user input can't be part of the command
54
+ return false if @input.size > @command.size
55
+
56
+ return false unless @command.include?(@input)
57
+
58
+ return false if ShellInjection::Helpers.is_safely_encapsulated @command, @input
59
+
60
+ ShellInjection::Helpers.contains_shell_syntax @command, @input
61
+ end
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../attack"
4
+ require_relative "../internals"
5
+
6
+ module Aikido::Zen
7
+ module Scanners
8
+ class SQLInjectionScanner
9
+ def self.skips_on_nil_context?
10
+ true
11
+ end
12
+
13
+ # Checks if the given SQL query may have dangerous user input injected,
14
+ # and returns an Attack if so, based on the current request.
15
+ #
16
+ # @param query [String]
17
+ # @param context [Aikido::Zen::Context]
18
+ # @param sink [Aikido::Zen::Sink] the Sink that is running the scan.
19
+ # @param dialect [Symbol] one of +:mysql+, +:postgesql+, or +:sqlite+.
20
+ # @param operation [Symbol, String] name of the method being scanned.
21
+ # Expects +sink.operation+ being set to get the full module/name combo.
22
+ #
23
+ # @return [Aikido::Zen::Attack, nil] an Attack if any user input is
24
+ # detected to be attempting a SQL injection, or nil if this is safe.
25
+ #
26
+ # @raise [Aikido::Zen::InternalsError] if an error occurs when loading or
27
+ # calling zenlib. See Sink#scan.
28
+ def self.call(query:, dialect:, sink:, context:, operation:)
29
+ dialect = DIALECTS.fetch(dialect) do
30
+ Aikido::Zen.config.logger.warn "Unknown SQL dialect #{dialect.inspect}"
31
+ DIALECTS[:common]
32
+ end
33
+
34
+ context.payloads.each do |payload|
35
+ next unless new(query, payload.value, dialect).attack?
36
+
37
+ return Attacks::SQLInjectionAttack.new(
38
+ sink: sink,
39
+ query: query,
40
+ input: payload,
41
+ dialect: dialect,
42
+ context: context,
43
+ operation: "#{sink.operation}.#{operation}"
44
+ )
45
+ end
46
+
47
+ nil
48
+ end
49
+
50
+ def initialize(query, input, dialect)
51
+ @query = query.downcase
52
+ @input = input.downcase
53
+ @dialect = dialect
54
+ end
55
+
56
+ def attack?
57
+ # Ignore single char inputs since they shouldn't be able to do much harm
58
+ return false if @input.length <= 1
59
+
60
+ # If the input is longer than the query, then it is not part of it
61
+ return false if @input.length > @query.length
62
+
63
+ # If the input is not included in the query at all, then we are safe
64
+ return false unless @query.include?(@input)
65
+
66
+ # If the input is solely alphanumeric, we can ignore it
67
+ return false if /\A[[:alnum:]_]+\z/i.match?(@input)
68
+
69
+ # If the input is a comma-separated list of numbers, ignore it.
70
+ return false if /\A(?:\d+(?:,\s*)?)+\z/i.match?(@input)
71
+
72
+ Internals.detect_sql_injection(@query, @input, @dialect)
73
+ end
74
+
75
+ # @api private
76
+ Dialect = Struct.new(:name, :internals_key, keyword_init: true) do
77
+ alias_method :to_s, :name
78
+ alias_method :to_int, :internals_key
79
+ end
80
+
81
+ # Maps easy-to-use Symbols to a struct that keeps both the name and the
82
+ # internal identifier used by libzen.
83
+ #
84
+ # @see https://github.com/AikidoSec/zen-internals/blob/main/src/sql_injection/helpers/select_dialect_based_on_enum.rs
85
+ DIALECTS = {
86
+ common: Dialect.new(name: "SQL", internals_key: 0),
87
+ mysql: Dialect.new(name: "MySQL", internals_key: 8),
88
+ postgresql: Dialect.new(name: "PostgreSQL", internals_key: 9),
89
+ sqlite: Dialect.new(name: "SQLite", internals_key: 12)
90
+ }
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "delegate"
4
+
5
+ module Aikido::Zen
6
+ module Scanners
7
+ module SSRF
8
+ # Simple per-request cache of all DNS lookups performed for a given host.
9
+ # We can store this in the context after performing a lookup, and have the
10
+ # SSRF scanner make sure the hostname being inspected doesn't actually
11
+ # resolve to an internal/dangerous IP.
12
+ class DNSLookups < SimpleDelegator
13
+ def initialize
14
+ super(Hash.new { |h, k| h[k] = [] })
15
+ end
16
+
17
+ def add(hostname, addresses)
18
+ self[hostname].concat(Array(addresses))
19
+ end
20
+
21
+ def ===(hostname)
22
+ key?(hostname)
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end