omamori 0.1.1 → 0.1.2
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.
- checksums.yaml +4 -4
- data/Gemfile +0 -3
- data/Gemfile.lock +3 -11
- data/lib/omamori/ai_analysis_engine/gemini_client.rb +2 -1
- data/lib/omamori/ai_analysis_engine/prompt_manager.rb +70 -36
- data/lib/omamori/version.rb +1 -1
- metadata +16 -24
- data/demo_/ai_analysis_vulnerability.rb +0 -28
- data/demo_/csrf_vulnerability.rb +0 -31
- data/demo_/eval_vulnerability.rb +0 -29
- data/demo_/idor_vulnerability.rb +0 -39
- data/demo_/insecure_cookie_vulnerability.rb +0 -25
- data/demo_/open_redirect_vulnerability.rb +0 -22
- data/demo_/static_analysis_vulnerability.rb +0 -18
- data/demo_/xss_vulnerability.rb +0 -21
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
2
|
SHA256:
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
3
|
+
metadata.gz: 2c6e52c517c84f78c559299c80b6d0c3817ea6b1cc7cdb9e0bc041bb2c6ccad1
|
4
|
+
data.tar.gz: c654919d2b1db48f3bb286e55ccd8909a82b9c69d4c3fd88d67fadfe03a621e7
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: ded5134ca28c5835ba121b637c7105a5cbe6930777275562fbc49b45fcfc021ddb7d57f5c26c1bbb5958a56f52d1f7e9df6175de1274de19fee2683081db3bfa
|
7
|
+
data.tar.gz: c495125630ff1467816c47c21888d4e984c08a5e074cc8f904a10045860c11e17212432ef146bd5a37324601589dca67c4ffe1546b2196518d9b3faa216e79cf
|
data/Gemfile
CHANGED
data/Gemfile.lock
CHANGED
@@ -1,19 +1,15 @@
|
|
1
1
|
PATH
|
2
2
|
remote: .
|
3
3
|
specs:
|
4
|
-
omamori (0.1.
|
4
|
+
omamori (0.1.2)
|
5
5
|
colorize (~> 0.8)
|
6
6
|
dotenv (~> 2.0)
|
7
|
+
ruby-gemini-api (~> 0.1.1)
|
7
8
|
|
8
9
|
GEM
|
9
10
|
remote: https://rubygems.org/
|
10
11
|
specs:
|
11
12
|
ast (2.4.3)
|
12
|
-
brakeman (7.0.2)
|
13
|
-
racc
|
14
|
-
bundler-audit (0.9.2)
|
15
|
-
bundler (>= 1.2.0, < 3)
|
16
|
-
thor (~> 1.0)
|
17
13
|
colorize (0.8.1)
|
18
14
|
diff-lcs (1.6.1)
|
19
15
|
dotenv (2.8.1)
|
@@ -68,12 +64,11 @@ GEM
|
|
68
64
|
rubocop-ast (1.44.1)
|
69
65
|
parser (>= 3.3.7.2)
|
70
66
|
prism (~> 1.4)
|
71
|
-
ruby-gemini-api (0.1.
|
67
|
+
ruby-gemini-api (0.1.1)
|
72
68
|
faraday (~> 2.0)
|
73
69
|
faraday-multipart (~> 1.0)
|
74
70
|
json (~> 2.0)
|
75
71
|
ruby-progressbar (1.13.0)
|
76
|
-
thor (1.3.2)
|
77
72
|
unicode-display_width (3.1.4)
|
78
73
|
unicode-emoji (~> 4.0, >= 4.0.4)
|
79
74
|
unicode-emoji (4.0.4)
|
@@ -84,14 +79,11 @@ PLATFORMS
|
|
84
79
|
x86_64-linux
|
85
80
|
|
86
81
|
DEPENDENCIES
|
87
|
-
brakeman (~> 7.0)
|
88
82
|
bundler (~> 2.0)
|
89
|
-
bundler-audit (~> 0.9.2)
|
90
83
|
omamori!
|
91
84
|
rake (~> 13.0)
|
92
85
|
rspec (~> 3.0)
|
93
86
|
rubocop (~> 1.0)
|
94
|
-
ruby-gemini-api (~> 0.1.0)
|
95
87
|
|
96
88
|
BUNDLED WITH
|
97
89
|
2.5.17
|
@@ -18,7 +18,8 @@ module Omamori
|
|
18
18
|
response = @client.generate_content(
|
19
19
|
prompt,
|
20
20
|
model: model,
|
21
|
-
response_schema: json_schema # Use response_schema for Structured Output
|
21
|
+
response_schema: json_schema, # Use response_schema for Structured Output
|
22
|
+
temperature: 0.0
|
22
23
|
)
|
23
24
|
|
24
25
|
# Debug: Inspect the response object
|
@@ -5,7 +5,7 @@ module Omamori
|
|
5
5
|
class PromptManager
|
6
6
|
# TODO: Load prompt templates from config file
|
7
7
|
DEFAULT_PROMPT_TEMPLATE = <<~TEXT
|
8
|
-
You are a security expert specializing in Ruby. Analyze the following code and detect any potential security risks.
|
8
|
+
You are a security expert specializing in Ruby. Analyze the following code and detect any potential security risks. Think step by step.
|
9
9
|
Focus particularly on identifying the following types of vulnerabilities: %{risk_list}
|
10
10
|
Report any detected risks in the format specified by the following JSON Schema:
|
11
11
|
%{json_schema}
|
@@ -16,43 +16,77 @@ module Omamori
|
|
16
16
|
%{code_content}
|
17
17
|
TEXT
|
18
18
|
|
19
|
+
# dangerous_eval の説明、脆弱なRubyコード例、検出ステップ(導入文付き)を定義する文字列
|
20
|
+
dangerous_eval_prompt = <<~PROMPT
|
21
|
+
Dangerous Code Execution (eval, exec): Dynamic code execution using untrusted input, allowing arbitrary code injection.
|
19
22
|
|
23
|
+
**Vulnerable Ruby Code Examples:**
|
24
|
+
```ruby
|
25
|
+
# Direct eval of user input (e.g., from HTTP parameters like params[:user_code])
|
26
|
+
result = eval(params[:user_code])
|
27
|
+
|
28
|
+
# User input embedded in evaluated string (String interpolation)
|
29
|
+
log_message = "User action: \#{params[:action]}"
|
30
|
+
# Even if log_message seems harmless, injecting code like "'); malicious_code; # " might be possible
|
31
|
+
eval("log('\#{log_message}')") # Note: Interpolation inside eval string needs care with escaping
|
32
|
+
|
33
|
+
# OS Command injection via system() or backticks (`) using user input
|
34
|
+
# Assumes params[:directory] or params[:filename] comes directly from user input
|
35
|
+
output = `ls \#{params[:directory]}` # User input determines command executed
|
36
|
+
system("process_file.sh \#{params[:filename]}") # User input determines command argument
|
37
|
+
|
38
|
+
# Dynamic method invocation using send() or public_send() with user-controlled method names or arguments
|
39
|
+
# Assumes params[:method_name] or params[:argument] comes from user input
|
40
|
+
target_object = SomeClass.new
|
41
|
+
target_object.send(params[:method_name], params[:argument]) # User can potentially call dangerous methods
|
42
|
+
|
43
|
+
# Using instance_eval or class_eval with user-provided code strings
|
44
|
+
user_script = params[:custom_script]
|
45
|
+
some_object.instance_eval(user_script) # Executes arbitrary Ruby code in the object's context
|
46
|
+
To detect code vulnerable to Dangerous Code Execution like the examples provided above, perform the following detection steps:
|
47
|
+
|
48
|
+
Search for methods enabling dynamic code execution in Ruby code (e.g., eval, instance_eval, class_eval, send, public_send, system, exec, backticks `).
|
49
|
+
Check if arguments passed to these methods originate from or are directly influenced by external untrusted input (e.g., HTTP request parameters params, data from files, network responses). Look for patterns similar to the vulnerable Ruby examples shown above.
|
50
|
+
Verify if user input is rigorously sanitized or validated specifically to prevent code injection vectors before being used in these methods. Standard escaping for HTML (like XSS prevention) is not sufficient here. Check if execution is restricted only to a predefined, absolutely safe allowlist of commands or methods if dynamic execution cannot be avoided.
|
51
|
+
Assess if safer alternatives exist that can achieve the same functionality without dynamic code execution. Examples include using Hash lookups for dispatching actions, case statements based on input values, leveraging safe templating engines, or using specific library functions designed for the task instead of generic execution methods.
|
52
|
+
PROMPT
|
53
|
+
|
20
54
|
RISK_PROMPTS = {
|
21
|
-
xss: "Cross-Site Scripting (XSS): A vulnerability where user input is not properly escaped and is embedded into HTML or JavaScript, leading to arbitrary script execution in the victim
|
22
|
-
csrf: "Cross-Site Request Forgery (CSRF): An attack that forces an authenticated user to perform unwanted actions via forged requests.
|
23
|
-
idor: "Insecure Direct Object Reference (IDOR): Occurs when object identifiers (e.g., IDs) are exposed and access control is missing, allowing unauthorized access to other users
|
24
|
-
open_redirect: "Open Redirect: Redirecting users to external URLs based on user-supplied input without proper validation. Check
|
25
|
-
ssrf: "Server-Side Request Forgery (SSRF): The server makes HTTP requests to an arbitrary destination supplied by the user, potentially exposing internal resources or metadata.",
|
26
|
-
session_fixation: "Session Fixation: The server accepts a pre-supplied session ID, allowing an attacker to hijack the session after authentication. Look for
|
27
|
-
inappropriate_cookie_attributes: "Insecure Cookie Attributes: Missing HttpOnly, Secure, or SameSite flags, which may lead to session theft or CSRF.",
|
28
|
-
insufficient_encryption: "Insufficient Encryption: Use of weak algorithms (e.g., MD5, SHA1) or lack of encryption for sensitive data. Check for insecure hash functions or plain-text handling.",
|
29
|
-
insecure_deserialization_rce: "Insecure Deserialization leading to RCE: Deserializing untrusted data can lead to arbitrary code execution. Detect unsafe use of deserialization functions without validation.",
|
30
|
-
directory_traversal: "Directory Traversal: Allows attackers to access files outside the intended directory using ../ patterns. Check for path manipulation and missing canonicalization.",
|
31
|
-
dangerous_eval: "Dangerous Code Execution (eval, exec): Dynamic code execution using untrusted input, allowing arbitrary code injection.",
|
32
|
-
inappropriate_file_permissions: "Insecure File Permissions: Files or directories with overly permissive modes (e.g., 777), allowing unauthorized read/write/execute access.",
|
33
|
-
temporary_backup_file_leak: "Temporary or Backup File Exposure: Sensitive files like .bak, .tmp, or ~ versions are publicly accessible due to poor file handling.",
|
34
|
-
overly_detailed_errors: "Excessive Error Information Disclosure: Stack traces or internal error messages exposed to users, leaking implementation details.",
|
35
|
-
csp_not_set: "Missing Content Security Policy (CSP): Absence of CSP headers increases risk of XSS. Look for missing Content-Security-Policy header.",
|
36
|
-
mime_sniffing_vulnerability: "MIME Sniffing Vulnerability: Missing X-Content-Type-Options: nosniff header can allow browsers to misinterpret content types.",
|
37
|
-
clickjacking_vulnerability: "Clickjacking Protection Missing: Absence of X-Frame-Options or frame-ancestors directive allows malicious framing of pages.",
|
38
|
-
auto_index_exposure: "Auto Indexing Enabled: Directory listing is active, exposing files and internal structure to users.",
|
39
|
-
inappropriate_password_policy: "Weak Password Policy: Inadequate rules such as short length, lack of complexity, or missing brute-force protections.",
|
40
|
-
two_factor_auth_missing: "Missing Two-Factor Authentication (2FA): Lack of secondary authentication factor for sensitive operations.",
|
41
|
-
race_condition: "Race Condition: Concurrent access without proper locking can lead to inconsistent states or privilege escalation.",
|
42
|
-
server_error_information_exposure: "Server Error Information Exposure: Internal errors (e.g., 500) reveal stack traces or server information in responses.",
|
43
|
-
dependency_trojan_package: "Dependency Trojan Package Risk: Installation of malicious or typosquatted packages from untrusted sources.",
|
44
|
-
api_overexposure: "Excessive API Exposure: Public APIs exposed without authentication, leading to data leakage or unauthorized access.",
|
45
|
-
security_middleware_disabled: "Security Middleware Disabled: Important protections (e.g., CSRF tokens, input sanitization) are turned off or removed.",
|
46
|
-
security_header_inconsistency: "Security Header Inconsistency: Inconsistent or missing security headers across environments or routes.",
|
47
|
-
excessive_login_attempts: "Excessive Login Attempts Allowed: Lack of rate limiting allows brute-force login attempts.",
|
48
|
-
inappropriate_cache_settings: "Insecure Cache Settings: Sensitive pages are cached publicly (e.g., with Cache-Control: public), risking data leakage.",
|
49
|
-
secret_key_committed: "Secret Key Committed to Repository: Credentials, JWT secrets, or API keys are hardcoded or pushed to version control.",
|
50
|
-
third_party_script_validation_missing:
|
51
|
-
over_logging: "Over-Logging: Logging sensitive information such as passwords, tokens, or personal data.",
|
52
|
-
fail_open_design: "Fail-Open Design: On error or exception, access is granted instead of safely denied.",
|
53
|
-
environment_differences: "Uncontrolled Environment Differences: Security settings differ between development and production without strict controls.",
|
54
|
-
audit_log_missing: "Missing Audit Logging: Lack of logging for critical actions or authorization checks prevents accountability.",
|
55
|
-
time_based_side_channel: "Time-Based Side Channel: Execution time differences can leak secrets (e.g., timing attacks in string comparison)."
|
55
|
+
xss: "Cross-Site Scripting (XSS): A vulnerability where user input is not properly escaped and is embedded into HTML or JavaScript, leading to arbitrary script execution in the victim's browser. Detection steps: 1) Identify where user input is output to HTML/JS context. 2) Check if proper encoding/escaping is applied (e.g., html_safe, raw, sanitize, escape_javascript). 3) Look for unsafe methods that bypass default Rails escaping (html_safe, raw, <%==). 4) Examine JavaScript that incorporates user input via template interpolation. 5) Check for improper content-type headers that might enable XSS. 6) Verify if user input is passed to eval(), setTimeout(), document.write() or DOM manipulation functions. 7) Look for attribute injection possibilities where user input sets HTML attributes.",
|
56
|
+
csrf: "Cross-Site Request Forgery (CSRF): An attack that forces an authenticated user to perform unwanted actions via forged requests. Detection steps: 1) Check if CSRF protection is disabled globally or for specific controllers/actions (skip_before_action :verify_authenticity_token). 2) Look for APIs or endpoints that handle state-changing operations (POST, PUT, DELETE methods). 3) Verify if authenticity tokens are properly validated for forms and AJAX requests. 4) Check if the application relies solely on cookies for authentication without additional CSRF protection. 5) Look for custom CSRF protection implementations that might be incomplete. 6) Verify if SameSite cookie attributes are properly set. 7) Check if the application validates the Origin or Referer header for cross-origin requests.",
|
57
|
+
idor: "Insecure Direct Object Reference (IDOR): Occurs when object identifiers (e.g., IDs) are exposed and access control is missing, allowing unauthorized access to other users' data. Detection steps: 1) Identify endpoints that access data using user-supplied identifiers (e.g., params[:id]). 2) Check if proper authorization checks exist before accessing the data (e.g., current_user.orders vs Order.find). 3) Look for functions retrieving data without verifying the current user's ownership or access rights. 4) Check for sequential or predictable IDs that can be enumerated. 5) Verify if sensitive operations verify resource ownership before modifications. 6) Look for authorization checks that can be bypassed through parameter manipulation. 7) Examine APIs that return data based on user-supplied identifiers.",
|
58
|
+
open_redirect: "Open Redirect: Redirecting users to external URLs based on user-supplied input without proper validation. Detection steps: 1) Identify redirect methods or functions (redirect_to, headers['Location'], response.redirect, etc.). 2) Check if the redirect URL or destination can be controlled by user input. 3) Verify if there is proper validation of the redirect URL to prevent external redirects. 4) Look for validation patterns that only check for URL prefixes that could be bypassed. 5) Check if the code restricts redirects to only allowed domains or uses relative paths. 6) Watch for URL manipulation techniques that might bypass validation (using //, additional domains in path, URL encoding).",
|
59
|
+
ssrf: "Server-Side Request Forgery (SSRF): The server makes HTTP requests to an arbitrary destination supplied by the user, potentially exposing internal resources or metadata. Detection steps: 1) Identify code that makes network requests (HTTP, TCP, etc.). 2) Check if the URL or destination can be influenced by user input. 3) Verify if there is proper validation of user-supplied URLs or IPs to prevent access to internal resources. 4) Look for use of libraries like Net::HTTP, open-uri, rest-client, faraday, or HTTP clients where the URL is constructed dynamically. 5) Check if the code restricts requests to only allowed domains or IP ranges.",
|
60
|
+
session_fixation: "Session Fixation: The server accepts a pre-supplied session ID, allowing an attacker to hijack the session after authentication. Detection steps: 1) Check if the application regenerates session IDs upon authentication (reset_session, new session creation). 2) Look for login methods that don't rotate session identifiers. 3) Examine session management code for proper session invalidation after login/logout. 4) Verify if the application accepts externally provided session identifiers. 5) Check if cookie settings include proper security flags (HttpOnly, Secure, SameSite). 6) Examine how session state is maintained across privilege changes (e.g., becoming admin). 7) Look for custom session handling that bypasses Rails' built-in protection mechanisms.",
|
61
|
+
inappropriate_cookie_attributes: "Insecure Cookie Attributes: Missing HttpOnly, Secure, or SameSite flags, which may lead to session theft or CSRF. Detection steps: 1) Examine cookie configuration in session store settings. 2) Check for explicit cookie setting in controllers with cookies[:name] assignments. 3) Verify if sensitive cookies have the HttpOnly flag to prevent JavaScript access. 4) Check if cookies transmitting sensitive data have the Secure flag to prevent transmission over HTTP. 5) Verify if cookies have appropriate SameSite attribute (Strict, Lax, or None with Secure) to prevent CSRF and information leakage. 6) Look for custom session management that might not set proper cookie attributes. 7) Check if cookie expiration times are appropriate for the sensitivity of the data they contain.",
|
62
|
+
insufficient_encryption: "Insufficient Encryption: Use of weak algorithms (e.g., MD5, SHA1) or lack of encryption for sensitive data. Check for insecure hash functions or plain-text handling. Detection steps: 1) Identify code handling sensitive data (passwords, API keys, PII). 2) Check if data at rest (database) or in transit (network) is encrypted. 3) Identify algorithms used for hashing/encryption (e.g., Digest::MD5, Digest::SHA1). 4) Verify if algorithms meet current security standards (e.g., bcrypt, scrypt, SHA-256+ for hashing; AES for encryption). 5) Check secure management of encryption keys.",
|
63
|
+
insecure_deserialization_rce: "Insecure Deserialization leading to RCE: Deserializing untrusted data can lead to arbitrary code execution. Detect unsafe use of deserialization functions without validation. Detection steps: 1) Locate code performing deserialization (e.g., Marshal.load, YAML.load, JSON.parse). 2) Determine if the input data comes from untrusted sources (user input, network). 3) Verify if the data is validated or sanitized before deserialization. 4) Check if safe alternatives are used (e.g., YAML.safe_load, JSON.parse with appropriate options). 5) Analyze custom deserializers for vulnerabilities.",
|
64
|
+
directory_traversal: "Directory Traversal: Allows attackers to access files outside the intended directory using ../ patterns. Check for path manipulation and missing canonicalization. Detection steps: 1) Identify code accessing the file system using paths derived from user input. 2) Check if user input influencing file paths is sanitized (e.g., removing '../'). 3) Verify if path canonicalization functions (e.g., File.expand_path, Pathname#cleanpath) are used correctly. 4) Ensure the final path is validated to be within the intended base directory before access.",
|
65
|
+
dangerous_eval: "Dangerous Code Execution (eval, exec): Dynamic code execution using untrusted input, allowing arbitrary code injection. Detection steps: 1) Search for methods enabling dynamic code execution (eval, instance_eval, class_eval, send, public_send, system, exec, ` ``). 2) Check if arguments passed to these methods originate from or are influenced by user input. 3) Verify if user input is rigorously sanitized or validated before use, or if execution is restricted to safe, predefined commands/methods. 4) Assess if safer alternatives can replace dynamic execution.",
|
66
|
+
inappropriate_file_permissions: "Insecure File Permissions: Files or directories with overly permissive modes (e.g., 777), allowing unauthorized read/write/execute access. Detection steps: 1) Find code that creates files/directories or changes permissions (e.g., FileUtils.chmod, File.chmod, Dir.mkdir with mode). 2) Examine the permission modes being set (e.g., 0777, 0666). 3) Evaluate if permissions follow the principle of least privilege, especially avoiding world-writable (o+w) or world-readable (o+r) for sensitive files. 4) Check permissions of configuration files, log files, and uploaded files.",
|
67
|
+
temporary_backup_file_leak: "Temporary or Backup File Exposure: Sensitive files like .bak, .tmp, or ~ versions are publicly accessible due to poor file handling. Detection steps: 1) Identify logic creating temporary or backup files. 2) Check if common backup extensions (.bak, .tmp, ~, .old) are used. 3) Verify these files are not created within web-accessible directories. 4) Ensure temporary/backup files are securely deleted after use. 5) Check if .gitignore excludes these file patterns.",
|
68
|
+
overly_detailed_errors: "Excessive Error Information Disclosure: Stack traces or internal error messages exposed to users, leaking implementation details. Detection steps: 1) Examine error handling code (rescue blocks, error page rendering). 2) Check error messages displayed to users in the production environment. 3) Verify that stack traces, internal paths, database queries, or configuration details are not included in user-facing errors. 4) Confirm framework settings disable detailed errors in production (e.g., Rails `config.consider_all_requests_local = false`). 5) Ensure generic errors are shown to users, while details are logged server-side.",
|
69
|
+
csp_not_set: "Missing Content Security Policy (CSP): Absence of CSP headers increases risk of XSS. Look for missing Content-Security-Policy header. Detection steps: 1) Identify code setting HTTP response headers (middleware, controllers). 2) Check for the presence of the `Content-Security-Policy` header. 3) If missing or policy is overly permissive (e.g., includes 'unsafe-inline', 'unsafe-eval', '*'), report as risk. 4) Check framework CSP configuration mechanisms (e.g., Rails `config.content_security_policy`).",
|
70
|
+
mime_sniffing_vulnerability: "MIME Sniffing Vulnerability: Missing X-Content-Type-Options: nosniff header can allow browsers to misinterpret content types. Detection steps: 1) Identify code setting HTTP response headers. 2) Check for the presence of the `X-Content-Type-Options` header. 3) If the header is missing or its value is not exactly `nosniff`, report as risk. 4) Check framework defaults or security middleware for automatic inclusion.",
|
71
|
+
clickjacking_vulnerability: "Clickjacking Protection Missing: Absence of X-Frame-Options or frame-ancestors directive allows malicious framing of pages. Detection steps: 1) Identify code setting HTTP response headers. 2) Check for the `X-Frame-Options` header (e.g., `DENY`, `SAMEORIGIN`). 3) Alternatively, check for the `frame-ancestors` directive in the `Content-Security-Policy` header (e.g., `'none'`, `'self'`). 4) If neither is present or configured securely, report as risk. 5) Check framework defaults or security middleware.",
|
72
|
+
auto_index_exposure: "Auto Indexing Enabled: Directory listing is active, exposing files and internal structure to users. Detection steps: 1) Review web server configuration files (Nginx, Apache). 2) Look for directives enabling directory listing (e.g., Apache `Options +Indexes`, Nginx `autoindex on`). 3) Check if directory listing is unintentionally enabled for specific locations. 4) If the application framework serves static files, ensure its directory listing feature is disabled.",
|
73
|
+
inappropriate_password_policy: "Weak Password Policy: Inadequate rules such as short length, lack of complexity, or missing brute-force protections. Detection steps: 1) Locate code related to password setting/changing. 2) Check validation logic for minimum length, complexity requirements (character types). 3) Verify if checks against common weak passwords (dictionaries, patterns) exist. 4) Look for enforcement of password history (reuse prevention) and expiration. 5) Check for related brute-force protection (see `excessive_login_attempts`).",
|
74
|
+
two_factor_auth_missing: "Missing Two-Factor Authentication (2FA): Lack of secondary authentication factor for sensitive operations. Detection steps: 1) Identify login process and code for sensitive operations (e.g., profile change, payment). 2) Check if a second factor (SMS, TOTP, key) is required beyond the password. 3) Look for 2FA setup and management features. 4) Determine if 2FA is mandatory or optional for users.",
|
75
|
+
race_condition: "Race Condition: Concurrent access without proper locking can lead to inconsistent states or privilege escalation. Detection steps: 1) Identify code accessing shared resources (database records, files, cache). 2) Find sections where multiple threads/processes might read/write concurrently. 3) Look for non-atomic check-then-act patterns. 4) Verify use of proper locking mechanisms (database transactions, Mutex, file locks). 5) Focus on critical operations like balance updates, inventory control.",
|
76
|
+
server_error_information_exposure: "Server Error Information Exposure: Internal errors (e.g., 500) reveal stack traces or server information in responses. Detection steps: 1) Examine error handling for server-side errors (e.g., HTTP 500). 2) Check the content of error responses sent to the client in production. 3) Verify that server-specific information (software type/version, OS details) is not included. 4) Check server configuration to suppress revealing headers (e.g., `Server` header; Nginx `server_tokens off;`). 5) Ensure detailed errors are logged only, with generic messages shown to users. (Similar to `overly_detailed_errors` but focusing on server info).",
|
77
|
+
dependency_trojan_package: "Dependency Trojan Package Risk: Installation of malicious or typosquatted packages from untrusted sources. Detection steps: 1) Review dependency files (`Gemfile`, `Gemfile.lock`). 2) Scan the list of Gems for typosquatting or unfamiliar names. 3) Check Gem sources (avoid untrusted Git repos if possible). 4) Investigate reputation and maintenance status of less-known Gems. 5) Ensure `Gemfile.lock` is committed to version control. 6) Check if dependency scanning tools (e.g., `bundler-audit`) are used.",
|
78
|
+
api_overexposure: "Excessive API Exposure: Public APIs exposed without authentication, leading to data leakage or unauthorized access. Detection steps: 1) Identify all API endpoint definitions. 2) Verify that appropriate authentication and authorization checks are applied to each endpoint. 3) Check if rate limiting or access controls are in place, even for public APIs. 4) Ensure sensitive data or internal-only information is not returned by unauthenticated endpoints. 5) Review API documentation for unintended exposure.",
|
79
|
+
security_middleware_disabled: "Security Middleware Disabled: Important protections (e.g., CSRF tokens, input sanitization) are turned off or removed. Detection steps: 1) Review framework initialization and configuration files. 2) Look for intentional disabling or removal of standard security middleware (e.g., CSRF protection, secure session handling). 3) Check for route-specific or controller-specific disabling of security features (e.g., `skip_before_action :verify_authenticity_token`) and evaluate the justification.",
|
80
|
+
security_header_inconsistency: "Security Header Inconsistency: Inconsistent or missing security headers across environments or routes. Detection steps: 1) Locate code setting security headers (CSP, X-Frame-Options, HSTS, etc.). 2) Compare header settings across different environments (dev, staging, prod), ensuring production is not weaker. 3) Verify consistent application of headers across different routes/pages within the application. 4) Check for conflicts if headers are set in multiple places (middleware, reverse proxy).",
|
81
|
+
excessive_login_attempts: "Excessive Login Attempts Allowed: Lack of rate limiting allows brute-force login attempts. Detection steps: 1) Identify the login authentication code. 2) Check for logic that counts and limits login attempts per account and/or IP address within a time window. 3) Verify that countermeasures (account lockout, CAPTCHA, delay) are triggered upon exceeding the limit. 4) Check configuration of rate-limiting libraries (e.g., `rack-attack`). 5) Ensure similar limits exist for password reset functions.",
|
82
|
+
inappropriate_cache_settings: "Insecure Cache Settings: Sensitive pages are cached publicly (e.g., with Cache-Control: public), risking data leakage. Detection steps: 1) Identify code setting `Cache-Control` or `Pragma` headers. 2) Locate code generating pages containing user-specific or sensitive data. 3) Ensure these pages have restrictive cache directives (`private`, `no-store`, `no-cache`). 4) Look for inappropriate use of `public` or long `max-age`. 5) Review framework caching (page, action, fragment) usage for sensitive content. 6) Consider cache settings in reverse proxies/CDNs.",
|
83
|
+
secret_key_committed: "Secret Key Committed to Repository: Credentials, JWT secrets, or API keys are hardcoded or pushed to version control. Detection steps: 1) Scan codebase for hardcoded secrets (passwords, API keys, tokens). 2) Review configuration files (`database.yml`, `secrets.yml`, `.env`) for secrets and ensure they are gitignored if present. 3) Verify secrets are loaded from environment variables or dedicated secret management systems. 4) Scan version control history for accidentally committed secrets (and rotate if found). 5) Consider using secret scanning tools (e.g., `truffleHog`, `gitleaks`).",
|
84
|
+
third_party_script_validation_missing: 'Missing Validation for Third-Party Scripts: External scripts are loaded without integrity checks (e.g., Subresource Integrity). Detection steps: 1) Find HTML templates loading external JS/CSS (`<script src="...">`, `<link href="...">`). 2) Check if these tags include the `integrity` attribute (for SRI). 3) Report as risk if `integrity` attribute is missing or empty. 4) Verify the `crossorigin="anonymous"` attribute is also present when using SRI. 5) Check dynamically loaded scripts for similar integrity validation mechanisms.',
|
85
|
+
over_logging: "Over-Logging: Logging sensitive information such as passwords, tokens, or personal data. Detection steps: 1) Identify all logging statements (`Rails.logger.*`, `puts`, etc.). 2) Examine the data being logged. 3) Check specifically for sensitive data like passwords, tokens, API keys, PII, credit card numbers. 4) Pay attention to logging of entire request parameters or exception objects. 5) Verify framework parameter filtering (e.g., Rails `config.filter_parameters`) is configured correctly to mask sensitive fields.",
|
86
|
+
fail_open_design: "Fail-Open Design: On error or exception, access is granted instead of safely denied. Detection steps: 1) Identify security check code (authentication, authorization, access control). 2) Examine behavior within exception handling blocks (`rescue`). 3) Verify that exceptions during security checks default to denying access (fail-close/fail-safe), not granting it. 4) Look for checks where an error state might be misinterpreted as permissive. 5) Ensure critical operations use transactions and roll back safely on error.",
|
87
|
+
environment_differences: "Uncontrolled Environment Differences: Security settings differ between development and production without strict controls. Detection steps: 1) Compare configuration files across environments (`environments/development.rb` vs `environments/production.rb`). 2) Identify differences in security settings (error reporting, SSL, headers, auth). 3) Evaluate if differences weaken security in production. 4) Check for a process to manage and review environment-specific configurations. 5) Consider potential infrastructure differences (firewalls, server settings).",
|
88
|
+
audit_log_missing: "Missing Audit Logging: Lack of logging for critical actions or authorization checks prevents accountability. Detection steps: 1) Identify code performing critical actions (login, permission change, sensitive data access/modification, config change). 2) Verify these actions generate logs including who (user), when (timestamp), what (action/resource), result (success/fail), and where (IP address). 3) Check if authentication successes/failures and authorization failures are logged. 4) Assess if logs are stored securely and retained appropriately. 5) Ensure log format is consistent and useful for monitoring.",
|
89
|
+
time_based_side_channel: "Time-Based Side Channel: Execution time differences can leak secrets (e.g., timing attacks in string comparison). Detection steps: 1) Locate code comparing secret values (passwords, tokens, API keys). 2) Check if standard comparison operators (`==`) are used for secrets. 3) Verify use of constant-time comparison functions (e.g., `ActiveSupport::SecurityUtils.secure_compare`, `Rack::Utils.secure_compare`). 4) Analyze cryptographic operations for potential timing leaks (may depend on library implementation). 5) Consider if database query times varying based on input could leak information."
|
56
90
|
}.freeze
|
57
91
|
|
58
92
|
|
data/lib/omamori/version.rb
CHANGED
metadata
CHANGED
@@ -1,14 +1,14 @@
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
2
2
|
name: omamori
|
3
3
|
version: !ruby/object:Gem::Version
|
4
|
-
version: 0.1.
|
4
|
+
version: 0.1.2
|
5
5
|
platform: ruby
|
6
6
|
authors:
|
7
7
|
- rira100000000
|
8
8
|
autorequire:
|
9
9
|
bindir: exe
|
10
10
|
cert_chain: []
|
11
|
-
date: 2025-04
|
11
|
+
date: 2025-05-04 00:00:00.000000000 Z
|
12
12
|
dependencies:
|
13
13
|
- !ruby/object:Gem::Dependency
|
14
14
|
name: colorize
|
@@ -38,6 +38,20 @@ dependencies:
|
|
38
38
|
- - "~>"
|
39
39
|
- !ruby/object:Gem::Version
|
40
40
|
version: '2.0'
|
41
|
+
- !ruby/object:Gem::Dependency
|
42
|
+
name: ruby-gemini-api
|
43
|
+
requirement: !ruby/object:Gem::Requirement
|
44
|
+
requirements:
|
45
|
+
- - "~>"
|
46
|
+
- !ruby/object:Gem::Version
|
47
|
+
version: 0.1.1
|
48
|
+
type: :runtime
|
49
|
+
prerelease: false
|
50
|
+
version_requirements: !ruby/object:Gem::Requirement
|
51
|
+
requirements:
|
52
|
+
- - "~>"
|
53
|
+
- !ruby/object:Gem::Version
|
54
|
+
version: 0.1.1
|
41
55
|
- !ruby/object:Gem::Dependency
|
42
56
|
name: bundler
|
43
57
|
requirement: !ruby/object:Gem::Requirement
|
@@ -94,20 +108,6 @@ dependencies:
|
|
94
108
|
- - "~>"
|
95
109
|
- !ruby/object:Gem::Version
|
96
110
|
version: '1.0'
|
97
|
-
- !ruby/object:Gem::Dependency
|
98
|
-
name: ruby-gemini-api
|
99
|
-
requirement: !ruby/object:Gem::Requirement
|
100
|
-
requirements:
|
101
|
-
- - "~>"
|
102
|
-
- !ruby/object:Gem::Version
|
103
|
-
version: 0.1.0
|
104
|
-
type: :development
|
105
|
-
prerelease: false
|
106
|
-
version_requirements: !ruby/object:Gem::Requirement
|
107
|
-
requirements:
|
108
|
-
- - "~>"
|
109
|
-
- !ruby/object:Gem::Version
|
110
|
-
version: 0.1.0
|
111
111
|
description: omamori scans Ruby code and diffs using AI (Google Gemini) to detect
|
112
112
|
security vulnerabilities often missed by traditional tools.
|
113
113
|
email:
|
@@ -130,14 +130,6 @@ files:
|
|
130
130
|
- demo/open_redirect_vulnerability.rb
|
131
131
|
- demo/static_analysis_vulnerability.rb
|
132
132
|
- demo/xss_vulnerability.rb
|
133
|
-
- demo_/ai_analysis_vulnerability.rb
|
134
|
-
- demo_/csrf_vulnerability.rb
|
135
|
-
- demo_/eval_vulnerability.rb
|
136
|
-
- demo_/idor_vulnerability.rb
|
137
|
-
- demo_/insecure_cookie_vulnerability.rb
|
138
|
-
- demo_/open_redirect_vulnerability.rb
|
139
|
-
- demo_/static_analysis_vulnerability.rb
|
140
|
-
- demo_/xss_vulnerability.rb
|
141
133
|
- exe/omamori
|
142
134
|
- lib/omamori.rb
|
143
135
|
- lib/omamori/ai_analysis_engine/diff_splitter.rb
|
@@ -1,28 +0,0 @@
|
|
1
|
-
# This file contains vulnerabilities that AI analysis can help detect.
|
2
|
-
|
3
|
-
require 'net/http'
|
4
|
-
require 'uri'
|
5
|
-
|
6
|
-
API_KEY = "HARDCODED_SECRET_API_KEY_12345" # Hardcoded sensitive information
|
7
|
-
|
8
|
-
def fetch_data(user_input)
|
9
|
-
# Insufficient input validation
|
10
|
-
if user_input.length > 100
|
11
|
-
puts "Input too long, truncating."
|
12
|
-
user_input = user_input[0..99]
|
13
|
-
end
|
14
|
-
|
15
|
-
uri = URI("https://api.example.com/data?query=#{user_input}&api_key=#{API_KEY}")
|
16
|
-
response = Net::HTTP.get_response(uri)
|
17
|
-
|
18
|
-
if response.is_a?(Net::HTTPSuccess)
|
19
|
-
puts "Data fetched successfully: #{response.body}"
|
20
|
-
else
|
21
|
-
# Poor error handling - reveals internal details
|
22
|
-
puts "Error fetching data: #{response.code} - #{response.message}"
|
23
|
-
end
|
24
|
-
end
|
25
|
-
|
26
|
-
# Example usage
|
27
|
-
# fetch_data("some data")
|
28
|
-
# fetch_data("a" * 200) # Long input
|
data/demo_/csrf_vulnerability.rb
DELETED
@@ -1,31 +0,0 @@
|
|
1
|
-
# frozen_string_literal: true
|
2
|
-
|
3
|
-
require 'sinatra'
|
4
|
-
|
5
|
-
# CSRF (Cross-Site Request Forgery) の脆弱性を含むデモコード
|
6
|
-
# フォーム送信時にCSRFトークンによる検証を行っていない例
|
7
|
-
|
8
|
-
# ユーザー情報を更新する想定のPOSTエンドポイント
|
9
|
-
post '/update_profile' do
|
10
|
-
# 本来はここでCSRFトークンの検証が必要だが、省略されている
|
11
|
-
user_id = params['user_id']
|
12
|
-
new_email = params['email']
|
13
|
-
|
14
|
-
# ユーザー情報の更新処理 (実際には行わない)
|
15
|
-
puts "ユーザー #{user_id} のメールアドレスを #{new_email} に更新しました。"
|
16
|
-
|
17
|
-
"Profile updated for user #{user_id}."
|
18
|
-
end
|
19
|
-
|
20
|
-
# 実行方法:
|
21
|
-
# 1. このファイルを保存
|
22
|
-
# 2. ターミナルで `ruby demo/csrf_vulnerability.rb` を実行
|
23
|
-
# 3. 攻撃者は、このエンドポイントへのPOSTリクエストをユーザーに意図せず実行させるような細工を施したページを作成し、ユーザーを誘導する。
|
24
|
-
# 例えば、以下のようなHTMLを含むページを別のサイトに用意する:
|
25
|
-
# <form action="http://localhost:4567/update_profile" method="post">
|
26
|
-
# <input type="hidden" name="user_id" value="123">
|
27
|
-
# <input type="hidden" name="email" value="attacker@example.com">
|
28
|
-
# <input type="submit" value="Click me!">
|
29
|
-
# </form>
|
30
|
-
# または、JavaScriptを使って自動的にPOSTリクエストを送信させる。
|
31
|
-
# ユーザーがログインした状態でこのページを閲覧すると、意図せずプロファイルが更新される可能性がある。
|
data/demo_/eval_vulnerability.rb
DELETED
@@ -1,29 +0,0 @@
|
|
1
|
-
# frozen_string_literal: true
|
2
|
-
|
3
|
-
require 'sinatra'
|
4
|
-
|
5
|
-
# 危険な eval/動的コード実行の脆弱性を含むデモコード
|
6
|
-
# ユーザーからの入力を eval で直接評価している例
|
7
|
-
|
8
|
-
get '/calculate' do
|
9
|
-
# ユーザーからの入力 (expression) を取得
|
10
|
-
expression = params['expression']
|
11
|
-
|
12
|
-
# 取得した入力を eval で評価
|
13
|
-
# ここにコードインジェクションの脆弱性がある
|
14
|
-
# 攻撃者は任意のRubyコードを実行させることが可能になる
|
15
|
-
begin
|
16
|
-
result = eval(expression)
|
17
|
-
"Result: #{result}"
|
18
|
-
rescue StandardError => e
|
19
|
-
status 500
|
20
|
-
"Error: #{e.message}"
|
21
|
-
end
|
22
|
-
end
|
23
|
-
|
24
|
-
# 実行方法:
|
25
|
-
# 1. このファイルを保存
|
26
|
-
# 2. ターミナルで `ruby demo/eval_vulnerability.rb` を実行
|
27
|
-
# 3. ブラウザで `http://localhost:4567/calculate?expression=2%2B2` にアクセスすると "Result: 4" が表示される。
|
28
|
-
# 4. 悪意のある入力を与える例: `http://localhost:4567/calculate?expression=system('ls%20-l')`
|
29
|
-
# サーバー側で `ls -l` コマンドが実行されてしまう可能性がある。
|
data/demo_/idor_vulnerability.rb
DELETED
@@ -1,39 +0,0 @@
|
|
1
|
-
# frozen_string_literal: true
|
2
|
-
|
3
|
-
require 'sinatra'
|
4
|
-
|
5
|
-
# IDOR (Insecure Direct Object Reference) の脆弱性を含むデモコード
|
6
|
-
# ユーザーからの入力(ID)を直接使用してリソースにアクセスし、認可チェックを行っていない例
|
7
|
-
|
8
|
-
# ユーザー情報を表示する想定のエンドポイント
|
9
|
-
get '/user_info/:user_id' do
|
10
|
-
user_id = params['user_id']
|
11
|
-
|
12
|
-
# 本来はここで、リクエストを行ったユーザーが、指定された user_id の情報にアクセスする権限があるかチェックが必要だが、省略されている
|
13
|
-
user_data = fetch_user_data(user_id) # ユーザーIDに基づいてデータを取得する関数を想定
|
14
|
-
|
15
|
-
if user_data
|
16
|
-
"User Info for ID #{user_id}: #{user_data}"
|
17
|
-
else
|
18
|
-
status 404
|
19
|
-
"User not found."
|
20
|
-
end
|
21
|
-
end
|
22
|
-
|
23
|
-
# ダミーのユーザーデータ取得関数
|
24
|
-
def fetch_user_data(user_id)
|
25
|
-
# 実際にはデータベースなどからデータを取得する
|
26
|
-
users = {
|
27
|
-
'101' => 'Alice',
|
28
|
-
'102' => 'Bob',
|
29
|
-
'103' => 'Charlie'
|
30
|
-
}
|
31
|
-
users[user_id]
|
32
|
-
end
|
33
|
-
|
34
|
-
# 実行方法:
|
35
|
-
# 1. このファイルを保存
|
36
|
-
# 2. ターミナルで `ruby demo/idor_vulnerability.rb` を実行
|
37
|
-
# 3. ブラウザで `http://localhost:4567/user_info/101` にアクセスすると Alice の情報が表示される。
|
38
|
-
# 4. ログインしていない、または権限のないユーザーが `http://localhost:4567/user_info/102` にアクセスすると、
|
39
|
-
# 本来アクセス権限がないはずの Bob の情報が表示されてしまう可能性がある。
|
@@ -1,25 +0,0 @@
|
|
1
|
-
# frozen_string_literal: true
|
2
|
-
|
3
|
-
require 'sinatra'
|
4
|
-
|
5
|
-
# 不適切なクッキー属性(HttpOnly, Secure, SameSite 未設定)の脆弱性を含むデモコード
|
6
|
-
# セキュリティ関連の属性が設定されていないクッキーを発行する例
|
7
|
-
|
8
|
-
# ログイン成功時にセッションクッキーを発行する想定のエンドポイント
|
9
|
-
get '/login' do
|
10
|
-
user_id = params['user_id'] # ダミーのユーザーID取得
|
11
|
-
|
12
|
-
# セッションIDをクッキーに設定
|
13
|
-
# HttpOnly, Secure, SameSite 属性が設定されていない
|
14
|
-
# これにより、XSS攻撃によるクッキー情報の窃盗や、CSRF攻撃のリスクが高まる
|
15
|
-
response.set_cookie('session_id', value: "user_#{user_id}_#{Time.now.to_i}")
|
16
|
-
|
17
|
-
"Logged in as user #{user_id}. Session cookie set."
|
18
|
-
end
|
19
|
-
|
20
|
-
# 実行方法:
|
21
|
-
# 1. このファイルを保存
|
22
|
-
# 2. ターミナルで `ruby demo/insecure_cookie_vulnerability.rb` を実行
|
23
|
-
# 3. ブラウザで `http://localhost:4567/login?user_id=test_user` にアクセス
|
24
|
-
# 開発者ツールなどでクッキーを確認すると、session_id クッキーに HttpOnly, Secure, SameSite 属性が付与されていないことがわかる。
|
25
|
-
# HTTPSでアクセスした場合でもSecure属性が付かない。
|
@@ -1,22 +0,0 @@
|
|
1
|
-
# frozen_string_literal: true
|
2
|
-
|
3
|
-
require 'sinatra'
|
4
|
-
|
5
|
-
# オープンリダイレクトの脆弱性を含むデモコード
|
6
|
-
# ユーザーからの入力(URL)を検証せずにリダイレクト先に指定している例
|
7
|
-
|
8
|
-
get '/redirect' do
|
9
|
-
# ユーザーからの入力 (url) を取得
|
10
|
-
redirect_url = params['url']
|
11
|
-
|
12
|
-
# 取得した入力をそのままリダイレクト先に指定
|
13
|
-
# ここにオープンリダイレクトの脆弱性がある
|
14
|
-
redirect redirect_url
|
15
|
-
end
|
16
|
-
|
17
|
-
# 実行方法:
|
18
|
-
# 1. このファイルを保存
|
19
|
-
# 2. ターミナルで `ruby demo/open_redirect_vulnerability.rb` を実行
|
20
|
-
# 3. ブラウザで `http://localhost:4567/redirect?url=https://malicious-site.example.com` にアクセス
|
21
|
-
# 悪意のあるサイトにリダイレクトされてしまう。
|
22
|
-
# フィッシング詐欺などに悪用される可能性がある。
|
@@ -1,18 +0,0 @@
|
|
1
|
-
# This file contains a vulnerability detectable by static analysis tools like Brakeman.
|
2
|
-
|
3
|
-
require 'sqlite3'
|
4
|
-
|
5
|
-
def find_user(username)
|
6
|
-
db = SQLite3::Database.open 'users.db'
|
7
|
-
# Vulnerable to SQL injection
|
8
|
-
query = "SELECT * FROM users WHERE username = '#{username}'"
|
9
|
-
puts "Executing query: #{query}"
|
10
|
-
db.execute query
|
11
|
-
rescue SQLite3::Exception => e
|
12
|
-
puts "Exception occurred: #{e}"
|
13
|
-
ensure
|
14
|
-
db.close if db
|
15
|
-
end
|
16
|
-
|
17
|
-
# Example usage (vulnerable)
|
18
|
-
# find_user("' OR '1'='1")
|
data/demo_/xss_vulnerability.rb
DELETED
@@ -1,21 +0,0 @@
|
|
1
|
-
# frozen_string_literal: true
|
2
|
-
|
3
|
-
require 'sinatra'
|
4
|
-
|
5
|
-
# XSS (Cross-Site Scripting) の脆弱性を含むデモコード
|
6
|
-
# ユーザーからの入力を適切にエスケープせずにHTMLに出力している例
|
7
|
-
|
8
|
-
get '/greet' do
|
9
|
-
# ユーザーからの入力 (name) を取得
|
10
|
-
name = params['name']
|
11
|
-
|
12
|
-
# 取得した入力をそのままHTMLに埋め込んで出力
|
13
|
-
# ここにXSSの脆弱性がある
|
14
|
-
"<h1>Hello, #{name}!</h1>"
|
15
|
-
end
|
16
|
-
|
17
|
-
# 実行方法:
|
18
|
-
# 1. このファイルを保存
|
19
|
-
# 2. ターミナルで `ruby demo/xss_vulnerability.rb` を実行
|
20
|
-
# 3. ブラウザで `http://localhost:4567/greet?name=<script>alert('XSS')</script>` にアクセス
|
21
|
-
# アラートが表示されれば脆弱性がある
|