Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NIGHT-668 : Python and HCL codescan analysis #64

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .github/workflows/code-scananalysis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: "Code Scanning"

on:
push:
branches:
- master
pull_request:
branches:
- master
workflow_dispatch:


permissions:
actions: write
contents: read
security-events: write
packages: read
pull-requests: read

jobs:
code-scan-analysis:
name: Code Scan Analysis
uses: meltwater/sec-global-gh-actions/.github/workflows/codeql-horusec-analysis.yml@main
115 changes: 115 additions & 0 deletions vulnerability-hcl.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
# Vulnerable Terraform Configuration for AWS
# Provider Configuration
provider "aws" {
region = "us-east-1"
access_key = "AKIAEXAMPLEKEY" # Hardcoded access key (critical vulnerability)
secret_key = "SECRETKEYEXAMPLE12345" # Hardcoded secret key (critical vulnerability)
}
# Insecure Security Group with excessive open ports and IP ranges
resource "aws_security_group" "insecure_sg" {
name = "insecure_sg"
description = "Insecure security group open to all IPs"
ingress {
from_port = 0
to_port = 65535
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"] # Open to all IPs (extremely insecure)
}
egress {
from_port = 0
to_port = 65535
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"] # Open to all IPs (insecure)
}
}
# EC2 Instance with hardcoded sensitive data (password)
resource "aws_instance" "example_instance" {
ami = "ami-12345678"
instance_type = "t2.micro"
key_name = "my_key_pair" # Should not use SSH key pairs hardcoded in configuration
# Insecure Security Group referenced here
security_group_ids = [aws_security_group.insecure_sg.id]
# User Data with hardcoded sensitive information (password)
user_data = <<-EOF
#!/bin/bash
echo "Setting up application"
echo "mysecretpassword" > /home/ec2-user/password.txt # Hardcoded password (critical vulnerability)
EOF
}
# S3 Bucket with public read access (exposes data to the world)
resource "aws_s3_bucket" "insecure_bucket" {
bucket = "my-insecure-bucket-12345"
acl = "public-read" # Bucket is publicly accessible (insecure)
}
# IAM Role with overly permissive policy
resource "aws_iam_role" "insecure_role" {
name = "insecure-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "ec2.amazonaws.com"
}
},
]
})
}
resource "aws_iam_policy" "insecure_policy" {
name = "insecure-policy"
description = "Overly permissive policy"
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "s3:*"
Effect = "Allow"
Resource = "arn:aws:s3:::*"
},
{
Action = "ec2:*"
Effect = "Allow"
Resource = "*"
},
{
Action = "iam:*" # Overly permissive IAM permissions
Effect = "Allow"
Resource = "*"
},
]
})
}
resource "aws_iam_role_policy_attachment" "policy_attach" {
role = aws_iam_role.insecure_role.name
policy_arn = aws_iam_policy.insecure_policy.arn
}
# AWS RDS Database with public accessibility and no encryption enabled
resource "aws_db_instance" "insecure_rds" {
allocated_storage = 20
storage_type = "gp2"
engine = "mysql"
engine_version = "5.7"
instance_class = "db.t2.micro"
name = "insecuredb"
username = "admin"
password = "adminpassword" # Hardcoded password (critical vulnerability)
publicly_accessible = true # Database is publicly accessible (critical vulnerability)
skip_final_snapshot = true
multi_az = false
storage_encrypted = false # No encryption enabled (critical vulnerability)
}
# AWS Lambda function with hardcoded secrets
resource "aws_lambda_function" "insecure_lambda" {
function_name = "insecure-lambda"
runtime = "python3.8"
role = aws_iam_role.insecure_role.arn
handler = "lambda_function.lambda_handler"
# Hardcoded sensitive data (API keys)
environment {
variables = {
API_KEY = "abcdef1234567890" # Hardcoded API key (critical vulnerability)
}
}
}
82 changes: 82 additions & 0 deletions vulnerability-python.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import os
import subprocess
import hashlib
import sqlite3
import pickle
from flask import Flask, request, jsonify

app = Flask(__name__)

# Vulnerable to SQL Injection
def vulnerable_sql_injection(user_input):
conn = sqlite3.connect('example.db')
cursor = conn.cursor()

# 1. Insecure SQL Query with User Input
query = "SELECT * FROM users WHERE username = '" + user_input + "'"
cursor.execute(query) # Vulnerable to SQL injection
result = cursor.fetchall()
conn.close()

return result

# Insecure deserialization (Pickle vulnerability)
def vulnerable_deserialization(serialized_data):
# 2. Insecure Deserialization using pickle (arbitrary code execution)
deserialized_data = pickle.loads(serialized_data) # Allows arbitrary code execution
return deserialized_data

# Insecure file handling (Path traversal)
def vulnerable_file_access(user_input):
# 3. Path Traversal vulnerability - allows access to arbitrary files on the server
file_path = "uploads/" + user_input # Unsanitized user input used in file path
try:
with open(file_path, 'r') as file:
content = file.read()
return content
except Exception as e:
return f"Error: {e}"

# Command injection vulnerability
def vulnerable_command_injection(user_input):
# 4. Command Injection - Executes user input as a system command
command = "ls " + user_input # Directly inserts user input into system command
result = subprocess.run(command, shell=True, capture_output=True, text=True)
return result.stdout

# Weak password storage (Using MD5 for hashing)
def vulnerable_password_storage(password):
# 5. Weak cryptography (MD5 is weak)
hashed_password = hashlib.md5(password.encode()).hexdigest() # MD5 is not secure for hashing

Check failure

Code scanning / CodeQL

Use of a broken or weak cryptographic hashing algorithm on sensitive data High

Sensitive data (password)
is used in a hashing algorithm (MD5) that is insecure for password hashing, since it is not a computationally expensive hash function.
return hashed_password

# Insecure cookie handling (no HttpOnly and Secure flags)
@app.route('/set_cookie')
def set_cookie():
# 6. Insecure cookie (does not use HttpOnly or Secure flags)
resp = jsonify(message="Setting insecure cookie")
resp.set_cookie('session', 'random_session_value')

Check warning

Code scanning / CodeQL

Failure to use secure cookies Medium

Cookie is added without the Secure and HttpOnly attributes properly set.
return resp

# Broken authentication (hardcoded password)
@app.route('/login', methods=['POST'])
def login():
# 7. Broken authentication - hardcoded credentials (this is insecure)
username = request.form['username']
password = request.form['password']

# Hardcoded password
if username == 'admin' and password == 'admin123':
return jsonify(message="Logged in successfully!")
else:
return jsonify(message="Invalid credentials"), 403

# Open Redirect vulnerability
@app.route('/redirect')
def open_redirect():
# 8. Open Redirect - redirects to a URL based on user input without validation
target_url = request.args.get('url')
return redirect(target_url) # No check on the validity of the URL

if __name__ == "__main__":
app.run(debug=True)

Check failure

Code scanning / CodeQL

Flask app is run in debug mode High

A Flask app appears to be run in debug mode. This may allow an attacker to run arbitrary code through the debugger.

Copilot Autofix AI 16 days ago

To fix the problem, we need to ensure that the Flask application does not run in debug mode in a production environment. The best way to achieve this is by using an environment variable to control the debug mode. This way, we can enable debug mode during development and disable it in production without changing the code.

  1. Modify the app.run() method to check an environment variable (e.g., FLASK_DEBUG) to determine whether to run in debug mode.
  2. Update the code to read the environment variable and set the debug parameter accordingly.
Suggested changeset 1
vulnerability-python.py

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/vulnerability-python.py b/vulnerability-python.py
--- a/vulnerability-python.py
+++ b/vulnerability-python.py
@@ -81,2 +81,3 @@
 if __name__ == "__main__":
-    app.run(debug=True)
\ No newline at end of file
+    debug_mode = os.getenv('FLASK_DEBUG', 'False').lower() in ['true', '1', 't']
+    app.run(debug=debug_mode)
\ No newline at end of file
EOF
@@ -81,2 +81,3 @@
if __name__ == "__main__":
app.run(debug=True)
debug_mode = os.getenv('FLASK_DEBUG', 'False').lower() in ['true', '1', 't']
app.run(debug=debug_mode)
Copilot is powered by AI and may make mistakes. Always verify output.
Positive Feedback
Negative Feedback

Provide additional feedback

Please help us improve GitHub Copilot by sharing more details about this comment.

Please select one or more of the options