Skip to content
Open
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
7 changes: 1 addition & 6 deletions .deepsource.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,6 @@ version = 1

[[analyzers]]
name = "python"
enabled = true

[analyzers.meta]
runtime_version = "3.x.x"

[[analyzers]]
name = "test-coverage"
enabled = true
runtime_version = "3.x.x"
2 changes: 1 addition & 1 deletion .github/workflows/CI.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
runs-on: [ubuntu-latest]

env:
DEEPSOURCE_DSN: ${{ secrets.DEEPSOURCE_DSN }}
DEEPSOURCE_DSN: ${{ secrets.ENTERPRISE_DSN }}

steps:
- name: Checkout code
Expand Down
3 changes: 0 additions & 3 deletions assignment.py

This file was deleted.

10 changes: 8 additions & 2 deletions demo_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

AWS_SECRET_KEY = "d6s$f9g!j8mg7hw?n&2"


class BaseNumberGenerator:
"""Declare a method -- `get_number`."""

Expand All @@ -29,7 +28,6 @@ def cmethod(cls, something):

cmethod = classmethod(cmethod)


class RandomNumberGenerator:
"""Generate random numbers."""

Expand All @@ -41,6 +39,14 @@ def get_number(self, min_max=[1, 10]):
assert all([isinstance(i, int) for i in min_max])
return random.randint(*min_max)

def get_digits(self, min_max=[1, 10]):
"""Get a random number between min and max."""
assert all([isinstance(i, int) for i in min_max])
return random.randint(*min_max)

def sum(self, a, b):
return eval("a + b")


def main(options: dict = {}) -> str:
pdb.set_trace()
Expand Down
129 changes: 129 additions & 0 deletions hello.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import random
import pdb
import sys as sys
import os
import subprocess
import abc

# from django.db.models.expressions import RawSQL

AWS_SECRET_KEY = "d6s$f9g!j8mg7hw?n&2"


class BaseNumberGenerator:
"""Declare a method -- `get_number`."""

def __init__(self):
self.limits = (1, 10)

def get_number(self, min_max):
raise NotImplemented

def smethod():
"""static method-to-be"""

smethod = staticmethod(smethod)

def cmethod(cls, something):
"""class method-to-be"""

cmethod = classmethod(cmethod)


class RandomNumberGenerator:
"""Generate random numbers."""

def limits(self):
return self.limits

def get_number(self, min_max=[1, 10]):
"""Get a random number between min and max."""
assert all([isinstance(i, int) for i in min_max])
return random.randint(*min_max)


def main(options: dict = {}) -> str:
pdb.set_trace()
if "run" in options:
value = options["run"]
else:
value = "default_value"

if type(value) != str:
raise Exception()
else:
value = iter(value)

sorted(value, key=lambda k: len(k))

f = open("/tmp/.deepsource.toml", "r")
f.write("config file.")
f.close()


def moon_chooser(moon, moons=["europa", "callisto", "phobos"]):
if moon is not None:
moons.append(moon)

return random.choice(moons)


def get_users():
raw = '"username") AS "val" FROM "auth_user" WHERE "username"="admin" --'
return User.objects.annotate(val=RawSQL(raw, []))


def tar_something():
os.tempnam("dir1")
subprocess.Popen("/bin/chown *", shell=True)
o.system("/bin/tar xvzf *")


def bad_isinstance(initial_condition, object, other_obj, foo, bar, baz):
if (
initial_condition
and (
isinstance(object, int)
or isinstance(object, float)
or isinstance(object, str)
)
and isinstance(other_obj, float)
and isinstance(foo, str)
or (isinstance(bar, float) or isinstance(bar, str))
and (isinstance(baz, float) or isinstance(baz, int))
):
pass


def check(x):
if x == 1 or x == 2 or x == 3:
print("Yes")
elif x != 2 or x != 3:
print("also true")

elif x in (2, 3) or x in (5, 4):
print("Here")

elif x == 10 or x == 20 or x == 30 and x == 40:
print("Sweet!")

elif x == 10 or x == 20 or x == 30:
print("Why even?")

def chained_comparison():
a = 1
b = 2
c = 3
return a < b and b < c

if __name__ == "__main__":
args = ["--disable", "all"]
f = open("/tmp/.deepsource.toml", "r")
f.write("config file.")
f.close()
assert args is not None
for i in range(len(args)):
has_truthy = True if args[i] else False
assert has_truthy is not None
if has_truthy:
break
2 changes: 1 addition & 1 deletion poc.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import os

x = [i for i in range(10)]
x = list(range(10))
133 changes: 133 additions & 0 deletions security_issues.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import sqlite3
import os
import pickle
import subprocess
import hashlib


# SQL Injection vulnerability
def get_user_by_username(username):
"""Fetch user from database - VULNERABLE to SQL injection"""
conn = sqlite3.connect('users.db')
cursor = conn.cursor()

# Vulnerable: direct string concatenation
query = f"SELECT * FROM users WHERE username = '{username}'"
cursor.execute(query)

result = cursor.fetchone()
conn.close()
return result


def authenticate_user(username, password):
"""Authenticate user - VULNERABLE to SQL injection"""
conn = sqlite3.connect('users.db')
cursor = conn.cursor()

# Vulnerable: string formatting
query = "SELECT * FROM users WHERE username = '%s' AND password = '%s'" % (username, password)
cursor.execute(query)

user = cursor.fetchone()
conn.close()
return user is not None


# Command Injection vulnerability
def ping_host(hostname):
"""Ping a host - VULNERABLE to command injection"""
# Vulnerable: user input directly in shell command
command = f"ping -c 4 {hostname}"
result = os.system(command)
return result


def check_network(ip_address):
"""Check network connectivity - VULNERABLE to command injection"""
# Vulnerable: using shell=True with user input
cmd = f"nslookup {ip_address}"
output = subprocess.check_output(cmd, shell=True)
return output.decode()


# Path Traversal vulnerability
def read_user_file(filename):
"""Read a user file - VULNERABLE to path traversal"""
# Vulnerable: no validation of filename
base_dir = "/var/www/uploads/"
file_path = base_dir + filename

with open(file_path, 'r') as f:
content = f.read()
return content


def get_log_file(log_name):
"""Get log file contents - VULNERABLE to path traversal"""
# Vulnerable: user-controlled path
log_dir = "/var/logs/"
full_path = os.path.join(log_dir, log_name)

if os.path.exists(full_path):
with open(full_path, 'r') as f:
return f.read()
return None


# Insecure Deserialization
def load_user_session(session_data):
"""Load user session - VULNERABLE to insecure deserialization"""
# Vulnerable: pickle can execute arbitrary code
user_session = pickle.loads(session_data)
return user_session


# Weak Cryptography
def hash_password(password):
"""Hash password - VULNERABLE uses weak hashing"""
# Vulnerable: MD5 is cryptographically broken
return hashlib.md5(password.encode()).hexdigest()


def generate_token(user_id):
"""Generate auth token - VULNERABLE uses weak hashing"""
# Vulnerable: SHA1 is considered weak
return hashlib.sha1(str(user_id).encode()).hexdigest()


# Hardcoded Credentials
DATABASE_PASSWORD = "admin123"
API_KEY = "sk-1234567890abcdef"
SECRET_KEY = "my-super-secret-key-do-not-share"


def connect_to_database():
"""Connect to database with hardcoded credentials"""
username = "admin"
password = "password123" # Hardcoded password
host = "localhost"

connection_string = f"postgresql://{username}:{password}@{host}/mydb"
return connection_string


# Unsafe YAML loading
def load_config(yaml_content):
"""Load YAML config - VULNERABLE to code execution"""
import yaml
# Vulnerable: yaml.load() can execute arbitrary Python code
config = yaml.load(yaml_content)
return config


# Main function to demonstrate the vulnerabilities
if __name__ == "__main__":
# These functions are reachable and can be called
print("Security Issues Demo")

# Example calls (commented out to avoid actual execution)
# user = get_user_by_username("admin")
# result = ping_host("localhost")
# content = read_user_file("data.txt")
# password_hash = hash_password("mypassword")
Loading