language
stringclasses
10 values
tag
stringclasses
34 values
vulnerability_type
stringlengths
4
68
βŒ€
description
stringlengths
7
146
βŒ€
vulnerable_code
stringlengths
14
1.96k
secure_code
stringlengths
18
3.21k
Python
CWE-707, λΆ€μ μ ˆν•œ 쀑립화 처리
null
CWE-175, ν˜Όν•© μΈμ½”λ”©μ˜ λΆ€μ μ ˆν•œ 처리
""" Non-compliant Code Example """ import io LOREM = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.""" output = io.BytesIO() wrapper = io.TextIOWrapper(output, encoding='utf-8', line_buffering=True) wrapper.write(LOREM) wrapper.seek(0, 0) # Below outputs UnicodeDecodeError: 'utf-16-le' codec can't decode byte 0x2e in position 1336: truncated data print(f"{len(output.getvalue().decode('utf-16le'))} characters in string")
""" Compliant Code Example """ import io LOREM = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.""" output = io.BytesIO() wrapper = io.TextIOWrapper(output, encoding='utf-8', line_buffering=True) wrapper.write(LOREM) wrapper.seek(0, 0) # 1337 characters in string print(f"{len(output.getvalue().decode('utf-8'))} characters in string")
Python
CWE-707, λΆ€μ μ ˆν•œ 쀑립화 처리
null
CWE-180, 잘λͺ»λœ λ™μž‘ μˆœμ„œ: 검증 전에 μœ νš¨μ„± 검사
# SPDX-FileCopyrightText: OpenSSF project contributors # SPDX-License-Identifier: MIT """ Non-compliant Code Example """ import re import unicodedata def api_with_ids(suspicious_string): """Fancy intrusion detection system(IDS)""" if re.search("./", suspicious_string): normalized_string = unicodedata.normalize("NFKC", suspicious_string) print(f"detected an attack sequence {normalized_string}") else: print("Nothing suspicious") ##################### # attempting to exploit above code example ##################### # The MALICIOUS_INPUT is using: # \u2024 or "ONE DOT LEADER" # \uFF0F or 'FULLWIDTH SOLIDUS' api_with_ids("\u2024\u2024\uFF0F" * 10 + "passwd")
# SPDX-FileCopyrightText: OpenSSF project contributors # SPDX-License-Identifier: MIT """ Compliant Code Example """ import re import unicodedata def api_with_ids(suspicious_string): """Fancy intrusion detection system(IDS)""" normalized_string = unicodedata.normalize("NFKC", suspicious_string) if re.search("./", normalized_string): print("detected an attack sequence with . or /") else: print("Nothing suspicious") ##################### # attempting to exploit above code example ##################### # The MALICIOUS_INPUT is using: # \u2024 or "ONE DOT LEADER" # \uFF0F or 'FULLWIDTH SOLIDUS' api_with_ids("\u2024\u2024\uFF0F" * 10 + "passwd")
Python
CWE-707, λΆ€μ μ ˆν•œ 쀑립화 처리
null
CWE-78, OS λͺ…령에 μ‚¬μš©λ˜λŠ” 특수 μš”μ†Œμ˜ λΆ€μ μ ˆν•œ 무λ ₯ν™”(OS Command Injection)
""" Non-compliant Code Example """ # SPDX-FileCopyrightText: OpenSSF project contributors # SPDX-License-Identifier: MIT """ Non-compliant Code Example """ from subprocess import Popen import os class FileOperations: """Helper class for file system operations""" def list_dir(self, dirname: str): """List the contents of a directory""" if "nt" in os.name: Popen("dir " + dirname, shell=True).communicate() if "posix" in os.name: Popen("ls " + dirname, shell=True).communicate() ##################### # Trying to exploit above code example ##################### if "nt" in os.name: FileOperations().list_dir("%HOMEPATH% & net user") if "posix" in os.name: FileOperations().list_dir("/etc/shadow; head -1 /etc/passwd")
""" Compliant Code Example """ # SPDX-FileCopyrightText: OpenSSF project contributors # SPDX-License-Identifier: MIT """ Compliant Code Example """ import os from pathlib import Path def list_dir(dirname: str): """List the contents of a directory recursively Parameters: dirname (string): Directory name """ path = Path(dirname) allowed_directory = Path.home() # TODO: input sanitation # TODO: Add secure logging if Path( allowed_directory.joinpath(dirname) .resolve() .relative_to(allowed_directory.resolve()) ): for item in path.glob("*"): print(item) ##################### # Trying to exploit above code example ##################### # just to keep it clean we create folder for this test os.makedirs("temp", exist_ok=True) # simulating upload area (payload): print("Testing Corrupted Directory") if "posix" in os.name: with open("temp/toast.sh", "w", encoding="utf-8") as file_handle: file_handle.write("uptime\n") os.makedirs("temp/. -exec bash toast.sh {} +", exist_ok=True) # running the query: list_dir("temp")
Python
CWE-707, λΆ€μ μ ˆν•œ 쀑립화 처리
null
CWE-78, OS λͺ…령에 μ‚¬μš©λ˜λŠ” 특수 μš”μ†Œμ˜ λΆ€μ μ ˆν•œ 무λ ₯ν™”(OS Command Injection)
# SPDX-FileCopyrightText: OpenSSF project contributors # SPDX-License-Identifier: MIT """ Non-compliant Code Example """ import os import shlex from subprocess import run def list_dir(dirname: str): """Lists only 2 levels of folders in a default directory""" os.chdir(dirname) cmd = "find . -maxdepth 1 -type d" result = run(shlex.split(cmd), check=True, capture_output=True) for subfolder in result.stdout.decode("utf-8").splitlines(): cmd = "find " + subfolder + " -maxdepth 1 -type d" subresult = run(shlex.split(cmd), check=True, capture_output=True) for item in subresult.stdout.decode("utf-8").splitlines(): print(item) ##################### # Trying to exploit above code example ##################### # just to keep it clean we create folder for this test os.makedirs("temp", exist_ok=True) # simulating upload area (payload): print("Testing Corrupted Directory") if "posix" in os.name: with open("temp/toast.sh", "w", encoding="utf-8") as file_handle: file_handle.write("uptime\n") os.makedirs("temp/. -exec bash toast.sh {} +", exist_ok=True) # running the query: list_dir("temp")
""" Compliant Code Example """ # SPDX-FileCopyrightText: OpenSSF project contributors # SPDX-License-Identifier: MIT """ Compliant Code Example """ import os from pathlib import Path def list_dir(dirname: str): """List the contents of a directory recursively Parameters: dirname (string): Directory name """ path = Path(dirname) allowed_directory = Path.home() # TODO: input sanitation # TODO: Add secure logging if Path( allowed_directory.joinpath(dirname) .resolve() .relative_to(allowed_directory.resolve()) ): for item in path.glob("*"): print(item) ##################### # Trying to exploit above code example ##################### # just to keep it clean we create folder for this test os.makedirs("temp", exist_ok=True) # simulating upload area (payload): print("Testing Corrupted Directory") if "posix" in os.name: with open("temp/toast.sh", "w", encoding="utf-8") as file_handle: file_handle.write("uptime\n") os.makedirs("temp/. -exec bash toast.sh {} +", exist_ok=True) # running the query: list_dir("temp")
Python
CWE-707, λΆ€μ μ ˆν•œ 쀑립화 처리
null
CWE-838, 좜λ ₯ μ»¨ν…μŠ€νŠΈμ— λΆ€μ μ ˆν•œ 인코딩
# SPDX-FileCopyrightText: OpenSSF project contributors # SPDX-License-Identifier: MIT """ Non-compliant Code Example """ def report_record_attack(stream: bytearray): print("important text:", stream.decode("utf-8")) ##################### # attempting to exploit above code example ##################### payload = bytearray("user: ζ―›ζ³½δΈœε…ˆη”Ÿ attempted a directory traversal".encode("utf-8")) # Introducing an error in the encoded text, a byte payload[3] = 128 report_record_attack(payload)
# SPDX-FileCopyrightText: OpenSSF project contributors # SPDX-License-Identifier: MIT """Compliant Code Example""" import base64 def report_record_attack(stream: bytearray): try: decoded_text = stream.decode("utf-8") except UnicodeDecodeError as e: # Encode the stream using Base64 if there is an exception encoded_payload = base64.b64encode(stream).decode("utf-8") # Logging encoded payload for forensic analysis print("Base64 Encoded Payload for Forensic Analysis:", encoded_payload) print("Error decoding payload:", e) else: print("Important text:", decoded_text) ##################### # attempting to exploit above code example ##################### payload = bytearray("user: ζ―›ζ³½δΈœε…ˆη”Ÿ attempted a directory traversal".encode("utf-8")) # Introducing an error in the encoded text, a byte payload[3] = 128 report_record_attack(payload)
Python
CWE-707, λΆ€μ μ ˆν•œ 쀑립화 처리
null
CWE-89, SQL λͺ…령에 μ‚¬μš©λœ 특수 μš”μ†Œμ˜ λΆ€μ μ ˆν•œ 무λ ₯ν™”(SQL Injection)
# SPDX-FileCopyrightText: OpenSSF project contributors # SPDX-License-Identifier: MIT """ Non-compliant Code Example """ import sqlite3 class Records: """ Non-compliant code. Possible SQL injection vector through string-based query construction """ def __init__(self, data_base): self.connection = sqlite3.connect(data_base) self.cursor = self.connection.cursor() self.cursor.execute("CREATE TABLE IF NOT EXISTS Students(student TEXT)") self.connection.commit() def get_record(self, name): ''' Fetches a student record from the table for given name Parameters: name (string): A string with the student name Returns: object (fetchall): sqlite3.cursor.fetchall() object ''' get_values = "SELECT * FROM Students WHERE student = '{name}'".format(name=name) self.cursor.execute(get_values) return self.cursor.fetchall() def add_record(self, name=""): ''' Adds a student name to the table Parameters: name (string): A string with the student name ''' add_values = "INSERT INTO Students(student) VALUES('{name}');" add_values_query = add_values.format(name=name) try: self.cursor.executescript(add_values_query) except sqlite3.OperationalError as operational_error: print(operational_error) self.connection.commit() ##################### # exploiting above code example ##################### print("sqlite3.sqlite_version=" + sqlite3.sqlite_version) records = Records("school.db") records.add_record("Alice") records.add_record("Robert'); DROP TABLE students;--") records.add_record("Malorny") print(records.get_record("Alice")) # normal as "Robert" has not been added as "Robert": print(records.get_record("Robert'); DROP TABLE students;--")) print(records.get_record("Malorny"))
# SPDX-FileCopyrightText: OpenSSF project contributors # SPDX-License-Identifier: MIT """ Compliant Code Example """ import sqlite3 class Records: """ Compliant code, providing protection against injection. Missing input sanitation as such. """ def __init__(self, data_base: str): self.connection = sqlite3.connect(data_base) self.cursor = self.connection.cursor() self.cursor.execute("CREATE TABLE IF NOT EXISTS Students(student TEXT)") self.connection.commit() def get_record(self, name: str) -> list: ''' Fetches a student record from the table for given name Parameters: name (string): A string with the student name Returns: object (fetchall): sqlite3.cursor.fetchall() object ''' data_tuple = (name,) get_values = "SELECT * FROM Students WHERE student = ?" self.cursor.execute(get_values, data_tuple) return self.cursor.fetchall() def add_record(self, name: str): ''' Adds a student name to the table Parameters: name (string): A string with the student name ''' data_tuple = (name,) add_values = """INSERT INTO Students VALUES (?)""" try: self.cursor.execute(add_values, data_tuple) except sqlite3.OperationalError as operational_error: print(operational_error) self.connection.commit() ##################### # exploiting above code example ##################### print("sqlite3.sqlite_version=" + sqlite3.sqlite_version) records = Records("school.db") records.add_record("Alice") records.add_record("Robert'); DROP TABLE students;--") records.add_record("Malorny") print(records.get_record("Alice")) # normal as "Robert" has not been added as "Robert": print(records.get_record("Robert'); DROP TABLE students;--")) print(records.get_record("Malorny"))
Python
CWE-710, μ½”λ”© ν‘œμ€€μ˜ λΆ€μ μ ˆν•œ μ€€μˆ˜
null
CWE-1095, 루프 λ‚΄ 루프 쑰건 κ°’ μ—…λ°μ΄νŠΈ
""" Non-compliant Code Example """ userlist = ['Alice', 'Bob', 'Charlie'] print(f'Unmodified list: {userlist}') for user in userlist: if user == 'Bob': userlist.remove(user) print(f'Modified list: {userlist}')
""" Compliant Code Example """ userlist = ['Alice', 'Bob', 'Charlie'] print(f'Unmodified list: {userlist}') # Create a copy for user in userlist.copy(): if user == 'Bob': userlist.remove(user) print(f'Modified list: {userlist}') # Create a sample collection: list userlist2 = ['Alice', 'Bob', 'Charlie'] print(f'Unmodified list: {userlist2}') # Create new list activeusers = [] for user in userlist2: if user != 'Bob': activeusers.append(user) print(f'New list: {activeusers}')
Python
CWE-710, μ½”λ”© ν‘œμ€€μ˜ λΆ€μ μ ˆν•œ μ€€μˆ˜
null
CWE-1095, 루프 λ‚΄ 루프 쑰건 κ°’ μ—…λ°μ΄νŠΈ
""" Non-compliant Code Example """ userdict = {'Alice': 'active', 'Bob': 'inactive', 'Charlie': 'active'} print(f'Unmodified dict: {userdict}') for user, status in userdict.items(): if status == 'inactive': del userdict[user] print(f'Modified dict: {userdict}')
""" Compliant Code Example """ userdict = {'Alice': 'active', 'Bob': 'inactive', 'Charlie': 'active'} print(f'Unmodified dict: {userdict}') # Create a copy for user, status in userdict.copy().items(): if status == 'inactive': del userdict[user] print(f'Modified dict: {userdict}') # Create new dict userdict2 = {'Alice': 'active', 'Bob': 'inactive', 'Charlie': 'active'} activeuserdict = {} for user, status in userdict2.items(): if status != 'inactive': activeuserdict.update({user: status}) print(f'New dict: {activeuserdict}')
Python
CWE-710, μ½”λ”© ν‘œμ€€μ˜ λΆ€μ μ ˆν•œ μ€€μˆ˜
null
CWE-1095, 루프 λ‚΄ 루프 쑰건 κ°’ μ—…λ°μ΄νŠΈ
""" Non-compliant Code Example """ userset = {'Alice', 'Bob', 'Charlie'} print(f'Unmodified set: {userset}') for user in userset: if user == 'Bob': userset.remove(user)
""" Compliant Code Example """ userset = {'Alice', 'Bob', 'Charlie'} print(f'Unmodified set: {userset}') # Create a copy for user in userset.copy(): if user == 'Bob': userset.remove(user) print(f'Modified set: {userset}') # Create a new set userset2 = {'Alice', 'Bob', 'Charlie'} activeuserset = set() for user in userset2: if user != 'Bob': activeuserset.add(user) print(f'Modified set: {activeuserset}')
Python
CWE-710, μ½”λ”© ν‘œμ€€μ˜ λΆ€μ μ ˆν•œ μ€€μˆ˜
null
CWE-1109, μ—¬λŸ¬ λͺ©μ μ— λ™μΌν•œ λ³€μˆ˜ μ‚¬μš©
# SPDX-FileCopyrightText: OpenSSF project contributors # SPDX-License-Identifier: MIT """ Non-compliant Code Example """ numbers = ["one", "two", "three"] print(f"len({numbers}) == {len(numbers)}") def len(x): """ implementing a dodgy version of a build in method """ return sum(1 for _ in x) + 1 print(f"len({numbers}) == {len(numbers)}")
# SPDX-FileCopyrightText: OpenSSF project contributors # SPDX-License-Identifier: MIT """ Compliant Code Example """ numbers = ["one", "two", "three"] print(f"len({numbers}) == {len(numbers)}") def custom_len(x): """ implementing a dodgy version of a build in method """ return sum(1 for _ in x) + 1 print(f"len({numbers}) == {len(numbers)}")
Python
CWE-710, μ½”λ”© ν‘œμ€€μ˜ λΆ€μ μ ˆν•œ μ€€μˆ˜
null
CWE-1109, μ—¬λŸ¬ λͺ©μ μ— λ™μΌν•œ λ³€μˆ˜ μ‚¬μš©
# SPDX-FileCopyrightText: OpenSSF project contributors # SPDX-License-Identifier: MIT """ Non-compliant Code Example """ import os print(f"Logged in user is {os.getlogin()}") class os: """ redefining standard class """ @staticmethod def getlogin(): """ redefining standard class method """ return "Not implemented" print(f"Logged in user is {os.getlogin()}")
# SPDX-FileCopyrightText: OpenSSF project contributors # SPDX-License-Identifier: MIT """ Compliant Code Example """ import os print(f"Logged in user is {os.getlogin()}") class custom_os: """ redefining standard class """ @staticmethod def getlogin(): """ redefining standard class method """ return "Not implemented" print(f"Logged in user is {os.getlogin()}")