aikido-zen 1.0.2.beta.2-aarch64-linux

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 (116) 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/proxy.md +10 -0
  14. data/docs/rails.md +114 -0
  15. data/lib/aikido/zen/actor.rb +116 -0
  16. data/lib/aikido/zen/agent/heartbeats_manager.rb +66 -0
  17. data/lib/aikido/zen/agent.rb +179 -0
  18. data/lib/aikido/zen/api_client.rb +145 -0
  19. data/lib/aikido/zen/attack.rb +207 -0
  20. data/lib/aikido/zen/background_worker.rb +52 -0
  21. data/lib/aikido/zen/capped_collections.rb +68 -0
  22. data/lib/aikido/zen/collector/hosts.rb +15 -0
  23. data/lib/aikido/zen/collector/routes.rb +66 -0
  24. data/lib/aikido/zen/collector/sink_stats.rb +95 -0
  25. data/lib/aikido/zen/collector/stats.rb +111 -0
  26. data/lib/aikido/zen/collector/users.rb +30 -0
  27. data/lib/aikido/zen/collector.rb +144 -0
  28. data/lib/aikido/zen/config.rb +282 -0
  29. data/lib/aikido/zen/context/rack_request.rb +24 -0
  30. data/lib/aikido/zen/context/rails_request.rb +44 -0
  31. data/lib/aikido/zen/context.rb +112 -0
  32. data/lib/aikido/zen/detached_agent/agent.rb +78 -0
  33. data/lib/aikido/zen/detached_agent/front_object.rb +37 -0
  34. data/lib/aikido/zen/detached_agent/server.rb +78 -0
  35. data/lib/aikido/zen/detached_agent.rb +2 -0
  36. data/lib/aikido/zen/errors.rb +107 -0
  37. data/lib/aikido/zen/event.rb +71 -0
  38. data/lib/aikido/zen/internals.rb +103 -0
  39. data/lib/aikido/zen/libzen-v0.1.39-aarch64-linux.so +0 -0
  40. data/lib/aikido/zen/middleware/check_allowed_addresses.rb +26 -0
  41. data/lib/aikido/zen/middleware/middleware.rb +11 -0
  42. data/lib/aikido/zen/middleware/rack_throttler.rb +48 -0
  43. data/lib/aikido/zen/middleware/request_tracker.rb +192 -0
  44. data/lib/aikido/zen/middleware/set_context.rb +26 -0
  45. data/lib/aikido/zen/outbound_connection.rb +45 -0
  46. data/lib/aikido/zen/outbound_connection_monitor.rb +23 -0
  47. data/lib/aikido/zen/package.rb +22 -0
  48. data/lib/aikido/zen/payload.rb +50 -0
  49. data/lib/aikido/zen/rails_engine.rb +56 -0
  50. data/lib/aikido/zen/rate_limiter/breaker.rb +61 -0
  51. data/lib/aikido/zen/rate_limiter/bucket.rb +76 -0
  52. data/lib/aikido/zen/rate_limiter/result.rb +31 -0
  53. data/lib/aikido/zen/rate_limiter.rb +50 -0
  54. data/lib/aikido/zen/request/heuristic_router.rb +115 -0
  55. data/lib/aikido/zen/request/rails_router.rb +77 -0
  56. data/lib/aikido/zen/request/schema/auth_discovery.rb +86 -0
  57. data/lib/aikido/zen/request/schema/auth_schemas.rb +54 -0
  58. data/lib/aikido/zen/request/schema/builder.rb +121 -0
  59. data/lib/aikido/zen/request/schema/definition.rb +107 -0
  60. data/lib/aikido/zen/request/schema/empty_schema.rb +28 -0
  61. data/lib/aikido/zen/request/schema.rb +87 -0
  62. data/lib/aikido/zen/request.rb +122 -0
  63. data/lib/aikido/zen/route.rb +39 -0
  64. data/lib/aikido/zen/runtime_settings/endpoints.rb +49 -0
  65. data/lib/aikido/zen/runtime_settings/ip_set.rb +36 -0
  66. data/lib/aikido/zen/runtime_settings/protection_settings.rb +62 -0
  67. data/lib/aikido/zen/runtime_settings/rate_limit_settings.rb +47 -0
  68. data/lib/aikido/zen/runtime_settings.rb +65 -0
  69. data/lib/aikido/zen/scan.rb +75 -0
  70. data/lib/aikido/zen/scanners/path_traversal/helpers.rb +65 -0
  71. data/lib/aikido/zen/scanners/path_traversal_scanner.rb +63 -0
  72. data/lib/aikido/zen/scanners/shell_injection/helpers.rb +159 -0
  73. data/lib/aikido/zen/scanners/shell_injection_scanner.rb +64 -0
  74. data/lib/aikido/zen/scanners/sql_injection_scanner.rb +93 -0
  75. data/lib/aikido/zen/scanners/ssrf/dns_lookups.rb +27 -0
  76. data/lib/aikido/zen/scanners/ssrf/private_ip_checker.rb +97 -0
  77. data/lib/aikido/zen/scanners/ssrf_scanner.rb +265 -0
  78. data/lib/aikido/zen/scanners/stored_ssrf_scanner.rb +49 -0
  79. data/lib/aikido/zen/scanners.rb +7 -0
  80. data/lib/aikido/zen/sink.rb +118 -0
  81. data/lib/aikido/zen/sinks/action_controller.rb +83 -0
  82. data/lib/aikido/zen/sinks/async_http.rb +80 -0
  83. data/lib/aikido/zen/sinks/curb.rb +113 -0
  84. data/lib/aikido/zen/sinks/em_http.rb +83 -0
  85. data/lib/aikido/zen/sinks/excon.rb +118 -0
  86. data/lib/aikido/zen/sinks/file.rb +112 -0
  87. data/lib/aikido/zen/sinks/http.rb +93 -0
  88. data/lib/aikido/zen/sinks/httpclient.rb +95 -0
  89. data/lib/aikido/zen/sinks/httpx.rb +78 -0
  90. data/lib/aikido/zen/sinks/kernel.rb +33 -0
  91. data/lib/aikido/zen/sinks/mysql2.rb +31 -0
  92. data/lib/aikido/zen/sinks/net_http.rb +101 -0
  93. data/lib/aikido/zen/sinks/patron.rb +103 -0
  94. data/lib/aikido/zen/sinks/pg.rb +72 -0
  95. data/lib/aikido/zen/sinks/resolv.rb +62 -0
  96. data/lib/aikido/zen/sinks/socket.rb +78 -0
  97. data/lib/aikido/zen/sinks/sqlite3.rb +46 -0
  98. data/lib/aikido/zen/sinks/trilogy.rb +31 -0
  99. data/lib/aikido/zen/sinks/typhoeus.rb +78 -0
  100. data/lib/aikido/zen/sinks.rb +36 -0
  101. data/lib/aikido/zen/sinks_dsl.rb +250 -0
  102. data/lib/aikido/zen/synchronizable.rb +24 -0
  103. data/lib/aikido/zen/system_info.rb +84 -0
  104. data/lib/aikido/zen/version.rb +10 -0
  105. data/lib/aikido/zen/worker.rb +87 -0
  106. data/lib/aikido/zen.rb +246 -0
  107. data/lib/aikido-zen.rb +3 -0
  108. data/placeholder/.gitignore +4 -0
  109. data/placeholder/README.md +11 -0
  110. data/placeholder/Rakefile +75 -0
  111. data/placeholder/lib/placeholder.rb.template +3 -0
  112. data/placeholder/placeholder.gemspec.template +20 -0
  113. data/tasklib/bench.rake +94 -0
  114. data/tasklib/libzen.rake +133 -0
  115. data/tasklib/wrk.rb +88 -0
  116. metadata +205 -0
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ipaddr"
4
+
5
+ module Aikido::Zen
6
+ # Models a list of IP addresses or CIDR blocks, where we can check if a given
7
+ # address is part of any of the members.
8
+ class RuntimeSettings::IPSet
9
+ def self.from_json(ips)
10
+ new(Array(ips).map { |ip| IPAddr.new(ip) })
11
+ end
12
+
13
+ def initialize(ips = Set.new)
14
+ @ips = ips.to_set
15
+ end
16
+
17
+ def empty?
18
+ @ips.empty?
19
+ end
20
+
21
+ def include?(ip)
22
+ @ips.any? { |pattern| pattern === ip }
23
+ end
24
+ alias_method :===, :include?
25
+
26
+ def ==(other)
27
+ other.is_a?(RuntimeSettings::IPSet) && to_set == other.to_set
28
+ end
29
+
30
+ protected
31
+
32
+ def to_set
33
+ @ips
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "ip_set"
4
+ require_relative "rate_limit_settings"
5
+
6
+ module Aikido::Zen
7
+ # Models the settings for a given Route as configured in the Aikido UI.
8
+ class RuntimeSettings::ProtectionSettings
9
+ # @return [Aikido::Zen::RuntimeSettings::ProtectionSettings] singleton
10
+ # instance for endpoints with no configured protections on a given route,
11
+ # that can be used as a default value for routes.
12
+ def self.none
13
+ @no_settings ||= new
14
+ end
15
+
16
+ # Initialize settings from an API response.
17
+ #
18
+ # @param data [Hash] the deserialized JSON data.
19
+ # @option data [Boolean] "forceProtectionOff" whether the user has
20
+ # disabled attack protection for this route.
21
+ # @option data [Array<String>] "allowedIPAddresses" the list of IPs that
22
+ # can make requests to this endpoint.
23
+ # @option data [Hash] "rateLimiting" the rate limiting options for this
24
+ # endpoint. See {Aikido::Zen::RuntimeSettings::RateLimitSettings.from_json}.
25
+ #
26
+ # @return [Aikido::Zen::RuntimeSettings::ProtectionSettings]
27
+ # @raise [IPAddr::InvalidAddressError] if any of the IPs in
28
+ # "allowedIPAddresses" is not a valid address or family.
29
+ def self.from_json(data)
30
+ ips = RuntimeSettings::IPSet.from_json(data["allowedIPAddresses"])
31
+ rate_limiting = RuntimeSettings::RateLimitSettings.from_json(data["rateLimiting"])
32
+
33
+ new(
34
+ protected: !data["forceProtectionOff"],
35
+ allowed_ips: ips,
36
+ rate_limiting: rate_limiting
37
+ )
38
+ end
39
+
40
+ # @return [Aikido::Zen::RuntimeSettings::IPSet] list of IP addresses which
41
+ # are allowed to make requests on this route. If empty, all IP addresses
42
+ # are allowed.
43
+ attr_reader :allowed_ips
44
+
45
+ # @return [Aikido::Zen::RuntimeSettings::RateLimitSettings]
46
+ attr_reader :rate_limiting
47
+
48
+ def initialize(
49
+ protected: true,
50
+ allowed_ips: RuntimeSettings::IPSet.new,
51
+ rate_limiting: RuntimeSettings::RateLimitSettings.disabled
52
+ )
53
+ @protected = !!protected
54
+ @rate_limiting = rate_limiting
55
+ @allowed_ips = allowed_ips
56
+ end
57
+
58
+ def protected?
59
+ @protected
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aikido::Zen
4
+ # Simple data object that holds the configuration for rate limiting a given
5
+ # endpoint.
6
+ class RuntimeSettings::RateLimitSettings
7
+ # Initialize the settings from an API response.
8
+ #
9
+ # @param data [Hash] the deserialized JSON data.
10
+ # @option data [Boolean] "enabled"
11
+ # @option data [Integer] "maxRequests"
12
+ # @option data [Integer] "windowSizeInMS"
13
+ #
14
+ # @return [Aikido::Zen::RateLimitSettings]
15
+ def self.from_json(data)
16
+ new(
17
+ enabled: !!data["enabled"],
18
+ max_requests: Integer(data["maxRequests"]),
19
+ period: Integer(data["windowSizeInMS"]) / 1000
20
+ )
21
+ end
22
+
23
+ # Initializes a disabled object that we can use as a default value for
24
+ # endpoints that have not configured rate limiting.
25
+ #
26
+ # @return [Aikido::Zen::RuntimeSettings::RateLimitSettings]
27
+ def self.disabled
28
+ new(enabled: false)
29
+ end
30
+
31
+ # @return [Integer] the fixed window to bucket requests in, in seconds.
32
+ attr_reader :period
33
+
34
+ # @return [Integer]
35
+ attr_reader :max_requests
36
+
37
+ def initialize(enabled: false, max_requests: 1000, period: 60)
38
+ @enabled = enabled
39
+ @period = period
40
+ @max_requests = max_requests
41
+ end
42
+
43
+ def enabled?
44
+ @enabled
45
+ end
46
+ end
47
+ end
@@ -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