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:10:37.786286+00:00 | 1,692,976,388,000 | f11911a93da97dc51a5996d8a1daea669ef0ceaa | 2 | {
"blob_id": "f11911a93da97dc51a5996d8a1daea669ef0ceaa",
"branch_name": "refs/heads/master",
"committer_date": 1692976388000,
"content_id": "85fbc210d2cfb4c3d291b2d25d9f19b3ee20ce8a",
"detected_licenses": [
"MIT"
],
"directory_id": "7f0acb6ce41afb89ae526d3a699ad9570438215b",
"extension": "py",
"filename": "webdav_ls.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 139420031,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1691,
"license": "MIT",
"license_type": "permissive",
"path": "/webdav/webdav_ls.py",
"provenance": "stack-edu-0054.json.gz:581323",
"repo_name": "sourceperl/sandbox",
"revision_date": 1692976388000,
"revision_id": "2790384d5fef8fbbe93fb9764d8ec275d9aba3b7",
"snapshot_id": "e684721e5cce3a30d5b67abd748be3d16aabc666",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sourceperl/sandbox/2790384d5fef8fbbe93fb9764d8ec275d9aba3b7/webdav/webdav_ls.py",
"visit_date": "2023-08-31T13:36:27.466442"
} | 2.3125 | stackv2 | #!/usr/bin/env python3
from xml.dom import minidom
import urllib3
import urllib.parse
import requests
# configure package (disable warning for self-signed certificate)
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# some consts
WEBDAV_URL_HOST = 'http://localhost:8080'
WEBDAV_URL_PATH = '/remote.php/webdav/'
WEBDAV_USER = 'admin'
WEBDAV_PASS = 'admin'
HTTP_MULTI_STATUS = 207
PROPFIND_REQUEST = '''<?xml version="1.0" encoding="utf-8" ?>
<d:propfind xmlns:d="DAV:">
<d:prop xmlns:oc="http://owncloud.org/ns">
<oc:size/>
</d:prop>
</d:propfind>'''
# init request session
s = requests.Session()
s.auth = (WEBDAV_USER, WEBDAV_PASS)
r = s.request(method='PROPFIND', url=WEBDAV_URL_HOST + WEBDAV_URL_PATH, data=PROPFIND_REQUEST,
headers={'Depth': '1'}, verify=False)
# check result
if r.status_code == HTTP_MULTI_STATUS:
# parse XML
dom = minidom.parseString(r.text.encode('ascii', 'xmlcharrefreplace'))
# d:href in d:response
for response in dom.getElementsByTagName('d:response'):
href = response.getElementsByTagName('d:href')[0].firstChild.data
# oc:size in d:response/d:propstat/d:prop
prop_stat = response.getElementsByTagName('d:propstat')[0]
prop = prop_stat.getElementsByTagName('d:prop')[0]
oc_size = prop.getElementsByTagName('oc:size')[0].firstChild.data
# extract filename and file size
file_name = urllib.parse.unquote(href[len(WEBDAV_URL_PATH):])
if not file_name:
file_name = '.'
file_size = int(oc_size)
# print result
print('%10i %s' % (file_size, file_name))
else:
print('HTTP error (code %d)' % r.status_code)
| 49 | 33.51 | 94 | 14 | 457 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_c7adbbe1b8a209e0_97273dde", "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": 28, "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/c7adbbe1b8a209e0.py", "start": {"line": 3, "col": 1, "offset": 24}, "end": {"line": 3, "col": 28, "offset": 51}, "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
] | [
28
] | [
"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"
] | webdav_ls.py | /webdav/webdav_ls.py | sourceperl/sandbox | MIT | |
2024-11-18T20:23:09.028426+00:00 | 1,506,038,973,000 | 95bed077cebe5093304ee56fac9470b9d3bde4ff | 2 | {
"blob_id": "95bed077cebe5093304ee56fac9470b9d3bde4ff",
"branch_name": "refs/heads/master",
"committer_date": 1506038973000,
"content_id": "f117324b2a7397533bd7e4e36b2a9dc7a0494acf",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "fc1816393a64a87a66332ac01a3f64f9d3bbc10b",
"extension": "py",
"filename": "CraftSetupHelper.py",
"fork_events_count": 0,
"gha_created_at": 1505543016000,
"gha_event_created_at": 1506038228000,
"gha_language": "Python",
"gha_license_id": null,
"github_id": 103730366,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 13150,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/bin/CraftSetupHelper.py",
"provenance": "stack-edu-0054.json.gz:581342",
"repo_name": "hipolipolopigus/craft",
"revision_date": 1506038973000,
"revision_id": "a775389a0d36805b6595613f2b932e6b2f68f874",
"snapshot_id": "d7684ba182c717dca35d6402325e0cf3ebddfe42",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hipolipolopigus/craft/a775389a0d36805b6595613f2b932e6b2f68f874/bin/CraftSetupHelper.py",
"visit_date": "2021-07-04T00:58:37.932227"
} | 2.34375 | stackv2 | # -*- coding: utf-8 -*-
# Helper script for substitution of paths, independent of cmd or powershell
# copyright:
# Hannah von Reth <vonreth [AT] kde [DOT] org>
import argparse
import collections
import subprocess
from CraftCompiler import craftCompiler
from CraftConfig import *
from CraftDebug import craftDebug
from CraftOS.osutils import OsUtils
# The minimum python version for craft please edit here
# if you add code that changes this requirement
from CraftStandardDirs import CraftStandardDirs, TemporaryUseShortpath
MIN_PY_VERSION = (3, 6, 0)
def log(msg):
craftDebug.print(msg, sys.stderr)
if sys.version_info[0:3] < MIN_PY_VERSION:
log("Error: Python too old!")
log("Craft needs at least Python Version %s.%s.%s" % MIN_PY_VERSION)
log("Please install it and adapt your CraftSettings.ini")
exit(1)
class SetupHelper(object):
CraftVersion = "master"
def __init__(self, args=None):
self.args = args
def _getOutput(self, command):
craftDebug.log.debug(f"SetupHelper._getOutput: {command}")
status, output = subprocess.getstatusoutput(command)
craftDebug.log.debug(f"SetupHelper._getOutput: return {status} {output}")
return status, output
def run(self):
parser = argparse.ArgumentParser()
parser.add_argument("--subst", action="store_true")
parser.add_argument("--get", action="store_true")
parser.add_argument("--print-banner", action="store_true")
parser.add_argument("--getenv", action="store_true")
parser.add_argument("--setup", action="store_true")
parser.add_argument("rest", nargs=argparse.REMAINDER)
args = parser.parse_args()
if args.subst:
self.subst()
elif args.get:
default = ""
if len(args.rest) == 3:
default = args.rest[2]
craftDebug.log.info(craftSettings.get(args.rest[0], args.rest[1], default))
elif args.print_banner:
self.printBanner()
elif args.getenv:
self.printEnv()
elif args.setup:
self.subst()
self.printEnv()
self.printBanner()
def checkForEvilApplication(self):
blackList = []
if OsUtils.isWin():
blackList += ["sh"]
if craftCompiler.isMSVC():
blackList += ["gcc", "g++"]
for app in blackList:
location = shutil.which(app)
if location:
location = os.path.dirname(location)
if not craftSettings.getboolean("ContinuousIntegration", "Enabled", False):
log(
f"Found \"{app}\" in your PATH: \"{location}\"\n"
f"This application is known to cause problems with your configuration of Craft.\n"
f"Please remove it from PATH or manually set a value for PATH in your CraftSettings.ini:\n"
f"\n"
f"[Environment]\n"
f"PATH="
f"\n")
else:
path = collections.OrderedDict.fromkeys(os.environ["Path"].split(os.path.pathsep))
del path[location]
self.addEnvVar("Path", os.path.pathsep.join(path))
def subst(self):
if not OsUtils.isWin():
return
def _subst(path, drive):
if not os.path.exists(path):
os.makedirs(path)
self._getOutput("subst {drive} {path}".format(drive=craftSettings.get("ShortPath", drive),path=path))
if craftSettings.getboolean("ShortPath", "Enabled", False):
with TemporaryUseShortpath(False):
if ("ShortPath", "RootDrive") in craftSettings:
_subst(CraftStandardDirs.craftRoot(), "RootDrive")
if ("ShortPath", "DownloadDrive") in craftSettings:
_subst(CraftStandardDirs.downloadDir(), "DownloadDrive")
if ("ShortPath", "GitDrive") in craftSettings:
_subst(CraftStandardDirs.gitDir(), "GitDrive")
if craftSettings.getboolean("ShortPath", "EnableJunctions", False):
with TemporaryUseShortpath(False):
if ("ShortPath", "JunctionDrive") in craftSettings:
_subst(CraftStandardDirs.junctionsDir(getDir=True), "JunctionDrive")
def printBanner(self):
def printRow(name, value):
log(f"{name:20}: {value}")
if CraftStandardDirs.isShortPathEnabled():
with TemporaryUseShortpath(False):
printRow("Craft Root", CraftStandardDirs.craftRoot())
printRow("Craft", CraftStandardDirs.craftRoot())
printRow("Version", SetupHelper.CraftVersion)
printRow("ABI", craftCompiler)
printRow("Svn directory", CraftStandardDirs.svnDir())
printRow("Git directory", CraftStandardDirs.gitDir())
printRow("Download directory", CraftStandardDirs.downloadDir())
if "CraftDeprecatedEntryScript" in os.environ:
oldScript = os.environ["CraftDeprecatedEntryScript"]
ext = ".ps1" if OsUtils.isWin() else ".sh"
log(f"You used the deprecated script {oldScript}\n"
f"Please use craftenv{ext} instead")
def addEnvVar(self, key, val):
os.environ[key] = val
os.environ[key] = val
def prependPath(self, key, var):
if not type(var) == list:
var = [var]
if key in os.environ:
env = var + os.environ[key].split(os.path.pathsep)
var = list(collections.OrderedDict.fromkeys(env))
os.environ[key] = os.path.pathsep.join(var)
def stringToEnv(self, string):
for line in string.split("\n"):
key, value = line.strip().split("=", 1)
os.environ[key] = value
def getEnv(self):
if craftCompiler.isMSVC():
architectures = {"x86": "x86", "x64": "amd64", "x64_cross": "x86_amd64"}
version = craftCompiler.getInternalVersion()
vswhere = os.path.join(CraftStandardDirs.craftBin(), "3rdparty", "vswhere", "vswhere.exe")
path = subprocess.getoutput(f"\"{vswhere}\""
f" -version \"[{version},{version+1})\" -property installationPath -legacy -nologo -latest -products *")
arg = architectures[craftCompiler.architecture] + ("_cross" if not craftCompiler.isNative() else "")
path = os.path.join(path, "VC")
if version >= 15:
path = os.path.join(path, "Auxiliary", "Build")
path = os.path.join(path, "vcvarsall.bat")
if not os.path.isfile(path):
log(f"Failed to setup msvc compiler.\n"
f"{path} does not exist.")
exit(1)
command = f"\"{path}\" {arg}"
status, result = subprocess.getstatusoutput(f"{command} > NUL && set")
craftDebug.log.debug(result)
if status != 0:
log(f"Failed to setup msvc compiler.\n"
f"Command: {command} ")
exit(1)
return self.stringToEnv(result)
elif craftCompiler.isIntel():
architectures = {"x86": "ia32", "x64": "intel64"}
programFiles = os.getenv("ProgramFiles(x86)") or os.getenv("ProgramFiles")
status, result = subprocess.getstatusoutput(
"\"%s\\Intel\\Composer XE\\bin\\compilervars.bat\" %s > NUL && set" % (
programFiles, architectures[craftCompiler.architecture]))
if status != 0:
log("Failed to setup intel compiler")
exit(1)
return self.stringToEnv(result)
def setXDG(self):
self.prependPath("XDG_DATA_DIRS", [os.path.join(CraftStandardDirs.craftRoot(), "share")])
if OsUtils.isUnix():
self.prependPath("XDG_CONFIG_DIRS", [os.path.join(CraftStandardDirs.craftRoot(), "etc", "xdg")])
self.addEnvVar("XDG_DATA_HOME",
os.path.join(CraftStandardDirs.craftRoot(), "home", os.getenv("USER"), ".local5", "share"))
self.addEnvVar("XDG_CONFIG_HOME",
os.path.join(CraftStandardDirs.craftRoot(), "home", os.getenv("USER"), ".config"))
self.addEnvVar("XDG_CACHE_HOME",
os.path.join(CraftStandardDirs.craftRoot(), "home", os.getenv("USER"), ".cache"))
def setupEnvironment(self):
for var, value in craftSettings.getSection("Environment"): # set and overide existing values
self.addEnvVar(var, value)
self.prependPath("PATH", os.path.dirname(sys.executable))
self.getEnv()
self.checkForEvilApplication()
self.addEnvVar("KDEROOT", CraftStandardDirs.craftRoot())
if craftSettings.getboolean("Compile", "UseCCache", False):
self.addEnvVar("CCACHE_DIR",
craftSettings.get("Paths", "CCACHE_DIR", os.path.join(CraftStandardDirs.craftRoot(),
"build", "CCACHE")))
if self.version < 2:
self.addEnvVar("GIT_SSH", "plink")
self.addEnvVar("SVN_SSH", "plink")
if not "HOME" in os.environ:
self.addEnvVar("HOME", os.getenv("USERPROFILE"))
self.prependPath("PKG_CONFIG_PATH", os.path.join(CraftStandardDirs.craftRoot(), "lib", "pkgconfig"))
self.prependPath("QT_PLUGIN_PATH", [os.path.join(CraftStandardDirs.craftRoot(), "plugins"),
os.path.join(CraftStandardDirs.craftRoot(), "lib", "plugins"),
os.path.join(CraftStandardDirs.craftRoot(), "lib64", "plugins"),
os.path.join(CraftStandardDirs.craftRoot(), "lib", "x86_64-linux-gnu",
"plugins"),
os.path.join(CraftStandardDirs.craftRoot(), "lib", "plugin")
])
self.prependPath("QML2_IMPORT_PATH", [os.path.join(CraftStandardDirs.craftRoot(), "qml"),
os.path.join(CraftStandardDirs.craftRoot(), "lib", "qml"),
os.path.join(CraftStandardDirs.craftRoot(), "lib64", "qml"),
os.path.join(CraftStandardDirs.craftRoot(), "lib", "x86_64-linux-gnu",
"qml")
])
self.prependPath("QML_IMPORT_PATH", os.environ["QML2_IMPORT_PATH"])
if OsUtils.isUnix():
self.prependPath("LD_LIBRARY_PATH", [os.path.join(CraftStandardDirs.craftRoot(), "lib"),
os.path.join(CraftStandardDirs.craftRoot(), "lib",
"x86_64-linux-gnu")])
if OsUtils.isMac():
self.prependPath("DYLD_LIBRARY_PATH", [os.path.join(CraftStandardDirs.craftRoot(), "lib")])
self.setXDG()
if craftSettings.getboolean("QtSDK", "Enabled", "false"):
self.prependPath("PATH",
os.path.join(craftSettings.get("QtSDK", "Path"), craftSettings.get("QtSDK", "Version"),
craftSettings.get("QtSDK", "Compiler"), "bin"))
if craftCompiler.isMinGW():
if not craftSettings.getboolean("QtSDK", "Enabled", "false"):
if craftCompiler.isX86():
self.prependPath("PATH", os.path.join(CraftStandardDirs.craftRoot(), "mingw", "bin"))
else:
self.prependPath("PATH", os.path.join(CraftStandardDirs.craftRoot(), "mingw64", "bin"))
else:
compilerName = craftSettings.get("QtSDK", "Compiler")
compilerMap = {"mingw53_32": "mingw530_32"}
self.prependPath("PATH", os.path.join(craftSettings.get("QtSDK", "Path"), "Tools",
compilerMap.get(compilerName, compilerName), "bin"))
if OsUtils.isUnix():
self.prependPath("PATH", CraftStandardDirs.craftBin())
self.prependPath("PATH", os.path.join(CraftStandardDirs.craftRoot(), "dev-utils", "bin"))
# make sure thate craftroot bin is the first to look for dlls etc
self.prependPath("PATH", os.path.join(CraftStandardDirs.craftRoot(), "bin"))
# add python site packages to pythonpath
self.prependPath("PythonPath", os.path.join(CraftStandardDirs.craftRoot(), "lib", "site-packages"))
def printEnv(self):
self.setupEnvironment()
for key, val in os.environ.items():
craftDebug.log.info(f"{key}={val}")
@property
def version(self):
return craftSettings.version
if __name__ == '__main__':
helper = SetupHelper()
helper.run()
| 284 | 45.3 | 145 | 21 | 2,872 | python | [{"finding_id": "semgrep_rules.python.lang.correctness.use-sys-exit_914a550b0fb5d886_3cc32ca0", "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": 28, "line_end": 28, "column_start": 5, "column_end": 12, "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/914a550b0fb5d886.py", "start": {"line": 28, "col": 5, "offset": 825}, "end": {"line": 28, "col": 12, "offset": 832}, "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.audit.dangerous-subprocess-use-audit_914a550b0fb5d886_3aecef48", "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 'getstatusoutput' 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": 38, "line_end": 38, "column_start": 26, "column_end": 61, "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/914a550b0fb5d886.py", "start": {"line": 38, "col": 26, "offset": 1078}, "end": {"line": 38, "col": 61, "offset": 1113}, "extra": {"message": "Detected subprocess function 'getstatusoutput' 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.maintainability.useless-assignment-keyed_914a550b0fb5d886_023e9722", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-assignment-keyed", "finding_type": "maintainability", "severity": "low", "confidence": "medium", "message": "key `key` in `os.environ` is assigned twice; the first assignment is useless", "remediation": "", "location": {"file_path": "unknown", "line_start": 134, "line_end": 135, "column_start": 9, "column_end": 30, "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/914a550b0fb5d886.py", "start": {"line": 134, "col": 9, "offset": 5366}, "end": {"line": 135, "col": 30, "offset": 5417}, "extra": {"message": "key `key` in `os.environ` 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.security.audit.dangerous-subprocess-use-audit_914a550b0fb5d886_b0693e38", "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 'getoutput' 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": 155, "line_end": 156, "column_start": 20, "column_end": 146, "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/914a550b0fb5d886.py", "start": {"line": 155, "col": 20, "offset": 6207}, "end": {"line": 156, "col": 146, "offset": 6390}, "extra": {"message": "Detected subprocess function 'getoutput' 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.use-sys-exit_914a550b0fb5d886_4b6a3f2f", "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": 165, "line_end": 165, "column_start": 17, "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://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/914a550b0fb5d886.py", "start": {"line": 165, "col": 17, "offset": 6857}, "end": {"line": 165, "col": 24, "offset": 6864}, "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.audit.dangerous-subprocess-use-audit_914a550b0fb5d886_b48b85ad", "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 'getstatusoutput' 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": 167, "line_end": 167, "column_start": 30, "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/914a550b0fb5d886.py", "start": {"line": 167, "col": 30, "offset": 6936}, "end": {"line": 167, "col": 83, "offset": 6989}, "extra": {"message": "Detected subprocess function 'getstatusoutput' 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.use-sys-exit_914a550b0fb5d886_490b4e0f", "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": 172, "line_end": 172, "column_start": 17, "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://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/914a550b0fb5d886.py", "start": {"line": 172, "col": 17, "offset": 7175}, "end": {"line": 172, "col": 24, "offset": 7182}, "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.audit.dangerous-subprocess-use-audit_914a550b0fb5d886_05fe6bbb", "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 'getstatusoutput' 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": 178, "line_end": 180, "column_start": 30, "column_end": 78, "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/914a550b0fb5d886.py", "start": {"line": 178, "col": 30, "offset": 7444}, "end": {"line": 180, "col": 78, "offset": 7637}, "extra": {"message": "Detected subprocess function 'getstatusoutput' 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_914a550b0fb5d886_0ad7cb0f", "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 'getstatusoutput' 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": 179, "line_end": 180, "column_start": 17, "column_end": 77, "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/914a550b0fb5d886.py", "start": {"line": 179, "col": 17, "offset": 7488}, "end": {"line": 180, "col": 77, "offset": 7636}, "extra": {"message": "Detected subprocess function 'getstatusoutput' 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.correctness.use-sys-exit_914a550b0fb5d886_c75914b5", "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": 183, "line_end": 183, "column_start": 17, "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://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/914a550b0fb5d886.py", "start": {"line": 183, "col": 17, "offset": 7736}, "end": {"line": 183, "col": 24, "offset": 7743}, "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"}}}] | 10 | true | [
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.danger... | [
"security",
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | [
38,
155,
167,
178,
179
] | [
38,
156,
167,
180,
180
] | [
26,
20,
30,
30,
17
] | [
61,
146,
83,
78,
77
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'getstatusoutput' 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 subpro... | [
7.5,
7.5,
7.5,
7.5,
7.5
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"MEDIUM"
] | CraftSetupHelper.py | /bin/CraftSetupHelper.py | hipolipolopigus/craft | BSD-2-Clause | |
2024-11-18T20:23:13.528307+00:00 | 1,482,238,385,000 | 0267a55fa19b4dd2dcd3eb1ba3aefe4d0947407d | 3 | {
"blob_id": "0267a55fa19b4dd2dcd3eb1ba3aefe4d0947407d",
"branch_name": "refs/heads/master",
"committer_date": 1482238385000,
"content_id": "48017a4aed5c4a3d2e35f77a69d3c9a6c6c3ed7c",
"detected_licenses": [
"MIT"
],
"directory_id": "aae890389b214e48c784687184a2d084afd857d3",
"extension": "py",
"filename": "P1_3_AdrianDavia.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 76954811,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4017,
"license": "MIT",
"license_type": "permissive",
"path": "/2/P1_3_AdrianDavia.py",
"provenance": "stack-edu-0054.json.gz:581399",
"repo_name": "carmedevis/PYTHON---GLADE",
"revision_date": 1482238385000,
"revision_id": "03fcbe911517aa7ec142386ae888bbdc6878cc77",
"snapshot_id": "f74cab78ffb324bddf59657395c27309915b3542",
"src_encoding": "WINDOWS-1250",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/carmedevis/PYTHON---GLADE/03fcbe911517aa7ec142386ae888bbdc6878cc77/2/P1_3_AdrianDavia.py",
"visit_date": "2021-01-13T02:45:25.714580"
} | 2.625 | stackv2 | #!usr/bin/env python
# -*- coding: utf-8 -*-
from gi.repository import Gtk
import sqlite3
#Introducimos los datos del formulario en la ventana de diálogo
def aceptar_registro(button):
window2.show_all()
resultado_usuario.set_text(usuario.get_text())
resultado_password.set_text(password.get_text())
resultado_correo.set_text(correo.get_text())
resultado_nombre.set_text(nombre.get_text())
resultado_apellido.set_text(apellido.get_text())
resultado_direccion.set_text(direccion.get_text())
#Al pulsar el botón cancelar, se queda en un segundo plano
def cancelar_dialogo(button):
dialogo = builder.get_object("dialogo")
dialogo.hide()
#Al pulsar el botón aceptar, introducimos los datos en la base de datos
def aceptar_dialogo(button):
usu = resultado_usuario.get_text()
pasw = resultado_password.get_text()
corr = resultado_correo.get_text()
name = resultado_nombre.get_text()
apell = resultado_apellido.get_text()
dircc =resultado_direccion.get_text()
cursor.execute("INSERT INTO tUsuario (Usuario,Contrasenya,Email,Nombre,Apellido,Direccion)"+
"VALUES ('"+usu+"','"+pasw+"','"+corr+"','"+name+"','"+apell+"','"+dircc+"')");
conec.commit()
conec.rollback()
conec.close()
#Al pulsar el botón listar, aparecen los datos que están guardados en la base de datos en las etiquetas utilizadas
def listar(button):
ventana2=builder.get_object("ventana_listar")
cursor.execute("SELECT * FROM tusuario")
lista0=[]
lista1=[]
lista2=[]
lista3=[]
lista4=[]
lista5=[]
for row in cursor:
lista0.append(row[0])
lista1.append(row[1])
lista2.append(row[2])
lista3.append(row[3])
lista4.append(row[4])
lista5.append(row[5])
lista_usuario.set_text(str(lista0))
lista_contrasenya.set_text(str(lista1))
lista_correo.set_text(str(lista2))
lista_nombre.set_text(str(lista3))
lista_apellido.set_text(str(lista4))
lista_direccion.set_text(str(lista5))
conec.commit()
ventana2.show()
builder = Gtk.Builder()
#Creamos la conexión a la base de datos y el cursor para movernos por ella
conec = sqlite3.connect("basededatos")
cursor = conec.cursor()
builder.add_from_file("P1_3_AdrianDavia.glade")
handlers = {
"Terminar": Gtk.main_quit,
"reposo":Gtk.main_quit,
"aceptar_registro": aceptar_registro,
"aceptar_dialogo":aceptar_dialogo,
"cancelar_dialogo":cancelar_dialogo,
"boton_listar": listar
}
builder.connect_signals(handlers)
window = builder.get_object("ventana")
window2 = builder.get_object("dialogo")
usuario = builder.get_object("entrada_usuario")
password = builder.get_object("entrada_contra")
password.set_visibility(False)
correo = builder.get_object("entrada_correo")
nombre = builder.get_object("entrada_nombre")
apellido = builder.get_object("entrada_apellido")
direccion = builder.get_object("entrada_direccion")
resultado_usuario = builder.get_object("etiqueta_resultado_usuario")
resultado_password = builder.get_object("etiqueta_resultado_contr")
resultado_correo = builder.get_object("etiqueta_resultado_correo")
resultado_nombre = builder.get_object("etiqueta_resultado_nombre")
resultado_apellido = builder.get_object("etiqueta_resultado_apellido")
resultado_direccion = builder.get_object("etiqueta_resultado_direccion")
lista_usuario = builder.get_object("lista_us")
lista_contrasenya = builder.get_object("lista_co")
lista_correo = builder.get_object("lista_em")
lista_nombre = builder.get_object("lista_no")
lista_apellido = builder.get_object("lista_ap")
lista_direccion = builder.get_object("lista_di")
window.show_all()
Gtk.main()
| 113 | 33.5 | 114 | 21 | 880 | python | [{"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_727905c2e3da8c8e_054c2b66", "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": 31, "line_end": 32, "column_start": 9, "column_end": 79, "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/727905c2e3da8c8e.py", "start": {"line": 31, "col": 9, "offset": 1056}, "end": {"line": 32, "col": 79, "offset": 1227}, "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"}}}] | 1 | true | [
"CWE-89"
] | [
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
31
] | [
32
] | [
9
] | [
79
] | [
"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"
] | P1_3_AdrianDavia.py | /2/P1_3_AdrianDavia.py | carmedevis/PYTHON---GLADE | MIT | |
2024-11-18T20:23:13.697879+00:00 | 1,663,535,443,000 | 71e7a9086631d08b977fd65bd3d3ad401cac13a7 | 3 | {
"blob_id": "71e7a9086631d08b977fd65bd3d3ad401cac13a7",
"branch_name": "refs/heads/master",
"committer_date": 1663535443000,
"content_id": "b7b0a8df6fb9d2a34769403ae681b46450380d57",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "bda1141a3038fb0cc026a3060ba79cf8c22de0ab",
"extension": "py",
"filename": "configWrapper.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 41821925,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4591,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/web/labio/configWrapper.py",
"provenance": "stack-edu-0054.json.gz:581402",
"repo_name": "WalterPaixaoCortes/DB-InhA",
"revision_date": 1663535443000,
"revision_id": "92d8993c7d7c1561e825acc238f953f01dc80454",
"snapshot_id": "0374d24be8185ba7c749e7d5e098ebc728c38cbb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/WalterPaixaoCortes/DB-InhA/92d8993c7d7c1561e825acc238f953f01dc80454/web/labio/configWrapper.py",
"visit_date": "2022-10-09T00:07:06.108134"
} | 3.40625 | stackv2 | """
Purpose
The purpose of the configWrapper module is to create an easy way to use the native ConfigParser module from python distribution
in order to load parameters from configuration file.
Description
It contains a simple wrapper for the ConfigParser module, exposing a load_configuration method.
Dependencies
ConfigParser, json.
"""
#Imports used on this module
try:
import configparser
except:
import ConfigParser as configparser
import json
#---------------------------------------------------------------------------------------
# [history]
# [13/03/2014 - walter.paixao-cortes] - First version.
# [14/03/2014 - walter.paixao-cortes] - Added attribute args to the dynamic class to re-
# ceive the arguments dictionary.
# [17/03/2014 - walter.paixao-cortes] - Added attribute log to the dynamic class to re-
# ceive the logging parameters.
# [19/03/2014 - walter.paixao-cortes] - Adding comments to generate the documentation.
#---------------------------------------------------------------------------------------
def load_configuration(fileName="app.config"):
"""
Purpose
Parse the configuration file and return a class with the information.
Description
The method receives the configuration file name and parse it into a
ConfigParser object. This object is then iterated and populates a
dictionary.
Parameter
fileName - the name of the config file. If not filled, the default is "app.config".
Returns
Dynamic class with attributes created from the keys of the dictionary.
Config file structure
The config file is a .INI like file with sections and attributes:
::
[section name]
parameter = value
.
.
.
[other section name]
otherparameter = other value
otherparameter2 = other value2
.
.
.
Sections with specific names
The section names can be pretty much anything, but there are 4 section names that serve to specific purposes:
* [lists] - all parameters that are lists or list of lists or dictionaries shall be declared under this section.
* [dicts] - all parameters that are lists or list of lists or dictionaries shall be declared under this section.
* [structures] - all parameters that are lists or list of lists or dictionaries shall be declared under this section.
* [numbers] - all integer or float items shall be declared under this section.
* [booleans] - all booleans items shall be declared under this section.
* [commandline] - all parameters that are related to command line arguments or optional parameters.
* [logging] - all parameters related to logging configuration.
* [database] - all parameters related to open a database connection.
"""
#Initializing dictionaries
attrs = {}
args = {}
log = {}
database = {}
try:
configFile = configparser.ConfigParser()
configFile.optionxform = str
configFile.read(fileName)
for section in configFile.sections():
if section == 'commandline':
for item in configFile.options(section):
args[item] = json.loads(configFile.get(section, item, raw=True))
attrs['args'] = args
elif section == 'logging':
for item in configFile.options(section):
log[item] = configFile.get(section, item, raw=True)
attrs['log'] = log
elif section == 'database':
for item in configFile.options(section):
database[item] = configFile.get(section, item, raw=True)
attrs['database'] = database
else:
for item in configFile.options(section):
if section in ['lists','numbers','dicts','structures','booleans']:
attrs[item] = eval(configFile.get(section, item, raw=True))
else:
attrs[item] = configFile.get(section, item, raw=True)
isLoaded = True
except configparser.NoSectionError:
isLoaded = False
attrs['isLoaded'] = isLoaded
return type('Config',(), attrs)
| 113 | 39.63 | 136 | 22 | 866 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_b6aa2ecad464b0d3_6e0b1cba", "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": 103, "line_end": 103, "column_start": 39, "column_end": 84, "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/b6aa2ecad464b0d3.py", "start": {"line": 103, "col": 39, "offset": 4276}, "end": {"line": 103, "col": 84, "offset": 4321}, "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"
] | [
103
] | [
103
] | [
39
] | [
84
] | [
"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"
] | configWrapper.py | /web/labio/configWrapper.py | WalterPaixaoCortes/DB-InhA | Apache-2.0 | |
2024-11-18T20:23:14.703126+00:00 | 1,535,658,654,000 | 8e33246aab78a9a4ff4066facaf184381a38a577 | 2 | {
"blob_id": "8e33246aab78a9a4ff4066facaf184381a38a577",
"branch_name": "refs/heads/master",
"committer_date": 1535659205000,
"content_id": "576ac018a68c69fe43c05f4ad5b91fb1d28c4e37",
"detected_licenses": [
"MIT"
],
"directory_id": "a8e74e0b9a885def1cf8a8ef58e26848725690f6",
"extension": "py",
"filename": "get_perspective_points.py",
"fork_events_count": 0,
"gha_created_at": 1533669960000,
"gha_event_created_at": 1533669961000,
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 143917815,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2280,
"license": "MIT",
"license_type": "permissive",
"path": "/get_perspective_points.py",
"provenance": "stack-edu-0054.json.gz:581416",
"repo_name": "apollo2030/CarND-Advanced-Lane-Lines",
"revision_date": 1535658654000,
"revision_id": "cb59ee21288cde8a0648310004af3a98263caacc",
"snapshot_id": "48c3c685eaf1f2b0681b101fd0ea8f054df98f77",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/apollo2030/CarND-Advanced-Lane-Lines/cb59ee21288cde8a0648310004af3a98263caacc/get_perspective_points.py",
"visit_date": "2020-03-25T16:09:36.194126"
} | 2.5 | stackv2 | import numpy as np
import cv2
import matplotlib.image as mpimg
import pickle
from show_original_and_result import *
def get_perspective_points(
mtx,
dist,
distace_from_center = 1.9, # distance from the center of the lines
distance_meters = 30.0, # distance in the road ahead
tvec_x_meters = 0, # translation on x axis of the camera
tvec_y_meters = 1.3, # traslation on y axis (heigh above ground) of the camera
tvec_z_meters = 4.7, # translation on z axis of the camera
):
scale = 4.54 #units per meter
zerorvecs = np.zeros((1,3))
zerorvecs[0][1] = -.026
zerorvecs[0][0] = -.03
tvec = np.array([[tvec_x_meters], [tvec_y_meters], [tvec_z_meters]])*scale
left_meters = distace_from_center
right_meters = -distace_from_center
pos_x_left = left_meters * scale
pos_x_right = right_meters * scale
distance = distance_meters * scale
objectPoints = np.array([
[pos_x_left, 0, distance],
[pos_x_left, 0, 0],
[pos_x_right, 0, distance],
[pos_x_right, 0, 0]],
dtype=float)
imgpts, jac = cv2.projectPoints(objectPoints, zerorvecs, tvec, mtx, dist)
imgpts = np.int32(imgpts).reshape(-1,2)
return imgpts
def get_perspective_points_test_bed(
dfc = 1.9,
dm = 30,
tvec_x_meters = 0.0,
tvec_y_meters = 1.3,
tvec_z_meters = 4.7,
):
tmp = mpimg.imread('output_images/undist_straight_lines2.jpg')
camera_data = pickle.load( open( "camera_cal/distortion_matrix_pickle.p", "rb" ) )
imgpts = get_perspective_points(camera_data['mtx'], camera_data['dist'], dfc, dm, tvec_x_meters, tvec_y_meters, tvec_z_meters)
print(imgpts)
cv2.line(tmp, tuple(imgpts[0]), tuple(imgpts[1]),[255,0,0],4) #BGR
cv2.line(tmp, tuple(imgpts[1]), tuple(imgpts[3]),[0,255,0],4) #BGR
cv2.line(tmp, tuple(imgpts[2]), tuple(imgpts[3]),[255,0,0],4) #BGR
cv2.line(tmp, tuple(imgpts[2]), tuple(imgpts[0]),[0,0,255],4) #BGR
show_original_and_result(tmp, tmp,'gray')
def get_dest_perspective_points(imgshape, src):
rb=src[1]
lb=src[3]
height = imgshape[0]
dest = np.float32([
[rb[0], 0],
[rb[0], height],
[lb[0], height],
[lb[0], 0]])
return dest
| 75 | 29.41 | 130 | 11 | 775 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_6eabdcfe9a281e3e_72e0aa00", "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": 50, "line_end": 50, "column_start": 19, "column_end": 87, "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/6eabdcfe9a281e3e.py", "start": {"line": 50, "col": 19, "offset": 1470}, "end": {"line": 50, "col": 87, "offset": 1538}, "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"
] | [
50
] | [
50
] | [
19
] | [
87
] | [
"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"
] | get_perspective_points.py | /get_perspective_points.py | apollo2030/CarND-Advanced-Lane-Lines | MIT | |
2024-11-18T20:23:17.087642+00:00 | 1,435,107,499,000 | 119971b784738ba0ab9a8c295a9da1365ec5cd92 | 2 | {
"blob_id": "119971b784738ba0ab9a8c295a9da1365ec5cd92",
"branch_name": "refs/heads/master",
"committer_date": 1435107499000,
"content_id": "eca95c0465367533b9e89bd4b72e33b67ae5b65b",
"detected_licenses": [
"MIT"
],
"directory_id": "486820178701ecb337f72fd00cd2e281c1f3bbb2",
"extension": "py",
"filename": "provision.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 35654249,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8320,
"license": "MIT",
"license_type": "permissive",
"path": "/teuthology_master/teuthology/provision.py",
"provenance": "stack-edu-0054.json.gz:581436",
"repo_name": "hgichon/anycloud-test",
"revision_date": 1435107499000,
"revision_id": "0d4cd18d8b6bb4dcf1b59861fea21fefe6a2c922",
"snapshot_id": "9e0161bc563a20bd048ecff57ad7bf72dcb1d420",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/hgichon/anycloud-test/0d4cd18d8b6bb4dcf1b59861fea21fefe6a2c922/teuthology_master/teuthology/provision.py",
"visit_date": "2016-09-11T09:32:23.832032"
} | 2.390625 | stackv2 | import logging
import os
import subprocess
import tempfile
import yaml
from .config import config
from .contextutil import safe_while
from .misc import decanonicalize_hostname, get_distro, get_distro_version
from .lockstatus import get_status
log = logging.getLogger(__name__)
def downburst_executable():
"""
First check for downburst in the user's path.
Then check in ~/src, ~ubuntu/src, and ~teuthology/src.
Return '' if no executable downburst is found.
"""
if config.downburst:
return config.downburst
path = os.environ.get('PATH', None)
if path:
for p in os.environ.get('PATH', '').split(os.pathsep):
pth = os.path.join(p, 'downburst')
if os.access(pth, os.X_OK):
return pth
import pwd
little_old_me = pwd.getpwuid(os.getuid()).pw_name
for user in [little_old_me, 'ubuntu', 'teuthology']:
pth = os.path.expanduser(
"~%s/src/downburst/virtualenv/bin/downburst" % user)
if os.access(pth, os.X_OK):
return pth
return ''
class Downburst(object):
"""
A class that provides methods for creating and destroying virtual machine
instances using downburst: https://github.com/ceph/downburst
"""
def __init__(self, name, os_type, os_version, status=None):
self.name = name
self.os_type = os_type
self.os_version = os_version
self.status = status or get_status(self.name)
self.config_path = None
self.host = decanonicalize_hostname(self.status['vm_host']['name'])
self.executable = downburst_executable()
def create(self):
"""
Launch a virtual machine instance.
If creation fails because an instance with the specified name is
already running, first destroy it, then try again. This process will
repeat two more times, waiting 60s between tries, before giving up.
"""
if not self.executable:
log.error("No downburst executable found.")
return False
self.build_config()
success = None
with safe_while(sleep=60, tries=3,
action="downburst create") as proceed:
while proceed():
(returncode, stdout, stderr) = self._run_create()
if returncode == 0:
log.info("Downburst created %s: %s" % (self.name,
stdout.strip()))
success = True
break
elif stderr:
# If the guest already exists first destroy then re-create:
if 'exists' in stderr:
success = False
log.info("Guest files exist. Re-creating guest: %s" %
(self.name))
self.destroy()
else:
success = False
log.info("Downburst failed on %s: %s" % (
self.name, stderr.strip()))
break
return success
def _run_create(self):
"""
Used by create(), this method is what actually calls downburst when
creating a virtual machine instance.
"""
if not self.config_path:
raise ValueError("I need a config_path!")
shortname = decanonicalize_hostname(self.name)
args = [self.executable, '-c', self.host, 'create',
'--meta-data=%s' % self.config_path, shortname,
]
log.info("Provisioning a {distro} {distroversion} vps".format(
distro=self.os_type,
distroversion=self.os_version
))
proc = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = proc.communicate()
return (proc.returncode, out, err)
def destroy(self):
"""
Destroy (shutdown and delete) a virtual machine instance.
"""
executable = self.executable
if not executable:
log.error("No downburst executable found.")
return False
shortname = decanonicalize_hostname(self.name)
args = [executable, '-c', self.host, 'destroy', shortname]
proc = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE,)
out, err = proc.communicate()
if err:
log.error("Error destroying {machine}: {msg}".format(
machine=self.name, msg=err))
return False
elif proc.returncode == 0:
out_str = ': %s' % out if out else ''
log.info("Destroyed %s%s" % (self.name, out_str))
return True
else:
log.error("I don't know if the destroy of {node} succeded!".format(
node=self.name))
return False
def build_config(self):
"""
Assemble a configuration to pass to downburst, and write it to a file.
"""
config_fd = tempfile.NamedTemporaryFile(delete=False)
file_info = {
'disk-size': '100G',
'ram': '1.9G',
'cpus': 1,
'networks': [
{'source': 'front', 'mac': self.status['mac_address']}],
'distro': self.os_type.lower(),
'distroversion': self.os_version,
'additional-disks': 3,
'additional-disks-size': '200G',
'arch': 'x86_64',
}
fqdn = self.name.split('@')[1]
file_out = {'downburst': file_info, 'local-hostname': fqdn}
yaml.safe_dump(file_out, config_fd)
self.config_path = config_fd.name
return True
def remove_config(self):
"""
Remove the downburst configuration file created by build_config()
"""
if self.config_path and os.path.exists(self.config_path):
os.remove(self.config_path)
self.config_path = None
return True
return False
def __del__(self):
self.remove_config()
def create_if_vm(ctx, machine_name, _downburst=None):
"""
Use downburst to create a virtual machine
:param _downburst: Only used for unit testing.
"""
if _downburst:
status_info = _downburst.status
else:
status_info = get_status(machine_name)
if not status_info.get('is_vm', False):
return False
os_type = get_distro(ctx)
os_version = get_distro_version(ctx)
has_config = hasattr(ctx, 'config') and ctx.config is not None
if has_config and 'downburst' in ctx.config:
log.warning(
'Usage of a custom downburst config has been deprecated.'
)
dbrst = _downburst or Downburst(name=machine_name, os_type=os_type,
os_version=os_version, status=status_info)
return dbrst.create()
def destroy_if_vm(ctx, machine_name, user=None, description=None,
_downburst=None):
"""
Use downburst to destroy a virtual machine
Return False only on vm downburst failures.
:param _downburst: Only used for unit testing.
"""
if _downburst:
status_info = _downburst.status
else:
status_info = get_status(machine_name)
if not status_info or not status_info.get('is_vm', False):
return True
if user is not None and user != status_info['locked_by']:
msg = "Tried to destroy {node} as {as_user} but it is locked " + \
"by {locked_by}"
log.error(msg.format(node=machine_name, as_user=user,
locked_by=status_info['locked_by']))
return False
if (description is not None and description !=
status_info['description']):
msg = "Tried to destroy {node} with description {desc_arg} " + \
"but it is locked with description {desc_lock}"
log.error(msg.format(node=machine_name, desc_arg=description,
desc_lock=status_info['description']))
return False
dbrst = _downburst or Downburst(name=machine_name, os_type=None,
os_version=None, status=status_info)
return dbrst.destroy()
| 231 | 35.02 | 79 | 23 | 1,792 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_1e28580164962b55_7a80ce78", "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": 106, "line_end": 107, "column_start": 16, "column_end": 56, "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/1e28580164962b55.py", "start": {"line": 106, "col": 16, "offset": 3780}, "end": {"line": 107, "col": 56, "offset": 3882}, "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_1e28580164962b55_6547fe2c", "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": 121, "line_end": 122, "column_start": 16, "column_end": 57, "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/1e28580164962b55.py", "start": {"line": 121, "col": 16, "offset": 4360}, "end": {"line": 122, "col": 57, "offset": 4463}, "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.best-practice.open-never-closed_1e28580164962b55_cb7d7430", "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": 141, "line_end": 141, "column_start": 9, "column_end": 62, "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/1e28580164962b55.py", "start": {"line": 141, "col": 9, "offset": 5117}, "end": {"line": 141, "col": 62, "offset": 5170}, "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.correctness.tempfile.tempfile-without-flush_1e28580164962b55_0179b2fa", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.tempfile.tempfile-without-flush", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Using 'config_fd.name' without '.flush()' or '.close()' may cause an error because the file may not exist when 'config_fd.name' is used. Use '.flush()' or close the file before using 'config_fd.name'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 158, "line_end": 158, "column_start": 28, "column_end": 42, "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-without-flush", "path": "/tmp/tmppq52ww6s/1e28580164962b55.py", "start": {"line": 158, "col": 28, "offset": 5764}, "end": {"line": 158, "col": 42, "offset": 5778}, "extra": {"message": "Using 'config_fd.name' without '.flush()' or '.close()' may cause an error because the file may not exist when 'config_fd.name' is used. Use '.flush()' or close the file before using 'config_fd.name'.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "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"
] | [
106,
121
] | [
107,
122
] | [
16,
16
] | [
56,
57
] | [
"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"
] | provision.py | /teuthology_master/teuthology/provision.py | hgichon/anycloud-test | MIT | |
2024-11-18T20:23:18.095432+00:00 | 1,587,808,794,000 | e91ccd992f7e12da7a2e09a94ed165b5d6a74234 | 3 | {
"blob_id": "e91ccd992f7e12da7a2e09a94ed165b5d6a74234",
"branch_name": "refs/heads/master",
"committer_date": 1587808794000,
"content_id": "7985640f2084c234203e4aae7302b1af72668360",
"detected_licenses": [
"MIT"
],
"directory_id": "9ec8586c43ab6ae6b79e427c43be93f1911f2e5f",
"extension": "py",
"filename": "upload_fdfs_image.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 257598764,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1143,
"license": "MIT",
"license_type": "permissive",
"path": "/Bxin/utils/fastdfs/upload_fdfs_image.py",
"provenance": "stack-edu-0054.json.gz:581447",
"repo_name": "Wang-TaoTao/Bxin",
"revision_date": 1587808794000,
"revision_id": "ec9c48005262851eb8f2fa1727a9104c323a1730",
"snapshot_id": "0da49ba1710a995c3354dd8dd1aeaa16635c3a6a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Wang-TaoTao/Bxin/ec9c48005262851eb8f2fa1727a9104c323a1730/Bxin/utils/fastdfs/upload_fdfs_image.py",
"visit_date": "2022-04-26T01:22:40.808572"
} | 2.59375 | stackv2 | import pymysql
from Bxin.settings import logger
'''图片上传到fastdfs并且将返回的file_id存入mysql的image_file_id字段'''
# 建立连接
conn = pymysql.connect(host='localhost', port=3306,user='root', password='mysql', database='bxin', charset='utf8')
# 游标
cur = conn.cursor()
## 1. 导入FastDFS客户端扩展
from fdfs_client.client import Fdfs_client
# 2. 创建FastDFS客户端实例
client = Fdfs_client('client.conf')
# 3. 调用FastDFS客户端上传文件方法 将所有电影图片上传到fastdfs的stroger
for i in range(1,251):
ret = client.upload_by_filename('/home/python/Desktop/Bxin_project/Bxin/Bxin/static/images2/{}.jpg'.format(i))
# 4.将图片上传信息打印出来,便于访问。
print(ret)
print(ret['Remote file_id'])
try:
value_ = ret['Remote file_id']
sql = "update tb_movie set image_file_id = '%s' where id='%i';" % (value_,i)
row_count = cur.execute(sql)
conn.commit()
except Exception as e:
logger.error(e)
print("有异常")
break
print("success")
# 关闭连接
cur.close()
conn.close()
| 42 | 22.31 | 114 | 11 | 307 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_7fce4a3787f273bf_9e20973e", "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": 30, "line_end": 30, "column_start": 21, "column_end": 37, "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/7fce4a3787f273bf.py", "start": {"line": 30, "col": 21, "offset": 948}, "end": {"line": 30, "col": 37, "offset": 964}, "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_7fce4a3787f273bf_dff5901e", "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": 30, "line_end": 30, "column_start": 21, "column_end": 37, "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/7fce4a3787f273bf.py", "start": {"line": 30, "col": 21, "offset": 948}, "end": {"line": 30, "col": 37, "offset": 964}, "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.lang.security.audit.formatted-sql-query",
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"HIGH"
] | [
30,
30
] | [
30,
30
] | [
21,
21
] | [
37,
37
] | [
"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"
] | upload_fdfs_image.py | /Bxin/utils/fastdfs/upload_fdfs_image.py | Wang-TaoTao/Bxin | MIT | |
2024-11-18T20:23:21.148768+00:00 | 1,535,450,058,000 | f904063c8c98fbd3e207481ac886028c40cf6fc4 | 3 | {
"blob_id": "f904063c8c98fbd3e207481ac886028c40cf6fc4",
"branch_name": "refs/heads/master",
"committer_date": 1535450058000,
"content_id": "730fd88275536536d274416742a93b3fd0260963",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "58aa436f321ffeecaa0b2ba9fd4e4eed323edd93",
"extension": "py",
"filename": "meta_models.py",
"fork_events_count": 0,
"gha_created_at": 1510590054000,
"gha_event_created_at": 1510590054000,
"gha_language": null,
"gha_license_id": null,
"github_id": 110571782,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1927,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/meta_models.py",
"provenance": "stack-edu-0054.json.gz:581483",
"repo_name": "j6e/hyperband",
"revision_date": 1535450058000,
"revision_id": "76f5978204a3e8e0abebf241b5757e9c71281ad3",
"snapshot_id": "0a790cfb80100b3663c9fa6ff1f56dd96c7b4a5a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/j6e/hyperband/76f5978204a3e8e0abebf241b5757e9c71281ad3/meta_models.py",
"visit_date": "2018-11-30T03:13:06.651347"
} | 2.515625 | stackv2 | import pickle as pickle
from functools import partial
from pprint import pprint
from defs.meta import get_params as get_params_c
from defs.meta import try_params as try_params_c
from defs_regression.meta import get_params as get_params_r
from defs_regression.meta import try_params as try_params_r
from hyperband import Hyperband
def classification_meta_model(data, output_file='results.pkl', max_iter=81, eta=3):
if not output_file.endswith('.pkl'):
output_file += '.pkl'
print("Will save results to", output_file)
#
try_params_data = partial(try_params_c, data=data)
hb = Hyperband(get_params_c, try_params_data, max_iter=max_iter, eta=3)
results = hb.run(skip_last=1)
print("{} total, best:\n".format(len(results)))
for r in sorted(results, key=lambda x: x['loss'])[:5]:
print("loss: {:.2%} | {} seconds | {:.1f} iterations | run {} ".format(
r['loss'], r['seconds'], r['iterations'], r['counter']))
pprint(r['params'])
print()
print("saving...")
with open(output_file, 'wb') as f:
pickle.dump(results, f)
return results
def regression_meta_model(data, output_file='results.pkl', max_iter=81, eta=3):
if not output_file.endswith('.pkl'):
output_file += '.pkl'
print("Will save results to", output_file)
#
try_params_data = partial(try_params_r, data=data)
hb = Hyperband(get_params_r, try_params_data, max_iter=max_iter, eta=eta)
results = hb.run(skip_last=1)
print("{} total, best:\n".format(len(results)))
for r in sorted(results, key=lambda x: x['loss'])[:5]:
print("loss: {:.2%} | {} seconds | {:.1f} iterations | run {} ".format(
r['loss'], r['seconds'], r['iterations'], r['counter']))
pprint(r['params'])
print()
print("saving...")
with open(output_file, 'wb') as f:
pickle.dump(results, f)
return results
| 63 | 29.59 | 83 | 13 | 486 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_a7ff1342682748b6_cf834f30", "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": 34, "line_end": 34, "column_start": 9, "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/a7ff1342682748b6.py", "start": {"line": 34, "col": 9, "offset": 1086}, "end": {"line": 34, "col": 32, "offset": 1109}, "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_a7ff1342682748b6_0d035d00", "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": 61, "line_end": 61, "column_start": 9, "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/a7ff1342682748b6.py", "start": {"line": 61, "col": 9, "offset": 1883}, "end": {"line": 61, "col": 32, "offset": 1906}, "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"
] | [
34,
61
] | [
34,
61
] | [
9,
9
] | [
32,
32
] | [
"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"
] | meta_models.py | /meta_models.py | j6e/hyperband | BSD-3-Clause,BSD-2-Clause | |
2024-11-18T20:23:21.460255+00:00 | 1,632,884,834,000 | 570436b4099ccd87596a582cdcc29dab086cd857 | 2 | {
"blob_id": "570436b4099ccd87596a582cdcc29dab086cd857",
"branch_name": "refs/heads/master",
"committer_date": 1632884834000,
"content_id": "4fe638ac2585b91178ec45f4b182d94476048c74",
"detected_licenses": [
"MIT"
],
"directory_id": "49849a84b0424ba9fb3d5218a43fb3867c489ddf",
"extension": "py",
"filename": "create_db.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": 5698,
"license": "MIT",
"license_type": "permissive",
"path": "/create_db.py",
"provenance": "stack-edu-0054.json.gz:581484",
"repo_name": "yotofu/kitti360LabelTool",
"revision_date": 1632884834000,
"revision_id": "ab24ef2240b536dd73bd9ebf0330bdac77bd14d6",
"snapshot_id": "378e3331ffdbf453c3d454d1229f8cad2df9e2a2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yotofu/kitti360LabelTool/ab24ef2240b536dd73bd9ebf0330bdac77bd14d6/create_db.py",
"visit_date": "2023-08-25T13:06:03.464612"
} | 2.34375 | stackv2 | """
Copyright 2018 Autonomous Vision Group
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 os
import sqlite3
import hashlib
from datetime import datetime
db_name = 'db/user_task.db'
now = datetime.now()
date = '%d-%02d-%02d' % (now.year, now.month, now.day)
# KEEP CONSISTENT with labelApp.py
num_subtask = 6
if not os.path.isfile(db_name):
# Setup db if it has not been created before
conn = sqlite3.connect(db_name)
conn.execute('CREATE TABLE user_task \
(id integer primary key, user_id text, task_id text, status int, editable int)')
conn.execute('CREATE TABLE user \
(email text primary key, ack text, username text, password text, is_admin boolean)')
conn.close()
print('Table created successfully!')
conn = sqlite3.connect(db_name)
data_folder = 'db_import'
public_folder = 'public'
conn.execute('CREATE TABLE if not exists user_progress \
(user_id text, task_id text, work_time int DEFAULT 0, work_date date)')
columns = [i[1] for i in conn.execute('PRAGMA table_info( user )')]
if 'offset' not in columns:
conn.execute('ALTER TABLE user ADD COLUMN offset numeric')
for i in range(num_subtask):
if 'subtask%d' % (i+1) not in columns:
conn.execute('ALTER TABLE user ADD COLUMN subtask%d boolean DEFAULT 0' % (i+1))
columns = [i[1] for i in conn.execute('PRAGMA table_info( user_task )')]
for i in range(num_subtask):
if 'subtask%d' % (i+1) not in columns:
conn.execute('ALTER TABLE user_task ADD COLUMN subtask%d boolean DEFAULT 0' % (i+1))
# drop information
# conn.execute('DELETE FROM user')
# conn.execute('DELETE FROM user_task')
def encrypt_password(password):
# Do not use this algorithm in a real environment
encrypted_pass = hashlib.sha1(password.encode('utf-8')).hexdigest()
return encrypted_pass
# build up folder structure
results = public_folder + '/results'
print('buildup ' + results)
if not os.path.exists(results):
os.makedirs(results)
backup = public_folder + '/backup'
print('buildup ' + backup)
if not os.path.exists(backup):
os.makedirs(backup)
data_loc = public_folder + '/data'
print('buildup ' + data_loc)
if not os.path.exists(data_loc):
os.makedirs(data_loc)
# read user files
with open(data_folder + '/users.txt') as f:
for lines in f:
l = lines.strip().split(' ')
email = l[0]
ack = l[1]
username = l[2]
password = encrypt_password(l[3])
is_admin = int(l[4])
offset = 0
if len(l)>5:
offset = float(l[5])
# subtask is deprecated
#subtask = [ int(i) for i in l[6].split(',') ]
subtask = [0]
cursor = conn.execute('SELECT email FROM user WHERE username = \'%s\'' % username)
data = cursor.fetchone()
if data is None:
conn.execute('INSERT OR IGNORE INTO user (email, ack, username, password, is_admin, offset) \
VALUES (\'%s\', \'%s\', \'%s\', \'%s\', %d, %f)' \
% (email, ack, username, password, is_admin, offset))
else:
print('%s already exists, updating...' % username)
conn.execute('UPDATE user SET email = \'%s\', password = \'%s\', is_admin = %d, offset = %f WHERE username = \'%s\'' %
(email, password, is_admin, offset, username))
# assign mini-tasks
for i in range(num_subtask):
if i+1 in subtask:
conn.execute('UPDATE user SET subtask%d = 1 WHERE username = \'%s\'' % (i+1, username))
else:
conn.execute('UPDATE user SET subtask%d = 0 WHERE username = \'%s\'' % (i+1, username))
cursor = conn.execute('SELECT email, username, password from user')
for row in cursor:
print('email = %s' % row[0])
print('username = %s' % row[1])
# read task files
with open(data_folder + '/taskLists.txt') as f:
for lines in f:
l = lines.strip().split(' ')
task_name = l[0]
user_name = l[1]
editable = int(l[2])
status = 0
if editable != 1:
status = 2
cursor = conn.execute('SELECT status FROM user_task WHERE task_id = \'%s\' AND user_id = \'%s\'' % (task_name, user_name))
data = cursor.fetchone()
if data is None:
conn.execute('INSERT OR IGNORE INTO user_task (task_id, user_id, status, editable) VALUES (\'%s\', \'%s\', %d, %d)'
% (task_name, user_name, status, editable))
else:
print('(%s, %s) already exists, skip' % (user_name, task_name))
cursor = conn.execute('SELECT task_id FROM user_progress WHERE task_id = \'%s\' AND user_id = \'%s\'' % (task_name, user_name))
data = cursor.fetchone()
if data is None:
conn.execute('INSERT OR IGNORE INTO user_progress (task_id, user_id, work_date) VALUES (\'%s\', \'%s\', \'%s\')'
% (task_name, user_name, date))
cursor = conn.execute('SELECT id, task_id, user_id from user_task')
for row in cursor:
print('ID = %s' % row[0])
print('taskname = %s' % row[1])
print('username = %s\n' % row[2])
conn.commit()
conn.close()
| 169 | 32.72 | 129 | 17 | 1,540 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_edff608644c8f33f_b1522a15", "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": 58, "line_end": 58, "column_start": 3, "column_end": 82, "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/edff608644c8f33f.py", "start": {"line": 58, "col": 3, "offset": 2175}, "end": {"line": 58, "col": 82, "offset": 2254}, "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_edff608644c8f33f_622f2fad", "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": 58, "line_end": 58, "column_start": 3, "column_end": 82, "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/edff608644c8f33f.py", "start": {"line": 58, "col": 3, "offset": 2175}, "end": {"line": 58, "col": 82, "offset": 2254}, "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_edff608644c8f33f_2d43990b", "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": 63, "line_end": 63, "column_start": 3, "column_end": 87, "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/edff608644c8f33f.py", "start": {"line": 63, "col": 3, "offset": 2403}, "end": {"line": 63, "col": 87, "offset": 2487}, "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_edff608644c8f33f_1a5c8ba4", "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": 63, "line_end": 63, "column_start": 3, "column_end": 87, "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/edff608644c8f33f.py", "start": {"line": 63, "col": 3, "offset": 2403}, "end": {"line": 63, "col": 87, "offset": 2487}, "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.insecure-hash-algorithm-sha1_edff608644c8f33f_e46460cf", "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(password.encode('utf-8'))", "location": {"file_path": "unknown", "line_start": 71, "line_end": 71, "column_start": 19, "column_end": 57, "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/tmppq52ww6s/edff608644c8f33f.py", "start": {"line": 71, "col": 19, "offset": 2685}, "end": {"line": 71, "col": 57, "offset": 2723}, "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(password.encode('utf-8'))", "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.unspecified-open-encoding_edff608644c8f33f_d617d360", "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": 92, "line_end": 92, "column_start": 6, "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/edff608644c8f33f.py", "start": {"line": 92, "col": 6, "offset": 3168}, "end": {"line": 92, "col": 38, "offset": 3200}, "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.formatted-sql-query_edff608644c8f33f_7b284ade", "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": 110, "line_end": 110, "column_start": 12, "column_end": 85, "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/edff608644c8f33f.py", "start": {"line": 110, "col": 12, "offset": 3520}, "end": {"line": 110, "col": 85, "offset": 3593}, "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_edff608644c8f33f_a8e96a17", "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": 110, "line_end": 110, "column_start": 12, "column_end": 85, "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/edff608644c8f33f.py", "start": {"line": 110, "col": 12, "offset": 3520}, "end": {"line": 110, "col": 85, "offset": 3593}, "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_edff608644c8f33f_02e37f9b", "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": 113, "line_end": 115, "column_start": 4, "column_end": 58, "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/edff608644c8f33f.py", "start": {"line": 113, "col": 4, "offset": 3643}, "end": {"line": 115, "col": 58, "offset": 3850}, "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_edff608644c8f33f_2bfb1ce6", "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": 113, "line_end": 115, "column_start": 4, "column_end": 58, "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/edff608644c8f33f.py", "start": {"line": 113, "col": 4, "offset": 3643}, "end": {"line": 115, "col": 58, "offset": 3850}, "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_edff608644c8f33f_1050ee6f", "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": 118, "line_end": 119, "column_start": 4, "column_end": 51, "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/edff608644c8f33f.py", "start": {"line": 118, "col": 4, "offset": 3919}, "end": {"line": 119, "col": 51, "offset": 4089}, "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_edff608644c8f33f_88211b3a", "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": 118, "line_end": 119, "column_start": 4, "column_end": 51, "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/edff608644c8f33f.py", "start": {"line": 118, "col": 4, "offset": 3919}, "end": {"line": 119, "col": 51, "offset": 4089}, "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_edff608644c8f33f_8f55f9d5", "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": 124, "line_end": 124, "column_start": 5, "column_end": 92, "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/edff608644c8f33f.py", "start": {"line": 124, "col": 5, "offset": 4170}, "end": {"line": 124, "col": 92, "offset": 4257}, "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_edff608644c8f33f_4ca0a20e", "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": 124, "line_end": 124, "column_start": 5, "column_end": 92, "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/edff608644c8f33f.py", "start": {"line": 124, "col": 5, "offset": 4170}, "end": {"line": 124, "col": 92, "offset": 4257}, "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_edff608644c8f33f_dd4af535", "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": 126, "line_end": 126, "column_start": 5, "column_end": 92, "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/edff608644c8f33f.py", "start": {"line": 126, "col": 5, "offset": 4271}, "end": {"line": 126, "col": 92, "offset": 4358}, "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_edff608644c8f33f_a76d1c0a", "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": 126, "line_end": 126, "column_start": 5, "column_end": 92, "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/edff608644c8f33f.py", "start": {"line": 126, "col": 5, "offset": 4271}, "end": {"line": 126, "col": 92, "offset": 4358}, "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_edff608644c8f33f_b88e6f56", "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": 135, "line_end": 135, "column_start": 6, "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://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/edff608644c8f33f.py", "start": {"line": 135, "col": 6, "offset": 4535}, "end": {"line": 135, "col": 42, "offset": 4571}, "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.formatted-sql-query_edff608644c8f33f_8c035b15", "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": 148, "line_end": 148, "column_start": 12, "column_end": 125, "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/edff608644c8f33f.py", "start": {"line": 148, "col": 12, "offset": 4749}, "end": {"line": 148, "col": 125, "offset": 4862}, "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_edff608644c8f33f_3ea7b4b6", "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": 148, "line_end": 148, "column_start": 12, "column_end": 125, "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/edff608644c8f33f.py", "start": {"line": 148, "col": 12, "offset": 4749}, "end": {"line": 148, "col": 125, "offset": 4862}, "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_edff608644c8f33f_e54ad21e", "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": 151, "line_end": 152, "column_start": 4, "column_end": 47, "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/edff608644c8f33f.py", "start": {"line": 151, "col": 4, "offset": 4912}, "end": {"line": 152, "col": 47, "offset": 5075}, "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_edff608644c8f33f_887b3ea2", "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": 151, "line_end": 152, "column_start": 4, "column_end": 47, "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/edff608644c8f33f.py", "start": {"line": 151, "col": 4, "offset": 4912}, "end": {"line": 152, "col": 47, "offset": 5075}, "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_edff608644c8f33f_0eb5bb1d", "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": 156, "line_end": 156, "column_start": 12, "column_end": 130, "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/edff608644c8f33f.py", "start": {"line": 156, "col": 12, "offset": 5164}, "end": {"line": 156, "col": 130, "offset": 5282}, "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_edff608644c8f33f_7a7de49c", "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": 156, "line_end": 156, "column_start": 12, "column_end": 130, "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/edff608644c8f33f.py", "start": {"line": 156, "col": 12, "offset": 5164}, "end": {"line": 156, "col": 130, "offset": 5282}, "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_edff608644c8f33f_31a37b3b", "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": 159, "line_end": 160, "column_start": 4, "column_end": 35, "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/edff608644c8f33f.py", "start": {"line": 159, "col": 4, "offset": 5332}, "end": {"line": 160, "col": 35, "offset": 5480}, "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_edff608644c8f33f_f7cafe93", "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": 159, "line_end": 160, "column_start": 4, "column_end": 35, "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/edff608644c8f33f.py", "start": {"line": 159, "col": 4, "offset": 5332}, "end": {"line": 160, "col": 35, "offset": 5480}, "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"}}}] | 25 | true | [
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"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",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH"
] | [
58,
58,
63,
63,
110,
110,
113,
113,
118,
118,
124,
124,
126,
126,
148,
148,
151,
151,
156,
156,
159,
159
] | [
58,
58,
63,
63,
110,
110,
115,
115,
119,
119,
124,
124,
126,
126,
148,
148,
152,
152,
156,
156,
160,
160
] | [
3,
3,
3,
3,
12,
12,
4,
4,
4,
4,
5,
5,
5,
5,
12,
12,
4,
4,
12,
12,
4,
4
] | [
82,
82,
87,
87,
85,
85,
58,
58,
51,
51,
92,
92,
92,
92,
125,
125,
47,
47,
130,
130,
35,
35
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01... | [
"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,
5,
7.5,
5,
7.5,
5,
7.5,
5,
7.5,
5,
7.5,
5,
7.5,
5,
7.5
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | create_db.py | /create_db.py | yotofu/kitti360LabelTool | MIT | |
2024-11-18T20:23:23.291911+00:00 | 1,590,712,244,000 | b3dd5cac369cecd88dfe1a49f5ee458d6b0e9ab4 | 3 | {
"blob_id": "b3dd5cac369cecd88dfe1a49f5ee458d6b0e9ab4",
"branch_name": "refs/heads/master",
"committer_date": 1590712244000,
"content_id": "c4785c58265eebafcaca5e676b7fd80c0f0c62b1",
"detected_licenses": [
"MIT"
],
"directory_id": "3dec61f1afb546564e34a765ac3236a4fb17a3ff",
"extension": "py",
"filename": "commands.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 267718402,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2455,
"license": "MIT",
"license_type": "permissive",
"path": "/src/commands.py",
"provenance": "stack-edu-0054.json.gz:581503",
"repo_name": "jakobkhansen/CattCommand",
"revision_date": 1590712244000,
"revision_id": "86a813a4a36625cad1ccf9c74baff26d1edf3124",
"snapshot_id": "2d66886ec65cefc040039556fd46ea199d917e73",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jakobkhansen/CattCommand/86a813a4a36625cad1ccf9c74baff26d1edf3124/src/commands.py",
"visit_date": "2022-08-14T08:20:16.924353"
} | 2.9375 | stackv2 | import os
import re
import json
# Commands file
# Values, modified by settings.json
basecommand = "catt"
volume_increment = 10
rewind_amount = 15
seek_amount = 15
saved_volume = 100
# Loads settings into values from settings.json
def load_settings():
global basecommand, volume_increment, rewind_amount, seek_amount
filepath = os.path.dirname(__file__) + "/settings.json"
config = json.load(open(filepath, "r"))
basecommand = config["basecommand"]
volume_increment = config["volume_increment"]
rewind_amount = config["rewind_amount"]
seek_amount = config["seek_amount"]
# Gets info from catt
def get_info():
return exec_command("info")
# Prints info from catt
def print_info():
print(get_info())
# Toggles play/pause
def play_toggle():
exec_command("play_toggle")
# Turns volume down
def volumedown():
command = "volumedown {}".format(volume_increment)
exec_command(command)
# Turns volume up
def volumeup():
command = "volumeup {}".format(volume_increment)
exec_command(command)
# Rewinds the video
def rewind():
command = "rewind {}".format(str(rewind_amount))
exec_command(command)
# Gets current volume
def get_volume():
info = get_info()
return float(re.findall("^volume_level: (.*)", info, re.MULTILINE)[0])
# Toggles mute
def toggle_mute():
global saved_volume
volume_level = get_volume()
if (volume_level > 0):
saved_volume = volume_level
exec_command("volume 0")
else:
new_volume = int(saved_volume*100) & 101
exec_command("volume {}".format(new_volume))
# Gets current time
def get_time():
info = get_info()
return float(re.findall("^current_time: (.*)", info, re.MULTILINE)[0])
# Skips ahead
def skip():
current_time = int(get_time())
new_time = current_time + seek_amount
command = "seek {}".format(new_time)
exec_command(command)
# Stops catt
def stop_stream():
exec_command("stop")
# Executes a command in shell
def exec_command(command):
full_command = "{} {}".format(basecommand, command)
return os.popen(full_command).read()
# List of commands with bindings.
command_list = {
" ": [play_toggle, "Toggling play"],
"i": [print_info, None],
"m": [toggle_mute, "Toggling mute"],
# Arrow keys
68: [rewind, "Rewind"],
65: [volumeup, "Volume up"],
66: [volumedown, "Volume down"],
67: [skip, "Skip"],
"x": [stop_stream, "Goodbye"]
}
| 103 | 22.83 | 74 | 13 | 637 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_76baff7588e7200c_ed56b2be", "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": 24, "column_end": 43, "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/76baff7588e7200c.py", "start": {"line": 18, "col": 24, "offset": 406}, "end": {"line": 18, "col": 43, "offset": 425}, "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_76baff7588e7200c_f1248f75", "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": 89, "line_end": 89, "column_start": 12, "column_end": 34, "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/76baff7588e7200c.py", "start": {"line": 89, "col": 12, "offset": 2086}, "end": {"line": 89, "col": 34, "offset": 2108}, "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"}}}] | 2 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
89
] | [
89
] | [
12
] | [
34
] | [
"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."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | commands.py | /src/commands.py | jakobkhansen/CattCommand | MIT | |
2024-11-18T20:23:24.658324+00:00 | 1,601,317,445,000 | 3dc30a486241a0546112e1aff7a36957bb8e5910 | 3 | {
"blob_id": "3dc30a486241a0546112e1aff7a36957bb8e5910",
"branch_name": "refs/heads/master",
"committer_date": 1601317445000,
"content_id": "8705d904f7e43edfa28b0249d99fcbeebac74894",
"detected_licenses": [
"MIT"
],
"directory_id": "48fc12461c8465543398fb1af73e1a78239da704",
"extension": "py",
"filename": "database.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 299387632,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1888,
"license": "MIT",
"license_type": "permissive",
"path": "/src/database.py",
"provenance": "stack-edu-0054.json.gz:581520",
"repo_name": "a-samir97/Flextock-task",
"revision_date": 1601317445000,
"revision_id": "10b4012876e79b50203d9faed6a836f37daaf314",
"snapshot_id": "9148a35ca47c04e28246b8f80acb1ec848d1ad5a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/a-samir97/Flextock-task/10b4012876e79b50203d9faed6a836f37daaf314/src/database.py",
"visit_date": "2022-12-19T05:50:55.219074"
} | 3.09375 | stackv2 | import psycopg2
import asyncio
from api import get_rate
POSTGRES_CONFIG = {
'database': 'flextock',
'host': 'localhost',
'user': 'ahmedsamir',
'password': 'postgres'
}
def database_connection():
'''
function that connect to database
if:
the database connected successfully return connection object
else:
return None
'''
try:
connection = psycopg2.connect(**POSTGRES_CONFIG)
return connection
except:
return None
async def insert_data(cur, to_currency, from_currency, date, rate):
'''
To Insert data into our database
'''
cur.execute('''
INSERT INTO exchange_currency(to_currency, from_currency, date, rate)
VALUES('%s', '%s', '%s', '%s')
''' % (to_currency, from_currency, date, rate))
def get_data(to_currency, from_currency, date):
'''
To get data from database
if
exist,
else
insert new row for data,
Finally
print data to the user
'''
conn = database_connection()
if conn is not None:
cur = conn.cursor()
cur.execute('''SELECT rate from exchange_currency WHERE date='%s' and
to_currency='%s' and from_currency='%s';''' % (date, to_currency, from_currency))
get_data = cur.fetchone()
if get_data is not None:
cur.close()
conn.close()
print("Rate: %s" %get_data[0])
else:
rate = get_rate(to_currency, from_currency, date)
asyncio.run(insert_data(cur, to_currency, from_currency,date, rate))
# to save change
conn.commit()
print("Rate: %s" % rate)
else:
print('there is an error in database connection') | 79 | 22.91 | 102 | 14 | 406 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_07e066da2272f980_a446ab77", "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": 33, "line_end": 36, "column_start": 5, "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/07e066da2272f980.py", "start": {"line": 33, "col": 5, "offset": 653}, "end": {"line": 36, "col": 64, "offset": 865}, "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_07e066da2272f980_78ecd876", "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": 33, "line_end": 36, "column_start": 5, "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/07e066da2272f980.py", "start": {"line": 33, "col": 5, "offset": 653}, "end": {"line": 36, "col": 64, "offset": 865}, "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_07e066da2272f980_50fe7354", "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": 56, "line_end": 57, "column_start": 9, "column_end": 103, "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/07e066da2272f980.py", "start": {"line": 56, "col": 9, "offset": 1214}, "end": {"line": 57, "col": 103, "offset": 1386}, "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_07e066da2272f980_66a4be74", "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": 56, "line_end": 57, "column_start": 9, "column_end": 103, "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/07e066da2272f980.py", "start": {"line": 56, "col": 9, "offset": 1214}, "end": {"line": 57, "col": 103, "offset": 1386}, "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.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"
] | [
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH"
] | [
33,
33,
56,
56
] | [
36,
36,
57,
57
] | [
5,
5,
9,
9
] | [
64,
64,
103,
103
] | [
"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
] | [
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | database.py | /src/database.py | a-samir97/Flextock-task | MIT | |
2024-11-18T20:23:25.187070+00:00 | 1,688,679,991,000 | 8fce41314257dcbc63deb5fb88c9cb1a982e282b | 3 | {
"blob_id": "8fce41314257dcbc63deb5fb88c9cb1a982e282b",
"branch_name": "refs/heads/main",
"committer_date": 1688679991000,
"content_id": "70ada4a9ebef5418da5bd412518a43b46b7525e5",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "7920ac571217d627aad1ed8fa0b87ef1436cdb28",
"extension": "py",
"filename": "email.py",
"fork_events_count": 30,
"gha_created_at": 1426239107000,
"gha_event_created_at": 1689752699000,
"gha_language": "Python",
"gha_license_id": "BSD-3-Clause",
"github_id": 32147348,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2054,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/casepro/utils/email.py",
"provenance": "stack-edu-0054.json.gz:581524",
"repo_name": "rapidpro/casepro",
"revision_date": 1688679991000,
"revision_id": "66177c00b06b2bd6e6cad2b648feb8f28f592add",
"snapshot_id": "34777e5373822d41ff2e5f3995f86d009c2d1e7c",
"src_encoding": "UTF-8",
"star_events_count": 23,
"url": "https://raw.githubusercontent.com/rapidpro/casepro/66177c00b06b2bd6e6cad2b648feb8f28f592add/casepro/utils/email.py",
"visit_date": "2023-07-20T00:16:09.616516"
} | 2.59375 | stackv2 | from django.conf import settings
from django.contrib.auth.models import User
from django.core.mail import EmailMultiAlternatives, get_connection
from django.template import loader
def send_email(recipients, subject, template, context):
"""
Sends a multi-part (text and optionally HTML) email generated from templates
"""
html_template = loader.get_template(template + ".html")
text_template = loader.get_template(template + ".txt")
html = html_template.render(context)
text = text_template.render(context)
send_raw_email(recipients, subject, text, html)
def send_raw_email(recipients, subject, text, html):
"""
Sends and multi-part (text and optionally HTML) email to a list of users or email addresses
"""
to_addresses = []
for recipient in recipients:
if isinstance(recipient, User):
to_addresses.append(recipient.email)
elif isinstance(recipient, str):
to_addresses.append(recipient)
else: # pragma: no cover
raise ValueError("Email recipients must users or email addresses")
from_address = getattr(settings, "DEFAULT_FROM_EMAIL", "website@casepro.io")
if getattr(settings, "SEND_EMAILS", False):
# send individual messages so as to not leak users email addresses, but use bulk send operation for speed
messages = []
for to_address in to_addresses:
message = EmailMultiAlternatives(subject, text, from_email=from_address, to=[to_address])
if html:
message.attach_alternative(html, "text/html")
messages.append(message)
get_connection().send_messages(messages)
else: # pragma: no cover
print("FAKE SENDING this email to %s:" % ", ".join(to_addresses))
print("--------------------------------------- text -----------------------------------------")
print(text)
if html:
print("--------------------------------------- html -----------------------------------------")
print(html)
| 51 | 39.27 | 113 | 14 | 393 | python | [{"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_7de4dd2df1938b19_84b381d3", "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": 14, "line_end": 14, "column_start": 12, "column_end": 41, "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/7de4dd2df1938b19.py", "start": {"line": 14, "col": 12, "offset": 466}, "end": {"line": 14, "col": 41, "offset": 495}, "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.flask.security.xss.audit.direct-use-of-jinja2_7de4dd2df1938b19_de27c1cd", "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": 15, "line_end": 15, "column_start": 12, "column_end": 41, "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/7de4dd2df1938b19.py", "start": {"line": 15, "col": 12, "offset": 507}, "end": {"line": 15, "col": 41, "offset": 536}, "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"}}}] | 2 | true | [
"CWE-79",
"CWE-79"
] | [
"rules.python.flask.security.xss.audit.direct-use-of-jinja2",
"rules.python.flask.security.xss.audit.direct-use-of-jinja2"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
14,
15
] | [
14,
15
] | [
12,
12
] | [
41,
41
] | [
"A07:2017 - Cross-Site Scripting (XSS)",
"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 direct use of jinja2. If n... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | email.py | /casepro/utils/email.py | rapidpro/casepro | BSD-3-Clause | |
2024-11-18T20:23:28.430391+00:00 | 1,555,402,998,000 | 4b14f436f3356c71b8b64082fb050160c32ec1df | 2 | {
"blob_id": "4b14f436f3356c71b8b64082fb050160c32ec1df",
"branch_name": "refs/heads/master",
"committer_date": 1555402998000,
"content_id": "821de3452a1b87eb6b0b86d5fec955d6de0952a6",
"detected_licenses": [
"MIT"
],
"directory_id": "3f1918a279e807505c6fa13a597eb0d121a095f6",
"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": 225296899,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4476,
"license": "MIT",
"license_type": "permissive",
"path": "/file_hosting_system/app.py",
"provenance": "stack-edu-0054.json.gz:581565",
"repo_name": "linrong/flask-practice",
"revision_date": 1555402998000,
"revision_id": "91ec9d8219482562cb95a1df9ff846f9ca7ea9f1",
"snapshot_id": "b177d5f52c4b55e78bbd5bf14c47decd74c87a28",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/linrong/flask-practice/91ec9d8219482562cb95a1df9ff846f9ca7ea9f1/file_hosting_system/app.py",
"visit_date": "2020-09-22T18:13:19.673917"
} | 2.46875 | stackv2 | #! /usr/bin/env python
# coding=utf-8
import os
# 一种WSGI中间件,为开发环境或简单的服务器设置提供静态内容
from werkzeug import SharedDataMiddleware
from flask import abort,Flask,request,jsonify,redirect,send_file
from ext import db,mako,render_template
#from mysql_models import PasteFile
from mongo_models import PasteFile
from utils import get_file_path,humanize_bytes
ONE_MONTH=60*60*24*30
app=Flask(__name__,template_folder='./templates',static_folder='./static')
app.config.from_object('config')
# SharedDataMiddleware 是提供一个静态文件分享(下载)的路由。
# 和 flask 中默认的 static 不同,flask 是利用的 send_file ,而 SharedDataMiddleware 可以直接在 app 里注册相关的路由,并绑定一个磁盘路径,并分享这个路径下的文件。
# 路由i指向文件夹
app.wsgi_app=SharedDataMiddleware(app.wsgi_app,{'/i/':get_file_path()})
mako.init_app(app)
db.init_app(app)
# 对现有的图片重新设置大小,返回新的地址
@app.route('/r/<img_hash>')
def rsize(img_hash):
w = request.args['w']
h = request.args['h']
# 数据库根据hash查找数据
old_paste = PasteFile.get_by_filehash(img_hash)
# 图片进行剪切
new_paste = PasteFile.rsize(old_paste,w,h)
return new_paste.url_i
# 文件下载,通过使用send_file实现
@app.route('/d/<filehash>',methods=['GET'])
def download(filehash):
paste_file = PasteFile.get_by_filehash(filehash)
return send_file(open(paste_file.path,'rb'),
mimetype='application/octet-stream',
cache_timeout=ONE_MONTH,
as_attachment=True,
attachment_filename=paste_file.filename.encode('utf-8'))
# 首页
@app.route('/',methods=['GET','POST'])
def index():
if request.method == 'POST':
uploaded_file=request.files['file']
w= request.form.get('w')
h= request.form.get('h')
if not uploaded_file:
return abort(400)
if w and h :
# 如果上传指定长和宽则会先剪切
paste_file = PasteFile.rsize(uploaded_file,w,h)
else:
# 创建PasteFile实例
paste_file = PasteFile.create_by_upload_file(uploaded_file)
# # mysql的保存
# db.session.add(paste_file)
# db.session.commit()
# mongo
paste_file.save()
return jsonify({
'url_d':paste_file.url_d,
'url_i':paste_file.url_i,
'url_s':paste_file.url_s,
'url_p':paste_file.url_p,
'filename':paste_file.filename,
'size':humanize_bytes(paste_file.size),
'time':str(paste_file.uploadtime),
'type':paste_file.type,
'quoteurl':paste_file.quoteurl
})
# 不是POST的话,直接渲染index
return render_template('index.html',**locals())
@app.after_request
def after_request(response):
response.headers['Access-Control-Allow-Origin']='*'
response.headers['Access-Control-Allow-Headers']='Content-Type'
return response
@app.route('/j',methods=['POST'])
def j():
uploaded_file=request.files['file']
if uploaded_file:
paste_file=PasteFile.create_by_upload_file(uploaded_file)
# # mysql的保存
# db.session.add(paste_file)
# db.session.commit()
paste_file.save()
width,height=paste_file.image_size
return jsonify({
'url':paste_file.url_i,
'short_url':paste_file.url_s,
'origin_filename':paste_file.filename,
'hash':paste_file.filehash,
'width':width,
'height':height
})
return abort(400)
# 文件预览页
@app.route('/p/<filehash>')
def preview(filehash):
paste_file = PasteFile.get_by_filehash(filehash)
if not paste_file:
filepath=get_file_path(filehash)
if not(os.path.exists(filepath) and (not os.path.islink(filepath))):
return abort(404)
paste_file=PasteFile.create_by_old_paste(filehash)
# db.session.add(paste_file)
# db.session.commit()
paste_file.save()
return render_template('success.html',p=paste_file)
# 短链接页
@app.route('/s/<symlink>')
def s(symlink):
paste_file=PasteFile.get_by_symlink(symlink)
return redirect(paste_file.url_p)
if __name__=='__main__':
app.run(host='0.0.0.0',port=8080)
| 138 | 28.67 | 111 | 16 | 1,059 | python | [{"finding_id": "semgrep_rules.python.flask.security.injection.path-traversal-open_891b2e46369f75f0_b439e8e7", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.injection.path-traversal-open", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found request data in a call to 'open'. Ensure the request data is validated or sanitized, otherwise it could result in path traversal attacks.", "remediation": "", "location": {"file_path": "unknown", "line_start": 42, "line_end": 42, "column_start": 22, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": "CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A05:2017 - Broken Access Control", "references": [{"url": "https://owasp.org/www-community/attacks/Path_Traversal", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.injection.path-traversal-open", "path": "/tmp/tmppq52ww6s/891b2e46369f75f0.py", "start": {"line": 42, "col": 22, "offset": 1499}, "end": {"line": 42, "col": 48, "offset": 1525}, "extra": {"message": "Found request data in a call to 'open'. Ensure the request data is validated or sanitized, otherwise it could result in path traversal attacks.", "metadata": {"cwe": ["CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')"], "owasp": ["A05:2017 - Broken Access Control", "A01:2021 - Broken Access Control", "A01:2025 - Broken Access Control"], "references": ["https://owasp.org/www-community/attacks/Path_Traversal"], "category": "security", "technology": ["flask"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "MEDIUM", "impact": "HIGH", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.audit.avoid_app_run_with_bad_host_891b2e46369f75f0_086b54c0", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.audit.avoid_app_run_with_bad_host", "finding_type": "security", "severity": "medium", "confidence": "high", "message": "Running flask app with host 0.0.0.0 could expose the server publicly.", "remediation": "", "location": {"file_path": "unknown", "line_start": 138, "line_end": 138, "column_start": 5, "column_end": 38, "code_snippet": "requires login"}, "cwe_id": "CWE-668: Exposure of Resource to Wrong Sphere", "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.flask.security.audit.avoid_app_run_with_bad_host", "path": "/tmp/tmppq52ww6s/891b2e46369f75f0.py", "start": {"line": 138, "col": 5, "offset": 4442}, "end": {"line": 138, "col": 38, "offset": 4475}, "extra": {"message": "Running flask app with host 0.0.0.0 could expose the server publicly.", "metadata": {"cwe": ["CWE-668: Exposure of Resource to Wrong Sphere"], "owasp": ["A01:2021 - Broken Access Control", "A01:2025 - Broken Access Control"], "category": "security", "technology": ["flask"], "references": ["https://owasp.org/Top10/A01_2021-Broken_Access_Control"], "subcategory": ["vuln"], "likelihood": "HIGH", "impact": "MEDIUM", "confidence": "HIGH"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-22"
] | [
"rules.python.flask.security.injection.path-traversal-open"
] | [
"security"
] | [
"MEDIUM"
] | [
"HIGH"
] | [
42
] | [
42
] | [
22
] | [
48
] | [
"A05:2017 - Broken Access Control"
] | [
"Found request data in a call to 'open'. Ensure the request data is validated or sanitized, otherwise it could result in path traversal attacks."
] | [
7.5
] | [
"MEDIUM"
] | [
"HIGH"
] | app.py | /file_hosting_system/app.py | linrong/flask-practice | MIT | |
2024-11-18T20:23:28.780627+00:00 | 1,581,739,193,000 | 8bf44ecbb8cfaad492c46f26f79d06815dacaa1f | 3 | {
"blob_id": "8bf44ecbb8cfaad492c46f26f79d06815dacaa1f",
"branch_name": "refs/heads/master",
"committer_date": 1581739193000,
"content_id": "4768610aba4b8384d3818426a5fe1ac0606e0e47",
"detected_licenses": [
"MIT"
],
"directory_id": "255943a1043596d867fb2fe7236b52a9ad33ed72",
"extension": "py",
"filename": "utility.py",
"fork_events_count": 11,
"gha_created_at": 1430166309000,
"gha_event_created_at": 1674510092000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 34689346,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2750,
"license": "MIT",
"license_type": "permissive",
"path": "/scripts/utility.py",
"provenance": "stack-edu-0054.json.gz:581569",
"repo_name": "JinfengChen/RelocaTE2",
"revision_date": 1581739193000,
"revision_id": "b7746986af5b662f8537432ed1b1ed819a046406",
"snapshot_id": "c72099b329e3c1eec5e7bffbd5a9a85a924fa65b",
"src_encoding": "UTF-8",
"star_events_count": 14,
"url": "https://raw.githubusercontent.com/JinfengChen/RelocaTE2/b7746986af5b662f8537432ed1b1ed819a046406/scripts/utility.py",
"visit_date": "2023-01-30T02:02:14.717799"
} | 2.625 | stackv2 | #utility.py
#functions used in several scripts
#jinfeng.chen@ucr.edu
##############################dirs and files##################
##create new directory
def createdir(dirname):
if not os.path.exists(dirname):
os.mkdir(dirname)
##write content to new file
def writefile(outfile, lines):
ofile = open(outfile, 'w')
print >> ofile, lines
ofile.close()
###############################multiprocess#####################
##run function with parameters using multiprocess of #cpu
def mp_pool_function(function, parameters, cpu):
pool = mp.Pool(int(cpu))
imap_it = pool.map(function, tuple(parameters))
collect_list = []
for x in imap_it:
print 'status: %s' %(x)
collect_list.append(x)
return collect_list
##run command line by os.system
def shell_runner(cmdline):
try:
os.system(cmdline)
except:
return 0
return 1
##run multi process job using pool with limited number of cpu
##cmds is list of shell command, cpu is number of cpu to use
def mp_pool(cmds, cpu):
pool = mp.Pool(int(cpu))
imap_it = pool.map(shell_runner, cmds)
count= 0
for x in imap_it:
print 'job: %s' %(cmds[count])
print 'status: %s' %(x)
count += 1
##run job by sequence
def single_run(cmds):
for cmd in cmds:
status = shell_runner(cmd)
print 'job: %s' %(cmd)
print 'status: %s' %(status)
##########################fasta##############################
##get fasta id
def fasta_id(fastafile):
fastaid = defaultdict(str)
for record in SeqIO.parse(fastafile,"fasta"):
fastaid[record.id] = 1
return fastaid
##complement sequence
def complement(seq):
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}
bases = list(seq)
for i in range(len(bases)):
bases[i] = complement[bases[i]] if complement.has_key(bases[i]) else bases[i]
return ''.join(bases)
##reverse_complement sequence
def reverse_complement(seq):
return complement(seq[::-1])
#########################bam################################
##convert tags collumn in sam format into dictionary
def convert_tag(tag):
tags = {}
for t in tag:
tags[t[0]] = t[1]
return tags
#########################relocate###########################
##parse regex.txt
def parse_regex(infile):
data = []
with open (infile, 'r') as filehd:
for line in filehd:
line = line.rstrip()
if len(line) > 2:
unit = re.split(r'\s+',line)
unit[0] = re.sub(r'.(fq|fastq)','',unit[0])
unit[1] = re.sub(r'.(fq|fastq)','',unit[1])
unit[2] = re.sub(r'.(fq|fastq)','',unit[2])
data = unit
return data
| 106 | 24.94 | 85 | 15 | 689 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_1152c026e5f9229b_74600d38", "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": 15, "line_end": 15, "column_start": 13, "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/1152c026e5f9229b.py", "start": {"line": 15, "col": 13, "offset": 316}, "end": {"line": 15, "col": 31, "offset": 334}, "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_1152c026e5f9229b_8b352fee", "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": 34, "line_end": 34, "column_start": 9, "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://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/1152c026e5f9229b.py", "start": {"line": 34, "col": 9, "offset": 842}, "end": {"line": 34, "col": 27, "offset": 860}, "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.unspecified-open-encoding_1152c026e5f9229b_4295c037", "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": 10, "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/1152c026e5f9229b.py", "start": {"line": 95, "col": 10, "offset": 2357}, "end": {"line": 95, "col": 28, "offset": 2375}, "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"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
34
] | [
34
] | [
9
] | [
27
] | [
"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."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | utility.py | /scripts/utility.py | JinfengChen/RelocaTE2 | MIT | |
2024-11-18T20:23:31.190210+00:00 | 1,619,203,264,000 | b5137728f12123a3f300ccb695bd8d36fc6e362c | 3 | {
"blob_id": "b5137728f12123a3f300ccb695bd8d36fc6e362c",
"branch_name": "refs/heads/master",
"committer_date": 1619203264000,
"content_id": "501dfb9e0be00508b2e7de9ab29ff4f4ea4d6ee6",
"detected_licenses": [
"MIT"
],
"directory_id": "5e45335083c62d0f2e2ee2dda07ef57d4c678376",
"extension": "py",
"filename": "verify.py",
"fork_events_count": 5,
"gha_created_at": 1591993997000,
"gha_event_created_at": 1688681493000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 271885345,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9424,
"license": "MIT",
"license_type": "permissive",
"path": "/verify.py",
"provenance": "stack-edu-0054.json.gz:581599",
"repo_name": "synesthesiam/voice-recorder",
"revision_date": 1619203264000,
"revision_id": "9230784f00426d0e4a13e5630d981bff6f99138c",
"snapshot_id": "29628acfc7e22a23bb656e25e5a427fc4385fe17",
"src_encoding": "UTF-8",
"star_events_count": 19,
"url": "https://raw.githubusercontent.com/synesthesiam/voice-recorder/9230784f00426d0e4a13e5630d981bff6f99138c/verify.py",
"visit_date": "2023-07-22T02:38:02.183541"
} | 2.984375 | stackv2 | #!/usr/bin/env python3
"""
Simple tkinter application for verifying voice samples with text prompts.
Shows plot of WAV data. Left click to add trim start, right click to add trim
end. Play and Verify will respect trimmings.
Change prompt in text box to have different text written with Verify.
"""
import argparse
import logging
import subprocess
import threading
import tkinter as tk
import tkinter.messagebox
import typing
from pathlib import Path
from tkinter import ttk
import matplotlib
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from scipy.io.wavfile import read as wav_read
matplotlib.use("TkAgg")
# Directory of this script
_DIR = Path(__file__).parent
_LOGGER = logging.getLogger("verify")
# -----------------------------------------------------------------------------
def main():
"""Main entry point."""
parser = argparse.ArgumentParser()
parser.add_argument(
"input_dir", help="Directory with input WAV files and text prompts"
)
parser.add_argument(
"output_dir",
help="Directory to write verified/trimmed WAV files and text prompts to",
)
args = parser.parse_args()
logging.basicConfig(level=logging.DEBUG)
_LOGGER.debug(args)
input_dir = Path(args.input_dir)
output_dir = Path(args.output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
# -------------------------------------------------------------------------
# Load WAV files to be verified
# -------------------------------------------------------------------------
_LOGGER.debug("Looking for WAV files in %s", input_dir)
todo_prompts: typing.Dict[Path, str] = {}
for wav_path in input_dir.glob("*.wav"):
text_path = wav_path.with_suffix(".txt")
if not text_path.is_file():
_LOGGER.warning("Missing %s", text_path)
continue
rel_wav_path = wav_path.relative_to(input_dir)
done_wav_path = output_dir / rel_wav_path.name
if done_wav_path.is_file():
# Skip already completed WAV files
continue
todo_prompts[rel_wav_path] = text_path.read_text().strip()
todo_paths = list(sorted(todo_prompts.keys()))
total_paths = len(todo_paths)
current_path: typing.Optional[Path] = None
_LOGGER.debug("Found %s WAV files to verify", len(todo_paths))
# -------------------------------------------------------------------------
# Verify Samples
# -------------------------------------------------------------------------
window = tk.Tk()
window.title("Sample Verifier")
# Text box with prompt text
textbox = tk.Text(window, height=3, wrap=tk.WORD)
textbox.config(font=("Courier", 20))
textbox.pack(fill=tk.X, padx=10, pady=10)
# Progress bar for how many prompts are done
progress = ttk.Progressbar(
window, orient=tk.HORIZONTAL, length=100, mode="determinate"
)
progress.pack(fill="x", padx=10, pady=10)
# Label with current WAV file
path_label = tk.Label(window)
path_label.pack(fill=tk.X, padx=10, pady=10)
# Plot of WAV data
figure = Figure(figsize=(8, 3), dpi=100)
plot = figure.add_subplot(1, 1, 1)
figure.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0)
canvas = FigureCanvasTkAgg(figure, window)
canvas.get_tk_widget().pack(fill=tk.BOTH, padx=10, pady=10)
# Start of trimming
left_cut = None
# End of trimming
right_cut = None
# Sample rate (Hz) of current WAV file
sample_rate = None
def redraw():
"""Clears and re-draws WAV plot with trim lines."""
nonlocal sample_rate
plot.cla()
if current_path:
wav_path = input_dir / current_path
_LOGGER.debug("Loading %s", wav_path)
wav_sample_rate, wav_data = wav_read(str(wav_path))
sample_rate = wav_sample_rate
audio = wav_data[:, 0]
plot.plot(audio, color="blue")
plot.set_xlim(0, len(audio))
# Trim lines
if left_cut is not None:
plot.axvline(linewidth=2, x=left_cut, color="red")
if right_cut is not None:
plot.axvline(linewidth=2, x=right_cut, color="green")
canvas.draw()
def onclick(event):
"""Handles mouse clicks on plot."""
nonlocal left_cut, right_cut
if event.button == 1:
# Left click
left_cut = event.xdata
redraw()
elif (event.button == 2) and current_path:
# Middle click
wav_path = input_dir / current_path
if wav_path and wav_path.is_file():
from_sec = event.xdata / sample_rate
play_command = [
"play",
"--ignore-length",
str(wav_path),
"trim",
str(from_sec),
]
if right_cut is not None:
to_sec = right_cut / sample_rate
play_command.append(f"={to_sec}")
threading.Thread(
target=lambda: subprocess.check_call(play_command)
).start()
elif event.button == 3:
# Right click
right_cut = event.xdata
redraw()
canvas.mpl_connect("button_press_event", onclick)
skip_button = None
play_button = None
verify_button = None
def do_next(*_args):
"""Get the next prompt and show text."""
nonlocal current_path, left_cut, right_cut
left_cut = None
right_cut = None
current_path = None
if todo_paths:
current_path = todo_paths.pop()
if current_path:
# Update prompt and WAV plot
wav_path = input_dir / current_path
textbox.delete(1.0, tk.END)
textbox.insert(1.0, todo_prompts[current_path])
path_label["text"] = str(wav_path)
redraw()
else:
tkinter.messagebox.showinfo(message="All done :)")
path_label["text"] = ""
# Update progress bar
if total_paths > 0:
progress["value"] = 100 * ((total_paths - len(todo_paths)) / total_paths)
verify_button["text"] = f"Verify ({len(todo_paths)})"
verify_button.config(bg="#F0F0F0")
play_button.config(bg="yellow")
def do_play(*_args):
"""Play current WAV file"""
wav_path = input_dir / current_path
_LOGGER.debug("Playing %s", wav_path)
if wav_path and wav_path.is_file():
play_command = ["play", "--ignore-length", str(wav_path)]
if (left_cut is not None) or (right_cut is not None):
# Play clipped WAV file
from_sec = 0 if left_cut is None else (left_cut / sample_rate)
play_command.extend(["trim", str(from_sec)])
if right_cut is not None:
to_sec = right_cut / sample_rate
play_command.append(f"={to_sec}")
_LOGGER.debug(play_command)
threading.Thread(target=lambda: subprocess.check_call(play_command)).start()
play_button.config(bg="green")
verify_button.config(bg="yellow")
def do_verify(*_args):
"""Verify recording."""
if current_path:
input_path = input_dir / current_path
output_path = output_dir / current_path
sox_command = ["sox", "--ignore-length", str(input_path), str(output_path)]
if (left_cut is not None) or (right_cut is not None):
# Write clipped WAV file
from_sec = 0 if left_cut is None else (left_cut / sample_rate)
sox_command.extend(["trim", str(from_sec)])
if right_cut is not None:
to_sec = right_cut / sample_rate
sox_command.append(f"={to_sec}")
_LOGGER.debug(sox_command)
subprocess.check_call(sox_command)
# Write prompt
prompt_path = output_dir / current_path.with_suffix(".txt")
prompt_path.write_text(textbox.get(1.0, tk.END).strip())
do_next()
else:
tkinter.messagebox.showinfo(message="No prompt")
# -------------------------------------------------------------------------
bottom_frame = tk.Frame(window)
bottom_frame.pack(fill=tk.BOTH, padx=10, pady=10)
# Button to skip WAV file
skip_button = tk.Button(bottom_frame, text="Skip", command=do_next)
skip_button.config(bg="white", activebackground="red", font=("Courier", 20))
skip_button.pack(side="left", padx=10, pady=10)
# Button to confirm WAV file
verify_button = tk.Button(bottom_frame, text="Verify", command=do_verify)
verify_button.config(
activebackground="green", activeforeground="white", font=("Courier", 20)
)
verify_button.pack(side="right", padx=10, pady=10)
# Button to play back WAV file
play_button = tk.Button(bottom_frame, text="Play", command=do_play)
play_button.config(font=("Courier", 20))
play_button.pack(side="right", padx=10, pady=10)
do_next()
window.mainloop()
# -----------------------------------------------------------------------------
if __name__ == "__main__":
main()
| 292 | 31.27 | 88 | 20 | 2,063 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_f76a0e75c19ac680_ed8f2fed", "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": 171, "line_end": 171, "column_start": 36, "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/f76a0e75c19ac680.py", "start": {"line": 171, "col": 36, "offset": 5201}, "end": {"line": 171, "col": 71, "offset": 5236}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_f76a0e75c19ac680_a6c76f32", "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": 230, "line_end": 230, "column_start": 45, "column_end": 80, "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/f76a0e75c19ac680.py", "start": {"line": 230, "col": 45, "offset": 7211}, "end": {"line": 230, "col": 80, "offset": 7246}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_f76a0e75c19ac680_3a814c24", "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": 251, "line_end": 251, "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/f76a0e75c19ac680.py", "start": {"line": 251, "col": 13, "offset": 8068}, "end": {"line": 251, "col": 47, "offset": 8102}, "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"}}}] | 3 | true | [
"CWE-78",
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH"
] | [
171,
230,
251
] | [
171,
230,
251
] | [
36,
45,
13
] | [
71,
80,
47
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"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()'.",
"Detected subprocess ... | [
7.5,
7.5,
7.5
] | [
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH"
] | verify.py | /verify.py | synesthesiam/voice-recorder | MIT | |
2024-11-18T20:23:35.639877+00:00 | 1,534,843,829,000 | 71411d78a6a491eeb0786e821e4ff62d0c44a28f | 3 | {
"blob_id": "71411d78a6a491eeb0786e821e4ff62d0c44a28f",
"branch_name": "refs/heads/master",
"committer_date": 1534843829000,
"content_id": "c4aee5b28fbd5d1ca75faa069e892768e524b3b4",
"detected_licenses": [
"MIT"
],
"directory_id": "a300412602307da4b3ce30d101d6cb7ce2b9c050",
"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": 144000229,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1252,
"license": "MIT",
"license_type": "permissive",
"path": "/images/backer/src/accounts/models.py",
"provenance": "stack-edu-0054.json.gz:581645",
"repo_name": "elston/flaskit",
"revision_date": 1534843829000,
"revision_id": "849e1fcfa8904771e2ebcb55877bb41440359cd5",
"snapshot_id": "64cfadc1b1c74fd0c1aafa51f6d47dc4dc7a0341",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/elston/flaskit/849e1fcfa8904771e2ebcb55877bb41440359cd5/images/backer/src/accounts/models.py",
"visit_date": "2020-03-25T17:52:11.025682"
} | 2.71875 | stackv2 | import datetime as dt
from flask_login import UserMixin
from database import Column, Model, SurrogatePK, db, reference_col, relationship
from extensions import bcrypt
class User(UserMixin, SurrogatePK, Model):
__tablename__ = 'users'
username = Column(db.String(80), unique=True, nullable=False) #..email
password = Column(db.Binary(128), nullable=True)
# ..
created = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
is_active = Column(db.Boolean(), default=False)
is_admin = Column(db.Boolean(), default=False)
def __init__(self, username, password=None, **kwargs):
# ..
Model.__init__(self, username=username, password=password, **kwargs)
# ..
if password:
self.set_password(password)
else:
self.password = None
def __repr__(self):
"""Represent instance as a unique string."""
return '<User({username!r})>'.format(username=self.username)
def set_password(self, password):
"""Set password."""
self.password = bcrypt.generate_password_hash(password)
def check_password(self, value):
"""Check password."""
return bcrypt.check_password_hash(self.password, value) | 41 | 29.56 | 80 | 12 | 265 | python | [{"finding_id": "semgrep_rules.python.django.security.audit.unvalidated-password_0f15279bcd12c9f8_86848a15", "tool_name": "semgrep", "rule_id": "rules.python.django.security.audit.unvalidated-password", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "The password on 'self' is being set without validating the password. Call django.contrib.auth.password_validation.validate_password() with validation functions before setting the password. See https://docs.djangoproject.com/en/3.0/topics/auth/passwords/ for more information.", "remediation": "if django.contrib.auth.password_validation.validate_password(password, user=self):\n self.set_password(password)", "location": {"file_path": "unknown", "line_start": 27, "line_end": 27, "column_start": 13, "column_end": 40, "code_snippet": "requires login"}, "cwe_id": "CWE-521: Weak Password Requirements", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2021 - Identification and Authentication Failures", "references": [{"url": "https://docs.djangoproject.com/en/3.0/topics/auth/passwords/#module-django.contrib.auth.password_validation", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.audit.unvalidated-password", "path": "/tmp/tmppq52ww6s/0f15279bcd12c9f8.py", "start": {"line": 27, "col": 13, "offset": 764}, "end": {"line": 27, "col": 40, "offset": 791}, "extra": {"message": "The password on 'self' is being set without validating the password. Call django.contrib.auth.password_validation.validate_password() with validation functions before setting the password. See https://docs.djangoproject.com/en/3.0/topics/auth/passwords/ for more information.", "fix": "if django.contrib.auth.password_validation.validate_password(password, user=self):\n self.set_password(password)", "metadata": {"cwe": ["CWE-521: Weak Password Requirements"], "owasp": ["A07:2021 - Identification and Authentication Failures", "A07:2025 - Authentication Failures"], "references": ["https://docs.djangoproject.com/en/3.0/topics/auth/passwords/#module-django.contrib.auth.password_validation"], "category": "security", "technology": ["django"], "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-521"
] | [
"rules.python.django.security.audit.unvalidated-password"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
27
] | [
27
] | [
13
] | [
40
] | [
"A07:2021 - Identification and Authentication Failures"
] | [
"The password on 'self' is being set without validating the password. Call django.contrib.auth.password_validation.validate_password() with validation functions before setting the password. See https://docs.djangoproject.com/en/3.0/topics/auth/passwords/ for more information."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | models.py | /images/backer/src/accounts/models.py | elston/flaskit | MIT | |
2024-11-18T20:23:41.662091+00:00 | 1,584,328,528,000 | 768bfeed286942b057a13f6c30ec15a6b6862ac9 | 3 | {
"blob_id": "768bfeed286942b057a13f6c30ec15a6b6862ac9",
"branch_name": "refs/heads/master",
"committer_date": 1584328528000,
"content_id": "c7ab3202fc4c2da204501ec54d9e580ba5398836",
"detected_licenses": [
"MIT"
],
"directory_id": "fad318e39158f275e8a92c4687312278e8b46395",
"extension": "py",
"filename": "__init__.py",
"fork_events_count": 1,
"gha_created_at": 1584328414000,
"gha_event_created_at": 1584328415000,
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 247599937,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8383,
"license": "MIT",
"license_type": "permissive",
"path": "/pandas_access/__init__.py",
"provenance": "stack-edu-0054.json.gz:581664",
"repo_name": "montoux/pandas_access",
"revision_date": 1584328528000,
"revision_id": "3db7994e0b6b5a55e37f0a0c41d1923f21a9b080",
"snapshot_id": "b352f1aa5ec157c95c0adbe37a984005d0ded8ec",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/montoux/pandas_access/3db7994e0b6b5a55e37f0a0c41d1923f21a9b080/pandas_access/__init__.py",
"visit_date": "2021-03-25T07:47:43.066127"
} | 2.9375 | stackv2 | import re
import subprocess
import pandas as pd
import numpy as np
try:
from StringIO import StringIO as BytesIO
except ImportError:
from io import BytesIO
TABLE_RE = re.compile("CREATE TABLE \[([^\]]+)\]\s+\((.*?\));",
re.MULTILINE | re.DOTALL)
class MdbTable:
""" A MdbTable is basically a list of MdbColumns with some added
functionality.
:param name: Name of the table
"""
def __init__(self, name):
self._name = name
# array instead of dict to preserve the order
self._columns = []
def update_dtypes(self, newDtypes):
""" sets the dtype manually to the given types
:param newDtypes: a dictionary {columnName: newDtype}
"""
for c in self._columns:
if c.get_name() in newDtypes:
c.set_dtype(newDtypes[c.get_name()])
def get_dtypes(self, promote=None):
""" return a dictionary of {columnName: dataType}
:param promote: see MdbColumn.get_dtype
"""
return {c.get_name(): c.get_dtype(promote) for c in self._columns}
def date_field_indices(self):
""" returns the column indices of all datetime fields """
result = []
for idx, col in enumerate(self._columns):
if col.is_datetime():
result.append(idx)
return result
def parse_columns(self, defs_str, implicit_string=True):
"""
Initialize the columns of the table from a schema definition string
created by mdb-schema. The defs_str needs to look like:
[FieldA] Text (100) NOT NULL,
[FieldB] DateTime NOT NULL
...
Even though the table name can be included in the defs_str, the table
name will NOT be altered by this function.
"""
defs = []
lines = defs_str.splitlines()
for line in lines:
col = MdbColumn.try_parse_schema_line(line)
if col is None:
continue
if col.get_dtype() is None and implicit_string:
col.set_dtype(np.str_)
defs.append(col)
self._columns = defs
def get_columns(self):
return self._columns
def get_name(self):
return self._name
class MdbColumn:
__type_conversions = {
'single': np.float32,
'double': np.float64,
'long integer': np.int64,
'integer': np.int_,
'text': np.str_,
'long text': np.str_,
'boolean': np.bool_,
'datetime': np.str_, # additional special handling
}
__schema_line_regex = re.compile(
"^\s*\[(\w+)\]\s*(.*?)(?:\s+(NOT NULL))?,?\s*$", re.IGNORECASE)
@staticmethod
def try_parse_schema_line(line):
""" Create a new MdbColumn object from the given line if possible.
If the format doesn't fit, return None. """
m = MdbColumn.__schema_line_regex.match(line)
if m:
return MdbColumn(m.group(1), m.group(2), m.group(3) == 'NOT NULL')
return None
def __init__(self, name, mdb_type_name, not_null):
self._name = name
self._data_type_name = mdb_type_name
self._dtype = self.__get_numpy_type(mdb_type_name)
self._not_null = not_null
def is_datetime(self):
return self._data_type_name.lower().startswith('datetime')
def __get_numpy_type(self, mdb_type_name):
mdb_name_lc = mdb_type_name.lower()
for mdbstart, nptype in MdbColumn.__type_conversions.items():
if mdb_name_lc.startswith(mdbstart):
return nptype
# print("Unknown type:", mdb_type_name)
return None
def get_name(self):
return self._name
def get_dtype(self, promote=None):
"""
Returns the data type of a column, possibly promoted to a different
type - promotions are useful for NAN values where no NAN is supported
in pandas.
:param promote: Valid values: 'int_to_float', 'nullable_int_to_float'
"""
if self._dtype in [np.int_, np.int64]:
if (promote == 'nullable_int_to_float' and self.maybe_null()) or \
(promote == 'int_to_float'):
return np.float_
return self._dtype
def set_dtype(self, newtype):
self._dtype = newtype
def is_not_null(self):
return self._not_null
def maybe_null(self):
return not self.is_not_null()
def list_tables(rdb_file, encoding="utf-8"):
"""
:param rdb_file: The MS Access database file.
:param encoding: The content encoding of the output. MDBTools
print the output in UTF-8.
:return: A list of the tables in a given database.
"""
# We use -1 (one table name per line) to support stange table names
tables = subprocess.check_output(['mdb-tables', '-1', rdb_file])
return tables.decode(encoding).splitlines()
def read_schema(rdb_file, encoding='utf8', implicit_string=True):
"""
:param rdb_file: The MS Access database file.
:param encoding: The schema encoding. I'm almost positive that MDBTools
spits out UTF-8, exclusively.
:return: a dictionary of tablename -> MdbTable object
"""
output = subprocess.check_output(['mdb-schema', rdb_file])
lines = output.decode(encoding).splitlines()
schema_ddl = "\n".join(l for l in lines if l and not l.startswith('-'))
schema = {}
for tablename, defs in TABLE_RE.findall(schema_ddl):
table = MdbTable(tablename)
table.parse_columns(defs, implicit_string)
schema[tablename] = table
return schema
def read_table(rdb_file, table_name, *args, **kwargs):
"""
Read a MS Access database as a Pandas DataFrame.
Unless you set `converters_from_schema=False`, this function assumes you
want to infer the schema from the Access database's schema. This sets the
`dtype` argument of `read_csv`, which makes things much faster, in most
cases. If you set the `dtype` keyword argument also, it overrides
inferences. The `schema_encoding and implicit_string keyword arguments are
passed through to `read_schema`.
In case you have integer columns with NaNs (not supported by pandas), you
can either manually set the corresponding columns to float by passing the
`dtype` argument. By passing `promote='int_to_float'`, all ints are
automatically converted to float64. For NOT NULL int columns, it is safe
to keep them as int. To promote only int columns that aren't marked NOT
NULL, pass `promote='nullable_int_to_float'`to `read_table`.
I recommend setting `chunksize=k`, where k is some reasonable number of
rows. This is a simple interface, that doesn't do basic things like
counting the number of rows ahead of time. You may inadvertently start
reading a 100TB file into memory. (Although, being a MS product, I assume
the Access format breaks after 2^32 bytes -- har, har.)
:param rdb_file: The MS Access database file.
:param table_name: The name of the table to process.
:param args: positional arguments passed to `pd.read_csv`
:param kwargs: keyword arguments passed to `pd.read_csv`
:return: a pandas `DataFrame` (or, `TextFileReader` if you set
`chunksize=k`)
"""
if kwargs.pop('converters_from_schema', True):
specified_dtypes = kwargs.pop('dtype', {})
schema_encoding = kwargs.pop('schema_encoding', 'utf8')
promote = kwargs.pop('promote', None)
schemas = read_schema(rdb_file, schema_encoding,
kwargs.pop('implicit_string', True))
table = schemas[table_name]
table.update_dtypes(specified_dtypes)
kwargs['dtype'] = table.get_dtypes(promote)
kwargs['parse_dates'] = table.date_field_indices()
cmd = ['mdb-export', '-D', '%Y-%m-%d %H:%M:%S', rdb_file, table_name]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
try:
return pd.read_csv(proc.stdout, *args, **kwargs)
except ValueError as ve:
if 'Integer column has NA values' in str(ve):
msg = str(ve).splitlines()[-1]
raise ValueError("\n".join((
msg,
"Consider passing promote='nullable_int_to_float' or",
"passing promote='int_to_float' to read_table")))
else:
raise ve
| 227 | 35.93 | 78 | 16 | 1,974 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_c403b35df75819c0_fae29d13", "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": 216, "line_end": 216, "column_start": 12, "column_end": 57, "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/c403b35df75819c0.py", "start": {"line": 216, "col": 12, "offset": 7911}, "end": {"line": 216, "col": 57, "offset": 7956}, "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"
] | [
216
] | [
216
] | [
12
] | [
57
] | [
"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"
] | __init__.py | /pandas_access/__init__.py | montoux/pandas_access | MIT | |
2024-11-18T20:48:56.633720+00:00 | 1,589,794,107,000 | dd6d50bf6069af1a82999ba53d887800bb050208 | 3 | {
"blob_id": "dd6d50bf6069af1a82999ba53d887800bb050208",
"branch_name": "refs/heads/master",
"committer_date": 1589794107000,
"content_id": "c72c947489c42e822bfff0c0aab166ae9dd5e9d1",
"detected_licenses": [
"MIT"
],
"directory_id": "cfe9c83075381a2d1edfb54ff652d2d4bc4eafaa",
"extension": "py",
"filename": "_nda.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 242320558,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9133,
"license": "MIT",
"license_type": "permissive",
"path": "/_nda.py",
"provenance": "stack-edu-0054.json.gz:581700",
"repo_name": "Bobyuan1015/KDA",
"revision_date": 1589794107000,
"revision_id": "ce442922deb93b1bfe2ad7c418f1c63f5c40e000",
"snapshot_id": "062ee6ea9d4bc3c26e5f928d3b673b4aa8146079",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Bobyuan1015/KDA/ce442922deb93b1bfe2ad7c418f1c63f5c40e000/_nda.py",
"visit_date": "2021-01-09T13:34:13.130670"
} | 2.6875 | stackv2 | # -*- coding: utf-8 -*-
"""
File Name: _nda.py
Description : data augmentation by extending noise data into data set.
Author : yuanfang
date: 2019/12/13
"""
# os模块中包含很多操作文件和目录的函数
import os
import subprocess
import time
from collections import defaultdict
import pandas as pd
import jieba
import re
from collections import Counter
import collections
from sklearn.utils import shuffle
def merge_csv(files, merge_path):
if len(files) < 1:
return None
dfs = []
for f in files:
if f is None:
return None
else:
df = pd.read_csv(f)
df = shuffle(df)
dfs.append(df)
concat_df = pd.concat(dfs, axis=0, ignore_index=True)
concat_df = concat_df.loc[:, ['final_all_keys']]
concat_df = shuffle(concat_df)
concat_df.drop_duplicates(subset=['final_all_keys'], keep='first', inplace=True) # remove duplication rows
concat_df.to_csv(merge_path, index=False)
return len(concat_df), merge_path
def merge_all_refine_keys(refine_dir):
print(refine_dir)
paths = []
for root, dirs_p, files in os.walk(refine_dir):
for dir in dirs_p:
for root, dirs, files in os.walk(refine_dir + dir):
for file_name in files:
if file_name.endswith('refine.csv'):
print(f" {file_name}")
paths.append(refine_dir + dir+'/'+file_name)
print(paths)
l,merge_path = merge_csv(paths, refine_dir+'all_refine.csv')
print(f"merge len=", l)
return merge_path
def merge_path(path, out_file_name, sub_name_in_file='clean'):
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
pd.set_option('max_colwidth', 100)
# -----------merge all files
path = path+'/'
tomerge_files = []
for root, dirs, files in os.walk(path):
for file_name in files:
if sub_name_in_file in file_name:
tomerge_files.append(path + file_name)
break
#print('merge files:',tomerge_files)
merge_csv(tomerge_files, path + out_file_name)
def mergse_all_txts(dir):
# 获取目标文件夹的路径
# meragefiledir = os.getcwd() + '//MerageFiles'
meragefiledir = dir
# 获取当前文件夹中的文件名称列表
filenames = os.listdir(meragefiledir)
stopwords = []
# 先遍历文件名
for filename in filenames:
if '.txt' in filename:
filepath = meragefiledir + '/'
filepath = filepath + filename
# 遍历单个文件,读取行数
for line in open(filepath):
stopwords.append(line)
# 关闭文件
allstops = list(set(stopwords))
df = pd.DataFrame({'stops':allstops})
print(f"old len={len(stopwords)}, new len={len(df)}")
df.to_csv(dir+'/stops.csv',index=False)
return dir+'/stops.csv'
def dataPrepos(text, stopkey):
# l = []
# pos = ['n','v','vn']
#'nz',#名词
#'v',
# 'vd',
#'vn',#动词
#'l',
#'a',#形容词
# 'd'#副词
#] # 定义选取的词性
seg = jieba.cut(text) # 分词
# for i in seg:
# if i.word not in stopkey:
# # if i.word not in stopkey: # 去停用词 + 词性筛选
# l.append(i.word)
l=[]
for aseg in seg:
if len(aseg) > 1 and ' ' not in aseg and not bool(re.search(r'\d', aseg)):
l.append(aseg)
return l
def compute_useless_words(file,exclude_words):
df = pd.read_csv(file)
df['segs'] = df.apply(lambda row:dataPrepos(row['content'],exclude_words),axis=1)
text = []
for alist in df['segs'].to_list():
text.extend(alist)
c = Counter(text)
# all_size = len(set(list(c.elements())))
# print("all_size=",all_size)
count_pairs = c.most_common()
words, _ = list(zip(*count_pairs))
hight_tf_words = words[:5000]
low_tf_words = words[-5000:]
stopword_dictionary = list(set(hight_tf_words+low_tf_words))
print(c)
return stopword_dictionary
def get_useless(save_dir,root_dir, refine_path):
all_files = ['1.csv', '0.csv', '体育.csv',
'娱乐.csv', '家居.csv', '房产.csv',
'教育.csv', '时尚.csv', '游戏.csv',
'科技.csv', '财经.csv', '时政.csv']
root_dir = 'data/data_orginal/'
refine_df = pd.read_csv(refine_path)
refine_words = refine_df['final_all_keys'].to_list()
for root, dirs_p, files in os.walk(root_dir):
all_keys = []
final_all_keys = set()
for dir in dirs_p:
if dir in ['cnews_10', 'weibo_senti_100k', 'chnsenticorp']:
save_folder = save_dir+dir
subprocess.getstatusoutput(f"mkdir -p {save_folder}")
for root_, dirs_, files_ in os.walk(root_dir+dir):
keys_classes = []
for file_name in files_:
if file_name in all_files:
file = root_dir + dir + '/' + file_name
print(file)
useless_words = compute_useless_words(file, refine_words)
key_save_path = save_folder + '/' + file_name + '_useless_size' + str(len(useless_words)) + '.csv'
df = pd.DataFrame({'useless_words':useless_words})
df.to_csv(key_save_path, index=False)
def search_replacement(sentence, words):
searched_list = []
for word in words:
if word in sentence:
searched_list.append(word)
return searched_list
def nda(file_path, dict_path, newsize=-1):
df = pd.read_csv(file_path+'.csv')
row_num = len(df)
da_size = newsize - row_num
print('kda open ', file_path, row_num, ' ', dict_path)
df_synonyms = pd.read_csv(dict_path)
df_synonyms.drop(df_synonyms[df_synonyms.final_all_keys.isnull()].index, inplace=True)
df_synonyms.drop(df_synonyms[df_synonyms.close_words.isnull()].index, inplace=True)
synonym_dict = defaultdict(list)
for index, row in df_synonyms.iterrows():
synonym_dict[row['final_all_keys']] = row['close_words'].split(',')
da_sentences = []
hit_keywords = []
for index, row in df.iterrows():
sentence = row['content']
keywords_to_be_replaced = search_replacement(sentence, df_synonyms['final_all_keys'].tolist())
hit_keywords.append(keywords_to_be_replaced)
labels = []
keys = []
for index, row in df.iterrows():
sentence = row['content']
new_sents = augment(sentence, hit_keywords[index], synonym_dict, row_num-index, da_size)
da_size -= len(new_sents)
da_sentences.extend(new_sents)
for i in range(len(new_sents)):
labels.append(row['label'])
keys.append(hit_keywords[index])
if da_size < 1:
break
df_da = pd.DataFrame({"content": da_sentences, "label": labels, "keys": keys})
new_df = pd.concat([df, df_da])
new_df.to_csv(file_path+'_kda.csv', index=False)
return file_path+'_kda.csv'
def augument_data(original_data, da_number):
"""
:param original_data: a list of orginal data paths type:list
:param number: the amount of the data after data augmentation process type:int
"""
data_kda_folders = [path+'_nda_'+str(da_number)+'/' for path in original_data]
useless_words_dir = 'data/stopwords/'
time_start = time.time()
for index, folder_p in enumerate(data_kda_folders):
# print(index,' ',folder_p)
subprocess.getstatusoutput('rm -rf ' + folder_p)
subprocess.getstatusoutput('cp -rf ' + original_data[index] + ' ' + folder_p)
subprocess.getstatusoutput('find ' + folder_p + ' -name train.csv |xargs rm')
for root, dirs_p, files in os.walk(folder_p):
for dir in dirs_p:
for root, dirs, files in os.walk(folder_p + dir):
for file_name in files:
if 'train.csv' not in file_name:
f_name = file_name.split('.csv')[0]
dict_path = useless_words_dir + dir + '/' + f_name + 'picked.csv' #近义词+refine的停用词
nda(folder_p + dir + '/' + f_name, dict_path, da_number)
print("Augmenting all the data, take times :" + str((time.time() - time_start) / 60) + ' mins')
# build training set
for folder_p in data_kda_folders:
for root, dirs_p, files in os.walk(folder_p):
for dir in dirs_p:
merge_path(folder_p + dir, 'train.csv', '_nda.csv')
break
#1.获得所有refine的词
# refine_path = merge_all_refine_keys("data/refine_keywords/")
#2.收集网络上的停用词
# stops_path = mergse_all_txts("data/stopwords")
#3.分词并计算词频
# refine_path='data/refine_keywords/all_refine.csv'
# get_useless("data/stopwords/", "data/data_orginal/", refine_path)
#4.数据增强
augument_data(['data/data_500', 'data/data_2000'],5000) | 265 | 32.38 | 126 | 24 | 2,294 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_1bb6d6ee07bb85d4_3aacd4e3", "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": 85, "line_end": 85, "column_start": 25, "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/tmppq52ww6s/1bb6d6ee07bb85d4.py", "start": {"line": 85, "col": 25, "offset": 2676}, "end": {"line": 85, "col": 39, "offset": 2690}, "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_1bb6d6ee07bb85d4_b084fc63", "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 'getstatusoutput' 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": 156, "line_end": 156, "column_start": 17, "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/1bb6d6ee07bb85d4.py", "start": {"line": 156, "col": 17, "offset": 4785}, "end": {"line": 156, "col": 70, "offset": 4838}, "extra": {"message": "Detected subprocess function 'getstatusoutput' 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_1bb6d6ee07bb85d4_24316b28", "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 'getstatusoutput' 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": 229, "line_end": 229, "column_start": 9, "column_end": 57, "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/1bb6d6ee07bb85d4.py", "start": {"line": 229, "col": 9, "offset": 7655}, "end": {"line": 229, "col": 57, "offset": 7703}, "extra": {"message": "Detected subprocess function 'getstatusoutput' 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_1bb6d6ee07bb85d4_29a65695", "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 'getstatusoutput' 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": 230, "line_end": 230, "column_start": 9, "column_end": 86, "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/1bb6d6ee07bb85d4.py", "start": {"line": 230, "col": 9, "offset": 7712}, "end": {"line": 230, "col": 86, "offset": 7789}, "extra": {"message": "Detected subprocess function 'getstatusoutput' 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_1bb6d6ee07bb85d4_b8f9abf4", "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 'getstatusoutput' 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": 231, "line_end": 231, "column_start": 9, "column_end": 86, "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/1bb6d6ee07bb85d4.py", "start": {"line": 231, "col": 9, "offset": 7798}, "end": {"line": 231, "col": 86, "offset": 7875}, "extra": {"message": "Detected subprocess function 'getstatusoutput' 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"}}}] | 5 | true | [
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | [
156,
229,
230,
231
] | [
156,
229,
230,
231
] | [
17,
9,
9,
9
] | [
70,
57,
86,
86
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'getstatusoutput' 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 subpro... | [
7.5,
7.5,
7.5,
7.5
] | [
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | _nda.py | /_nda.py | Bobyuan1015/KDA | MIT | |
2024-11-18T20:48:57.767308+00:00 | 1,614,608,022,000 | 612827a771027a6fa1007880ac24c3a0f69aa22d | 2 | {
"blob_id": "612827a771027a6fa1007880ac24c3a0f69aa22d",
"branch_name": "refs/heads/master",
"committer_date": 1614608022000,
"content_id": "e133d55214c70ea45092d3d0e2156e59cebf76fb",
"detected_licenses": [
"MIT"
],
"directory_id": "e53f30bdd729a5a59d73ab41792157d9ac35a189",
"extension": "py",
"filename": "streaming.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 295474984,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7358,
"license": "MIT",
"license_type": "permissive",
"path": "/OT-AI/streaming.py",
"provenance": "stack-edu-0054.json.gz:581716",
"repo_name": "OpenTonk/OT-AI",
"revision_date": 1614608022000,
"revision_id": "591f5ec733077a5508d5371dce71b076e616707e",
"snapshot_id": "7d83c38fe3ba93eb186dde950c3774af81488488",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/OpenTonk/OT-AI/591f5ec733077a5508d5371dce71b076e616707e/OT-AI/streaming.py",
"visit_date": "2023-03-09T08:02:23.299247"
} | 2.34375 | stackv2 | import socket
import asyncio
import struct
import cv2
import pickle
import numpy as np
from datetime import datetime
import threading
import io
try:
from picamera.array import PiRGBArray
from picamera import PiCamera
except:
pass
buffer_size = 4096
class AsyncServer:
def __init__(self, host: str, port: int, usePiCam=False):
self.host = host
self.port = port
self.on_frame_array = []
self.on_disconnect_array = []
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if usePiCam:
self.socket = socket.socket()
self.lastFrame = None
self.frameNum = 0
self.usePiCam = usePiCam
self.frame = []
async def serve(self):
# self.sock = await asyncio.start_server(self.server_handler, self.host, self.port)
print("starting stream server...")
self.socket.bind((self.host, self.port))
if self.usePiCam:
self.socket.makefile('rb')
print("stream server expects to recieve picam images")
self.socket.listen(0)
try:
await self.server_handler()
except KeyboardInterrupt:
pass
async def server_handler(self):
while True:
conn, info = self.socket.accept()
print("Stream client connected", conn.getpeername())
startTime = datetime.now()
self.frameNum = 0
if self.usePiCam:
cam = PiCameraThread(conn)
t = threading.Thread(target=cam.loop)
t.start()
await asyncio.sleep(2)
while t.is_alive():
#start = datetime.now()
if not np.array_equal(self.lastFrame, cam.frame):
self.call_on_frame(cam.frame)
#print((datetime.now() - start).total_seconds())
#await asyncio.sleep(0.05)
else:
package_size = struct.calcsize('L')
data = b''
while (datetime.now() - startTime).total_seconds() < 0.2:
buf = []
skip = False
while(len(data) < package_size):
buf = conn.recv(buffer_size)
if len(buf) == 0:
skip = True
break
data += buf
# if no frame data then skip
if skip:
continue
packed_msg_size = data[:package_size]
# unpack data
data = data[package_size:]
msg_size = struct.unpack("L", packed_msg_size)[0]
# recieve frame data
while(len(data) < msg_size):
buf = conn.recv(buffer_size)
if len(buf) == 0:
skip = True
break
data += buf
# no frame data then skip
if skip:
continue
frame_data = data[:msg_size]
data = data[msg_size:]
frame = pickle.loads(frame_data)
startTime = datetime.now()
self.call_on_frame(frame)
print("Stream client disconnected", conn.getpeername())
cv2.destroyAllWindows()
self.call_on_disconnect()
def call_on_frame(self, frame):
self.frameNum += 1
self.lastFrame = frame
for f in self.on_frame_array:
f(frame)
def call_on_disconnect(self):
for f in self.on_disconnect_array:
f()
def on_frame(self):
def decorator(f):
self.on_frame_array.append(f)
return f
return decorator
def on_disconnect(self):
def decorator(f):
self.on_disconnect_array.append(f)
return f
return decorator
class AsyncClient:
def __init__(self, host, port, usePiCam=False):
self.host = host
self.port = port
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if usePiCam:
self.socket = socket.socket()
self.on_msg_functions = []
self.usePiCam = usePiCam
async def connect(self):
print("starting stream client...")
self.socket.connect((self.host, self.port))
if self.usePiCam:
print("stream client will use picamera")
try:
await self.client_handler()
except KeyboardInterrupt:
pass
async def client_handler(self):
if self.usePiCam:
cam = PiCamera()
cam.resolution = (360, 270)
cam.framerate = 24
# get file-like object connection
conn = self.socket.makefile('wb')
# get stream to store img
stream = io.BytesIO()
# read capture stream
try:
for img in cam.capture_continuous(stream, 'jpeg', use_video_port=True):
# send image length
conn.write(struct.pack('<L', stream.tell()))
conn.flush()
# rewind stream and send image data
stream.seek(0)
conn.write(stream.read())
# reset stream
stream.seek(0)
stream.truncate()
finally:
conn.write(struct.pack('<L', 0))
conn.flush()
conn.close()
self.socket.close()
cam.stop_recording()
else:
while True:
frame = self.get_frame()
data = pickle.dumps(frame)
self.socket.sendall(struct.pack("L", len(data)) + data)
print("client handler stopped")
def close(self):
self.writer.close()
def get_frame(self) -> np.ndarray:
return self.get_frame_func()
def on_get_frame(self):
def decorator(f):
self.get_frame_func = f
return f
return decorator
class PiCameraThread:
def __init__(self, conn):
self.frame = []
self.conn = conn.makefile('rb')
def loop(self):
package_size = struct.calcsize('<L')
img_stream = io.BytesIO()
try:
while True:
start = datetime.now()
img_len = struct.unpack('<L', self.conn.read(package_size))[0]
# disconnect when img length is 0
if not img_len:
break
# img stream to store img
img_stream.write(self.conn.read(img_len))
# rewind stream
img_stream.seek(0)
# convert to cv2 frame
data = np.fromstring(img_stream.getvalue(), dtype=np.uint8)
self.frame = cv2.imdecode(data, 1)
# reset stream
img_stream.seek(0)
img_stream.truncate()
# print((datetime.now() - start).total_seconds())
finally:
return 0
| 265 | 26.77 | 91 | 19 | 1,412 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_82d3c1ca57f972f3_cc224412", "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": 119, "line_end": 119, "column_start": 29, "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/tmppq52ww6s/82d3c1ca57f972f3.py", "start": {"line": 119, "col": 29, "offset": 3320}, "end": {"line": 119, "col": 53, "offset": 3344}, "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_82d3c1ca57f972f3_03dc0a00", "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": 214, "line_end": 214, "column_start": 24, "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/82d3c1ca57f972f3.py", "start": {"line": 214, "col": 24, "offset": 5917}, "end": {"line": 214, "col": 43, "offset": 5936}, "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"
] | [
119,
214
] | [
119,
214
] | [
29,
24
] | [
53,
43
] | [
"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"
] | streaming.py | /OT-AI/streaming.py | OpenTonk/OT-AI | MIT | |
2024-11-18T20:49:15.091384+00:00 | 1,521,544,521,000 | b8ef44dc2f3f103a97a0798c2c9ee153ffa47be7 | 3 | {
"blob_id": "b8ef44dc2f3f103a97a0798c2c9ee153ffa47be7",
"branch_name": "refs/heads/master",
"committer_date": 1521544521000,
"content_id": "51ae2f43f32dd2685a8c7f1702f62762989d54e8",
"detected_licenses": [
"MIT"
],
"directory_id": "811dee382e5c13e222557de7c7c75084fc5e0939",
"extension": "py",
"filename": "main.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 126005398,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2975,
"license": "MIT",
"license_type": "permissive",
"path": "/app/main.py",
"provenance": "stack-edu-0054.json.gz:581726",
"repo_name": "madforjs/cvsm",
"revision_date": 1521544521000,
"revision_id": "4901cb4f5b1a4307912bc27dc839b4c45317a385",
"snapshot_id": "a92886158f0260f705c777899af6e1c064413437",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/madforjs/cvsm/4901cb4f5b1a4307912bc27dc839b4c45317a385/app/main.py",
"visit_date": "2021-09-10T00:27:23.230409"
} | 2.515625 | stackv2 | import cgi
import io
import glob
import os
import json
from bottle import route, run, template, post, request
from requests import get
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.corpus import wordnet
stop_words = []
files = []
fcontent = {}
fildoclist = []
filwords =[]
pptokens =[]
c_dict = {}
def stopWords(words):
stop_words = stopwords.words('english')
for w in words:
stop_words.append(w)
print(stop_words)
return stop_words
@post('/sw') # or @route('/login', method='POST')
def do_sw():
words = request.json['words']
words = words.split(',')
print(words)
global stop_words
stop_words = stopWords(words)
str = ','.join(stop_words)
str = "{'data':'stopwords','words':'" + str + "'}"
return str
@post('/swget') # or @route('/login', method='POST')
def do_sw():
global stop_words
str = ','.join(stop_words)
str = "{'data':'stopwords','words':'" + str + "'}"
return str
@route('/exec/upload', method='POST')
def do_upload():
global files
global fcontent
files = request.files.getall('files')
print(request.files)
for f in files:
fcontent[f.filename] = f.file.read()
print(fcontent)
return "Upload success"
@route('/exec/pp', method='POST')
def do_pp():
global stop_words
global fcontent
global fildoclist
c = 0
for file_name in fcontent:
# Tokenization
word_tokenize_list = word_tokenize(fcontent[file_name])
# Stop word Removal
filteredfilename = "filtered_docs" + "/" + "filter%d.txt" % c
fildoclist.append(os.path.basename(filteredfilename))
file2 = open(filteredfilename,'w+')
for r in word_tokenize_list:
if not r in stop_words:
file2.write(r.lower()+" ")
file2.close()
collect_tokens(c)
c+=1
return "Preprocess sucesss"
def collect_tokens(c):
global fildoclist
global pptokens
global filwords
for f_file_name in fildoclist:
f_fi = open(f_file_name,'r')
f_file_content = f_fi.read()
tokens = f_file_content.split()
uniquetokens = []
for i in tokens:
if i not in uniquetokens:
uniquetokens.append(i)
# add each token to pptokens list
filwords.append(uniquetokens)
for i in uniquetokens:
if i not in pptokens:
pptokens.append(i)
print(pptokens)
def generating_concepts():
global pptokens
global c_dict
for word in pptokens:
synonyms = []
synunique = []
for syn in wordnet.synsets(word):
for l in syn.lemmas():
synonyms.append(l.name())
for i in synonyms:
if i not in synunique:
synunique.append(i)
c_dict[word] = synunique
print (c_dict)
return c_dict
### Localhost process
run(host='localhost', port=3000, debug=True) | 114 | 25.11 | 69 | 17 | 736 | python | [{"finding_id": "semgrep_rules.python.flask.security.audit.directly-returned-format-string_ee74221c75c4f0c6_798c43b2", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.audit.directly-returned-format-string", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected Flask route directly returning a formatted string. This is subject to cross-site scripting if user input can reach the string. Consider using the template engine instead and rendering pages with 'render_template()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 37, "line_end": 37, "column_start": 5, "column_end": 15, "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://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.audit.directly-returned-format-string", "path": "/tmp/tmppq52ww6s/ee74221c75c4f0c6.py", "start": {"line": 37, "col": 5, "offset": 788}, "end": {"line": 37, "col": 15, "offset": 798}, "extra": {"message": "Detected Flask route directly returning a formatted string. This is subject to cross-site scripting if user input can reach the string. Consider using the template engine instead and rendering pages with 'render_template()'.", "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"], "category": "security", "technology": ["flask"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "HIGH", "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_ee74221c75c4f0c6_787fe35b", "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": 17, "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/ee74221c75c4f0c6.py", "start": {"line": 69, "col": 17, "offset": 1680}, "end": {"line": 69, "col": 44, "offset": 1707}, "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_ee74221c75c4f0c6_98aa3b01", "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": 83, "line_end": 83, "column_start": 9, "column_end": 37, "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/ee74221c75c4f0c6.py", "start": {"line": 83, "col": 9, "offset": 2050}, "end": {"line": 83, "col": 37, "offset": 2078}, "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_ee74221c75c4f0c6_6c030185", "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": 83, "line_end": 83, "column_start": 16, "column_end": 37, "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/ee74221c75c4f0c6.py", "start": {"line": 83, "col": 16, "offset": 2057}, "end": {"line": 83, "col": 37, "offset": 2078}, "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-79"
] | [
"rules.python.flask.security.audit.directly-returned-format-string"
] | [
"security"
] | [
"MEDIUM"
] | [
"MEDIUM"
] | [
37
] | [
37
] | [
5
] | [
15
] | [
"A07:2017 - Cross-Site Scripting (XSS)"
] | [
"Detected Flask route directly returning a formatted string. This is subject to cross-site scripting if user input can reach the string. Consider using the template engine instead and rendering pages with 'render_template()'."
] | [
5
] | [
"HIGH"
] | [
"MEDIUM"
] | main.py | /app/main.py | madforjs/cvsm | MIT | |
2024-11-18T20:49:18.613174+00:00 | 1,410,931,033,000 | fb2a59bbcf6b86e32a3d39e83eb6c21a56579552 | 3 | {
"blob_id": "fb2a59bbcf6b86e32a3d39e83eb6c21a56579552",
"branch_name": "refs/heads/master",
"committer_date": 1410931033000,
"content_id": "ff3a5406f7f6584bcd0f1bf5357835354bac2e4b",
"detected_licenses": [
"MIT"
],
"directory_id": "ee1d2ebec08fb1c9858bab1b5bd061cc6a0d6087",
"extension": "py",
"filename": "__main__.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": 3260,
"license": "MIT",
"license_type": "permissive",
"path": "/__main__.py",
"provenance": "stack-edu-0054.json.gz:581761",
"repo_name": "scizzorz/leap-volume",
"revision_date": 1410931033000,
"revision_id": "d8e31ba3c012dc08a901824fae5df727af0543db",
"snapshot_id": "b6074b3f603c685ecece2618b9c9ce861c67ab5e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/scizzorz/leap-volume/d8e31ba3c012dc08a901824fae5df727af0543db/__main__.py",
"visit_date": "2016-09-06T17:37:45.483288"
} | 2.75 | stackv2 | #!/usr/bin/env python2
import os
import sys
import thread
import time
sys.path.insert(0, '/usr/lib/Leap')
import Leap as L
from Leap import CircleGesture
from Leap import Gesture
from Leap import SwipeGesture
def call_amixer():
pass
def set_volume():
pass
print "Leap imported."
class SampleListener(L.Listener):
VOL_SPEED = 3
pvol = 20
volume = 20
muted = False
def set_volume(self, volume):
vol = min(64, max(0, int(volume)))
if vol != self.pvol:
self.pvol = vol
os.system('amixer -q sset Master %d' % vol)
print 'Set volume to %d' % vol
def save_volume(self):
self.volume = self.pvol
print 'Saved volume to %d' % self.pvol
def mute(self):
self.muted = True
os.system('amixer -q sset Master toggle')
print 'Muted volume'
def unmute(self):
self.muted = False
os.system('amixer -q sset Master toggle')
print 'Unmuted volume'
def next(self):
os.system('xdotool key XF86AudioNext')
print 'Next song'
def prev(self):
os.system('xdotool key XF86AudioPrev')
print 'Previous song'
def pause(self):
os.system('xdotool key XF86AudioPlay')
print 'Play/pause song'
def on_init(self, controller):
print "Initialized"
def on_connect(self, controller):
print "Connected"
# Enable gestures
controller.enable_gesture(Gesture.TYPE_CIRCLE);
controller.enable_gesture(Gesture.TYPE_SWIPE);
def on_disconnect(self, controller):
# Note: not dispatched when running in a debugger.
print "Disconnected"
def on_exit(self, controller):
print "Exited"
def on_frame(self, controller):
# Get the most recent frame and report some basic information
frame = controller.frame()
# Check for mute
if self.muted and len(frame.hands) == 0:
self.unmute()
for hand in frame.hands:
if self.muted and len(hand.fingers.extended()) < 5:
self.unmute()
break
if not self.muted and len(hand.fingers.extended()) == 5:
self.mute()
break
# Get gestures
for gesture in frame.gestures():
if gesture.type == Gesture.TYPE_CIRCLE:
circle = CircleGesture(gesture)
# Determine clock direction using the angle between the pointable and the circle normal
if circle.pointable.direction.angle_to(circle.normal) <= L.PI/2:
clockwiseness = "clockwise"
else:
clockwiseness = "counterclockwise"
mod = circle.progress * self.VOL_SPEED
if clockwiseness == 'counterclockwise':
mod = -mod
self.set_volume(self.volume + mod)
if gesture.state is Gesture.STATE_STOP:
self.save_volume()
if gesture.type == Gesture.TYPE_SWIPE:
swipe = SwipeGesture(gesture)
if gesture.state is Gesture.STATE_STOP:
if swipe.direction[0] > 0.6:
self.next()
elif swipe.direction[0] < -0.6:
self.prev()
elif abs(swipe.direction[1]) > 0.6:
self.pause()
def main():
# Create a sample listener and controller
listener = SampleListener()
controller = L.Controller()
# Have the sample listener receive events from the controller
controller.add_listener(listener)
# Keep this process running until Enter is pressed
print "Press Enter to quit..."
try:
sys.stdin.readline()
except KeyboardInterrupt:
pass
finally:
# Remove the sample listener when done
controller.remove_listener(listener)
main()
| 143 | 21.8 | 91 | 19 | 858 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.pass-body-fn_f45386f5f6ed2669_adf922ae", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.pass-body-fn", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "`pass` is the body of function call_amixer. Consider removing this or raise NotImplementedError() if this is a TODO", "remediation": "", "location": {"file_path": "unknown", "line_start": 13, "line_end": 14, "column_start": 1, "column_end": 6, "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.best-practice.pass-body-fn", "path": "/tmp/tmppq52ww6s/f45386f5f6ed2669.py", "start": {"line": 13, "col": 1, "offset": 211}, "end": {"line": 14, "col": 6, "offset": 235}, "extra": {"message": "`pass` is the body of function call_amixer. Consider removing this or raise NotImplementedError() if this is a TODO", "metadata": {"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.best-practice.pass-body-fn_f45386f5f6ed2669_e73a1a54", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.pass-body-fn", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "`pass` is the body of function set_volume. Consider removing this or raise NotImplementedError() if this is a TODO", "remediation": "", "location": {"file_path": "unknown", "line_start": 16, "line_end": 17, "column_start": 1, "column_end": 6, "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.best-practice.pass-body-fn", "path": "/tmp/tmppq52ww6s/f45386f5f6ed2669.py", "start": {"line": 16, "col": 1, "offset": 237}, "end": {"line": 17, "col": 6, "offset": 260}, "extra": {"message": "`pass` is the body of function set_volume. Consider removing this or raise NotImplementedError() if this is a TODO", "metadata": {"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.security.audit.dangerous-system-call-audit_f45386f5f6ed2669_1cf29d3e", "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": 32, "line_end": 32, "column_start": 4, "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://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/f45386f5f6ed2669.py", "start": {"line": 32, "col": 4, "offset": 489}, "end": {"line": 32, "col": 47, "offset": 532}, "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"}}}] | 3 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
32
] | [
32
] | [
4
] | [
47
] | [
"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."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | __main__.py | /__main__.py | scizzorz/leap-volume | MIT | |
2024-11-18T20:49:21.269816+00:00 | 1,610,475,046,000 | dda32d54f8ced9af3a84d0469d9b1c7e46fe62b2 | 3 | {
"blob_id": "dda32d54f8ced9af3a84d0469d9b1c7e46fe62b2",
"branch_name": "refs/heads/main",
"committer_date": 1610475046000,
"content_id": "d9f06885c3894a6756e8e1cbd835328ede7da76e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "3a064e9e0673f0c72ca6e9b70381e26405a13d47",
"extension": "py",
"filename": "1.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 329071607,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3098,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/personalAssistant/1.py",
"provenance": "stack-edu-0054.json.gz:581796",
"repo_name": "SouSageYa/A_Droid_With_Python_On_Raspberry_Pi",
"revision_date": 1610475046000,
"revision_id": "ae314289c2367573fc5fd8477c01921cbea4252a",
"snapshot_id": "b65f0da682631b06ae30ebdbdb6acf394cc45239",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SouSageYa/A_Droid_With_Python_On_Raspberry_Pi/ae314289c2367573fc5fd8477c01921cbea4252a/personalAssistant/1.py",
"visit_date": "2023-02-17T20:41:39.150217"
} | 2.578125 | stackv2 | import speech_recognition as sr
import pyttsx3
import os
import pickle
import time
filename = 'Personalinfo'
outfile = open(filename, 'wb')
os.system('cls')
listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
def talk(text):
engine.say(text)
engine.runAndWait()
def take_komut():
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source)
komut = listener.recognize_google(voice)
komut = komut.lower()
finally:
pass
return komut
komut = take_komut()
time.sleep(10)
if 'alexa setup' in komut:
talk(
"Hello,dear sir. Welcome to TRON Setup interface. I will ask you some questions to optimize myself. "
"Please answer the questions step by step.")
talk("Your name and surname")
komut = take_komut()
print(komut)
if 'my name is' in komut or "i am" in komut or "this is " in komut:
person = komut.replace('Name and surname', '')
pickle.dump(person, outfile)
talk("Next up can I have the date of your birth. Firstly year")
else:
talk("Please give me a valid answer")
talk("Shutting down please retry")
exit()
komut = take_komut()
print(komut)
if 'birth year' in komut or 'year' in komut or 'it is' in komut:
birth_year = komut.replace('Birth year', '')
pickle.dump(birth_year, outfile)
talk("Can I have the month please.")
else:
talk("Please give me a valid answer")
talk("Shutting down please retry")
exit()
komut = take_komut()
print(komut)
if 'birth month' in komut or 'month' in komut or 'it is' in komut:
birth_month = komut.replace('Birth month', '')
pickle.dump(birth_month, outfile)
talk("And finally your birthday")
else:
talk("Please give me a valid answer")
talk("Shutting down please retry")
exit()
komut = take_komut()
print(komut)
if 'birth day' in komut or 'day' in komut or 'it is' in komut:
birth_day = komut.replace('Birth day', '')
pickle.dump(birth_day, outfile)
talk("Next up mail information. Your Mail adress")
else:
talk("Please give me a valid answer")
talk("Shutting down please retry")
exit()
komut = take_komut()
print(komut)
if 'gmail.com' in komut or "outlook.com" in komut or "hotmail.com" in komut or "yahoo.com" in komut or "att.com" in komut or "comcast.com" in komut or "verizon.com" in komut:
mail_adress = komut.replace('Mail adress', '')
pickle.dump(mail_adress, outfile)
talk("for multiple adresses please enter them while sending an e-mail")
talk("Next up your password. Use password keyword")
outfile.close()
else:
talk("Please give me a valid answer")
talk("Shutting down please retry")
exit()
os.system('2.py')
| 90 | 32.42 | 178 | 13 | 771 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_6a0e117956a11b20_15a074fb", "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": 31, "line_end": 31, "column_start": 1, "column_end": 15, "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/6a0e117956a11b20.py", "start": {"line": 31, "col": 1, "offset": 649}, "end": {"line": 31, "col": 15, "offset": 663}, "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.deserialization.avoid-pickle_6a0e117956a11b20_b6f24113", "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": 41, "line_end": 41, "column_start": 9, "column_end": 37, "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/6a0e117956a11b20.py", "start": {"line": 41, "col": 9, "offset": 1075}, "end": {"line": 41, "col": 37, "offset": 1103}, "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_6a0e117956a11b20_571ebc41", "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": 51, "line_end": 51, "column_start": 9, "column_end": 41, "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/6a0e117956a11b20.py", "start": {"line": 51, "col": 9, "offset": 1462}, "end": {"line": 51, "col": 41, "offset": 1494}, "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_6a0e117956a11b20_be2ec44c", "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": 61, "line_end": 61, "column_start": 9, "column_end": 42, "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/6a0e117956a11b20.py", "start": {"line": 61, "col": 9, "offset": 1830}, "end": {"line": 61, "col": 42, "offset": 1863}, "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_6a0e117956a11b20_95c7b5eb", "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": 71, "line_end": 71, "column_start": 9, "column_end": 40, "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/6a0e117956a11b20.py", "start": {"line": 71, "col": 9, "offset": 2188}, "end": {"line": 71, "col": 40, "offset": 2219}, "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_6a0e117956a11b20_6cd505c3", "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": 9, "column_end": 42, "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/6a0e117956a11b20.py", "start": {"line": 81, "col": 9, "offset": 2677}, "end": {"line": 81, "col": 42, "offset": 2710}, "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"
] | [
"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"
] | [
"security",
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
41,
51,
61,
71,
81
] | [
41,
51,
61,
71,
81
] | [
9,
9,
9,
9,
9
] | [
37,
41,
42,
40,
42
] | [
"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
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | 1.py | /personalAssistant/1.py | SouSageYa/A_Droid_With_Python_On_Raspberry_Pi | Apache-2.0 | |
2024-11-18T20:49:23.370338+00:00 | 1,253,984,206,000 | 3d53b383d7cb4d6134b9b7be70238d509c160a24 | 2 | {
"blob_id": "3d53b383d7cb4d6134b9b7be70238d509c160a24",
"branch_name": "refs/heads/master",
"committer_date": 1253984206000,
"content_id": "8fc94448a0ea6500987abadbb7646332f0751261",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0cf45e468422eb0907a8ae3958fb52fa9ef7ebeb",
"extension": "py",
"filename": "intid.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 42944685,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2342,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/twistedae/intid.py",
"provenance": "stack-edu-0054.json.gz:581819",
"repo_name": "TheProjecter/twistedae",
"revision_date": 1253984206000,
"revision_id": "96a22c936a970809d753ac428d1d2bcf2c6fdf55",
"snapshot_id": "2bd8d794153974f18213c98e6fc5606fb8ed0039",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/TheProjecter/twistedae/96a22c936a970809d753ac428d1d2bcf2c6fdf55/src/twistedae/intid.py",
"visit_date": "2021-01-10T19:41:15.810119"
} | 2.453125 | stackv2 | # -*- coding: utf-8 -*-
#
# Copyright 2009 Tobias Rodäbel
#
# 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.
"""Simple intid server implementation."""
import logging
import os
import shelve
import socket
import threading
logging.basicConfig(
format='%(levelname)-8s %(asctime)s %(filename)s:%(lineno)s] %(message)s',
level=logging.INFO)
lock = threading.Lock()
class Worker(threading.Thread):
"""The worker thread."""
def __init__(self, sock, db, num):
super(Worker, self).__init__()
self.socket = sock
self.db = db
self.num = num
def run(self):
while 1:
data = self.socket.recv(3)
if data == 'int':
lock.acquire()
self.db['int'] += 1
self.socket.send(str(self.db['int']))
self.db.sync()
lock.release()
elif data == 'con':
self.socket.send('ack')
else:
self.socket.close()
logging.info("client %i disconnected" % self.num)
break
def main():
"""The main function."""
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("127.0.0.1", 9009))
server_socket.listen(10)
db = shelve.open(
os.path.join(os.environ['TMPDIR'], 'intid'), writeback=True)
if not 'int' in db:
db['int'] = 0
logging.info("server starting")
client_num = 0
try:
while 1:
socketfd, address = server_socket.accept()
client_num += 1
logging.info("client %i %s connected" % (client_num, address))
t = Worker(socketfd, db, client_num)
t.start()
except KeyboardInterrupt:
db.close()
server_socket.close()
logging.info("server stopping")
| 84 | 26.87 | 78 | 17 | 537 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-shelve_0085136bc74d677a_fe852c7b", "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": 64, "line_end": 65, "column_start": 10, "column_end": 69, "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/0085136bc74d677a.py", "start": {"line": 64, "col": 10, "offset": 1781}, "end": {"line": 65, "col": 69, "offset": 1862}, "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"}}}] | 1 | true | [
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-shelve"
] | [
"security"
] | [
"MEDIUM"
] | [
"MEDIUM"
] | [
64
] | [
65
] | [
10
] | [
69
] | [
"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"
] | intid.py | /src/twistedae/intid.py | TheProjecter/twistedae | Apache-2.0 | |
2024-11-18T20:49:24.884702+00:00 | 1,692,295,864,000 | ac4879e01d059c0b9c86927aca365429ac915dcc | 2 | {
"blob_id": "ac4879e01d059c0b9c86927aca365429ac915dcc",
"branch_name": "refs/heads/main",
"committer_date": 1692295864000,
"content_id": "4ee365ec6d4fe078b50dc1d9d039f9d71a9a37a6",
"detected_licenses": [
"MIT"
],
"directory_id": "899090818b68b045201eab9ef24ec882528a7fb1",
"extension": "py",
"filename": "command.py",
"fork_events_count": 8,
"gha_created_at": 1582055390000,
"gha_event_created_at": 1693523504000,
"gha_language": "Python",
"gha_license_id": "NOASSERTION",
"github_id": 241453043,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1862,
"license": "MIT",
"license_type": "permissive",
"path": "/qgreenland/util/command.py",
"provenance": "stack-edu-0054.json.gz:581837",
"repo_name": "nsidc/qgreenland",
"revision_date": 1692295864000,
"revision_id": "7d4f2047bc0c121c20d0c746a699ceab69d5ee5c",
"snapshot_id": "ad9f80aa29903abf724e09e097a030fb647337ad",
"src_encoding": "UTF-8",
"star_events_count": 31,
"url": "https://raw.githubusercontent.com/nsidc/qgreenland/7d4f2047bc0c121c20d0c746a699ceab69d5ee5c/qgreenland/util/command.py",
"visit_date": "2023-08-17T19:58:11.989608"
} | 2.421875 | stackv2 | import logging
import subprocess
from collections.abc import Sequence
import qgreenland.exceptions as exc
from qgreenland.constants.project import ENV_MANAGER
from qgreenland.util.runtime_vars import EvalStr
logger = logging.getLogger("luigi-interface")
def interpolate_args(
args: Sequence[EvalStr],
**kwargs,
) -> list[str]:
"""Replace slugs in `args` with keys and values in `kwargs`."""
return [arg.eval(**kwargs) for arg in args]
def run_qgr_command(args: list[str]) -> None:
"""Run a command in the `qgreenland-cmd` environment."""
conda_env_name = "qgreenland-cmd"
# With conda or mamba, `. activate myenv` works as expected, but with micromamba, we
# need something a little different.
if ENV_MANAGER == "micromamba":
cmd = [
"eval",
'"$(micromamba shell hook -s posix)"',
"&&",
"micromamba",
"activate",
conda_env_name,
"&&",
*args,
]
else:
cmd = [".", "activate", conda_env_name, "&&", *args]
run_cmd(cmd)
return
def run_cmd(args: list[str]) -> subprocess.CompletedProcess:
"""Run a command and log it."""
# Hack. The activation of a conda environment does not work without `shell=True`.
cmd_str = " ".join(str(arg) for arg in args)
logger.info("Running command:")
logger.info(cmd_str)
result = subprocess.run(
cmd_str,
shell=True,
executable="/bin/bash",
capture_output=True,
)
if result.returncode != 0:
stdout = str(result.stdout, encoding="utf8")
stderr = str(result.stderr, encoding="utf8")
output = f"===STDOUT===\n{stdout}\n\n===STDERRR===\n{stderr}"
raise exc.QgrSubprocessError(
f"Subprocess failed with output:\n\n{output}",
)
return result
| 66 | 27.21 | 88 | 12 | 454 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_8b2b800b91f928fa_204855db", "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": 51, "line_end": 56, "column_start": 14, "column_end": 6, "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/8b2b800b91f928fa.py", "start": {"line": 51, "col": 14, "offset": 1408}, "end": {"line": 56, "col": 6, "offset": 1527}, "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.subprocess-list-passed-as-string_8b2b800b91f928fa_5e6ec04e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-list-passed-as-string", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected `\" \".join(...)` being passed to `subprocess.run`. This can lead to argument splitting issues and potential security vulnerabilities. Instead, pass the list directly to `subprocess.run` to preserve argument separation.", "remediation": "", "location": {"file_path": "unknown", "line_start": 52, "line_end": 52, "column_start": 9, "column_end": 16, "code_snippet": "requires login"}, "cwe_id": "C", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://docs.python.org/3/library/subprocess.html#frequently-used-arguments", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-list-passed-as-string", "path": "/tmp/tmppq52ww6s/8b2b800b91f928fa.py", "start": {"line": 52, "col": 9, "offset": 1432}, "end": {"line": 52, "col": 16, "offset": 1439}, "extra": {"message": "Detected `\" \".join(...)` being passed to `subprocess.run`. This can lead to argument splitting issues and potential security vulnerabilities. Instead, pass the list directly to `subprocess.run` to preserve argument separation.", "metadata": {"category": "security", "cwe": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "references": ["https://docs.python.org/3/library/subprocess.html#frequently-used-arguments"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "technology": ["python"], "confidence": "LOW", "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "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_8b2b800b91f928fa_ac62671d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'run' 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": 53, "line_end": 53, "column_start": 15, "column_end": 19, "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/8b2b800b91f928fa.py", "start": {"line": 53, "col": 15, "offset": 1455}, "end": {"line": 53, "col": 19, "offset": 1459}, "extra": {"message": "Found 'subprocess' function 'run' 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"}}}] | 3 | 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"
] | [
51,
53
] | [
56,
53
] | [
14,
15
] | [
6,
19
] | [
"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()'.",
"Found 'subprocess' function... | [
7.5,
7.5
] | [
"LOW",
"HIGH"
] | [
"HIGH",
"LOW"
] | command.py | /qgreenland/util/command.py | nsidc/qgreenland | MIT | |
2024-11-18T20:49:24.978309+00:00 | 1,675,066,623,000 | b7b23162d0013fd75c19e41d041b1a0864b3d8c8 | 3 | {
"blob_id": "b7b23162d0013fd75c19e41d041b1a0864b3d8c8",
"branch_name": "refs/heads/master",
"committer_date": 1675066623000,
"content_id": "1da0c89372285045fa7d56b078d4c4284a468da0",
"detected_licenses": [
"MIT"
],
"directory_id": "3958e5746685a6473edbb43c6d6264f84ebf4e80",
"extension": "py",
"filename": "amazon_title_similarity.py",
"fork_events_count": 15,
"gha_created_at": 1521090927000,
"gha_event_created_at": 1684872620000,
"gha_language": "Java",
"gha_license_id": "MIT",
"github_id": 125315634,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2978,
"license": "MIT",
"license_type": "permissive",
"path": "/ch04-recommending-products-and-services/amazon_title_similarity.py",
"provenance": "stack-edu-0054.json.gz:581839",
"repo_name": "PacktPublishing/AIBlueprints",
"revision_date": 1675066623000,
"revision_id": "bca812a61ad96ba88d776f09ef3735fa096742cf",
"snapshot_id": "f210d413a6118ab97821716a64b273e802ec2935",
"src_encoding": "UTF-8",
"star_events_count": 34,
"url": "https://raw.githubusercontent.com/PacktPublishing/AIBlueprints/bca812a61ad96ba88d776f09ef3735fa096742cf/ch04-recommending-products-and-services/amazon_title_similarity.py",
"visit_date": "2023-05-25T16:03:04.466442"
} | 2.625 | stackv2 | import json
import re
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.decomposition import TruncatedSVD
from sklearn.pipeline import make_pipeline
import faiss
import os.path
import pickle
import gzip
use_gpu = False
if os.path.exists('product_asin.pkl') and os.path.exists('product_text.pkl'):
print("Loading pickled product asin's and text.")
with open('product_asin.pkl', 'rb') as f:
product_asin = pickle.load(f)
with open('product_text.pkl', 'rb') as f:
product_text = pickle.load(f)
print("Loaded %d products" % len(product_asin))
else:
print("Processing metadata-small.json.gz...")
product_asin = []
product_text = []
with gzip.open('metadata-small.json.gz', encoding='utf-8', mode='rt') as f:
for line in f:
try:
# fix improper quoting
line = re.sub(r'(\W)\'', r'\1"', line)
line = re.sub(r'\'(\W)', r'"\1', line)
line = re.sub(r'(\w)"(\w)', r"\1'\2", line)
p = json.loads(line)
s = p['title']
if 'description' in p:
s += ' ' + p['description']
product_text.append(s)
product_asin.append(p['asin'])
except:
pass
print("Count: %d" % len(product_asin))
with open('product_asin.pkl', 'wb') as f:
pickle.dump(product_asin, f)
with open('product_text.pkl', 'wb') as f:
pickle.dump(product_text, f)
product_text = product_text[:3000000]
product_asin = product_asin[:3000000]
if os.path.exists('amazon_title_bow.npy'):
print("Loading BOW array.")
d = np.load('amazon_title_bow.npy')
else:
print("Running pipeline...")
pipeline = make_pipeline(CountVectorizer(stop_words='english', max_features=10000),
TfidfTransformer(),
TruncatedSVD(n_components=128))
d = pipeline.fit_transform(product_text).astype('float32')
print("Saving BOW array.")
np.save('amazon_title_bow.npy', d)
print(d.shape)
ncols = np.shape(d)[1]
if use_gpu:
gpu_resources = faiss.StandardGpuResources()
index = faiss.GpuIndexIVFFlat(gpu_resources, ncols, 400, faiss.METRIC_INNER_PRODUCT)
else:
quantizer = faiss.IndexFlat(ncols)
index = faiss.IndexIVFFlat(quantizer, ncols, 400, faiss.METRIC_INNER_PRODUCT)
print(index.is_trained)
index.train(d)
print(index.is_trained)
index.add(d)
print(index.ntotal)
rec_asins = ["0001048775"]
for asin in rec_asins:
idx = -1
for i in range(len(product_asin)):
if product_asin[i] == asin:
idx = i
break
if idx != -1:
print('--')
print((product_asin[idx], product_text[idx]))
distances, indexes = index.search(d[idx:idx+1], 5)
print(distances, indexes)
for i in indexes[0]:
print((product_asin[i], product_text[i]))
| 92 | 31.37 | 88 | 18 | 778 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e5f3069d6bb12acb_0f1b6261", "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": 24, "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/e5f3069d6bb12acb.py", "start": {"line": 17, "col": 24, "offset": 482}, "end": {"line": 17, "col": 38, "offset": 496}, "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_e5f3069d6bb12acb_fac63751", "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": 19, "line_end": 19, "column_start": 24, "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/e5f3069d6bb12acb.py", "start": {"line": 19, "col": 24, "offset": 566}, "end": {"line": 19, "col": 38, "offset": 580}, "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_e5f3069d6bb12acb_daa39a50", "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": 42, "line_end": 42, "column_start": 9, "column_end": 37, "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/e5f3069d6bb12acb.py", "start": {"line": 42, "col": 9, "offset": 1441}, "end": {"line": 42, "col": 37, "offset": 1469}, "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_e5f3069d6bb12acb_c7ce4777", "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": 44, "line_end": 44, "column_start": 9, "column_end": 37, "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/e5f3069d6bb12acb.py", "start": {"line": 44, "col": 9, "offset": 1524}, "end": {"line": 44, "col": 37, "offset": 1552}, "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_e5f3069d6bb12acb_a4536952", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_trained\" a function or an attribute? If it is a function, you may have meant index.is_trained() because index.is_trained is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 71, "line_end": 71, "column_start": 7, "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/tmppq52ww6s/e5f3069d6bb12acb.py", "start": {"line": 71, "col": 7, "offset": 2441}, "end": {"line": 71, "col": 23, "offset": 2457}, "extra": {"message": "Is \"is_trained\" a function or an attribute? If it is a function, you may have meant index.is_trained() because index.is_trained 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_e5f3069d6bb12acb_17a6cf4c", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_trained\" a function or an attribute? If it is a function, you may have meant index.is_trained() because index.is_trained is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 73, "line_end": 73, "column_start": 7, "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/tmppq52ww6s/e5f3069d6bb12acb.py", "start": {"line": 73, "col": 7, "offset": 2480}, "end": {"line": 73, "col": 23, "offset": 2496}, "extra": {"message": "Is \"is_trained\" a function or an attribute? If it is a function, you may have meant index.is_trained() because index.is_trained is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "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"
] | [
"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"
] | [
17,
19,
42,
44
] | [
17,
19,
42,
44
] | [
24,
24,
9,
9
] | [
38,
38,
37,
37
] | [
"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"
] | amazon_title_similarity.py | /ch04-recommending-products-and-services/amazon_title_similarity.py | PacktPublishing/AIBlueprints | MIT | |
2024-11-18T20:49:26.851437+00:00 | 1,569,684,702,000 | 8a487a30f3664f41da27a5e35b1d99b7b3f56bb4 | 3 | {
"blob_id": "8a487a30f3664f41da27a5e35b1d99b7b3f56bb4",
"branch_name": "refs/heads/master",
"committer_date": 1569684702000,
"content_id": "67bc901a4c7881af460dc74e992f81d3934b403f",
"detected_licenses": [
"MIT"
],
"directory_id": "b731ba53534bd98248174523101250a2302b162c",
"extension": "py",
"filename": "pipeline.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 209240549,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 13969,
"license": "MIT",
"license_type": "permissive",
"path": "/pipeline.py",
"provenance": "stack-edu-0054.json.gz:581862",
"repo_name": "nathangeology/FORCE_Geolocation_Docs",
"revision_date": 1569684702000,
"revision_id": "1f7ef447bacdbdd424dce5ba8f37e738462ba372",
"snapshot_id": "21b8ed0730406ecd36576312d02a90ef3bce8a1b",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/nathangeology/FORCE_Geolocation_Docs/1f7ef447bacdbdd424dce5ba8f37e738462ba372/pipeline.py",
"visit_date": "2020-07-27T23:10:24.057206"
} | 2.671875 | stackv2 | # Import the key used libraries
import os
import sys
import pandas as pd
import numpy as np
import PyPDF2
import re
from data_load_functions import *
from joblib import Parallel, delayed
import pickle
try:
import geopandas as gpd
except:
print('geopandas not found, will enter exception blocks throughout')
pass
def create_npd_shapefile_dict_preprocess(main_path='./sample_data/'):
"""
Function designed to grab a variety of shape files from the NPD database. Assumes hard coded files are present
Arguments:
main_path: string, absolute file path to the shapefiles
Returns: dictionary of files
@ author: Nathan Jones
"""
# Create a dictionary of file paths
try:
files = {'blocks': os.path.join(main_path, 'shapefiles', 'loc_npd_blocks.shp'),
'discoveries': os.path.join(main_path, 'shapefiles', 'loc_npd_discoveries.shp'),
'well_bores': os.path.join(main_path, 'shapefiles', 'loc_npd_ea_wells.shp'),
'wells': os.path.join(main_path, 'shapefiles', 'loc_npd_ea_wells.shp'),
'facilities': os.path.join(main_path, 'shapefiles', 'loc_npd_facilities.shp'),
'fields': os.path.join(main_path, 'shapefiles', 'loc_npd_fields.shp'),
'structures': os.path.join(main_path, 'shapefiles', 'loc_npd_struct_elements.shp'),
'structures_en': os.path.join(main_path, 'shapefiles', 'loc_npd_struct_elements.shp'),
'basins': os.path.join(main_path, 'shapefiles', 'loc_npd_struct_elements.shp'),
'sub_areas': os.path.join(main_path, 'shapefiles', 'loc_npd_subareas.shp')}
except:
print('Check list of files for exact files and name matches')
return None
# Initialize empty output dictionary and iterate through file dictionary and read over the shapefiles
output = {}
for key, value in files.items():
# Read shape file - Uses geopandas
output[key] = gpd.read_file(value)
# Grab well header information from a CSV file
output['well_header'] = pd.read_csv(os.path.join(main_path, 'with-coordinates.csv'), delimiter=';')
return output
def get_key_words_preprocess(main_path):
"""
Function to create a list of possible key words from a shapefile compendium for a certain region
Arguments:
main_path: string, absolute file path to the shapefiles
Returns: List of alphanumeric + special character strings, and type
@ author: Nathan Jones
"""
# Create dictionary of key columns to go through to find key words from shape files
key_cols = {
'blocks': 'LABEL',
'discoveries': 'DISCNAME',
'well_bores': 'wlbWellbor',
'wells': 'wlbWell',
'facilities': 'FACNAME',
'fields': 'FIELDNAME',
'structures': 'steNameNO',
'structures_en': 'steNameEN',
'basins': 'steTopogra',
'sub_areas': 'NAME',
}
# Initialize empty lists for output and key word type
output = []
type = []
# This function is presently specific to the Norway Petroleum Database shapefile, if it doesn't work, try a pre-save pkl file
# should return a dictionary
try:
data_dict = create_npd_shapefile_dict_preprocess()
except Exception as ex:
object = []
with open(os.path.join(main_path, 'npd_lookup_dfs_no_geopandas.pkl'), 'rb') as openfile:
while True:
try:
object.append(pkl.load(openfile))
except EOFError:
break
data_dict = object[0]
# Iterate through the returned data dictionary from the shapefiles
for key, value in data_dict.items():
if 'well_header' not in key:
df = pd.DataFrame(value)
temp = list(df[key_cols[key]])
temp_type = [key] * len(temp)
type += temp_type
output += temp
return output, type
### Clean up text file
def clean_text(txt):
"""
Function to clean out any problematic or illegal characters
Arguments:
txt: List of character strings
Returns: List of character strings
@ author: Christopher Olsen, ConocoPhillips
"""
txt = [x.lower() for x in txt] # For ease of use, convert all characters to lowercase
txt = [x.replace('/', '_') for x in txt] # Convert forward slash to underscore
txt = [x.replace('\u00C5', 'aa') for x in txt] # Convert Norwegian (uppercase version, just in case) to aa
txt = [x.replace('\u00E5', 'aa') for x in txt] # Convert Norwegian (lowercase version) to aa
txt = [x.replace('\u00C6', 'ae') for x in txt] # Convert Norwegian (uppercase version, just in case) to ae
txt = [x.replace('\u00E6', 'ae') for x in txt] # Convert Norwegian (lowercase version) to ae
txt = [x.replace('\u00C8', 'oe') for x in txt] # Convert Norwegian (uppercase version, just in case) to oe
txt = [x.replace('\u00E8', 'oe') for x in txt] # Convert Norwegian (lowercase version) to oe
txt = [x.replace('\u00E3', 'oe') for x in txt] # Convert Norwegian a tilde to oe
txt = [x.replace('¸', '') for x in txt] # Replace special character with nothing
txt = [x.replace('\u25A1', '') for x in txt] # Replace 'Yen' symbol with nothing
txt = [x.replace('\25', '') for x in txt] # Replace unfilled square with nothing
# txt = [x.replace(' ', '_') for x in txt] # Not used: Convert whitespace to underscores
return txt
def PreprocessKeyWords(key_words, clean=True, exception_list=None, min_chars=3):
"""
Function used to further process a list of key words that have been generated via a shapefile compendium
Arguments:
key_words: List of strings of key words prepared by other functions in this file
clean: boolean, whether or not to run some cleaning functions to remove illegal or problematic characters
exception_list: List of strings to ensure are included after trimming down the list
min_chars: integer, minimum length of a keyword string to minimize high frequency linguistic combinations
Returns: list of strings, key words of a certain form and format
@ author: Christopher Olsen, ConocoPhillips
"""
# Verify some initial conditions first
if isinstance(key_words, (list,)):
pass
else:
print('Key words must be a proper python list')
return None
# Copy list to new variable for simplicity
kw = key_words
# If clearn option is selected (True by default)
if clean:
kw = clean_text(kw)
# define regex patterns
pattern1 = re.compile('\d') # search/match only digits
pattern2 = re.compile('^_') # search/match only a single underscore at beginning of word
pattern3 = re.compile('\W+') # search/match only non-alphanumeric characters
# define complex regex pattern based on Norway Well name convention
pattern_Norway_Well = re.compile(
'(\d\d\d\d|\d\d|\d)([\/, ]{1}|[_, ]{1})(\d\d|\d)([-, ]{0,1})(\d\d|\d){0,1}([-, ]{0,1})([a-zA-Z0-9.+_]{0,2})([-]{0,1})(\d\d|\d{0,1})')
# first prepare non-numeric based keywords
kw_nonum = [x.replace('_', '').replace('-', '').isdigit() for x in
kw] # remove digits after temporarily cutting _ and -
kw_alpha_inds = np.nonzero(np.array(kw_nonum, dtype=bool) == False)[0] # grab indices based on boolean array
kw_alpha = [kw[x] for x in kw_alpha_inds] # create subsetted list with leading digits cut
kw_alpha = [re.sub(pattern1, '', x) for x in kw_alpha] # concatenate characters between pattern1
kw_alpha = [x.replace('_', '').replace('-', '') for x in kw_alpha] # concatenate characters around _ and -
kw_alpha = [x.replace('(', '').replace(')', '') for x in kw_alpha] # remove leading and trailing parenthesis
kw_alpha = [re.sub(pattern2, ' ', x) for x in kw_alpha] # replace pattern2 with whitespace
# kwc_alpha = [x.replace(' ', '_') for x in kwc_alpha] # not used: replace whitespace with _
kw_alpha = [re.sub(pattern3, ' ', x) for x in kw_alpha] # replace pattern3 with whitespace
kw_alpha = [x.replace('__', '_') for x in kw_alpha] # replace double underscore with single underscore
kw_alpha = [x for x in kw_alpha if len(x) > min_chars] # return only strings greater than the minimum
if exception_list is not None: # if exception list is populated
kw_alpha.extend(exception_list) # add back in excepted key words
kw_alpha = sorted(set(kw_alpha)) # create sorted unique list letter based of key words
# Second prepare numeric based keywords (e.g. well names)
kw_well = [re.search(pattern_Norway_Well, x) for x in kw] # apply complex pattern to find wells
kw_num = [] # Initialize empty list
for i in kw_well: # Iterate over list of matched terms
if i: # Since none matches are empty [None], if not empty
kw_num.append(i.group(0)) # Append to the list the matched first group
# Combine whittled key words lists
kw_comb = kw_alpha + kw_num
return kw_comb
def ProcessTextFile(document, key_words):
"""
Function that takes in an absolute file path (e.g. C:\\User\\Documents\\TextFiles\\TextFile.pdf)
and a list of key words to search over
Returns: Dataframe of search results narrowed down to just the positive findings
@ author: Christopher Olsen, ConocoPhillips
"""
try:
# Verify some initial conditions first
if isinstance(key_words, (list,)):
pass
else:
print('Key words must be a proper python list')
return None
if isinstance(document, (list,)):
print('This function is for a single pdf document only')
return None
else:
pass
assert isinstance(document, (str,))
if not document[-4:].lower() == '.pdf':
print('This function is presently designed only to process OCR complete PDF documents')
return None
else:
pass
# Open the document as a PDF object, read each page, and shove into a list
with open(document, 'rb') as pdfFileObj:
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
txt = []
for page in range(pdfReader.numPages):
pageObj = pdfReader.getPage(page)
page_txt = pageObj.extractText()
txt.extend(page_txt)
# Join all characters together as one single character string
txt = ''.join(txt)
# Split apart each line into a list of lines based on the common \n newline character
txt = txt.splitlines()
# Run a text cleaning process on the text file that will roughly match the same process as for key words
txt = clean_text(txt)
# Create dataframe framework to build off of
df_txt = pd.DataFrame({'Document': [document] * len(txt), 'Lines': txt})
# Iterate over each line of text (may take a moment)
for word in key_words:
df_txt[word] = pd.Series([x.find(word) for x in txt])
# Convert numeric results to numeric flag, ignore positional location from result here
ndf = df_txt._get_numeric_data()
ndf[ndf < 0] = 0
ndf[ndf > 1] = 1
# Aggregate the results
results = [df_txt[col].sum() for col in df_txt.columns[2:]]
# Create new dataframe based on the document, key words, and sum of matches
df = pd.DataFrame(
{'Document': [document] * len(df_txt.columns[2:]), 'Key_Words': df_txt.columns[2:], 'Total_Matches': results})
# Reduce size of dataframe only to matches to key words
df = df[df['Total Matches'] > 0]
return df
except Exception as ex:
print(ex)
return pd.DataFrame()
if __name__ == '__main__':
# Define our main data path where the shape files may be loaded from
data_path ='/media/nathanieljones/New Volume/univ stavanger documents-20190918T063414Z-001/univ stavanger documents/'
document_folder = data_path
# document_folder = os.path.join(data_path, 'text_documents\\')
# singular document used for testing purposes
test_document = 'Rock physics models for Cenozoic siliciclastic sediments in the North Sea.pdf'
# Used only if geopandas doesn't work, pre-exported list of raw key words as a list
keywords_list = 'keywords.pkl'
# Try to use the primary coded functions, otherwise default back to pickle file
try:
kw, _ = get_key_words_preprocess('/')
except Exception as ex:
print(ex)
print('Possibly missing GeoPandas package')
with open(os.path.join(data_path, keywords_list), 'rb') as openfile:
kw = pkl.load(openfile)
# Created exception list of character strings we want to make sure are included in the search strings
exception_list = [' tor '] # Note, extra white space on either side given it's combination is frequently part of larger words
# Clean up key words creating letter based key words as well as supposed well names
kw = PreprocessKeyWords(kw, clean=True, exception_list = exception_list, min_chars = 3)
# Create list of text documents (PDFs)
documents = os.listdir(document_folder)
documents = [os.path.join(document_folder, x) for x in documents]
# Initialize empty list
df_list = []
# Iterate over the list of documents (may take a little while, would benefit from parallelization)
df_list = Parallel(n_jobs=1)(
delayed(ProcessTextFile)(doc, kw) for doc, kw in zip(documents, [kw] * len(documents)))
# for doc in documents:
# df_list.append(ProcessTextFile(doc, kw))
# Stack together the output dataframes from the search string results
ResultDF = pd.concat(df_list)
with open('thesis_docs.pkl', 'wb') as f:
pickle.dump(ResultDF, f) | 323 | 42.25 | 141 | 18 | 3,442 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_5ad08be47d351731_4adc234f", "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": 323, "line_end": 323, "column_start": 9, "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/5ad08be47d351731.py", "start": {"line": 323, "col": 9, "offset": 13945}, "end": {"line": 323, "col": 33, "offset": 13969}, "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"
] | [
323
] | [
323
] | [
9
] | [
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"
] | pipeline.py | /pipeline.py | nathangeology/FORCE_Geolocation_Docs | MIT | |
2024-11-18T20:49:29.583716+00:00 | 1,649,083,474,000 | fa6522ce3128a04cf06a78d97fb3f9d15431e346 | 3 | {
"blob_id": "fa6522ce3128a04cf06a78d97fb3f9d15431e346",
"branch_name": "refs/heads/master",
"committer_date": 1649083474000,
"content_id": "88c85c29e6f77c186b1c7272440df01bfb159b8f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "b6332e57c69582a20416bda42eeb6108310ef763",
"extension": "py",
"filename": "traversal_model.py",
"fork_events_count": 1,
"gha_created_at": 1579895223000,
"gha_event_created_at": 1648591077000,
"gha_language": "Python",
"gha_license_id": "NOASSERTION",
"github_id": 236072096,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2252,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/models/traversal_model.py",
"provenance": "stack-edu-0054.json.gz:581898",
"repo_name": "ejyager00/porterpassing",
"revision_date": 1649083474000,
"revision_id": "2c604b896f509099744171656cf5383386f47e8e",
"snapshot_id": "6c6ba8317ec9f1a4d84e21d45a91a58b8264a995",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ejyager00/porterpassing/2c604b896f509099744171656cf5383386f47e8e/src/models/traversal_model.py",
"visit_date": "2022-04-29T13:24:33.577728"
} | 2.96875 | stackv2 | import pickle
from numpy import NaN
from numpy import isnan
import sys
DISTANCE_AHEAD = 300
HEIGHT_DIFF = 3.5
def distance(x1,y1,x2,y2):
return ((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))**.5
def check_arguments(args):
if len(args)<2:
raise RuntimeError("You must include two pickle files in the arguments.")
def main(args):
heights=pickle.load(open(args[0], 'rb')) #'data/interim/centerpoints.pickle'
roads=[]
for road in heights:
r=[]
for i, point in enumerate(road):
if isnan(point[2]):
r.append([False,False])
continue
p = []
dif=1
dist=0
while True:
if i+dif==len(road):
p.append(False)
break
else:
dist+= distance(road[i+dif][0],road[i+dif][1],road[i+dif-1][0],road[i+dif-1][1])
if isnan(road[i+dif][2]):
p.append(False)
break
elif road[i+dif][2]-point[2]>=HEIGHT_DIFF:
p.append(False)
break
elif dist>DISTANCE_AHEAD:
p.append(True)
break
dif+=1
dif=-1
dist=0
while True:
if i+dif==-1:
p.append(False)
break
else:
dist+= distance(road[i+dif][0],road[i+dif][1],road[i+dif+1][0],road[i+dif+1][1])
if isnan(road[i+dif][2]):
p.append(False)
break
elif road[i+dif][2]-point[2]>=HEIGHT_DIFF:
p.append(False)
break
elif dist>DISTANCE_AHEAD:
p.append(True)
break
dif-=1
r.append(p)
roads.append(r)
with open(args[1], 'wb') as pickle_file: #'data/processed/zones.pickle'
pickle.dump(roads, pickle_file)
if __name__=='__main__':
#args: centerpoints_pickle zones_pickle
check_arguments(sys.argv[1:])
main(sys.argv[1:])
| 73 | 29.85 | 100 | 21 | 518 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e475e1c7a99e2ba3_732d8143", "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": 18, "line_end": 18, "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/e475e1c7a99e2ba3.py", "start": {"line": 18, "col": 13, "offset": 348}, "end": {"line": 18, "col": 45, "offset": 380}, "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_e475e1c7a99e2ba3_72cc69ff", "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": 68, "line_end": 68, "column_start": 9, "column_end": 40, "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/e475e1c7a99e2ba3.py", "start": {"line": 68, "col": 9, "offset": 2093}, "end": {"line": 68, "col": 40, "offset": 2124}, "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"
] | [
18,
68
] | [
18,
68
] | [
13,
9
] | [
45,
40
] | [
"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"
] | traversal_model.py | /src/models/traversal_model.py | ejyager00/porterpassing | Apache-2.0 | |
2024-11-18T20:49:30.081134+00:00 | 1,433,554,466,000 | 2f0cb75a704af1ae6969e3c9c55b2797d8ed46a2 | 2 | {
"blob_id": "2f0cb75a704af1ae6969e3c9c55b2797d8ed46a2",
"branch_name": "refs/heads/master",
"committer_date": 1433554466000,
"content_id": "572ceefc1091fb7a60fb3b30cb187541fbf7c705",
"detected_licenses": [
"MIT"
],
"directory_id": "e022be52fde651dc14346bd02210c3778f32f16a",
"extension": "py",
"filename": "syncSO.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 32976509,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6552,
"license": "MIT",
"license_type": "permissive",
"path": "/pycrm/syncSO.py",
"provenance": "stack-edu-0054.json.gz:581905",
"repo_name": "wcl/pycrm",
"revision_date": 1433554466000,
"revision_id": "216b61f2a553cb785d746d127964e44686cf7d05",
"snapshot_id": "196092743b89d682aca14a456768e7a17f69e863",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/wcl/pycrm/216b61f2a553cb785d746d127964e44686cf7d05/pycrm/syncSO.py",
"visit_date": "2016-09-05T21:27:32.088543"
} | 2.453125 | stackv2 | # -*- coding: utf-8 -*-
import urllib2
import urllib
import hashlib
import collections
import ssl
import httplib
import json
import logging
import time
import datetime
import binascii
import os
import csv
import sys
reload(sys)
sys.setdefaultencoding('utf8')
logging.basicConfig(filename="..//..//..//logs//syncOrder.log",
level=logging.DEBUG, format='%(asctime)s %(message)s')
def to_tag(k, v):
return '<{key}>{value}</{key}>'.format(key=k, value=get_content(k, v))
def get_content(k, v):
if isinstance(v, basestring):
# it's a string, so just return the value
return unicode(v).encode('utf-8')
elif isinstance(v, dict):
# it's a dict, so create a new tag for each element
# and join them with newlines
return '\n%s\n' % '\n'.join(to_tag(*e) for e in v.items())
elif isinstance(v, list):
# it's a list, so create a new key for each element
# by using the enumerate method and create new tags
return '\n%s\n' % '\n'.join(to_tag('{key}-{value}'.format(key=k, value=i + 1), e) for i, e in enumerate(v))
CERT_FILE = 'apiclient_cert.pem' # Renamed from PEM_FILE to avoid confusion
KEY_FILE = 'apiclient_key.pem' # This is your client cert!
class HTTPSClientAuthHandler(urllib2.HTTPSHandler):
def __init__(self, key, cert):
urllib2.HTTPSHandler.__init__(self)
self.key = key
self.cert = cert
def https_open(self, req):
# Rather than pass in a reference to a connection class, we pass in
# a reference to a function which, for all intents and purposes,
# will behave as a constructor
return self.do_open(self.getConnection, req)
def getConnection(self, host, timeout=300):
return httplib.HTTPSConnection(host, key_file=self.key, cert_file=self.cert)
cert_handler = HTTPSClientAuthHandler(KEY_FILE, CERT_FILE)
opener = urllib2.build_opener(cert_handler)
urllib2.install_opener(opener)
def syncSO():
#前提:.csv为一天内的数据
currentTime=datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
path="CsvData//{0}.csv".format(time.strftime('%Y%m%d',time.localtime(time.time())))
logging.debug(path)
isSuccess=True
#获取错误时的行号
errorLineNum=1 #默认错误行号,即从1开始
fileName="errorLineNumFile.txt"
if os.path.exists(fileName):
errorLineNumFile = open (fileName,'r')
errorLineNumStr=errorLineNumFile.read()
isInt=unicode(str(errorLineNumStr)).isdecimal()
if isInt:
errorLineNum=int(errorLineNumStr)
errorLineNumFile.close()
#准备进行数据同步(从错误行号开始,默认从头开始,错误号为1)
if os.path.exists(path):
with open(path) as cf:
reader = csv.reader(cf)
try:
for row in reader:
tmpErrorLineNum=reader.line_num
#忽略第一行标题
if reader.line_num <= errorLineNum:
continue
data=row
list1=['tradeTime','wxOrderNo','userWXID','tradeType','tradeStatus','bank','currencyType','totalPrice','redPrice'
,'productName','refundOrderNo','refundTotalPrice','refundredPrice','refundType','refundStatus']
tradeTime=data[0].replace('`','') #交易时间
wxOrderNo=data[5].replace('`','') #微信订单号
userWXID=data[7].replace('`','') #客户微信ID
tradeType=data[8].replace('`','') #交易类型
tradeStatus=data[9].replace('`','') #交易状态
bank=data[10].replace('`','') #付款银行
currencyType=data[11].replace('`','')#货币种类
totalPrice=data[12].replace('`','') #总金额
redPrice=data[13].replace('`','') #企业红包金额
productName=data[20].replace('`','').decode("gb2312")#商品名称
logging.debug("productName={0}".format(productName))
refundOrderNo=data[14].replace('`','') #微信退款单号
refundTotalPrice=data[16].replace('`','')#退款额度
refundredPrice=data[17].replace('`','')#企业红包退款金额
refundType=data[18].replace('`','')#退款类型
refundStatus=data[19].replace('`','')#退款状态
list2=[tradeTime,wxOrderNo,userWXID,tradeType,tradeStatus,bank,currencyType,totalPrice,redPrice
,productName,refundOrderNo,refundTotalPrice,refundredPrice,refundType,refundStatus]
sorderData=dict(zip(list1,list2))
logging.debug(sorderData)
crmSOrder_Insert(sorderData)
except:
isSuccess=False
errorLineNum=tmpErrorLineNum-1
logging.exception("errorLineNum={0}".format(str(errorLineNum)))
logging.exception(currentTime)
#失败则记录下此时的错误行号
if isSuccess==False:
if os.path.exists(fileName):
errorLineNumFile = open (fileName,'w')
errorLineNumFile.write(str(errorLineNum))
errorLineNumFile.close()
logging.debug("isSuccess={0}".format(str(isSuccess)))
#对本次同步到销售订单表的数据进行销售统计
if isSuccess==True:
syncSalesReport()
else:
logging.debug("file: {0} not find ".format(path))
#调用本地API创建销售订单及字表
def crmSOrder_Insert(sorderData):
url="http://127.0.0.1"
#url="http://192.168.1.109:8000"
logging.debug("order={0}".format(str(sorderData)))
data=str(sorderData).replace("u'","\"").replace("'","\"")
logging.debug("data={0}".format(data))
req = urllib2.Request("{0}/api/method/pycrm.neworderapi.newOrder".format(url),data=data,headers={'Content-Type': 'application/json','skip':'doraemon'})
u = urllib2.urlopen(req)
resp = u.read()
return resp
#销售业绩统计
def syncSalesReport():
url="http://127.0.0.1"
#url="http://192.168.1.109:8000"
req = urllib2.Request("{0}/api/method/pycrm.neworderapi.newSalesReportData".format(url),headers={'Content-Type': 'application/json','skip':'doraemon'})
u = urllib2.urlopen(req)
resp = u.read()
return resp
syncSO()
| 148 | 40.78 | 155 | 19 | 1,603 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.httpsconnection-detected_f780e994913de792_5ec59ca7", "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": 48, "line_end": 48, "column_start": 16, "column_end": 85, "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/f780e994913de792.py", "start": {"line": 48, "col": 16, "offset": 1753}, "end": {"line": 48, "col": 85, "offset": 1822}, "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.best-practice.unspecified-open-encoding_f780e994913de792_a9e42443", "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": 63, "line_end": 63, "column_start": 28, "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/f780e994913de792.py", "start": {"line": 63, "col": 28, "offset": 2414}, "end": {"line": 63, "col": 47, "offset": 2433}, "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_f780e994913de792_7924da01", "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": 24, "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/f780e994913de792.py", "start": {"line": 71, "col": 14, "offset": 2770}, "end": {"line": 71, "col": 24, "offset": 2780}, "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_f780e994913de792_4e0f71d1", "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": 111, "line_end": 111, "column_start": 40, "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/f780e994913de792.py", "start": {"line": 111, "col": 40, "offset": 5265}, "end": {"line": 111, "col": 59, "offset": 5284}, "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-295"
] | [
"rules.python.lang.security.audit.httpsconnection-detected"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
48
] | [
48
] | [
16
] | [
85
] | [
"A03:2017 - Sensitive Data Exposure"
] | [
"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.HTTPSConnecti... | [
5
] | [
"LOW"
] | [
"LOW"
] | syncSO.py | /pycrm/syncSO.py | wcl/pycrm | MIT | |
2024-11-18T20:49:35.048467+00:00 | 1,592,386,074,000 | 681cd764d72faba2cd0bd309f5dcc81da60995ae | 3 | {
"blob_id": "681cd764d72faba2cd0bd309f5dcc81da60995ae",
"branch_name": "refs/heads/master",
"committer_date": 1592386074000,
"content_id": "797f465cc7d552668591713bec1aa84f1338e849",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "5a35e571dbda8599692ce705a1430a66177d25b2",
"extension": "py",
"filename": "serializers.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": 1986,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/accounts/serializers.py",
"provenance": "stack-edu-0054.json.gz:581969",
"repo_name": "bellyfat/saasinit",
"revision_date": 1592386074000,
"revision_id": "2ee632a6c8f72d05d0504f457f8ab659e262348d",
"snapshot_id": "b42ecba89d93538a2c3fca1a318ab6e8dddb1239",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bellyfat/saasinit/2ee632a6c8f72d05d0504f457f8ab659e262348d/accounts/serializers.py",
"visit_date": "2022-10-21T19:08:14.008056"
} | 2.59375 | stackv2 | from django.contrib.auth import get_user_model
from rest_framework import serializers
from .models import Tenant
User = get_user_model()
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = (
'url',
'id',
'username',
'password',
)
# Make sure that the password field is never sent back to the client.
extra_kwargs = {
'password': {'write_only': True},
}
def create(self, validated_data):
return User.objects.create_user(**validated_data)
def update(self, instance, validated_data):
updated = super().update(instance, validated_data)
# We save again the user if the password was specified to make sure it's properly hashed.
if 'password' in validated_data:
updated.set_password(validated_data['password'])
updated.save()
return updated
class TenantSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Tenant
fields = (
'id',
'name',
'address',
)
class AccountSerializer(serializers.Serializer):
"""Serializer that has two nested Serializers: tenant and user"""
tenant = TenantSerializer()
user = UserSerializer()
def create(self, validated_data):
tenant_data = validated_data['tenant']
user_data = validated_data['user']
# Call our TenantManager method to create the Tenant and the User
tenant, user = Tenant.objects.create_account(
tenant_name=tenant_data.get('name'),
tenant_address=tenant_data.get('address'),
username=user_data.get('username'),
password=user_data.get('password'),
)
return {'tenant': tenant, 'user': user}
def update(self, instance, validated_data):
raise NotImplementedError('Cannot call update() on an account')
| 69 | 27.78 | 97 | 14 | 379 | python | [{"finding_id": "semgrep_rules.python.django.security.audit.unvalidated-password_342d43ef48f92eef_eacaf01c", "tool_name": "semgrep", "rule_id": "rules.python.django.security.audit.unvalidated-password", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "The password on 'updated' is being set without validating the password. Call django.contrib.auth.password_validation.validate_password() with validation functions before setting the password. See https://docs.djangoproject.com/en/3.0/topics/auth/passwords/ for more information.", "remediation": "if django.contrib.auth.password_validation.validate_password(validated_data['password'], user=updated):\n updated.set_password(validated_data['password'])", "location": {"file_path": "unknown", "line_start": 32, "line_end": 32, "column_start": 13, "column_end": 61, "code_snippet": "requires login"}, "cwe_id": "CWE-521: Weak Password Requirements", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2021 - Identification and Authentication Failures", "references": [{"url": "https://docs.djangoproject.com/en/3.0/topics/auth/passwords/#module-django.contrib.auth.password_validation", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.audit.unvalidated-password", "path": "/tmp/tmppq52ww6s/342d43ef48f92eef.py", "start": {"line": 32, "col": 13, "offset": 871}, "end": {"line": 32, "col": 61, "offset": 919}, "extra": {"message": "The password on 'updated' is being set without validating the password. Call django.contrib.auth.password_validation.validate_password() with validation functions before setting the password. See https://docs.djangoproject.com/en/3.0/topics/auth/passwords/ for more information.", "fix": "if django.contrib.auth.password_validation.validate_password(validated_data['password'], user=updated):\n updated.set_password(validated_data['password'])", "metadata": {"cwe": ["CWE-521: Weak Password Requirements"], "owasp": ["A07:2021 - Identification and Authentication Failures", "A07:2025 - Authentication Failures"], "references": ["https://docs.djangoproject.com/en/3.0/topics/auth/passwords/#module-django.contrib.auth.password_validation"], "category": "security", "technology": ["django"], "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-521"
] | [
"rules.python.django.security.audit.unvalidated-password"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
32
] | [
32
] | [
13
] | [
61
] | [
"A07:2021 - Identification and Authentication Failures"
] | [
"The password on 'updated' is being set without validating the password. Call django.contrib.auth.password_validation.validate_password() with validation functions before setting the password. See https://docs.djangoproject.com/en/3.0/topics/auth/passwords/ for more information."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | serializers.py | /accounts/serializers.py | bellyfat/saasinit | Apache-2.0 | |
2024-11-18T20:49:39.272949+00:00 | 1,548,262,988,000 | 9a09eafa2c6a81ca413fbb001fc3cd4aaedaa1a9 | 3 | {
"blob_id": "9a09eafa2c6a81ca413fbb001fc3cd4aaedaa1a9",
"branch_name": "refs/heads/master",
"committer_date": 1548262988000,
"content_id": "7b7d95e7f0c68b4c8bd9e5e8dada1ea45c82f11a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "fc4e0b7e3c992cb55ac719e7a0387e934dd46d17",
"extension": "py",
"filename": "randomsentenceloader.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 97815156,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5381,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/randomsentenceloader.py",
"provenance": "stack-edu-0054.json.gz:582014",
"repo_name": "c-martinez/w2v-convergence",
"revision_date": 1548262988000,
"revision_id": "4c1d240cc5afeefcc73d103b3d22e28fc4cda573",
"snapshot_id": "5ca1a8abd07e65085d6a1b390dd62f47a20c9adc",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/c-martinez/w2v-convergence/4c1d240cc5afeefcc73d103b3d22e28fc4cda573/randomsentenceloader.py",
"visit_date": "2021-01-01T16:22:15.718183"
} | 3.265625 | stackv2 | import gzip
import numpy as np
import cPickle as pkl
from glob2 import glob
from collections import defaultdict
from helpers import getSentencesForYear
from settings import chunkCache
import logging
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
def getChunks():
'''Generate a list of chunks for each year available on the chunkCache.
Lists of all available chunks are stored in a dictionary with years as its keys.
A 'chunk' is a pklz file containing N sentences from a given year.
e.g:
chunks = {
1900: [ '1900_s1000_b000001.pklz', '1900_s1000_b000002.pklz' ]
1910: [ '1910_s1000_b000001.pklz', '1910_s1000_b000002.pklz' ]
}
'''
chunks = glob(chunkCache + '*.pklz')
chunks = [chunk.replace(chunkCache, '') for chunk in chunks]
year_chunk = defaultdict(list)
for chunk in chunks:
key = chunk.replace('.pklz', '').split('_')[0]
key = int(key)
year_chunk[key].append(chunk)
return year_chunk
def getChunkName(year, chunkSize, chunkNumber='*'):
'''Build the name of a 'chunk' for a given year, size and chunk number.
The year indicates the year from which sentences in a chunk come from.
The chunkSize incidates the maximum number of sentences in the chunk.
The chunkNumber indicates is a consecutive number identifying the chunk.
If no chunkNumber is given, the name is generated with a '*' (which can
be use in a glob).
'''
return '%d_s%d_b%s.pklz' % (year, chunkSize, chunkNumber)
def buildChunks(year, chunkSize):
'''Loads all sentences from a given year and splits them in chuncks
of the given number of sentences (chunkSize). The number of chunks depends on
the total number of sentences available. E.g. for a year containing 5123
sentences, with a chunk size of 1000, 6 chunks will be generated (5 chunks
with 1000 sentences and one chunk with 123).'''
existingChunks = glob(chunkCache + getChunkName(year, chunkSize))
if len(existingChunks) > 0:
print 'Chunks for %d have already been created. Skipping...' % year
return
n0 = 0
sentences = getSentencesForYear(year)
r = range(chunkSize, len(sentences), chunkSize) + [len(sentences)]
for i, n1 in enumerate(r):
sentence_chunk = sentences[n0:n1]
n0 = n1
chunkName = getChunkName(year, chunkSize, chunkNumber=str(i).zfill(6))
fileName = chunkCache + chunkName
with gzip.open(fileName, 'wb') as f:
pkl.dump(sentence_chunk, f)
class RandomSentenceLoader():
'''Loads batches of sentences from a range of years at random.
E.g: Given the years with available chunks.
1900: [ c1900.1, c1900.2, c1900.3, c1900.4, c1900.5, c1900.6 ]
1901: [ c1901.1, c1901.2, c1901.3, c1901.4, c1901.5, c1901.6 ]
1902: [ c1902.1, c1902.2, c1902.3, c1902.4, c1902.5, c1902.6 ]
A batch could be: [ c1900.3, c1902.1, c1900.5, c1901.5 ]. Where c190?.? is
a list of sentences.
'''
def __init__(self, years, chunkSize=1000, seed=90517):
'''Initialize sentence loader.
Years is the range of years from which sentences can be loaded. chunkSize
is the numbe of sentences on each chunk. seed is used to initialize random
number generator (so randomness can be reproducible). This is necessary
in order to produce two random sets which are random, but identical to
each other.'''
self.seed = seed
self.years = years
self.chunkSize = chunkSize
self.reset()
def reset(self):
'''Reset random number generator to initial state.'''
np.random.seed(self.seed)
chunks = getChunks()
self.chunks = {y: chunks[y] for y in self.years}
def _nextRandomYear(self):
'''Select year from which next chunk will be taken'''
if len(self.chunks) == 0:
return None
nextYear = np.random.choice(self.chunks.keys())
log.debug('Next year: %d', nextYear)
return nextYear
def _nextChunkName(self):
'''Select the filename of the next chunk to be loaded'''
nextYear = self._nextRandomYear()
if nextYear is None:
return None
yearChunks = self.chunks[nextYear]
selectIdx = np.random.randint(len(yearChunks))
miniBatch = yearChunks[selectIdx]
del yearChunks[selectIdx]
if len(yearChunks) == 0:
del self.chunks[nextYear]
return miniBatch
def _nextChunk(self):
'''Loads the next chunk of sentences.'''
fileName = self._nextChunkName()
if fileName is None:
return []
with gzip.open(chunkCache + fileName, 'rb') as f:
return pkl.load(f)
def nextBatch(self, batchSize=2000):
'''Generate a batch of sentences of the given batchSize. Sentences are
selected (in chunks) from different years at random.'''
batch = []
for i in range(0, batchSize, self.chunkSize):
batch += self._nextChunk()
return batch
def nextBatchGenerator(self, batchSize=2000):
'''As nextBatch, but returns a generator (so the full batch is not
loaded into memory at once).'''
for i in range(0, batchSize, self.chunkSize):
batch = self._nextChunk()
for b in batch:
yield b
| 147 | 35.61 | 84 | 15 | 1,486 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_85d053715ad4d8cb_952f54b2", "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": 69, "line_end": 69, "column_start": 13, "column_end": 40, "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/85d053715ad4d8cb.py", "start": {"line": 69, "col": 13, "offset": 2508}, "end": {"line": 69, "col": 40, "offset": 2535}, "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_85d053715ad4d8cb_9a422cfd", "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": 131, "line_end": 131, "column_start": 20, "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-cPickle", "path": "/tmp/tmppq52ww6s/85d053715ad4d8cb.py", "start": {"line": 131, "col": 20, "offset": 4741}, "end": {"line": 131, "col": 31, "offset": 4752}, "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"
] | [
69,
131
] | [
69,
131
] | [
13,
20
] | [
40,
31
] | [
"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"
] | randomsentenceloader.py | /randomsentenceloader.py | c-martinez/w2v-convergence | Apache-2.0 | |
2024-11-18T20:49:52.192407+00:00 | 1,487,947,050,000 | 4145f2de662b22b88b8a1eadd6646e516c154241 | 2 | {
"blob_id": "4145f2de662b22b88b8a1eadd6646e516c154241",
"branch_name": "refs/heads/master",
"committer_date": 1487947050000,
"content_id": "c637d5dfd4cb21d6253a0a34573c95b6cb2e5651",
"detected_licenses": [
"MIT"
],
"directory_id": "76f26d554763660fc41b77b9e7dec75a89a82cb5",
"extension": "py",
"filename": "create_toc_mapper_rf.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 82962502,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2282,
"license": "MIT",
"license_type": "permissive",
"path": "/create_toc_mapper_rf.py",
"provenance": "stack-edu-0054.json.gz:582065",
"repo_name": "rupendrab/py_unstr_parse",
"revision_date": 1487947050000,
"revision_id": "3cece3fb7ca969734bf5e60fe5846a7148ce8be4",
"snapshot_id": "d63cbb3f8f5846e566b94e3029367f67e062f6d5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rupendrab/py_unstr_parse/3cece3fb7ca969734bf5e60fe5846a7148ce8be4/create_toc_mapper_rf.py",
"visit_date": "2020-04-06T04:47:03.450683"
} | 2.4375 | stackv2 | #!/usr/bin/env python3.5
import pandas as pd
import math
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import preprocessing
from sklearn.linear_model.logistic import LogisticRegression
from sklearn.metrics import classification_report, accuracy_score, confusion_matrix
from sklearn.pipeline import Pipeline
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.grid_search import GridSearchCV
import pickle
from extract_toc import parseargs
def create_mapper(mapfile, modelfile):
data = pd.read_csv(mapfile, header=None)
data2 = data[data[2]> '']
X = np.array(data2[0])
y = np.array(data2[2])
origmap = dict(zip(X,y))
vectorizer = TfidfVectorizer(stop_words='english')
X_train = vectorizer.fit_transform(X)
# print(y)
le = preprocessing.LabelEncoder()
sorted_y = sorted(set(y))
le.fit(sorted_y)
y_train = le.transform(y)
# le.inverse_transform(0)
pipeline = Pipeline([
('clf', RandomForestClassifier(criterion='entropy'))
])
parameters = {
'clf__n_estimators': (5, 10, 20, 50),
'clf__max_depth': (50, 150, 250),
'clf__min_samples_split': (1, 2, 3),
'clf__min_samples_leaf': (1, 2, 3)
}
grid_search = GridSearchCV(pipeline, parameters, n_jobs=2, verbose=1,
scoring='precision')
grid_search.fit(X_train, y_train)
predicted = grid_search.predict(X_train)
print(classification_report(y_train, predicted))
cnt_diff = 0
for i,val in enumerate(y_train):
if (val != predicted[i]):
cnt_diff += 1
print('Actual = %s, Predicted = %s' % (le.inverse_transform(val), le.inverse_transform(predicted[i])))
print('Number of differences: %d' % cnt_diff)
tosave = [origmap, sorted_y, vectorizer, le, grid_search]
with open(modelfile, 'wb') as f:
pickle.dump(tosave, f)
print('Saved model to %s' % modelfile)
if __name__ == '__main__':
import sys
args = sys.argv[1:]
argsmap = parseargs(args)
mapfile = argsmap.get("map")
modelfile = argsmap.get("savemodel")
if (not mapfile or not modelfile):
print('Both map and savemodel must be specified...')
sys.exit(1)
mapfile = mapfile[0]
modelfile = modelfile[0]
create_mapper(mapfile, modelfile)
| 78 | 28.26 | 108 | 16 | 625 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_f15af6f8a9e2e735_0ca21fde", "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": 63, "line_end": 63, "column_start": 5, "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/tmppq52ww6s/f15af6f8a9e2e735.py", "start": {"line": 63, "col": 5, "offset": 1860}, "end": {"line": 63, "col": 27, "offset": 1882}, "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"
] | [
63
] | [
63
] | [
5
] | [
27
] | [
"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_toc_mapper_rf.py | /create_toc_mapper_rf.py | rupendrab/py_unstr_parse | MIT | |
2024-11-18T20:49:52.368861+00:00 | 1,692,304,842,000 | eff9d8b2301d472bd0f6e15d56911c4b57e7e5ca | 2 | {
"blob_id": "eff9d8b2301d472bd0f6e15d56911c4b57e7e5ca",
"branch_name": "refs/heads/main",
"committer_date": 1692304842000,
"content_id": "ba8e38119b907c4cc576b0975088946e00ea2e8a",
"detected_licenses": [
"Unlicense"
],
"directory_id": "24a3641a9575f40dbc6ada1bf3a4148cf78a98ad",
"extension": "py",
"filename": "DrivePermissionCheck.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 73973864,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3965,
"license": "Unlicense",
"license_type": "permissive",
"path": "/Python/DrivePermissionCheck.py",
"provenance": "stack-edu-0054.json.gz:582068",
"repo_name": "rupumped/NicksAPPS",
"revision_date": 1692304842000,
"revision_id": "dbd653e52ee9c421052a80469a9cebd0190e1ccc",
"snapshot_id": "77fad8ef08e6eca730406b4d9ff508ccc7b4c85a",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/rupumped/NicksAPPS/dbd653e52ee9c421052a80469a9cebd0190e1ccc/Python/DrivePermissionCheck.py",
"visit_date": "2023-09-01T18:20:43.369347"
} | 2.40625 | stackv2 | #! /usr/bin/env python
# Imports
from apiclient import discovery, errors
from httplib2 import Http
from oauth2client import file, client, tools
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import argparse, os, pickle
# Parse Terminal Input
parser = argparse.ArgumentParser(description='List all documents in GDrive with link sharing.')
parser.add_argument('--d', metavar='DIR', type=str, help='Name of the folder within which to search. Use "/" to search within subfolders.')
parser.add_argument('--cred', metavar='CREDENTIALS_FILE', type=str, default='credentials.json', help='Name of json file containing OAuth credentials')
parser.add_argument('--f', action='store_true', help='Forcefully remove link sharing')
parser.add_argument('--verbose', action='store_true', help='If in force mode, notifies user of ')
args = parser.parse_args()
# If modifying these scopes, delete the file token.pickle.
SCOPES = 'https://www.googleapis.com/auth/drive'
creds = None
# 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)
DRIVE = build('drive', 'v3', credentials=creds)
files = DRIVE.files().list().execute().get('files', [])
# Recursively Search GDrive for Documents with Link Sharing
def print_files_in_folder(service, folderId):
request = service.files().list(q="'" + folderId + "' in parents",fields="files(id,name,mimeType,permissions)")
while request is not None:
response = request.execute()
for f in response['files']: # For each file in folder
if 'permissions' in f: # If I have permission to view the permissions of that file
permissions = f['permissions']
for p in permissions: # For each account with which the file has been shared
if p['id']=='anyoneWithLink': # Check to see if the file has link sharing turned on
if args.verbose or not args.f: # If I'm verbose or not forcibly changing the permission, print the name of the file
print(f['name'])
if args.f: # If I am forcibly changing the permission, try to delete the link sharing permission
try:
service.permissions().delete(fileId=f['id'], permissionId=p['id']).execute()
except errors.HttpError:
print('Could not fix permission for ' + f['name'])
break
else: # If I don't have permission, print the name of the file with an asterisk.
print('*' + f['name'])
if f['mimeType']=='application/vnd.google-apps.folder': # Recursively process folders
print_files_in_folder(service, f['id'])
request = service.files().list_next(request, response) # Iterate
# Get Folder ID
folderId = 'root'
if args.d is not None:
folderName = args.d.split('/')
for fn in folderName:
files = DRIVE.files().list(q="'" + folderId + "' in parents").execute()['files']
lastFolderId = folderId
for f in files:
if f['name']==fn and f['mimeType']=='application/vnd.google-apps.folder':
folderId = f['id']
break
if folderId==lastFolderId:
print('Invalid directory: ' + fn + ' cannot be found in path.')
exit()
print_files_in_folder(DRIVE, folderId) | 86 | 45.12 | 150 | 26 | 907 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_39ae646d87c00b15_3de0c3c8", "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": 29, "line_end": 29, "column_start": 11, "column_end": 29, "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/39ae646d87c00b15.py", "start": {"line": 29, "col": 11, "offset": 1317}, "end": {"line": 29, "col": 29, "offset": 1335}, "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_39ae646d87c00b15_2d115b26", "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": 3, "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-pickle", "path": "/tmp/tmppq52ww6s/39ae646d87c00b15.py", "start": {"line": 40, "col": 3, "offset": 1735}, "end": {"line": 40, "col": 28, "offset": 1760}, "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"
] | [
29,
40
] | [
29,
40
] | [
11,
3
] | [
29,
28
] | [
"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"
] | DrivePermissionCheck.py | /Python/DrivePermissionCheck.py | rupumped/NicksAPPS | Unlicense | |
2024-11-18T20:49:53.083314+00:00 | 1,616,524,352,000 | 235105f84fc59621c65ed2081253a3dd262f38c7 | 3 | {
"blob_id": "235105f84fc59621c65ed2081253a3dd262f38c7",
"branch_name": "refs/heads/main",
"committer_date": 1616524352000,
"content_id": "5f74a563758c680ba4fc56242b5181729a169c83",
"detected_licenses": [
"MIT"
],
"directory_id": "9c19cf382951db22a7932de1e9c1efd7b381b0da",
"extension": "py",
"filename": "handler.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 342411580,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1342,
"license": "MIT",
"license_type": "permissive",
"path": "/api/handler.py",
"provenance": "stack-edu-0054.json.gz:582079",
"repo_name": "cardosoyuri/RossmannStoreSalesPrediction",
"revision_date": 1616524352000,
"revision_id": "0264417b4d849c982203f1770ff56f08f4b2185e",
"snapshot_id": "9aee1e28e33a6d54104802c4512204c2b8d8e2c3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cardosoyuri/RossmannStoreSalesPrediction/0264417b4d849c982203f1770ff56f08f4b2185e/api/handler.py",
"visit_date": "2023-03-30T17:45:30.593391"
} | 2.65625 | stackv2 | import pickle
import pandas as pd
from flask import Flask, request, Response
from rossmann.Rossmann import Rossmann
#loading model
model = pickle.load(open(r'C:\Users\prese\Desktop\Data Scince\Projetos\RossmannStoreSales\model\model_rossmann.pkl','rb'))
#Initialize API
app = Flask(__name__)
@app.route('/rossmann/predict', methods = ['POST'])
def rossmann_predict():
test_json = request.get_json()
if test_json: #there is data
if isinstance(test_json, dict): #Unique Example
test_raw = pd.DataFrame(test_json, index=[0])
else:
#Multiple Examples
test_raw = pd.DataFrame(test_json, columns = test_json[0].keys())
# Instantiate Rossmann class
pipeline = Rossmann() # creating an Rossmann class object
# data cleaning
df1 = pipeline.data_cleaning( test_raw )
# feature engineering
df2 = pipeline.feature_engineering( df1 )
# data preparation
df3 = pipeline.data_preparation( df2 )
# prediction
df_response = pipeline.get_prediction( model, test_raw, df3 )
return df_response
else:
return Response('{}', status=200, mimetype = 'application/json')
if __name__ == '__main__':
app.run('127.0.0.1') | 45 | 28.84 | 122 | 18 | 319 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_b6d9094d5ada8618_e2997a0d", "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": 7, "line_end": 7, "column_start": 9, "column_end": 123, "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/b6d9094d5ada8618.py", "start": {"line": 7, "col": 9, "offset": 152}, "end": {"line": 7, "col": 123, "offset": 266}, "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"
] | [
7
] | [
7
] | [
9
] | [
123
] | [
"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"
] | handler.py | /api/handler.py | cardosoyuri/RossmannStoreSalesPrediction | MIT | |
2024-11-18T20:49:57.109180+00:00 | 1,611,964,501,000 | f6a0d274b3dbf993e68529a7652e0d96163000c7 | 2 | {
"blob_id": "f6a0d274b3dbf993e68529a7652e0d96163000c7",
"branch_name": "refs/heads/master",
"committer_date": 1611964501000,
"content_id": "404e1aba5b5cabbaf234121abc5aa841b686d50d",
"detected_licenses": [
"MIT"
],
"directory_id": "5c44a18a25da1ed5726b13ebfd55d511f10c7a90",
"extension": "py",
"filename": "models.py",
"fork_events_count": 0,
"gha_created_at": 1609960238000,
"gha_event_created_at": 1611964502000,
"gha_language": "Python",
"gha_license_id": null,
"github_id": 327406540,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3561,
"license": "MIT",
"license_type": "permissive",
"path": "/mysite/main/models.py",
"provenance": "stack-edu-0054.json.gz:582101",
"repo_name": "AaronTheBruce/inventory-tracker",
"revision_date": 1611964501000,
"revision_id": "1378e548922cbefd8014096aba8fc2af82171def",
"snapshot_id": "e75929f3f99669877eadb846dbf8dd4b4c4fb37f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/AaronTheBruce/inventory-tracker/1378e548922cbefd8014096aba8fc2af82171def/mysite/main/models.py",
"visit_date": "2023-02-26T13:10:58.739718"
} | 2.484375 | stackv2 | # https://docs.djangoproject.com/en/2.1/ref/models/fields/
# https://doc.oroinc.com/user/concept-guides/inventory/ ideas for how to classify inventory status
# https://www.techwithtim.net/tutorials/django/
# https://github.com/arsentieva/campy-backend/blob/master/app/models/models.py | referring to an old project I worked on
# https://dev.to/joshwizzy/customizing-django-authentication-using-abstractbaseuser-llg
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
# from django.utils.translation import ugettext_lazy as _
class EmployeeManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, first_name, last_name, password=None, **extra_fields):
values = [email, first_name, last_name]
field_value_map = dict(zip(self.model.REQUIRED_FIELDS, values))
for field_name, value in field_value_map.items():
if not value:
raise ValueError('The {} value must be set'.format(field_name))
email = self.normalize_email(email)
user = self.model(
email=email,
first_name=first_name,
last_name=last_name,
**extra_fields
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, first_name, last_name, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, name, phone, password, **extra_fields)
def create_superuser(self, email, first_name, last_name, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, first_name, last_name, password, **extra_fields)
# Create your models here.
class Employee(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
first_name = models.CharField(max_length=40)
last_name = models.CharField(max_length=40)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
objects = EmployeeManager()
def __str__(self):
return self.email
def to_dictionary(self):
return {
"id": self.id,
"first_name": self.first_name,
"last_name": self.last_name,
"email": self.email,
"password": self.password
}
# Employee._meta.get_field_by_name('email')[0]._unique=True
class Product(models.Model):
# InStock, OutOfStock, Discontinued
INVENTORY_STATUS = ( # By default, products should be Out of Stock
('In Stock', 'In Stock'),
('Out of Stock', 'Out of Stock'),
('Discontinued', 'Discontinued'),
)
employee = models.ForeignKey(Employee, on_delete=models.CASCADE, default="") # default set to "" to bypass makemigrations error
item_name = models.CharField(max_length=100)
item_quantity = models.IntegerField(default=0)
status = models.CharField(max_length=12, choices=INVENTORY_STATUS, default='Out of Stock')
def to_dictionary(self):
return {
"id": self.id,
"item_name": self.item_name,
"item_quantity": self.item_quantity,
"status": self.status,
"employee_id": self.employee_id,
}
| 96 | 36.09 | 129 | 16 | 825 | python | [{"finding_id": "semgrep_rules.python.django.security.audit.unvalidated-password_2602e86fc6be8b6f_20bfb107", "tool_name": "semgrep", "rule_id": "rules.python.django.security.audit.unvalidated-password", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "The password on 'user' is being set without validating the password. Call django.contrib.auth.password_validation.validate_password() with validation functions before setting the password. See https://docs.djangoproject.com/en/3.0/topics/auth/passwords/ for more information.", "remediation": "if django.contrib.auth.password_validation.validate_password(password, user=user):\n user.set_password(password)", "location": {"file_path": "unknown", "line_start": 27, "line_end": 27, "column_start": 7, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": "CWE-521: Weak Password Requirements", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2021 - Identification and Authentication Failures", "references": [{"url": "https://docs.djangoproject.com/en/3.0/topics/auth/passwords/#module-django.contrib.auth.password_validation", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.audit.unvalidated-password", "path": "/tmp/tmppq52ww6s/2602e86fc6be8b6f.py", "start": {"line": 27, "col": 7, "offset": 1221}, "end": {"line": 27, "col": 34, "offset": 1248}, "extra": {"message": "The password on 'user' is being set without validating the password. Call django.contrib.auth.password_validation.validate_password() with validation functions before setting the password. See https://docs.djangoproject.com/en/3.0/topics/auth/passwords/ for more information.", "fix": "if django.contrib.auth.password_validation.validate_password(password, user=user):\n user.set_password(password)", "metadata": {"cwe": ["CWE-521: Weak Password Requirements"], "owasp": ["A07:2021 - Identification and Authentication Failures", "A07:2025 - Authentication Failures"], "references": ["https://docs.djangoproject.com/en/3.0/topics/auth/passwords/#module-django.contrib.auth.password_validation"], "category": "security", "technology": ["django"], "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-521"
] | [
"rules.python.django.security.audit.unvalidated-password"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
27
] | [
27
] | [
7
] | [
34
] | [
"A07:2021 - Identification and Authentication Failures"
] | [
"The password on 'user' is being set without validating the password. Call django.contrib.auth.password_validation.validate_password() with validation functions before setting the password. See https://docs.djangoproject.com/en/3.0/topics/auth/passwords/ for more information."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | models.py | /mysite/main/models.py | AaronTheBruce/inventory-tracker | MIT | |
2024-11-18T20:49:58.590844+00:00 | 1,524,494,907,000 | 9416923bd2600343c76d861a3d376d3849ac7360 | 2 | {
"blob_id": "9416923bd2600343c76d861a3d376d3849ac7360",
"branch_name": "refs/heads/master",
"committer_date": 1524494907000,
"content_id": "0ddc0f85827d12340876c42d8129472278c1169c",
"detected_licenses": [
"MIT"
],
"directory_id": "5bfe80d256e3a8f3f290c421bb1f637115a32456",
"extension": "py",
"filename": "parallelsample.py",
"fork_events_count": 0,
"gha_created_at": 1524044869000,
"gha_event_created_at": 1524044870000,
"gha_language": null,
"gha_license_id": null,
"github_id": 130040941,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4717,
"license": "MIT",
"license_type": "permissive",
"path": "/svtyper/parallelsample.py",
"provenance": "stack-edu-0054.json.gz:582119",
"repo_name": "florealcab/svtyper",
"revision_date": 1524494907000,
"revision_id": "e175cea9137e1e7bc3c0607dc01193b3f619d440",
"snapshot_id": "cc131b5b0f688784a35d2323785089a353a6403f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/florealcab/svtyper/e175cea9137e1e7bc3c0607dc01193b3f619d440/svtyper/parallelsample.py",
"visit_date": "2020-03-11T14:00:21.987434"
} | 2.46875 | stackv2 | #!/usr/bin/env python3
import sys
import gzip
import argparse
import shutil
import tempfile
from argparse import RawTextHelpFormatter
import os
import multiprocessing
from functools import partial
from subprocess import call
import random
import string
from pysam import AlignmentFile, tabix_compress, tabix_index
from svtyper import singlesample as single
from svtyper import version as svtyper_version
def get_args():
parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter, description="\
svtyper\n\
author: " + svtyper_version.__author__ + "\n\
version: " + svtyper_version.__version__ + "\n\
description: Compute genotype of structural variants based on breakpoint depth")
parser.add_argument('-B', '--bam',
type=str, required=True,
help='BAM list files')
parser.add_argument('-i', '--input_vcf',
type=str, required=False, default=None,
help='VCF input')
parser.add_argument('-o', '--output_vcf',
type=str, required=False, default=None,
help='output VCF to write')
parser.add_argument('-t', '--threads', type=int, default=1,
help='number of threads to use (set at maximum number of available cores)')
args = parser.parse_args()
if args.input_vcf is None:
args.input_vcf = sys.stdin
if args.output_vcf is None:
args.output_vcf = sys.stdout
return args
def fetchId(bamfile):
"""
Fetch sample id in a bam file
:param bamfile: the bam file
:type bamfile: file
:return: sample name
:rtype: str
"""
bamfile_fin = AlignmentFile(bamfile, 'rb')
name = bamfile_fin.header['RG'][0]['SM']
bamfile_fin.close()
return name
def get_bamfiles(bamlist):
with open(bamlist, "r") as fin:
bamfiles = [os.path.abspath(f.strip()) for f in fin]
return bamfiles
def random_string(length=10):
return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(length))
def genotype_multiple_samples(bamlist, vcf_in, vcf_out, cores=1):
bamfiles = get_bamfiles(bamlist)
if vcf_out == sys.stdout:
tmp_dir = tempfile.mkdtemp()
else:
tmp_dir = os.path.join(os.path.dirname(vcf_out), "tmp" + random_string())
os.mkdir(tmp_dir)
if vcf_in == sys.stdin:
vcf_in = single.dump_piped_vcf_to_file(vcf_in, tmp_dir)
elif vcf_in.endswith(".gz"):
vcf_in_gz = vcf_in
vcf_in = os.path.join(tmp_dir, os.path.basename(vcf_in[:-3]))
with gzip.open(vcf_in_gz, 'rb') as f_in, open(vcf_in, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
pool = multiprocessing.Pool(processes=cores)
launch_ind = partial(genotype_single_sample,
vcf_in=vcf_in, out_dir=tmp_dir)
vcf_files = pool.map(launch_ind, bamfiles)
merge_cmd = "bcftools merge -m id "
if vcf_out != sys.stdout:
merge_cmd += "-O z " + " -o " + vcf_out + " "
merge_cmd += " ".join(vcf_files)
exit_code = call(merge_cmd, shell=True)
if exit_code == 0:
if vcf_out != sys.stdout:
tabix_index(vcf_out, force=True, preset="vcf")
shutil.rmtree(tmp_dir)
else:
print("Failed: bcftools merge exits with status %d" % exit_code)
exit(1)
def genotype_single_sample(bam, vcf_in, out_dir):
lib_info_json = bam + ".json"
sample = fetchId(bam)
out_vcf = os.path.join(out_dir, sample + ".gt.vcf")
with open(vcf_in, "r") as inf, open(out_vcf, "w") as outf:
single.sso_genotype(bam_string=bam,
vcf_in=inf,
vcf_out=outf,
min_aligned=20,
split_weight=1,
disc_weight=1,
num_samp=1000000,
lib_info_path=lib_info_json,
debug=False,
ref_fasta=None,
sum_quals=False,
max_reads=1000,
cores=None,
batch_size=None)
out_gz = out_vcf + ".gz"
tabix_compress(out_vcf, out_gz, force=True)
tabix_index(out_gz, force=True, preset="vcf")
return out_gz
def main():
args = get_args()
genotype_multiple_samples(args.bam, args.input_vcf, args.output_vcf, cores=args.threads)
def cli():
try:
sys.exit(main())
except IOError as e:
if e.errno != 32: # ignore SIGPIPE
raise
if __name__ == '__main__':
cli()
| 157 | 29.04 | 99 | 16 | 1,160 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_95ea508b39064e70_28438681", "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": 65, "line_end": 65, "column_start": 10, "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/95ea508b39064e70.py", "start": {"line": 65, "col": 10, "offset": 1872}, "end": {"line": 65, "col": 28, "offset": 1890}, "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_95ea508b39064e70_aa263c1c", "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": 105, "line_end": 105, "column_start": 17, "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/95ea508b39064e70.py", "start": {"line": 105, "col": 17, "offset": 3131}, "end": {"line": 105, "col": 44, "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.security.audit.subprocess-list-passed-as-string_95ea508b39064e70_5dfae1bc", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-list-passed-as-string", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected `\" \".join(...)` being passed to `subprocess.run`. This can lead to argument splitting issues and potential security vulnerabilities. Instead, pass the list directly to `subprocess.run` to preserve argument separation.", "remediation": "", "location": {"file_path": "unknown", "line_start": 105, "line_end": 105, "column_start": 22, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": "C", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://docs.python.org/3/library/subprocess.html#frequently-used-arguments", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-list-passed-as-string", "path": "/tmp/tmppq52ww6s/95ea508b39064e70.py", "start": {"line": 105, "col": 22, "offset": 3136}, "end": {"line": 105, "col": 31, "offset": 3145}, "extra": {"message": "Detected `\" \".join(...)` being passed to `subprocess.run`. This can lead to argument splitting issues and potential security vulnerabilities. Instead, pass the list directly to `subprocess.run` to preserve argument separation.", "metadata": {"category": "security", "cwe": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "references": ["https://docs.python.org/3/library/subprocess.html#frequently-used-arguments"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "technology": ["python"], "confidence": "LOW", "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "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_95ea508b39064e70_ec6a9cb9", "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": 105, "line_end": 105, "column_start": 39, "column_end": 43, "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/95ea508b39064e70.py", "start": {"line": 105, "col": 39, "offset": 3153}, "end": {"line": 105, "col": 43, "offset": 3157}, "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.correctness.use-sys-exit_95ea508b39064e70_29270987", "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": 114, "line_end": 114, "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/tmppq52ww6s/95ea508b39064e70.py", "start": {"line": 114, "col": 9, "offset": 3399}, "end": {"line": 114, "col": 16, "offset": 3406}, "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.best-practice.unspecified-open-encoding_95ea508b39064e70_bde1b31d", "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": 10, "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://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/95ea508b39064e70.py", "start": {"line": 121, "col": 10, "offset": 3592}, "end": {"line": 121, "col": 27, "offset": 3609}, "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_95ea508b39064e70_aa38512f", "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": 36, "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/95ea508b39064e70.py", "start": {"line": 121, "col": 36, "offset": 3618}, "end": {"line": 121, "col": 54, "offset": 3636}, "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",
"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"
] | [
105,
105
] | [
105,
105
] | [
17,
39
] | [
44,
43
] | [
"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"
] | parallelsample.py | /svtyper/parallelsample.py | florealcab/svtyper | MIT | |
2024-11-18T20:49:58.683324+00:00 | 1,547,312,110,000 | 96b5c513c6f9388bf24c0e1e14a07e6b064bb1f5 | 3 | {
"blob_id": "96b5c513c6f9388bf24c0e1e14a07e6b064bb1f5",
"branch_name": "refs/heads/master",
"committer_date": 1547312110000,
"content_id": "994279174b025ab5cea13b457832a0d8b3f3979e",
"detected_licenses": [
"MIT"
],
"directory_id": "b0e43f80af3e897f7053c0b05f0ce63ed5d71cab",
"extension": "py",
"filename": "mnist.py",
"fork_events_count": 0,
"gha_created_at": 1536830349000,
"gha_event_created_at": 1536830349000,
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 148613542,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2462,
"license": "MIT",
"license_type": "permissive",
"path": "/tflib/mnist.py",
"provenance": "stack-edu-0054.json.gz:582120",
"repo_name": "eitanrich/improved_wgan_training",
"revision_date": 1547312110000,
"revision_id": "87dcc7fabf12fae07f99f17fd345b258dc92bcd9",
"snapshot_id": "15d61b87e0fe6eb3f54ddde87608cdbffa3a1e33",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/eitanrich/improved_wgan_training/87dcc7fabf12fae07f99f17fd345b258dc92bcd9/tflib/mnist.py",
"visit_date": "2020-03-28T15:39:26.839129"
} | 2.75 | stackv2 | import numpy
import os
import urllib
import gzip
import pickle
def mnist_generator(data, batch_size, digits_filter, div_by=None):
images, targets = data
if digits_filter is not None:
relevant_samples = numpy.isin(targets, digits_filter)
images = images[relevant_samples]
targets = targets[relevant_samples]
print('Samples shape =', images.shape)
rng_state = numpy.random.get_state()
numpy.random.shuffle(images)
numpy.random.set_state(rng_state)
numpy.random.shuffle(targets)
if div_by is not None:
limit = int(round(images.shape[0]/div_by))
print("WARNING ONLY 1/{} = {} MNIST DIGITS".format(div_by, limit))
images = images.astype('float32')[:limit]
targets = targets.astype('int32')[:limit]
def get_epoch():
rng_state = numpy.random.get_state()
numpy.random.shuffle(images)
numpy.random.set_state(rng_state)
numpy.random.shuffle(targets)
num_samples = images.shape[0] - images.shape[0]%batch_size
image_batches = images[:num_samples].reshape(-1, batch_size, 784)
target_batches = targets[:num_samples].reshape(-1, batch_size)
for i in xrange(len(image_batches)):
yield (numpy.copy(image_batches[i]), numpy.copy(target_batches[i]))
return get_epoch
def load(batch_size, test_batch_size, digits_filter=None, div_by=None):
filepath = '/tmp/mnist.pkl.gz'
url = 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz'
if not os.path.isfile(filepath):
print("Couldn't find MNIST dataset in /tmp, downloading...")
urllib.urlretrieve(url, filepath)
with gzip.open('/tmp/mnist.pkl.gz', 'rb') as f:
train_data, dev_data, test_data = pickle.load(f)
return (
mnist_generator(train_data, batch_size, digits_filter, div_by),
mnist_generator(dev_data, test_batch_size, digits_filter, div_by),
mnist_generator(test_data, test_batch_size, digits_filter, div_by)
)
def load_now(digits_filter=None):
filepath = '/tmp/mnist.pkl.gz'
url = 'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz'
if not os.path.isfile(filepath):
print("Couldn't find MNIST dataset in /tmp, downloading...")
urllib.urlretrieve(url, filepath)
with gzip.open('/tmp/mnist.pkl.gz', 'rb') as f:
train_data, dev_data, test_data = pickle.load(f)
return train_data, dev_data, test_data
| 70 | 34.17 | 79 | 15 | 582 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dynamic-urllib-use-detected_73d843d9b51793b9_6c83b45f", "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": 47, "line_end": 47, "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/tmppq52ww6s/73d843d9b51793b9.py", "start": {"line": 47, "col": 9, "offset": 1627}, "end": {"line": 47, "col": 42, "offset": 1660}, "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-pickle_73d843d9b51793b9_1a8007ae", "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": 50, "line_end": 50, "column_start": 43, "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/73d843d9b51793b9.py", "start": {"line": 50, "col": 43, "offset": 1756}, "end": {"line": 50, "col": 57, "offset": 1770}, "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.audit.dynamic-urllib-use-detected_73d843d9b51793b9_aa9a4e50", "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": 64, "line_end": 64, "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/tmppq52ww6s/73d843d9b51793b9.py", "start": {"line": 64, "col": 9, "offset": 2273}, "end": {"line": 64, "col": 42, "offset": 2306}, "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-pickle_73d843d9b51793b9_023d84d8", "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": 67, "line_end": 67, "column_start": 43, "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/73d843d9b51793b9.py", "start": {"line": 67, "col": 43, "offset": 2402}, "end": {"line": 67, "col": 57, "offset": 2416}, "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"
] | [
50,
67
] | [
50,
67
] | [
43,
43
] | [
57,
57
] | [
"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"
] | mnist.py | /tflib/mnist.py | eitanrich/improved_wgan_training | MIT | |
2024-11-18T20:49:58.742785+00:00 | 1,592,145,927,000 | b2a2b0faa5e6bea7749fc584e0d0cda200faa1c2 | 3 | {
"blob_id": "b2a2b0faa5e6bea7749fc584e0d0cda200faa1c2",
"branch_name": "refs/heads/master",
"committer_date": 1592145927000,
"content_id": "d285e2207403ec5fe654144a349c8faed596be65",
"detected_licenses": [
"BSD-3-Clause",
"MIT"
],
"directory_id": "9b8a35506f275494b29edaf28c9a5b286c623f0a",
"extension": "py",
"filename": "draw4.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": 1793,
"license": "BSD-3-Clause,MIT",
"license_type": "permissive",
"path": "/src/draw4.py",
"provenance": "stack-edu-0054.json.gz:582121",
"repo_name": "loki371/CenterNet",
"revision_date": 1592145927000,
"revision_id": "27a5dfef89c7f7a318d7f96fd6bbcfc94198c76f",
"snapshot_id": "6413ce7137bf89119beddb307277bc0ebc892883",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/loki371/CenterNet/27a5dfef89c7f7a318d7f96fd6bbcfc94198c76f/src/draw4.py",
"visit_date": "2022-10-19T01:08:48.500369"
} | 2.53125 | stackv2 | import json
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import os
name_model = 'dla_34'
threshold = 0.3
count = 0
name_folder = 'json_'+ name_model
video_folder = 'anno_videos_' + name_model
ls_dir = os.listdir(name_folder)
os.system('mkdir {}'.format(video_folder))
# lsd = *.json
for lsd in ls_dir:
# convert old format to new format
# {'image_name':[list of bbox]}
dic_result_demo = {}
print('open {}/{}.json'.format(name_folder, lsd))
with open('{}/{}'.format(name_folder, lsd),'r') as f:
file_content = json.load(f)
for ob in file_content:
image_name = ob['image_name']
if image_name not in dic_result_demo:
dic_result_demo[image_name] = []
# count+=1
dic_result_demo[image_name].append({
"category_id": ob["category_id"],
"bbox": ob["bbox"],
"score": ob["score"]
})
# use new format to draw
os.system('mkdir {}/{}'.format(video_folder, lsd.split('.')[0]))
for imgtmp, lsbbox in dic_result_demo.items():
img= 'extracted_frames/{}/{}'.format(lsd.split('.')[0], imgtmp.split('/')[-1])
print('+ drawing {}'.format(img))
source_img = Image.open(img).convert("RGB")
draw = ImageDraw.Draw(source_img)
for ob in lsbbox:
if ob['score'] >= threshold:
bbxs = ob['bbox']
draw.rectangle(((bbxs[0], bbxs[1]), (bbxs[0]+bbxs[2], bbxs[1]+bbxs[3])),outline='red', width=5)
source_img.save('{}/{}/{}'.format(video_folder,lsd.split('.')[0],img.split('/')[-1]))
print('saved {}/{}/{}'.format(video_folder,lsd.split('.')[0],img.split('/')[-1]))
# print(count)
# dic_result_demo
| 52 | 33.48 | 111 | 17 | 460 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_6075f09c205b44b1_e3f2928a", "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": 15, "line_end": 15, "column_start": 1, "column_end": 43, "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/6075f09c205b44b1.py", "start": {"line": 15, "col": 1, "offset": 258}, "end": {"line": 15, "col": 43, "offset": 300}, "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.unspecified-open-encoding_6075f09c205b44b1_bc853fba", "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": 23, "line_end": 23, "column_start": 10, "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/6075f09c205b44b1.py", "start": {"line": 23, "col": 10, "offset": 493}, "end": {"line": 23, "col": 52, "offset": 535}, "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_6075f09c205b44b1_c64e7fb9", "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": 5, "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://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/6075f09c205b44b1.py", "start": {"line": 38, "col": 5, "offset": 1014}, "end": {"line": 38, "col": 69, "offset": 1078}, "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"}}}] | 3 | 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"
] | [
15,
38
] | [
15,
38
] | [
1,
5
] | [
43,
69
] | [
"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"
] | draw4.py | /src/draw4.py | loki371/CenterNet | BSD-3-Clause,MIT | |
2024-11-18T20:50:04.012737+00:00 | 1,582,073,960,000 | 75274f4816a3aeff644793e0f5da92a4bebcc098 | 3 | {
"blob_id": "75274f4816a3aeff644793e0f5da92a4bebcc098",
"branch_name": "refs/heads/master",
"committer_date": 1582073960000,
"content_id": "542e70df65449cff42f53da7e6ce611d61da7131",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "68ff8bebf7e4aab95e8e7c68d7cdee262c10c228",
"extension": "py",
"filename": "corpus.py",
"fork_events_count": 0,
"gha_created_at": 1582073654000,
"gha_event_created_at": 1582073654000,
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 241501183,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 490,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/web-app/application/analysis/corpus.py",
"provenance": "stack-edu-0054.json.gz:582152",
"repo_name": "rkeb/discover-archetype",
"revision_date": 1582073960000,
"revision_id": "ba2cad70c6b7dfc7aa2ad7d9be5a92f44abc49c5",
"snapshot_id": "e7d88983b68eebc83e9102ef630c4c028881e2c2",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/rkeb/discover-archetype/ba2cad70c6b7dfc7aa2ad7d9be5a92f44abc49c5/web-app/application/analysis/corpus.py",
"visit_date": "2021-01-06T22:30:24.309509"
} | 2.609375 | stackv2 | import pickle
import pandas as pd
from application.models import CorpusResult
def get_corpus_results(corpus_id):
results = CorpusResult.query.filter(
CorpusResult.corpus_id == corpus_id
).all()
df_dic = {}
for result in results:
watson_response = pickle.loads(result.data)
df_dic[result.name] = {}
for item in list(watson_response.result.items()):
df_dic[result.name][item[0]] = pd.DataFrame(list(item[1]))
return df_dic
| 19 | 24.79 | 70 | 15 | 109 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_cde29d707858a41a_a893ce1a", "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": 27, "column_end": 52, "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/cde29d707858a41a.py", "start": {"line": 15, "col": 27, "offset": 284}, "end": {"line": 15, "col": 52, "offset": 309}, "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"
] | [
15
] | [
15
] | [
27
] | [
52
] | [
"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"
] | corpus.py | /web-app/application/analysis/corpus.py | rkeb/discover-archetype | Apache-2.0 | |
2024-11-18T20:50:08.347752+00:00 | 1,604,175,989,000 | f9b5e2bef6b491217934a022dd3cb452758cb350 | 3 | {
"blob_id": "f9b5e2bef6b491217934a022dd3cb452758cb350",
"branch_name": "refs/heads/master",
"committer_date": 1604175989000,
"content_id": "07234d98397d9156fdb6050f96dab80ce1dd006b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "70e3bcb355076503e68ed75fd06d6566d280e675",
"extension": "py",
"filename": "execute_notebook.py",
"fork_events_count": 0,
"gha_created_at": 1592399623000,
"gha_event_created_at": 1617550207000,
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 272977829,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1727,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/scripts/execute_notebook.py",
"provenance": "stack-edu-0054.json.gz:582180",
"repo_name": "vishalbelsare/OmniNet",
"revision_date": 1604175989000,
"revision_id": "15c61fddfb225988ce3d14c565441bd8ae7c58bf",
"snapshot_id": "57a66d1629ef38e3a90f35cd7343614489bd156a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vishalbelsare/OmniNet/15c61fddfb225988ce3d14c565441bd8ae7c58bf/scripts/execute_notebook.py",
"visit_date": "2023-03-30T02:03:29.458149"
} | 3.109375 | stackv2 | #!/usr/bin/env python
import glob
import os
if __name__ == '__main__':
print('Searching for notebooks in the notebooks directory')
# maybe executing like execute_notebook.py
notebook_dir = '../notebooks'
result_dir = '../results'
if not os.path.exists(notebook_dir):
# maybe executing like scripts/execute_notebook.py
notebook_dir = './notebooks'
result_dir = './results'
if not os.path.exists(notebook_dir):
# still did not find the notebook directory
print('Notebook Directory not found! Exiting')
exit(0)
# glob notebooks
notebooks = glob.glob(f'{notebook_dir}/*.ipynb')
# the length cannot be 0
if len(notebooks) == 0:
print('No Notebooks found! Exiting.')
exit(0)
print('Select a notebook to run. Results will be logged to <notebook_name>.log in the results directory\n')
for i in range(len(notebooks)):
print(f'{i + 1}. {os.path.basename(notebooks[i])}')
try:
option = int(input('\nEnter option: '))
if option > len(notebooks):
assert IndexError
print(f'Executing notebook {os.path.basename(notebooks[option - 1])}')
# deal with spaces in file names
selected_notebook = notebooks[option - 1].replace(' ', '\ ')
result_file_name = os.path.splitext(os.path.basename(selected_notebook))[0]
# run the selected notebook
os.system(f'jupyter nbconvert --to script --execute --stdout {selected_notebook} | '
f'python -u 2>&1 | tee {result_dir}/{result_file_name}.log &')
print('Process started!')
except IndexError as e:
print('Invalid option! Existing.')
exit(0)
| 42 | 40.12 | 111 | 15 | 403 | python | [{"finding_id": "semgrep_rules.python.lang.correctness.use-sys-exit_fbbd1451f33ebba9_e619a406", "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(0)", "location": {"file_path": "unknown", "line_start": 17, "line_end": 17, "column_start": 13, "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://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/fbbd1451f33ebba9.py", "start": {"line": 17, "col": 13, "offset": 589}, "end": {"line": 17, "col": 20, "offset": 596}, "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(0)", "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.correctness.use-sys-exit_fbbd1451f33ebba9_24935724", "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(0)", "location": {"file_path": "unknown", "line_start": 23, "line_end": 23, "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/tmppq52ww6s/fbbd1451f33ebba9.py", "start": {"line": 23, "col": 9, "offset": 782}, "end": {"line": 23, "col": 16, "offset": 789}, "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(0)", "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.audit.dangerous-system-call-audit_fbbd1451f33ebba9_220af6f0", "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": 37, "line_end": 38, "column_start": 9, "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/tmppq52ww6s/fbbd1451f33ebba9.py", "start": {"line": 37, "col": 9, "offset": 1439}, "end": {"line": 38, "col": 82, "offset": 1605}, "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.correctness.use-sys-exit_fbbd1451f33ebba9_f39c9756", "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(0)", "location": {"file_path": "unknown", "line_start": 42, "line_end": 42, "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/tmppq52ww6s/fbbd1451f33ebba9.py", "start": {"line": 42, "col": 9, "offset": 1719}, "end": {"line": 42, "col": 16, "offset": 1726}, "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(0)", "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"}}}] | 4 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
37
] | [
38
] | [
9
] | [
82
] | [
"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."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | execute_notebook.py | /scripts/execute_notebook.py | vishalbelsare/OmniNet | Apache-2.0 | |
2024-11-18T20:50:09.134912+00:00 | 1,649,458,931,000 | d719fdc63e0eeb2313cebfcd6009d5441107663a | 3 | {
"blob_id": "d719fdc63e0eeb2313cebfcd6009d5441107663a",
"branch_name": "refs/heads/master",
"committer_date": 1649458931000,
"content_id": "2bccc024073b57485faf17db151b6dd78a8495c9",
"detected_licenses": [
"MIT"
],
"directory_id": "1463e2c6e1e5ac799e14de945147309c3db4d1bc",
"extension": "py",
"filename": "modules.py",
"fork_events_count": 0,
"gha_created_at": 1619156805000,
"gha_event_created_at": 1619156806000,
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 360776173,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6920,
"license": "MIT",
"license_type": "permissive",
"path": "/sc_utils/modules.py",
"provenance": "stack-edu-0054.json.gz:582187",
"repo_name": "ishine/Auto-Tuning-Spectral-Clustering",
"revision_date": 1649458931000,
"revision_id": "ae97f9be9c33b554205c7192c5137ce8f456c1b7",
"snapshot_id": "191b699f4389332fc9f2ad7d0326dccd0b65f7d9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ishine/Auto-Tuning-Spectral-Clustering/ae97f9be9c33b554205c7192c5137ce8f456c1b7/sc_utils/modules.py",
"visit_date": "2022-04-30T16:01:23.500704"
} | 2.53125 | stackv2 | import numpy as np
import pickle
import os
from subprocess import Popen, PIPE
import time
import datetime
import ipdb
from sklearn.utils import shuffle
def noremDiv(nu, de):
if nu % de == 0:
return nu // de
else:
return nu // de + 1
def batchDiv(nu, de):
if nu % de == 0:
return (nu // de) - 1
else:
return nu // de + 1
def cprint(st, c='r'):
if c=='r':
CRED = '\033[91m'
elif c=='g':
CRED = '\033[92m'
elif c=='b':
CRED = '\033[94m'
elif c=='y':
CRED = '\033[93m'
CEND = '\033[0m'
print(CRED + st + CEND)
def timeStamped(fname, fmt='%Y-%m-%d-%H-%M-%S_{fname}'):
return datetime.datetime.now().strftime(fmt).format(fname=fname)
def rsc(x):
return x.split(':')[0]
def bashGet(bash_command):
p = Popen(bash_command.split(' '), stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate()
txtout = output.decode('utf-8')
return txtout
def dictConvert(inDict):
key_list = list(inDict.keys())
out = {}
for t in key_list:
# print(inDict[t])
D = inDict[t].split('_')# speaker, start, dur, word
out.update({t: [D[0], int(100*float(D[1])), int(100*float(D[2])), D[3]]})
return out
def dictClean_Pickle(b):
trans_dict = {}
raw_dict = b[0]
for key, val in raw_dict.items():
trans_dict[key] = modules.dictConvert(val)
with open('/data-local/taejin/feat_dir/Fisher/fisher_trans_dict.pickle', 'wb') as handle:
pickle.dump(trans_dict, handle, protocol=pickle.HIGHEST_PROTOCOL)
def loadPickle(file_path):
print('Loading Pickle File: ', file_path)
st = time.time()
try:
with open(file_path, 'rb') as handle:
b = pickle.load(handle)
print('Loading complete. Elapsed time: %fs' %(time.time()-st))
except:
print('No such file as: ', file_path)
raise ValueError
return b
def savePickle(pickle_path, save_list):
with open(pickle_path, 'wb') as handle:
pickle.dump(save_list, handle, protocol=pickle.HIGHEST_PROTOCOL)
def read_txt(list_path):
with open(list_path) as f:
content = []
for line in f:
line = line.strip()
content.append(line)
f.close()
assert content != [], "File is empty. Abort. Given path: " + list_path
return content
def unison_shuffled_copies(a, b):
assert len(a) == len(b)
p = np.random.permutation(len(a))
return a[p], b[p]
def unison_shuffled_copies_three(amat, bmat, slmat):
ipdb.set_trace()
assert len(amat) == len(bmat) and len(bmat) == len(slmat)
pmat = np.random.permutation(len(amat))
return amat[pmat], bmat[pmat], slmat[pmat]
def unison_numpy_shuffled(amat, bmat, slmat):
# ipdb.set_trace()
assert len(amat) == len(bmat) and len(bmat) == len(slmat)
amat, bmat, slmat = shuffle(amat, bmat, slmat)
return amat, bmat, slmat
def getGPUbatchSize(num_gpus, batch_size):
nf = int( noremDiv(batch_size,num_gpus))
nl = batch_size - nf*(num_gpus-1)
return np.cumsum([0] + [nf]*(num_gpus-1) + [nl])
def write_txt(w_path, list_to_wr):
with open(w_path, "w") as output:
for k, val in enumerate(list_to_wr):
output.write(val + '\n')
return None
def nanCheck(np_mat):
if np.isnan(np_mat).any():
print('Number of nan: ', np.count_nonzero(np.isnan(np_mat)))
raise ValueError('mean_act_out matrix contains NAN value.')
def segRead(fn, start, end):
fo = open(fn, "r")
line = fo.readlines()[start:end]
fo.close()
return line
def makeDict(content):
feat_dict = {}
for line in content:
line = line.split(' ')
feat_dict[line[0]] = [line[1], line[2], line[3]]
return feat_dict
def readFeat(dkey, feat_dict, kaldi_feat_path):
fn = kaldi_feat_path + '/' + feat_dict[dkey][0]
start = int(feat_dict[dkey][1])
end = int(feat_dict[dkey][2])
segRead(fn, start, end)
def loadFisherFeatList(kaldi_feat_path):
fisher_mfcc_abs_path = kaldi_feat_path + '/' + '*.txt'
kaldi_mfcc_file_index = []
# Read all the kaldi-generated feature files
for file in glob.glob(fisher_mfcc_abs_path):
print('###### ARK file open: ', file)
kaldi_mfcc_file_index.append(file)
return kaldi_mfcc_file_index
def ftm(name):
'''
Fisher speaker tag remover:
(Trans dictionary is indexed per session, not speaker.)
'''
return name.replace('-A', '').replace('-B', '')
def kaldiFeatLoader(kaldi_mfcc_file_index_list, trans_dict):
'''
Using trans_dict, this generator function loads
kaldi feature file per session sequentially.
Args:
kaldi_mfcc_file_index_list: Please include all the .txt path for features
trans_dict: Please include all the dictionary for the training/test data.
Returns:
fileid
mfcc numpy array (length x #ch)
trans_dict: transcription in dictionary format ex( key format: "fe_03_01234"
'''
for list_path in kaldi_mfcc_file_index_list:
print(list_path)
with open(list_path) as f:
mfcc_lines = []
raw_mfcc_id = list_path.split('/')[-1]
for i, line in enumerate(f):
line = line.strip()
if 'fe' in line: # The first line
fileid = line.replace('[', '').strip()
print('Captured fileID: %s' %(fileid))
start_line_num = str(i+1)
elif ']' in list(line): # The last line -> output a set of training samples
line = line.replace(']', '')
print(line)
mfcc_lines.append([float(x) for x in line.strip().split(' ')])
end_line_num = str(i)
index_list = [fileid, raw_mfcc_id, start_line_num, end_line_num]
yield [fileid,
np.asarray(mfcc_lines),
trans_dict[ftm(fileid)]]
mfcc_lines = [] # Empty the buffer list
else:
mfcc_lines.append([float(x) for x in line.strip().split(' ')])
def seqLen(tD):
'''Calculate the number of non-zero elements for variable length RNN
'''
# return np.expand_dims(np.count_nonzero(tD, axis=1), axis=1)
# return list(np.count_nonzero(tD, axis=1))
# SLout = np.count_nonzero(tD, axis=1)
SLout = np.count_nonzero(tD, axis=1)
return SLout
def fisherSpkCH(fileid):
''' Fisher Corpora Channel Mapper '''
spk = fileid.strip()[-1]
if spk == 'A':
return 0
elif spk == 'B':
return 1
def makeTxtBash(file_name):
if not os.path.isfile(file_name):
bashGet('touch ' + file_name)
else:
bashGet('rm ' + file_name)
bashGet('touch ' + file_name)
| 226 | 29.62 | 93 | 22 | 1,882 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_30a73725b89a1b65_cb7c260d", "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": 41, "line_end": 41, "column_start": 9, "column_end": 77, "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/30a73725b89a1b65.py", "start": {"line": 41, "col": 9, "offset": 816}, "end": {"line": 41, "col": 77, "offset": 884}, "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.deserialization.avoid-pickle_30a73725b89a1b65_ac07a77f", "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": 61, "line_end": 61, "column_start": 9, "column_end": 74, "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/30a73725b89a1b65.py", "start": {"line": 61, "col": 9, "offset": 1512}, "end": {"line": 61, "col": 74, "offset": 1577}, "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_30a73725b89a1b65_8f9208cf", "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": 68, "line_end": 68, "column_start": 17, "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/tmppq52ww6s/30a73725b89a1b65.py", "start": {"line": 68, "col": 17, "offset": 1744}, "end": {"line": 68, "col": 36, "offset": 1763}, "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_30a73725b89a1b65_f2fe88c3", "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": 77, "line_end": 77, "column_start": 9, "column_end": 73, "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/30a73725b89a1b65.py", "start": {"line": 77, "col": 9, "offset": 2025}, "end": {"line": 77, "col": 73, "offset": 2089}, "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_30a73725b89a1b65_0e147af8", "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": 10, "column_end": 25, "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/30a73725b89a1b65.py", "start": {"line": 81, "col": 10, "offset": 2126}, "end": {"line": 81, "col": 25, "offset": 2141}, "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_30a73725b89a1b65_707261c6", "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": 113, "line_end": 113, "column_start": 10, "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://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/30a73725b89a1b65.py", "start": {"line": 113, "col": 10, "offset": 3165}, "end": {"line": 113, "col": 27, "offset": 3182}, "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_30a73725b89a1b65_c4e21494", "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": 124, "line_end": 124, "column_start": 10, "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://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/30a73725b89a1b65.py", "start": {"line": 124, "col": 10, "offset": 3522}, "end": {"line": 124, "col": 23, "offset": 3535}, "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_30a73725b89a1b65_e2573edd", "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": 176, "line_end": 176, "column_start": 14, "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/30a73725b89a1b65.py", "start": {"line": 176, "col": 14, "offset": 5105}, "end": {"line": 176, "col": 29, "offset": 5120}, "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-502",
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"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"
] | [
"HIGH",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
41,
61,
68,
77
] | [
41,
61,
68,
77
] | [
9,
9,
17,
9
] | [
77,
74,
36,
73
] | [
"A01:2017 - Injection",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"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()'.",
"Avoid using `pickle`, whi... | [
7.5,
5,
5,
5
] | [
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | modules.py | /sc_utils/modules.py | ishine/Auto-Tuning-Spectral-Clustering | MIT | |
2024-11-18T20:50:12.490925+00:00 | 1,505,881,663,000 | a6e49d07b33b1ad44ec75ee6ec632e614c9f59a7 | 2 | {
"blob_id": "a6e49d07b33b1ad44ec75ee6ec632e614c9f59a7",
"branch_name": "refs/heads/master",
"committer_date": 1505881663000,
"content_id": "464164ed368acf778c06f8a4a2e1da32fd56fe4a",
"detected_licenses": [
"MIT"
],
"directory_id": "69f2796fd681b2030ea64d5346ad58d3bff8fb1b",
"extension": "py",
"filename": "filter.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 103875894,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1397,
"license": "MIT",
"license_type": "permissive",
"path": "/relations/filter.py",
"provenance": "stack-edu-0054.json.gz:582219",
"repo_name": "AnthonySigogne/HackatonIWCS2017",
"revision_date": 1505881663000,
"revision_id": "d0683a1c8246b75d110984207ec1f1cee67accef",
"snapshot_id": "97ed59a9d4f10928fbcac6db4566dff3975b886b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/AnthonySigogne/HackatonIWCS2017/d0683a1c8246b75d110984207ec1f1cee67accef/relations/filter.py",
"visit_date": "2021-06-30T08:17:53.558673"
} | 2.5 | stackv2 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#python3
import pickle
import os
import re
# final relations dict
relations = {}
# relations we want to extract
allowed_rels = {
"17":"r_has_carac",
"23":"r_has_carac",
"6":"r_is_a",
"9":"r_has_part",
"15":"r_lieu",
"24":"r_has_agent",
"26":"r_has_patient",
"16":"r_has_instrument",
"41":"r_has_consequence",
"53":"r_make_use_of"
}
for filename in os.listdir("./") :
with open(filename, "r", encoding="latin-1") as f :
if not filename.endswith(".txt") : continue
print("load filename : "+filename)
for line in f :
try :
# extraction relations for a word
mot1, rels = line.strip().split(":",1)
mot1 = mot1.split(">")[0]
for relation in re.finditer("[{,]?(?P<mot2>[^:]+):{(?P<relation>[0-9]+),(?P<poids>[0-9]+)}", rels) :
mot2 = relation.group("mot2").split(">")[0]
rel = relation.group("relation")
if rel in allowed_rels :
relations["%s %s"%(mot1, mot2)] = allowed_rels[rel]
relations["%s %s"%(mot2, mot1)] = allowed_rels[rel]
except Exception as inst:
print(inst)
print("pickle relations...")
pickle.dump( relations, open( "relations.pickled", "wb" ) , protocol=2)
| 46 | 29.37 | 116 | 20 | 386 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_925549075c6ae171_5295e631", "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": 46, "line_end": 46, "column_start": 1, "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-pickle", "path": "/tmp/tmppq52ww6s/925549075c6ae171.py", "start": {"line": 46, "col": 1, "offset": 1325}, "end": {"line": 46, "col": 72, "offset": 1396}, "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"
] | [
46
] | [
46
] | [
1
] | [
72
] | [
"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"
] | filter.py | /relations/filter.py | AnthonySigogne/HackatonIWCS2017 | MIT | |
2024-11-18T20:50:16.049189+00:00 | 1,628,581,801,000 | a3870eac6e89b2c3ca18a9d9a1a0c1a1ab8489b5 | 3 | {
"blob_id": "a3870eac6e89b2c3ca18a9d9a1a0c1a1ab8489b5",
"branch_name": "refs/heads/main",
"committer_date": 1628581801000,
"content_id": "2c208309d4ea2bf71cc0066179740fcb056ead6d",
"detected_licenses": [
"MIT"
],
"directory_id": "f4cb1f4b83b70da53c365b7373d76cf15c8a6732",
"extension": "py",
"filename": "rosparam_yaml_monkey_patch.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 366685553,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3819,
"license": "MIT",
"license_type": "permissive",
"path": "/src/haroslaunch/rosparam_yaml_monkey_patch.py",
"provenance": "stack-edu-0054.json.gz:582223",
"repo_name": "git-afsantos/haroslaunch",
"revision_date": 1628581801000,
"revision_id": "5c5826683a6979c2249da0969a85b8739c238914",
"snapshot_id": "8de090e5ec1f94aa2fcbbdc125f2833d98cc8127",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/git-afsantos/haroslaunch/5c5826683a6979c2249da0969a85b8739c238914/src/haroslaunch/rosparam_yaml_monkey_patch.py",
"visit_date": "2023-07-04T19:31:51.582563"
} | 2.6875 | stackv2 | # -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
# Copyright © 2021 André Santos
###############################################################################
# Imports
###############################################################################
import base64
import math
import re
try:
from xmlrpc.client import Binary
except ImportError:
from xmlrpclib import Binary
import yaml
###############################################################################
# Constants
###############################################################################
TAG_YAML_BINARY = u'tag:yaml.org,2002:binary'
YAML_RAD = u'!radians'
YAML_DEG = u'!degrees'
RAD_START = 'rad('
DEG_START = 'deg('
RAD_PATTERN = re.compile(r'^rad\([^\)]*\)$')
DEG_PATTERN = re.compile(r'^deg\([^\)]*\)$')
TAG_UNICODE = u'tag:yaml.org,2002:python/unicode'
###############################################################################
# Errors and Exceptions
###############################################################################
class RosParamException(Exception):
pass
###############################################################################
# YAML Binary Data
###############################################################################
def represent_xml_binary(loader, data):
data = base64.b64encode(data.data)
return loader.represent_scalar(TAG_YAML_BINARY, data, style='|')
def construct_yaml_binary(loader, node):
return Binary(loader.construct_yaml_binary(node))
###############################################################################
# YAML Angle Data
###############################################################################
# python-yaml utility for converting rad(num) into float value
def construct_angle_radians(loader, node):
value = loader.construct_scalar(node).strip()
exprvalue = value.replace('pi', 'math.pi')
if exprvalue.startswith(RAD_START):
exprvalue = exprvalue[4:-1]
try:
return float(eval(exprvalue))
except SyntaxError as e:
raise RosParamException('invalid radian expression: ' + str(value))
# python-yaml utility for converting deg(num) into float value
def construct_angle_degrees(loader, node):
value = loader.construct_scalar(node)
exprvalue = value
if exprvalue.startswith(DEG_START):
exprvalue = exprvalue.strip()[4:-1]
try:
return float(exprvalue) * math.pi / 180.0
except ValueError:
raise RosParamException('invalid degree value: ' + str(value))
###############################################################################
# Unicode Strings
###############################################################################
def construct_unicode(loader, node):
return node.value
###############################################################################
# Monkey Patch
###############################################################################
# binary data
yaml.add_representer(Binary, represent_xml_binary)
yaml.add_constructor(TAG_YAML_BINARY, construct_yaml_binary)
yaml.SafeLoader.add_constructor(TAG_YAML_BINARY, construct_yaml_binary)
# radians (allow !radians 2*pi)
yaml.add_constructor(YAML_RAD, construct_angle_radians)
yaml.SafeLoader.add_constructor(YAML_RAD, construct_angle_radians)
yaml.add_implicit_resolver(YAML_RAD, RAD_PATTERN, first=RAD_START)
yaml.SafeLoader.add_implicit_resolver(YAML_RAD, RAD_PATTERN, first=RAD_START)
# degrees (allow !degrees 180)
yaml.add_constructor(YAML_DEG, construct_angle_degrees)
yaml.SafeLoader.add_constructor(YAML_DEG, construct_angle_degrees)
yaml.add_implicit_resolver(YAML_DEG, DEG_PATTERN, first=DEG_START)
yaml.SafeLoader.add_implicit_resolver(YAML_DEG, DEG_PATTERN, first=DEG_START)
# unicode
yaml.SafeLoader.add_constructor(TAG_UNICODE, construct_unicode)
| 110 | 33.7 | 79 | 13 | 697 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xmlrpc_65c0b5981fc70e5c_1f26fec7", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xmlrpc", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 15, "line_end": 15, "column_start": 5, "column_end": 37, "code_snippet": "requires login"}, "cwe_id": "CWE-776: Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://pypi.org/project/defusedxml/", "title": null}, {"url": "https://docs.python.org/3/library/xml.html#xml-vulnerabilities", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xmlrpc", "path": "/tmp/tmppq52ww6s/65c0b5981fc70e5c.py", "start": {"line": 15, "col": 5, "offset": 308}, "end": {"line": 15, "col": 37, "offset": 340}, "extra": {"message": "Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead.", "metadata": {"cwe": ["CWE-776: Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion')"], "owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "source-rule-url": "https://github.com/PyCQA/bandit/blob/07f84cb5f5e7c1055e6feaa0fe93afa471de0ac3/bandit/blacklists/imports.py#L160", "references": ["https://pypi.org/project/defusedxml/", "https://docs.python.org/3/library/xml.html#xml-vulnerabilities"], "category": "security", "technology": ["python"], "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-xmlrpc_65c0b5981fc70e5c_80d06e84", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xmlrpc", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 17, "line_end": 17, "column_start": 5, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": "CWE-776: Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://pypi.org/project/defusedxml/", "title": null}, {"url": "https://docs.python.org/3/library/xml.html#xml-vulnerabilities", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xmlrpc", "path": "/tmp/tmppq52ww6s/65c0b5981fc70e5c.py", "start": {"line": 17, "col": 5, "offset": 365}, "end": {"line": 17, "col": 33, "offset": 393}, "extra": {"message": "Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead.", "metadata": {"cwe": ["CWE-776: Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion')"], "owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "source-rule-url": "https://github.com/PyCQA/bandit/blob/07f84cb5f5e7c1055e6feaa0fe93afa471de0ac3/bandit/blacklists/imports.py#L160", "references": ["https://pypi.org/project/defusedxml/", "https://docs.python.org/3/library/xml.html#xml-vulnerabilities"], "category": "security", "technology": ["python"], "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.eval-detected_65c0b5981fc70e5c_7f649371", "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": 22, "column_end": 37, "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/65c0b5981fc70e5c.py", "start": {"line": 66, "col": 22, "offset": 1999}, "end": {"line": 66, "col": 37, "offset": 2014}, "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"}}}] | 3 | true | [
"CWE-776",
"CWE-776",
"CWE-95"
] | [
"rules.python.lang.security.use-defused-xmlrpc",
"rules.python.lang.security.use-defused-xmlrpc",
"rules.python.lang.security.audit.eval-detected"
] | [
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"MEDIUM"
] | [
15,
17,
66
] | [
15,
17,
66
] | [
5,
5,
22
] | [
37,
33,
37
] | [
"A04:2017 - XML External Entities (XXE)",
"A04:2017 - XML External Entities (XXE)",
"A03:2021 - Injection"
] | [
"Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead.",
"Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead.",
"Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If... | [
7.5,
7.5,
5
] | [
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"HIGH"
] | rosparam_yaml_monkey_patch.py | /src/haroslaunch/rosparam_yaml_monkey_patch.py | git-afsantos/haroslaunch | MIT | |
2024-11-18T20:50:19.330606+00:00 | 1,610,889,042,000 | e2d466b0e7e5fe875cefdc1b1b3f55ebe1e0cc38 | 3 | {
"blob_id": "e2d466b0e7e5fe875cefdc1b1b3f55ebe1e0cc38",
"branch_name": "refs/heads/master",
"committer_date": 1610889042000,
"content_id": "3efb8f39c80ec8896a91a7872354c8298a610e73",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4e5d4287404c640814bfd20b11cca8afece070bc",
"extension": "py",
"filename": "datasets_xml.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 330392427,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5276,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/SSD/datasets_xml.py",
"provenance": "stack-edu-0054.json.gz:582265",
"repo_name": "PieceZhang/face_detect_yolov4_yolov4tiny_ssd",
"revision_date": 1610889042000,
"revision_id": "81f29c541d694acdc63e5922b46f135ed62ef94d",
"snapshot_id": "46289fa8c39b2bed76bb50455c2821c10bee0630",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/PieceZhang/face_detect_yolov4_yolov4tiny_ssd/81f29c541d694acdc63e5922b46f135ed62ef94d/SSD/datasets_xml.py",
"visit_date": "2023-02-13T16:41:51.354875"
} | 2.71875 | stackv2 | try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
import cv2
import os
import shutil
import random
import colorsys
import matplotlib.pyplot as plt
import matplotlib.image as imgplt
import numpy as np
def convert(s, box):
"""
:param s: 图像总大小,二维元组或列表 (w, h)
:param box: 四维元组或列表 (xmin, xmax, ymin, ymax)
:return: (x, y, w, h)
"""
dw = 1. / s[0]
dh = 1. / s[1]
x = (box[0] + box[1]) / 2.0
y = (box[2] + box[3]) / 2.0
w = box[1] - box[0]
h = box[3] - box[2]
x = x * dw
w = w * dw
y = y * dh
h = h * dh
return x, y, w, h
def de_convert(x, y, w, h) -> list:
"""
:return: box (xmin, ymin, xmax, ymax) 注意顺序
"""
s = [500, 500]
dw = 1. / s[0]
dh = 1. / s[1]
x = x / dw
w = w / dw
y = y / dh
h = h / dh
box = [0, 0, 0, 0]
box[0] = int((2 * x - w) / 2)
box[2] = int((2 * x + w) / 2)
box[1] = int((2 * y - h) / 2)
box[3] = int((2 * y + h) / 2)
return box
def draw(image, box):
"""
:param image: 图片路径
:param box: 左上和右下坐标 (xmin, ymin, xmax, ymax) 注意顺序!
:return: None
"""
image = imgplt.imread(image)
assert image is not None, 'Image is not found, No such file or directory'
# plt.imshow(image)
# plt.show()
hsv_tuples = [(1.0 * x / 1, 1., 1.) for x in range(1)]
colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors))
random.seed(0)
random.shuffle(colors)
random.seed(None)
cv2.rectangle(image, (box[0], box[1]), (box[2], box[3]), colors[0], 2)
plt.imshow(image)
plt.show()
class BboxError(object):
def __init__(self):
self.error_list = []
def error_process(self, num, name):
if num[0] >= num[2] or num[1] >= num[3]:
tempt = num[0:2]
num[0] = num[2]
num[1] = num[3]
num[2] = tempt[0]
num[3] = tempt[1]
for elem in num:
if elem < 0:
self.error_list.append(name)
elif elem > 500:
self.error_list.append(name)
return num
def error_summary(self):
print('[INFO] total error: {}'.format(len(self.error_list)))
workspace_dir = 'D:/D_Python code/darknet-master-opencv340-cuda10.1/build/darknet/x64/data/VOCdevkit/VOC2007'
save_image_dir = workspace_dir + '/JPEGImages'
save_xml_dir = workspace_dir + '/Annotations'
save_label_dir = workspace_dir + '/labels'
if __name__ == '__main__':
assert os.path.isdir(workspace_dir), "[ERROR] workspace_dir:{} is not found!".format(workspace_dir)
assert os.path.isdir(save_image_dir), "[ERROR] save_image_dir:{} is not found!".format(save_image_dir)
assert os.path.isdir(save_xml_dir), "[ERROR] save_xml_dir:{} is not found!".format(save_xml_dir)
assert os.path.isdir(save_label_dir), "[ERROR] save_label_dir:{} is not found!".format(save_label_dir)
print("[INFO] loading image files into index...")
image_list = os.listdir(save_image_dir)
label_list = os.listdir(save_label_dir)
assert len(image_list) == len(label_list), "[ERROR] the amounts of images and labels are not equal!"
print("[INFO] load {} files in total! ".format(len(image_list)))
# convert label to xml
error = BboxError()
print('\n=================================')
for label in label_list:
print('[INFO] converting: {}'.format(label))
with open(save_label_dir + '/' + label, 'r') as f:
data = f.read()
# 从label提取bbox
data = list(map(float, data[2:-1].split()))
# bbox逆转换
data = de_convert(data[0], data[1], data[2], data[3])
# 处理错误
data = error.error_process(data, os.path.splitext(label)[0])
# draw(save_image_dir + '/%s.jpg' % os.path.splitext(label)[0], data)
# 从sample模板复制sml
shutil.copy(workspace_dir + '/sample.xml', save_xml_dir + '/%s.xml' % os.path.splitext(label)[0])
# 读取xml
tree = ET.ElementTree(file=save_xml_dir + '/%s.xml' % os.path.splitext(label)[0])
# 获取根节点
child = tree.getroot()
child[1].text = os.path.splitext(label)[0] + '.jpg' # filename
child[4][0].text = child[4][1].text = '500' # size-width/height
child[4][2].text = '3' # size-depth
child[6][0].text = 'face' # object-name
child[6][4][0].text = str(data[0])
child[6][4][1].text = str(data[1])
child[6][4][2].text = str(data[2])
child[6][4][3].text = str(data[3]) # bbox
tree.write(save_xml_dir + '/%s.xml' % os.path.splitext(label)[0], encoding='UTF-8')
print('[INFO] convert complete!')
print('\n=================================')
# 处理错误
error.error_summary()
for f in error.error_list:
print('[INFO] delet {}'.format(f))
os.remove(save_xml_dir + '/{}.xml'.format(f))
# [INFO] delet 2546
# [INFO] delet 3494
# [INFO] delet 4188
# [INFO] delet 5392
# [INFO] delet 6476
# [INFO] delet 7687
# total: 9766-6=9760
# 1003?
| 159 | 31.36 | 109 | 19 | 1,647 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_c6ef61b9851aa65e_8f861a69", "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": 5, "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/c6ef61b9851aa65e.py", "start": {"line": 2, "col": 5, "offset": 9}, "end": {"line": 2, "col": 40, "offset": 44}, "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_c6ef61b9851aa65e_9deff8c0", "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": 4, "line_end": 4, "column_start": 5, "column_end": 39, "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/c6ef61b9851aa65e.py", "start": {"line": 4, "col": 5, "offset": 69}, "end": {"line": 4, "col": 39, "offset": 103}, "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_c6ef61b9851aa65e_314140e2", "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": 118, "line_end": 118, "column_start": 14, "column_end": 53, "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/c6ef61b9851aa65e.py", "start": {"line": 118, "col": 14, "offset": 3606}, "end": {"line": 118, "col": 53, "offset": 3645}, "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"
] | [
2,
4
] | [
2,
4
] | [
5,
5
] | [
40,
39
] | [
"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"
] | datasets_xml.py | /SSD/datasets_xml.py | PieceZhang/face_detect_yolov4_yolov4tiny_ssd | Apache-2.0 | |
2024-11-18T20:50:19.458264+00:00 | 1,415,012,218,000 | 55b050811d04da4dfa698567de9dba4fc3635bc9 | 3 | {
"blob_id": "55b050811d04da4dfa698567de9dba4fc3635bc9",
"branch_name": "refs/heads/master",
"committer_date": 1415012218000,
"content_id": "2138eb7d26f772c0ae079197ead075b0dd552e3a",
"detected_licenses": [
"MIT"
],
"directory_id": "c890c8077841b19d50999c86290f5588bac3aa03",
"extension": "py",
"filename": "handler.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 25904005,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2212,
"license": "MIT",
"license_type": "permissive",
"path": "/api/handler.py",
"provenance": "stack-edu-0054.json.gz:582267",
"repo_name": "similitude/sumo-simmer",
"revision_date": 1415012218000,
"revision_id": "5b0a5e4324204555aa09252ab3983a987f9888f2",
"snapshot_id": "75f83e074b26a55c243a99481429ba4844fef564",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/similitude/sumo-simmer/5b0a5e4324204555aa09252ab3983a987f9888f2/api/handler.py",
"visit_date": "2020-05-19T19:55:30.497128"
} | 2.625 | stackv2 | import subprocess
import uuid
from api.util import SECONDS_IN_HOUR, build_clargs, build_data_filename, \
generate_output_spec, generate_random_routes, write_file
# The command to execute SUMO from the command line.
COMMAND = 'sumo'
class SumoServiceHandler():
"""
Implements the SumoService interface.
"""
def call(self, args):
"""
Invokes SUMO from the command line.
Parameters:
- args: A dictionary of the command line arguments.
"""
job = uuid.uuid4()
if '--additional-files' not in args:
args['--additional-files'] = build_data_filename(job, 'additional')
out_path = build_data_filename(job, 'output')
write_file(args['--additional-files'], generate_output_spec(out_path))
args = [COMMAND] + build_clargs(args)
print('Calling SUMO with arguments:\n%s' % ' '.join(args))
subprocess.call(args)
# If there was any output to a file, include that too.
with open(out_path) as f:
return f.read()
def randomHourMinutes(self, network):
"""
Simulates traffic for an hour with random trips on the given network,
with minutely output.
Parameters:
- network: The contents of the .net.xml file.
"""
job = uuid.uuid4()
types = ('network', 'routes', 'additional', 'output')
(net_file_path, route_file_path, adtl_file_path, out_file_path) = \
[build_data_filename(job, t) for t in types]
write_file(net_file_path, network)
generate_random_routes(job)
write_file(adtl_file_path, generate_output_spec(out_file_path))
args = {
'--net-file': net_file_path, # Network input file.
'--route-files': route_file_path, # Route input file.
'--additional-files': adtl_file_path, # Output format spec.
'--begin': 0, # Time to begin the simulation.
'--end': SECONDS_IN_HOUR, # Time to end the simulation.
'--time-to-teleport': -1, # Disable teleporting for stuck vehicles.
'-W': None, # Disable warning messages.
}
return self.call(args)
| 67 | 32.01 | 80 | 13 | 491 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_39fe8d913df8542f_d42c8e5c", "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": 34, "line_end": 34, "column_start": 9, "column_end": 30, "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/39fe8d913df8542f.py", "start": {"line": 34, "col": 9, "offset": 913}, "end": {"line": 34, "col": 30, "offset": 934}, "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_39fe8d913df8542f_9e4b4343", "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": 34, "line_end": 34, "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/39fe8d913df8542f.py", "start": {"line": 34, "col": 20, "offset": 924}, "end": {"line": 34, "col": 24, "offset": 928}, "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_39fe8d913df8542f_038c4a62", "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": 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/39fe8d913df8542f.py", "start": {"line": 37, "col": 14, "offset": 1012}, "end": {"line": 37, "col": 28, "offset": 1026}, "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"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
34
] | [
34
] | [
9
] | [
30
] | [
"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"
] | handler.py | /api/handler.py | similitude/sumo-simmer | MIT | |
2024-11-18T20:50:27.751891+00:00 | 1,516,810,139,000 | 1856e26f88c5cb61284de20c28afbb59541b82bb | 3 | {
"blob_id": "1856e26f88c5cb61284de20c28afbb59541b82bb",
"branch_name": "refs/heads/master",
"committer_date": 1516810139000,
"content_id": "b4486fa9997a0d1132bac25fec8a80f3f58f101d",
"detected_licenses": [
"MIT"
],
"directory_id": "f5fae97a6b76ff660495ad6107e2563d1b6273d4",
"extension": "py",
"filename": "binding_site_subselection_association.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": 3280,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/sEH-TPPU/binding_site_subselection_association.py",
"provenance": "stack-edu-0054.json.gz:582282",
"repo_name": "Computational-Chemistry-Research/mastic",
"revision_date": 1516810139000,
"revision_id": "58749c40fe364110e3e7be8aa79a89f32d956d09",
"snapshot_id": "e9ec66ff1d4577ac0686ed9eaefe96f48e2270a6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Computational-Chemistry-Research/mastic/58749c40fe364110e3e7be8aa79a89f32d956d09/examples/sEH-TPPU/binding_site_subselection_association.py",
"visit_date": "2021-12-29T19:16:06.075303"
} | 2.609375 | stackv2 | import os.path as osp
import pickle
import numpy as np
from mastic.system import AssociationType
from mastic.molecule import MoleculeTypeAtomSelection
# load the SystemType we will add associations to
system_type_pkl_path = osp.join(".", "sEH_TPPU_SystemType.pkl")
with open(system_type_pkl_path, 'rb') as rf:
sEH_TPPU_SystemType = pickle.load(rf)
# substantiate a crystal structure system so we can figure out where
# the bidning site is
# load the coordinates for the members
member_coords = [np.load(osp.realpath(osp.join('.', 'TPPU_coords.npy'))),
np.load(osp.realpath(osp.join('.', 'sEH_coords.npy')))]
# substantiate the system
cryst_system = sEH_TPPU_SystemType.to_system(member_coords)
# find atoms in the binding site using a cutoff distance from the
# ligand
binding_site_cutoff_dist = 4 #in Angstroms \AA
# find the atoms within this distance
binding_site_atoms = cryst_system.molecules[0].atoms_within_distance(
binding_site_cutoff_dist)
# get the indices of these atoms to define the AssociationType
binding_site_atom_idxs = [cryst_system.molecules[1].atoms.index(atom) for
atom in binding_site_atoms]
# you might also want to get the pdb serial numbers so you can
# visually check to see where these atoms are
binding_site_atom_serials = [atom.atom_type.pdb_serial_number for atom
in binding_site_atoms]
# the selection map tells the association the index of the member and
# the indices of the atoms to include as one component of the
# association. By selection None as the indices no selection will be
# made and the whole molecule will be a component
selection_map = [(1, binding_site_atom_idxs), (0, None)]
# The selection types correspond to the elements in the selection map
# and tell the AssociationType what kind of selection to make on the
# molecule. Setting one of them to None should mean the selection map
# also had no indices selected and it should use the whole system
# member. The MoleculeTypeAtomSelection allows for selection of atoms in a
# Molecule or MoelculeType.
selection_types = [MoleculeTypeAtomSelection, None]
# make the actual association
sehBS_tppu_assoc = AssociationType("sEHBS-TPPU",
system_type=sEH_TPPU_SystemType,
selection_map=selection_map,
selection_types=selection_types
)
# now you can add it to the original SystemType if you want, or you
# can use it to generate interaction classes for a particular
# interaction type (see other examples)
sEH_TPPU_SystemType.add_association_type(sehBS_tppu_assoc)
# then if our interaction is assymetric (which is the case for
# HydrogenBondType) we need to do it the other way around.
selection_map = [(0, None), (1, binding_site_atom_idxs)]
selection_types = [None, MoleculeTypeAtomSelection]
tppu_sehBS_assoc = AssociationType("TPPU-sEHBS",
system_type=sEH_TPPU_SystemType,
selection_map=selection_map,
selection_types=selection_types
)
sEH_TPPU_SystemType.add_association_type(tppu_sehBS_assoc)
| 78 | 41.05 | 74 | 12 | 726 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_805578b50f06ad28_96a458ac", "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": 12, "line_end": 12, "column_start": 27, "column_end": 42, "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/805578b50f06ad28.py", "start": {"line": 12, "col": 27, "offset": 339}, "end": {"line": 12, "col": 42, "offset": 354}, "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"
] | [
12
] | [
12
] | [
27
] | [
42
] | [
"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"
] | binding_site_subselection_association.py | /examples/sEH-TPPU/binding_site_subselection_association.py | Computational-Chemistry-Research/mastic | MIT | |
2024-11-18T20:50:31.979744+00:00 | 1,609,524,101,000 | 237edfce0647b02bea1b37351670ce7222001798 | 2 | {
"blob_id": "237edfce0647b02bea1b37351670ce7222001798",
"branch_name": "refs/heads/master",
"committer_date": 1609524101000,
"content_id": "2594835fcd51a42178c4c5fc8d5b6fb3a835b52b",
"detected_licenses": [
"MIT"
],
"directory_id": "8ce0c003bd995695487163a44afe0a72a5424ba8",
"extension": "py",
"filename": "parse_mbsyncrc.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 285858740,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5098,
"license": "MIT",
"license_type": "permissive",
"path": "/mbsync_watcher/parse_mbsyncrc.py",
"provenance": "stack-edu-0054.json.gz:582327",
"repo_name": "alkim0/mbsync-watcher",
"revision_date": 1609524101000,
"revision_id": "9f68b9f2e33f7affd5d834b992aeefe820d47738",
"snapshot_id": "3a1edecf056fce5d1b7bfb21e2540c1e59c92f4a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/alkim0/mbsync-watcher/9f68b9f2e33f7affd5d834b992aeefe820d47738/mbsync_watcher/parse_mbsyncrc.py",
"visit_date": "2023-02-15T15:23:25.351651"
} | 2.5 | stackv2 | #!/usr/bin/env python
"""
Parse mbsync's config file.
Limitations: Currently does not parse the Patterns for Channels and assumes we
want to perform IDLE with INBOX.
"""
import json
import os
import subprocess
class MbsyncrcError(Exception):
pass
class Mbsyncrc(object):
def __init__(self, config_path):
self._config_path = config_path
self.accounts = {}
self.stores = {}
self.channels = {}
self.groups = {}
self._parse()
def _parse(self):
with open(self._config_path) as f:
self._lines = f.readlines()
self._idx = 0
while self._idx < len(self._lines):
line = self._lines[self._idx].strip()
if line.startswith("IMAPAccount"):
self._parse_imap_account()
elif line.startswith("IMAPStore"):
self._parse_imap_store()
elif line.startswith("Channel"):
self._parse_channel()
elif line.startswith("Group"):
self._parse_group()
else:
# Other stuff we don't care about.
self._idx += 1
def _parse_imap_account(self):
REQUIRED_FIELDS = ("host", "user", "password", "ssl")
name = self._lines[self._idx].strip().split()[1]
data = {"ssl": False}
self.accounts[name] = data
self._idx += 1
while self._idx < len(self._lines):
line = self._lines[self._idx].strip()
if not line:
self._idx += 1
assert all(data[x] is not None for x in REQUIRED_FIELDS)
return
if line.startswith("Host"):
data["host"] = line.split()[1]
elif line.startswith("User"):
data["user"] = line.split()[1]
elif line.startswith("PassCmd"):
data["password"] = (
subprocess.check_output(
line.split(maxsplit=1)[1].strip('"'), shell=True
)
.decode()
.strip()
)
elif line.startswith("Pass"):
data["password"] = line.strip()[1]
elif line.startswith("SSLType"):
ssl_type = line.split()[1]
assert ssl_type in ("STARTTLS", "IMAPS")
data["ssl"] = ssl_type == "IMAPS"
elif line.startswith("AuthMech"):
data["auth"] = line.split()[1]
else:
raise MbsyncrcError(
"Unable to parse line {}: {}".format(self._idx + 1, line)
)
self._idx += 1
def _parse_imap_store(self):
REQUIRED_FIELDS = ("account",)
name = self._lines[self._idx].strip().split()[1]
data = {}
self.stores[name] = data
self._idx += 1
while self._idx < len(self._lines):
line = self._lines[self._idx].strip()
if not line:
self._idx += 1
assert all(data[x] is not None for x in REQUIRED_FIELDS)
return
if line.startswith("Account"):
data["account"] = line.split()[1]
else:
raise MbsyncrcError(
"Unable to parse line {}: {}".format(self._idx + 1, line)
)
self._idx += 1
def _parse_channel(self):
REQUIRED_FIELDS = ("master", "slave")
name = self._lines[self._idx].strip().split()[1]
data = {}
self.channels[name] = data
self._idx += 1
while self._idx < len(self._lines):
line = self._lines[self._idx].strip()
if not line:
self._idx += 1
assert all(data[x] is not None for x in REQUIRED_FIELDS)
return
if line.startswith("Master"):
data["master"] = line.split()[1].strip(":")
elif line.startswith("Slave"):
data["slave"] = line.split()[1].strip(":")
elif line.startswith("Pattern"):
# TODO: Add patterns for IDLE
pass
else:
raise MbsyncrcError(
"Unable to parse line {}: {}".format(self._idx + 1, line)
)
self._idx += 1
def _parse_group(self):
REQUIRED_FIELDS = ("channels",)
name = self._lines[self._idx].strip().split()[1]
data = {"channels": []}
self.groups[name] = data
self._idx += 1
while self._idx < len(self._lines):
line = self._lines[self._idx].strip()
if not line:
self._idx += 1
assert all(data[x] is not None for x in REQUIRED_FIELDS)
return
if line.startswith("Channel"):
data["channels"].append(line.split()[1])
else:
raise MbsyncrcError(
"Unable to parse line {}: {}".format(self._idx + 1, line)
)
self._idx += 1
| 166 | 29.71 | 78 | 26 | 1,110 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_a22e7e6ecf946037_9790966a", "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": 30, "line_end": 30, "column_start": 14, "column_end": 37, "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/a22e7e6ecf946037.py", "start": {"line": 30, "col": 14, "offset": 522}, "end": {"line": 30, "col": 37, "offset": 545}, "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_a22e7e6ecf946037_d7ef9570", "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": 70, "line_end": 72, "column_start": 21, "column_end": 22, "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/a22e7e6ecf946037.py", "start": {"line": 70, "col": 21, "offset": 1920}, "end": {"line": 72, "col": 22, "offset": 2039}, "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_a22e7e6ecf946037_1316c8a9", "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": 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/tmppq52ww6s/a22e7e6ecf946037.py", "start": {"line": 71, "col": 69, "offset": 2013}, "end": {"line": 71, "col": 73, "offset": 2017}, "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"}}}] | 3 | 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"
] | [
70,
71
] | [
72,
71
] | [
21,
69
] | [
22,
73
] | [
"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_mbsyncrc.py | /mbsync_watcher/parse_mbsyncrc.py | alkim0/mbsync-watcher | MIT | |
2024-11-18T20:50:34.460073+00:00 | 1,418,935,736,000 | 09d9dded102b4dfbd30f9e274853b5e5cbf1b522 | 3 | {
"blob_id": "09d9dded102b4dfbd30f9e274853b5e5cbf1b522",
"branch_name": "refs/heads/master",
"committer_date": 1418935736000,
"content_id": "596be9caca45badf63e005398c4491dbec31d9ad",
"detected_licenses": [
"MIT"
],
"directory_id": "54fc1082676c0f4da82dc8eaa01c98ba50b4f43b",
"extension": "py",
"filename": "server.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": 2763,
"license": "MIT",
"license_type": "permissive",
"path": "/server.py",
"provenance": "stack-edu-0054.json.gz:582339",
"repo_name": "vhp-jjh/online-tag",
"revision_date": 1418935736000,
"revision_id": "f0629157b3cd2f845ea2bf8b0a16a70704483983",
"snapshot_id": "cec544252ecdaebc67cd9c1eca98e96f8e11013e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vhp-jjh/online-tag/f0629157b3cd2f845ea2bf8b0a16a70704483983/server.py",
"visit_date": "2020-03-30T13:53:31.751649"
} | 2.671875 | stackv2 | import socket
import pickle
import time
import constants
from utils import printd
from engine import Engine
import random
import sys
import time
CLOSE = "close"
class Server:
def __init__(self, engine, port):
self.engine = engine
self.s = socket.socket(constants.S_FAMILY, constants.S_TYPE)
self.port = port
self.s.bind(("", self.port)) # "" = all available interfaces
self.addresses = [] # List of addresses
self.addr_to_player_id_map = {} #for tag, id = color
def wait_for_players(self, n_players):
for n_joined in range(n_players):
print("Waiting for %d players to connect..." % (n_players - n_joined))
data = ""
while data == "" or data == None:
data, addr = self.s.recvfrom(1024)
self.addresses.append(addr)
self.addr_to_player_id_map[addr] = self.engine.add_player()
def send_data(self, data):
msg = pickle.dumps(data)
for addr in self.addresses:
# DROP_RATE is zero if DEBUG is set to false
if random.random() >= constants.DROP_RATE:
self.s.sendto(msg, addr)
else:
printd("SERVER: dropping packet")
def start_game(self):
print("SERVER: Game started!")
for addr in self.addresses:
game_data = self.engine.get_game_start_data()
game_data.set_player_id(self.addr_to_player_id_map[addr])
self.s.sendto(pickle.dumps(game_data), addr)
self.s.settimeout(constants.S_TIMEOUT)
def send_update_to_clients(self):
update = self.engine.get_game_update()
self.send_data(update)
def get_updates_from_clients(self):
waiting_for = list(self.addresses) # to get a copy not pointer
# for i in range(len(self.addresses)): #TODO: maybe make this smarter
data = ""
while len(waiting_for) > 0:
try:
data, addr_recv = self.s.recvfrom(1024)
except socket.timeout:
printd("SERVER: no data received")
if len(data) > 0 and addr_recv in waiting_for:
player_update = pickle.loads(data)
player_id = self.addr_to_player_id_map[addr_recv]
status_message = self.engine.update_player(player_id, player_update)
if status_message == constants.GAME_OVER_MESSAGE:
self.close_conns()
sys.exit()
waiting_for.remove(addr_recv)
self.engine.update_positions()
def close_conns(self):
self.send_data(CLOSE)
def play(self):
while True:
self.send_update_to_clients()
self.get_updates_from_clients()
if __name__ == "__main__":
random.seed(time.time())
server = Server(Engine(), constants.SERVER_PORT)
server.wait_for_players(constants.N_PLAYERS)
time.sleep(1)
server.start_game()
server.play()
| 87 | 29.76 | 76 | 15 | 641 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.network.avoid-bind-to-all-interfaces_e4219e007ec7dee8_42f56276", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.network.avoid-bind-to-all-interfaces", "finding_type": "security", "severity": "low", "confidence": "high", "message": "Running `socket.bind` to 0.0.0.0, or empty string could unexpectedly expose the server publicly as it binds to all available interfaces. Consider instead getting correct address from an environment variable or configuration file.", "remediation": "", "location": {"file_path": "unknown", "line_start": 16, "line_end": 18, "column_start": 5, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": "CWE-200: Exposure of Sensitive Information to an Unauthorized Actor", "cwe_name": null, "cvss_score": 3.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.lang.security.audit.network.avoid-bind-to-all-interfaces", "path": "/tmp/tmppq52ww6s/e4219e007ec7dee8.py", "start": {"line": 16, "col": 5, "offset": 242}, "end": {"line": 18, "col": 33, "offset": 356}, "extra": {"message": "Running `socket.bind` to 0.0.0.0, or empty string could unexpectedly expose the server publicly as it binds to all available interfaces. Consider instead getting correct address from an environment variable or configuration file.", "metadata": {"cwe": ["CWE-200: Exposure of Sensitive Information to an Unauthorized Actor"], "owasp": ["A01:2021 - Broken Access Control", "A01:2025 - Broken Access Control"], "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A01_2021-Broken_Access_Control"], "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "HIGH", "impact": "MEDIUM", "confidence": "HIGH"}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e4219e007ec7dee8_bd2a586a", "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": 33, "line_end": 33, "column_start": 11, "column_end": 29, "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/e4219e007ec7dee8.py", "start": {"line": 33, "col": 11, "offset": 889}, "end": {"line": 33, "col": 29, "offset": 907}, "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_e4219e007ec7dee8_19cabff4", "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": 46, "line_end": 46, "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/e4219e007ec7dee8.py", "start": {"line": 46, "col": 21, "offset": 1357}, "end": {"line": 46, "col": 44, "offset": 1380}, "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_e4219e007ec7dee8_55df679c", "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": 63, "line_end": 63, "column_start": 25, "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/e4219e007ec7dee8.py", "start": {"line": 63, "col": 25, "offset": 1972}, "end": {"line": 63, "col": 43, "offset": 1990}, "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.arbitrary-sleep_e4219e007ec7dee8_dc431f45", "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": 85, "line_end": 85, "column_start": 3, "column_end": 16, "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/e4219e007ec7dee8.py", "start": {"line": 85, "col": 3, "offset": 2624}, "end": {"line": 85, "col": 16, "offset": 2637}, "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-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"
] | [
33,
46,
63
] | [
33,
46,
63
] | [
11,
21,
25
] | [
29,
44,
43
] | [
"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"
] | server.py | /server.py | vhp-jjh/online-tag | MIT | |
2024-11-18T20:50:36.848446+00:00 | 1,425,311,891,000 | ae2d1559c56aa8c1f965c618ff651e2f27bdfc67 | 3 | {
"blob_id": "ae2d1559c56aa8c1f965c618ff651e2f27bdfc67",
"branch_name": "refs/heads/master",
"committer_date": 1425311891000,
"content_id": "6e38398c4f8bbbbee413f2b94415db7bf069272d",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "2a882c2537f0a1d1675a84dd909fcc2369dad3ed",
"extension": "py",
"filename": "BlastXMLParser.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 13590896,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6374,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/hsp_tiler/BlastXMLParser.py",
"provenance": "stack-edu-0054.json.gz:582365",
"repo_name": "edraizen/hsp_tiler",
"revision_date": 1425311891000,
"revision_id": "091bc1eafdaf2d8eac3ab4cfeadde1dd3071edfb",
"snapshot_id": "1a1360af88c34fa02f7926cbee28752b9a89f138",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/edraizen/hsp_tiler/091bc1eafdaf2d8eac3ab4cfeadde1dd3071edfb/hsp_tiler/BlastXMLParser.py",
"visit_date": "2021-01-23T13:22:34.303530"
} | 2.78125 | stackv2 | # Author: Eli Draizen
# Date 5-1-14
# File: BlastXMLParser.py
#Standard libraries
import sys
import xml.etree.cElementTree as ET
import re
from math import exp
#Custom libraries
from Parser import Parser, Match, Matches
class HSP(Match):
"""Holds information about a given High-scoring Sequence Pair (HSP)
returned from BLASTX.
"""
def __init__(self, hsp, rapsearch=False):
"""Initialise an Hsp object, with the XML
representation of the hsp, and a contig.
Parameter:
__________
hsp : Element object containing HSP information
"""
frame = int(hsp.find('Hsp_query-frame').text)
if rapsearch:
#1 = frames 0,1,2; -1 = frames 3,4,5
self.frame = frame % 3
self.strand = 1 if frame < 3 else -1
else:
# 1 = frames 1,2,3; -1 = frames -1,-2,-3
self.frame = abs(frame)
self.strand = 1 if 0<frame<=3 else -1
self.query_start = int(hsp.find('Hsp_query-from').text)-1 #position in nts relative to query
self.query_end = int(hsp.find('Hsp_query-to').text)
self.hit_start = int(hsp.find('Hsp_hit-from').text)-1 #position in aas relative to hit
self.hit_end = int(hsp.find('Hsp_hit-to').text)
try:
self.evalue = float(hsp.find('Hsp_evalue').text)
except:
try:
self.evalue = exp(float(hsp.find('Hsp_log-evalue').text))
except:
raise RuntimeError("XML file must be from BLASTX or RAPSearch2")
self.score = float(hsp.find('Hsp_score').text)
self.bitscore = float(hsp.find('Hsp_bit-score').text)
self.hitID = hsp.find("hitID").text
self.used = False # True marks hsps that have already been incorporated into the tile
self.num = int(hsp.find('Hsp_num').text)
self.query_seq = hsp.find('Hsp_qseq').text
class BlastXMLParser(Parser):
"""Parses BLAST XML files and easily separates Iterations, Hits, and HSPs without
loading all of the data into memory. Also can filter results by evalue or
Taxonmic information.
Reinventing the wheel. Biopython may be more robust, but this does the job.
"""
def __init__(self, *args, **kwds): #blast, allHits=False, evalue=1e-10, taxFilter=None, taxFilterType=0):
"""Intialise a BLAST XML parser.
"""
#Initialize Parser super class
Parser.__init__(self, *args, **kwds)
#Build iter to loop over XML
self.context = iter(ET.iterparse(self.infile, events=("start", "end")))
#Boolean to allow hits to be returned
self.runHSP = True
#Save the current contig, or queryID
self.queryID = None
#The number of Hits that have been processed
self.numHits = 0
#File came form RAPSearch2?
self.rapsearch = kwds.get("rapsearch", False)
#Start initial parsing
event, root = self.context.next()
if root.tag not in ["BlastOutput", "Output"]:
raise RuntimeError("This is not a valid BLAST XML file or RAPSearch2 XML file")
elif root.tag == "Output":
self.rapsearch = True
#Start looping over data until we get to first iteration
for event, elem in self.context:
if event == "start" and elem.tag == "Iteration":
break
def parse(self):
"""Real work done here. Combine the query with its HSPs
"""
for query in self.parseQuery():
yield Matches(query, self.parseHsp())
def parseQuery(self):
"""Parse each query (i.e. Iteration and Hits), but only use first hit unless allHits is specified
Sets up parser for user to select HSP with the parseHSP method.
Return: Contig name or QueryID of the current query.
"""
for event, elem in self.context:
if event == "end" and elem.tag == "Iteration_query-def":
#Save current contig or queryID and
self.queryID = elem.text
yield self.queryID
if self.runHSP and event == "start" and elem.tag == "Hit":
self.runHSP = self.allHits #Continue looking for hits if allHits is True
if not self.runHSP and event == "end" and elem.tag == "Iteration_hits":
self.runHSP = True
def parseHsp(self):
"""Process each HSP for a given hit. Must be called during parseQuery.
Return: XML object of HSP. If allHits is specified, all HSPS for every
hit are returned for each contig, otehrwise only the HSP within the first
hit are used.
"""
#Decide whether the current HSP is returned
returnHsp = False
#Save ID for hit
hitID = None
for event, elem in self.context:
if event == "end" and elem.tag == "Hit_id":
try:
#Assume NCBI headers
hitID = elem.text.split("|")[1] #field is 'gi|XXXXX|ref|abcd', save XXXX
except:
hitID = elem.text #just use the whole hit id
elif event == "end" and elem.tag == "Hit_def":
#Get species and genus for use with filter
#One more hit has been seen
self.numHits += 1
if hitID is None:
#RAPSearch doesn't use Hit_id
hitID = elem.text
#Returns all HSP if there is no fitler, else only return HSPS that do not contain filter
returnHsp = self._filterTaxa(elem.text) if self.taxFilter else True
elif event == "end" and elem.tag == "Hsp_evalue" and float(elem.text) > self.evalue:
#Don't return HSP is evalue is above cutoff
returnHsp = False
elif event == "end" and elem.tag == "Hsp_log-evalue":
#RAPSearch2 uses log(evalue)
evalue = exp(float(elem.text))
elem.text = evalue
if evalue > self.evalue:
returnHsp = False
elif returnHsp and event == "end" and elem.tag == "Hsp":
#Add the hitID to current HSP to process later
hitElement = ET.SubElement(elem, "hitID")
hitElement.text = hitID
yield HSP(elem, rapsearch=self.rapsearch)
elif not self.allHits and event == "end" and elem.tag == "Hit_hsps":
#Stop after 1st HSP hits are finished
break
elif self.allHits and event == "end" and elem.tag == "Iteration_hits":
#Stop after all of HSPs from every hit are finished
break
if __name__ == "__main__":
try:
blast = open(sys.argv[1])
except:
raise RuntimeError("Cannot open BLAST XML file")
parser = BlastXMLParser(blast)
for queryID in parser.parseQuery():
print queryID
for hsp in parser.parseHsp():
print "\t", hsp
print "\t\t", abs(int(hsp.find('Hsp_query-frame').text))
print "\t\t", int(hsp.find('Hsp_query-from').text) #position in nts relative to query
print "\t\t", int(hsp.find('Hsp_query-to').text)
| 187 | 33.09 | 106 | 21 | 1,825 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_1135acddc02f49be_5932b5e1", "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": 7, "line_end": 7, "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/1135acddc02f49be.py", "start": {"line": 7, "col": 1, "offset": 94}, "end": {"line": 7, "col": 36, "offset": 129}, "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_1135acddc02f49be_d0c10dc9", "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": 174, "line_end": 174, "column_start": 3, "column_end": 28, "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/1135acddc02f49be.py", "start": {"line": 174, "col": 3, "offset": 5936}, "end": {"line": 174, "col": 28, "offset": 5961}, "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_1135acddc02f49be_3b7efc2a", "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": 174, "line_end": 174, "column_start": 11, "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/1135acddc02f49be.py", "start": {"line": 174, "col": 11, "offset": 5944}, "end": {"line": 174, "col": 28, "offset": 5961}, "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"
] | [
"rules.python.lang.security.use-defused-xml"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
7
] | [
7
] | [
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"
] | BlastXMLParser.py | /hsp_tiler/BlastXMLParser.py | edraizen/hsp_tiler | BSD-3-Clause | |
2024-11-18T20:50:36.907279+00:00 | 1,608,332,487,000 | 9c8a268e721d92955b40c97d0ecc19b68e98ed9c | 2 | {
"blob_id": "9c8a268e721d92955b40c97d0ecc19b68e98ed9c",
"branch_name": "refs/heads/main",
"committer_date": 1608332487000,
"content_id": "a51545f0eda3f0a64c3311d0f5cce444acd7270e",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "e5c2d54924b7149e1f97762d35290ea6885d7a0c",
"extension": "py",
"filename": "sbom_gen.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 322721783,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 15517,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/sbom_gen.py",
"provenance": "stack-edu-0054.json.gz:582366",
"repo_name": "tidepool-org/sbom_gen",
"revision_date": 1608332487000,
"revision_id": "823f91c8fbbfe10a888873ce29634b69ee7542e0",
"snapshot_id": "329be75b3910300e0f476ca57aea50fd3eb123a5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tidepool-org/sbom_gen/823f91c8fbbfe10a888873ce29634b69ee7542e0/sbom_gen.py",
"visit_date": "2023-02-03T06:50:19.549263"
} | 2.328125 | stackv2 | #!/usr/bin/env python3
"""
SBOM Generator
This Python script reads all dependencies of a project and produces a
software bill-of-materials (SBOM) artifacts from them.
Copyright (c) 2020, Tidepool Project
All rights reserved.
"""
import sys
import os
import logging
import logging.config
import argparse
import subprocess
import requests
import hashlib
import uuid
import re
import json
from enum import Enum, unique
from functools import cached_property
from dotenv import load_dotenv
from typing import List
# from https://pypi.org/project/spdx-tools/
from spdx.document import Document, License, LicenseConjunction, ExtractedLicense
from spdx.version import Version
from spdx.creationinfo import Person, Organization, Tool
from spdx.review import Review
from spdx.package import Package, ExternalPackageRef
from spdx.file import File, FileType
from spdx.checksum import Algorithm
from spdx.utils import SPDXNone, NoAssert, UnKnown
from spdx.writers.tagvalue import write_document as WriteTagValue
from spdx.writers.rdf import write_document as WriteRdf
from spdx.writers.json import write_document as WriteJson
from spdx.writers.yaml import write_document as WriteYaml
VERSION = '1.0'
load_dotenv()
logging.basicConfig(format = "%(asctime)s %(levelname)s [%(module)s] %(message)s", datefmt = "%Y-%m-%dT%H:%M:%S", encoding = "utf-8", level = logging.INFO)
logger = logging.getLogger('sbom')
def exec(cmd: str, cwd: str = None) -> str:
"""
Execute a shell command and capture stdout and stderr as string
"""
# logger.debug(f"executing [{cmd}] in [{cwd}]")
return subprocess.check_output(cmd, encoding = "utf-8", stderr = subprocess.STDOUT, shell = True, text = True, cwd = cwd)
class SPDX():
"""
SPDX helper methods
"""
@staticmethod
def id(tag: str) -> str:
"""
Generate a SPDX identifier "SPDXRef-{tag}"
"""
return f"SPDXRef-{tag}"
@staticmethod
def hash_id(tag: str) -> str:
"""
Generate a unique SPDX identifier "SPDXRef-{tag}" by taking the first 10 digits of a hashed tag
"""
return SPDX.id(SPDX.sha256(tag).value[:10])
@staticmethod
def document_id() -> str:
"""
Return the SPDX identifier for a document: "SPDXRef-DOCUMENT"
"""
return SPDX.id("DOCUMENT")
@staticmethod
def document_namespace(name: str) -> str:
"""
Return the SPDX document namespace for a document: "http://[CreatorWebsite]/[pathToSpdx]/[DocumentName]-[UUID]"
"""
return f"http://tidepool.org/spdx/spdxdocs/{name}-{uuid.uuid4()}"
@staticmethod
def package_id(name: str) -> str:
"""
Return the unique SPDX identifier for a package: "SPDXRef-{package_name}"
"""
return SPDX.hash_id(name)
@staticmethod
def file_id(filename: str) -> str:
"""
Return the unique SPDX identifier for a file: "SPDXRef-{filename}"
"""
return SPDX.hash_id(filename)
@staticmethod
def file_type(abs_path: str) -> FileType:
"""
Determine SPDX file type
"""
type = exec(f"file --brief --mime-type '{abs_path}'")
if type.startswith("text") or type.startswith("application"):
return FileType.SOURCE
elif type.startswith("image"):
return FileType.BINARY
return FileType.OTHER
@staticmethod
def file_checksum(abs_path: str) -> Algorithm:
"""
Calculate the checksum (SHA1) of a file
"""
sha1 = hashlib.sha1()
with open(abs_path, "rb") as file:
while True:
chunk = file.read(32 * 1024)
if not chunk:
break
sha1.update(chunk)
return Algorithm("SHA1", sha1.hexdigest())
@staticmethod
def file_copyright(abs_path: str) -> str:
try:
with open(abs_path, "r") as file:
pattern = re.compile(r"\s*(Copyright.+\d+.+)\s*")
for line in file:
match = pattern.match(line)
if match:
return match.group(1).strip()
except IOError:
return None
@staticmethod
def sha1(data: str) -> Algorithm:
"""
Calculate SHA1 hash over a string
"""
hasher = hashlib.sha1()
hasher.update(data.encode("utf-8"))
return Algorithm("SHA1", hasher.hexdigest())
@staticmethod
def sha256(data: str) -> Algorithm:
"""
Calculate SHA256 hash over a string
"""
hasher = hashlib.sha256()
hasher.update(data.encode("utf-8"))
return Algorithm("SHA256", hasher.hexdigest())
class SubModule:
def __init__(self, source_root: str, rel_path: str, version: str, commit: str, status: str, repo_url: str):
self.source_root = source_root
self.rel_path = rel_path
self.version = version
self.commit = commit
self.status = status
self.repo_url = repo_url.replace("git@github.com:", "").replace("https://github.com/", "").replace(".git", "")
@property
def org(self) -> str:
"""
Return the organization part of a repo name (e.g. "tidepool-org" from "tidepool-org/LoopWorkspace")
"""
return self.repo_url.split('/')[0]
@property
def repo(self) -> str:
"""
Return the repo part of a repo name (e.g. "LoopWorkspace" from "tidepool-org/LoopWorkspace")
"""
return self.repo_url.split('/')[1]
@property
def name(self) -> str:
"""
Return the name of a repo from a submodule name (e.g. "TrueTime" from "Common/TrueTime")
"""
return os.path.basename(self.rel_path)
@property
def abs_path(self) -> str:
"""
Return the absolute file path of he repo
"""
return os.path.join(self.source_root, self.rel_path)
@property
def description(self) -> str:
"""
Return the description of a repo
"""
return self.info.get('description')
@cached_property
def copyright(self) -> str:
"""
Return the copyright text of a repo
Read the LICENSE or LICENSE.md file
"""
logger.debug(f"scanning {self.name} for copyright text")
for license_file in [ "LICENSE", "LICENSE.md" ]:
match = SPDX.file_copyright(os.path.join(self.abs_path, license_file))
if match:
return match
return ''
@property
def license(self) -> str:
"""
Return the license of a repo
"""
return (self.info.get('license') or { }).get('spdx_id')
@property
def homepage_url(self) -> str:
"""
Return the homepage URL of a repo
"""
return self.info.get('homepage') or self.info.get('html_url')
@property
def commit_url(self) -> str:
"""
Return the commit URL of a repo
"""
return f"{self.info.get('html_url')}/tree/{self.commit}"
@cached_property
def info(self, auth = None) -> dict:
"""
Fetch the information of a repo
Requires authentication credentials (username, personal access token) for private repos,
and to avoid rate-limiting.
"""
if not auth:
auth = (os.environ.get('GITHUB_USERNAME'), os.environ.get('GITHUB_TOKEN'))
if auth == (None, None):
auth = None
url = f"https://api.github.com/repos/{self.org}/{self.repo}"
logger.debug(f"fetching repo information from {url}")
res = requests.get(url, auth = auth)
if res.ok:
return res.json()
return { }
def __repr__(self) -> str:
"""
Dump the details of this repo
"""
return "\n".join([
f"submodule: {self.name}",
f" path: {self.rel_path}",
f" description: {self.description}",
f" copyright: {self.copyright}",
f" version: {self.version}",
f" license: {self.license}",
f" commit: {self.commit}",
f" status: {self.status}",
f" homepage_url: {self.homepage_url}",
f" commit_url: {self.commit_url}",
])
def scan(self) -> Document:
"""
Scan the submodule to produce a SPDX document
"""
logger.info(f"scanning {self.abs_path}")
doc = Document(name = self.name, spdx_id = SPDX.document_id(), version = Version(1, 2))
doc.namespace = SPDX.document_namespace(self.name)
doc.data_license = License.from_identifier("CC0-1.0")
doc.creation_info.add_creator(Organization("Tidepool Project", "security@tidepool.org"))
doc.creation_info.add_creator(Tool(f"Tidepool SBOM Generator v{VERSION}"))
doc.creation_info.set_created_now()
doc.creation_info.comment = f"This SPDX file was generated automatically using a Python script and the 'spdx-tools' package (https://github.com/spdx/tools-python)"
package = Package(name = self.name, spdx_id = SPDX.package_id(self.name), version = self.version, download_location = self.commit_url)
package.description = self.description
package.homepage = self.homepage_url
package.supplier = NoAssert()
package.originator = NoAssert()
package.source_info = f"Scanned from {self.rel_path} and {self.homepage_url}"
package.conc_lics = License.from_identifier(self.license)
package.license_declared = License.from_identifier(self.license)
package.cr_text = self.copyright or NoAssert()
package.files_analyzed = True
package.licenses_from_files = [ NoAssert() ]
total_size = 0
for root, dirs, files in os.walk(self.abs_path, topdown = True):
for filename in files:
abs_path = os.path.join(root, filename)
rel_path = os.path.join(".", os.path.relpath(abs_path, start = self.abs_path))
logger.debug(f"scanning {rel_path}")
file = File(rel_path, spdx_id = SPDX.file_id(abs_path))
file.type = SPDX.file_type(abs_path)
file.chk_sum = SPDX.file_checksum(abs_path)
total_size += os.path.getsize(abs_path)
file.conc_lics = NoAssert()
file.add_lics(NoAssert())
if file.type == FileType.SOURCE:
copyright = SPDX.file_copyright(abs_path)
file.copyright = copyright or SPDXNone()
else:
file.copyright = NoAssert()
package.add_file(file)
package.verif_code = package.calc_verif_code()
package.check_sum = Algorithm("SHA1", package.verif_code)
package.comment = f"{len(package.files)} files, {total_size} bytes"
package.add_pkg_ext_refs(ExternalPackageRef(category = "PERSISTENT-ID", pkg_ext_ref_type = "swh", locator = f"swh:1:rev:{self.commit}", comment = "GitHub commit ID"))
doc.package = package
return doc
def write(self, target_root: str) -> None:
"""
Write the SPDX file(s) for this submodule
"""
def __write(doc: Document, writer, filename: str, mode: str = "wt"):
"""
Internal helper method that write a single output file of desired type
"""
logger.info(f"writing output to {filename}")
with open(filename, mode) as file:
writer(doc, file)
doc = self.scan()
target_base = os.path.join(target_root, self.name)
__write(doc, WriteTagValue, f"{target_base}.spdx_tv")
__write(doc, WriteJson, f"{target_base}.json")
__write(doc, WriteYaml, f"{target_base}.yaml")
__write(doc, WriteRdf, f"{target_base}.spdx", "wb")
@unique
class SubModuleStatus(Enum):
NO_INIT = "-"
IN_SYNC = " "
NO_SYNC = "+"
MERGE_CONFLICTS = "U"
class SubModules():
def __init__(self, args):
self.source_root = args.source_root
logger.info(f"fetching submodule status from git")
module_statuses = exec("git submodule status", cwd = self.source_root)
logger.debug("found submodules:")
self.modules = { }
for module_status in module_statuses.split("\n"):
if module_status:
status, commit, rel_path, version = [ module_status[:1], *module_status[1:].split(" ") ]
url = exec(f"git config --get submodule.{rel_path}.url", cwd = self.source_root).strip()
status = SubModuleStatus(status)
version = version.strip("()")
module = SubModule(self.source_root, rel_path, version, commit, status, url)
logger.debug(module)
self.modules[rel_path] = module
def write(self, module: str, args):
self.modules[module].write(args.target_root)
class VersionAction(argparse.Action):
"""
Show version information
"""
def __call__(self, parser, ns, values, option = None):
print(VERSION)
exit(1)
class HelpAction(argparse.Action):
"""
Show argument help
"""
def __call__(self, parser, ns, values, option = None):
parser.print_help()
exit(1)
class NegateAction(argparse.Action):
"""
Creates a negated version of a command line flag: "--foo" --> "--no-foo"
"""
def __call__(self, parser, ns, values, option = None):
setattr(ns, self.dest, option[2:4] != 'no')
def main():
"""
Main function
"""
default_source_root = os.environ.get("SBOM_SOURCE_ROOT") or "~/src/tidepool/LoopWorkspace"
default_target_root = os.environ.get("SBOM_TARGET_ROOT") or "./output"
parser = argparse.ArgumentParser(description = 'Generate SBOM from a project folder and GitHub', add_help = False)
parser.add_argument('--version', action = VersionAction, nargs = 0, help = 'show version information')
parser.add_argument('-h', '--help', action = HelpAction, nargs = 0, help = 'show this help message and exit')
parser.add_argument('--verbose', '--no-verbose', dest = 'verbose', default = False, action = NegateAction, nargs = 0, help = 'enable verbose mode (default: off)')
parser.add_argument('--source', default = default_source_root, dest = 'source_root', action = 'store', help = f'set source folder (default: {default_source_root})')
parser.add_argument('--target', default = default_target_root, dest = 'target_root', action = 'store', help = f'set target folder (default: {default_target_root})')
parser.add_argument('--tag', default = '', action = 'store', help = 'set arbitrary tag for use by templates (default: none)')
parser.add_argument('--build', default = '', action = 'store', help = 'set build number (default: none)')
args = parser.parse_args()
if args.verbose:
logger.setLevel(logging.DEBUG)
args.source_root = os.path.abspath(os.path.expanduser(args.source_root))
args.target_root = os.path.abspath(os.path.expanduser(args.target_root))
logger.info(f"Tidepool SBOM Generator v{VERSION}")
modules = SubModules(args)
modules.write("Common/TrueTime", args)
modules.write("Common/MKRingProgressView", args)
modules.write("Common/Minizip", args)
modules.write("Common/SwiftCharts", args)
logger.info("done")
if __name__ == "__main__":
main()
| 424 | 35.6 | 174 | 20 | 3,574 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_477a3200596a9fec_45774cdd", "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": 52, "line_end": 52, "column_start": 12, "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/tmppq52ww6s/477a3200596a9fec.py", "start": {"line": 52, "col": 12, "offset": 1589}, "end": {"line": 52, "col": 126, "offset": 1703}, "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_477a3200596a9fec_391fbb34", "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": 52, "line_end": 52, "column_start": 97, "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://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/477a3200596a9fec.py", "start": {"line": 52, "col": 97, "offset": 1674}, "end": {"line": 52, "col": 101, "offset": 1678}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.exec-detected_477a3200596a9fec_75473ff3", "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": 106, "line_end": 106, "column_start": 16, "column_end": 62, "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/477a3200596a9fec.py", "start": {"line": 106, "col": 16, "offset": 3137}, "end": {"line": 106, "col": 62, "offset": 3183}, "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.security.insecure-hash-algorithm-sha1_477a3200596a9fec_4ce4ba18", "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()", "location": {"file_path": "unknown", "line_start": 118, "line_end": 118, "column_start": 16, "column_end": 30, "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/tmppq52ww6s/477a3200596a9fec.py", "start": {"line": 118, "col": 16, "offset": 3550}, "end": {"line": 118, "col": 30, "offset": 3564}, "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()", "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.unspecified-open-encoding_477a3200596a9fec_3d055215", "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": 18, "column_end": 37, "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/477a3200596a9fec.py", "start": {"line": 130, "col": 18, "offset": 3914}, "end": {"line": 130, "col": 37, "offset": 3933}, "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.insecure-hash-algorithm-sha1_477a3200596a9fec_c57ebf54", "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()", "location": {"file_path": "unknown", "line_start": 144, "line_end": 144, "column_start": 18, "column_end": 32, "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/tmppq52ww6s/477a3200596a9fec.py", "start": {"line": 144, "col": 18, "offset": 4363}, "end": {"line": 144, "col": 32, "offset": 4377}, "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()", "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.requests.best-practice.use-timeout_477a3200596a9fec_ec6bd879", "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, auth = auth, timeout=30)", "location": {"file_path": "unknown", "line_start": 249, "line_end": 249, "column_start": 15, "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://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/477a3200596a9fec.py", "start": {"line": 249, "col": 15, "offset": 7663}, "end": {"line": 249, "col": 45, "offset": 7693}, "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, auth = auth, 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_477a3200596a9fec_c81889c6", "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": 333, "line_end": 333, "column_start": 18, "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/477a3200596a9fec.py", "start": {"line": 333, "col": 18, "offset": 11565}, "end": {"line": 333, "col": 38, "offset": 11585}, "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.exec-detected_477a3200596a9fec_a2d009bd", "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": 355, "line_end": 355, "column_start": 27, "column_end": 79, "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/477a3200596a9fec.py", "start": {"line": 355, "col": 27, "offset": 12246}, "end": {"line": 355, "col": 79, "offset": 12298}, "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.security.audit.exec-detected_477a3200596a9fec_a58600f9", "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": 361, "line_end": 361, "column_start": 23, "column_end": 97, "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/477a3200596a9fec.py", "start": {"line": 361, "col": 23, "offset": 12583}, "end": {"line": 361, "col": 97, "offset": 12657}, "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.correctness.use-sys-exit_477a3200596a9fec_bb32489d", "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": 377, "line_end": 377, "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/tmppq52ww6s/477a3200596a9fec.py", "start": {"line": 377, "col": 9, "offset": 13207}, "end": {"line": 377, "col": 16, "offset": 13214}, "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.correctness.use-sys-exit_477a3200596a9fec_22c445a3", "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": 385, "line_end": 385, "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/tmppq52ww6s/477a3200596a9fec.py", "start": {"line": 385, "col": 9, "offset": 13385}, "end": {"line": 385, "col": 16, "offset": 13392}, "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"}}}] | 12 | true | [
"CWE-78",
"CWE-78",
"CWE-95",
"CWE-95",
"CWE-95"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.subprocess-shell-true",
"rules.python.lang.security.audit.exec-detected",
"rules.python.lang.security.audit.exec-detected",
"rules.python.lang.security.audit.exec-detected"
] | [
"security",
"security",
"security",
"security",
"security"
] | [
"LOW",
"MEDIUM",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
52,
52,
106,
355,
361
] | [
52,
52,
106,
355,
361
] | [
12,
97,
16,
27,
23
] | [
126,
101,
62,
79,
97
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A03:2021 - Injection",
"A03:2021 - Injection",
"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()'.",
"Found 'subprocess'... | [
7.5,
7.5,
5,
5,
5
] | [
"LOW",
"HIGH",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"LOW",
"HIGH",
"HIGH",
"HIGH"
] | sbom_gen.py | /sbom_gen.py | tidepool-org/sbom_gen | BSD-2-Clause | |
2024-11-18T20:50:37.425111+00:00 | 1,559,533,164,000 | 7da52e641f4ca0fc2029138a48cd51bc8e260276 | 3 | {
"blob_id": "7da52e641f4ca0fc2029138a48cd51bc8e260276",
"branch_name": "refs/heads/master",
"committer_date": 1559533164000,
"content_id": "23b54fa354e9578ea397668db3b7b71ad8941e49",
"detected_licenses": [
"MIT"
],
"directory_id": "e17ae8bf899b159ed01d6e28a082ae71a931e404",
"extension": "py",
"filename": "encryption.py",
"fork_events_count": 0,
"gha_created_at": 1559532627000,
"gha_event_created_at": 1603835201000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 189928815,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5153,
"license": "MIT",
"license_type": "permissive",
"path": "/encryption.py",
"provenance": "stack-edu-0054.json.gz:582370",
"repo_name": "rgabeflores/Python-Encryption",
"revision_date": 1559533164000,
"revision_id": "08221b45654528d94778fbb5f0c8ee676cbdc258",
"snapshot_id": "55383d4e8425882a630b47621f50e5db2e4e5b57",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/rgabeflores/Python-Encryption/08221b45654528d94778fbb5f0c8ee676cbdc258/encryption.py",
"visit_date": "2021-07-03T23:05:20.982867"
} | 2.703125 | stackv2 | from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding, hmac, hashes
from cryptography.exceptions import InvalidSignature
from os import urandom, path
from handlers import cd
'''
This module AES encrypts files with CBC mode.
'''
# Debug flag for testing purposes
DEBUG = False
IV_SIZE = 16
KEY_LENGTH = 32
PADDING_BLOCK_SIZE = 128
BACKEND = default_backend()
def myEncrypt(message, key):
'''
Encrypt data with a given key.
'''
if len(key) < KEY_LENGTH:
raise Exception("Key length must be at least 32.")
# Generate random 16 Bytes
IV = urandom(IV_SIZE)
# Initialize encryption object
cipher = Cipher(algorithms.AES(key), modes.CBC(IV), backend=BACKEND)
encryptor = cipher.encryptor()
# Initialize padding object
padder = padding.PKCS7(PADDING_BLOCK_SIZE).padder()
# Append padding to message and close padding object
p_message = padder.update(message) + padder.finalize()
# Encrypt the padded message and close encryption object
C = encryptor.update(p_message) + encryptor.finalize()
return (C, IV)
def myFileEncrypt(filename, klength=KEY_LENGTH):
'''
Encrypt a file with a randomly generated 32-bit key.
'''
# Open image file and save the bytes
with open(filename, 'rb') as f:
print('Reading file...')
content = b''.join(f.readlines())
# Get file extension
ext = path.splitext(filename)[1]
# Generate random key
key = urandom(klength)
# Encrypt the contents of the file
C, IV = myEncrypt(content, key)
return (C, IV, key, ext)
def myDecrypt(encrypted_message, key, IV):
'''
Decrypt data with a given key
'''
# Initialize decryption object
cipher = Cipher(algorithms.AES(key), modes.CBC(IV), backend=BACKEND)
decryptor = cipher.decryptor()
# Decrypt the encrypted message
decrypted_message = decryptor.update(encrypted_message) + decryptor.finalize()
# Initialize unpadding object
unpadder = padding.PKCS7(128).unpadder()
# Unpad the decrypted message
M = unpadder.update(decrypted_message) + unpadder.finalize()
return M
def myFileDecrypt(filename, key, IV):
'''
Decrypt a file with a given key.
'''
# Open encrypted file and save the bytes
with open(filename, 'rb') as f:
print('Reading file...')
C = b''.join(f.readlines())
# Decrypt bytes
result = myDecrypt(C, key, IV)
return result
def myEncryptMAC(message, encKey, HMACKey):
'''
Encrypt data with an HMAC tag for verification.
'''
# Encrypt data
C, IV = myEncrypt(message, encKey)
# Create HMAC object with encrypted data as input
h = hmac.HMAC(HMACKey, hashes.SHA256(), backend=BACKEND)
h.update(C)
# Generate the tag by closing the hashing object
tag = h.finalize()
return (C, IV, tag)
def myFileEncryptMAC(filename, klength=KEY_LENGTH):
'''
Encrypt a file with HMAC verification.
'''
# Open image file and save the bytes
with open(filename, 'rb') as f:
print('Reading file...')
content = b''.join(f.readlines())
# Get file extension
ext = path.splitext(filename)[1]
# Generate random key
encKey = urandom(klength)
# Generate random HMAC key
HMACKey = urandom(klength)
# Encrypt the contents of the file
C, IV, tag = myEncryptMAC(content, encKey, HMACKey)
return (C, IV, tag, encKey, HMACKey, ext)
def myFileDecryptMAC(filename, encKey, HMACKey, IV, tag):
'''
Decrypt a file with a given key.
'''
# Open encrypted file and save the bytes
with open(filename, 'rb') as f:
print('Reading file...')
C = b''.join(f.readlines())
if DEBUG:
# Purposefully deprecate data for testing purposes
C += b'Append junk to test invalid data'
# Create HMAC object
h = hmac.HMAC(HMACKey, hashes.SHA256(), backend=BACKEND)
h.update(C)
# Verify the data with the HMAC tag
try:
h.verify(tag)
except InvalidSignature as e:
# Notify user and exit program if verification fails
print('Encrypted data was not valid.')
exit(1)
# Decrypt bytes
result = myDecrypt(C, encKey, IV)
return result
def main():
# Paths to input and output folders
INPUT_DIR = 'input'
OUTPUT_DIR = 'output'
# Sample image file
filename = 'smile.jpg'
# Encrypt the file
C, IV, tag, encKey, HMACKey, ext = myFileEncryptMAC(f'{INPUT_DIR}/{filename}')
# Save the encrypted file
with open(f'{OUTPUT_DIR}/encrypted_file{ext}', 'wb') as f:
print('Saving encrypted file...')
f.write(C)
# Decrypt file
M = myFileDecryptMAC(f'{OUTPUT_DIR}/encrypted_file{ext}', encKey, HMACKey, IV, tag)
# Save decrypted file
with open(f'{OUTPUT_DIR}/decrypted_file{ext}', 'wb') as f:
print('Saving decrypted file...')
f.write(M)
print('Done.')
if __name__ == '__main__':
main()
| 203 | 24.38 | 87 | 12 | 1,289 | python | [{"finding_id": "semgrep_rules.python.cryptography.security.crypto-mode-without-authentication_0c01dcfafc171d3a_10d94983", "tool_name": "semgrep", "rule_id": "rules.python.cryptography.security.crypto-mode-without-authentication", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "An encryption mode of operation is being used without proper message authentication. This can potentially result in the encrypted content to be decrypted by an attacker. Consider instead use an AEAD mode of operation like GCM. ", "remediation": "", "location": {"file_path": "unknown", "line_start": 33, "line_end": 33, "column_start": 14, "column_end": 73, "code_snippet": "requires login"}, "cwe_id": "CWE-327: Use of a Broken or Risky Cryptographic Algorithm", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://owasp.org/Top10/A02_2021-Cryptographic_Failures", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.cryptography.security.crypto-mode-without-authentication", "path": "/tmp/tmppq52ww6s/0c01dcfafc171d3a.py", "start": {"line": 33, "col": 14, "offset": 779}, "end": {"line": 33, "col": 73, "offset": 838}, "extra": {"message": "An encryption mode of operation is being used without proper message authentication. This can potentially result in the encrypted content to be decrypted by an attacker. Consider instead use an AEAD mode of operation like GCM. ", "metadata": {"category": "security", "technology": ["cryptography"], "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"], "references": ["https://owasp.org/Top10/A02_2021-Cryptographic_Failures"], "subcategory": ["audit"], "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.cryptography.security.crypto-mode-without-authentication_0c01dcfafc171d3a_99b7e75f", "tool_name": "semgrep", "rule_id": "rules.python.cryptography.security.crypto-mode-without-authentication", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "An encryption mode of operation is being used without proper message authentication. This can potentially result in the encrypted content to be decrypted by an attacker. Consider instead use an AEAD mode of operation like GCM. ", "remediation": "", "location": {"file_path": "unknown", "line_start": 75, "line_end": 75, "column_start": 14, "column_end": 73, "code_snippet": "requires login"}, "cwe_id": "CWE-327: Use of a Broken or Risky Cryptographic Algorithm", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://owasp.org/Top10/A02_2021-Cryptographic_Failures", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.cryptography.security.crypto-mode-without-authentication", "path": "/tmp/tmppq52ww6s/0c01dcfafc171d3a.py", "start": {"line": 75, "col": 14, "offset": 1872}, "end": {"line": 75, "col": 73, "offset": 1931}, "extra": {"message": "An encryption mode of operation is being used without proper message authentication. This can potentially result in the encrypted content to be decrypted by an attacker. Consider instead use an AEAD mode of operation like GCM. ", "metadata": {"category": "security", "technology": ["cryptography"], "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"], "references": ["https://owasp.org/Top10/A02_2021-Cryptographic_Failures"], "subcategory": ["audit"], "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_0c01dcfafc171d3a_a4a5445a", "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": 167, "line_end": 167, "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/tmppq52ww6s/0c01dcfafc171d3a.py", "start": {"line": 167, "col": 9, "offset": 4329}, "end": {"line": 167, "col": 16, "offset": 4336}, "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-327",
"CWE-327"
] | [
"rules.python.cryptography.security.crypto-mode-without-authentication",
"rules.python.cryptography.security.crypto-mode-without-authentication"
] | [
"security",
"security"
] | [
"MEDIUM",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
33,
75
] | [
33,
75
] | [
14,
14
] | [
73,
73
] | [
"A03:2017 - Sensitive Data Exposure",
"A03:2017 - Sensitive Data Exposure"
] | [
"An encryption mode of operation is being used without proper message authentication. This can potentially result in the encrypted content to be decrypted by an attacker. Consider instead use an AEAD mode of operation like GCM. ",
"An encryption mode of operation is being used without proper message authenticatio... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | encryption.py | /encryption.py | rgabeflores/Python-Encryption | MIT | |
2024-11-18T20:50:39.279963+00:00 | 1,528,903,999,000 | ac5bf1dd88fce81fdd336b4e8127ba396cce57f5 | 3 | {
"blob_id": "ac5bf1dd88fce81fdd336b4e8127ba396cce57f5",
"branch_name": "refs/heads/master",
"committer_date": 1528903999000,
"content_id": "d3f1de388f6e7b8df8c529c39f039000a05d4335",
"detected_licenses": [
"MIT"
],
"directory_id": "5ff8185863b28d84d9d706692b65878dbdcadfb1",
"extension": "py",
"filename": "map.py",
"fork_events_count": 0,
"gha_created_at": 1531071994000,
"gha_event_created_at": 1531071995000,
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 140189644,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8228,
"license": "MIT",
"license_type": "permissive",
"path": "/gpkit/nomials/map.py",
"provenance": "stack-edu-0054.json.gz:582394",
"repo_name": "sichu366/gpkit",
"revision_date": 1528903999000,
"revision_id": "a8999737980ba45682e6e00770cf4546ca5337af",
"snapshot_id": "0672822e4e4aa2b36e3be1b88704c4cb1b0caa0f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/sichu366/gpkit/a8999737980ba45682e6e00770cf4546ca5337af/gpkit/nomials/map.py",
"visit_date": "2020-03-22T14:34:33.835210"
} | 3.09375 | stackv2 | "Implements the NomialMap class"
from collections import defaultdict
import numpy as np
from ..exceptions import DimensionalityError
from ..small_classes import HashVector, Quantity, Strings, qty
from ..small_scripts import mag
from .substitution import parse_subs
DIMLESS_QUANTITY = qty("dimensionless")
class NomialMap(HashVector):
"""Class for efficent algebraic represention of a nomial
A NomialMap is a mapping between hashvectors representing exponents
and their coefficients in a posynomial.
For example, {{x : 1}: 2.0, {y: 1}: 3.0} represents 2*x + 3*y, where
x and y are VarKey objects.
"""
units = None
expmap = None # used for monomial-mapping postsubstitution; see .mmap()
csmap = None # used for monomial-mapping postsubstitution; see .mmap()
def units_of_product(self, thing, thing2=None):
"Sets units to those of `thing*thing2`"
if thing is None and thing2 is None:
self.units = None
elif hasattr(thing, "units"):
if hasattr(thing2, "units"):
self.units = qty((thing*thing2).units)
try: # faster than "if self.units.dimensionless"
conversion = float(self.units)
self.units = None
for key in self:
self[key] *= conversion
except DimensionalityError:
pass
elif not isinstance(thing, Quantity):
self.units = thing.units
else:
self.units = qty(thing.units)
elif hasattr(thing2, "units"):
self.units = qty(thing2.units)
elif thing2 is None and isinstance(thing, Strings):
self.units = qty(thing)
else:
self.units = None
def to(self, units):
"Returns a new NomialMap of the given units"
sunits = self.units or DIMLESS_QUANTITY
nm = self * sunits.to(units).magnitude # note that * creates a copy
nm.units_of_product(units) # pylint: disable=no-member
return nm
def __add__(self, other):
"Adds NomialMaps together"
if self.units != other.units:
try:
other *= float(other.units/self.units)
except TypeError: # if one of those units is None
raise DimensionalityError(self.units, other.units)
hmap = HashVector.__add__(self, other)
hmap.units = self.units
return hmap
def remove_zeros(self):
"""Removes zeroed exponents and monomials.
If `only_check_cs` is True, checks only whether any values are zero.
If False also checks whether any exponents in the keys are zero.
"""
for key, value in self.items():
zeroes = set(vk for vk, exp in key.items() if exp == 0)
if zeroes:
# raise ValueError(self)
del self[key]
for vk in zeroes:
key._hashvalue ^= hash((vk, key[vk]))
del key[vk]
self[key] = value + self.get(key, 0)
def diff(self, varkey):
"Differentiates a NomialMap with respect to a varkey"
out = NomialMap()
for exp in self:
if varkey in exp:
exp = HashVector(exp)
x = exp[varkey]
c = self[exp] * x
if x is 1: # speed optimization
del exp[varkey]
else:
exp[varkey] = x-1
out[exp] = c
out.units_of_product(self.units,
1.0/varkey.units if varkey.units else None)
return out
def sub(self, substitutions, varkeys, parsedsubs=False):
"""Applies substitutions to a NomialMap
Parameters
----------
substitutions : (dict-like)
list of substitutions to perform
varkeys : (set-like)
varkeys that are present in self
(required argument so as to require efficient code)
parsedsubs : bool
flag if the substitutions have already been parsed
to contain only keys in varkeys
"""
# pylint: disable=too-many-locals, too-many-branches
if parsedsubs or not substitutions:
fixed = substitutions
else:
fixed, _, _ = parse_subs(varkeys, substitutions)
if not substitutions:
if not self.expmap:
self.expmap, self.csmap = {exp: exp for exp in self}, {}
return self
cp = NomialMap()
cp.units = self.units
# csmap is modified during substitution, but keeps the same exps
cp.expmap, cp.csmap = {}, self.copy()
varlocs = defaultdict(set)
for exp, c in self.items():
new_exp = exp.copy()
cp.expmap[exp] = new_exp # cp modifies exps, so it needs new ones
cp[new_exp] = c
for vk in new_exp:
varlocs[vk].add((exp, new_exp))
for vk in varlocs:
if vk in fixed:
expval = []
exps, cval = varlocs[vk], fixed[vk]
if hasattr(cval, "hmap"):
expval, = cval.hmap.keys() # TODO: catch "can't-sub-posys"
cval = cval.hmap
if hasattr(cval, "to"):
cval = mag(cval.to(vk.units or DIMLESS_QUANTITY))
if isinstance(cval, NomialMap) and cval.keys() == [{}]:
cval, = cval.values()
if expval:
cval, = cval.values()
exps_covered = set()
for o_exp, exp in exps:
subinplace(cp, exp, o_exp, vk, cval, expval, exps_covered)
return cp
def mmap(self, orig):
"""Maps substituted monomials back to the original nomial
self.expmap is the map from pre- to post-substitution exponents, and
takes the form {original_exp: new_exp}
self.csmap is the map from pre-substitution exponents to coefficients.
m_from_ms is of the form {new_exp: [old_exps, ]}
pmap is of the form [{orig_idx1: fraction1, orig_idx2: fraction2, }, ]
where at the index corresponding to each new_exp is a dictionary
mapping the indices corresponding to the old exps to their
fraction of the post-substitution coefficient
"""
m_from_ms = defaultdict(dict)
pmap = [{} for _ in self]
origexps = list(orig.keys())
selfexps = list(self.keys())
for orig_exp, self_exp in self.expmap.items():
total_c = self.get(self_exp, None)
if total_c:
fraction = self.csmap.get(orig_exp, orig[orig_exp])/total_c
m_from_ms[self_exp][orig_exp] = fraction
orig_idx = origexps.index(orig_exp)
pmap[selfexps.index(self_exp)][orig_idx] = fraction
return pmap, m_from_ms
# pylint: disable=invalid-name
def subinplace(cp, exp, o_exp, vk, cval, expval, exps_covered):
"Modifies cp by substituing cval/expval for vk in exp"
x = exp[vk]
powval = float(cval)**x if cval != 0 or x >= 0 else np.inf
cp.csmap[o_exp] *= powval
if exp in cp and exp not in exps_covered:
c = cp.pop(exp)
exp._hashvalue ^= hash((vk, x)) # remove (key, value) from _hashvalue
del exp[vk]
for key in expval:
if key in exp:
exp._hashvalue ^= hash((key, exp[key])) # remove from hash
newval = expval[key]*x + exp[key]
else:
newval = expval[key]*x
exp._hashvalue ^= hash((key, newval)) # add to hash
exp[key] = newval
value = powval * c
if exp in cp:
currentvalue = cp[exp]
if value != -currentvalue:
cp[exp] = value + currentvalue
else:
del cp[exp] # remove zeros created during substitution
elif value:
cp[exp] = value
if not cp: # make sure it's never an empty hmap
cp[HashVector()] = 0.0
exps_covered.add(exp)
| 217 | 36.92 | 79 | 20 | 1,939 | python | [{"finding_id": "semgrep_rules.python.lang.correctness.dict-del-while-iterate_1d83903282434890_f3e41a47", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.dict-del-while-iterate", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "It appears that `self[key]` is a dict with items being deleted while in a for loop. This is usually a bad idea and will likely lead to a RuntimeError: dictionary changed size during iteration", "remediation": "", "location": {"file_path": "unknown", "line_start": 74, "line_end": 82, "column_start": 9, "column_end": 53, "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/stdtypes.html#dictionary-view-objects", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.dict-del-while-iterate", "path": "/tmp/tmphvvervh1/1d83903282434890.py", "start": {"line": 74, "col": 9, "offset": 2739}, "end": {"line": 82, "col": 53, "offset": 3109}, "extra": {"message": "It appears that `self[key]` is a dict with items being deleted while in a for loop. This is usually a bad idea and will likely lead to a RuntimeError: dictionary changed size during iteration", "metadata": {"references": ["https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
""
] | [
"rules.python.lang.correctness.dict-del-while-iterate"
] | [
"correctness"
] | [
"MEDIUM"
] | [
"MEDIUM"
] | [
74
] | [
82
] | [
9
] | [
53
] | [
""
] | [
"It appears that `self[key]` is a dict with items being deleted while in a for loop. This is usually a bad idea and will likely lead to a RuntimeError: dictionary changed size during iteration"
] | [
5
] | [
""
] | [
""
] | map.py | /gpkit/nomials/map.py | sichu366/gpkit | MIT | |
2024-11-18T20:50:40.657872+00:00 | 1,539,343,991,000 | d412bc3b80570df8631ac79b9599a37630df99bd | 3 | {
"blob_id": "d412bc3b80570df8631ac79b9599a37630df99bd",
"branch_name": "refs/heads/master",
"committer_date": 1539343991000,
"content_id": "cf400e71aae1febee6e288b862f2c08219b63451",
"detected_licenses": [
"MIT"
],
"directory_id": "1fe7e1fa3ee057dc8a8d8278f5be24f77b287537",
"extension": "py",
"filename": "utils.py",
"fork_events_count": 0,
"gha_created_at": 1570616128000,
"gha_event_created_at": 1570616128000,
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 213886160,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 782,
"license": "MIT",
"license_type": "permissive",
"path": "/trax/trax/utils.py",
"provenance": "stack-edu-0054.json.gz:582412",
"repo_name": "christianlupus/trax",
"revision_date": 1539343991000,
"revision_id": "85af6f908cbf55584f74856207ae3f6530728ccb",
"snapshot_id": "2e8277927ab5b3663085186abb257c3e9b4442dc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/christianlupus/trax/85af6f908cbf55584f74856207ae3f6530728ccb/trax/trax/utils.py",
"visit_date": "2020-08-08T18:15:52.949027"
} | 2.703125 | stackv2 | import dateparser
from django.utils import timezone
def humanize_timedelta(delta):
days, rem = divmod(delta.seconds, 86400)
hours, rem = divmod(rem, 3600)
minutes, seconds = divmod(rem, 60)
if seconds < 1:seconds = 1
magnitudes = ["days", "hours", "minutes"]
if seconds / delta.seconds > 0.05:
magnitudes.append('seconds')
locals_ = locals()
magnitudes_str = ("{n} {magnitude}".format(n=int(locals_[magnitude]), magnitude=magnitude)
for magnitude in magnitudes if locals_[magnitude])
return ", ".join(magnitudes_str)
def parse_future(s, tz):
now = timezone.now()
result = dateparser.parse(s, settings={'PREFER_DATES_FROM': 'future'})
if result:
result = tz.localize(result)
return result
| 24 | 31.58 | 94 | 13 | 208 | python | [{"finding_id": "semgrep_rules.python.lang.security.dangerous-globals-use_26bac3a3339686aa_bbd1aad3", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.dangerous-globals-use", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 14, "line_end": 14, "column_start": 54, "column_end": 72, "code_snippet": "requires login"}, "cwe_id": "CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.dangerous-globals-use", "path": "/tmp/tmphvvervh1/26bac3a3339686aa.py", "start": {"line": 14, "col": 54, "offset": 433}, "end": {"line": 14, "col": 72, "offset": 451}, "extra": {"message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "metadata": {"cwe": ["CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186"], "category": "security", "technology": ["python"], "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.dangerous-globals-use_26bac3a3339686aa_e2b4713d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.dangerous-globals-use", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 15, "line_end": 15, "column_start": 54, "column_end": 72, "code_snippet": "requires login"}, "cwe_id": "CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.dangerous-globals-use", "path": "/tmp/tmphvvervh1/26bac3a3339686aa.py", "start": {"line": 15, "col": 54, "offset": 528}, "end": {"line": 15, "col": 72, "offset": 546}, "extra": {"message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "metadata": {"cwe": ["CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186"], "category": "security", "technology": ["python"], "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-96",
"CWE-96"
] | [
"rules.python.lang.security.dangerous-globals-use",
"rules.python.lang.security.dangerous-globals-use"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
14,
15
] | [
14,
15
] | [
54,
54
] | [
72,
72
] | [
"A03:2021 - Injection",
"A03:2021 - Injection"
] | [
"Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.",
"Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | utils.py | /trax/trax/utils.py | christianlupus/trax | MIT | |
2024-11-18T20:50:40.700273+00:00 | 1,689,149,970,000 | 8fa6d439257b3824ca1c04cefea1820179137b23 | 3 | {
"blob_id": "8fa6d439257b3824ca1c04cefea1820179137b23",
"branch_name": "refs/heads/main",
"committer_date": 1689149970000,
"content_id": "9bfc41187ece02d367361e447b4507de3293643e",
"detected_licenses": [
"MIT"
],
"directory_id": "352ee943d093baa644f47a5c90a52b6ce6b410ce",
"extension": "py",
"filename": "approximate_cnv.py",
"fork_events_count": 6,
"gha_created_at": 1599797613000,
"gha_event_created_at": 1681379144000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 294591698,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3513,
"license": "MIT",
"license_type": "permissive",
"path": "/bin/approximate_cnv.py",
"provenance": "stack-edu-0054.json.gz:582413",
"repo_name": "sc-zhang/bioscripts",
"revision_date": 1689149970000,
"revision_id": "ffdf4509392db073d8878fd95ef7128c85bf9fd8",
"snapshot_id": "7226ee1b2a7eafa76d7fff17fdb599b53861147d",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/sc-zhang/bioscripts/ffdf4509392db073d8878fd95ef7128c85bf9fd8/bin/approximate_cnv.py",
"visit_date": "2023-07-21T21:00:19.236417"
} | 2.546875 | stackv2 | #!/usr/bin/env python
import sys, os
import multiprocessing
def help_message():
print("Usage: python "+sys.argv[0]+" -bam <bam_list_file> -g <genome_size> -l <read_length> -bed <bed_file> -o <out_file> [-t <thread_nums>]")
def get_opts(ARGV):
opts = {}
if len(ARGV) < 3:
help_message()
sys.exit(0)
for i in range(1, len(ARGV), 2):
key = ARGV[i][1:]
value = ARGV[i+1]
if key not in opts:
opts[key] = value
return opts
def calc_mapped_reads_count(in_bam):
fn = in_bam + '.read_counts.txt'
counts = 0
res = os.popen("samtools view "+in_bam)
for line in res:
data = line.strip().split()
if data[2] != '*':
counts += 1
with open(fn, 'w') as f_out:
f_out.write(str(counts))
def calc_read_depth(in_bam, in_bed):
fn = in_bam + '.read_depth.txt'
res = os.popen("bedtools coverage -a "+in_bed+" -b "+in_bam+" 2>/dev/null")
with open(fn, 'w') as f_out:
for line in res:
data = line.strip().split('\t')
if len(data) < 7:
continue
f_out.write(line)
def calc_pipeline(in_bams, in_bed):
calc_mapped_reads_count(in_bams)
calc_read_depth(in_bams, in_bed)
def quick_CNV(opts):
bam_list = []
name_list = []
bed_rows = 0
print("Calculating read depth and counts")
with open(opts['bam'], 'r') as f_in:
for line in f_in:
print("\tDealing %s"%line.strip())
bam_list.append(line.strip())
name_list.append(line.strip().split('/')[-1].split('\\')[-1].split('.')[0])
if 't' in opts:
t_n = int(opts['t'])
else:
t_n = 1
print("Creating processes pool")
bed_file = opts['bed']
pool = multiprocessing.Pool(processes=t_n)
for bam_file in bam_list:
res = pool.apply_async(calc_pipeline, (bam_file, bed_file,))
pool.close()
pool.join()
genome_size = int(opts['g'])
read_length = int(opts['l'])
gene_length_db = {}
print("Reading bed")
with open(bed_file, 'r') as f_in:
for line in f_in:
data = line.strip().split()
gene_name = data[-1]
s_p = int(data[1])
e_p = int(data[2])
length = e_p - s_p
if length < 0:
length = -length
gene_length_db[gene_name] = length
print("Approximating CNV")
bed_rows = len(data)
mapped_rc = {}
coverage_db = {}
for i in range(0, len(bam_list)):
fn = bam_list[i] + '.read_counts.txt'
with open(fn, 'r') as f_in:
for line in f_in:
if line.strip() == '':
continue
mapped_rc[name_list[i]] = int(line.strip())
#os.remove(fn)
fn = bam_list[i] + '.read_depth.txt'
if name_list[i] not in coverage_db:
coverage_db[name_list[i]] = {}
with open(fn, 'r') as f_in:
for line in f_in:
if line.strip() == '':
continue
data = line.strip().split('\t')
gene_name = data[bed_rows-1]
if gene_name not in coverage_db[name_list[i]]:
coverage_db[name_list[i]][gene_name] = int(data[bed_rows])
#os.remove(fn)
print("Writing result")
out_file = opts['o']
with open(out_file, 'w') as f_out:
f_out.write("#Sample\\CopyNumber\t")
f_out.write('\t'.join(list(sorted(gene_length_db.keys())))+'\n')
for name in sorted(mapped_rc.keys()):
f_out.write(name)
seq_depth = mapped_rc[name]*1.0*read_length/genome_size
for gene in sorted(gene_length_db.keys()):
copy_number = 1.0*coverage_db[name][gene]*read_length/gene_length_db[gene]/seq_depth
f_out.write('\t'+str(copy_number))
f_out.write('\n')
print("Finished")
if __name__ == "__main__":
opts = get_opts(sys.argv)
necessary_paras = ['bam', 'g', 'l', 'bed', 'o']
for key in necessary_paras:
if key not in opts:
help_message()
sys.exit(0)
quick_CNV(opts)
| 141 | 23.91 | 143 | 22 | 1,078 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_c1c4d5a8f55d2cfe_72ac8271", "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": 27, "line_end": 27, "column_start": 8, "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://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/tmphvvervh1/c1c4d5a8f55d2cfe.py", "start": {"line": 27, "col": 8, "offset": 532}, "end": {"line": 27, "col": 41, "offset": 565}, "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.unspecified-open-encoding_c1c4d5a8f55d2cfe_9f4fae8b", "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": 32, "line_end": 32, "column_start": 7, "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/tmphvvervh1/c1c4d5a8f55d2cfe.py", "start": {"line": 32, "col": 7, "offset": 656}, "end": {"line": 32, "col": 20, "offset": 669}, "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_c1c4d5a8f55d2cfe_9c3b388a", "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": 8, "column_end": 77, "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/tmphvvervh1/c1c4d5a8f55d2cfe.py", "start": {"line": 38, "col": 8, "offset": 786}, "end": {"line": 38, "col": 77, "offset": 855}, "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.unspecified-open-encoding_c1c4d5a8f55d2cfe_2039d7e1", "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": 7, "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/tmphvvervh1/c1c4d5a8f55d2cfe.py", "start": {"line": 39, "col": 7, "offset": 862}, "end": {"line": 39, "col": 20, "offset": 875}, "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_c1c4d5a8f55d2cfe_16b0067c", "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": 57, "line_end": 57, "column_start": 7, "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/tmphvvervh1/c1c4d5a8f55d2cfe.py", "start": {"line": 57, "col": 7, "offset": 1219}, "end": {"line": 57, "col": 29, "offset": 1241}, "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_c1c4d5a8f55d2cfe_ff54046f", "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": 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/tmphvvervh1/c1c4d5a8f55d2cfe.py", "start": {"line": 81, "col": 7, "offset": 1810}, "end": {"line": 81, "col": 26, "offset": 1829}, "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_c1c4d5a8f55d2cfe_c2886ffc", "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": 98, "line_end": 98, "column_start": 8, "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/tmphvvervh1/c1c4d5a8f55d2cfe.py", "start": {"line": 98, "col": 8, "offset": 2225}, "end": {"line": 98, "col": 21, "offset": 2238}, "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_c1c4d5a8f55d2cfe_fb4ff5f1", "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": 108, "line_end": 108, "column_start": 8, "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/tmphvvervh1/c1c4d5a8f55d2cfe.py", "start": {"line": 108, "col": 8, "offset": 2494}, "end": {"line": 108, "col": 21, "offset": 2507}, "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_c1c4d5a8f55d2cfe_837e010b", "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": 120, "line_end": 120, "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/tmphvvervh1/c1c4d5a8f55d2cfe.py", "start": {"line": 120, "col": 7, "offset": 2835}, "end": {"line": 120, "col": 26, "offset": 2854}, "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-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"
] | [
27,
38
] | [
27,
38
] | [
8,
8
] | [
41,
77
] | [
"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"
] | approximate_cnv.py | /bin/approximate_cnv.py | sc-zhang/bioscripts | MIT | |
2024-11-18T20:50:40.861745+00:00 | 1,407,845,983,000 | bf24978cb145b5b74571929c093e1b66f9069a21 | 3 | {
"blob_id": "bf24978cb145b5b74571929c093e1b66f9069a21",
"branch_name": "refs/heads/master",
"committer_date": 1407845983000,
"content_id": "7678c8c88be8d0acd95da82ae108405841c539fe",
"detected_licenses": [
"MIT"
],
"directory_id": "73bca317047b37eda3cb6f49704a0ba7382f8d98",
"extension": "py",
"filename": "hostinfodb.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": 651,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/hostinfodb.py",
"provenance": "stack-edu-0054.json.gz:582415",
"repo_name": "Hadhat/flow-inspector",
"revision_date": 1407845983000,
"revision_id": "b53d5a06046992ae2cb9be8586454da1625f215e",
"snapshot_id": "aa0e65f8117367549d88f65dec1792c9adc4875e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Hadhat/flow-inspector/b53d5a06046992ae2cb9be8586454da1625f215e/lib/hostinfodb.py",
"visit_date": "2020-12-25T13:24:03.553525"
} | 2.53125 | stackv2 | import sys
import config
hostDBFields = {
"hostIP": "IP"
}
class HostInfoDB:
def __init__(self):
try:
import cx_Oracle
connection_string = config.host_info_user + "/" + config.host_info_password + "@" + config.host_info_host + ":" + str(config.host_info_port) + "/" +config.host_info_name
self.conn = cx_Oracle.Connection(connection_string)
self.cursor = cx_Oracle.Cursor(self.conn)
except Exception, e:
print >> sys.stderr, "Could not connect to HostInfoDB: ", e
sys.exit(-1)
def run_query(self, tableName, query):
query = query % (tableName)
print query
self.cursor.execute(query)
return self.cursor.fetchall()
| 25 | 25.04 | 172 | 19 | 164 | python | [{"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_2d49c37d527f442d_621f3bbb", "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": 23, "line_end": 23, "column_start": 3, "column_end": 29, "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/tmphvvervh1/2d49c37d527f442d.py", "start": {"line": 23, "col": 3, "offset": 591}, "end": {"line": 23, "col": 29, "offset": 617}, "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"}}}] | 1 | true | [
"CWE-89"
] | [
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
23
] | [
23
] | [
3
] | [
29
] | [
"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"
] | hostinfodb.py | /lib/hostinfodb.py | Hadhat/flow-inspector | MIT | |
2024-11-18T20:50:41.625425+00:00 | 1,438,552,148,000 | 11f6187cb2c7eb01bec51f2bcf4348a3beee408d | 3 | {
"blob_id": "11f6187cb2c7eb01bec51f2bcf4348a3beee408d",
"branch_name": "refs/heads/master",
"committer_date": 1438552148000,
"content_id": "40cf551240e9166ae644cc8da2cb0b69685dda4f",
"detected_licenses": [
"MIT"
],
"directory_id": "984c4cd6738cf431515e761c90557af822a8e6b4",
"extension": "py",
"filename": "tableSlope.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 26749602,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2516,
"license": "MIT",
"license_type": "permissive",
"path": "/scripts/tableSlope.py",
"provenance": "stack-edu-0054.json.gz:582426",
"repo_name": "griffinfoster/pulsar-polarization-sims",
"revision_date": 1438552148000,
"revision_id": "c77234930e9d832e7999a4e5f2a77d574ac37ee2",
"snapshot_id": "d0445724358dc0a0858bdcd2db594e0709f22b8d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/griffinfoster/pulsar-polarization-sims/c77234930e9d832e7999a4e5f2a77d574ac37ee2/scripts/tableSlope.py",
"visit_date": "2020-05-20T05:29:00.285230"
} | 2.609375 | stackv2 | #!/usr/bin/env python
"""
"""
import os,sys
import numpy as np
import cPickle as pkl
if __name__ == "__main__":
from optparse import OptionParser
o = OptionParser()
o.set_usage('%prog [options] [pklReduceDict.py DICT]')
o.set_description(__doc__)
o.add_option('--snr',dest='snr',default=100,type='int',
help='SNR value to use (rounds to nearest int value), default: 100')
o.add_option('--info',dest='info',action='store_true',
help='Print parameter information in the dictionary and exit')
o.add_option('--dJ',dest='dJ',default=0.05,type='float',
help='Calibration error to select out, default: 0.05')
o.add_option('-c','--cal',dest='calMode',default='cal',
help='cal mode to use: cal or uncal, default: cal')
o.add_option('-m','--mode',dest='mode',default='rms',
help='Data mode: rms, chi2, sigma ; default: rms')
o.add_option('-r','--rms', dest='rmsMode', default=0, type='int',
help='Set RMS mode, 0: total intesity, 1: invariant interval, 2: matrix template matching. default: 0')
opts, args = o.parse_args(sys.argv[1:])
print 'Loading PKL file'
reduceDict=pkl.load(open(args[0]))
if opts.info:
snrs=[]
deltaJs=[]
ixrs=[]
for key,val in reduceDict.iteritems():
snrs.append(key[1])
deltaJs.append(key[2]*100.)
ixrs.append(10.*np.log10(1./(key[3]**2)))
snrs=np.array(snrs)
deltaJs=np.array(deltaJs)
ixrs=np.array(ixrs)
print 'SNR:', np.unique(snrs)
print 'delta J (\%):',np.unique(deltaJs)
print 'IXR (dB):', np.unique(ixrs)
exit()
ixrdbs=[]
vals=[]
for key,val in reduceDict.iteritems():
#key: (mode,snr,dJ,IXR,cal/uncal)
#val keys: ['rms', 'chi2', 'avgSigma', 'obsMJD', 'nobs', 'expMJD', 'sigmas']
if key[0]==opts.rmsMode and int(key[1])==opts.snr and key[2]==opts.dJ and key[4].startswith(opts.calMode): #timing mode, snr, dJ, cal mode selection
ixrdb=10.*np.log10(1./(key[3]**2))
ixrdbs.append(ixrdb)
if opts.mode.startswith('rms'): vals.append(val['rms'])
elif opts.mode.startswith('chi'): vals.append(val['chi2'])
elif opts.mode.startswith('sigma'): vals.append(val['avgSigma'])
ixrdbs=np.array(ixrdbs)
vals=np.array(vals)
idx=np.argsort(ixrdbs)
print 'IXR',ixrdbs[idx]
print 'RMS',vals[idx]
print 'precent',100.*np.diff(vals[idx])/vals[idx][:-1]
| 67 | 36.55 | 156 | 18 | 741 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_5dfa5b353e7521f8_d3ebc7f7", "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": 30, "line_end": 30, "column_start": 16, "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-cPickle", "path": "/tmp/tmphvvervh1/5dfa5b353e7521f8.py", "start": {"line": 30, "col": 16, "offset": 1165}, "end": {"line": 30, "col": 39, "offset": 1188}, "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.best-practice.unspecified-open-encoding_5dfa5b353e7521f8_b02bdca9", "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": 30, "line_end": 30, "column_start": 25, "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/tmphvvervh1/5dfa5b353e7521f8.py", "start": {"line": 30, "col": 25, "offset": 1174}, "end": {"line": 30, "col": 38, "offset": 1187}, "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-cPickle"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
30
] | [
30
] | [
16
] | [
39
] | [
"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"
] | tableSlope.py | /scripts/tableSlope.py | griffinfoster/pulsar-polarization-sims | MIT | |
2024-11-18T20:50:52.113115+00:00 | 1,619,889,663,000 | 8f923e6bdef6cfde8286fb136f45a738fd1e79ab | 2 | {
"blob_id": "8f923e6bdef6cfde8286fb136f45a738fd1e79ab",
"branch_name": "refs/heads/main",
"committer_date": 1619889663000,
"content_id": "25f5815b259b318896861cda6fc98735c039d6b9",
"detected_licenses": [
"MIT"
],
"directory_id": "17b176195388438a14da788302f3df7970f1b21c",
"extension": "py",
"filename": "Test.py",
"fork_events_count": 0,
"gha_created_at": 1619104871000,
"gha_event_created_at": 1619889663000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 360564696,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2895,
"license": "MIT",
"license_type": "permissive",
"path": "/Test.py",
"provenance": "stack-edu-0054.json.gz:582541",
"repo_name": "TuquiSierra/Ehealth",
"revision_date": 1619889663000,
"revision_id": "e2e89c64978569e458e04bcda61972b7028dd7be",
"snapshot_id": "4d4796c2020eb380f3b4de5d3bd8e0a00b7d4c45",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/TuquiSierra/Ehealth/e2e89c64978569e458e04bcda61972b7028dd7be/Test.py",
"visit_date": "2023-04-10T22:29:18.967475"
} | 2.5 | stackv2 | from scripts.anntools import Collection
from pathlib import Path
from our_annotations import parse_sentence
import matplotlib.pyplot as plt
import numpy as np
import string
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pad_sequence
from data import WordDataset, EqualLenghtSequence, chunk, SentenceDataset
from training import train
from torch.utils.data import DataLoader
from metrics import Accuracy, F1Score
from tagger import get_tag_list
from LSTMnn import MyLSTM
from functools import reduce
import pickle
from postag import pos_tag,pickle_postag
c = Collection()
c.load(Path("./2021/ref/training/medline.1200.es.txt"))
# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
TAGS = ['B_C', 'I_C', 'L_C','B_A', 'I_A', 'L_A','B_P', 'I_P', 'L_P','B_R', 'I_R', 'L_R', 'U_C', 'U_A', 'U_P', 'U_R', 'V_C', 'V_A', 'V_P', 'V_R', 'O', 'V' ]
LETTERS = string.printable + 'áéíóúÁÉÍÓÚñüö'
def letter_to_index(letter):
return LETTERS.index(letter)
def line_to_tensor(line):
tensor = torch.zeros(len(line), len(LETTERS))
for i, c in enumerate(line):
tensor[i][letter_to_index(c)] = 1
return tensor
def label_to_tensor(label):
return torch.tensor([TAGS.index(label)])
def sentence_to_tensor(sentence):
words = sentence.split()
sentence_len = len(words)
words_representation = []
for word in words:
tensor = line_to_tensor(word)
word_representation = (len(word), tensor)
words_representation.append(word_representation)
bert_vectors = bert_embeddings[sentence]
postag_vectors=postags[sentence]
return (sentence_len, words_representation, bert_vectors, postag_vectors)
bert_embeddings = pickle.load(open('bert_embeddings_v2.data', 'rb'))
postags=pickle.load(open('postag.data', 'rb'))
criterion = nn.CrossEntropyLoss()
learning_rate = 0.005
DEVICE = "gpu:0" if torch.cuda.is_available() else "cpu"
def main():
# c=Collection()
# c.load(Path("./2021/ref/training/medline.1200.es.txt"))
# pickle_postag(c)
file = './2021/ref/training/medline.1200.es.txt'
data = SentenceDataset(file, transform=sentence_to_tensor, target_transform=lambda l : torch.stack(tuple(map(label_to_tensor, l))))
data_loader = DataLoader(data, batch_size=4, collate_fn=my_collate_fn, shuffle=True)
n = MyLSTM(50, 50, len(TAGS), 113, 50 )
n.to(DEVICE)
optimizer = torch.optim.SGD(n.parameters(), lr=learning_rate)
metrics = {
'acc' : lambda pred, true : Accuracy()(pred, true),
'f1' : lambda pred, true : F1Score()(torch.tensor(pred.argmax(dim=1), dtype=torch.float32), torch.tensor(true, dtype=torch.float32))
}
train(data_loader, n, criterion, optimizer, 5, filename='test_lstm.pth', metrics=metrics)
if __name__ == '__main__':
main()
| 87 | 32.13 | 156 | 16 | 811 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_82bbb8b4750dc83b_d7aec7ae", "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": 61, "line_end": 61, "column_start": 19, "column_end": 69, "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/tmphvvervh1/82bbb8b4750dc83b.py", "start": {"line": 61, "col": 19, "offset": 1788}, "end": {"line": 61, "col": 69, "offset": 1838}, "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_82bbb8b4750dc83b_ba12d11b", "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": 62, "line_end": 62, "column_start": 9, "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/tmphvvervh1/82bbb8b4750dc83b.py", "start": {"line": 62, "col": 9, "offset": 1847}, "end": {"line": 62, "col": 47, "offset": 1885}, "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"
] | [
61,
62
] | [
61,
62
] | [
19,
9
] | [
69,
47
] | [
"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"
] | Test.py | /Test.py | TuquiSierra/Ehealth | MIT | |
2024-11-18T20:50:54.203989+00:00 | 1,535,124,025,000 | db990e121529cfba2fe3de0a7c1d9e3d38a4acde | 3 | {
"blob_id": "db990e121529cfba2fe3de0a7c1d9e3d38a4acde",
"branch_name": "refs/heads/master",
"committer_date": 1535124025000,
"content_id": "6ec29ac720295505e2cbce778bb794681b071521",
"detected_licenses": [
"MIT"
],
"directory_id": "757d879807b905b096d8e8dd0ff79973357d5e97",
"extension": "py",
"filename": "outer.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": 6590,
"license": "MIT",
"license_type": "permissive",
"path": "/outer.py",
"provenance": "stack-edu-0054.json.gz:582568",
"repo_name": "ifigueroap/Multitask4Veracity",
"revision_date": 1535124025000,
"revision_id": "56d9aed33d15d58fae5d6049db67622e6d07a4a4",
"snapshot_id": "66c348442b3591fa5d05787a0bd25dbd9eb90e86",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ifigueroap/Multitask4Veracity/56d9aed33d15d58fae5d6049db67622e6d07a4a4/outer.py",
"visit_date": "2023-03-17T02:46:55.517208"
} | 2.828125 | stackv2 | """
Run outer.py
python outer.py
outer.py has the following options:
python outer.py --model='mtl2stance' --data='RumEval' --search=True --ntrials=10 --params="output/bestparams.txt"
--model - which task to train, stance or veracity
--data - which dataset to use
--search - boolean, controls whether parameter search should be performed
--ntrials - if --search is True then this controls how many different
parameter combinations should be assessed
--params - specifies filepath to file with parameters if --search is false
-h, --help - explains the command line
If performing parameter search, then execution will take long time
depending on number of trials, size and number of layers in parameter space.
Use of GPU is highly recommended.
If running with default parametes then search won't be performed
"""
import pickle
# os.environ["THEANO_FLAGS"]="floatX=float32"
# if using theano then use flag to set floatX=float32
from optparse import OptionParser
from parameter_search import parameter_search
from MTL2_RumEval_VeracityStance import eval_MTL2_RumEval
from MTL2_RumEval_VeracityStance import objective_MTL2_RumEval
from MTL2_CV_VeracityStance import eval_MTL2_stance_CV
from MTL2_CV_VeracityStance import objective_MTL2_stance_CV5
from MTL2_CV_VeracityStance import objective_MTL2_stance_CV9
from MTL2_CV_VeracityDetection import eval_MTL2_detection_CV
from MTL2_CV_VeracityDetection import objective_MTL2_detection_CV5
from MTL2_CV_VeracityDetection import objective_MTL2_detection_CV9
from MTL3_CV_VeracityStanceDetection import eval_MTL3
from MTL3_CV_VeracityStanceDetection import objective_MTL3_CV5
from MTL3_CV_VeracityStanceDetection import objective_MTL3_CV9
#%%
def main():
parser = OptionParser()
parser.add_option(
'--search', dest='psearch', default=False,
help='Whether parameter search should be done: default=%default')
parser.add_option('--ntrials', dest='ntrials', default=10,
help='Number of trials: default=%default')
parser.add_option(
'--model', dest='model', default='mtl2stance',
help='Which model to use. Can be one of the following: mtl2stance, mtl2detect, mtl3; default=%default')
parser.add_option(
'--data', dest='data', default='RumEval',
help='Which dataset to use: RumEval(train, dev, test) or PHEME5 or PHEME9 (leave one event out cross-validation): default=%default')
(options, args) = parser.parse_args()
psearch = options.psearch
ntrials = int(options.ntrials)
data = options.data
model = options.model
output = []
if model == 'mtl2stance':
if data == 'RumEval':
if psearch:
params = parameter_search(ntrials, objective_MTL2_RumEval,
'MTL2_RumEval')
else:
params_file = 'bestparams_MTL2_RumEval.txt'
with open(params_file, 'rb') as f:
params = pickle.load(f)
print(params)
output = eval_MTL2_RumEval(params, 'MTL2_RumEval')
elif data == 'PHEME5':
if psearch:
params = parameter_search(ntrials, objective_MTL2_stance_CV5,
'MTL2_stance_PHEME5')
else:
params_file = 'bestparams_MTL2_stance_PHEME5.txt'
with open(params_file, 'rb') as f:
params = pickle.load(f)
print(params)
output = eval_MTL2_stance_CV(params,'PHEME5',
'MTL2_stance_PHEME5')
elif data == 'PHEME9':
if psearch:
params = parameter_search(ntrials, objective_MTL2_stance_CV9,
'MTL2_stance_PHEME9')
else:
params_file = 'bestparams_MTL2_stance_PHEME9.txt'
with open(params_file, 'rb') as f:
params = pickle.load(f)
print(params)
output = eval_MTL2_stance_CV(params,'PHEME9',
'MTL2_stance_PHEME9')
else:
print ("Check dataset name")
elif model == 'mtl2detect':
if data == 'PHEME5':
if psearch:
params = parameter_search(ntrials,
objective_MTL2_detection_CV5,
'MTL2_detection_PHEME5')
else:
params_file = 'bestparams_MTL2_detection_PHEME5.txt'
with open(params_file, 'rb') as f:
params = pickle.load(f)
print(params)
output = eval_MTL2_detection_CV(params,'PHEME5',
'MTL2_detection_PHEME5')
elif data == 'PHEME9':
if psearch:
params = parameter_search(ntrials,
objective_MTL2_detection_CV9,
'MTL2_detection_PHEME9')
else:
params_file = 'bestparams_MTL2_detection_PHEME9.txt'
with open(params_file, 'rb') as f:
params = pickle.load(f)
print(params)
output = eval_MTL2_detection_CV(params,'PHEME9',
'MTL2_detection_PHEME9')
else:
print ("Check dataset name")
elif model == 'mtl3':
if data == 'PHEME5':
if psearch:
params = parameter_search(ntrials, objective_MTL3_CV5,
'MTL3_PHEME5')
else:
params_file = 'bestparams_MTL3_PHEME5.txt'
with open(params_file, 'rb') as f:
params = pickle.load(f)
print(params)
output = eval_MTL3(params, 'PHEME5', 'MTL3_PHEME5')
elif data == 'PHEME9':
if psearch:
params = parameter_search(ntrials,
objective_MTL3_CV9,
'MTL3_PHEME9')
else:
params_file = 'bestparams_MTL3_PHEME9.txt'
with open(params_file, 'rb') as f:
params = pickle.load(f)
print(params)
output = eval_MTL3(params, 'PHEME9', 'MTL3_PHEME9')
else:
print ("Check dataset name")
else:
print ('Check model name')
return output
#%%
if __name__ == '__main__':
output = main() | 154 | 41.8 | 144 | 20 | 1,539 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_5d4ac14017681033_e6f7d2cb", "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": 68, "line_end": 68, "column_start": 30, "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/tmphvvervh1/5d4ac14017681033.py", "start": {"line": 68, "col": 30, "offset": 3001}, "end": {"line": 68, "col": 44, "offset": 3015}, "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_5d4ac14017681033_a6a5fb58", "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": 30, "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/tmphvvervh1/5d4ac14017681033.py", "start": {"line": 78, "col": 30, "offset": 3466}, "end": {"line": 78, "col": 44, "offset": 3480}, "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_5d4ac14017681033_a2399820", "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": 89, "line_end": 89, "column_start": 30, "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/tmphvvervh1/5d4ac14017681033.py", "start": {"line": 89, "col": 30, "offset": 3989}, "end": {"line": 89, "col": 44, "offset": 4003}, "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_5d4ac14017681033_5811aa2a", "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": 105, "line_end": 105, "column_start": 30, "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/tmphvvervh1/5d4ac14017681033.py", "start": {"line": 105, "col": 30, "offset": 4657}, "end": {"line": 105, "col": 44, "offset": 4671}, "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_5d4ac14017681033_267d05c6", "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": 117, "line_end": 117, "column_start": 30, "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/tmphvvervh1/5d4ac14017681033.py", "start": {"line": 117, "col": 30, "offset": 5240}, "end": {"line": 117, "col": 44, "offset": 5254}, "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_5d4ac14017681033_6cfb8fa5", "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": 131, "line_end": 131, "column_start": 30, "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/tmphvvervh1/5d4ac14017681033.py", "start": {"line": 131, "col": 30, "offset": 5827}, "end": {"line": 131, "col": 44, "offset": 5841}, "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_5d4ac14017681033_d1e7c79f", "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": 142, "line_end": 142, "column_start": 30, "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/tmphvvervh1/5d4ac14017681033.py", "start": {"line": 142, "col": 30, "offset": 6314}, "end": {"line": 142, "col": 44, "offset": 6328}, "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"}}}] | 7 | true | [
"CWE-502",
"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",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
68,
78,
89,
105,
117,
131,
142
] | [
68,
78,
89,
105,
117,
131,
142
] | [
30,
30,
30,
30,
30,
30,
30
] | [
44,
44,
44,
44,
44,
44,
44
] | [
"A08:2017 - Insecure Deserialization",
"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,
5
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | outer.py | /outer.py | ifigueroap/Multitask4Veracity | MIT | |
2024-11-18T20:50:55.474489+00:00 | 1,688,236,841,000 | 13a18dee2089768dca3d38f954d6eaf6c49d210c | 2 | {
"blob_id": "13a18dee2089768dca3d38f954d6eaf6c49d210c",
"branch_name": "refs/heads/master",
"committer_date": 1688236841000,
"content_id": "dae6a0dff106e78556da6207b7b2f71a08eab18e",
"detected_licenses": [
"BSD-3-Clause-LBNL"
],
"directory_id": "4c52e1aa84713a91c759495a70e8f5e3dcf74b12",
"extension": "py",
"filename": "setup.py",
"fork_events_count": 0,
"gha_created_at": 1396116805000,
"gha_event_created_at": 1573425805000,
"gha_language": "Python",
"gha_license_id": "NOASSERTION",
"github_id": 18247410,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4451,
"license": "BSD-3-Clause-LBNL",
"license_type": "permissive",
"path": "/setup.py",
"provenance": "stack-edu-0054.json.gz:582581",
"repo_name": "nstawski/prpr",
"revision_date": 1688236841000,
"revision_id": "d8346f50b4fa3cc126fb300c709a427e2e7e8a04",
"snapshot_id": "7706475c86fb4a9da75f056c123acaeaaaf78129",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/nstawski/prpr/d8346f50b4fa3cc126fb300c709a427e2e7e8a04/setup.py",
"visit_date": "2023-07-20T00:39:07.411973"
} | 2.359375 | stackv2 | __author__ = 'Nina Stawski'
__version__ = '0.32'
import sqlite3
import os
import stat
def DatabaseConnect():
global conn
conn = sqlite3.connect('prpr.db')
global crsr
crsr = conn.cursor()
def DatabaseDisconnect():
conn.commit()
crsr.close()
conn.close()
def CreateTables():
DatabaseConnect()
#Experiment info
crsr.execute('create table Experiments(ExpID UNIQUE, maxTips, maxVolume, Platform, Language)')
crsr.execute('create table ExperimentInfo(ExpID UNIQUE, Name, Comment)')
#Methods
crsr.execute('create table Methods(Method UNIQUE)')
crsr.execute('create table DefaultMethod(Method Unique)')
#Wells
crsr.execute('create table Wells(ExpID, WellID, Plate, Location, PRIMARY KEY(ExpID, WellID, Plate, Location))')
#Reagents
crsr.execute('create table Components(ExpID, ComponentID, WellID, PRIMARY KEY(ExpID, ComponentID, WellID))')
crsr.execute('create table ComponentMethods(ExpID, ComponentID, Method, PRIMARY KEY(ExpID, ComponentID, Method))')
crsr.execute('create table ComponentNames(ExpID, ComponentID, Name, PRIMARY KEY(ExpID, ComponentID, Name))')
#Plates
crsr.execute('create table Plates(FactoryName UNIQUE, Rows, Columns)')
crsr.execute('create table PlateLocations(ExpID, Plate, FactoryName, Grid, Site, PlateLocation, PRIMARY KEY(ExpID, Plate))')
crsr.execute('create table PlateNicknames(ExpID, Plate, Nickname, PRIMARY KEY(ExpID, Nickname))')
#Volumes
crsr.execute('create table Volumes(ExpID, VolumeName, VolumeValue, PRIMARY KEY(ExpID, VolumeName))')
#Recipes
crsr.execute('create table Recipes(ExpID, Recipe, Row, Column, Name, Volume, PRIMARY KEY(ExpID, Recipe, Row, Column))')
crsr.execute('create table Subrecipes(ExpID, Recipe, Row, Subrecipe, PRIMARY KEY(ExpID, Recipe, Row, Subrecipe))')
#Transactions
crsr.execute('create table Actions(ExpID, ActionID, Type, PRIMARY KEY(ExpID, ActionID));')
crsr.execute('create table Transfers(ExpID, ActionID, trOrder, srcWellID, dstWellID, Volume, Method, PRIMARY KEY(ExpID, ActionID, trOrder, srcWellID, dstWellID));')
crsr.execute('create table Commands(ExpID, ActionID, trOrder, Command, Options, PRIMARY KEY(ExpID, ActionID, trOrder));')
crsr.execute('create table CommandLocations(ExpID, ActionID, trOrder, Location, PRIMARY KEY(ExpID, ActionID, Location));')
#Microfluidics
crsr.execute('create table mfWellLocations(ExpID, WellName, WellCoords, PRIMARY KEY(ExpID, WellName, WellCoords));')
crsr.execute('create table mfWellConnections(ExpID, WellName, ConnectionName, PRIMARY KEY(ExpID, WellName, ConnectionName));')
#Updating experiments
crsr.execute('insert into Experiments values(0, "", "", "", "");')
DatabaseDisconnect()
def UpdateMethods():
methodFile = open('methodsInfo.txt', 'r')
f = methodFile.readlines()
for method in f:
try:
DatabaseConnect()
if f.index(method) == 0:
message = 'INSERT INTO DefaultMethod VALUES("' + str(method.strip()) + '");'
else:
message = 'INSERT INTO Methods VALUES("' + str(method.strip()) + '");'
crsr.execute(message)
DatabaseDisconnect()
except sqlite3.IntegrityError:
pass
def UpdatePlates():
plateFile = open('platesInfo.txt', 'r')
f = plateFile.readlines()
for plate in sorted(f):
data = plate.split(',')
name = data[0]
print(name)
dimensions = data[1]
size = dimensions.split('x')
try:
message = 'INSERT INTO Plates VALUES("' + name + '",' + size[0] + ',' + size[1] + ');'
DatabaseConnect()
crsr.execute(message)
except sqlite3.IntegrityError:
DatabaseConnect()
message = 'UPDATE Plates SET Rows = ' + size[0] + ', Columns = ' + size[1] + ' WHERE FactoryName = ' + '"' + name + '"'
crsr.execute(message)
DatabaseDisconnect()
def CreateFolders():
dirs = ['esc', 'incoming', 'logs']
for directory in dirs:
if not os.path.exists(directory):
os.mkdir(directory)
os.chmod(directory, stat.S_IRWXU|stat.S_IRWXG|stat.S_IRWXO)
def setup():
CreateFolders()
CreateTables()
UpdatePlates()
UpdateMethods()
os.chmod('prpr.db', stat.S_IRWXU|stat.S_IRWXG|stat.S_IRWXO)
print('Done!')
if __name__ == '__main__':
setup()
| 118 | 36.72 | 168 | 19 | 1,136 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.open-never-closed_69fb8c4368c487eb_14d0d304", "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": 67, "line_end": 67, "column_start": 5, "column_end": 46, "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/tmphvvervh1/69fb8c4368c487eb.py", "start": {"line": 67, "col": 5, "offset": 2800}, "end": {"line": 67, "col": 46, "offset": 2841}, "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_69fb8c4368c487eb_8f8b75af", "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": 67, "line_end": 67, "column_start": 18, "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/tmphvvervh1/69fb8c4368c487eb.py", "start": {"line": 67, "col": 18, "offset": 2813}, "end": {"line": 67, "col": 46, "offset": 2841}, "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_69fb8c4368c487eb_64937457", "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": 83, "line_end": 83, "column_start": 5, "column_end": 44, "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/tmphvvervh1/69fb8c4368c487eb.py", "start": {"line": 83, "col": 5, "offset": 3321}, "end": {"line": 83, "col": 44, "offset": 3360}, "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_69fb8c4368c487eb_a4687d1b", "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": 83, "line_end": 83, "column_start": 17, "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/tmphvvervh1/69fb8c4368c487eb.py", "start": {"line": 83, "col": 17, "offset": 3333}, "end": {"line": 83, "col": 44, "offset": 3360}, "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.sqlalchemy.security.sqlalchemy-execute-raw-query_69fb8c4368c487eb_d00d76e3", "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": 95, "line_end": 95, "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/tmphvvervh1/69fb8c4368c487eb.py", "start": {"line": 95, "col": 13, "offset": 3715}, "end": {"line": 95, "col": 34, "offset": 3736}, "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_69fb8c4368c487eb_50adae51", "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": 99, "line_end": 99, "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/tmphvvervh1/69fb8c4368c487eb.py", "start": {"line": 99, "col": 13, "offset": 3951}, "end": {"line": 99, "col": 34, "offset": 3972}, "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.insecure-file-permissions_69fb8c4368c487eb_0087eb85", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.insecure-file-permissions", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "These permissions `stat.S_IRWXU|stat.S_IRWXG|stat.S_IRWXO` are widely permissive and grant access to more people than may be necessary. A good default is `0o644` which gives read and write access to yourself and read access to everyone else.", "remediation": "", "location": {"file_path": "unknown", "line_start": 107, "line_end": 107, "column_start": 13, "column_end": 72, "code_snippet": "requires login"}, "cwe_id": "CWE-276: Incorrect Default Permissions", "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.lang.security.audit.insecure-file-permissions", "path": "/tmp/tmphvvervh1/69fb8c4368c487eb.py", "start": {"line": 107, "col": 13, "offset": 4176}, "end": {"line": 107, "col": 72, "offset": 4235}, "extra": {"message": "These permissions `stat.S_IRWXU|stat.S_IRWXG|stat.S_IRWXO` are widely permissive and grant access to more people than may be necessary. A good default is `0o644` which gives read and write access to yourself and read access to everyone else.", "metadata": {"category": "security", "owasp": ["A01:2021 - Broken Access Control", "A01:2025 - Broken Access Control"], "cwe": ["CWE-276: Incorrect Default Permissions"], "technology": ["python"], "references": ["https://owasp.org/Top10/A01_2021-Broken_Access_Control"], "cwe2022-top25": true, "cwe2021-top25": true, "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.insecure-file-permissions_69fb8c4368c487eb_f442c3d7", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.insecure-file-permissions", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "These permissions `stat.S_IRWXU|stat.S_IRWXG|stat.S_IRWXO` are widely permissive and grant access to more people than may be necessary. A good default is `0o644` which gives read and write access to yourself and read access to everyone else.", "remediation": "", "location": {"file_path": "unknown", "line_start": 114, "line_end": 114, "column_start": 5, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": "CWE-276: Incorrect Default Permissions", "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.lang.security.audit.insecure-file-permissions", "path": "/tmp/tmphvvervh1/69fb8c4368c487eb.py", "start": {"line": 114, "col": 5, "offset": 4332}, "end": {"line": 114, "col": 64, "offset": 4391}, "extra": {"message": "These permissions `stat.S_IRWXU|stat.S_IRWXG|stat.S_IRWXO` are widely permissive and grant access to more people than may be necessary. A good default is `0o644` which gives read and write access to yourself and read access to everyone else.", "metadata": {"category": "security", "owasp": ["A01:2021 - Broken Access Control", "A01:2025 - Broken Access Control"], "cwe": ["CWE-276: Incorrect Default Permissions"], "technology": ["python"], "references": ["https://owasp.org/Top10/A01_2021-Broken_Access_Control"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 8 | 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"
] | [
95,
99
] | [
95,
99
] | [
13,
13
] | [
34,
34
] | [
"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"
] | setup.py | /setup.py | nstawski/prpr | BSD-3-Clause-LBNL | |
2024-11-18T20:51:05.641734+00:00 | 1,634,147,749,000 | 05f1febf5643d25d2ee74adb2f7a7a6091430d87 | 2 | {
"blob_id": "05f1febf5643d25d2ee74adb2f7a7a6091430d87",
"branch_name": "refs/heads/main",
"committer_date": 1634147749000,
"content_id": "71601c5a1cee9cac6c44b18c22fd8ebd34fd4e8d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "bd0056edc11779091f3ddd0ba56f523867d798b5",
"extension": "py",
"filename": "cli.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": 378,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/lib/bubbletea/cli.py",
"provenance": "stack-edu-0054.json.gz:582626",
"repo_name": "scoutcool/Bubbletea",
"revision_date": 1634147749000,
"revision_id": "f0312d6f1c7fde4098d500e811f0503796973d07",
"snapshot_id": "3199b8cbcc19da57eb8678fcfb0ea30d0a0e8320",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/scoutcool/Bubbletea/f0312d6f1c7fde4098d500e811f0503796973d07/lib/bubbletea/cli.py",
"visit_date": "2023-08-12T09:20:11.689384"
} | 2.40625 | stackv2 | import click
import os
@click.group()
def main():
pass
# click.echo(f'RUNNING STREAM LIT {target}')
# os.system(f'streamlit run {target}')
@click.command()
@click.argument("target", required=True)
def run(target):
# click.echo(f'RUNNING STREAMLIT {target}')
os.system(f'streamlit run {target}')
# cli._main_run()
if __name__ == '__main__':
run() | 20 | 17.95 | 48 | 10 | 101 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.pass-body-fn_c308b95a5c9b091e_6533c559", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.pass-body-fn", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "`pass` is the body of function main. Consider removing this or raise NotImplementedError() if this is a TODO", "remediation": "", "location": {"file_path": "unknown", "line_start": 5, "line_end": 7, "column_start": 1, "column_end": 9, "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.best-practice.pass-body-fn", "path": "/tmp/tmphvvervh1/c308b95a5c9b091e.py", "start": {"line": 5, "col": 1, "offset": 25}, "end": {"line": 7, "col": 9, "offset": 60}, "extra": {"message": "`pass` is the body of function main. Consider removing this or raise NotImplementedError() if this is a TODO", "metadata": {"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.security.audit.dangerous-system-call-audit_c308b95a5c9b091e_a18b483c", "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": 15, "line_end": 15, "column_start": 5, "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://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/tmphvvervh1/c308b95a5c9b091e.py", "start": {"line": 15, "col": 5, "offset": 281}, "end": {"line": 15, "col": 41, "offset": 317}, "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"}}}] | 2 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
15
] | [
15
] | [
5
] | [
41
] | [
"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."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | cli.py | /lib/bubbletea/cli.py | scoutcool/Bubbletea | Apache-2.0 | |
2024-11-18T20:51:05.992508+00:00 | 1,519,362,636,000 | aacd579a3e121aeae41163fabb09283247063c18 | 3 | {
"blob_id": "aacd579a3e121aeae41163fabb09283247063c18",
"branch_name": "refs/heads/master",
"committer_date": 1519362636000,
"content_id": "4954dc5b237cd34c219ecf266d965448aa435a2f",
"detected_licenses": [
"MIT"
],
"directory_id": "cc3202fd671acf2ba7dde348074470d2864381e8",
"extension": "py",
"filename": "tutorial.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 44414167,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4392,
"license": "MIT",
"license_type": "permissive",
"path": "/src/tutorial.py",
"provenance": "stack-edu-0054.json.gz:582631",
"repo_name": "Jessime/Excision",
"revision_date": 1519362636000,
"revision_id": "f1194485fe4a8b9a1078508d4c112c8747be29b4",
"snapshot_id": "5e8165c17aea509590c4f80e1cd82c19032e3deb",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/Jessime/Excision/f1194485fe4a8b9a1078508d4c112c8747be29b4/src/tutorial.py",
"visit_date": "2021-05-04T10:02:43.483477"
} | 2.703125 | stackv2 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 20 15:50:23 2016
@author: jessime
"""
#TODO integrate this with play_levels and remove duplicated Code
import sys
import os
import subprocess as sp
import traceback
import numpy as np
from shutil import copyfile
from importlib import import_module, reload
class Tutorial():
script = None
def tutorial_gc(self):
error = None
gc_txt = '../results/tutorial/gc.txt'
if os.path.isfile(gc_txt):
os.remove(gc_txt)
cmd = 'python {} ATATATATGGGGGC'.format(self.script)
try:
sp.run(cmd.split(), stderr=sp.PIPE, check=True)
except sp.CalledProcessError as e:
error = e.stderr.decode("utf-8")
if error is None:
if not os.path.isfile(gc_txt):
error = 'Your program did not produce a file in the proper location.'
else:
with open(gc_txt) as infile:
result = infile.read().strip()
if not result:
error = 'There is nothing in the file you created.'
elif result != '43%':
error = 'Your answer is not correct.'
success = error is None
return success, error
def tutorial_sum(self):
error = None
sum_txt = '../results/tutorial/sum.txt'
if os.path.isfile(sum_txt):
os.remove(sum_txt)
#generate temp data
rand = np.random.randint(-10, 10, [10, 10])
max_val = max(rand.sum(0).max(), rand.sum(1).max())
rand_file = '../results/sum_rand.txt'
np.savetxt(rand_file, rand, delimiter=',')
cmd = 'python {} {}'.format(self.script, rand_file)
try:
sp.run(cmd.split(), stderr=sp.PIPE, check=True)
except sp.CalledProcessError as e:
error = e.stderr.decode("utf-8")
if error is None:
if not os.path.isfile(sum_txt):
error = 'Your program did not produce a file in the proper location.'
else:
with open(sum_txt) as infile:
result = infile.read().strip()
if not result:
error = 'There is nothing in the file you created.'
elif result != str(max_val):
error = 'Your answer is not correct.'
success = error is None
return success, error
def tutorial_task1(self):
error = None
new = self.temp_copy(self)
module_name = new.split('.')[0]
try:
if module_name in sys.modules:
user_import = reload(sys.modules[module_name])
else:
user_import = import_module(module_name)
result1 = user_import.squared_sum([1, 2, 3])
result2 = user_import.squared_sum([-1, 3])
if result1 != 14 or result2 != 10:
error = 'Your answer is not correct.'
except Exception:
error = traceback.format_exc()
self.temp_del(self, new)
success = error is None
return success, error
def tutorial_task2(self):
error = None
new = self.temp_copy(self)
module_name = new.split('.')[0]
try:
if module_name in sys.modules:
user_import = reload(sys.modules[module_name])
else:
user_import = import_module(module_name)
result1 = set(user_import.seen([1, 2, 3], [1,2,3,4,4,5, 'what']))
result2 = user_import.seen(['s', 9], ['s', 9])
if result1 != set(['what', 4, 5]) or result2 != []:
error = 'Your answer is not correct.'
except Exception:
error = traceback.format_exc()
self.temp_del(self, new)
success = error is None
return success, error
def temp_copy(self):
"""Creates a copy of a user file into the src dir to be imported"""
new = os.path.basename(self.script)
copyfile(self.script, new)
return new
def temp_del(self, temp):
"""Delete file created by temp_copy."""
if os.path.isfile(temp):
os.remove(temp)
@classmethod
def process_request(self, func_name):
"""Execute the method corresponding to func_name."""
result = vars(self)[func_name](self)
return result
| 134 | 31.78 | 85 | 19 | 987 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_66f76b8b763a2ff9_4d65e15c", "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": 29, "line_end": 29, "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/tmphvvervh1/66f76b8b763a2ff9.py", "start": {"line": 29, "col": 13, "offset": 590}, "end": {"line": 29, "col": 60, "offset": 637}, "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.best-practice.unspecified-open-encoding_66f76b8b763a2ff9_9ee917c0", "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": 22, "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://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/tmphvvervh1/66f76b8b763a2ff9.py", "start": {"line": 36, "col": 22, "offset": 920}, "end": {"line": 36, "col": 34, "offset": 932}, "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_66f76b8b763a2ff9_67f00ec3", "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": 60, "line_end": 60, "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/tmphvvervh1/66f76b8b763a2ff9.py", "start": {"line": 60, "col": 13, "offset": 1746}, "end": {"line": 60, "col": 60, "offset": 1793}, "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.best-practice.unspecified-open-encoding_66f76b8b763a2ff9_11fad95b", "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": 67, "line_end": 67, "column_start": 22, "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/tmphvvervh1/66f76b8b763a2ff9.py", "start": {"line": 67, "col": 22, "offset": 2077}, "end": {"line": 67, "col": 35, "offset": 2090}, "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.non-literal-import_66f76b8b763a2ff9_42d20f5a", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.non-literal-import", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Untrusted user input in `importlib.import_module()` function allows an attacker to load arbitrary code. Avoid dynamic values in `importlib.import_module()` or use a whitelist to prevent running untrusted code.", "remediation": "", "location": {"file_path": "unknown", "line_start": 85, "line_end": 85, "column_start": 31, "column_end": 57, "code_snippet": "requires login"}, "cwe_id": "CWE-706: Use of Incorrectly-Resolved Name or Reference", "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.lang.security.audit.non-literal-import", "path": "/tmp/tmphvvervh1/66f76b8b763a2ff9.py", "start": {"line": 85, "col": 31, "offset": 2716}, "end": {"line": 85, "col": 57, "offset": 2742}, "extra": {"message": "Untrusted user input in `importlib.import_module()` function allows an attacker to load arbitrary code. Avoid dynamic values in `importlib.import_module()` or use a whitelist to prevent running untrusted code.", "metadata": {"owasp": ["A01:2021 - Broken Access Control", "A01:2025 - Broken Access Control"], "cwe": ["CWE-706: Use of Incorrectly-Resolved Name or Reference"], "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A01_2021-Broken_Access_Control"], "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.audit.non-literal-import_66f76b8b763a2ff9_094a6066", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.non-literal-import", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Untrusted user input in `importlib.import_module()` function allows an attacker to load arbitrary code. Avoid dynamic values in `importlib.import_module()` or use a whitelist to prevent running untrusted code.", "remediation": "", "location": {"file_path": "unknown", "line_start": 106, "line_end": 106, "column_start": 31, "column_end": 57, "code_snippet": "requires login"}, "cwe_id": "CWE-706: Use of Incorrectly-Resolved Name or Reference", "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.lang.security.audit.non-literal-import", "path": "/tmp/tmphvvervh1/66f76b8b763a2ff9.py", "start": {"line": 106, "col": 31, "offset": 3416}, "end": {"line": 106, "col": 57, "offset": 3442}, "extra": {"message": "Untrusted user input in `importlib.import_module()` function allows an attacker to load arbitrary code. Avoid dynamic values in `importlib.import_module()` or use a whitelist to prevent running untrusted code.", "metadata": {"owasp": ["A01:2021 - Broken Access Control", "A01:2025 - Broken Access Control"], "cwe": ["CWE-706: Use of Incorrectly-Resolved Name or Reference"], "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A01_2021-Broken_Access_Control"], "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-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,
60
] | [
29,
60
] | [
13,
13
] | [
60,
60
] | [
"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"
] | tutorial.py | /src/tutorial.py | Jessime/Excision | MIT | |
2024-11-18T20:51:08.606587+00:00 | 1,692,694,190,000 | e9486dbd4a813658c0cd638cdd53a922e2eacb3e | 3 | {
"blob_id": "e9486dbd4a813658c0cd638cdd53a922e2eacb3e",
"branch_name": "refs/heads/main",
"committer_date": 1692694190000,
"content_id": "3843314a4e20524c42a4dd0805a2df5acc98fe30",
"detected_licenses": [
"MIT"
],
"directory_id": "0dcbf8f782d55f74dc72015214f51d6f6bd11618",
"extension": "py",
"filename": "common.py",
"fork_events_count": 7,
"gha_created_at": 1424123165000,
"gha_event_created_at": 1694391388000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 30889973,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5806,
"license": "MIT",
"license_type": "permissive",
"path": "/venvs/common.py",
"provenance": "stack-edu-0054.json.gz:582664",
"repo_name": "Julian/venvs",
"revision_date": 1692694190000,
"revision_id": "1463a9a7a3e87f9c98bcf23af77df99e0153acbc",
"snapshot_id": "ac7fff0c9536b5432294565f1cd625a5cc7b0cd3",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/Julian/venvs/1463a9a7a3e87f9c98bcf23af77df99e0153acbc/venvs/common.py",
"visit_date": "2023-08-31T23:37:13.652326"
} | 2.671875 | stackv2 | """
Objects for interacting with a central set of virtual environments.
"""
from itertools import chain
from shutil import which
import os
import platform
import subprocess
import sys
from filesystems.click import PATH
import attr
import click
import filesystems.native
def _create_virtualenv(virtualenv, arguments, python, stdout, stderr):
subprocess.check_call(
[
sys.executable,
"-m",
"virtualenv",
"--python",
which(python),
"--quiet",
]
+ list(arguments)
+ [str(virtualenv.path)],
stderr=stderr,
)
def _install_into_virtualenv(
virtualenv,
packages,
requirements,
stdout,
stderr,
):
if not packages and not requirements:
return
things = list(
chain(
packages,
*(("-r", requirement) for requirement in requirements),
),
)
subprocess.check_call(
[
str(virtualenv.binary("python")),
"-m",
"pip",
"--quiet",
"install",
]
+ things,
stdout=stdout,
stderr=stderr,
)
@attr.s
class VirtualEnv:
"""
A virtual environment.
"""
path = attr.ib()
_create = attr.ib(default=_create_virtualenv, repr=False)
_install = attr.ib(default=_install_into_virtualenv, repr=False)
def exists_on(self, filesystem):
"""
Return whether this environment already exist on the given filesystem.
"""
return filesystem.is_dir(path=self.path)
def binary(self, name):
"""
Retrieve the path to a given binary within this environment.
"""
return self.path.descendant("bin", name)
def create(
self,
arguments=(),
python=sys.executable,
stdout=sys.stdout,
stderr=sys.stderr,
):
"""
Create this virtual environment.
"""
self._create(
self,
arguments=arguments,
python=python,
stdout=stdout,
stderr=stderr,
)
def remove_from(self, filesystem):
"""
Delete this virtual environment off the given filesystem.
"""
filesystem.remove(self.path)
def recreate_on(self, filesystem, **kwargs):
"""
Recreate this environment, deleting an existing one if necessary.
"""
try:
self.remove_from(filesystem=filesystem)
except filesystems.exceptions.FileNotFound:
pass
self.create(**kwargs)
def install(self, stdout=sys.stdout, stderr=sys.stderr, **kwargs):
"""
Install a given set of packages into this environment.
"""
self._install(virtualenv=self, stdout=stdout, stderr=stderr, **kwargs)
@attr.s
class Locator:
"""
Locates virtualenvs from a common root directory.
"""
root = attr.ib()
make_virtualenv = attr.ib(default=VirtualEnv)
@classmethod
def default(cls, **kwargs):
"""
Return the default (OS-specific) location for environments.
"""
workon_home = os.getenv("WORKON_HOME")
if workon_home:
root = workon_home
else:
# On OSX, seemingly the best place to put this is also
# user_data_dir, but that's ~/Library/Application Support, which
# means that any binaries installed won't be runnable because they
# will get spaces in their shebangs. Emulating *nix behavior seems
# to be the "rightest" thing to do instead.
if platform.system() == "Darwin":
root = os.path.expanduser("~/.local/share/virtualenvs")
else:
from appdirs import user_data_dir
root = user_data_dir(appname="virtualenvs")
return cls(root=filesystems.Path.from_string(root), **kwargs)
def for_directory(self, directory):
"""
Find the virtualenv that would be associated with the given directory.
"""
return self.for_name(directory.basename())
def for_name(self, name):
"""
Retrieve the environment with the given name.
"""
if name.endswith(".py"):
name = name.removesuffix(".py")
elif name.startswith("python-"):
name = name.removeprefix("python-")
child = self.root.descendant(name.lower().replace("-", "_"))
return self.make_virtualenv(path=child)
def temporary(self):
"""
Retrieve a global temporary virtual environment.
"""
return self.for_name(".venvs-temporary-env")
class _Locator(click.ParamType):
name = "locator"
def convert(self, value, param, context):
if not isinstance(value, str):
return value
return Locator(root=PATH.convert(value, param, context))
_ROOT = click.option(
"--root",
"locator",
default=Locator.default,
type=_Locator(),
help="Specify a different root directory for virtualenvs.",
)
# Fucking click, cannot find a way to be able to override this
# parameter unless it actually is an argument, so make it one.
_FILESYSTEM = click.option(
"--filesystem",
default=filesystems.native.FS(),
type=lambda value: value,
)
_LINK_DIR = click.option(
"--link-dir",
default=filesystems.Path.from_string(
os.path.expanduser("~/.local/bin/"),
),
type=PATH,
help="The directory to link scripts into.",
)
_EX_OK = getattr(os, "EX_OK", 0)
_EX_USAGE = getattr(os, "EX_USAGE", 64)
_EX_NOINPUT = getattr(os, "EX_NOINPUT", 66)
class BadParameter(click.BadParameter):
"""
Set a different exit status from click's default.
"""
exit_code = _EX_USAGE
| 224 | 24.92 | 78 | 20 | 1,214 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_c2101ec855d0c7f4_6e23ecf8", "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": 19, "line_end": 31, "column_start": 5, "column_end": 6, "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/tmphvvervh1/c2101ec855d0c7f4.py", "start": {"line": 19, "col": 5, "offset": 349}, "end": {"line": 31, "col": 6, "offset": 626}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_c2101ec855d0c7f4_76f296ee", "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": 49, "line_end": 60, "column_start": 5, "column_end": 6, "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/tmphvvervh1/c2101ec855d0c7f4.py", "start": {"line": 49, "col": 5, "offset": 936}, "end": {"line": 60, "col": 6, "offset": 1177}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_c2101ec855d0c7f4_3f3a97a6", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 203, "line_end": 203, "column_start": 24, "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.return-not-in-function", "path": "/tmp/tmphvvervh1/c2101ec855d0c7f4.py", "start": {"line": 203, "col": 24, "offset": 5337}, "end": {"line": 203, "col": 29, "offset": 5342}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "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"
] | [
19,
49
] | [
31,
60
] | [
5,
5
] | [
6,
6
] | [
"A01:2017 - Injection",
"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()'.",
"Detected subprocess ... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | common.py | /venvs/common.py | Julian/venvs | MIT | |
2024-11-18T20:51:13.001842+00:00 | 1,687,436,962,000 | 3121cbc09734258495d98d611703aa867cb2aeab | 3 | {
"blob_id": "3121cbc09734258495d98d611703aa867cb2aeab",
"branch_name": "refs/heads/master",
"committer_date": 1687436962000,
"content_id": "a9ec67ea83353883ca6cd4004452df2693094383",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "95cec50712d94dcbbbc9cf29ea13fba29f7068cc",
"extension": "py",
"filename": "gbu.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 79283157,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9447,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/bob/bio/face/database/gbu.py",
"provenance": "stack-edu-0054.json.gz:582693",
"repo_name": "bioidiap/bob.bio.face",
"revision_date": 1687436962000,
"revision_id": "2200c110b299f124eb8d2200694323dda7d5bd3d",
"snapshot_id": "59004295077ac86c00533c7049c59ace4ec7a5b6",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/bioidiap/bob.bio.face/2200c110b299f124eb8d2200694323dda7d5bd3d/src/bob/bio/face/database/gbu.py",
"visit_date": "2023-08-25T00:07:14.560286"
} | 2.515625 | stackv2 | #!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Tiago de Freitas Pereira <tiago.pereira@idiap.ch>
# Sat 20 Aug 15:43:10 CEST 2016
import os
import xml.sax
from functools import partial
from clapper.rc import UserDefaults
import bob.io.base
from bob.bio.base.database.utils import download_file, md5_hash, search_and_open
from bob.bio.base.pipelines.abstract_classes import Database
from bob.pipelines import DelayedSample, SampleSet
rc = UserDefaults("bobrc.toml")
"""
GBU Database
Several of the rules used in this code were imported from
https://gitlab.idiap.ch/bob/bob.db.gbu/-/blob/master/bob/db/gbu/create.py
"""
def load_annotations(annotations_file):
annotations = dict()
for i, line in enumerate(annotations_file.readlines()):
# Skip the first line
if i == 0:
continue
line = line.split(",")
path = os.path.splitext(os.path.basename(line[0]))[0]
annotations[path] = {
"leye": (float(line[-1]), float(line[-2])),
"reye": (float(line[2]), float(line[1])),
}
return annotations
class File(object):
def __init__(self, subject_id, template_id, path):
self.subject_id = subject_id
self.template_id = template_id
self.path = path
class XmlFileReader(xml.sax.handler.ContentHandler):
def __init__(self):
self.m_signature = None
self.m_path = None
self.m_presentation = None
self.m_file_list = dict()
def startDocument(self):
pass
def endDocument(self):
pass
def startElement(self, name, attrs):
if name == "biometric-signature":
self.m_signature = attrs["name"] # subject_id
elif name == "presentation":
self.m_path = os.path.splitext(attrs["file-name"])[0] # path
self.m_presentation = attrs["name"] # template_id
else:
pass
def endElement(self, name):
if name == "biometric-signature":
# assert that everything was read correctly
assert (
self.m_signature is not None
and self.m_path is not None
and self.m_presentation is not None
)
# add a file to the sessions
self.m_file_list[self.m_presentation] = File(
subject_id_from_signature(self.m_signature),
self.m_presentation,
self.m_path,
)
self.m_presentation = self.m_signature = self.m_path = None
else:
pass
def subject_id_from_signature(signature):
return int(signature[4:])
def read_list(xml_file, eye_file=None):
"""Reads the xml list and attaches the eye files, if given"""
# create xml reading instance
handler = XmlFileReader()
xml.sax.parse(xml_file, handler)
return handler.m_file_list
class GBUDatabase(Database):
"""
The GBU (Good, Bad and Ugly) database consists of parts of the MBGC-V1 image set.
It defines three protocols, i.e., `Good`, `Bad` and `Ugly` for which different model and probe images are used.
.. warning::
To use this dataset protocol, you need to have the original files of the IJBC datasets.
Once you have it downloaded, please run the following command to set the path for Bob
.. code-block:: sh
bob config set bob.bio.face.gbu.directory [GBU PATH]
The code below allows you to fetch the gallery and probes of the "Good" protocol.
.. code-block:: python
>>> from bob.bio.face.database import GBUDatabase
>>> gbu = GBUDatabase(protocol="Good")
>>>
>>> # Fetching the gallery
>>> references = gbu.references()
>>> # Fetching the probes
>>> probes = gbu.probes()
"""
def __init__(
self,
protocol,
annotation_type="eyes-center",
fixed_positions=None,
original_directory=rc.get("bob.bio.face.gbu.directory"),
extension=rc.get("bob.bio.face.gbu.extension", ".jpg"),
):
import warnings
warnings.warn(
"The GBU database is not yet adapted to this version of bob. Please port it or ask for it to be ported.",
DeprecationWarning,
)
# Downloading model if not exists
urls = GBUDatabase.urls()
self.filename = download_file(
urls=urls,
destination_filename="gbu-xmls.tar.gz",
checksum="827de43434ee84020c6a949ece5e4a4d",
checksum_fct=md5_hash,
)
self.references_dict = {}
self.probes_dict = {}
self.annotations = None
self.original_directory = original_directory
self.extension = extension
self.background_samples = None
self._background_files = [
"GBU_Training_Uncontrolledx1.xml",
"GBU_Training_Uncontrolledx2.xml",
"GBU_Training_Uncontrolledx4.xml",
"GBU_Training_Uncontrolledx8.xml",
]
super().__init__(
name="gbu",
protocol=protocol,
score_all_vs_all=True,
annotation_type=annotation_type,
fixed_positions=fixed_positions,
memory_demanding=True,
)
@staticmethod
def protocols():
return ["Good", "Bad", "Ugly"]
@staticmethod
def urls():
return [
"https://www.idiap.ch/software/bob/databases/latest/gbu-xmls.tar.gz",
"http://www.idiap.ch/software/bob/databases/latest/gbu-xmls.tar.gz",
]
def background_model_samples(self):
if self.background_samples is None:
if self.annotations is None:
self.annotations = load_annotations(
search_and_open(
search_pattern="alleyes.csv", base_dir=self.filename
)
)
# for
self.background_samples = []
for b_files in self._background_files:
f = search_and_open(
search_pattern=f"{b_files}", base_dir=self.filename
)
self.background_samples += self._make_sampleset_from_filedict(
read_list(f)
)
return self.background_samples
def probes(self, group="dev"):
if self.protocol not in self.probes_dict:
if self.annotations is None:
self.annotations = load_annotations(
search_and_open(
search_pattern="alleyes.csv", base_dir=self.filename
)
)
f = search_and_open(
search_pattern=f"GBU_{self.protocol}_Query.xml",
base_dir=self.filename,
)
template_ids = [x.template_id for x in self.references()]
self.probes_dict[
self.protocol
] = self._make_sampleset_from_filedict(read_list(f), template_ids)
return self.probes_dict[self.protocol]
def references(self, group="dev"):
if self.protocol not in self.references_dict:
if self.annotations is None:
self.annotations = load_annotations(
search_and_open(
search_pattern="alleyes.csv", base_dir=self.filename
)
)
f = search_and_open(
search_pattern=f"GBU_{self.protocol}_Target.xml",
base_dir=self.filename,
)
self.references_dict[
self.protocol
] = self._make_sampleset_from_filedict(
read_list(f),
)
return self.references_dict[self.protocol]
def groups(self):
return ["dev"]
def all_samples(self, group="dev"):
self._check_group(group)
return self.references() + self.probes()
def _check_protocol(self, protocol):
assert (
protocol in self.protocols()
), "Invalid protocol `{}` not in {}".format(protocol, self.protocols())
def _check_group(self, group):
assert group in self.groups(), "Invalid group `{}` not in {}".format(
group, self.groups()
)
def _make_sampleset_from_filedict(self, file_dict, template_ids=None):
samplesets = []
for key in file_dict:
f = file_dict[key]
annotations_key = os.path.basename(f.path)
kwargs = (
{"references": template_ids} if template_ids is not None else {}
)
samplesets.append(
SampleSet(
key=f.path,
template_id=f.template_id,
subject_id=f.subject_id,
**kwargs,
samples=[
DelayedSample(
key=f.path,
annotations=self.annotations[annotations_key],
load=partial(
bob.io.base.load,
os.path.join(
self.original_directory,
f.path + self.extension,
),
),
)
],
)
)
return samplesets
| 307 | 29.77 | 117 | 24 | 1,939 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_2cd6a10c6baeb27d_e7ea7129", "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": 7, "line_end": 7, "column_start": 1, "column_end": 15, "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/tmphvvervh1/2cd6a10c6baeb27d.py", "start": {"line": 7, "col": 1, "offset": 149}, "end": {"line": 7, "col": 15, "offset": 163}, "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"
] | [
7
] | [
7
] | [
1
] | [
15
] | [
"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"
] | gbu.py | /src/bob/bio/face/database/gbu.py | bioidiap/bob.bio.face | BSD-3-Clause | |
2024-11-18T20:51:24.569724+00:00 | 1,416,205,372,000 | 0bbbdace437fa2ab716b0f208ea3a55ce55fc335 | 3 | {
"blob_id": "0bbbdace437fa2ab716b0f208ea3a55ce55fc335",
"branch_name": "refs/heads/master",
"committer_date": 1416205372000,
"content_id": "9b986be5e92ab0111afe1db4e3e5a4b80839a10d",
"detected_licenses": [
"MIT"
],
"directory_id": "246fbcc58c51a421cc8a45f42c8ef91aad3dbf2c",
"extension": "py",
"filename": "make_risks.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": 1148,
"license": "MIT",
"license_type": "permissive",
"path": "/scripts/make_risks.py",
"provenance": "stack-edu-0054.json.gz:582809",
"repo_name": "Thanajade/out-for-justice",
"revision_date": 1416205372000,
"revision_id": "2ef8bc559e05a330750e41b9803bc327e823de17",
"snapshot_id": "bee70f6f6ce78b679dedf5aca4a7760b76c7fd60",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Thanajade/out-for-justice/2ef8bc559e05a330750e41b9803bc327e823de17/scripts/make_risks.py",
"visit_date": "2021-05-28T00:45:15.156241"
} | 2.703125 | stackv2 |
import pickle
import numpy as np
import pandas as pd
def main(input_file):
with open(input_file) as f:
graph = pickle.load(f)
node_map = {int(node_id): i for i, node_id in enumerate(graph.nodes())}
outcomes = []
for fn, name in [
('data/sfnodesdtINTOXICATIONCRIME.csv', 'intoxication'),
('data/sfnodesdtPROPERTYCRIME.csv', 'property'),
('data/sfnodesdtVIOLENTCRIME.csv', 'violent'),
]:
df = pd.read_csv(fn)
df['crime_type'] = name
outcomes.append(df)
df = pd.concat(outcomes)
df['id'] = df['id'].apply(node_map.get)
df = df[df['id'].notnull()]
for (tod, dow), time_df in df.groupby(['daytime', 'superday']):
mat = time_df.set_index(['id', 'crime_type'])['preds'].unstack()
outfile = 'data/sf_crime_risks_{}_{}.npy'.format(
tod.lower().replace('-','_'),
dow.lower()
)
np.save(outfile, mat.values)
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('input_file')
args = parser.parse_args()
main(args.input_file)
| 44 | 25.09 | 75 | 15 | 303 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_6ffc4b53804b019a_a342ded0", "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": 8, "line_end": 8, "column_start": 10, "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/tmphvvervh1/6ffc4b53804b019a.py", "start": {"line": 8, "col": 10, "offset": 87}, "end": {"line": 8, "col": 26, "offset": 103}, "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_6ffc4b53804b019a_881fe1f0", "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": 9, "line_end": 9, "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/tmphvvervh1/6ffc4b53804b019a.py", "start": {"line": 9, "col": 17, "offset": 126}, "end": {"line": 9, "col": 31, "offset": 140}, "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"
] | [
9
] | [
9
] | [
17
] | [
31
] | [
"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"
] | make_risks.py | /scripts/make_risks.py | Thanajade/out-for-justice | MIT | |
2024-11-18T20:51:25.095502+00:00 | 1,553,694,071,000 | 9c3fdfdfae53b7c4aaa018acc0d65b308b924b54 | 3 | {
"blob_id": "9c3fdfdfae53b7c4aaa018acc0d65b308b924b54",
"branch_name": "refs/heads/master",
"committer_date": 1553694071000,
"content_id": "4c66ca7b8492245bc5959ab1530ce0c835e1d136",
"detected_licenses": [
"MIT"
],
"directory_id": "f3a8066d64eef9eea2d3e92179e7965ccde35d73",
"extension": "py",
"filename": "based_on_wordvec_v_0.2.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 143283830,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3187,
"license": "MIT",
"license_type": "permissive",
"path": "/extraction/based_on_wordvec_v_0.2.py",
"provenance": "stack-edu-0054.json.gz:582817",
"repo_name": "sthgreat/Automatic-summary-extraction",
"revision_date": 1553694071000,
"revision_id": "91b412b938a2e41c089f4bd4813113c069fb5756",
"snapshot_id": "29a1b2d8934f93d698deeb2984996adc406e3130",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/sthgreat/Automatic-summary-extraction/91b412b938a2e41c089f4bd4813113c069fb5756/extraction/based_on_wordvec_v_0.2.py",
"visit_date": "2020-03-25T02:18:57.137466"
} | 3.359375 | stackv2 | # author: 千山漫雪空
# time: 2018.8.7
# encoding:utf-8
# ---------------------------------------
# 摘要提取(向量实现)
# ---------------------------------------
def get_distance(np_sentence_vec, np_article_vec):
A = 0
B = 0
AB = 0
for i in range(len(np_article_vec)):
A = np.sum(np_sentence_vec*np_sentence_vec)
B = np.sum(np_article_vec*np_article_vec)
AB = np.sum(np_article_vec*np_sentence_vec)
distance = AB / (A ** 0.5 * B ** 0.5)
return distance
def process_txt(content_path):
'''
预处理文本内容
:param content_path: 文本路径(文本需utf-8编码)
:return: 返回一个列表[['今天','下雨'],['明天','天气','怎样'],['这','真的','是,'太棒了']]
'''
return_li = []
with open(r'E:\nlp\分词\停用词表_1.txt', 'r', encoding='utf-8') as f1: # 停用词表导入
stopword_li = f1.read().split('\n')
stopword_li.append('啊')
with open(content_path, 'r', encoding='utf-8') as f:
content = f.read().replace(' ', '').replace('\n', '').replace('、', '').replace('%', '')
sentence_li = content.split('。') # 分句
count = 0
for s in sentence_li: # 构建字典:序号+句子
dic_1[count] = s
count += 1
for element in sentence_li:
li = []
word_str = ','.join(jieba.cut(element)) # 分词
process_li = word_str.split(',')
for word in process_li:
if word not in stopword_li:
li.append(word)
return_li.append(li)
# print(process_li)
# return_li.append(process_li)
return return_li
def compute_sentence_vec(sentence_li): # 计算句子向量,构建字典:序号+句子向量
with open(r'E:\nlp\语料\文本摘要提取\词向量字典.txt', 'rb') as f:
dic_word_vec = pickle.load(f)
print('词向量字典加载完毕')
count = 0
for sentence in sentence_li:
sentence_vec = np.zeros(300, )
for word in sentence:
if word in dic_word_vec:
sentence_vec += dic_word_vec[word]
else:
sentence_vec += 0
dic_2[count] = sentence_vec/len(sentence)
count += 1
def compute_article_vec(): # 计算全文的向量
article_vec = np.zeros(300, )
for sentence in dic_2:
article_vec += dic_2[sentence]
return_vec = article_vec/len(dic_2)
return return_vec
def sigle_process():
article_vec = compute_article_vec()
for num in dic_2:
dic_3[num] = get_distance(dic_2[num], article_vec)
sorted(dic_3.items(), key=lambda x: x[1], reverse=True)
count = 0
for num in dic_3:
if count > 2:
break
print(dic_1[num])
count += 1
if __name__ == '__main__':
dic_1 = {} # 字典:序号+句子
dic_2 = {} # 字典:序号+句子向量
dic_3 = {} # 字典:序号+句子与文章的相似度
path = r'E:\nlp\Word_process\文章摘要提取\test_3.txt'
li = process_txt(path)
compute_sentence_vec(li)
sigle_process()
| 104 | 26.43 | 95 | 18 | 867 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_d42780bfb03b6dd6_10009142", "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": 57, "line_end": 57, "column_start": 24, "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/tmphvvervh1/d42780bfb03b6dd6.py", "start": {"line": 57, "col": 24, "offset": 1941}, "end": {"line": 57, "col": 38, "offset": 1955}, "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"
] | [
57
] | [
57
] | [
24
] | [
38
] | [
"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"
] | based_on_wordvec_v_0.2.py | /extraction/based_on_wordvec_v_0.2.py | sthgreat/Automatic-summary-extraction | MIT | |
2024-11-18T20:51:25.600110+00:00 | 1,628,770,440,000 | 58b9bfac8d565a91de74f5ac93d271333d070388 | 2 | {
"blob_id": "58b9bfac8d565a91de74f5ac93d271333d070388",
"branch_name": "refs/heads/master",
"committer_date": 1628770440000,
"content_id": "a7e59002be72773b688d4169a90e23fac17ad299",
"detected_licenses": [
"MIT"
],
"directory_id": "9fb2d55e10227a2facc960caca6d5c540826336b",
"extension": "py",
"filename": "config.py",
"fork_events_count": 0,
"gha_created_at": 1619719173000,
"gha_event_created_at": 1619720591000,
"gha_language": "Python",
"gha_license_id": null,
"github_id": 362903863,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1552,
"license": "MIT",
"license_type": "permissive",
"path": "/config.py",
"provenance": "stack-edu-0054.json.gz:582824",
"repo_name": "sadobin/Crawl3r",
"revision_date": 1628770440000,
"revision_id": "bb0d15968da3020eb937800f6a5e027beb33f4a3",
"snapshot_id": "1ef46ea8562ae0f0046e41a701106a3625de02cb",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/sadobin/Crawl3r/bb0d15968da3020eb937800f6a5e027beb33f4a3/config.py",
"visit_date": "2023-07-06T20:51:30.177140"
} | 2.359375 | stackv2 | #! /usr/bin/python3
import subprocess, os, sys
"""
Depth of crawling
E.g: If it was set to 2, passed URL and all found links in it will be crawled.
Assigning 0 to it, causing crawling the entire domain.
"""
DEPTH = 0
"""
Number of processes
"""
PROCESSES = 12
"""
Path to save the result
"""
home_dir = subprocess.check_output( 'echo $HOME', shell=True ).decode().strip()
if not os.path.exists(f"{home_dir}/crawl3r"):
os.system(f"mkdir {home_dir}/crawl3r")
RESULT_PATH = f"{home_dir}/crawl3r"
"""
Put desired request headers
- If Host header was set to TARGET, the hostname of target will be assigned to Host header during requests.
- Choose appropriate User-Agent header from user_agents.py file.
"""
REQUEST_HEADERS = {
'Host': 'TARGET',
'User-Agent': 'w7',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-US,en;q=0.5',
'Connection': 'keep-alive',
# 'DNT': '1',
#'Cache-Control': 'max-age=0',
#'Upgrade-Insecure-Requests': '1',
}
"""
Specify desired response headers to be indexed.
"""
RESPONSE_HEADERS = [
'',
]
"""
Define html attributes which contain uri (in regex format).
Check following discussion:
- https://stackoverflow.com/questions/2725156/complete-list-of-html-tag-attributes-which-have-a-url-value
"""
HTML_ATTRIBUTES = '(href|src|action)'
"""
Specify desired tag to be indexed.
"""
HTML_TAGS = [
'form',
]
| 69 | 21.49 | 113 | 11 | 405 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_2af7fdfcae1fc9f2_a22e7652", "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": 23, "line_end": 23, "column_start": 5, "column_end": 43, "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/tmphvvervh1/2af7fdfcae1fc9f2.py", "start": {"line": 23, "col": 5, "offset": 448}, "end": {"line": 23, "col": 43, "offset": 486}, "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"}}}] | 1 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
23
] | [
23
] | [
5
] | [
43
] | [
"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."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | config.py | /config.py | sadobin/Crawl3r | MIT | |
2024-11-18T21:13:45.817866+00:00 | 1,492,166,348,000 | fc08080dab14d78ec16839c1a7a72203f4083f05 | 2 | {
"blob_id": "fc08080dab14d78ec16839c1a7a72203f4083f05",
"branch_name": "refs/heads/master",
"committer_date": 1492166348000,
"content_id": "b7d73cdfda96e9a407a167d14098829e9fbb0db7",
"detected_licenses": [
"MIT"
],
"directory_id": "5217202825e0d9ea571f0e1bdaf86c42d2ca55ed",
"extension": "py",
"filename": "results.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 30636079,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2501,
"license": "MIT",
"license_type": "permissive",
"path": "/src/m3_ext/ui/results.py",
"provenance": "stack-edu-0054.json.gz:582874",
"repo_name": "barsgroup/m3-ui",
"revision_date": 1492166348000,
"revision_id": "15cd6772a5e664431e363ee9755c5fbf9a535c21",
"snapshot_id": "09fe1c837f23d44519acfaef624941531cfecbd2",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/barsgroup/m3-ui/15cd6772a5e664431e363ee9755c5fbf9a535c21/src/m3_ext/ui/results.py",
"visit_date": "2021-08-16T07:13:17.740259"
} | 2.4375 | stackv2 | # -*- coding: utf-8 -*-
"""
Результаты выполнения Action`s
"""
from django import http
from m3.actions import (
ActionResult as _ActionResult,
BaseContextedResult as _BaseContextedResult,
)
import helpers as _helpers
class ExtUIScriptResult(_BaseContextedResult):
"""
По аналогии с ExtUiComponentResult,
представляет собой некоторого наследника класса ExtUiComponent.
Единственное отличие заключается в том,
что get_http_response должен сформировать
готовый к отправке javascript.
.. note::
Т.е. должен быть вызван метод self.data.get_script()
"""
def __init__(
self, data=None, context=None,
http_params=None, secret_values=False):
super(ExtUIScriptResult, self).__init__(data, context, http_params)
self.secret_values = secret_values
def get_http_response(self):
self.data.action_context = self.context
response = http.HttpResponse(self.data.get_script())
response = self.process_http_params(response)
if self.secret_values:
response['secret_values'] = True
return response
class ExtUIComponentResult(_BaseContextedResult):
"""
Результат выполнения операции,
описанный в виде отдельного компонента пользовательского интерфейса.
В self.data хранится некоторый наследник класса m3_ext_demo.ui.ExtUiComponent.
Метод get_http_response выполняет метод render у объекта в self.data.
"""
def get_http_response(self):
self.data.action_context = self.context
return http.HttpResponse(self.data.render())
class ExtGridDataQueryResult(_ActionResult):
"""
Результат выполнения операции,
который выдает данные в формате, пригодном для
отображения в гриде
"""
def __init__(self, data=None, start=-1, limit=-1):
super(ExtGridDataQueryResult, self).__init__(data)
self.start = start
self.limit = limit
def get_http_response(self):
return http.HttpResponse(
_helpers.paginated_json_data(
self.data, self.start, self.limit))
| 68 | 29.9 | 82 | 13 | 476 | python | [{"finding_id": "semgrep_rules.python.django.security.audit.xss.direct-use-of-httpresponse_f051643b451e9aa0_d93ba060", "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": 33, "line_end": 33, "column_start": 20, "column_end": 61, "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/tmphvvervh1/f051643b451e9aa0.py", "start": {"line": 33, "col": 20, "offset": 1101}, "end": {"line": 33, "col": 61, "offset": 1142}, "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_f051643b451e9aa0_4613283b", "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": 51, "line_end": 51, "column_start": 16, "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://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/tmphvvervh1/f051643b451e9aa0.py", "start": {"line": 51, "col": 16, "offset": 1877}, "end": {"line": 51, "col": 53, "offset": 1914}, "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_f051643b451e9aa0_b994585d", "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": 66, "line_end": 68, "column_start": 16, "column_end": 52, "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/tmphvvervh1/f051643b451e9aa0.py", "start": {"line": 66, "col": 16, "offset": 2388}, "end": {"line": 68, "col": 52, "offset": 2500}, "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",
"CWE-79"
] | [
"rules.python.django.security.audit.xss.direct-use-of-httpresponse",
"rules.python.django.security.audit.xss.direct-use-of-httpresponse",
"rules.python.django.security.audit.xss.direct-use-of-httpresponse"
] | [
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
33,
51,
66
] | [
33,
51,
68
] | [
20,
16,
16
] | [
61,
53,
52
] | [
"A07:2017 - Cross-Site Scripting (XSS)",
"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,
5
] | [
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | results.py | /src/m3_ext/ui/results.py | barsgroup/m3-ui | MIT | |
2024-11-18T21:13:51.928515+00:00 | 1,600,993,454,000 | 3d4ba9fd4e01da499e743adb8b5c440ddcae878f | 3 | {
"blob_id": "3d4ba9fd4e01da499e743adb8b5c440ddcae878f",
"branch_name": "refs/heads/master",
"committer_date": 1600993454000,
"content_id": "23e4a8eb590d3bb3dc54dd5c1af181e67be0643d",
"detected_licenses": [
"MIT"
],
"directory_id": "89d935ed068a36faf738ca76c6219767685b0773",
"extension": "py",
"filename": "pretrained_resnet.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": 2289,
"license": "MIT",
"license_type": "permissive",
"path": "/transfer_learning/pretrained_resnet.py",
"provenance": "stack-edu-0054.json.gz:582908",
"repo_name": "zhangweiblan/pytorch_deep_learning_by_example",
"revision_date": 1600993454000,
"revision_id": "83c9e12364a359b9ef77f0645ca7815e9e817f58",
"snapshot_id": "880a3e480efc2ccc3f2af0b3a2beda0b3929975b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zhangweiblan/pytorch_deep_learning_by_example/83c9e12364a359b9ef77f0645ca7815e9e817f58/transfer_learning/pretrained_resnet.py",
"visit_date": "2022-12-16T04:25:18.989399"
} | 2.84375 | stackv2 | # pytorch transfer_learning example
import torch
import torchvision.models as models
from torchvision import transforms
from PIL import Image
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
# By default, models will be downloaded to your $HOME/.torch folder.
# You can modify this behavior using the $TORCH_MODEL_ZOO variable as follow:
# export TORCH_MODEL_ZOO="/local/pretrainedmodels
# load a pre-trained imagenet model
model = models.resnet18(pretrained=True)
# since we are just evaluate, put the model to eval mode
model.eval()
# load class_names for imagenet
# https://gist.githubusercontent.com/yrevar/942d3a0ac09ec9e5eb3a/raw/238f720ff059c1f82f368259d1ca4ffa5dd8f9f5/imagenet1000_clsidx_to_labels.txt
with open("imagenet1000_clsidx_to_labels.txt") as f:
class_names = eval(f.read())
# please download this sample file
# for example on linux
# wget https://en.wikipedia.org/wiki/File:African_Bush_Elephant.jpg
img_path = 'elephant.jpg'
with open(img_path, 'rb') as f:
with Image.open(f) as img:
img = img.convert('RGB')
#plt.show()
# according to: https://pytorch.org/docs/stable/torchvision/models.html
# we need to transform before feeding into pretrained model
transform = transforms.Compose([
transforms.Resize([224,224]),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
input_tensor = transform(img) # 3x400x225 -> 3x299x299 size may differ
input_tensor = input_tensor.unsqueeze(0) # 3x299x299 -> 1x3x299x299
input = torch.autograd.Variable(input_tensor, requires_grad=False)
# now do the prediction
output_logits = model(input)
#_, preds = torch.max(output_logits, 1)
top_preds = torch.topk(output_logits, k=3, dim=1)
probs = F.softmax(output_logits, dim=1)[0]
#print( output_logits )
print( top_preds )
for pred in top_preds[1][0]:
real_idx = pred.item()
print("It is: ", class_names[real_idx], " with prob:", probs[real_idx].item())
# output, we can see the African elephan has the highest score
# African elephant, Loxodonta africana
# tusker
# Indian elephant, Elephas maximus
| 68 | 32.66 | 143 | 11 | 638 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_ac6b95d7466b45ba_7c114172", "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": 22, "line_end": 22, "column_start": 6, "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/tmphvvervh1/ac6b95d7466b45ba.py", "start": {"line": 22, "col": 6, "offset": 754}, "end": {"line": 22, "col": 47, "offset": 795}, "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.eval-detected_ac6b95d7466b45ba_0cdbf121", "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": 23, "line_end": 23, "column_start": 19, "column_end": 33, "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/tmphvvervh1/ac6b95d7466b45ba.py", "start": {"line": 23, "col": 19, "offset": 820}, "end": {"line": 23, "col": 33, "offset": 834}, "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"}}}] | 2 | true | [
"CWE-95"
] | [
"rules.python.lang.security.audit.eval-detected"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
23
] | [
23
] | [
19
] | [
33
] | [
"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"
] | pretrained_resnet.py | /transfer_learning/pretrained_resnet.py | zhangweiblan/pytorch_deep_learning_by_example | MIT | |
2024-11-18T21:13:55.305813+00:00 | 1,692,115,312,000 | 63b06d9389175ebb7972bebc9d9836a4209f1e36 | 3 | {
"blob_id": "63b06d9389175ebb7972bebc9d9836a4209f1e36",
"branch_name": "refs/heads/master",
"committer_date": 1692115312000,
"content_id": "a8bf149f589c24588b5421108ec3c130bb7631cd",
"detected_licenses": [
"MIT"
],
"directory_id": "a9e60d0e5b3b5062a81da96be2d9c748a96ffca7",
"extension": "py",
"filename": "channelarchiver.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 121757699,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9593,
"license": "MIT",
"license_type": "permissive",
"path": "/configurations/i11-1-config/scripts/channelarchiver-0.0.4/channelarchiver/channelarchiver.py",
"provenance": "stack-edu-0054.json.gz:582949",
"repo_name": "openGDA/gda-diamond",
"revision_date": 1692115312000,
"revision_id": "bbb64dcfd581c30eddb210c647db5b5864b59166",
"snapshot_id": "3736718596f47607335ada470d06148d7b57526e",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/openGDA/gda-diamond/bbb64dcfd581c30eddb210c647db5b5864b59166/configurations/i11-1-config/scripts/channelarchiver-0.0.4/channelarchiver/channelarchiver.py",
"visit_date": "2023-08-16T08:01:11.075927"
} | 2.8125 | stackv2 | # -*- coding: utf-8 -*-
try:
from xmlrpclib import Server
except ImportError: # Python 3
from xmlrpc.client import Server
from collections import defaultdict
from itertools import groupby
from . import codes
from . import utils
from .models import ChannelData, ArchiveProperties, Limits
from .exceptions import ChannelNotFound, ChannelKeyMismatch
class Archiver(object):
'''
Class for interacting with an EPICS Channel Access Archiver.
'''
def __init__(self, host):
'''
host: The URL of your archiver's ArchiveDataServer.cgi. Will
look something like:
http://cr01arc01/cgi-bin/ArchiveDataServer.cgi
'''
super(Archiver, self).__init__()
self.server = Server(host)
self.archiver = self.server.archiver
self.archives_for_channel = defaultdict(list)
def scan_archives(self, channels=None):
'''
Determine which archives contain the specified channels. This
can be called prior to calling .get() with scan_archives=False
to speed up data retrieval.
channels: (optional) The channel names to scan for. Can be a
string or list of strings.
If omitted, all channels will be scanned for.
'''
if channels is None:
channels = []
elif isinstance(channels, utils.StrType):
channels = [ channels ]
channel_pattern = '|'.join(channels)
list_emptied_for_channel = defaultdict(bool)
for archive in self.archiver.archives():
archive_key = archive['key']
archives = self.archiver.names(archive_key, channel_pattern)
for archive_details in archives:
channel = archive_details['name']
start_time = utils.datetime_from_sec_and_nano(
archive_details['start_sec'],
archive_details['start_nano'],
utils.utc)
end_time = utils.datetime_from_sec_and_nano(
archive_details['end_sec'],
archive_details['end_nano'],
utils.utc)
properties = ArchiveProperties(archive_key,
start_time,
end_time)
if list_emptied_for_channel[channel]:
self.archives_for_channel[channel].append(properties)
else:
self.archives_for_channel[channel][:] = [ properties ]
list_emptied_for_channel[channel] = True
def _parse_values(self, archive_data, tz):
channel_data = ChannelData(channel=archive_data['name'],
data_type=archive_data['type'],
elements=archive_data['count'])
meta_data = archive_data['meta']
if meta_data['type'] == 0:
channel_data.states = meta_data['states']
else:
channel_data.display_limits = Limits(meta_data['disp_low'],
meta_data['disp_high'])
channel_data.alarm_limits = Limits(meta_data['alarm_low'],
meta_data['alarm_high'])
channel_data.warn_limits = Limits(meta_data['warn_low'],
meta_data['warn_high'])
channel_data.display_precision = meta_data['prec']
channel_data.units = meta_data['units']
statuses = []
severities = []
times = []
values = []
for sample in archive_data['values']:
if channel_data.elements == 1:
values.append(sample['value'][0])
else:
values.append(sample['value'])
statuses.append(sample['stat'])
severities.append(sample['sevr'])
times.append(utils.datetime_from_sec_and_nano(sample['secs'],
sample['nano'],
tz))
channel_data.values = values
channel_data.times = times
channel_data.statuses = statuses
channel_data.severities = severities
return channel_data
def get(self, channels, start, end, limit=1000,
interpolation='linear',
scan_archives=True, archive_keys=None, tz=None):
'''
Retrieves archived.
channels: The channels to get data for. Can be a string or
list of strings.
start: Start time as a datetime or ISO 8601 formatted string.
If no timezone is specified, assumes local timezone.
end: End time as a datetime or ISO 8601 formatted string.
limit: (optional) Number of data points to aim to retrieve.
The actual number returned may differ depending on the
number of points in the archive, the interpolation method
and the maximum allowed points set by the archiver.
interpolation: (optional) Method of interpolating the data.
Should be one of 'raw', 'spreadsheet', 'averaged',
'plot-binning' or 'linear'.
scan_archives: (optional) Whether or not to perform a scan to
determine which archives the channels are on. If this is to
be False .scan_archives() should have been called prior to
calling .get().
Default: True
archive_keys: (optional) The keys of the archives to get data
from. Should be the same length as channels. If this
is omitted the archives with the greatest coverage of the
requested time interval will be used.
tz: (optional) The timezone that datetimes should be returned
in. If omitted, the timezone of start will be used.
'''
received_str = isinstance(channels, utils.StrType)
if received_str:
channels = [ channels ]
if archive_keys is not None:
archive_keys = [ archive_keys ]
if isinstance(start, utils.StrType):
start = utils.datetime_from_isoformat(start)
if isinstance(end, utils.StrType):
end = utils.datetime_from_isoformat(end)
if isinstance(interpolation, utils.StrType):
interpolation = codes.interpolation[interpolation]
if start.tzinfo is None:
start = utils.localize_datetime(start, utils.local_tz)
if end.tzinfo is None:
end = utils.localize_datetime(end, utils.local_tz)
if tz is None:
tz = start.tzinfo
# Convert datetimes to seconds and nanoseconds for archiver request
start_sec, start_nano = utils.sec_and_nano_from_datetime(start)
end_sec, end_nano = utils.sec_and_nano_from_datetime(end)
if scan_archives:
self.scan_archives(channels)
if archive_keys is None:
channels_for_key = defaultdict(list)
for channel in channels:
greatest_overlap = None
key_with_greatest_overlap = None
archives = self.archives_for_channel[channel]
for archive_key, archive_start, archive_end in archives:
overlap = utils.overlap_between_intervals(start, end,
archive_start,
archive_end)
if greatest_overlap is None or overlap > greatest_overlap:
key_with_greatest_overlap = archive_key
greatest_overlap = overlap
if key_with_greatest_overlap is None:
raise ChannelNotFound(('Channel {0} not found in '
'any archive (an archive scan '
'may be needed).').format(channel))
channels_for_key[key_with_greatest_overlap].append(channel)
else:
# Group by archive key so we can request multiple channels
# with a single query
if len(channels) != len(archive_keys):
raise ChannelKeyMismatch('Number of archive keys must '
'equal number of channels.')
key_for_channel = dict(zip(channels, archive_keys))
group_func = key_for_channel.__getitem__
sorted_channels = sorted(channels, key=group_func)
group_by_iter = groupby(sorted_channels, key=group_func)
channels_for_key = dict(
(key, list(value)) for key, value in group_by_iter
)
return_data = [ None ] * len(channels)
for archive_key, channels_on_archive in channels_for_key.items():
data = self.archiver.values(archive_key, channels_on_archive,
start_sec, start_nano,
end_sec, end_nano,
limit, interpolation)
for archive_data in data:
channel_data = self._parse_values(archive_data, tz)
channel_data.archive_key = archive_key
channel_data.interpolation = interpolation
index = channels.index(channel_data.channel)
return_data[index] = channel_data
return return_data if not received_str else return_data[0]
| 219 | 42.8 | 78 | 20 | 1,761 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xmlrpc_5177c50bed6fb208_f9f5bec1", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xmlrpc", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 4, "line_end": 4, "column_start": 5, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": "CWE-776: Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://pypi.org/project/defusedxml/", "title": null}, {"url": "https://docs.python.org/3/library/xml.html#xml-vulnerabilities", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xmlrpc", "path": "/tmp/tmphvvervh1/5177c50bed6fb208.py", "start": {"line": 4, "col": 5, "offset": 34}, "end": {"line": 4, "col": 33, "offset": 62}, "extra": {"message": "Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead.", "metadata": {"cwe": ["CWE-776: Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion')"], "owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "source-rule-url": "https://github.com/PyCQA/bandit/blob/07f84cb5f5e7c1055e6feaa0fe93afa471de0ac3/bandit/blacklists/imports.py#L160", "references": ["https://pypi.org/project/defusedxml/", "https://docs.python.org/3/library/xml.html#xml-vulnerabilities"], "category": "security", "technology": ["python"], "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-xmlrpc_5177c50bed6fb208_c32e229c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xmlrpc", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 6, "line_end": 6, "column_start": 5, "column_end": 37, "code_snippet": "requires login"}, "cwe_id": "CWE-776: Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://pypi.org/project/defusedxml/", "title": null}, {"url": "https://docs.python.org/3/library/xml.html#xml-vulnerabilities", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xmlrpc", "path": "/tmp/tmphvvervh1/5177c50bed6fb208.py", "start": {"line": 6, "col": 5, "offset": 98}, "end": {"line": 6, "col": 37, "offset": 130}, "extra": {"message": "Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead.", "metadata": {"cwe": ["CWE-776: Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion')"], "owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "source-rule-url": "https://github.com/PyCQA/bandit/blob/07f84cb5f5e7c1055e6feaa0fe93afa471de0ac3/bandit/blacklists/imports.py#L160", "references": ["https://pypi.org/project/defusedxml/", "https://docs.python.org/3/library/xml.html#xml-vulnerabilities"], "category": "security", "technology": ["python"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-776",
"CWE-776"
] | [
"rules.python.lang.security.use-defused-xmlrpc",
"rules.python.lang.security.use-defused-xmlrpc"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | [
4,
6
] | [
4,
6
] | [
5,
5
] | [
33,
37
] | [
"A04:2017 - XML External Entities (XXE)",
"A04:2017 - XML External Entities (XXE)"
] | [
"Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead.",
"Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead."
] | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | channelarchiver.py | /configurations/i11-1-config/scripts/channelarchiver-0.0.4/channelarchiver/channelarchiver.py | openGDA/gda-diamond | MIT | |
2024-11-18T21:13:55.814965+00:00 | 1,603,214,045,000 | 12f87427715a1c74ee6014edce3b6dd2bed504b7 | 3 | {
"blob_id": "12f87427715a1c74ee6014edce3b6dd2bed504b7",
"branch_name": "refs/heads/master",
"committer_date": 1603214045000,
"content_id": "a7a8d764113bb584ff27f84642fc4c521213af20",
"detected_licenses": [
"MIT"
],
"directory_id": "c8ed31440e7a5e4813b60440efd27f2a7df0de21",
"extension": "py",
"filename": "take_ss.py",
"fork_events_count": 1,
"gha_created_at": 1580797652000,
"gha_event_created_at": 1603214023000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 238138620,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1163,
"license": "MIT",
"license_type": "permissive",
"path": "/take_ss.py",
"provenance": "stack-edu-0054.json.gz:582956",
"repo_name": "alper111/symbol-emergence",
"revision_date": 1603214045000,
"revision_id": "a4abd5d26b6fb36fe1ab3d6304a257df29be8e2c",
"snapshot_id": "7e1fa7b84956e5ce0fc20d0193e6db92592ff9ae",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/alper111/symbol-emergence/a4abd5d26b6fb36fe1ab3d6304a257df29be8e2c/take_ss.py",
"visit_date": "2022-12-30T23:52:21.162366"
} | 2.546875 | stackv2 | """Take screenshots of states."""
import os
import argparse
import torch
import rospy
import numpy as np
import env
import torobo_wrapper
parser = argparse.ArgumentParser("Record states.")
parser.add_argument("-s", help="state file", type=str, required=True)
parser.add_argument("-o", help="output folder", type=str, required=True)
args = parser.parse_args()
if not os.path.exists(args.o):
os.makedirs(args.o)
# INITIALIZE ROSNODE
rospy.init_node("test_node", anonymous=True)
rate = rospy.Rate(100)
rospy.sleep(1.0)
robot = torobo_wrapper.Torobo()
rospy.sleep(1.0)
# INITIALIZE ENVIRONMENT
objects = ["target_plate", "small_cube"]
random_ranges = {
"target_plate": np.array([[0.32, 0.52], [0.30, 0.50], [1.125, 1.125]]),
"small_cube": np.array([[0.32, 0.52], [0.0, 0.15], [1.155, 1.155]]),
}
world = env.Environment(robot=robot, objects=objects, rng_ranges=random_ranges)
rospy.sleep(0.5)
states = torch.load(args.s)
for i, s in enumerate(states):
s = s.tolist()
world.set_model_state("target_plate", s[:3], s[3:7])
world.set_model_state("small_cube", s[7:10], s[10:14])
os.system("import -window Gazebo %s/%d.jpg" % (args.o, i))
| 39 | 28.82 | 79 | 10 | 369 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_ad341089206297c7_fd6455fe", "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": 39, "line_end": 39, "column_start": 5, "column_end": 63, "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/tmphvvervh1/ad341089206297c7.py", "start": {"line": 39, "col": 5, "offset": 1104}, "end": {"line": 39, "col": 63, "offset": 1162}, "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_ad341089206297c7_405ebff9", "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": 39, "line_end": 39, "column_start": 5, "column_end": 63, "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/tmphvvervh1/ad341089206297c7.py", "start": {"line": 39, "col": 5, "offset": 1104}, "end": {"line": 39, "col": 63, "offset": 1162}, "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"}}}] | 2 | 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"
] | [
39,
39
] | [
39,
39
] | [
5,
5
] | [
63,
63
] | [
"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"
] | take_ss.py | /take_ss.py | alper111/symbol-emergence | MIT | |
2024-11-18T21:13:56.337613+00:00 | 1,308,055,566,000 | 5e28969e309219c2b00022d7b6aa5a3b56a75c06 | 2 | {
"blob_id": "5e28969e309219c2b00022d7b6aa5a3b56a75c06",
"branch_name": "refs/heads/master",
"committer_date": 1308055566000,
"content_id": "928518a0100900551f4c70fef1e1a5ad4fc4b013",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "a4b467c857f645910eb66259d0a3e1ca3a26f866",
"extension": "py",
"filename": "rstpages.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": 2916,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/hbag/rstpages/rstpages.py",
"provenance": "stack-edu-0054.json.gz:582964",
"repo_name": "vlad73/handlerbag",
"revision_date": 1308055566000,
"revision_id": "15639eb68f24eb70f4035fd412a6e0739860dc2f",
"snapshot_id": "624dbb30a7028c2678f4d518d0a807c3019b634f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vlad73/handlerbag/15639eb68f24eb70f4035fd412a6e0739860dc2f/hbag/rstpages/rstpages.py",
"visit_date": "2020-04-05T18:29:27.401880"
} | 2.484375 | stackv2 | '''Builds reStructuredText files into HTML as they change.'''
# tornado
import tornado.web
# watchdog
from watchdog.observers.polling import PollingObserver
from watchdog.events import PatternMatchingEventHandler
# std lib
import os.path
import datetime
import urlparse
import subprocess
import glob
import time
class PageWatcher(PatternMatchingEventHandler):
def __init__(self, options={}, **kwargs):
super(PageWatcher, self).__init__(**kwargs)
self.options = options
def _render(self, path):
root, ext = os.path.splitext(path)
opts = self.options.get('writer_opts')
args = ['rst2html-pygments']
if opts: args.extend(opts)
args.extend([path, root + '.html'])
subprocess.call(args)
def _remove(self, path):
# rm html for old file
root, ext = os.path.splitext(path)
try:
os.remove(root + '.html')
except OSError:
pass
def on_created(self, event):
self._render(event.src_path)
def on_deleted(self, event):
self._remove(event.src_path)
def on_modified(self, event):
self._render(event.src_path)
def on_moved(self, event):
self._remove(event.src_path)
self._render(event.dest_path)
class RstPagesHandler(tornado.web.StaticFileHandler):
@classmethod
def register(cls, path='.', **options):
ob = cls.observer = PollingObserver()
w = PageWatcher(patterns=['*.rst'], options=options)
# render existing documents
for fn in glob.glob(os.path.join(path, '*.rst')):
root, ext = os.path.splitext(fn)
html = root+'.html'
if not os.path.isfile(html):
w._render(html)
ob.schedule(w, path)
ob.start()
@classmethod
def unregister(cls):
cls.observer.stop()
cls.observer.join()
def initialize(self, writer_opts, **kwargs):
super(RstPagesHandler, self).initialize(**kwargs)
def get(self, fn, *args, **kwargs):
if not fn:
# generate index
docs = [(os.path.basename(fn), time.ctime(os.stat(fn).st_mtime))
for fn in glob.glob(os.path.join(self.root, '*.html'))]
docs.sort()
self.render('rstpages.html', docs=docs)
else:
super(RstPagesHandler, self).get(fn, *args, **kwargs)
def get_handler_map(app, webroot, options):
return [(webroot+'rstpages/?(.*)', RstPagesHandler, options)]
def get_default_options(app):
return {
'path' : os.path.join(app.dataPath, 'rstpages'),
'writer_opts' : [
'--stylesheet-path='+os.path.join(app.bagPath, 'rstpages', 'lsr.css'),
'--strip-comments',
'--generator',
'--field-name-limit=20',
'--date',
'--time'
]
} | 95 | 29.71 | 82 | 17 | 657 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_bdfc61b47155a266_cbc37c3e", "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": 26, "line_end": 26, "column_start": 9, "column_end": 30, "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/tmphvvervh1/bdfc61b47155a266.py", "start": {"line": 26, "col": 9, "offset": 738}, "end": {"line": 26, "col": 30, "offset": 759}, "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_bdfc61b47155a266_3d515a27", "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": 26, "line_end": 26, "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/tmphvvervh1/bdfc61b47155a266.py", "start": {"line": 26, "col": 20, "offset": 749}, "end": {"line": 26, "col": 24, "offset": 753}, "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"
] | [
26
] | [
26
] | [
9
] | [
30
] | [
"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"
] | rstpages.py | /hbag/rstpages/rstpages.py | vlad73/handlerbag | BSD-3-Clause | |
2024-11-18T21:13:57.500908+00:00 | 1,692,109,124,000 | 9653165d21e990cddff02f80901b95882825cc3a | 3 | {
"blob_id": "9653165d21e990cddff02f80901b95882825cc3a",
"branch_name": "refs/heads/main",
"committer_date": 1692109124000,
"content_id": "417040e342bf88acc65bd50d51f896dce0387991",
"detected_licenses": [
"MIT"
],
"directory_id": "3dfa0692f46628edc9dc2792bd17746700d69d18",
"extension": "py",
"filename": "util.py",
"fork_events_count": 65,
"gha_created_at": 1551560776000,
"gha_event_created_at": 1693919220000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 173498915,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1245,
"license": "MIT",
"license_type": "permissive",
"path": "/bot/util.py",
"provenance": "stack-edu-0054.json.gz:582978",
"repo_name": "anthonywritescode/twitch-chat-bot",
"revision_date": 1692109124000,
"revision_id": "ba63038df9f966fcfb8aeb5104d761b2ac38c7f3",
"snapshot_id": "d71546290a2ea6d647442ad6bc551355046ffa56",
"src_encoding": "UTF-8",
"star_events_count": 81,
"url": "https://raw.githubusercontent.com/anthonywritescode/twitch-chat-bot/ba63038df9f966fcfb8aeb5104d761b2ac38c7f3/bot/util.py",
"visit_date": "2023-08-18T03:43:08.042050"
} | 2.515625 | stackv2 | from __future__ import annotations
import asyncio.subprocess
import contextlib
import os.path
import tempfile
from typing import Generator
from typing import IO
def get_quantified_unit(unit: str, amount: int) -> str:
if amount == 1:
return unit
else:
return f'{unit}s'
def seconds_to_readable(seconds: int) -> str:
parts = []
for n, unit in (
(60 * 60, 'hour'),
(60, 'minute'),
(1, 'second'),
):
if seconds // n:
unit = get_quantified_unit(unit, seconds // n)
parts.append(f'{seconds // n} {unit}')
seconds %= n
return ', '.join(parts)
@contextlib.contextmanager
def atomic_open(filename: str) -> Generator[IO[bytes], None, None]:
fd, fname = tempfile.mkstemp(dir=os.path.dirname(filename))
try:
with open(fd, 'wb') as f:
yield f
os.replace(fname, filename)
except BaseException:
os.remove(fname)
raise
async def check_call(*cmd: str) -> None:
proc = await asyncio.subprocess.create_subprocess_exec(
*cmd, stdout=asyncio.subprocess.DEVNULL,
)
await proc.communicate()
if proc.returncode != 0:
raise ValueError(cmd, proc.returncode)
| 50 | 23.9 | 67 | 14 | 305 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-asyncio-create-exec-audit_35e4d07150f07f8b_546685e1", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-asyncio-create-exec-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected 'create_subprocess_exec' function 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": 45, "line_end": 47, "column_start": 18, "column_end": 6, "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://docs.python.org/3/library/asyncio-subprocess.html#asyncio.create_subprocess_exec", "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-asyncio-create-exec-audit", "path": "/tmp/tmphvvervh1/35e4d07150f07f8b.py", "start": {"line": 45, "col": 18, "offset": 1042}, "end": {"line": 47, "col": 6, "offset": 1139}, "extra": {"message": "Detected 'create_subprocess_exec' function 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://docs.python.org/3/library/asyncio-subprocess.html#asyncio.create_subprocess_exec", "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-asyncio-create-exec-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
45
] | [
47
] | [
18
] | [
6
] | [
"A01:2017 - Injection"
] | [
"Detected 'create_subprocess_exec' function 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"
] | util.py | /bot/util.py | anthonywritescode/twitch-chat-bot | MIT | |
2024-11-18T21:13:57.632779+00:00 | 1,303,627,704,000 | 6bf2f8418500ffc2a8f8a1e8527c2a82f0dc85dd | 2 | {
"blob_id": "6bf2f8418500ffc2a8f8a1e8527c2a82f0dc85dd",
"branch_name": "refs/heads/master",
"committer_date": 1303627704000,
"content_id": "9fbdda1bcb720081a2d6d49c0fa6d4f9866baf84",
"detected_licenses": [
"MIT"
],
"directory_id": "0cacc4500d7816ea9c22755b21d6fadc2c4f73c1",
"extension": "py",
"filename": "post_results.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 867775,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 836,
"license": "MIT",
"license_type": "permissive",
"path": "/python/post_results.py",
"provenance": "stack-edu-0054.json.gz:582980",
"repo_name": "ravi-rajakumar/Zombie-Simulator",
"revision_date": 1303627704000,
"revision_id": "a6cfd2fb81c1e1c0ef11e7556b0949755f94b7c3",
"snapshot_id": "9ab716f551bbd8d788920433c6a1008739b0553d",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/ravi-rajakumar/Zombie-Simulator/a6cfd2fb81c1e1c0ef11e7556b0949755f94b7c3/python/post_results.py",
"visit_date": "2016-09-06T18:23:51.819828"
} | 2.390625 | stackv2 | #!/usr/bin/env python
# import various dependencies
import MySQLdb, sys, cgi, connection
print "Content-type: text/html\n"
The_Form = cgi.FieldStorage()
if The_Form:
columns = "(`date`"
cells = "(CURRENT_TIMESTAMP"
for i in The_Form:
columns += ", `" + i + "`"
cells += ", '" + The_Form.getvalue(i) + "'"
columns += ")"
cells += ")"
try:
conn = MySQLdb.connect (host = connection.db_host, user = connection.db_user, passwd = connection.db_pass, db = connection.db)
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit (1)
sql = "INSERT INTO `zombie_data`.`zombie_sim_outcomes` " + columns + " VALUES " + cells
try:
cursor = conn.cursor ()
cursor.execute (sql)
cursor.close ()
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit (1)
| 34 | 23.59 | 129 | 12 | 249 | python | [{"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_75d22964986017e7_e1e12123", "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": 30, "line_end": 30, "column_start": 3, "column_end": 23, "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/tmphvvervh1/75d22964986017e7.py", "start": {"line": 30, "col": 3, "offset": 708}, "end": {"line": 30, "col": 23, "offset": 728}, "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"}}}] | 1 | true | [
"CWE-89"
] | [
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
30
] | [
30
] | [
3
] | [
23
] | [
"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"
] | post_results.py | /python/post_results.py | ravi-rajakumar/Zombie-Simulator | MIT | |
2024-11-18T21:13:58.306447+00:00 | 1,599,204,546,000 | d893bf7dbe5e5efd4cad52a8b778e27a89b2f3ea | 3 | {
"blob_id": "d893bf7dbe5e5efd4cad52a8b778e27a89b2f3ea",
"branch_name": "refs/heads/master",
"committer_date": 1599204546000,
"content_id": "badcc57b7ac5c3fa842b85e950fb47831abc8afb",
"detected_licenses": [
"MIT"
],
"directory_id": "ff79872e99211fc7f974d5cfefa87f80acca773d",
"extension": "py",
"filename": "connection.py",
"fork_events_count": 1,
"gha_created_at": 1589882809000,
"gha_event_created_at": 1618937163000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 265212109,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2187,
"license": "MIT",
"license_type": "permissive",
"path": "/project/main/db/connection.py",
"provenance": "stack-edu-0054.json.gz:582989",
"repo_name": "arezamoosavi/BTC-Alarming",
"revision_date": 1599204546000,
"revision_id": "8a11970889efad55c24c6fece59d48f129ede7d3",
"snapshot_id": "851a9652aeea765bf6a922c9ee81207b57fdf07a",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/arezamoosavi/BTC-Alarming/8a11970889efad55c24c6fece59d48f129ede7d3/project/main/db/connection.py",
"visit_date": "2023-04-04T09:37:59.205495"
} | 2.875 | stackv2 | import os
import asyncpg
from datetime import datetime
class Postgres:
def __init__(self):
self.db_url = os.getenv('POSTGRES_URL')
async def checkConnection(self):
conn = await asyncpg.connect(self.db_url)
await conn.execute('''
CREATE TABLE IF NOT EXISTS testusers(
id serial PRIMARY KEY,
name text,
dob date
)
''')
# Insert a record into the created table.
await conn.execute('''
INSERT INTO testusers(name, dob) VALUES($1, $2)
''', 'Bob', datetime.utcnow())
# Select a row from the table.
row = await conn.fetchrow(
'SELECT * FROM testusers WHERE name = $1', 'Bob')
print(dict(row), type(row))
# test ideas:1
print('------test idea1---------')
record=('Ali',datetime.utcnow())
await conn.execute('''
INSERT INTO testusers(name, dob) VALUES($1, $2)
''', record[0], record[1])
allrow = await conn.fetch('SELECT name FROM testusers')
print(allrow, type(allrow))
print([dict(row) for row in allrow])
print('# test ideas:1 :::::SAVED to USD_BTC table!!')
# test ideas:2
print('------test idea2---------')
db = 'testusers'
trow = await conn.fetch('SELECT name FROM {}'.format(db))
print(trow[-1])
print('# test ideas:2 :::::Got it!!')
# test ideas:3
print('------test idea3---------')
record=('Alireza',datetime.utcnow())
que = '''INSERT INTO {}(name, dob) VALUES($1, $2)'''.format('testusers')
await conn.execute(que, record[0], record[1])
allrow = await conn.fetch('SELECT name FROM {}'.format('testusers'))
print(allrow, type(allrow))
print([dict(row) for row in allrow])
print('# test ideas:3 :::::Worked!!')
# Drop Table
query = "DROP TABLE IF EXISTS {} CASCADE;".format("testusers")
await conn.execute(query)
print('\n\n', 'connection was succesfull!','\n\n', datetime.utcnow(), '\n\n\n' )
await conn.close() | 69 | 30.71 | 88 | 14 | 518 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.sqli.asyncpg-sqli_9956838d82c370d4_23abe711", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.sqli.asyncpg-sqli", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected string concatenation with a non-literal variable in a asyncpg 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 create parameterized queries like so: 'conn.fetch(\"SELECT $1 FROM table\", value)'. You can also create prepared statements with 'Connection.prepare': 'stmt = conn.prepare(\"SELECT $1 FROM table\"); await stmt.fetch(user_value)'", "remediation": "", "location": {"file_path": "unknown", "line_start": 47, "line_end": 47, "column_start": 22, "column_end": 66, "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://github.com/MagicStack/asyncpg", "title": null}, {"url": "https://magicstack.github.io/asyncpg/current/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.sqli.asyncpg-sqli", "path": "/tmp/tmphvvervh1/9956838d82c370d4.py", "start": {"line": 47, "col": 22, "offset": 1375}, "end": {"line": 47, "col": 66, "offset": 1419}, "extra": {"message": "Detected string concatenation with a non-literal variable in a asyncpg 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 create parameterized queries like so: 'conn.fetch(\"SELECT $1 FROM table\", value)'. You can also create prepared statements with 'Connection.prepare': 'stmt = conn.prepare(\"SELECT $1 FROM table\"); await stmt.fetch(user_value)'", "metadata": {"references": ["https://github.com/MagicStack/asyncpg", "https://magicstack.github.io/asyncpg/current/"], "category": "security", "cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "technology": ["asyncpg"], "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.lang.security.audit.sqli.asyncpg-sqli_9956838d82c370d4_d8526b68", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.sqli.asyncpg-sqli", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected string concatenation with a non-literal variable in a asyncpg 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 create parameterized queries like so: 'conn.fetch(\"SELECT impor FROM table\", value)'. You can also create prepared statements with 'Connection.prepare': 'stmt = conn.prepare(\"SELECT impor FROM table\"); await stmt.fetch(user_value)'", "remediation": "", "location": {"file_path": "unknown", "line_start": 47, "line_end": 47, "column_start": 22, "column_end": 66, "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://github.com/MagicStack/asyncpg", "title": null}, {"url": "https://magicstack.github.io/asyncpg/current/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.sqli.asyncpg-sqli", "path": "/tmp/tmphvvervh1/9956838d82c370d4.py", "start": {"line": 47, "col": 22, "offset": 1375}, "end": {"line": 47, "col": 66, "offset": 1419}, "extra": {"message": "Detected string concatenation with a non-literal variable in a asyncpg 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 create parameterized queries like so: 'conn.fetch(\"SELECT impor FROM table\", value)'. You can also create prepared statements with 'Connection.prepare': 'stmt = conn.prepare(\"SELECT impor FROM table\"); await stmt.fetch(user_value)'", "metadata": {"references": ["https://github.com/MagicStack/asyncpg", "https://magicstack.github.io/asyncpg/current/"], "category": "security", "cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "technology": ["asyncpg"], "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.lang.security.audit.sqli.asyncpg-sqli_9956838d82c370d4_198c997c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.sqli.asyncpg-sqli", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected string concatenation with a non-literal variable in a asyncpg 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 create parameterized queries like so: 'conn.fetch(\"SELECT $1 FROM table\", value)'. You can also create prepared statements with 'Connection.prepare': 'stmt = conn.prepare(\"SELECT $1 FROM table\"); await stmt.fetch(user_value)'", "remediation": "", "location": {"file_path": "unknown", "line_start": 56, "line_end": 56, "column_start": 15, "column_end": 54, "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://github.com/MagicStack/asyncpg", "title": null}, {"url": "https://magicstack.github.io/asyncpg/current/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.sqli.asyncpg-sqli", "path": "/tmp/tmphvvervh1/9956838d82c370d4.py", "start": {"line": 56, "col": 15, "offset": 1698}, "end": {"line": 56, "col": 54, "offset": 1737}, "extra": {"message": "Detected string concatenation with a non-literal variable in a asyncpg 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 create parameterized queries like so: 'conn.fetch(\"SELECT $1 FROM table\", value)'. You can also create prepared statements with 'Connection.prepare': 'stmt = conn.prepare(\"SELECT $1 FROM table\"); await stmt.fetch(user_value)'", "metadata": {"references": ["https://github.com/MagicStack/asyncpg", "https://magicstack.github.io/asyncpg/current/"], "category": "security", "cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "technology": ["asyncpg"], "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.lang.security.audit.sqli.asyncpg-sqli_9956838d82c370d4_63172336", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.sqli.asyncpg-sqli", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected string concatenation with a non-literal variable in a asyncpg 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 create parameterized queries like so: 'conn.fetch(\"SELECT import FROM table\", value)'. You can also create prepared statements with 'Connection.prepare': 'stmt = conn.prepare(\"SELECT import FROM table\"); await stmt.fetch(user_value)'", "remediation": "", "location": {"file_path": "unknown", "line_start": 56, "line_end": 56, "column_start": 15, "column_end": 54, "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://github.com/MagicStack/asyncpg", "title": null}, {"url": "https://magicstack.github.io/asyncpg/current/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.sqli.asyncpg-sqli", "path": "/tmp/tmphvvervh1/9956838d82c370d4.py", "start": {"line": 56, "col": 15, "offset": 1698}, "end": {"line": 56, "col": 54, "offset": 1737}, "extra": {"message": "Detected string concatenation with a non-literal variable in a asyncpg 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 create parameterized queries like so: 'conn.fetch(\"SELECT import FROM table\", value)'. You can also create prepared statements with 'Connection.prepare': 'stmt = conn.prepare(\"SELECT import FROM table\"); await stmt.fetch(user_value)'", "metadata": {"references": ["https://github.com/MagicStack/asyncpg", "https://magicstack.github.io/asyncpg/current/"], "category": "security", "cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "technology": ["asyncpg"], "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_9956838d82c370d4_2e687e85", "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": 56, "line_end": 56, "column_start": 15, "column_end": 54, "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/tmphvvervh1/9956838d82c370d4.py", "start": {"line": 56, "col": 15, "offset": 1698}, "end": {"line": 56, "col": 54, "offset": 1737}, "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.sqli.asyncpg-sqli_9956838d82c370d4_9f8dd2c2", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.sqli.asyncpg-sqli", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected string concatenation with a non-literal variable in a asyncpg 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 create parameterized queries like so: 'conn.fetch(\"SELECT $1 FROM table\", value)'. You can also create prepared statements with 'Connection.prepare': 'stmt = conn.prepare(\"SELECT $1 FROM table\"); await stmt.fetch(user_value)'", "remediation": "", "location": {"file_path": "unknown", "line_start": 58, "line_end": 58, "column_start": 24, "column_end": 77, "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://github.com/MagicStack/asyncpg", "title": null}, {"url": "https://magicstack.github.io/asyncpg/current/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.sqli.asyncpg-sqli", "path": "/tmp/tmphvvervh1/9956838d82c370d4.py", "start": {"line": 58, "col": 24, "offset": 1762}, "end": {"line": 58, "col": 77, "offset": 1815}, "extra": {"message": "Detected string concatenation with a non-literal variable in a asyncpg 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 create parameterized queries like so: 'conn.fetch(\"SELECT $1 FROM table\", value)'. You can also create prepared statements with 'Connection.prepare': 'stmt = conn.prepare(\"SELECT $1 FROM table\"); await stmt.fetch(user_value)'", "metadata": {"references": ["https://github.com/MagicStack/asyncpg", "https://magicstack.github.io/asyncpg/current/"], "category": "security", "cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "technology": ["asyncpg"], "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.lang.security.audit.sqli.asyncpg-sqli_9956838d82c370d4_304023ac", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.sqli.asyncpg-sqli", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected string concatenation with a non-literal variable in a asyncpg 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 create parameterized queries like so: 'conn.fetch(\"SELECT impor FROM table\", value)'. You can also create prepared statements with 'Connection.prepare': 'stmt = conn.prepare(\"SELECT impor FROM table\"); await stmt.fetch(user_value)'", "remediation": "", "location": {"file_path": "unknown", "line_start": 58, "line_end": 58, "column_start": 24, "column_end": 77, "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://github.com/MagicStack/asyncpg", "title": null}, {"url": "https://magicstack.github.io/asyncpg/current/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.sqli.asyncpg-sqli", "path": "/tmp/tmphvvervh1/9956838d82c370d4.py", "start": {"line": 58, "col": 24, "offset": 1762}, "end": {"line": 58, "col": 77, "offset": 1815}, "extra": {"message": "Detected string concatenation with a non-literal variable in a asyncpg 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 create parameterized queries like so: 'conn.fetch(\"SELECT impor FROM table\", value)'. You can also create prepared statements with 'Connection.prepare': 'stmt = conn.prepare(\"SELECT impor FROM table\"); await stmt.fetch(user_value)'", "metadata": {"references": ["https://github.com/MagicStack/asyncpg", "https://magicstack.github.io/asyncpg/current/"], "category": "security", "cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "technology": ["asyncpg"], "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.lang.security.audit.formatted-sql-query_9956838d82c370d4_f6885472", "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": 66, "line_end": 66, "column_start": 15, "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/tmphvvervh1/9956838d82c370d4.py", "start": {"line": 66, "col": 15, "offset": 2051}, "end": {"line": 66, "col": 34, "offset": 2070}, "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.asyncpg-sqli_9956838d82c370d4_14d838e4", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.sqli.asyncpg-sqli", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected string concatenation with a non-literal variable in a asyncpg 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 create parameterized queries like so: 'conn.fetch(\"SELECT $1 FROM table\", value)'. You can also create prepared statements with 'Connection.prepare': 'stmt = conn.prepare(\"SELECT $1 FROM table\"); await stmt.fetch(user_value)'", "remediation": "", "location": {"file_path": "unknown", "line_start": 66, "line_end": 66, "column_start": 15, "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://github.com/MagicStack/asyncpg", "title": null}, {"url": "https://magicstack.github.io/asyncpg/current/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.sqli.asyncpg-sqli", "path": "/tmp/tmphvvervh1/9956838d82c370d4.py", "start": {"line": 66, "col": 15, "offset": 2051}, "end": {"line": 66, "col": 34, "offset": 2070}, "extra": {"message": "Detected string concatenation with a non-literal variable in a asyncpg 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 create parameterized queries like so: 'conn.fetch(\"SELECT $1 FROM table\", value)'. You can also create prepared statements with 'Connection.prepare': 'stmt = conn.prepare(\"SELECT $1 FROM table\"); await stmt.fetch(user_value)'", "metadata": {"references": ["https://github.com/MagicStack/asyncpg", "https://magicstack.github.io/asyncpg/current/"], "category": "security", "cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "technology": ["asyncpg"], "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.lang.security.audit.sqli.asyncpg-sqli_9956838d82c370d4_03470071", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.sqli.asyncpg-sqli", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected string concatenation with a non-literal variable in a asyncpg 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 create parameterized queries like so: 'conn.fetch(\"SELECT import FROM table\", value)'. You can also create prepared statements with 'Connection.prepare': 'stmt = conn.prepare(\"SELECT import FROM table\"); await stmt.fetch(user_value)'", "remediation": "", "location": {"file_path": "unknown", "line_start": 66, "line_end": 66, "column_start": 15, "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://github.com/MagicStack/asyncpg", "title": null}, {"url": "https://magicstack.github.io/asyncpg/current/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.sqli.asyncpg-sqli", "path": "/tmp/tmphvvervh1/9956838d82c370d4.py", "start": {"line": 66, "col": 15, "offset": 2051}, "end": {"line": 66, "col": 34, "offset": 2070}, "extra": {"message": "Detected string concatenation with a non-literal variable in a asyncpg 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 create parameterized queries like so: 'conn.fetch(\"SELECT import FROM table\", value)'. You can also create prepared statements with 'Connection.prepare': 'stmt = conn.prepare(\"SELECT import FROM table\"); await stmt.fetch(user_value)'", "metadata": {"references": ["https://github.com/MagicStack/asyncpg", "https://magicstack.github.io/asyncpg/current/"], "category": "security", "cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "technology": ["asyncpg"], "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_9956838d82c370d4_f7e9d0ea", "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": 66, "line_end": 66, "column_start": 15, "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/tmphvvervh1/9956838d82c370d4.py", "start": {"line": 66, "col": 15, "offset": 2051}, "end": {"line": 66, "col": 34, "offset": 2070}, "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"}}}] | 11 | true | [
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89"
] | [
"rules.python.lang.security.audit.sqli.asyncpg-sqli",
"rules.python.lang.security.audit.sqli.asyncpg-sqli",
"rules.python.lang.security.audit.sqli.asyncpg-sqli",
"rules.python.lang.security.audit.sqli.asyncpg-sqli",
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query",
"rules.python.lang.securi... | [
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"HIGH",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"HIGH"
] | [
47,
47,
56,
56,
56,
58,
58,
66,
66,
66,
66
] | [
47,
47,
56,
56,
56,
58,
58,
66,
66,
66,
66
] | [
22,
22,
15,
15,
15,
24,
24,
15,
15,
15,
15
] | [
66,
66,
54,
54,
54,
77,
77,
34,
34,
34,
34
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"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 string concatenation with a non-literal variable in a asyncpg 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 create parameterized quer... | [
5,
5,
5,
5,
7.5,
5,
5,
5,
5,
5,
7.5
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | connection.py | /project/main/db/connection.py | arezamoosavi/BTC-Alarming | MIT | |
2024-11-18T21:14:01.274671+00:00 | 1,605,727,528,000 | d937cd472c073157c781b8a31ce0fc22c783eea2 | 3 | {
"blob_id": "d937cd472c073157c781b8a31ce0fc22c783eea2",
"branch_name": "refs/heads/main",
"committer_date": 1605727528000,
"content_id": "a0d2373050a52d7314dac36103b325b41f1fece3",
"detected_licenses": [
"MIT"
],
"directory_id": "c654585cd0918abf99c5722e5cd7b2110e6a889b",
"extension": "py",
"filename": "render_website.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 308422002,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1826,
"license": "MIT",
"license_type": "permissive",
"path": "/render_website.py",
"provenance": "stack-edu-0054.json.gz:583026",
"repo_name": "Zed-chi/dvmn_frontend_ch4",
"revision_date": 1605727528000,
"revision_id": "b0700b135a83324e36528af1556f29ac9cd6df51",
"snapshot_id": "e84ad6ca1dc644c096adbbf57e0bb4f5ad407460",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Zed-chi/dvmn_frontend_ch4/b0700b135a83324e36528af1556f29ac9cd6df51/render_website.py",
"visit_date": "2023-01-19T15:02:24.121570"
} | 2.640625 | stackv2 | import json
import os
from urllib.parse import quote
from jinja2 import Environment, FileSystemLoader, select_autoescape
from livereload import Server
from more_itertools import chunked
JSON_PATH = os.path.join("./", "books.json")
HTML_DIR = os.path.join("./", "pages")
def clean_html_dir():
filepaths_list = os.listdir(HTML_DIR)
for filepath in filepaths_list:
os.remove(os.path.join(HTML_DIR, filepath))
def get_books_description_from_json(filepath):
with open(filepath, "r", encoding="utf-8") as file:
data = file.read()
return json.loads(data)
def normalize_data_path(books):
for book in books:
book["img_src"] = quote(
book["img_src"].replace("\\", "/").replace(".", "..", 1))
book["book_path"] = quote(
book["book_path"].replace("\\", "/").replace(".", "..", 1))
def on_reload():
clean_html_dir()
description = get_books_description_from_json(JSON_PATH)
books_list = description["books"]
normalize_data_path(books_list)
env = Environment(
loader=FileSystemLoader("."),
autoescape=select_autoescape(["html", "xml"]),
)
template = env.get_template("template.html")
chunks_by_10 = [*chunked(description["books"], 10, strict=False)]
pages_count = len(chunks_by_10)
for id, chunk in enumerate(chunks_by_10):
rendered_page = template.render(
books=[*chunked(chunk, 2)],
pages_count=pages_count,
current_page=id + 1,
)
path = os.path.join(HTML_DIR, f"index{id+1}.html")
with open(path, "w", encoding="utf8") as file:
file.write(rendered_page)
if __name__ == "__main__":
on_reload()
server = Server()
server.watch("./template.html", on_reload)
server.serve(root="./")
| 64 | 27.53 | 71 | 16 | 437 | python | [{"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_6a859693f07f7b4b_af7d4635", "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": 41, "line_end": 44, "column_start": 11, "column_end": 6, "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/tmphvvervh1/6a859693f07f7b4b.py", "start": {"line": 41, "col": 11, "offset": 1053}, "end": {"line": 44, "col": 6, "offset": 1164}, "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.flask.security.xss.audit.direct-use-of-jinja2_6a859693f07f7b4b_b2b009f3", "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": 50, "line_end": 54, "column_start": 25, "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/tmphvvervh1/6a859693f07f7b4b.py", "start": {"line": 50, "col": 25, "offset": 1391}, "end": {"line": 54, "col": 10, "offset": 1527}, "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"}}}] | 2 | true | [
"CWE-79",
"CWE-79"
] | [
"rules.python.flask.security.xss.audit.direct-use-of-jinja2",
"rules.python.flask.security.xss.audit.direct-use-of-jinja2"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
41,
50
] | [
44,
54
] | [
11,
25
] | [
6,
10
] | [
"A07:2017 - Cross-Site Scripting (XSS)",
"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 direct use of jinja2. If n... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | render_website.py | /render_website.py | Zed-chi/dvmn_frontend_ch4 | MIT | |
2024-11-18T21:14:01.845390+00:00 | 1,566,431,789,000 | ee51104afee26619863dc1029daa3c831c34dd76 | 2 | {
"blob_id": "ee51104afee26619863dc1029daa3c831c34dd76",
"branch_name": "refs/heads/master",
"committer_date": 1566431789000,
"content_id": "026a6fa2c9027d96933bb617f79c674cce9ad70e",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "6d9a044b97aba7a16812fb470b943374e059ae63",
"extension": "py",
"filename": "gloo_qsub.py",
"fork_events_count": 0,
"gha_created_at": 1553673986000,
"gha_event_created_at": 1553673986000,
"gha_language": null,
"gha_license_id": null,
"github_id": 177947091,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1886,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/script/gloo_qsub.py",
"provenance": "stack-edu-0054.json.gz:583033",
"repo_name": "chen-xanadu/gloo",
"revision_date": 1566431789000,
"revision_id": "8a628348a5a59200393a2c0d55a8934eb5d3782c",
"snapshot_id": "f43c670b36bfd5f1da6473cbb8f1660cc4acd45e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/chen-xanadu/gloo/8a628348a5a59200393a2c0d55a8934eb5d3782c/script/gloo_qsub.py",
"visit_date": "2020-05-02T11:59:32.997175"
} | 2.453125 | stackv2 | # Launch multiple gloo processes through qsub. Benchmark the running times
# of ring-based and grid-based (w/ and w/o failures) all-reduce algorithms.
# The number of elements ranges from 1e5 to 1e8
# Usage:
# ./python3 gloo_qsub.py [#_processes] [#_node_requested] [groups]
#
from pathlib import Path
import subprocess
import sys
PBS_HEADER = '#!/bin/bash\n#PBS -l select=1:ncpus=60\n\n'
size = int(sys.argv[1])
node = int(sys.argv[2])
group = int(sys.argv[3])
nps = size // node
subprocess.run('rm -f ~/tmp/*', shell=True)
subprocess.run('rm -f ~/gloo_n*', shell=True)
subprocess.run(f'mkdir -p ~/output_{size}_{group}', shell=True)
p = Path(Path.home(), 'gloo_n.sh')
script = PBS_HEADER
script += 'sleep 15\n'
p.write_text(script)
p.chmod(0o755)
subprocess.run('qsub ./{}'.format(p.name), shell=True)
elements = [[1 * 10**i, 2 * 10**i, 5 * 10**i] for i in range(5, 9)]
elements = [e for el in elements for e in el]
for n in range(node):
p = Path(Path.home(), 'gloo_n{}.sh'.format(n))
script = PBS_HEADER
for i in range(n*nps, (n+1)*nps):
script += f'rm -f ~/output_{size}_{group}/{i}.txt\n'
script += f'cat $PBS_NODEFILE > ~/output_{size}_{group}/{i}.txt\n'
for element in elements:
if i == (n+1)*nps - 1:
script += f'PREFIX=test{size}{group}_{element} ELEMENT={element} ' \
f'SIZE={size} RANK={i} GROUP={group} ~/gloo/build/gloo/examples/example2' \
f' >> ~/output_{size}_{group}/{i}.txt\n\n'
else:
script += f'PREFIX=test{size}{group}_{element} ELEMENT={element} ' \
f'SIZE={size} RANK={i} GROUP={group} ~/gloo/build/gloo/examples/example2' \
f' >> ~/output_{size}_{group}/{i}.txt &\n\n'
p.write_text(script)
p.chmod(0o755)
subprocess.run('qsub ./{}'.format(p.name), shell=True)
| 58 | 31.52 | 95 | 16 | 575 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_f61a28c4b741671b_9cb9cecb", "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": 22, "line_end": 22, "column_start": 1, "column_end": 64, "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/tmphvvervh1/f61a28c4b741671b.py", "start": {"line": 22, "col": 1, "offset": 579}, "end": {"line": 22, "col": 64, "offset": 642}, "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_f61a28c4b741671b_f8475079", "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": 22, "line_end": 22, "column_start": 16, "column_end": 51, "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/tmphvvervh1/f61a28c4b741671b.py", "start": {"line": 22, "col": 16, "offset": 594}, "end": {"line": 22, "col": 51, "offset": 629}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_f61a28c4b741671b_5c6c8563", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'run' 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": 22, "line_end": 22, "column_start": 59, "column_end": 63, "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/tmphvvervh1/f61a28c4b741671b.py", "start": {"line": 22, "col": 59, "offset": 637}, "end": {"line": 22, "col": 63, "offset": 641}, "extra": {"message": "Found 'subprocess' function 'run' 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_f61a28c4b741671b_98b94278", "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": 32, "line_end": 32, "column_start": 1, "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/tmphvvervh1/f61a28c4b741671b.py", "start": {"line": 32, "col": 1, "offset": 761}, "end": {"line": 32, "col": 55, "offset": 815}, "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.subprocess-shell-true_f61a28c4b741671b_844abc16", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'run' 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": 32, "line_end": 32, "column_start": 50, "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://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/tmphvvervh1/f61a28c4b741671b.py", "start": {"line": 32, "col": 50, "offset": 810}, "end": {"line": 32, "col": 54, "offset": 814}, "extra": {"message": "Found 'subprocess' function 'run' 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_f61a28c4b741671b_0f92978e", "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": 58, "line_end": 58, "column_start": 5, "column_end": 59, "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/tmphvvervh1/f61a28c4b741671b.py", "start": {"line": 58, "col": 5, "offset": 1831}, "end": {"line": 58, "col": 59, "offset": 1885}, "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_f61a28c4b741671b_d2b27b47", "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": 58, "line_end": 58, "column_start": 20, "column_end": 46, "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/tmphvvervh1/f61a28c4b741671b.py", "start": {"line": 58, "col": 20, "offset": 1846}, "end": {"line": 58, "col": 46, "offset": 1872}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_f61a28c4b741671b_906e771d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'run' 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": 58, "line_end": 58, "column_start": 54, "column_end": 58, "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/tmphvvervh1/f61a28c4b741671b.py", "start": {"line": 58, "col": 54, "offset": 1880}, "end": {"line": 58, "col": 58, "offset": 1884}, "extra": {"message": "Found 'subprocess' function 'run' 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"}}}] | 8 | true | [
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"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",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.subp... | [
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security"
] | [
"LOW",
"MEDIUM",
"MEDIUM",
"LOW",
"MEDIUM",
"LOW",
"MEDIUM",
"MEDIUM"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | [
22,
22,
22,
32,
32,
58,
58,
58
] | [
22,
22,
22,
32,
32,
58,
58,
58
] | [
1,
16,
59,
1,
50,
5,
20,
54
] | [
64,
51,
63,
55,
54,
59,
46,
58
] | [
"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 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,
7.5,
7.5,
7.5,
7.5,
7.5,
7.5
] | [
"LOW",
"MEDIUM",
"HIGH",
"LOW",
"HIGH",
"LOW",
"MEDIUM",
"HIGH"
] | [
"HIGH",
"MEDIUM",
"LOW",
"HIGH",
"LOW",
"HIGH",
"MEDIUM",
"LOW"
] | gloo_qsub.py | /script/gloo_qsub.py | chen-xanadu/gloo | BSD-3-Clause | |
2024-11-18T21:14:03.233427+00:00 | 1,633,153,127,000 | 9e0d564266951df5d412bbc2f0ff323023fe87d4 | 3 | {
"blob_id": "9e0d564266951df5d412bbc2f0ff323023fe87d4",
"branch_name": "refs/heads/master",
"committer_date": 1633153127000,
"content_id": "3b4d325350fc1877fa70a1db4a638721a6ad02d5",
"detected_licenses": [
"MIT"
],
"directory_id": "01d94ab245c92fd71b57dbac0f2e6a6f2db01a36",
"extension": "py",
"filename": "NIFTY50FROMNIFTYALL.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": 4354,
"license": "MIT",
"license_type": "permissive",
"path": "/NIFTY50FROMNIFTYALL.py",
"provenance": "stack-edu-0054.json.gz:583049",
"repo_name": "anoop-phoenix/analysis-of-national-stock-exchange",
"revision_date": 1633153127000,
"revision_id": "578020878f66478967dd91782fb9f4f01c815431",
"snapshot_id": "a64f2dff41a1f863848e3c1fc3a2fd251d978523",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/anoop-phoenix/analysis-of-national-stock-exchange/578020878f66478967dd91782fb9f4f01c815431/NIFTY50FROMNIFTYALL.py",
"visit_date": "2023-08-07T06:20:44.916910"
} | 2.65625 | stackv2 | import csv
import mysql.connector
import os.path
import pandas as pd
import easygui
import datetime
from mysql.connector import Error
from mysql.connector import errorcode
import configparser
'''
This Script is for too Copy the Data of NiftyALL i.e the Bhavcopy Data to Nifty50Derived Table
which contain only Top 50 Nifty Symbol.
'''
class Nifty50FromNiftyAll:
def copyData(self):
config_obj = configparser.ConfigParser()
config_obj.read("Y:\\Python CSV\\1 Main Technical Analysis of National Stock Exchange\\Config\\Config.cfg")
# DataBase Connection
print("Hellos from NiftyAll to Nifty50Derived ")
try:
connection = mysql.connector.connect(host=config_obj.get("Setting", "host"),
database=config_obj.get("Setting", "database"),
user=config_obj.get("Setting", "user"),
password=config_obj.get("Setting", "password"))
cursor = connection.cursor()
# to check repeated record
qry = "Select * from NiftyAll"
pdata = pd.read_sql_query(qry, connection)
if pdata.empty == True:
easygui.msgbox("NiftyAll table is Empty", title="Process Message")
if (connection.is_connected()):
cursor.close()
connection.close()
return
last_day_of_nifty50 ="SELECT timestamp FROM Nifty50Derived WHERE Timestamp IN ( SELECT MAX( Timestamp ) " \
"FROM Nifty50Derived ) Group by timestamp ORDER BY timestamp ASC"
cursor.execute(last_day_of_nifty50)
last_day_of_nifty50 = cursor.fetchall()
if(len(last_day_of_nifty50)==0):
last_day_of_nifty50 = "SELECT timestamp FROM NiftyAll WHERE Timestamp IN ( SELECT MIN( Timestamp ) " \
"FROM NiftyAll ) Group by timestamp ORDER BY timestamp ASC"
cursor.execute(last_day_of_nifty50)
last_day_of_nifty50 = cursor.fetchall()
last_day_of_niftyAll="SELECT timestamp FROM NiftyAll WHERE Timestamp IN ( SELECT MAX( Timestamp ) " \
"FROM NiftyAll ) Group by timestamp ORDER BY timestamp ASC"
cursor.execute(last_day_of_niftyAll)
last_day_of_niftyAll = cursor.fetchall()
last_day_of_nifty50 = last_day_of_nifty50[0][0]
last_day_of_niftyAll = last_day_of_niftyAll[0][0]
print(last_day_of_nifty50)
print(last_day_of_niftyAll)
if(last_day_of_niftyAll == last_day_of_nifty50):
easygui.msgbox("Data Already Present in Nifty50Derived table", title="Process Message")
pass
else:
print("Entered")
sql_select_query = "Select * from NiftyAll where Symbol = (Select DISTINCT SYMBOL FROM NIFTY50 " \
"WHERE NIFTY50.SYMBOL = NIFTYALL.SYMBOL) and Series='EQ' and timestamp " \
"between '"+str(last_day_of_nifty50)+"' and '" + str(last_day_of_niftyAll)+"'"
print(sql_select_query)
cursor.execute(sql_select_query)
records = cursor.fetchall()
# Loop to store data
for i in records:
cursor.execute(""" INSERT INTO Nifty50Derived VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
(i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8], i[9], i[10], i[11], i[12]))
connection.commit()
easygui.msgbox("Record inserted successfully into Nifty50Derived table", title="Process Message")
except mysql.connector.Error as error:
connection.rollback() # rollback if any exception occured
msg="Failed inserting record into Nifty50Derived table {}".format(error)
easygui.msgbox(msg, title="Process Message")
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
easygui.msgbox("MySQL connection is closed", title="Process Message")
return
| 96 | 44.35 | 119 | 19 | 932 | python | [{"finding_id": "semgrep_rules.python.correctness.suppressed-exception-handling-finally-break_fa858a3b8333e7f4_fcf4adf2", "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": 24, "line_end": 95, "column_start": 9, "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://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/tmphvvervh1/fa858a3b8333e7f4.py", "start": {"line": 24, "col": 9, "offset": 651}, "end": {"line": 95, "col": 19, "offset": 4352}, "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.sqlalchemy.security.sqlalchemy-execute-raw-query_fa858a3b8333e7f4_b1f09da4", "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": 75, "line_end": 75, "column_start": 17, "column_end": 49, "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/tmphvvervh1/fa858a3b8333e7f4.py", "start": {"line": 75, "col": 17, "offset": 3324}, "end": {"line": 75, "col": 49, "offset": 3356}, "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"
] | [
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
75
] | [
75
] | [
17
] | [
49
] | [
"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"
] | NIFTY50FROMNIFTYALL.py | /NIFTY50FROMNIFTYALL.py | anoop-phoenix/analysis-of-national-stock-exchange | MIT | |
2024-11-18T21:14:05.683201+00:00 | 1,555,221,881,000 | 270c02634d40dd9c8485bdfa8a0a375e41619620 | 3 | {
"blob_id": "270c02634d40dd9c8485bdfa8a0a375e41619620",
"branch_name": "refs/heads/master",
"committer_date": 1555221881000,
"content_id": "8db756ca16d8b65813a616ddf4a3362311987021",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "fec619d74b55b0815266a2511b89dbfc1fd076c6",
"extension": "py",
"filename": "graph.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 181196893,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 686,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/benchmarks/graph.py",
"provenance": "stack-edu-0054.json.gz:583077",
"repo_name": "NK-Nikunj/Page-Replacement",
"revision_date": 1555221881000,
"revision_id": "b018c67694c46c5daef641176179a59ff80e6b3a",
"snapshot_id": "7211a5dd100ddac95d79b4aeb787a96a40ceb043",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/NK-Nikunj/Page-Replacement/b018c67694c46c5daef641176179a59ff80e6b3a/benchmarks/graph.py",
"visit_date": "2020-05-09T14:30:37.309053"
} | 2.71875 | stackv2 | import matplotlib.pyplot as plt
import subprocess
executables = ['clock', 'lru_aging', 'lru_counter', 'lru_stack']
for executable in executables:
bashCommand = "./build/" + executable
output = subprocess.check_output(['bash','-c', bashCommand])
output = output.split('\n')[:-1]
x = []
y = []
for i in range(0, len(output), 2):
elem = output[i].split(' ')[-1]
x.append(elem)
for i in range(1, len(output), 2):
elem = output[i].split(' ')[-1]
y.append(elem)
x = map(int, x)
y = map(int, y)
plt.plot(x, y)
plt.ylabel('Number of page faults')
plt.xlabel('Number of frames')
plt.show()
# print x,y | 32 | 20.47 | 64 | 12 | 191 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_99acae786ad94178_5b099b4c", "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": 9, "line_end": 9, "column_start": 14, "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/tmphvvervh1/99acae786ad94178.py", "start": {"line": 9, "col": 14, "offset": 204}, "end": {"line": 9, "col": 65, "offset": 255}, "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"}}}] | 1 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
9
] | [
9
] | [
14
] | [
65
] | [
"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()'."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | graph.py | /benchmarks/graph.py | NK-Nikunj/Page-Replacement | Apache-2.0 | |
2024-11-18T21:14:06.577860+00:00 | 1,684,497,112,000 | 1024b71fb546ac248468a771930b9611ede34a6c | 2 | {
"blob_id": "1024b71fb546ac248468a771930b9611ede34a6c",
"branch_name": "refs/heads/master",
"committer_date": 1684497112000,
"content_id": "46660ad1d8593ec308d4f1642b9cd1bdcd75b56b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ca94071518d3cc097d711628ed82abbdc9202769",
"extension": "py",
"filename": "spirv_capabilities_parser.py",
"fork_events_count": 144,
"gha_created_at": 1579913990000,
"gha_event_created_at": 1693320994000,
"gha_language": "Go",
"gha_license_id": "Apache-2.0",
"github_id": 236109124,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2584,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/vulkan_generator/vulkan_parser/internal/spirv_capabilities_parser.py",
"provenance": "stack-edu-0054.json.gz:583086",
"repo_name": "google/agi",
"revision_date": 1684497112000,
"revision_id": "7ee513c558ab754b6cf5c9ab2c662dc918ff92e9",
"snapshot_id": "5eb5dfbb583ee1ff9e4582c8bfda90b3f5a91639",
"src_encoding": "UTF-8",
"star_events_count": 792,
"url": "https://raw.githubusercontent.com/google/agi/7ee513c558ab754b6cf5c9ab2c662dc918ff92e9/vulkan_generator/vulkan_parser/internal/spirv_capabilities_parser.py",
"visit_date": "2023-09-01T07:40:49.168335"
} | 2.375 | stackv2 | # Copyright (C) 2022 Google Inc.
#
# 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.
""" This module is responsible for parsing Spirv capabilities"""
from typing import Optional
import xml.etree.ElementTree as ET
from vulkan_generator.vulkan_parser.internal import internal_types
def parse(spirv_element: ET.Element) -> internal_types.SpirvCapability:
"""Parses a Spirv capability or alias from the XML element that defines it
A sample spirv capability:
s<spirvcapability name="StoragePushConstant16">
<enable struct="VkPhysicalDeviceVulkan11Features" feature="storagePushConstant16"
requires="VK_VERSION_1_2"/>
<enable struct="VkPhysicalDevice16BitStorageFeatures" feature="storagePushConstant16"
requires="VK_KHR_16bit_storage"/>
</spirvcapability>
"""
name = spirv_element.attrib["name"]
version: Optional[str] = None
feature: Optional[internal_types.SpirvCapabilityFeature] = None
vulkan_property: Optional[internal_types.SpirvCapabilityProperty] = None
extension: Optional[str] = None
for enable in spirv_element:
if "version" in enable.attrib:
version = enable.attrib["version"]
elif "struct" in enable.attrib:
feature = internal_types.SpirvCapabilityFeature(
struct=enable.attrib["struct"],
feature=enable.attrib["feature"],
)
elif "property" in enable.attrib:
vulkan_property = internal_types.SpirvCapabilityProperty(
struct=enable.attrib["property"],
group=enable.attrib["member"],
value=enable.attrib["value"],
)
elif "extension" in enable.attrib:
extension = enable.attrib["extension"]
else:
raise SyntaxError(f"Unknown Spirv capability type: {ET.tostring(spirv_element, 'utf-8')}")
return internal_types.SpirvCapability(
name=name,
version=version,
feature=feature,
property=vulkan_property,
vulkan_extension=extension)
| 65 | 38.75 | 102 | 17 | 559 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_0e9ed94456c1548a_5dda1d70", "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": 18, "line_end": 18, "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/tmphvvervh1/0e9ed94456c1548a.py", "start": {"line": 18, "col": 1, "offset": 675}, "end": {"line": 18, "col": 35, "offset": 709}, "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"
] | [
18
] | [
18
] | [
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"
] | spirv_capabilities_parser.py | /vulkan_generator/vulkan_parser/internal/spirv_capabilities_parser.py | google/agi | Apache-2.0 | |
2024-11-18T21:14:08.909510+00:00 | 1,578,565,091,000 | 9d66cf60c2d3d6dccae2bcbc173b53d46b20e0cf | 2 | {
"blob_id": "9d66cf60c2d3d6dccae2bcbc173b53d46b20e0cf",
"branch_name": "refs/heads/master",
"committer_date": 1578565091000,
"content_id": "72ad803877bb8b3b96cd53f0281d8dd1ca5000d4",
"detected_licenses": [
"MIT"
],
"directory_id": "473da2c74f68f93f59ca799f2fcf441a59919496",
"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": 9238,
"license": "MIT",
"license_type": "permissive",
"path": "/openprescribing/common/utils.py",
"provenance": "stack-edu-0054.json.gz:583098",
"repo_name": "WeakLemonDrink/openprescribing",
"revision_date": 1578565091000,
"revision_id": "f2b0a29568dbce28c5102f50813d9d52b7420c07",
"snapshot_id": "014011bc7a9073f1657de6837f4cf1f6a0119a03",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/WeakLemonDrink/openprescribing/f2b0a29568dbce28c5102f50813d9d52b7420c07/openprescribing/common/utils.py",
"visit_date": "2020-12-09T23:36:31.890035"
} | 2.40625 | stackv2 | from collections import namedtuple
from contextlib import contextmanager
from datetime import datetime
from os import environ
from titlecase import titlecase
import argparse
import html2text
import logging
import re
from django.core.exceptions import ImproperlyConfigured
from django import db
logger = logging.getLogger(__name__)
def nhs_abbreviations(word, **kwargs):
if len(word) == 2 and word.lower() not in [
"at",
"of",
"in",
"on",
"to",
"is",
"me",
"by",
"dr",
"st",
]:
return word.upper()
elif word.lower() in ["dr", "st"]:
return word.title()
elif word.upper() in ("NHS", "CCG", "PMS", "SMA", "PWSI", "OOH", "HIV"):
return word.upper()
elif "&" in word:
return word.upper()
elif (word.lower() not in ["ptnrs", "by", "ccgs"]) and (
not re.match(r".*[aeiou]{1}", word.lower())
):
return word.upper()
def nhs_titlecase(words):
if words:
title_cased = titlecase(words, callback=nhs_abbreviations)
words = re.sub(r"Dr ([a-z]{2})", "Dr \1", title_cased)
return words
def email_as_text(html):
text_maker = html2text.HTML2Text()
text_maker.images_to_alt = True
text_maker.asterisk_emphasis = True
text_maker.wrap_links = False
text_maker.pad_tables = True
text_maker.ignore_images = True
text = text_maker.handle(html)
return text
def get_env_setting(setting, default=None):
""" Get the environment setting.
Return the default, or raise an exception if none supplied
"""
try:
return environ[setting]
except KeyError:
if default is not None:
return default
else:
error_msg = "Set the %s env variable" % setting
raise ImproperlyConfigured(error_msg)
def get_env_setting_bool(setting, default=None):
""" Get the environment setting as a boolean
Return the default, or raise an exception if none supplied
"""
value = get_env_setting(setting, default=default)
if value is default:
return value
normalised = value.lower().strip()
if normalised == "true":
return True
elif normalised == "false":
return False
else:
raise ImproperlyConfigured(
"Value for env variable {} is not a valid boolean: {}".format(
setting, value
)
)
def under_test():
return db.connections.databases["default"]["NAME"].startswith("test_")
@contextmanager
def constraint_and_index_reconstructor(table_name):
"""A context manager that drops indexes and constraints on the
specified table, yields, then recreates them.
According to postgres documentation, when doing bulk loads, this
should be faster than having the indexes update during the insert.
See https://www.postgresql.org/docs/current/static/populate.html
for more.
"""
with db.connection.cursor() as cursor:
# Record index and constraint definitions
indexes = {}
constraints = {}
cluster = None
# Build lists of current constraints and indexes, and any
# existing cluster
cursor.execute(
"SELECT conname, pg_get_constraintdef(c.oid) "
"FROM pg_constraint c "
"JOIN pg_namespace n "
"ON n.oid = c.connamespace "
"WHERE contype IN ('f', 'p','c','u') "
"AND conrelid = '%s'::regclass "
"ORDER BY contype;" % table_name
)
for name, definition in cursor.fetchall():
constraints[name] = definition
cursor.execute(
"SELECT indexname, indexdef "
"FROM pg_indexes "
"WHERE tablename = '%s';" % table_name
)
for name, definition in cursor.fetchall():
if name not in constraints.keys():
# UNIQUE constraints actuall create indexes, so
# we mustn't attempt to handle them twice
indexes[name] = definition
cursor.execute(
"""
SELECT
i.relname AS index_for_cluster
FROM
pg_index AS idx
JOIN
pg_class AS i
ON
i.oid = idx.indexrelid
WHERE
idx.indisclustered
AND idx.indrelid::regclass = '%s'::regclass;
"""
% table_name
)
row = cursor.fetchone()
if row:
cluster = row[0]
# drop foreign key constraints
for name in constraints.keys():
cursor.execute("ALTER TABLE %s DROP CONSTRAINT %s" % (table_name, name))
# drop indexes
logger.info("Dropping indexes")
for name in indexes.keys():
cursor.execute("DROP INDEX %s" % name)
logger.info("Dropped index %s" % name)
logger.info("Running wrapped command")
try:
yield
finally:
# we're updating everything. This takes 52 minutes.
# restore indexes
logger.info("Recreating indexes")
for name, cmd in indexes.items():
cursor.execute(cmd)
logger.info("Recreated index %s" % name)
logger.info("Recreating constraints")
# restore foreign key constraints
for name, cmd in constraints.items():
cmd = "ALTER TABLE %s " "ADD CONSTRAINT %s %s" % (table_name, name, cmd)
cursor.execute(cmd)
logger.info("Recreated constraint %s" % name)
if cluster:
cursor.execute("CLUSTER %s USING %s" % (table_name, cluster))
cursor.execute("ANALYZE %s" % table_name)
logger.info("CLUSTERED %s" % table_name)
def parse_date(s):
return datetime.strptime(s, "%Y-%m-%d")
def valid_date(s):
"""Validate ISO-formatted dates. For use in argparse arguments.
"""
try:
return parse_date(s)
except ValueError:
msg = "Not a valid date: '{0}'.".format(s)
raise argparse.ArgumentTypeError(msg)
def namedtuplefetchall(cursor):
"Return all rows from a cursor as a namedtuple"
desc = cursor.description
nt_result = namedtuple("Result", [col[0] for col in desc])
return [nt_result(*row) for row in cursor.fetchall()]
def ppu_sql(conditions=""):
# Model imports here because util module is used in Django's
# startup, before model registration is complete, leading to
# errors
from dmd.models import VMP, VMPP
from frontend.models import NCSOConcession
from frontend.models import PPUSaving
from frontend.models import Presentation
from frontend.models import Practice
from frontend.models import PCT
# See https://github.com/ebmdatalab/price-per-dose/issues/1 for an
# explanation of the extra BNF codes in vmp_bnf_codes below.
sql = """
WITH vmp_bnf_codes AS (
SELECT DISTINCT bnf_code FROM {vmp_table}
UNION ALL
SELECT '0601060D0AAA0A0' -- "Glucose Blood Testing Reagents"
UNION ALL
SELECT '0601060U0AAA0A0' -- "Urine Testing Reagents"
)
SELECT
{ppusavings_table}.id AS id,
{ppusavings_table}.date AS date,
{ppusavings_table}.lowest_decile AS lowest_decile,
{ppusavings_table}.quantity AS quantity,
{ppusavings_table}.price_per_unit AS price_per_unit,
{ppusavings_table}.possible_savings AS possible_savings,
{ppusavings_table}.formulation_swap AS formulation_swap,
{ppusavings_table}.pct_id AS pct,
{ppusavings_table}.practice_id AS practice,
{ppusavings_table}.bnf_code AS presentation,
{practice_table}.name AS practice_name,
{pct_table}.name AS pct_name,
subquery.price_concession IS NOT NULL as price_concession,
COALESCE({presentation_table}.dmd_name, {presentation_table}.name) AS name
FROM {ppusavings_table}
LEFT OUTER JOIN {presentation_table}
ON {ppusavings_table}.bnf_code = {presentation_table}.bnf_code
LEFT OUTER JOIN {practice_table}
ON {ppusavings_table}.practice_id = {practice_table}.code
LEFT OUTER JOIN {pct_table}
ON {ppusavings_table}.pct_id = {pct_table}.code
LEFT OUTER JOIN (SELECT DISTINCT bnf_code, 1 AS price_concession
FROM {vmpp_table}
INNER JOIN {ncsoconcession_table}
ON {vmpp_table}.vppid = {ncsoconcession_table}.vmpp_id
WHERE {ncsoconcession_table}.date = %(date)s) AS subquery
ON {ppusavings_table}.bnf_code = subquery.bnf_code
WHERE
{ppusavings_table}.date = %(date)s
AND {ppusavings_table}.bnf_code IN (SELECT bnf_code FROM vmp_bnf_codes)
"""
sql += conditions
return sql.format(
ppusavings_table=PPUSaving._meta.db_table,
practice_table=Practice._meta.db_table,
pct_table=PCT._meta.db_table,
presentation_table=Presentation._meta.db_table,
vmpp_table=VMPP._meta.db_table,
vmp_table=VMP._meta.db_table,
ncsoconcession_table=NCSOConcession._meta.db_table,
)
| 283 | 31.64 | 88 | 17 | 2,160 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_c7fdc3922cb695e1_34bc26cd", "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": 123, "line_end": 131, "column_start": 9, "column_end": 10, "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/tmphvvervh1/c7fdc3922cb695e1.py", "start": {"line": 123, "col": 9, "offset": 3223}, "end": {"line": 131, "col": 10, "offset": 3560}, "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_c7fdc3922cb695e1_5f706432", "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": 131, "column_start": 9, "column_end": 10, "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/tmphvvervh1/c7fdc3922cb695e1.py", "start": {"line": 123, "col": 9, "offset": 3223}, "end": {"line": 131, "col": 10, "offset": 3560}, "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_c7fdc3922cb695e1_f8e8a522", "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": 134, "line_end": 138, "column_start": 9, "column_end": 10, "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/tmphvvervh1/c7fdc3922cb695e1.py", "start": {"line": 134, "col": 9, "offset": 3663}, "end": {"line": 138, "col": 10, "offset": 3812}, "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_c7fdc3922cb695e1_b801579b", "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": 134, "line_end": 138, "column_start": 9, "column_end": 10, "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/tmphvvervh1/c7fdc3922cb695e1.py", "start": {"line": 134, "col": 9, "offset": 3663}, "end": {"line": 138, "col": 10, "offset": 3812}, "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_c7fdc3922cb695e1_b4e3bb14", "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": 144, "line_end": 159, "column_start": 9, "column_end": 10, "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/tmphvvervh1/c7fdc3922cb695e1.py", "start": {"line": 144, "col": 9, "offset": 4084}, "end": {"line": 159, "col": 10, "offset": 4480}, "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_c7fdc3922cb695e1_d5d44d0f", "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": 144, "line_end": 159, "column_start": 9, "column_end": 10, "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/tmphvvervh1/c7fdc3922cb695e1.py", "start": {"line": 144, "col": 9, "offset": 4084}, "end": {"line": 159, "col": 10, "offset": 4480}, "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_c7fdc3922cb695e1_662ff35f", "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": 166, "line_end": 166, "column_start": 13, "column_end": 85, "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/tmphvvervh1/c7fdc3922cb695e1.py", "start": {"line": 166, "col": 13, "offset": 4650}, "end": {"line": 166, "col": 85, "offset": 4722}, "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_c7fdc3922cb695e1_9c58712c", "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": 166, "line_end": 166, "column_start": 13, "column_end": 85, "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/tmphvvervh1/c7fdc3922cb695e1.py", "start": {"line": 166, "col": 13, "offset": 4650}, "end": {"line": 166, "col": 85, "offset": 4722}, "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_c7fdc3922cb695e1_6f7553e8", "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": 171, "line_end": 171, "column_start": 13, "column_end": 51, "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/tmphvvervh1/c7fdc3922cb695e1.py", "start": {"line": 171, "col": 13, "offset": 4835}, "end": {"line": 171, "col": 51, "offset": 4873}, "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_c7fdc3922cb695e1_2d5204c5", "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": 171, "line_end": 171, "column_start": 13, "column_end": 51, "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/tmphvvervh1/c7fdc3922cb695e1.py", "start": {"line": 171, "col": 13, "offset": 4835}, "end": {"line": 171, "col": 51, "offset": 4873}, "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_c7fdc3922cb695e1_7286e1c6", "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": 189, "line_end": 189, "column_start": 17, "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/tmphvvervh1/c7fdc3922cb695e1.py", "start": {"line": 189, "col": 17, "offset": 5552}, "end": {"line": 189, "col": 36, "offset": 5571}, "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_c7fdc3922cb695e1_ab530fbb", "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": 189, "line_end": 189, "column_start": 17, "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/tmphvvervh1/c7fdc3922cb695e1.py", "start": {"line": 189, "col": 17, "offset": 5552}, "end": {"line": 189, "col": 36, "offset": 5571}, "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_c7fdc3922cb695e1_54a4f918", "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": 192, "line_end": 192, "column_start": 17, "column_end": 78, "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/tmphvvervh1/c7fdc3922cb695e1.py", "start": {"line": 192, "col": 17, "offset": 5674}, "end": {"line": 192, "col": 78, "offset": 5735}, "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_c7fdc3922cb695e1_15065059", "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": 192, "line_end": 192, "column_start": 17, "column_end": 78, "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/tmphvvervh1/c7fdc3922cb695e1.py", "start": {"line": 192, "col": 17, "offset": 5674}, "end": {"line": 192, "col": 78, "offset": 5735}, "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_c7fdc3922cb695e1_65f21827", "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": 193, "line_end": 193, "column_start": 17, "column_end": 58, "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/tmphvvervh1/c7fdc3922cb695e1.py", "start": {"line": 193, "col": 17, "offset": 5752}, "end": {"line": 193, "col": 58, "offset": 5793}, "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_c7fdc3922cb695e1_854f2367", "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": 193, "line_end": 193, "column_start": 17, "column_end": 58, "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/tmphvvervh1/c7fdc3922cb695e1.py", "start": {"line": 193, "col": 17, "offset": 5752}, "end": {"line": 193, "col": 58, "offset": 5793}, "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"}}}] | 16 | true | [
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"CWE-89",
"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",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH"
] | [
123,
123,
134,
134,
144,
144,
166,
166,
171,
171,
189,
189,
192,
192,
193,
193
] | [
131,
131,
138,
138,
159,
159,
166,
166,
171,
171,
189,
189,
192,
192,
193,
193
] | [
9,
9,
9,
9,
9,
9,
13,
13,
13,
13,
17,
17,
17,
17,
17,
17
] | [
10,
10,
10,
10,
10,
10,
85,
85,
51,
51,
36,
36,
78,
78,
58,
58
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01... | [
"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,
5,
7.5,
5,
7.5,
5,
7.5,
5,
7.5
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | utils.py | /openprescribing/common/utils.py | WeakLemonDrink/openprescribing | MIT | |
2024-11-18T21:14:09.650674+00:00 | 1,519,393,753,000 | 4fb7205e62899a67712e5291cda44c28e2342c2a | 3 | {
"blob_id": "4fb7205e62899a67712e5291cda44c28e2342c2a",
"branch_name": "refs/heads/master",
"committer_date": 1519393753000,
"content_id": "d475bd95ad96e08a9b0e78fc1f0e6d2406e25efa",
"detected_licenses": [
"MIT"
],
"directory_id": "a19a6ebf18f956be04c5319b5e3021b2d87ae044",
"extension": "py",
"filename": "extractscore.py",
"fork_events_count": 1,
"gha_created_at": 1519634374000,
"gha_event_created_at": 1519634374000,
"gha_language": null,
"gha_license_id": null,
"github_id": 122939287,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1344,
"license": "MIT",
"license_type": "permissive",
"path": "/src/extractscore.py",
"provenance": "stack-edu-0054.json.gz:583109",
"repo_name": "Weeshlow/scripts",
"revision_date": 1519393753000,
"revision_id": "6bf77d737b0e0ffc7e20c31ae14069dd403b8db6",
"snapshot_id": "640bd2198fa0877dfb982debc55b307420ac3001",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Weeshlow/scripts/6bf77d737b0e0ffc7e20c31ae14069dd403b8db6/src/extractscore.py",
"visit_date": "2021-01-24T04:28:59.132032"
} | 2.640625 | stackv2 | #!/usr/bin/env python
####
#
# JOE SANDBOX EXTRACT SCORE SCRIPT
#
# Parses all XML reports within a directory and extracts the detection and score
#
import xml.etree.cElementTree as et
import os, stat, sys, time
import pickle
import itertools
import operator
def main():
if len(sys.argv) == 2:
evalDir(sys.argv[1])
else:
print "Usage: extractscore dir_to_search"
def evalDir(dir):
touched_sigs = {}
for r,d,f in os.walk(dir):
for file in f:
filepath = r + os.sep + file
if file == "report.xml":
try:
evalFile(filepath, touched_sigs)
except:
print "Unable to parse " + file
def evalFile(file, touched_sigs):
root = et.parse(file)
md5 = root.find("./fileinfo/md5")
if md5 != None:
md5 = md5.text
else:
md5 = "unknown"
det = root.find("./signaturedetections/strategy[@name='empiric']/detection")
score = root.find("./signaturedetections/strategy[@name='empiric']/score")
error = root.find("./errorinfo/error")
if error != None:
error = error.text
else:
error = ""
print md5 + "," + det.text + "," + score.text + ",\"" + error + "\""
if __name__=="__main__":
main()
| 57 | 21.58 | 80 | 16 | 325 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_513bca01d53829d2_5ba49fd5", "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": 10, "line_end": 10, "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/tmphvvervh1/513bca01d53829d2.py", "start": {"line": 10, "col": 1, "offset": 151}, "end": {"line": 10, "col": 36, "offset": 186}, "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"
] | [
10
] | [
10
] | [
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"
] | extractscore.py | /src/extractscore.py | Weeshlow/scripts | MIT | |
2024-11-18T21:14:15.920433+00:00 | 1,504,168,930,000 | c126ab848247d9d2485c28faca2ad9cab33a3cfa | 3 | {
"blob_id": "c126ab848247d9d2485c28faca2ad9cab33a3cfa",
"branch_name": "refs/heads/master",
"committer_date": 1504168930000,
"content_id": "241bd996452afbfd6268000477f3c7096aec6354",
"detected_licenses": [
"MIT"
],
"directory_id": "bb440faedbc974d9670b0d9b74c6a2b1f1133b3e",
"extension": "py",
"filename": "tools.py",
"fork_events_count": 0,
"gha_created_at": 1506482925000,
"gha_event_created_at": 1506482925000,
"gha_language": null,
"gha_license_id": null,
"github_id": 104967663,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5184,
"license": "MIT",
"license_type": "permissive",
"path": "/UI/utilities/tools.py",
"provenance": "stack-edu-0054.json.gz:583181",
"repo_name": "396175371/storj_gui_client",
"revision_date": 1504168930000,
"revision_id": "271283345304b8a21d1c41a322209fd1a298a291",
"snapshot_id": "0703d2ad7bf9f4c6d68adc0213d872c06185d7a7",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/396175371/storj_gui_client/271283345304b8a21d1c41a322209fd1a298a291/UI/utilities/tools.py",
"visit_date": "2021-06-25T11:09:22.106170"
} | 2.6875 | stackv2 | import re
import os
import platform
import pingparser
from os.path import expanduser
import tempfile
import errno
import hashlib
import requests
import miniupnpc
SYNC_SERVER_URL = "http://localhost:8234"
class Tools:
def encrypt_file_name(self):
return 1
def encrypt_bucket_name(self):
return 1
def temp_clean(self, file_name, temp_path):
return 1
def clear_all_logs(self):
return 1
def isWritable(self, path):
try:
testfile = tempfile.TemporaryFile(dir=path)
testfile.close()
except OSError as e:
if e.errno == errno.EACCES: # 13
return False
e.filename = path
raise
return True
def check_email(self, email):
if not re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email):
return False
else:
return True
def measure_ping_latency(self, destination_host):
"""
Measure ping latency of a host
Args:
destination_host (str): the ip of the host
Returns:
():
"""
ping_latency = str(os.system(
"ping " + ("-n 1 " if platform.system().lower() == "windows" else "-c 1 ") + str(destination_host)))
ping_data_parsed = pingparser.parse(ping_latency)
return ping_data_parsed
def human_size(self, size_bytes):
"""
format a size in bytes into a 'human' file size, e.g. bytes, KB, MB, GB, TB, PB
Note that bytes/KB will be reported in whole numbers but MB and above will have greater precision
e.g. 1 byte, 43 bytes, 443 KB, 4.3 MB, 4.43 GB, etc
From: <http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size>
"""
if size_bytes == 1:
# because I really hate unnecessary plurals
return "1 byte"
suffixes_table = [('bytes', 0), ('KB', 0), ('MB', 1), ('GB', 2), ('TB', 2), ('PB', 2)]
num = float(size_bytes)
for suffix, precision in suffixes_table:
if num < 1024.0:
break
num /= 1024.0
if precision == 0:
formatted_size = "%d" % num
else:
formatted_size = str(round(num, ndigits=precision))
return "%s %s" % (formatted_size, suffix)
def get_home_user_directory(self):
"""
Get the path of current user's home folder
Returns:
(str): the extended path of the home
"""
home = expanduser("~")
return str(home)
def count_directory_size(self, directory, include_subdirs):
"""
Args:
directory (str): the directory
include_subdirs (bool): include subdirs or not
Returns:
total_size (int): total size of the directory
"""
if include_subdirs:
start_path = str(directory)
total_size = 0
for dirpath, dirnames, filenames in os.walk(start_path):
for f in filenames:
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
else:
total_size = sum(os.path.getsize(f) for f in os.listdir(str(directory)) if os.path.isfile(f))
return total_size
def count_files_in_dir(self, directory, include_subdirs=False):
"""
Get the number of files in a directory
Args:
directory (str): the name of the directory
include_subdirs (bool): include subdirs or not
Returns:
files_count (int): number of files in dir
"""
files_count = len([name for name in os.listdir(str(directory)) if os.path.isfile(os.path.join(str(directory), name))])
return files_count
def start_synchronization_observer(self):
data = "start_sync_observer"
return requests.post(SYNC_SERVER_URL, data=data).text
def stop_synchronization_observer(self):
data = "stop_sync_observer"
return requests.post(SYNC_SERVER_URL, data=data).text
def is_sync_observer_active(self):
data = "is_sync_active"
return requests.post(SYNC_SERVER_URL, data=data).text
def generate_max_shard_size(self, max_shard_size_input, shard_size_unit):
if shard_size_unit == 0: # KB:
max_shard_size = (max_shard_size_input * 2048)
elif shard_size_unit == 1: # MB:
max_shard_size = (max_shard_size_input * 1024 * 2048)
elif shard_size_unit == 2: # GB:
max_shard_size = (max_shard_size_input * 1024 * 1024 * 2048)
elif shard_size_unit == 3: # TB:
max_shard_size = (max_shard_size_input * 1024 * 1024 * 1024 * 2048)
return max_shard_size
# NETWORK
def map_port_UPnP(self, port, description):
upnp = miniupnpc.UPnP()
upnp.discoverdelay = 10
upnp.discover()
upnp.selectigd()
upnp.addportmapping(port, 'TCP', upnp.lanaddr, port, description, '')
| 164 | 30.61 | 126 | 21 | 1,269 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_f297aa260755ddac_07759b5f", "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": 51, "line_end": 52, "column_start": 28, "column_end": 112, "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/tmphvvervh1/f297aa260755ddac.py", "start": {"line": 51, "col": 28, "offset": 1210}, "end": {"line": 52, "col": 112, "offset": 1332}, "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.requests.best-practice.use-raise-for-status_f297aa260755ddac_7d33d242", "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": 128, "line_end": 128, "column_start": 16, "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://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/tmphvvervh1/f297aa260755ddac.py", "start": {"line": 128, "col": 16, "offset": 4043}, "end": {"line": 128, "col": 57, "offset": 4084}, "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_f297aa260755ddac_bd4616c6", "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.post(SYNC_SERVER_URL, data=data, timeout=30)", "location": {"file_path": "unknown", "line_start": 128, "line_end": 128, "column_start": 16, "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://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/tmphvvervh1/f297aa260755ddac.py", "start": {"line": 128, "col": 16, "offset": 4043}, "end": {"line": 128, "col": 57, "offset": 4084}, "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.post(SYNC_SERVER_URL, data=data, 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_f297aa260755ddac_a4455137", "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": 133, "line_end": 133, "column_start": 16, "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://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/tmphvvervh1/f297aa260755ddac.py", "start": {"line": 133, "col": 16, "offset": 4188}, "end": {"line": 133, "col": 57, "offset": 4229}, "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_f297aa260755ddac_468f4f02", "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.post(SYNC_SERVER_URL, data=data, timeout=30)", "location": {"file_path": "unknown", "line_start": 133, "line_end": 133, "column_start": 16, "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://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/tmphvvervh1/f297aa260755ddac.py", "start": {"line": 133, "col": 16, "offset": 4188}, "end": {"line": 133, "col": 57, "offset": 4229}, "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.post(SYNC_SERVER_URL, data=data, 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_f297aa260755ddac_e1e24935", "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": 138, "line_end": 138, "column_start": 16, "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://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/tmphvvervh1/f297aa260755ddac.py", "start": {"line": 138, "col": 16, "offset": 4323}, "end": {"line": 138, "col": 57, "offset": 4364}, "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_f297aa260755ddac_8a33c5b4", "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.post(SYNC_SERVER_URL, data=data, timeout=30)", "location": {"file_path": "unknown", "line_start": 138, "line_end": 138, "column_start": 16, "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://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/tmphvvervh1/f297aa260755ddac.py", "start": {"line": 138, "col": 16, "offset": 4323}, "end": {"line": 138, "col": 57, "offset": 4364}, "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.post(SYNC_SERVER_URL, data=data, 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"}}}] | 7 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
51
] | [
52
] | [
28
] | [
112
] | [
"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."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | tools.py | /UI/utilities/tools.py | 396175371/storj_gui_client | MIT | |
2024-11-18T21:14:33.986600+00:00 | 1,585,853,191,000 | 5f2dce0928f8dedab7cd8c483142c855be94355d | 3 | {
"blob_id": "5f2dce0928f8dedab7cd8c483142c855be94355d",
"branch_name": "refs/heads/master",
"committer_date": 1585853191000,
"content_id": "92136be20cce4f5f492f8f7bbd72f3caa2782973",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "5ddd7751daa4ba02cfed5c0700b6c81292b60b3b",
"extension": "py",
"filename": "neo4jstuff.py",
"fork_events_count": 3,
"gha_created_at": 1450178995000,
"gha_event_created_at": 1585853193000,
"gha_language": "Python",
"gha_license_id": "Apache-2.0",
"github_id": 48038745,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5044,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/neo4jstuff.py",
"provenance": "stack-edu-0054.json.gz:583387",
"repo_name": "sergey-zarealye-com/wordnet2neo4j",
"revision_date": 1585853191000,
"revision_id": "2e97dda005549d60f284f851a2e6432f9a71422f",
"snapshot_id": "5ba6de5d31c1b861eb11138b07dd43aadea84e8c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sergey-zarealye-com/wordnet2neo4j/2e97dda005549d60f284f851a2e6432f9a71422f/neo4jstuff.py",
"visit_date": "2021-01-10T04:17:39.276385"
} | 2.703125 | stackv2 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 4 15:03:08 2015
REQUIRED:
* neo4j community server v4+
* py2neo v4.3+
@author: sergey, comcon1
"""
from py2neo import Graph
from py2neo import Node
from py2neo import Relationship
class StuffNeo4j():
def __init__(self, nodelabel, reltype):
self.graph_db = None
self.nodelabel = nodelabel
self.reltype = reltype
def connect(self, uri, usr="neo4j", pwd="neo4j"):
"""
Authentication using BOLT protocol.
Use `bolt://1.2.3.4:7687/` for _uri_
"""
if not uri.endswith('/'):
uri += '/'
self.graph_db = Graph(uri, password=pwd)
def create_indexes(self):
#If index is already created py2neo throws exception.
try:
self.graph_db.cypher.execute("CREATE INDEX ON :%s(name)" %
self.nodelabel)
except:
pass
try:
self.graph_db.cypher.execute("CREATE INDEX ON :%s(synset_id)" %
self.nodelabel)
except:
pass
try:
self.graph_db.cypher.execute("CREATE INDEX ON :%s(pointer_symbol)" %
self.reltype)
except:
pass
def create_node(self, nodetype, **kwargs):
return Node(nodetype, **kwargs)
def merge_node(self, nodetype, uniq_key, uniq_val, **kwargs):
n = self.graph_db.merge_one(nodetype, uniq_key, uniq_val)
for k in kwargs:
n.properties[k] = kwargs[k]
n.push()
return n
def insert_rel(self, reltype, node1, node2, **kwargs):
if node1 is not None and node2 is not None:
rel = Relationship(node1, reltype, node2, **kwargs)
self.graph_db.create(rel)
else:
print( "Could not insert relation (%s) - [%s] -> (%s)" % (
node1, reltype, node2) )
def merge_rel(self, reltype, node1, node2, **kwargs):
if node1 is not None and node2 is not None:
rel = Relationship(node1, reltype, node2, **kwargs)
return self.graph_db.create_unique(rel)
else:
print( "Could not merge relation (%s) - [%s] -> (%s)" % (
node1, reltype, node2) )
def create_wordnet_rel(self, synset1, synset2, ptype):
"""
Pointer symbols
http://wordnet.princeton.edu/wordnet/man/wninput.5WN.html
The pointer_symbol s for nouns are:
! Antonym
@ Hypernym
@i Instance Hypernym
~ Hyponym
~i Instance Hyponym
#m Member holonym
#s Substance holonym
#p Part holonym
%m Member meronym
%s Substance meronym
%p Part meronym
= Attribute
+ Derivationally related form
;c Domain of synset - TOPIC
-c Member of this domain - TOPIC
;r Domain of synset - REGION
-r Member of this domain - REGION
;u Domain of synset - USAGE
-u Member of this domain - USAGE
The pointer_symbol s for verbs are:
! Antonym
@ Hypernym
~ Hyponym
* Entailment
> Cause
^ Also see
$ Verb Group
+ Derivationally related form
;c Domain of synset - TOPIC
;r Domain of synset - REGION
;u Domain of synset - USAGE
The pointer_symbol s for adjectives are:
! Antonym
& Similar to
< Participle of verb
\ Pertainym (pertains to noun)
= Attribute
^ Also see
;c Domain of synset - TOPIC
;r Domain of synset - REGION
;u Domain of synset - USAGE
The pointer_symbol s for adverbs are:
! Antonym
\ Derived from adjective
;c Domain of synset - TOPIC
;r Domain of synset - REGION
;u Domain of synset - USAGE
"""
mm = self.graph_db.nodes.match( self.nodelabel )
node1 = mm.where('_.synset_id="%s" ' % (synset1) ).first()
node2 = mm.where('_.synset_id="%s" ' % (synset2) ).first()
if (node1 is not None) and (node2 is not None):
rel = Relationship(node1, self.reltype, node2, pointer_symbol=ptype)
return rel
else:
raise Exception("Could not create Wordnet relation (%s) - [%s] -> (%s)" % (
synset1, ptype, synset2))
def insert_bulk(self, objs):
if len(objs) > 0:
tx = self.graph_db.begin()
for obj in objs:
tx.create(obj)
tx.commit()
| 153 | 31.97 | 98 | 14 | 1,247 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_1c7e1b692d9fd64a_e15d55e7", "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": 35, "line_end": 36, "column_start": 13, "column_end": 32, "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/tmphvvervh1/1c7e1b692d9fd64a.py", "start": {"line": 35, "col": 13, "offset": 812}, "end": {"line": 36, "col": 32, "offset": 903}, "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_1c7e1b692d9fd64a_1df7ba6c", "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": 35, "line_end": 36, "column_start": 13, "column_end": 32, "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/tmphvvervh1/1c7e1b692d9fd64a.py", "start": {"line": 35, "col": 13, "offset": 812}, "end": {"line": 36, "col": 32, "offset": 903}, "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_1c7e1b692d9fd64a_85ba9598", "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": 40, "line_end": 41, "column_start": 13, "column_end": 32, "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/tmphvvervh1/1c7e1b692d9fd64a.py", "start": {"line": 40, "col": 13, "offset": 962}, "end": {"line": 41, "col": 32, "offset": 1058}, "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_1c7e1b692d9fd64a_a59aaa87", "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": 40, "line_end": 41, "column_start": 13, "column_end": 32, "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/tmphvvervh1/1c7e1b692d9fd64a.py", "start": {"line": 40, "col": 13, "offset": 962}, "end": {"line": 41, "col": 32, "offset": 1058}, "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_1c7e1b692d9fd64a_7f7baec7", "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": 45, "line_end": 46, "column_start": 13, "column_end": 30, "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/tmphvvervh1/1c7e1b692d9fd64a.py", "start": {"line": 45, "col": 13, "offset": 1117}, "end": {"line": 46, "col": 30, "offset": 1215}, "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_1c7e1b692d9fd64a_01cd2d1d", "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": 45, "line_end": 46, "column_start": 13, "column_end": 30, "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/tmphvvervh1/1c7e1b692d9fd64a.py", "start": {"line": 45, "col": 13, "offset": 1117}, "end": {"line": 46, "col": 30, "offset": 1215}, "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"}}}] | 6 | true | [
"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"
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH",
"MEDIUM",
"HIGH"
] | [
35,
35,
40,
40,
45,
45
] | [
36,
36,
41,
41,
46,
46
] | [
13,
13,
13,
13,
13,
13
] | [
32,
32,
32,
32,
30,
30
] | [
"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
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | neo4jstuff.py | /neo4jstuff.py | sergey-zarealye-com/wordnet2neo4j | Apache-2.0 | |
2024-11-18T21:14:34.708710+00:00 | 1,677,690,492,000 | 00524f03ad63f097fc2b183f400fa73cc3d956e5 | 2 | {
"blob_id": "00524f03ad63f097fc2b183f400fa73cc3d956e5",
"branch_name": "refs/heads/master",
"committer_date": 1677690492000,
"content_id": "70a48beb8254f1ca19a8a14abc2fcba0765ff736",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "58a9a6cdb9787866268a4d6ca49d9fa10f4f6c02",
"extension": "py",
"filename": "natlearn.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 229675391,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4705,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/bak/natlearn.py",
"provenance": "stack-edu-0054.json.gz:583395",
"repo_name": "ptarau/pypro",
"revision_date": 1677690492000,
"revision_id": "a9b65f0dc5721155b899e4748b425655cb541c23",
"snapshot_id": "150d616eb6bd172d9e3ad876e8c6386bf85f8235",
"src_encoding": "UTF-8",
"star_events_count": 16,
"url": "https://raw.githubusercontent.com/ptarau/pypro/a9b65f0dc5721155b899e4748b425655cb541c23/bak/natlearn.py",
"visit_date": "2023-03-03T10:14:34.661598"
} | 2.328125 | stackv2 | from .natlog import natlog
from .db import db
from .unify import const_of
#from Natlog.Parser import parse
#from Natlog.Scanner import Int
from sklearn.ensemble import RandomForestClassifier
from sklearn.neural_network import MLPClassifier
#from answerer import tsv2mat
import numpy as np
from sklearn.preprocessing import OneHotEncoder
# WORK IN PROGRESS, TODO "
def tsv2db(fname='natprogs/Db.tsv'):
rels=db()
#wss = tsv2mat(fname)
#for ws in wss: rels.add_db_clause(ws)
rels.load_tsv(fname)
return rels
'''
def wss2hotXy(wss,io_split = -1) :
Xy=np.array(wss)
X=Xy[:,:io_split]
y=Xy[:,io_split:]
print(X.shape,y.shape)
enc=OneHotEncoder(handle_unknown='ignore')
enc.fit(X)
hotX=enc.transform(X).toarray()
enc_ = OneHotEncoder(handle_unknown='ignore')
enc_.fit(y)
hoty = enc_.transform(y).toarray()
#print(hotX.shape,hoty.shape)
#coldX=enc.inverse_transform(hotX)
#print(coldX[0])
return enc,hotX,enc_,hoty
'''
def wss2hotX(wss,mask) :
mask=[mask]*len(wss[0])
X=np.array(wss)
Xplus=np.array(wss+[mask])
print(Xplus.shape)
enc=OneHotEncoder(handle_unknown='ignore')
enc.fit(X)
hotX=enc.transform(X).toarray()
return enc,X,hotX
# it might work for larger databases
learner=MLPClassifier(
hidden_layer_sizes=(64,16,64),
verbose=True,
activation='logistic',
max_iter=10000)
learner=RandomForestClassifier(random_state=1234)
# bit encodings
def set2bits(n,xs) :
return tuple(1 if x in xs else 0 for x in range(n))
def bits2set(bs):
return (i for i,b in enumerate(bs) if b==1)
def seq2nums(xs) :
return dict((x,i) for (i,x) in enumerate(xs))
def seq2bits(xs) :
d=seq2nums(xs)
l=len(xs)
return tuple(set2bits(l,[d[x]]) for x in xs)
def bits2seq(xs,bss) :
nss = map(bits2set,bss)
return [xs[i] for ns in nss for i in ns]
class multilearner(natlog) :
def __init__(self,
text=None,
file_name=None,
tsv_file='natprogs/Db.tsv',
learner=learner
):
if not text and not file_name: text = ""
super().__init__(text=text, file_name=file_name)
self.learner = learner
self.rels = tsv2db(fname=tsv_file)
l=len(self.rels.css)
ixbits=dict((x,set2bits(l,xs)) for (x,xs) in self.rels.index.items())
codes=seq2bits(self.rels.index)
print(len(ixbits),len(codes))
#print(ixbits)
X=np.array(codes)
y=np.array(list(ixbits.values()))
print(X)
print('\n',y)
self.X,self.y,self.codes,self.ixbits=X,y,codes,ixbits
self.train()
def generator_transformer(self):
print("!!!!!!THERE")
def eval_it(x):
print('EVAL', x, type(x))
f = eval(x)
print('AFTER EVAL', f, type(f))
return f
def train(self):
self.learner.fit(self.X,self.y)
def ask(self,qs):
print('TODO')
names_nums = seq2nums(self.rels.index)
consts=const_of(qs)
#print('NAMES',names_nums)
#print('CONSTS',consts)
nums=[names_nums[c] for c in consts if c in names_nums]
#print('NUMS',nums)
l=len(names_nums)
rs=np.array([[1]*self.y.shape[1]])
for qn in nums :
qa=np.array([[q for q in set2bits(l,[qn])]])
r=self.learner.predict(qa)
rs=np.bitwise_and(rs,r)
#print('RRR',rs[0])
vals=list(rs[0])
vals=list(bits2set(vals))
print('VALS:',vals)
Ans=[self.rels.css[v] for v in vals]
for A in Ans: yield A
'''
class natlearner(Natlog) :
def __init__(self,
text=None,
file_name=None,
tsv_file='natprogs/Db.tsv',
learner=learner
):
if not text and not file_name : text = ""
super().__init__(text=text,file_name=file_name)
self.learner = learner
self.mask='###'
self.rels=tsv2db(fname=tsv_file)
self.y0=np.array(self.rels.css)
self.enc,self.X,self.hotX=wss2hotX(self.rels.css,self.mask)
def train(self):
width=self.y0.shape[1]
yargs=[self.hotX for _ in range(width)]
y=np.concatenate(yargs,axis=0)
maskColumn=np.array([self.mask]*self.X.shape[0])
xargs=[]
for i in range(width) :
Xi=self.X.copy()
Xi[:,i]=maskColumn
xargs.append(Xi)
X=np.concatenate(tuple(xargs),axis=0)
X=self.enc.transform(X)
print(X.shape,y.shape)
return self.learner.fit(X,y)
def ask(self,qss):
Q=np.array(qss)
hotQ=self.enc.transform(Q).toarray()
assert hotQ.shape[1]==self.hotX.shape[1]
hotA=(self.learner.predict(hotQ))
altA = (self.learner.predict_proba(hotQ))
for x in hotA[0]: print('$$$',x)
for x in altA: print('!!!', x)
#print("\nANSWER's hot shape",hotA.shape,'\n')
A=self.enc.inverse_transform(hotA)
return A
'''
| 207 | 21.73 | 73 | 18 | 1,427 | python | [{"finding_id": "semgrep_rules.python.lang.maintainability.useless-inner-function_74f5622c12faeb25_6ce77ac6", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-inner-function", "finding_type": "maintainability", "severity": "high", "confidence": "medium", "message": "function `eval_it` is defined inside a function but never used", "remediation": "", "location": {"file_path": "unknown", "line_start": 113, "line_end": 117, "column_start": 5, "column_end": 15, "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.maintainability.useless-inner-function", "path": "/tmp/tmphvvervh1/74f5622c12faeb25.py", "start": {"line": 113, "col": 5, "offset": 2597}, "end": {"line": 117, "col": 15, "offset": 2715}, "extra": {"message": "function `eval_it` is defined inside a function but never used", "metadata": {"category": "maintainability", "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.eval-detected_74f5622c12faeb25_7d95ed52", "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": 115, "line_end": 115, "column_start": 11, "column_end": 18, "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/tmphvvervh1/74f5622c12faeb25.py", "start": {"line": 115, "col": 11, "offset": 2655}, "end": {"line": 115, "col": 18, "offset": 2662}, "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"}}}] | 2 | true | [
"CWE-95"
] | [
"rules.python.lang.security.audit.eval-detected"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
115
] | [
115
] | [
11
] | [
18
] | [
"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"
] | natlearn.py | /bak/natlearn.py | ptarau/pypro | Apache-2.0 | |
2024-11-18T21:14:35.003733+00:00 | 1,574,348,827,000 | ee48a18912bcfe37f61a12f7c33a35c885e3ae38 | 3 | {
"blob_id": "ee48a18912bcfe37f61a12f7c33a35c885e3ae38",
"branch_name": "refs/heads/master",
"committer_date": 1574348827000,
"content_id": "0b7bf1ce0babd4d9579aa76d4668155d16d28ae2",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "31ed390054f43cfec82db5d2dd55a0ced84c0800",
"extension": "py",
"filename": "io_py_result_processor.py",
"fork_events_count": 0,
"gha_created_at": 1574347263000,
"gha_event_created_at": 1574347264000,
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 223195454,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5829,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/scripts/postprocessing/io_py_result_processor.py",
"provenance": "stack-edu-0054.json.gz:583398",
"repo_name": "SofyaTavrovskaya/disk_perf_test_tool",
"revision_date": 1574348827000,
"revision_id": "de0ad119c509429eeff7de4df3b76a6c999540be",
"snapshot_id": "48564d4e395dc8cd4c949550163ce1d84948ef31",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SofyaTavrovskaya/disk_perf_test_tool/de0ad119c509429eeff7de4df3b76a6c999540be/scripts/postprocessing/io_py_result_processor.py",
"visit_date": "2020-09-14T17:08:55.397155"
} | 2.796875 | stackv2 | import sys
import math
import itertools
from colorama import Fore, Style
def med_dev(vals):
med = sum(vals) / len(vals)
dev = ((sum(abs(med - i) ** 2 for i in vals) / len(vals)) ** 0.5)
return int(med), int(dev)
def round_deviation(med_dev):
med, dev = med_dev
if dev < 1E-7:
return med_dev
dev_div = 10.0 ** (math.floor(math.log10(dev)) - 1)
dev = int(dev / dev_div) * dev_div
med = int(med / dev_div) * dev_div
return (type(med_dev[0])(med),
type(med_dev[1])(dev))
def groupby_globally(data, key_func):
grouped = {}
grouped_iter = itertools.groupby(data, key_func)
for (bs, cache_tp, act), curr_data_it in grouped_iter:
key = (bs, cache_tp, act)
grouped.setdefault(key, []).extend(curr_data_it)
return grouped
class Data(object):
def __init__(self, name):
self.name = name
self.series = {}
self.processed_series = {}
def process_inplace(data):
processed = {}
for key, values in data.series.items():
processed[key] = round_deviation(med_dev(values))
data.processed_series = processed
def diff_table(*datas):
res_table = {}
for key in datas[0].processed_series:
baseline = datas[0].processed_series[key]
base_max = baseline[0] + baseline[1]
base_min = baseline[0] - baseline[1]
res_line = [baseline]
for data in datas[1:]:
val, dev = data.processed_series[key]
val_min = val - dev
val_max = val + dev
diff_1 = int(float(val_min - base_max) / base_max * 100)
diff_2 = int(float(val_max - base_min) / base_max * 100)
diff_max = max(diff_1, diff_2)
diff_min = min(diff_1, diff_2)
res_line.append((diff_max, diff_min))
res_table[key] = res_line
return [data.name for data in datas], res_table
def print_table(headers, table):
lines = []
items = sorted(table.items())
lines.append([(len(i), i) for i in [""] + headers])
item_frmt = "{0}{1:>4}{2} ~ {3}{4:>4}{5}"
for key, vals in items:
ln1 = "{0:>4} {1} {2:>9} {3}".format(*map(str, key))
ln2 = "{0:>4} ~ {1:>3}".format(*vals[0])
line = [(len(ln1), ln1), (len(ln2), ln2)]
for idx, val in enumerate(vals[1:], 2):
cval = []
for vl in val:
if vl < -10:
cval.extend([Fore.RED, vl, Style.RESET_ALL])
elif vl > 10:
cval.extend([Fore.GREEN, vl, Style.RESET_ALL])
else:
cval.extend(["", vl, ""])
ln = len(item_frmt.format("", cval[1], "", "", cval[4], ""))
line.append((ln, item_frmt.format(*cval)))
lines.append(line)
max_columns_with = []
for idx in range(len(lines[0])):
max_columns_with.append(
max(line[idx][0] for line in lines))
sep = '-' * (4 + sum(max_columns_with) + 3 * (len(lines[0]) - 1))
print sep
for idx, line in enumerate(lines):
cline = []
for (curr_len, txt), exp_ln in zip(line, max_columns_with):
cline.append(" " * (exp_ln - curr_len) + txt)
print "| " + " | ".join(cline) + " |"
if 0 == idx:
print sep
print sep
def key_func(x):
return (x['__meta__']['blocksize'],
'd' if 'direct' in x['__meta__'] else 's',
x['__meta__']['name'])
template = "{bs:>4} {action:>12} {cache_tp:>3} {conc:>4}"
template += " | {iops[0]:>6} ~ {iops[1]:>5} | {bw[0]:>7} ~ {bw[1]:>6}"
template += " | {lat[0]:>6} ~ {lat[1]:>5} |"
headers = dict(bs="BS",
action="operation",
cache_tp="S/D",
conc="CONC",
iops=("IOPS", "dev"),
bw=("BW kBps", "dev"),
lat=("LAT ms", "dev"))
def load_io_py_file(fname):
with open(fname) as fc:
block = None
for line in fc:
if line.startswith("{"):
block = line
elif block is not None:
block += line
if block is not None and block.count('}') == block.count('{'):
cut = block.rfind('}')
block = block[0:cut+1]
yield eval(block)
block = None
if block is not None and block.count('}') == block.count('{'):
yield eval(block)
def main(argv):
items = []
CONC_POS = 3
for hdr_fname in argv[1:]:
hdr, fname = hdr_fname.split("=", 1)
data = list(load_io_py_file(fname))
item = Data(hdr)
for key, vals in groupby_globally(data, key_func).items():
item.series[key] = [val['iops'] * key[CONC_POS] for val in vals]
process_inplace(item)
items.append(item)
print_table(*diff_table(*items))
# print template.format(**headers)
# for (bs, cache_tp, act, conc), curr_data in sorted(grouped.items()):
# iops = med_dev([i['iops'] * int(conc) for i in curr_data])
# bw = med_dev([i['bw'] * int(conc) for i in curr_data])
# lat = med_dev([i['lat'] / 1000 for i in curr_data])
# iops = round_deviation(iops)
# bw = round_deviation(bw)
# lat = round_deviation(lat)
# params = dict(
# bs=bs,
# action=act,
# cache_tp=cache_tp,
# iops=iops,
# bw=bw,
# lat=lat,
# conc=conc
# )
# print template.format(**params)
if __name__ == "__main__":
exit(main(sys.argv))
# vals = [(123, 23), (125678, 5678), (123.546756, 23.77),
# (123.546756, 102.77), (0.1234, 0.0224),
# (0.001234, 0.000224), (0.001234, 0.0000224)]
# for val in :
# print val, "=>", round_deviation(val)
| 207 | 27.16 | 76 | 18 | 1,706 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_4c2c4e47fadef00a_8c1e48fa", "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": 144, "line_end": 144, "column_start": 10, "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/tmphvvervh1/4c2c4e47fadef00a.py", "start": {"line": 144, "col": 10, "offset": 3913}, "end": {"line": 144, "col": 21, "offset": 3924}, "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.eval-detected_4c2c4e47fadef00a_4266b21a", "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": 155, "line_end": 155, "column_start": 23, "column_end": 34, "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/tmphvvervh1/4c2c4e47fadef00a.py", "start": {"line": 155, "col": 23, "offset": 4285}, "end": {"line": 155, "col": 34, "offset": 4296}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_4c2c4e47fadef00a_9366294c", "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": 159, "line_end": 159, "column_start": 15, "column_end": 26, "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/tmphvvervh1/4c2c4e47fadef00a.py", "start": {"line": 159, "col": 15, "offset": 4408}, "end": {"line": 159, "col": 26, "offset": 4419}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.use-sys-exit_4c2c4e47fadef00a_b0fa93d5", "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(main(sys.argv))", "location": {"file_path": "unknown", "line_start": 201, "line_end": 201, "column_start": 5, "column_end": 25, "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/tmphvvervh1/4c2c4e47fadef00a.py", "start": {"line": 201, "col": 5, "offset": 5565}, "end": {"line": 201, "col": 25, "offset": 5585}, "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(main(sys.argv))", "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"}}}] | 4 | true | [
"CWE-95",
"CWE-95"
] | [
"rules.python.lang.security.audit.eval-detected",
"rules.python.lang.security.audit.eval-detected"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
155,
159
] | [
155,
159
] | [
23,
15
] | [
34,
26
] | [
"A03:2021 - Injection",
"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.",
"Detected the use of eval(). eval() can be dangerous if used... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | io_py_result_processor.py | /scripts/postprocessing/io_py_result_processor.py | SofyaTavrovskaya/disk_perf_test_tool | Apache-2.0 | |
2024-11-18T21:14:35.317098+00:00 | 1,687,111,332,000 | bdba9af3d109f769c2d174efa3e43c51a6e94d3a | 3 | {
"blob_id": "bdba9af3d109f769c2d174efa3e43c51a6e94d3a",
"branch_name": "refs/heads/master",
"committer_date": 1687111332000,
"content_id": "922d3f796f9d0406ff05ea9382177f0bc14fd9b0",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "94aa1f239df81f7ff7b82efd4123fa9075de4b1e",
"extension": "py",
"filename": "LDAModel.py",
"fork_events_count": 0,
"gha_created_at": 1577009042000,
"gha_event_created_at": 1676502137000,
"gha_language": "Python",
"gha_license_id": "Apache-2.0",
"github_id": 229548707,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3306,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/TwitterModelingPython/LDAModel.py",
"provenance": "stack-edu-0054.json.gz:583403",
"repo_name": "PatrickKoss/TwitterTopicModeling",
"revision_date": 1687111332000,
"revision_id": "cf57617c192ca536d7450e8e08b1fb2ae9d90b47",
"snapshot_id": "e023aed0e904f523504bb89e9eb9533263ef3134",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/PatrickKoss/TwitterTopicModeling/cf57617c192ca536d7450e8e08b1fb2ae9d90b47/TwitterModelingPython/LDAModel.py",
"visit_date": "2023-06-30T00:09:50.558522"
} | 3.34375 | stackv2 | import nltk
import pandas as pd
import gensim
from nltk.stem import WordNetLemmatizer
from nltk.stem.porter import *
import pickle
from multiprocessing import freeze_support
nltk.download('wordnet')
if __name__ == '__main__':
# add freeze support for multiprocessing LDA Multicore
freeze_support()
# use porterstemmer as stemmer
stemmer = PorterStemmer()
# function for lemmatizing
def lemmatize_stemming(text):
return stemmer.stem(WordNetLemmatizer().lemmatize(text, pos='v'))
# function for preprocessing a tweet
def preprocess(text):
result = []
for token in gensim.utils.simple_preprocess(text):
if token not in gensim.parsing.preprocessing.STOPWORDS and len(token) > 3 and "http" not in token:
result.append(lemmatize_stemming(token))
return result
# function for training the lda model
def train_lda(bow_corpus, dictionary, filename):
lda_model = gensim.models.LdaMulticore(bow_corpus, num_topics=10, id2word=dictionary)
# save the trained lda model with pickle
pickle.dump(lda_model, open(filename, 'wb'))
def prepare_docs(documents_outside):
# map a tweet to a processed tweet
return documents_outside['tweet'].map(preprocess)
def create_bow_corpus_dict(filename_bow, filename_dictionary):
# read in the tweets
df = pd.read_csv("tweets.csv", error_bad_lines=False)
# add an index column
df["index"] = df.index
# make a copy of the dataframe
documents = df.copy()
print(len(documents))
# map a tweet to a processed tweet
processed_docs = prepare_docs(documents)
# create a dictionary. Its keys are the indexes and the value are tokens.
dictionary = gensim.corpora.Dictionary(processed_docs)
# filter the dictionary. Remove a token if it is in less than 15 tweets and is in more than 0.5 documents.
# Also keep only the first 50000 tokens.
dictionary.filter_extremes(no_below=15, no_above=0.5, keep_n=50000)
# For each tweet create a dictionary how many words and how many times those words appear.
bow_corpus = [dictionary.doc2bow(doc) for doc in processed_docs]
pickle.dump(bow_corpus, open(filename_bow, 'wb'))
pickle.dump(dictionary, open(filename_dictionary, 'wb'))
# set a file name for saving the trained lda model
filename = 'lda_model.sav'
filename_bow_corpus = 'bow_corpus.sav'
filename_dict = 'dict.sav'
# create the bow corpus and dictionary
create_bow_corpus_dict(filename_bow_corpus, filename_dict)
bow_corpus = pickle.load(open(filename_bow_corpus, 'rb'))
dictionary = pickle.load(open(filename_dict, 'rb'))
# train the model and save it
train_lda(bow_corpus, dictionary, filename)
# load the before saved model
lda_model = pickle.load(open(filename, 'rb'))
# test an unseen document and see how it scores on the topics
unseen_document = 'I was going to the cinema and met a dog.'
bow_vector = dictionary.doc2bow(preprocess(unseen_document))
for index, score in sorted(lda_model[bow_vector], key=lambda tup: -1 * tup[1]):
print("Score: {}\t Topic: {}".format(score, lda_model.print_topic(index, 10)))
| 87 | 37 | 114 | 15 | 790 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_a14e75fe9c6d7e03_d8e5711c", "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": 36, "line_end": 36, "column_start": 9, "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/tmphvvervh1/a14e75fe9c6d7e03.py", "start": {"line": 36, "col": 9, "offset": 1100}, "end": {"line": 36, "col": 53, "offset": 1144}, "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_a14e75fe9c6d7e03_af2ce897", "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": 61, "line_end": 61, "column_start": 9, "column_end": 58, "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/tmphvvervh1/a14e75fe9c6d7e03.py", "start": {"line": 61, "col": 9, "offset": 2266}, "end": {"line": 61, "col": 58, "offset": 2315}, "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_a14e75fe9c6d7e03_5f61c8a5", "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": 62, "line_end": 62, "column_start": 9, "column_end": 65, "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/tmphvvervh1/a14e75fe9c6d7e03.py", "start": {"line": 62, "col": 9, "offset": 2324}, "end": {"line": 62, "col": 65, "offset": 2380}, "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_a14e75fe9c6d7e03_5f817b2c", "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": 73, "line_end": 73, "column_start": 18, "column_end": 62, "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/tmphvvervh1/a14e75fe9c6d7e03.py", "start": {"line": 73, "col": 18, "offset": 2668}, "end": {"line": 73, "col": 62, "offset": 2712}, "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_a14e75fe9c6d7e03_489d281a", "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": 74, "line_end": 74, "column_start": 18, "column_end": 56, "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/tmphvvervh1/a14e75fe9c6d7e03.py", "start": {"line": 74, "col": 18, "offset": 2730}, "end": {"line": 74, "col": 56, "offset": 2768}, "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_a14e75fe9c6d7e03_e5f2e7d3", "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": 80, "line_end": 80, "column_start": 17, "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/tmphvvervh1/a14e75fe9c6d7e03.py", "start": {"line": 80, "col": 17, "offset": 2903}, "end": {"line": 80, "col": 50, "offset": 2936}, "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.return-not-in-function_a14e75fe9c6d7e03_009aaf6e", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 85, "line_end": 85, "column_start": 71, "column_end": 82, "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.return-not-in-function", "path": "/tmp/tmphvvervh1/a14e75fe9c6d7e03.py", "start": {"line": 85, "col": 71, "offset": 3204}, "end": {"line": 85, "col": 82, "offset": 3215}, "extra": {"message": "`return` only makes sense inside a function", "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",
"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"
] | [
36,
61,
62,
73,
74,
80
] | [
36,
61,
62,
73,
74,
80
] | [
9,
9,
9,
18,
18,
17
] | [
53,
58,
65,
62,
56,
50
] | [
"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"
] | LDAModel.py | /TwitterModelingPython/LDAModel.py | PatrickKoss/TwitterTopicModeling | Apache-2.0 | |
2024-11-18T21:14:37.055678+00:00 | 1,675,067,711,000 | b67bb1c580683e17c7ccb9d173fecd110deba093 | 3 | {
"blob_id": "b67bb1c580683e17c7ccb9d173fecd110deba093",
"branch_name": "refs/heads/master",
"committer_date": 1675067711000,
"content_id": "8a69840882455cf98d49506619447654e3ecf6b6",
"detected_licenses": [
"MIT"
],
"directory_id": "5a01774b1815a3d9a5b02b26ca4d6ba9ecf41662",
"extension": "py",
"filename": "connection.py",
"fork_events_count": 41,
"gha_created_at": 1472214645000,
"gha_event_created_at": 1681728345000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 66646080,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1683,
"license": "MIT",
"license_type": "permissive",
"path": "/Module 1/Chapter12/Work_manager/TasksManager/views/connection.py",
"provenance": "stack-edu-0054.json.gz:583415",
"repo_name": "PacktPublishing/Django-Web-Development-with-Python",
"revision_date": 1675067711000,
"revision_id": "9f619f56553b5f0bca9b5ee2ae32953e142df1b2",
"snapshot_id": "bf08075ff0a85df41980cb5e272877e01177fd07",
"src_encoding": "UTF-8",
"star_events_count": 39,
"url": "https://raw.githubusercontent.com/PacktPublishing/Django-Web-Development-with-Python/9f619f56553b5f0bca9b5ee2ae32953e142df1b2/Module 1/Chapter12/Work_manager/TasksManager/views/connection.py",
"visit_date": "2023-04-27T22:36:07.610076"
} | 2.6875 | stackv2 | from django.shortcuts import render, redirect
from django import forms
from django.contrib.auth import authenticate, login
# This line allows you to import the necessary functions of the authentication module.
def page(request):
if request.POST:
# This line is used to check if the Form_connection form has been posted. If mailed, the form will be treated, otherwise it will be displayed to the user.
form = Form_connection(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(username=username, password=password)
# This line verifies that the username exists and the password is correct.
if user:
# In this line, the authenticate function returns None if authentication has failed, otherwise it returns an object that validate the condition.
login(request, user)
# In this line, the login() function allows the user to connect.
if request.GET.get('next') is not None:
return redirect(request.GET['next'])
else:
return render(request, 'en/public/connection.html', {'form' : form})
else:
form = Form_connection()
return render(request, 'en/public/connection.html', {'form' : form})
class Form_connection(forms.Form):
username = forms.CharField(label="Login")
password = forms.CharField(label="Password", widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(Form_connection, self).clean()
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
if not authenticate(username=username, password=password):
raise forms.ValidationError("Wrong login or passwsord")
return self.cleaned_data
| 35 | 47.09 | 155 | 17 | 350 | python | [{"finding_id": "semgrep_rules.python.django.security.injection.open-redirect_9100161236347886_9d09b7c3", "tool_name": "semgrep", "rule_id": "rules.python.django.security.injection.open-redirect", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Data from request ($DATA) is passed to redirect(). This is an open redirect and could be exploited. Ensure you are redirecting to safe URLs by using django.utils.http.is_safe_url(). See https://cwe.mitre.org/data/definitions/601.html for more information.", "remediation": "", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 6, "column_end": 42, "code_snippet": "requires login"}, "cwe_id": "CWE-601: URL Redirection to Untrusted Site ('Open Redirect')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2021 - Broken Access Control", "references": [{"url": "https://www.djm.org.uk/posts/djangos-little-protections-word-redirect-dangers/", "title": null}, {"url": "https://github.com/django/django/blob/d1b7bd030b1db111e1a3505b1fc029ab964382cc/django/utils/http.py#L231", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.injection.open-redirect", "path": "/tmp/tmphvvervh1/9100161236347886.py", "start": {"line": 19, "col": 6, "offset": 996}, "end": {"line": 19, "col": 42, "offset": 1032}, "extra": {"message": "Data from request ($DATA) is passed to redirect(). This is an open redirect and could be exploited. Ensure you are redirecting to safe URLs by using django.utils.http.is_safe_url(). See https://cwe.mitre.org/data/definitions/601.html 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://www.djm.org.uk/posts/djangos-little-protections-word-redirect-dangers/", "https://github.com/django/django/blob/d1b7bd030b1db111e1a3505b1fc029ab964382cc/django/utils/http.py#L231"], "category": "security", "technology": ["django"], "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.django.security.injection.open-redirect_9100161236347886_61947b9d", "tool_name": "semgrep", "rule_id": "rules.python.django.security.injection.open-redirect", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Data from request ($DATA) is passed to redirect(). This is an open redirect and could be exploited. Ensure you are redirecting to safe URLs by using django.utils.http.is_safe_url(). See https://cwe.mitre.org/data/definitions/601.html for more information.", "remediation": "", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 13, "column_end": 42, "code_snippet": "requires login"}, "cwe_id": "CWE-601: URL Redirection to Untrusted Site ('Open Redirect')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2021 - Broken Access Control", "references": [{"url": "https://www.djm.org.uk/posts/djangos-little-protections-word-redirect-dangers/", "title": null}, {"url": "https://github.com/django/django/blob/d1b7bd030b1db111e1a3505b1fc029ab964382cc/django/utils/http.py#L231", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.injection.open-redirect", "path": "/tmp/tmphvvervh1/9100161236347886.py", "start": {"line": 19, "col": 13, "offset": 1003}, "end": {"line": 19, "col": 42, "offset": 1032}, "extra": {"message": "Data from request ($DATA) is passed to redirect(). This is an open redirect and could be exploited. Ensure you are redirecting to safe URLs by using django.utils.http.is_safe_url(). See https://cwe.mitre.org/data/definitions/601.html 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://www.djm.org.uk/posts/djangos-little-protections-word-redirect-dangers/", "https://github.com/django/django/blob/d1b7bd030b1db111e1a3505b1fc029ab964382cc/django/utils/http.py#L231"], "category": "security", "technology": ["django"], "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-601",
"CWE-601"
] | [
"rules.python.django.security.injection.open-redirect",
"rules.python.django.security.injection.open-redirect"
] | [
"security",
"security"
] | [
"MEDIUM",
"MEDIUM"
] | [
"MEDIUM",
"MEDIUM"
] | [
19,
19
] | [
19,
19
] | [
6,
13
] | [
42,
42
] | [
"A01:2021 - Broken Access Control",
"A01:2021 - Broken Access Control"
] | [
"Data from request ($DATA) is passed to redirect(). This is an open redirect and could be exploited. Ensure you are redirecting to safe URLs by using django.utils.http.is_safe_url(). See https://cwe.mitre.org/data/definitions/601.html for more information.",
"Data from request ($DATA) is passed to redirect(). Thi... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | connection.py | /Module 1/Chapter12/Work_manager/TasksManager/views/connection.py | PacktPublishing/Django-Web-Development-with-Python | MIT | |
2024-11-18T21:14:37.178333+00:00 | 1,472,312,753,000 | 16ffa97087cd0d97da2b8fb7880cb28cec1bbadd | 3 | {
"blob_id": "16ffa97087cd0d97da2b8fb7880cb28cec1bbadd",
"branch_name": "refs/heads/master",
"committer_date": 1472313602000,
"content_id": "ad5f28200d841520e8121ad6c0c0407bd54814ac",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c9f3a222ab317ae69e2ced148a6d51610a4af477",
"extension": "py",
"filename": "worker.py",
"fork_events_count": 1,
"gha_created_at": 1468844212000,
"gha_event_created_at": 1469106510000,
"gha_language": "Python",
"gha_license_id": null,
"github_id": 63600514,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5975,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/worker.py",
"provenance": "stack-edu-0054.json.gz:583417",
"repo_name": "macisamuele/git-worker",
"revision_date": 1472312753000,
"revision_id": "679d7c497bcc4173aa8808eefb232a7d79c3010f",
"snapshot_id": "3c7b1aed292d50a232d713ed5abde6f4fc2b8344",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/macisamuele/git-worker/679d7c497bcc4173aa8808eefb232a7d79c3010f/src/worker.py",
"visit_date": "2020-04-06T06:58:22.081404"
} | 2.546875 | stackv2 | # -*- coding: utf-8 -*-
import logging
import subprocess
from abc import ABCMeta
from abc import abstractmethod
from sys import stderr
import return_codes
from autologging import TRACE
from autologging import traced
from configuration import Configuration
from git_commands import GitCommand
logging.basicConfig(level=TRACE, stream=stderr,
format='%(levelname)s | %(name)s | %(funcName)s:%(lineno)s | %(message)s')
class AbstractWorker:
__metaclass__ = ABCMeta
def __init__(self):
pass
@abstractmethod
def _start(self):
pass
@abstractmethod
def _join(self):
pass
@abstractmethod
def _pre_start(self):
pass
def run(self):
"""
Start and wait the execution of the RepositoryWorkers
:return: return code specifying the exit status. WorkerSuccess() is returned if everything if the process is
successfully completed, other extensions of WorkerReturnCode are returned in case of error
:rtype: WorkerReturnCode
"""
self._pre_start()
if not self._start(): # problems to start the executions? kill everything
return return_codes.StartError()
if not self._join(): # problems to wait the RepositoryWorkers? report a log
return return_codes.JoinError()
return return_codes.Success()
class RepositoryWorker(AbstractWorker):
"""
The class is handling the flow described on the
`How it works <https://github.com/macisamuele/git-worker/#how-it-works>`_
section of the README
"""
configuration = None
repository_cmds = None
def __init__(self, configuration):
super(RepositoryWorker, self).__init__()
self.configuration = configuration
if configuration is not None:
self.repository_cmds = GitCommand(configuration['repository'])
def _is_master_branch(self):
return self.repository_cmds.current_branch() == self.configuration['master_branch']
def _is_your_feature_branch(self):
return self.configuration['feature_branches'].match(self.repository_cmds.current_branch()) is not None
def _merge_rebase(self):
if self.configuration['update_strategy'] == 'merge':
return self.repository_cmds.merge(self.configuration['master_branch'])
elif self.configuration['update_strategy'] == 'rebase':
return self.repository_cmds.rebase(self.configuration['master_branch'])
def _merge_rebase_abort(self):
if self.configuration['update_strategy'] == 'merge':
return self.repository_cmds.merge_abort()
elif self.configuration['update_strategy'] == 'rebase':
return self.repository_cmds.rebase_abort()
@traced(logging.getLogger('RepositoryWorker'))
def _start(self):
if self._is_master_branch():
return self.repository_cmds.pull('{remote} {branch}'.format(
remote=self.configuration['git_remote'],
branch=self.configuration['master_branch'],
))
elif self._is_your_feature_branch():
if not self.repository_cmds.fetch('{remote} {branch}'.format(
remote=self.configuration['git_remote'],
branch=self.configuration['master_branch'],
)):
return False
self.repository_cmds.fetch(self.configuration['master_branch'])
if not self._merge_rebase():
self._merge_rebase_abort()
return False
try:
subprocess.check_call(self.configuration['build_command'].split())
subprocess.check_call(self.configuration['test_command'].split())
except subprocess.CalledProcessError:
self._merge_rebase_abort()
return False
return True
@traced(logging.getLogger('RepositoryWorker'))
def _join(self):
return True
@traced(logging.getLogger('RepositoryWorker'))
def _pre_start(self):
if self.configuration is None or self.repository_cmds is None:
return return_codes.ConfigurationError()
def __repr__(self):
return str(self.configuration['repository'].git_dir)
class Worker(AbstractWorker):
"""
The class is handling the whole git-worker process:
- configuration fetching and validation
- spinning elaboration for each repository (sequential way or one process per repository
Basically it acts as a manager for the RepositoryWorkers
"""
configuration = None
def __init__(self, args):
super(Worker, self).__init__()
worker_configuration = Configuration()
worker_configuration.parse(args)
self.configuration = worker_configuration.config
@traced(logging.getLogger('Worker'))
def _start(self):
"""
Start the execution of the RepositoryWorker or every required repository
NOTE: the execution of the RepositoryWorkers is executed in a sequential way (single process)
:return: True if the start process is correctly performed, False otherwise
:type: bool
"""
for repository_path, repository_config in self.configuration.items():
print repository_path
repository_worker = RepositoryWorker(repository_config)
repository_worker.run()
return True
@traced(logging.getLogger('Worker'))
def _join(self):
"""
Wait the execution end of all the started RepositoryWorkers
:return: True if the waiting process is correctly performed, False otherwise
:type: bool
"""
# for repository_path, repository_config in self.configuration.items():
# print repository_path
return True
@traced(logging.getLogger('Worker'))
def _pre_start(self):
if self.configuration is None:
return return_codes.ConfigurationError()
| 175 | 33.14 | 116 | 19 | 1,132 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_cb2f83a247e6d908_0ff988e3", "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": 103, "line_end": 103, "column_start": 17, "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/tmphvvervh1/cb2f83a247e6d908.py", "start": {"line": 103, "col": 17, "offset": 3578}, "end": {"line": 103, "col": 83, "offset": 3644}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_cb2f83a247e6d908_14d1b5cf", "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": 104, "line_end": 104, "column_start": 17, "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://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/tmphvvervh1/cb2f83a247e6d908.py", "start": {"line": 104, "col": 17, "offset": 3661}, "end": {"line": 104, "col": 82, "offset": 3726}, "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",
"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"
] | [
103,
104
] | [
103,
104
] | [
17,
17
] | [
83,
82
] | [
"A01:2017 - Injection",
"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()'.",
"Detected subprocess ... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | worker.py | /src/worker.py | macisamuele/git-worker | Apache-2.0 | |
2024-11-18T21:14:38.926325+00:00 | 1,524,495,351,000 | ef13ab8fc1067f2e6952ece75616349d5c0d3b71 | 3 | {
"blob_id": "ef13ab8fc1067f2e6952ece75616349d5c0d3b71",
"branch_name": "refs/heads/master",
"committer_date": 1524507270000,
"content_id": "74c56ec09dd3c2fe699e25095650a1ad9a40d487",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"directory_id": "5389e503feb7ffa0936ca11d543139919b555e1d",
"extension": "py",
"filename": "blockinfoparser.py",
"fork_events_count": 1,
"gha_created_at": 1507799870000,
"gha_event_created_at": 1524507271000,
"gha_language": "JavaScript",
"gha_license_id": "Apache-2.0",
"github_id": 106671291,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9625,
"license": "MIT,Apache-2.0",
"license_type": "permissive",
"path": "/docker/d-streamon-master/d-streamon/streamon/daemon/core/blockinfoparser.py",
"provenance": "stack-edu-0054.json.gz:583436",
"repo_name": "scissor-project/open-scissor",
"revision_date": 1524495351000,
"revision_id": "d54718a1969701798f3e2d57f3db68d829da1cc0",
"snapshot_id": "3a242d6d9035f0ae7f282d4e2c347afed86a15df",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/scissor-project/open-scissor/d54718a1969701798f3e2d57f3db68d829da1cc0/docker/d-streamon-master/d-streamon/streamon/daemon/core/blockinfoparser.py",
"visit_date": "2021-09-13T03:00:20.700121"
} | 2.859375 | stackv2 | import os
import sys
import ConfigParser
import xml.dom.minidom
class BlockInfoParser:
"""\brief Crawls blockmon's source tree for block files and creates a python
file containing a dictionary of block types to core.block.BlockInfo
objects. This script takes the root of the source tree as input and
only crawls the "blocks" directory, looking in the hpp or cpp files
for comments containing XML inside <blockinfo> tags. The dictionary
generated can be imported from written to core.blockinfo.py.block_infos.
"""
def __init__(self):
pass
def generate_blockinfo(self, blocks_path, base_path):
"""\brief Generates block information from source code comments
\param blocks_path (\c string) Blockmon's path to the blocks directory
\param base_path (\c string) Blockmon's base path
"""
# create output file and write beginning of it
info_str = "from block import BlockInfo, GateInfo, VariableInfo, IntegerRange\n\nblock_infos = {"
# process files
for root, subFolders, files in os.walk(blocks_path):
for file in files:
if file.endswith(".hpp") or \
file.endswith(".cpp"):
src_file = os.path.join(root,file)
print "processing " + str(src_file)
f = open(src_file, "r")
lines = f.read().splitlines()
f.close()
in_block_info = False
info = []
for line in lines:
if line.strip().startswith("*"):
if line.find("<blockinfo") != -1:
print "found documentation, processing"
in_block_info = True
if line.find("</blockinfo") != -1:
info.append(line.replace("*", ""))
in_block_info = False
if in_block_info:
info.append(line.replace("*", ""))
if len(info) > 0:
info_str += self.__append_blockinfo(info) + ', '
info_str = info_str[:len(info_str) - 2]
# append end of file and write it out
info_str += "}\n"
output_file = base_path + "/daemon/core/blockinfo.py"
f = open(output_file, "w")
f.write(info_str)
f.close()
print "wrote info to " + output_file
def __append_blockinfo(self, lines):
"""\brief Returns a string containing a block's info
\param lines (\c list[string]) The lines to parse
\return (\c string) The block's info
"""
(trimmed, params_example) = self.__extract_section("paramsexample", lines)
(trimmed, params_schema) = self.__extract_section("paramsschema", trimmed)
xml_str = ""
for line in trimmed:
xml_str += line + "\n"
dom = self.__get_DOM(xml_str, False)
if (dom == None):
print "blockinforparser::append_blockinfo: error while getting DOM object"
return None
blockinfo_xml = dom.getElementsByTagName('blockinfo')[0]
block_type = self.__get_label("type", blockinfo_xml)
string = '"' + block_type + '": BlockInfo("' + block_type + '", '
scheduling_type = self.__get_label("scheduling_type", blockinfo_xml)
string += '"' + scheduling_type + '", '
string += self.__append_gates_info(dom.getElementsByTagName("gate"))
string += ', "' + params_schema + '", "' + params_example + '", '
string += self.__append_variables_info(dom.getElementsByTagName("variable"), block_type)
human_desc = dom.getElementsByTagName('humandesc')[0].firstChild.nodeValue
string += ', "' + human_desc.replace("\n", "").replace('"', "'").strip() + '"'
short_desc = dom.getElementsByTagName('shortdesc')[0].firstChild.nodeValue
string += ', "' + short_desc.replace("\n", "").replace('"', '\"').strip() + '", '
thread_exclusive = self.__get_label("thread_exclusive", blockinfo_xml)
if thread_exclusive.lower() == "true":
thread_exclusive = True
else:
thread_exclusive = False
string += str(thread_exclusive) + ")"
return string
def __append_gates_info(self, gates_xml):
"""\brief Given parsed XML with information about gates, returns a
string with that information
\param gates_xml (\c Node) An XML node with the gate information
\return (\c string) The gate information
"""
string = "["
for gate_xml in gates_xml:
type = self.__get_label("type", gate_xml)
name = self.__get_label("name", gate_xml)
msg_type = self.__get_label("msg_type", gate_xml)
multiplicity_start = self.__get_label("m_start", gate_xml)
multiplicity_end = self.__get_label("m_end", gate_xml)
string += 'GateInfo("' + type + '", ' + \
'"' + name + '", ' + \
'"' + msg_type + '", ' + \
'IntegerRange(' + multiplicity_start + ', ' + \
multiplicity_end + ')), '
string = string[:len(string) - 2] + "]"
return string
def __append_variables_info(self, variables_xml, block_type):
"""\brief Given parsed XML with information about block variables,
returns a string with that information
\param variables_xml (\c Node) An XML node with the variables information
\param block_type (\c string) The block type
\return (\c string) The variables information
"""
string = "["
for variable_xml in variables_xml:
name = self.__get_label("name", variable_xml)
human_desc = self.__get_label("human_desc", variable_xml)
access = self.__get_label("access", variable_xml)
string += 'VariableInfo("' + block_type + '", ' + \
'"' + name + '", ' + \
'"' + human_desc + '", ' + \
'"' + access + '"), '
if len(variables_xml) > 0:
string = string[:len(string) - 2]
return string + "]"
def __extract_section(self, section_name, lines):
"""\brief Extracts a section enclosed in XML < /> angled brackets.
The function returns a tuple whose first object is a list
of strings represented the given lines with the section
extracted; the second object is a string containing the section
\param section_name (\c string) The section's name
\param lines (\c list[string]) The lines to parse
\return (\c tuple(list[string],string)) The extracted section
"""
in_section = False
section = ""
trimmed = []
for line in lines:
if line.find("<" + section_name) != -1:
in_section = True
if line.find("</" + section_name) != -1:
in_section = False
section += line + '\\n'
if in_section:
section += line + '\\n'
elif line.find("</" + section_name) == -1:
trimmed.append(line)
section = section.replace('"', "'")
return (trimmed, section)
def __get_DOM(self, desc, file=True):
"""\brief Turns an xml file into a DOM object. If the file parameter is set to
true, desc should be the path to the xml file to read. Otherwise, desc
is a string containing xml to turn into a DOM object.
\param desc (\c string) Path to an xml file or a string containing xml
\param file (\c bool) Whether desc is a file or an xml string (default is true)
\return (\c xml.dom.minidom.Document) The DOM object
"""
dom = None
try:
if file:
dom = xml.dom.minidom.parse(desc)
else:
dom = xml.dom.minidom.parseString(desc)
except Exception, e:
print "Error getting dom " + str(e)
return None
return dom
def __get_label(self, key, xml_object):
"""\brief Given an xml object and a key, returns the value matching that key
(a string) or None if nothing matches the key.
\param key (\c string) The key to search for
\param xml_object (\c minidom.Node) The xml object to search for the key in
\return (\c string) The value found or None if no value was found for the given key
"""
if xml_object.attributes.has_key(key):
return xml_object.attributes[key].value
else:
return None
if __name__ == "__main__":
if len(sys.argv) < 2:
print "usage: blockinfoparser.py [config]"
os._exit(1)
config = sys.argv[1]
cp = ConfigParser.ConfigParser()
cp.read(config)
blocks_path = cp.get('BLOCKS', 'blocks_path')
base_path = cp.get('DEFAULT', 'bm_basepath')
parser = BlockInfoParser()
parser.generate_blockinfo(blocks_path, base_path)
| 225 | 41.78 | 108 | 24 | 2,018 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_271f5e2e279114ea_4250c275", "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": 4, "line_end": 4, "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/tmphvvervh1/271f5e2e279114ea.py", "start": {"line": 4, "col": 1, "offset": 41}, "end": {"line": 4, "col": 23, "offset": 63}, "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_271f5e2e279114ea_f1b8fd3f", "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": 33, "line_end": 33, "column_start": 25, "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/tmphvvervh1/271f5e2e279114ea.py", "start": {"line": 33, "col": 25, "offset": 1433}, "end": {"line": 33, "col": 44, "offset": 1452}, "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_271f5e2e279114ea_04fe3fad", "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": 13, "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/tmphvvervh1/271f5e2e279114ea.py", "start": {"line": 59, "col": 13, "offset": 2567}, "end": {"line": 59, "col": 35, "offset": 2589}, "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"
] | [
"rules.python.lang.security.use-defused-xml"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
4
] | [
4
] | [
1
] | [
23
] | [
"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"
] | blockinfoparser.py | /docker/d-streamon-master/d-streamon/streamon/daemon/core/blockinfoparser.py | scissor-project/open-scissor | MIT,Apache-2.0 | |
2024-11-18T21:14:41.298456+00:00 | 1,693,082,372,000 | 28ff5061a88cd11f764a7f83370f076362fb23f8 | 3 | {
"blob_id": "28ff5061a88cd11f764a7f83370f076362fb23f8",
"branch_name": "refs/heads/main",
"committer_date": 1693083719000,
"content_id": "11b9b6e1b787d50671d211d24b801cd50e769434",
"detected_licenses": [
"MIT"
],
"directory_id": "6950d17118b97259e181cfc1e6ba3becf6fab753",
"extension": "py",
"filename": "pandoc.py",
"fork_events_count": 451,
"gha_created_at": 1529040336000,
"gha_event_created_at": 1694529666000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 137444487,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4078,
"license": "MIT",
"license_type": "permissive",
"path": "/jupytext/pandoc.py",
"provenance": "stack-edu-0054.json.gz:583467",
"repo_name": "mwouts/jupytext",
"revision_date": 1693082372000,
"revision_id": "28cc7de53d403838caf24c3470df95e94a82d132",
"snapshot_id": "8f38d974320e17d9bfdc02a91707b5d7cba999cc",
"src_encoding": "UTF-8",
"star_events_count": 6292,
"url": "https://raw.githubusercontent.com/mwouts/jupytext/28cc7de53d403838caf24c3470df95e94a82d132/jupytext/pandoc.py",
"visit_date": "2023-09-04T04:20:37.143750"
} | 3.140625 | stackv2 | """Jupyter notebook to Markdown and back, using Pandoc"""
import os
import subprocess
import tempfile
from functools import partial
# Copy nbformat reads and writes to avoid them being patched in the contents manager!!
from nbformat import reads as ipynb_reads
from nbformat import writes as ipynb_writes
from .parse_version import parse_version as parse
class PandocError(OSError):
"""An error related to Pandoc"""
def pandoc(args, filein=None, fileout=None):
"""Execute pandoc with the given arguments"""
cmd = ["pandoc"]
if filein:
cmd.append(filein)
if fileout:
cmd.append("-o")
cmd.append(fileout)
cmd.extend(args.split())
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
out, err = proc.communicate()
if proc.returncode:
raise PandocError(
f"pandoc exited with return code {proc.returncode}\n{str(err)}"
)
return out.decode("utf-8")
def is_pandoc_available(min_version="2.7.2", max_version=None):
"""Is Pandoc>=2.7.2 available?"""
try:
raise_if_pandoc_is_not_available(
min_version=min_version, max_version=max_version
)
return True
except PandocError:
return False
def raise_if_pandoc_is_not_available(min_version="2.7.2", max_version=None):
"""Raise with an informative error message if pandoc is not available"""
version = pandoc_version()
if version == "N/A":
raise PandocError(
f"The Pandoc Markdown format requires 'pandoc>={min_version}', "
"but pandoc was not found"
)
parse_version = partial(parse, custom_error=PandocError)
if parse_version(version) < parse_version(min_version):
raise PandocError(
f"The Pandoc Markdown format requires 'pandoc>={min_version}', "
f"but pandoc version {version} was found"
)
if max_version and parse_version(version) > parse_version(max_version):
raise PandocError(
f"The Pandoc Markdown format requires 'pandoc<={max_version}', "
f"but pandoc version {version} was found"
)
return version
def pandoc_version():
"""Pandoc's version number"""
try:
return pandoc("--version").splitlines()[0].split()[1]
except OSError:
return "N/A"
def md_to_notebook(text):
"""Convert a Markdown text to a Jupyter notebook, using Pandoc"""
raise_if_pandoc_is_not_available()
tmp_file = tempfile.NamedTemporaryFile(delete=False)
tmp_file.write(text.encode("utf-8"))
tmp_file.close()
parse_version = partial(parse, custom_error=PandocError)
if parse_version(pandoc_version()) < parse_version("2.11.2"):
pandoc_args = "--from markdown --to ipynb -s --atx-headers --wrap=preserve --preserve-tabs"
else:
pandoc_args = "--from markdown --to ipynb -s --markdown-headings=atx --wrap=preserve --preserve-tabs"
pandoc(
pandoc_args,
tmp_file.name,
tmp_file.name,
)
with open(tmp_file.name, encoding="utf-8") as opened_file:
notebook = ipynb_reads(opened_file.read(), as_version=4)
os.unlink(tmp_file.name)
return notebook
def notebook_to_md(notebook):
"""Convert a notebook to its Markdown representation, using Pandoc"""
raise_if_pandoc_is_not_available()
tmp_file = tempfile.NamedTemporaryFile(delete=False)
tmp_file.write(ipynb_writes(notebook).encode("utf-8"))
tmp_file.close()
parse_version = partial(parse, custom_error=PandocError)
if parse_version(pandoc_version()) < parse_version("2.11.2"):
pandoc_args = "--from ipynb --to markdown -s --atx-headers --wrap=preserve --preserve-tabs"
else:
pandoc_args = "--from ipynb --to markdown -s --markdown-headings=atx --wrap=preserve --preserve-tabs"
pandoc(
pandoc_args,
tmp_file.name,
tmp_file.name,
)
with open(tmp_file.name, encoding="utf-8") as opened_file:
text = opened_file.read()
os.unlink(tmp_file.name)
return "\n".join(text.splitlines())
| 132 | 29.89 | 109 | 16 | 990 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_39ee743e4cf43e05_3f2692d1", "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": 32, "line_end": 32, "column_start": 12, "column_end": 57, "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/tmphvvervh1/39ee743e4cf43e05.py", "start": {"line": 32, "col": 12, "offset": 698}, "end": {"line": 32, "col": 57, "offset": 743}, "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"
] | [
32
] | [
32
] | [
12
] | [
57
] | [
"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"
] | pandoc.py | /jupytext/pandoc.py | mwouts/jupytext | MIT | |
2024-11-18T21:14:42.847341+00:00 | 1,566,304,628,000 | 907b27af438bd2c78db123bb6762db29cd93e7cb | 2 | {
"blob_id": "907b27af438bd2c78db123bb6762db29cd93e7cb",
"branch_name": "refs/heads/master",
"committer_date": 1566304628000,
"content_id": "30a3137c315bc893ce1daef1e3749b151156aa48",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "7385124cee58d817f9094facd4d338a1a178a98b",
"extension": "py",
"filename": "json2voc.py",
"fork_events_count": 0,
"gha_created_at": 1562812954000,
"gha_event_created_at": 1565958156000,
"gha_language": "Python",
"gha_license_id": "Apache-2.0",
"github_id": 196307547,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2457,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/prepocess/json2voc.py",
"provenance": "stack-edu-0054.json.gz:583484",
"repo_name": "fregulationn/mmdetection",
"revision_date": 1566304628000,
"revision_id": "a2bbeed4ca251aea7eb34a1952f6ba82cd43b9b8",
"snapshot_id": "a34d639004d4373ddc985c303e8de37feb6c90b9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fregulationn/mmdetection/a2bbeed4ca251aea7eb34a1952f6ba82cd43b9b8/prepocess/json2voc.py",
"visit_date": "2020-06-18T12:47:12.123386"
} | 2.328125 | stackv2 | import pdb
import os
import json
import argparse
from lxml.etree import Element, SubElement, tostring, ElementTree
from xml.dom.minidom import parseString
import pickle
json_path = "/home/junjie/Code/tianchi/guangdong/guangdong1_round1_train1_20190818/Annotations/anno_train.json"
output_dir = "/home/junjie/Code/tianchi/guangdong/Label/Annotations/"
name_dict_path = "/home/junjie/Code/tianchi/guangdong/Label/ImageSets/Main/name.pickle"
height = 1000
width = 2446
with open(name_dict_path, 'rb') as handle:
name_dict = pickle.load(handle)
print(name_dict)
with open(json_path, 'r') as load_f:
load_dict = json.load(load_f)
for i,load_ann in enumerate(load_dict):
# build the xml structure
file_name = load_ann["name"];
node_root = Element('annotation')
node_floder = SubElement(node_root, 'floder')
node_floder.text = 'Cloth'
node_filename = SubElement(node_root, 'filename')
node_filename.text = file_name
node_size = SubElement(node_root, 'size')
node_width = SubElement(node_size, 'width')
node_width.text = str(width)
node_height = SubElement(node_size, 'height')
node_height.text = str(height)
node_depth = SubElement(node_size, 'depth')
node_depth.text = '3'
#every image only has a bbox
node_object = SubElement(node_root, 'object')
node_name = SubElement(node_object, 'name')
node_name.text = name_dict[load_ann["defect_name"]]
node_pose = SubElement(node_object, 'pose')
node_pose.text = 'Unspecified'
node_truncated = SubElement(node_object, 'truncated')
node_truncated.text = str(0)
node_difficult = SubElement(node_object, 'difficult')
node_difficult.text = str(0)
node_bndbox = SubElement(node_object, 'bndbox')
node_xmin = SubElement(node_bndbox, 'xmin')
node_xmin.text = str(int(load_ann["bbox"][0]))
node_ymin = SubElement(node_bndbox, 'ymin')
node_ymin.text = str(int(load_ann["bbox"][1]))
node_xmax = SubElement(node_bndbox, 'xmax')
node_xmax.text = str(int(load_ann["bbox"][2]))
node_ymax = SubElement(node_bndbox, 'ymax')
node_ymax.text = str(int(load_ann["bbox"][3]))
xml_dir=output_dir
if not os.path.exists(xml_dir):
os.makedirs(xml_dir)
xml_file = os.path.join(xml_dir, file_name[:-4]+'.xml')
xml = tostring(node_root, pretty_print=True)
dom = parseString(xml)
ElementTree(node_root).write(xml_file, pretty_print=True)
| 69 | 34.61 | 111 | 13 | 675 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.python-debugger-found_dc26f9e6beb1ed9d_54402c59", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.python-debugger-found", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Importing the python debugger; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 1, "line_end": 1, "column_start": 1, "column_end": 11, "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.best-practice.python-debugger-found", "path": "/tmp/tmphvvervh1/dc26f9e6beb1ed9d.py", "start": {"line": 1, "col": 1, "offset": 0}, "end": {"line": 1, "col": 11, "offset": 10}, "extra": {"message": "Importing the python debugger; did you mean to leave this in?", "metadata": {"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.security.use-defused-xml_dc26f9e6beb1ed9d_4180a589", "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": 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/tmphvvervh1/dc26f9e6beb1ed9d.py", "start": {"line": 6, "col": 1, "offset": 115}, "end": {"line": 6, "col": 40, "offset": 154}, "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.deserialization.avoid-pickle_dc26f9e6beb1ed9d_ad1a84b0", "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": 18, "line_end": 18, "column_start": 17, "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/tmphvvervh1/dc26f9e6beb1ed9d.py", "start": {"line": 18, "col": 17, "offset": 529}, "end": {"line": 18, "col": 36, "offset": 548}, "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_dc26f9e6beb1ed9d_cf4dd75e", "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": 22, "line_end": 22, "column_start": 6, "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/tmphvvervh1/dc26f9e6beb1ed9d.py", "start": {"line": 22, "col": 6, "offset": 573}, "end": {"line": 22, "col": 26, "offset": 593}, "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-611",
"CWE-502"
] | [
"rules.python.lang.security.use-defused-xml",
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"HIGH",
"MEDIUM"
] | [
6,
18
] | [
6,
18
] | [
1,
17
] | [
40,
36
] | [
"A04:2017 - XML External Entities (XXE)",
"A08:2017 - Insecure Deserialization"
] | [
"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.",
"Avoid using `pickle`, which is known to lead to code execu... | [
7.5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | json2voc.py | /prepocess/json2voc.py | fregulationn/mmdetection | Apache-2.0 | |
2024-11-18T20:10:31.599780+00:00 | 1,551,727,492,000 | a8d0945799acfe6fb706ff63b254c3feafd96fd2 | 3 | {
"blob_id": "a8d0945799acfe6fb706ff63b254c3feafd96fd2",
"branch_name": "refs/heads/master",
"committer_date": 1551727492000,
"content_id": "7f0a44b5941551750c1220d92f38dd283197925c",
"detected_licenses": [
"MIT"
],
"directory_id": "23fce9135a95b9fe058e7b9b1d9337191b066a37",
"extension": "py",
"filename": "files_parser.py",
"fork_events_count": 0,
"gha_created_at": 1549376091000,
"gha_event_created_at": 1549376092000,
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 169252191,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6850,
"license": "MIT",
"license_type": "permissive",
"path": "/paf_tools/populate/files_parser.py",
"provenance": "stack-edu-0054.json.gz:583527",
"repo_name": "osgirl/paf-tools",
"revision_date": 1551727492000,
"revision_id": "9c55108266b2f50f934edfdfab0f7573b5bba90f",
"snapshot_id": "3c9da66ece73799ba641429d1e07e0f4a09244a6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/osgirl/paf-tools/9c55108266b2f50f934edfdfab0f7573b5bba90f/paf_tools/populate/files_parser.py",
"visit_date": "2020-04-21T02:22:07.271768"
} | 3.328125 | stackv2 | """Parser module.
Contains tools for parsing the various PAF Mainfile component files.
The Address File is the main source tying together the other components,
containing each address within the UK through reference to the other
component files.
Each line in the Address File is 88 characters long, and is constructed
as follows:-
FIELD NAME LEVEL DATA TYPE SIZE
--------------------------------------------------------
Postcode 1
Outward Code 2 Alphanumeric 4
Inward Code 2 Alphanumeric 3
Address Key 1 Numeric 8
Locality Key 1 Numeric 6
Thoroughfare Key 1 Numeric 8 *
Thoroughfare Descriptor Key 1 Numeric 4 *
Dependent Thoroughfare Key 1 Numeric 8 *
Dep. Thoroughfare Desc. Key 1 Numeric 4 *
Building Number 1 Numeric 4 *
Building Name Key 1 Numeric 8 *
Sub Building Name Key 1 Numeric 8 *
Number of Households 1 Numeric 4 ¹
Organisation Key 1 Numeric 8 ²
Postcode Type 1 Alphanumeric 1 ²
Concatenation Indicator 1 Alphanumeric 1 ³
Delivery Point Suffix 1 Alphanumeric 2
Small User Org. Indicator 1 Alphanumeric 1 °
PO Box Number 1 Alphanumeric 6
* - If 0, there is no entry of this type present.
¹ - If 0 or 1, indicates one household at address. If greater than 1, this
indicates the number of households present.
² - If 0, there is no Organisation present. Refers to a record in Org. file
for Small & Large User. Refer to Postcode type to determine type of
user, whether S or L.
³ - Either 'Y' or space. If 'Y', indicates that Building Number and Sub
Building Name should appear concatenated on same address line.
° - Either 'Y' or space. If 'Y', indicates that a Small User Organisation is
present at the address.
--------------------------------------------------------
The other component files consist of entries in the format:-
<KEY><VALUE>
with no whitespace between the key and value.
"""
import os
from paf_tools.structure import *
class PAFReader(object):
"""This class defines the PAFReader class.
The class is used to read data from the postcode address file component
files to allow this data to be used for whatever purpose is required.
Details of the structure of the PAF component files is found in
structure.py, and each filetype is defined by two separate variables:
* <filetype>_FILENAME, which defines the filename(s) containing the
PAF data; and
* <filetype>_COMPONENTS, which defines the structure of each line
of the relevant file in the form of a list of integers, each
representing the length of one field of data.
"""
def __init__(self, path, filetype):
"""Initialise PAFReader instance."""
self.path = path
self.filetype = filetype
self.filedata = self.open_component_file()
def __iter__(self):
self.filedata = self.open_component_file()
return self
def __next__(self):
"""Define next method.
Reads the specified PAF component file line by line and passes
each line into the line parser.
Yields a tuple containing split address information.
"""
return next(self.filedata)
def open_component_file(self):
"""Open the PAF component file for reading."""
filelist = [os.path.join(self.path, x)
for x in self._filetype_data("filename")]
for entry in filelist:
with open(entry, errors='replace') as paf_file:
for line in paf_file:
#Skip headers and footers.
parsed_line = self._parse_line(line)
if (parsed_line[0] and
not (parsed_line[0] == "0" * len(parsed_line[0]) or
parsed_line[0] == "9" * len(parsed_line[0]))):
yield parsed_line
def _parse_line(self, line):
"""Parse line of Address File.
Splits the input address_line into separate components, and returns a
tuple containing these components.
"""
#Calculate indices at which splits occur.
splits_indices = [0]
for x in self._filetype_data("components"):
splits_indices.append(x + splits_indices[-1])
split_line = (line[splits_indices[x]:splits_indices[x+1]].strip()
for x in range(len(splits_indices)-1))
return tuple(split_line)
@property
def filetype(self):
"""Return filetype value."""
return self.__filetype
@filetype.setter
def filetype(self, filetype):
"""Set the filetype for this PAFReader.
Validate parameters against available filetypes. Used to ensure
that filetype parameter contents are valid.
Keyword arguments:
filetype - the input filetype value to validate against
"""
filetype = filetype.upper()
if filetype not in VALID_FILETYPES:
raise ValueError("Error! Invalid filetype specified. (Must be one "
"of {}.)".format(', '.join(VALID_FILETYPES)))
self.__filetype = filetype
def _validate_datatype(self, datatype):
"""Validate parameters against available datatypes.
Used to ensure that datatype parameters passed to parsing functions
are valid. Returns True if datatype is valid, else returns False.
Keyword arguments:
datatype - the input datatype value to validate against
"""
return datatype in VALID_DATATYPES
def _filetype_data(self, datatype):
"""Obtain specified data for a given filetype.
Each filetype is defined by a filename, and the (ordered) length of
the components of each line. This function returns the requested data
for the specified filetype.
Keyword arguments:
filetype - the type of file to obtain data for
datatype - the type of data required (filename or components)
"""
filetype, data = self.filetype.upper(), datatype.upper()
#Check for validity of filetype and data input.
if not self._validate_datatype(data):
raise ValueError("Invalid datatype specified.")
output_data = globals()["{}_{}".format(filetype, data)]
if isinstance(output_data, str):
output_data = [output_data]
return output_data
| 178 | 37.43 | 79 | 23 | 1,437 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_90368eaef999c817_391eb9fa", "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": 99, "line_end": 99, "column_start": 18, "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/tmphvvervh1/90368eaef999c817.py", "start": {"line": 99, "col": 18, "offset": 3834}, "end": {"line": 99, "col": 47, "offset": 3863}, "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.dangerous-globals-use_90368eaef999c817_4ae9f8b4", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.dangerous-globals-use", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 174, "line_end": 174, "column_start": 23, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": "CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.dangerous-globals-use", "path": "/tmp/tmphvvervh1/90368eaef999c817.py", "start": {"line": 174, "col": 23, "offset": 6699}, "end": {"line": 174, "col": 64, "offset": 6740}, "extra": {"message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "metadata": {"cwe": ["CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186"], "category": "security", "technology": ["python"], "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-96"
] | [
"rules.python.lang.security.dangerous-globals-use"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
174
] | [
174
] | [
23
] | [
64
] | [
"A03:2021 - Injection"
] | [
"Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | files_parser.py | /paf_tools/populate/files_parser.py | osgirl/paf-tools | MIT | |
2024-11-18T20:10:34.851509+00:00 | 1,693,456,282,000 | bf475b44e3b948a36a8c92524a694c30ce16868e | 2 | {
"blob_id": "bf475b44e3b948a36a8c92524a694c30ce16868e",
"branch_name": "refs/heads/main",
"committer_date": 1693456282000,
"content_id": "1ad53081217420ef60add79a86f2d587449d321e",
"detected_licenses": [
"MIT"
],
"directory_id": "977f7a7386899a5d0152b29b57ec26682b430437",
"extension": "py",
"filename": "data_manager_gemini_download.py",
"fork_events_count": 508,
"gha_created_at": 1410607129000,
"gha_event_created_at": 1694634074000,
"gha_language": "HTML",
"gha_license_id": "MIT",
"github_id": 23992530,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3782,
"license": "MIT",
"license_type": "permissive",
"path": "/data_managers/data_manager_gemini_database_downloader/data_manager/data_manager_gemini_download.py",
"provenance": "stack-edu-0054.json.gz:583563",
"repo_name": "galaxyproject/tools-iuc",
"revision_date": 1693456282000,
"revision_id": "96f8a533278b4b6394aebd7a8f537513b0d29b1a",
"snapshot_id": "0b87e21e1cb075ca6dc6b12622bc4e538a7c6507",
"src_encoding": "UTF-8",
"star_events_count": 164,
"url": "https://raw.githubusercontent.com/galaxyproject/tools-iuc/96f8a533278b4b6394aebd7a8f537513b0d29b1a/data_managers/data_manager_gemini_database_downloader/data_manager/data_manager_gemini_download.py",
"visit_date": "2023-08-31T16:14:34.563541"
} | 2.484375 | stackv2 | #!/usr/bin/env python2
# IMPORTANT: This will run using Python 2 still!
import datetime
import json
import os
import subprocess
import sys
import yaml
def write_gemini_config(config, config_file):
with open(config_file, 'w') as fo:
yaml.dump(config, fo, allow_unicode=False, default_flow_style=False)
def load_gemini_config(config_file):
with open(config_file) as fi:
return yaml.load(fi)
def main():
today = datetime.date.today()
with open(sys.argv[1]) as fh:
params = json.load(fh)
target_directory = params['output_data'][0]['extra_files_path']
os.mkdir(target_directory)
# Prepare the metadata for the new data table record
# The name of the database should reflect whether it was built with or
# without the optional GERP-bp data, the CADD scores, or both.
# This builds up the correpsonding part of the name:
anno_extras = []
if params['param_dict']['gerp_bp']:
anno_extras.append('GERP')
if params['param_dict']['cadd']:
anno_extras.append('CADD')
if anno_extras:
anno_desc = ' w/ ' + ' & '.join(anno_extras)
else:
anno_desc = ''
data_manager_dict = {
'data_tables': {
'gemini_versioned_databases': [
{
'value': today.isoformat(),
'dbkey': 'hg19',
'version': params['param_dict']['gemini_db_version'],
'name':
'GEMINI annotations%s (%s snapshot)' % (
anno_desc, today.isoformat()
),
'path': './%s' % today.isoformat()
}
]
}
}
# Save the data table metadata to the json results file
with open(sys.argv[1], 'w') as fh:
json.dump(data_manager_dict, fh, sort_keys=True)
# Generate a minimal configuration file for GEMINI update
# to instruct the tool to download the annotation data into a
# subfolder of the target directory.
config_file = os.path.join(target_directory, 'gemini-config.yaml')
anno_dir = os.path.join(target_directory, 'gemini/data')
gemini_bootstrap_config = {'annotation_dir': anno_dir}
write_gemini_config(gemini_bootstrap_config, config_file)
# Verify that we can read the config_file just created as we need to do so
# after the data download has finished and it is very annoying to have this
# fail after dozens of Gbs of data have been downloaded
config = load_gemini_config(config_file)
# Now gemini update can be called to download the data.
# The GEMINI_CONFIG environment variable lets the tool discover
# the configuration file we prepared for it.
# Note that the tool will rewrite the file turning it into a
# complete gemini configuration file.
gemini_env = os.environ.copy()
gemini_env['GEMINI_CONFIG'] = target_directory
cmd = ['gemini', 'update', '--dataonly']
if params['param_dict']['gerp_bp']:
cmd += ['--extra', 'gerp_bp']
if params['param_dict']['cadd']:
cmd += ['--extra', 'cadd_score']
if not params['param_dict']['test_data_manager']:
# This is not a test => Going to embark on a massive download now
subprocess.check_call(cmd, env=gemini_env)
# GEMINI tool wrappers that need access to the annotation files
# are supposed to symlink them into a gemini/data subfolder of
# the job working directory. To have GEMINI discover them there,
# we need to set this location as the 'annotation_dir' in the
# configuration file.
config = load_gemini_config(config_file)
config['annotation_dir'] = 'gemini/data'
write_gemini_config(config, config_file)
if __name__ == "__main__":
main()
| 108 | 34.02 | 79 | 17 | 880 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_6096c2e357187d93_2b00c483", "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": 15, "line_end": 15, "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/tmphvvervh1/6096c2e357187d93.py", "start": {"line": 15, "col": 10, "offset": 211}, "end": {"line": 15, "col": 32, "offset": 233}, "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_6096c2e357187d93_9d6d9af8", "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": 20, "line_end": 20, "column_start": 10, "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://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/tmphvvervh1/6096c2e357187d93.py", "start": {"line": 20, "col": 10, "offset": 366}, "end": {"line": 20, "col": 27, "offset": 383}, "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_6096c2e357187d93_38d803bf", "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": 26, "line_end": 26, "column_start": 10, "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://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/tmphvvervh1/6096c2e357187d93.py", "start": {"line": 26, "col": 10, "offset": 477}, "end": {"line": 26, "col": 27, "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.best-practice.unspecified-open-encoding_6096c2e357187d93_6ca964c3", "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": 64, "line_end": 64, "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/tmphvvervh1/6096c2e357187d93.py", "start": {"line": 64, "col": 10, "offset": 1783}, "end": {"line": 64, "col": 32, "offset": 1805}, "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_6096c2e357187d93_e67a8c49", "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": 95, "line_end": 95, "column_start": 9, "column_end": 51, "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/tmphvvervh1/6096c2e357187d93.py", "start": {"line": 95, "col": 9, "offset": 3267}, "end": {"line": 95, "col": 51, "offset": 3309}, "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"}}}] | 5 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
95
] | [
95
] | [
9
] | [
51
] | [
"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"
] | data_manager_gemini_download.py | /data_managers/data_manager_gemini_database_downloader/data_manager/data_manager_gemini_download.py | galaxyproject/tools-iuc | MIT | |
2024-11-18T20:10:38.604125+00:00 | 1,431,294,287,000 | 881dbe4ca14009f7904d4f2bdc2402a83617596e | 3 | {
"blob_id": "881dbe4ca14009f7904d4f2bdc2402a83617596e",
"branch_name": "refs/heads/master",
"committer_date": 1431294287000,
"content_id": "9dbc3fff45945d4ad63e8f7db36fa0f4893a7ba2",
"detected_licenses": [
"MIT"
],
"directory_id": "fce812e4b5c86e808ae685e6837c023f686de4e4",
"extension": "py",
"filename": "presentors.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 33846807,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4960,
"license": "MIT",
"license_type": "permissive",
"path": "/restmore/presentors.py",
"provenance": "stack-edu-0054.json.gz:583595",
"repo_name": "zbyte64/python-restmore",
"revision_date": 1431294287000,
"revision_id": "86916009806b9390260b8445f5536fa6aa345862",
"snapshot_id": "76d24e3272a63c09a8c75976032926d6091b6e90",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/zbyte64/python-restmore/86916009806b9390260b8445f5536fa6aa345862/restmore/presentors.py",
"visit_date": "2016-09-06T13:56:39.441381"
} | 2.5625 | stackv2 | '''
Request (set serializer in `handle`) -> Resource -> Data
-> Presentor (set response type in `build_response`, inject hypermedia in `serialize`)
-> Normalizer (globalized preparer) -> Serializer
'''
import mimeparse
from collections import namedtuple
from django.http import HttpResponse
from restless.serializers import JSONSerializer
from .normalizer import NormalizedPreparer
class HybridSerializer(object):
def __init__(self, serializer, deserializer):
self.serializer = serializer
self.deserializer = deserializer
def serialize(self, data):
return self.serializer.serialize(data)
def deserialize(self, data):
return self.deserializer.deserialize(data)
class Presentor(object):
'''
A passthrough presentor
'''
def __init__(self, content_type):
self.content_type = content_type
def inject(self, method, endpoint, data):
'''
Inject hypermedia data
'''
return data
def get_response_type(self):
return self.content_type
class StatusException(Exception):
def __init__(self, message, status=400):
super(StatusException, self).__init__(message)
self.status = status
class PresentorResourceMixin(object):
preparer = NormalizedPreparer()
def handle(self, endpoint, *args, **kwargs):
#why the extra layer of indirection? so we can dynamically switch serializers and hypermedia
try:
self.serializer = self.make_serializer()
except StatusException as error:
#TODO use handle_error instead
return HttpResponse(error.args[0], status=error.status)
try:
self.presentor = self.get_presentor()
except KeyError:
#406 = Bad Accept, 415 = Bad Content Type
return HttpResponse('Invalid Accepts', status=406)
return super(PresentorResourceMixin, self).handle(endpoint, *args, **kwargs)
def build_status_response(self, data, status=400):
'''
An event occurred preventing the request from being completed
'''
raise StatusException(data, status)
def make_serializer(self):
'''
Constructs the serializers to be used based on HTTP Headers
settable with django setting: `RESTMORE_SERIALIZERS`
'''
#print("make_serializer:", self.request.META)
from .settings import SERIALIZERS
media_types = SERIALIZERS.keys()
rt = self.request.META.get('CONTENT_TYPE') #request type
at = self.request.META.get('HTTP_ACCEPT', 'application/json') #accept type
#print("make_serializer:", rt, at)
rt = rt or at
#intelligent mimetype matching
rt = mimeparse.best_match(media_types, rt) or rt
at = mimeparse.best_match(media_types, at) or at
try:
rt_serializer = SERIALIZERS[rt]
except KeyError:
raise StatusException('Invalid Request Type: '+rt, 415)
try:
at_serializer = SERIALIZERS[at]
except KeyError:
raise StatusException('Invalid Accept Type: '+at, 406)
at_serializer = at_serializer()
rt_serializer = rt_serializer()
#hack so that serializers can read headers, like boundary
at_serializer.request = self.request
rt_serializer.request = self.request
return HybridSerializer(serializer=at_serializer, deserializer=rt_serializer)
def get_presentor(self):
'''
Constructs the presentor to be used based on HTTP Headers
settable with django setting: `RESTMORE_PRESENTORS`
'''
from .settings import PRESENTORS
ct = self.request.META.get('HTTP_ACCEPT') or self.request.META.get('CONTENT_TYPE') or 'application/json'
ct = mimeparse.best_match(PRESENTORS.keys(), ct) or 'application/json'
return PRESENTORS[ct](ct)
def build_response(self, data, status=200):
assert isinstance(data, (str, bytes)), "build_response only accepts serialized data"
resp = HttpResponse(data, content_type=self.presentor.get_response_type())
resp.status_code = status
return resp
def serialize(self, method, endpoint, data):
hyperdata = self.presentor.inject(method, endpoint, data)
return super(PresentorResourceMixin, self).serialize(method, endpoint, hyperdata)
def prepare(self, data):
"""
Given an item (``object`` or ``dict``), this will potentially go through
& reshape the output based on ``self.prepare_with`` object.
:param data: An item to prepare for serialization
:type data: object or dict
:returns: A potentially reshaped dict
:rtype: dict
"""
#pass along identity & authorization to the preparer so that fields may be properly masked
return self.preparer.prepare(data, identity=self.identity, authorization=self.authorization)
| 138 | 34.94 | 112 | 14 | 1,050 | python | [{"finding_id": "semgrep_rules.python.django.security.audit.xss.direct-use-of-httpresponse_4e5fbe31a088d469_43d15dee", "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": 58, "line_end": 58, "column_start": 20, "column_end": 68, "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/tmphvvervh1/4e5fbe31a088d469.py", "start": {"line": 58, "col": 20, "offset": 1617}, "end": {"line": 58, "col": 68, "offset": 1665}, "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"
] | [
58
] | [
58
] | [
20
] | [
68
] | [
"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"
] | presentors.py | /restmore/presentors.py | zbyte64/python-restmore | MIT | |
2024-11-18T20:10:39.578502+00:00 | 1,530,622,070,000 | 4c09b5880849b3be171bd582b88fb30c4b5ab918 | 3 | {
"blob_id": "4c09b5880849b3be171bd582b88fb30c4b5ab918",
"branch_name": "refs/heads/master",
"committer_date": 1530622070000,
"content_id": "e695b0ef591160a2e972b5af447f57bc197610a6",
"detected_licenses": [
"MIT"
],
"directory_id": "99bf7e47e805914f88159437cf03eb1a9d0ccb69",
"extension": "py",
"filename": "voc_label_tiao.py",
"fork_events_count": 0,
"gha_created_at": 1530320353000,
"gha_event_created_at": 1530320354000,
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 139208489,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2068,
"license": "MIT",
"license_type": "permissive",
"path": "/tiao_tools/voc_label_tiao.py",
"provenance": "stack-edu-0054.json.gz:583610",
"repo_name": "cooli7wa/keras-yolo3",
"revision_date": 1530622070000,
"revision_id": "50945aec0bcffc7922a89650d194dab55f4a9799",
"snapshot_id": "f48ef1727a4daf8ee6276296580b1534078d3bb1",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/cooli7wa/keras-yolo3/50945aec0bcffc7922a89650d194dab55f4a9799/tiao_tools/voc_label_tiao.py",
"visit_date": "2020-03-21T23:49:49.134050"
} | 2.609375 | stackv2 | import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
import sys
import re
import random
classes = ["box_normal", "box_score", "chessman"]
prop = 1.0
def convert(size, box):
dw = 1./size[0]
dh = 1./size[1]
x = (box[0] + box[1])/2.0
y = (box[2] + box[3])/2.0
w = box[1] - box[0]
h = box[3] - box[2]
x = x*dw
w = w*dw
y = y*dh
h = h*dh
return (x,y,w,h)
def convert_annotation(folder, image_id):
in_file = open('%s/%s.xml'%(folder, image_id))
out_file = open('%s/%s.txt'%(folder, image_id), 'w')
tree = ET.parse(in_file)
root = tree.getroot()
size = root.find('size')
w = int(size.find('width').text)
h = int(size.find('height').text)
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 = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), float(xmlbox.find('ymax').text))
bb = convert((w,h), b)
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
folder = os.path.abspath(sys.argv[1])
folder_list = os.listdir(folder)
image_ids = []
for name in folder_list:
if re.match(r'.*\.jpg', name):
image_ids.append(name.rsplit('.')[0])
list_file = open('%s/total.txt'%(folder), 'w')
for image_id in image_ids:
list_file.write('%s/%s.jpg\n'%(folder, image_id))
convert_annotation(folder, image_id)
list_file.close()
with open('%s/total.txt'%(folder), 'r') as f:
lines = f.readlines()
random.shuffle(lines)
train_lines = lines[:int(round(len(lines)*prop))]
test_lines = lines[int(round(len(lines)*prop)):]
with open('%s/train.txt'%(folder), 'w') as f:
for line in train_lines:
f.write(line)
with open('%s/test.txt'%(folder), 'w') as f:
for line in test_lines:
f.write(line)
| 77 | 25.86 | 144 | 16 | 618 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_b702e4be6d64424f_78966bcb", "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": 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/tmphvvervh1/b702e4be6d64424f.py", "start": {"line": 1, "col": 1, "offset": 0}, "end": {"line": 1, "col": 35, "offset": 34}, "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_b702e4be6d64424f_9863646a", "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": 27, "line_end": 27, "column_start": 5, "column_end": 51, "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/tmphvvervh1/b702e4be6d64424f.py", "start": {"line": 27, "col": 5, "offset": 505}, "end": {"line": 27, "col": 51, "offset": 551}, "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_b702e4be6d64424f_66bc7454", "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": 27, "line_end": 27, "column_start": 15, "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/tmphvvervh1/b702e4be6d64424f.py", "start": {"line": 27, "col": 15, "offset": 515}, "end": {"line": 27, "col": 51, "offset": 551}, "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_b702e4be6d64424f_1cdcd81d", "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": 28, "line_end": 28, "column_start": 5, "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/tmphvvervh1/b702e4be6d64424f.py", "start": {"line": 28, "col": 5, "offset": 556}, "end": {"line": 28, "col": 57, "offset": 608}, "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_b702e4be6d64424f_7b11c16f", "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": 28, "line_end": 28, "column_start": 16, "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/tmphvvervh1/b702e4be6d64424f.py", "start": {"line": 28, "col": 16, "offset": 567}, "end": {"line": 28, "col": 57, "offset": 608}, "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_b702e4be6d64424f_3683adec", "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": 29, "line_end": 29, "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/tmphvvervh1/b702e4be6d64424f.py", "start": {"line": 29, "col": 12, "offset": 620}, "end": {"line": 29, "col": 29, "offset": 637}, "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_b702e4be6d64424f_ce5799eb", "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": 54, "line_end": 54, "column_start": 13, "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/tmphvvervh1/b702e4be6d64424f.py", "start": {"line": 54, "col": 13, "offset": 1500}, "end": {"line": 54, "col": 47, "offset": 1534}, "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_b702e4be6d64424f_2cbf7d63", "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": 6, "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/tmphvvervh1/b702e4be6d64424f.py", "start": {"line": 60, "col": 6, "offset": 1681}, "end": {"line": 60, "col": 40, "offset": 1715}, "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_b702e4be6d64424f_0c01167e", "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": 67, "line_end": 67, "column_start": 6, "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/tmphvvervh1/b702e4be6d64424f.py", "start": {"line": 67, "col": 6, "offset": 1876}, "end": {"line": 67, "col": 40, "offset": 1910}, "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_b702e4be6d64424f_77657686", "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": 6, "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/tmphvvervh1/b702e4be6d64424f.py", "start": {"line": 71, "col": 6, "offset": 1974}, "end": {"line": 71, "col": 39, "offset": 2007}, "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"}}}] | 10 | 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"
] | [
1,
29
] | [
1,
29
] | [
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_label_tiao.py | /tiao_tools/voc_label_tiao.py | cooli7wa/keras-yolo3 | MIT | |
2024-11-18T20:10:46.913833+00:00 | 1,640,629,747,000 | 24677f22fa90565234a827010f7be752a9a647c5 | 2 | {
"blob_id": "24677f22fa90565234a827010f7be752a9a647c5",
"branch_name": "refs/heads/master",
"committer_date": 1640629747000,
"content_id": "536f862d7ac33a457a4635ae2f13e7746bbc8732",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "aceb7d4a721fb4aa36a1efe6a603ca5ad584e751",
"extension": "py",
"filename": "add-properties2turtle.py",
"fork_events_count": 26,
"gha_created_at": 1414255798000,
"gha_event_created_at": 1641849660000,
"gha_language": "Python",
"gha_license_id": "BSD-3-Clause",
"github_id": 25738703,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4482,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/scripts/add-properties2turtle.py",
"provenance": "stack-edu-0054.json.gz:583655",
"repo_name": "monarch-initiative/dipper",
"revision_date": 1640629747000,
"revision_id": "bf0a86c4472a2406919f96eee10afe156fe62951",
"snapshot_id": "8967366ad251394e606f2b1f64ed37ab2d97350d",
"src_encoding": "UTF-8",
"star_events_count": 57,
"url": "https://raw.githubusercontent.com/monarch-initiative/dipper/bf0a86c4472a2406919f96eee10afe156fe62951/scripts/add-properties2turtle.py",
"visit_date": "2022-12-04T23:44:29.184883"
} | 2.359375 | stackv2 | from rdflib.graph import ConjunctiveGraph, URIRef
from rdflib.namespace import RDF, OWL, DCTERMS
from rdflib import util as rdflib_util
from xml.sax import SAXParseException
import argparse
import re
import logging
logger = logging.getLogger(__name__)
def main():
parser = argparse.ArgumentParser(
description='description',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument(
'--input', '-i', type=str, required=True,
help='Location of input file')
parser.add_argument(
'--output', '-o', type=str, required=True,
help='Location of output file')
parser.add_argument(
'--input_format', '-f', type=str, default="turtle",
help='format of source rdf file (turtle, nt, rdf/xml)')
parser.add_argument(
'--output_format', '-g', type=str, default="turtle",
help='format of target rdf file (turtle, nt, rdf/xml)')
args = parser.parse_args()
property_list = get_properties_from_input(args.input, args.input_format)
merged_graph = make_property_graph(property_list, args)
# merge graphs
merged_graph.parse(args.input, format=args.input_format)
merged_graph.serialize(args.output, format=args.output_format)
def get_properties_from_input(file, input_format):
input_graph = ConjunctiveGraph()
input_graph.parse(file, format=input_format)
# collapse to single list
property_set = list()
for row in input_graph.predicates():
property_set.append(row)
return set(property_set)
def make_property_graph(properties, args):
graph = ConjunctiveGraph()
output_graph = ConjunctiveGraph()
GH = 'https://raw.githubusercontent.com'
OBO = 'https://purl.obolibrary.org/obo'
ontologies = [
OBO + '/sepio.owl',
OBO + '/geno.owl',
OBO + '/iao.owl',
OBO + '/pco.owl',
OBO + '/xco.owl',
OBO + '/ro.owl',
GH + '/jamesmalone/OBAN/master/ontology/oban_core.ttl',
]
for ontology in ontologies:
print("parsing: " + ontology)
try:
graph.parse(ontology, format=rdflib_util.guess_format(ontology))
except SAXParseException as e:
logger.error(e)
logger.error('Retrying: ' + ontology)
graph.parse(ontology, format="turtle")
except OSError as e: # URLError:
# simple retry
logger.error(e)
logger.error('Retrying: ' + ontology)
graph.parse(ontology, format=rdflib_util.guess_format(ontology))
# Get object properties
output_graph = add_property_to_graph(
graph.subjects(RDF['type'], OWL['ObjectProperty']),
output_graph, OWL['ObjectProperty'], properties)
# Get annotation properties
output_graph = add_property_to_graph(
graph.subjects(RDF['type'], OWL['AnnotationProperty']),
output_graph, OWL['AnnotationProperty'], properties)
# Get data properties
output_graph = add_property_to_graph(
graph.subjects(RDF['type'], OWL['DatatypeProperty']),
output_graph, OWL['DatatypeProperty'], properties)
# Hardcoded properties
output_graph.add(
(URIRef('https://monarchinitiative.org/MONARCH_cliqueLeader'),
RDF['type'], OWL['AnnotationProperty']))
output_graph.add(
(URIRef('https://monarchinitiative.org/MONARCH_anonymous'),
RDF['type'], OWL['AnnotationProperty']))
# Check monarch data triple
data_url = "https://data.monarchinitiative.org/ttl/{0}".format(
re.sub(r".*/", "", args.input))
new_url = "https://data.monarchinitiative.org/ttl/{0}".format(
re.sub(r".*/", "", args.output))
if (URIRef(data_url), RDF.type, OWL['Ontology']) in output_graph:
output_graph.remove(URIRef(data_url), RDF.type, OWL['Ontology'])
output_graph.add((URIRef(new_url), RDF.type, OWL['Ontology']))
for row in output_graph.predicates(
DC['source'], OWL['AnnotationProperty']):
if row == RDF['type']:
output_graph.remove(
(DC['source'], RDF['type'], OWL['AnnotationProperty']))
output_graph.add((DC['source'], RDF['type'], OWL['ObjectProperty']))
return output_graph
def add_property_to_graph(results, graph, property_type, property_list):
for row in results:
if row in property_list:
graph.add((row, RDF['type'], property_type))
return graph
if __name__ == "__main__":
main()
| 138 | 31.48 | 76 | 15 | 1,054 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_625eb1e8399becc5_49ea8170", "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": 4, "line_end": 4, "column_start": 1, "column_end": 38, "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/tmphvvervh1/625eb1e8399becc5.py", "start": {"line": 4, "col": 1, "offset": 136}, "end": {"line": 4, "col": 38, "offset": 173}, "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"
] | [
4
] | [
4
] | [
1
] | [
38
] | [
"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"
] | add-properties2turtle.py | /scripts/add-properties2turtle.py | monarch-initiative/dipper | BSD-3-Clause | |
2024-11-18T20:10:47.682966+00:00 | 1,509,972,463,000 | 3d303cfcb33d128ae4e7f8b36a28cf62385a69ca | 3 | {
"blob_id": "3d303cfcb33d128ae4e7f8b36a28cf62385a69ca",
"branch_name": "refs/heads/master",
"committer_date": 1509972463000,
"content_id": "051a9b51d61dc5ac399f99190e5600d19b6cff54",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "cbefadeb6433a6ce0a85056c1e5df738192bf629",
"extension": "py",
"filename": "exporting.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": 9075,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/scanpy/exporting.py",
"provenance": "stack-edu-0054.json.gz:583663",
"repo_name": "M0hammadL/scanpy",
"revision_date": 1509972463000,
"revision_id": "1c0b58dc7033f9a61841fa9c8041a8aca85c59a8",
"snapshot_id": "7fc539f0063c0bacc5b92ecf1bb086702328bc62",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/M0hammadL/scanpy/1c0b58dc7033f9a61841fa9c8041a8aca85c59a8/scanpy/exporting.py",
"visit_date": "2021-07-25T11:19:15.783541"
} | 2.71875 | stackv2 | # Author: F. Alex Wolf (http://falexwolf.de)
# T. Callies
"""Exporting to formats for other software.
"""
import numpy as np
import os
import json
import pdb
from math import inf
from .data_structs.data_graph import add_or_update_graph_in_adata
from scipy.sparse import issparse
def save_spring_dir(adata, k, project_directory, D=None,
custom_colors={}, cell_groupings=None, use_genes=[]):
"""Builds a SPRING project directory.
This is based on a preprocessing function by Caleb Weinreb:
https://github.com/AllonKleinLab/SPRING/
Parameters
----------
adata : AnnData() object
Matrix of gene expression. Rows correspond to cells and columns
correspond to genes.
k : int
Number of edges assigned to each node in knn graph
project_directory : str
Path to a directory where SPRING readable files will be written. The
directory does not have to exist before running this function.
D : np.ndarray (default: None)
Distance matrix for construction of knn graph. Any distance matrix can
be used as long as higher values correspond to greater distances.
If nothing is given, local graph distance is used (if available) or (re-)computed
cell_groupings : list of str (default: None)
Optional list of strings containing adata.add key to grouping. Adata.add should contain cell_groupings+'_order'
and cell_groupings+'colors' as keys with names / colors for groupings and for each cell the corresponding group
Furthermore. adata.smp[cell_groupings] should return an array of adata.X.shape[0] elements
custom_colors : dict (default: {})
Dictionary with one key-value pair for each custom color. The key is
the name of the color track and the value is a list of scalar values
(i.e. color intensities). If there are N cells total (i.e. X.shape[0] ==
N), then the list of labels should have N entries.
Currently not used
use_genes : list, default: []
Selects certain genes that are written into the coloring files. Default ([]) selects all genes
"""
# TODO: (LATER:) Make sure that this works for sparse adata objects as well
X= adata.X
# gene_list: list, np.ndarry - like
# An ordered list of gene names with length X.shape[1].
gene_list=adata.var_names
# File can be safed anywhere. However, for easy access via SPRING, safe it somewhere in the spring directory
os.system('mkdir ' + project_directory)
if not project_directory[-1] == '/': project_directory += '/'
if D==None:
if 'data_graph_distance_local' in adata.add:
D=adata.add['data_graph_distance_local']
edges= get_knn_edges_sparse(D, k)
else:
# if not available and nothing is given, calculate distances and add data_graph_distance_local to dictionary
add_or_update_graph_in_adata(
adata,
n_neighbors=30,
n_pcs=50,
n_dcs=15,
knn=None,
recompute_pca=False,
recompute_distances=False,
recompute_graph=False,
n_jobs=None)
# Note that output here will always be sparse
D = adata.add['data_graph_distance_local']
edges = get_knn_edges_sparse(D, k)
else:
if issparse(D):
edges = get_knn_edges_sparse(D, k)
else:
edges = get_knn_edges(D,k)
# save genesets
#TODO: (LATER:) Include when everything else works. Check how to include efficiently
# custom_colors['Uniform'] = np.zeros(X.shape[0])
# write_color_tracks(custom_colors, project_directory + 'color_data_gene_sets.csv')
all = []
# save gene colortracks
os.system('mkdir ' + project_directory + 'gene_colors')
# The following Split into left right (+ casting) makes sure that every gene is included, no out of bounds
II = int(len(gene_list) / 50) + 1
left=0
right=II
for j in range(50):
fname = project_directory + '/gene_colors/color_data_all_genes-' + repr(j) + '.csv'
if len(use_genes) > 0:
all_gene_colors = {
# Adapted slicing, so that it won't be OOB
g: X[:, i + left] for i, g in enumerate(gene_list[left: right]) if g in use_genes}
else:
all_gene_colors = {
# Here, the original control mechansim to included genes in Color if average expression across all cells is above 0.05
# This doesn't translate to anything meaningful here. Actually, no genes are then selected
g: X[:, i + left] for i, g in enumerate(
gene_list[left: right]) }
write_color_tracks(all_gene_colors, fname)
left+=II
right+=II
# Avoid OOB:
if right >=len(gene_list):
right=len(gene_list)
all += all_gene_colors.keys()
# Create and save a dictionary of color profiles to be used by the visualizer
# Cast: numpy datatypes as input not json serializable
color_stats = {}
for i in range(X.shape[1]):
mean = float(np.mean(X[:, i]))
std = float(np.std(X[:, i]))
max = float(np.max(X[:, i]))
centile = float(np.percentile(X[:, i], 99.6))
color_stats[gene_list[i]] = (mean, std, 0, max, centile)
json.dump(color_stats,
open(project_directory + '/color_stats.json', 'w'), indent=4, sort_keys=True)
# save cell labels
# Categorical coloring data:
categorical_coloring_data = {}
# Adapt groupby
if cell_groupings is None:
# In this case, do nothing
pass
else:
for j in range(cell_groupings):
if (cell_groupings[j]+'_order' not in adata.add) or (cell_groupings[j]+'_colors' not in adata.add) :
# TODO: Change to logging
print('Adata annotation does not exist. Check input' )
else:
groups=adata.smp[cell_groupings[j]]
group_names=adata.add[cell_groupings[j]+'_order']
group_colors=adata.add[cell_groupings[j]+'_colors']
label_colors = {l: group_colors[i] for i, l in enumerate(group_names)}
labels = list(groups)
# SPRING expects a Dictionary for label_colors, but a list for labels !
categorical_coloring_data[cell_groupings[j]] = {'label_colors': label_colors, 'label_list': labels}
json.dump(categorical_coloring_data, open(
project_directory + '/categorical_coloring_data.json', 'w'), indent=4)
#
nodes = [{'name': i, 'number': i} for i in range(X.shape[0])]
edges = [{'source': int(i), 'target': int(j)} for i, j in edges]
out = {'nodes': nodes, 'links': edges}
# Possible Error: ' instead of ": For now, it seems to work
open(project_directory + 'graph_data.json', 'w').write(
json.dumps(out, indent=4, separators=(',', ': ')))
# The following method is only used when a full (non-sparse) distance matrix is given as an input parameter
# Depending on input size, this can be very cost-inefficient
def get_knn_edges(dmat, k):
edge_dict = {}
for i in range(dmat.shape[0]):
# Save modified coordinate values, rewrite so that adata_object is not changed!
l=k
saved_values={}
while l>0:
j = dmat[i, :].argmin()
saved_values[j]=dmat[i,j]
if i != j:
ii, jj = tuple(sorted([i, j]))
edge_dict[(ii, jj)] = dmat[i, j]
dmat[i, j] = 0
l=l-1
# Rewrite safed values:
for j, val in enumerate(saved_values):
dmat[i,j]=val
return edge_dict.keys()
# This is a (preliminary) alternative to get_knn_edges
# We assume that D is a distance matrix containing only non-zero entries for the (k-1)nn
# (as is the value for data graph distance local)
# This is the version for knn as in graph distance local.
def get_knn_edges_sparse(dmat, k):
edge_dict = {}
if not issparse(dmat):
return get_knn_edges(dmat,k)
else:
for i in range(dmat.shape[0]):
row = dmat.getrow(i)
l=1
saved_values={}
while l<k:
data_index=row.data.argmin()
j=row.indices[data_index]
saved_values[j] = dmat[i, j]
if i != j:
ii, jj = tuple(sorted([i, j]))
edge_dict[(ii, jj)] = dmat[i, j]
dmat[i, j] = inf
l = l + 1
# Rewrite safed values:
for j, val in enumerate(saved_values):
dmat[i, j] = val
return edge_dict.keys()
def write_color_tracks(ctracks, fname):
out = []
for name, score in ctracks.items():
line = ','.join([name] + [repr(round(x, 1)) for x in score])
out += [line]
out = sorted(out, key=lambda x: x.split(',')[0])
open(fname, 'w').write('\n'.join(out))
| 214 | 41.41 | 134 | 20 | 2,195 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.python-debugger-found_1c4ee88a4dd48b8e_f0bfa4a7", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.python-debugger-found", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Importing the python debugger; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 9, "line_end": 9, "column_start": 1, "column_end": 11, "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.best-practice.python-debugger-found", "path": "/tmp/tmphvvervh1/1c4ee88a4dd48b8e.py", "start": {"line": 9, "col": 1, "offset": 157}, "end": {"line": 9, "col": 11, "offset": 167}, "extra": {"message": "Importing the python debugger; did you mean to leave this in?", "metadata": {"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.security.audit.dangerous-system-call-audit_1c4ee88a4dd48b8e_7c066c82", "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": 55, "line_end": 55, "column_start": 5, "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://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/tmphvvervh1/1c4ee88a4dd48b8e.py", "start": {"line": 55, "col": 5, "offset": 2496}, "end": {"line": 55, "col": 44, "offset": 2535}, "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-audit_1c4ee88a4dd48b8e_5421c439", "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": 90, "line_end": 90, "column_start": 5, "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://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/tmphvvervh1/1c4ee88a4dd48b8e.py", "start": {"line": 90, "col": 5, "offset": 3821}, "end": {"line": 90, "col": 60, "offset": 3876}, "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.unspecified-open-encoding_1c4ee88a4dd48b8e_01e5eac5", "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": 125, "line_end": 125, "column_start": 15, "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/tmphvvervh1/1c4ee88a4dd48b8e.py", "start": {"line": 125, "col": 15, "offset": 5455}, "end": {"line": 125, "col": 65, "offset": 5505}, "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_1c4ee88a4dd48b8e_a0a37507", "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": 148, "column_start": 46, "column_end": 76, "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/tmphvvervh1/1c4ee88a4dd48b8e.py", "start": {"line": 147, "col": 46, "offset": 6578}, "end": {"line": 148, "col": 76, "offset": 6659}, "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_1c4ee88a4dd48b8e_045cbe92", "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": 155, "line_end": 155, "column_start": 5, "column_end": 53, "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/tmphvvervh1/1c4ee88a4dd48b8e.py", "start": {"line": 155, "col": 5, "offset": 6924}, "end": {"line": 155, "col": 53, "offset": 6972}, "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_1c4ee88a4dd48b8e_4965401e", "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": 214, "line_end": 214, "column_start": 5, "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/tmphvvervh1/1c4ee88a4dd48b8e.py", "start": {"line": 214, "col": 5, "offset": 9036}, "end": {"line": 214, "col": 21, "offset": 9052}, "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",
"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"
] | [
55,
90
] | [
55,
90
] | [
5,
5
] | [
44,
60
] | [
"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"
] | exporting.py | /scanpy/exporting.py | M0hammadL/scanpy | BSD-3-Clause | |
2024-11-18T20:10:47.912976+00:00 | 1,434,144,825,000 | a64583568debcd7fb768ecb0227b500b9cefade5 | 3 | {
"blob_id": "a64583568debcd7fb768ecb0227b500b9cefade5",
"branch_name": "refs/heads/master",
"committer_date": 1434144825000,
"content_id": "d9480c0cd19a54be62afc8f0164f4030b861c0e3",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "f869bdf871c834eaa502fa113c3ee495f66f8ef1",
"extension": "py",
"filename": "linear_model.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": 4923,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/siglearn/linear_model.py",
"provenance": "stack-edu-0054.json.gz:583666",
"repo_name": "erichseamon/siglearn",
"revision_date": 1434144825000,
"revision_id": "2cfd2cabcbbcdca8cef27748756c6549be15f7c9",
"snapshot_id": "b1daa5652b5b6e8e85f2626c1ba8e091e958808c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/erichseamon/siglearn/2cfd2cabcbbcdca8cef27748756c6549be15f7c9/siglearn/linear_model.py",
"visit_date": "2021-01-16T20:49:56.031665"
} | 2.78125 | stackv2 | # Authors: Jake VanderPlas
# License: BSD
__all__ = ['LinearRegression', 'Ridge', 'Lasso']
import inspect
import types
import imp
import numpy as np
from sklearn import linear_model as sklearn_linear_model
from .base import BaseEstimator
class LinearModel(BaseEstimator):
"""Base class for Linear regression with errors in y"""
def fit(self, X, y, sigma_y=None):
X, y = self._construct_X_y(X, y, sigma_y, self.fit_intercept)
self.model.fit(X, y)
return self
def predict(self, X):
X = self._transform_X(X, self.fit_intercept)
return self.model.predict(X)
@staticmethod
def _transform_X(X, fit_intercept=True):
X = np.atleast_2d(X)
if fit_intercept:
X = np.hstack([np.ones([X.shape[0], 1]), X])
return X
@staticmethod
def _construct_X_y(X, y, sigma_y=None, fit_intercept=True):
"""
Construct the X matrix and y vectors
scaled appropriately by error in y
"""
if sigma_y is None:
sigma_y = 1
X = np.atleast_2d(X)
y = np.asarray(y)
sigma_y = np.asarray(sigma_y)
# quick sanity checks on inputs.
assert X.ndim == 2
assert y.ndim == 1
assert sigma_y.ndim in (0, 1, 2)
assert X.shape[0] == y.shape[0]
# Intercept is implemented via a column of 1s in the X matrix
X = LinearModel._transform_X(X, fit_intercept)
# with no error or constant errors, no scaling needed
if sigma_y.ndim == 0:
X_out, y_out = X, y
elif sigma_y.ndim == 1:
assert sigma_y.shape == y.shape
X_out, y_out = X / sigma_y[:, None], y / sigma_y
elif sigma_y.ndim == 2:
assert sigma_y.shape == (y.size, y.size)
evals, evecs = np.linalg.eigh(sigma_y)
X_out = np.dot(evecs * (evals ** -0.5),
np.dot(evecs.T, X))
y_out = np.dot(evecs * (evals ** -0.5),
np.dot(evecs.T, y))
else:
raise ValueError("sigma_y must have 0, 1, or 2 dimensions")
return X_out, y_out
#class LinearRegression(LinearModel):
# """Ordinary least squares Linear Regression with errors
# """
# BaseModel = linear_model.LinearRegression
#
# def __init__(self, fit_intercept=True, normalize=False, copy_X=True):
# self.fit_intercept = fit_intercept
# self.normalize = normalize
# self.copy_X = copy_X
# self.model = self.BaseModel(fit_intercept=fit_intercept,
# normalize=normalize)
def _model_factory(BaseModel, docstring=None):
"""Generate a siglearn linear model from a scikit-learn linear model"""
argspec = inspect.getargspec(BaseModel.__init__)
args = argspec.args
defaults = argspec.defaults
# Construct __init__() function code
arglist = ", ".join(arg for arg in args[:len(args) - len(defaults)])
kwarglist = ", ".join("{0}={1}".format(arg, repr(val))
for arg, val in zip(args[len(args) - len(defaults):],
defaults))
print(kwarglist)
initcode = "self.model = self.BaseModel({0})".format(', '.join(args[1:]))
allargs = ", ".join("{arg}={arg}".format(arg=arg)
if arg != 'fit_intercept'
else 'fit_intercept=False'
for arg in args[1:])
arg_assignments = "\n ".join("self.{arg} = {arg}".format(arg=arg)
for arg in args[1:])
initcode = ("def __init__({args}, {kwargs}):\n"
" {arg_assignments}\n"
" self.model = self.BaseModel({allargs})\n"
"".format(args=arglist, kwargs=kwarglist, allargs=allargs,
arg_assignments=arg_assignments))
if docstring is None:
docstring = BaseModel.__doc__
# build the class namespace dictionary
classmembers = dict(__doc__=docstring,
BaseModel=BaseModel)
# TODO: use six._exec here; following is Python 3 only
exec(initcode, classmembers)
# return the dynamically-constructed class
return type(BaseModel.__name__, (LinearModel,), classmembers)
#----------------------------------------------------------------------
# Use the model factory to build some models
LinearRegression = _model_factory(
sklearn_linear_model.LinearRegression,
"""Ordinary least squares Linear Regression with errors
TODO: further documentation
""")
Ridge = _model_factory(
sklearn_linear_model.Ridge,
"""Ridge-regularized Linear Regression with errors
TODO: further docuementation
""")
Lasso = _model_factory(
sklearn_linear_model.Lasso,
"""Lasso-regularized Linear Regression with errors
TODO: further documentation
""")
| 149 | 32.04 | 79 | 19 | 1,188 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.exec-detected_cad3fbca5dba5b41_db43a804", "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": 122, "line_end": 122, "column_start": 5, "column_end": 33, "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/tmphvvervh1/cad3fbca5dba5b41.py", "start": {"line": 122, "col": 5, "offset": 4163}, "end": {"line": 122, "col": 33, "offset": 4191}, "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"}}}] | 1 | true | [
"CWE-95"
] | [
"rules.python.lang.security.audit.exec-detected"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
122
] | [
122
] | [
5
] | [
33
] | [
"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"
] | linear_model.py | /siglearn/linear_model.py | erichseamon/siglearn | BSD-2-Clause | |
2024-11-18T20:10:48.788542+00:00 | 1,599,158,272,000 | 6834a1792c7dc2337520cbc8e653cf351a23c340 | 2 | {
"blob_id": "6834a1792c7dc2337520cbc8e653cf351a23c340",
"branch_name": "refs/heads/master",
"committer_date": 1599158272000,
"content_id": "d02ec4c5eed60e03b2d1a4bf7f3e6c68255ca956",
"detected_licenses": [
"MIT"
],
"directory_id": "27b60c59ae5fe8d3a81a4a44485618e891ff0e34",
"extension": "py",
"filename": "motorizedfocuscamerapreview.py",
"fork_events_count": 0,
"gha_created_at": 1597097528000,
"gha_event_created_at": 1597097529000,
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 286588729,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1233,
"license": "MIT",
"license_type": "permissive",
"path": "/References/motorizedfocuscamerapreview.py",
"provenance": "stack-edu-0054.json.gz:583679",
"repo_name": "vmendivil/pi-timelapse",
"revision_date": 1599158272000,
"revision_id": "cc3622911cf7ee79384f170e4efb0a5d0d7fe3e9",
"snapshot_id": "1eb2e43dde401ce8a7f6bd148ece063740f9c904",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vmendivil/pi-timelapse/cc3622911cf7ee79384f170e4efb0a5d0d7fe3e9/References/motorizedfocuscamerapreview.py",
"visit_date": "2022-12-09T13:41:17.968837"
} | 2.3125 | stackv2 |
import os
import time
import sys
import threading
import pygame,sys
from pygame.locals import *
from time import ctime, sleep
pygame.init()
screen=pygame.display.set_mode((320,240),0,32)
pygame.key.set_repeat(100)
def runFocus(func):
temp_val = 512
while True:
for event in pygame.event.get():
if event.type ==KEYDOWN:
print temp_val
if event.key == K_UP:
print 'UP'
if temp_val < 1000:
temp_val += 10
else:
temp_val = temp_val
value = (temp_val<<4) & 0x3ff0
dat1 = (value>>8)&0x3f
dat2 = value & 0xf0
os.system("i2cset -y 0 0x0c %d %d" % (dat1,dat2))
elif event.key==K_DOWN:
print 'DOWN'
if temp_val <12 :
temp_val = temp_val
else:
temp_val -= 10
value = (temp_val<<4) & 0x3ff0
dat1 = (value>>8)&0x3f
dat2 = value & 0xf0
os.system("i2cset -y 0 0x0c %d %d" % (dat1,dat2))
def runCamera():
cmd = "sudo raspistill -t 0"
os.system(cmd)
if __name__ == "__main__":
t1 = threading.Thread(target=runFocus,args=("t1",))
t1.setDaemon(True)
t1.start()
runCamera()
| 47 | 25.23 | 63 | 18 | 384 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_9c3a7bb5ffd78907_e815d2df", "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": 28, "line_end": 28, "column_start": 15, "column_end": 64, "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/tmphvvervh1/9c3a7bb5ffd78907.py", "start": {"line": 28, "col": 15, "offset": 630}, "end": {"line": 28, "col": 64, "offset": 679}, "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-audit_9c3a7bb5ffd78907_87a7dab8", "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": 15, "column_end": 64, "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/tmphvvervh1/9c3a7bb5ffd78907.py", "start": {"line": 38, "col": 15, "offset": 987}, "end": {"line": 38, "col": 64, "offset": 1036}, "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"}}}] | 2 | 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"
] | [
28,
38
] | [
28,
38
] | [
15,
15
] | [
64,
64
] | [
"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"
] | motorizedfocuscamerapreview.py | /References/motorizedfocuscamerapreview.py | vmendivil/pi-timelapse | MIT | |
2024-11-18T20:10:49.843211+00:00 | 1,577,173,776,000 | 425a2b878e391f066a7e8d97d473ae807f620562 | 3 | {
"blob_id": "425a2b878e391f066a7e8d97d473ae807f620562",
"branch_name": "refs/heads/master",
"committer_date": 1577173776000,
"content_id": "9a3add6b0ab3c9e1633eb2db8331042b0aae8ff4",
"detected_licenses": [
"MIT"
],
"directory_id": "f2475329a1924b82704d0fe3d52f1f9cbc5a94d6",
"extension": "py",
"filename": "q5.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": 1095,
"license": "MIT",
"license_type": "permissive",
"path": "/ass/ass3/q5.py",
"provenance": "stack-edu-0054.json.gz:583686",
"repo_name": "GaryccOps/cs3311",
"revision_date": 1577173776000,
"revision_id": "0c1af6672c126f94c20bdb573b04a9b1c80b03eb",
"snapshot_id": "e8ee57c0d5f22d140576a482e94b703631e01d0f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/GaryccOps/cs3311/0c1af6672c126f94c20bdb573b04a9b1c80b03eb/ass/ass3/q5.py",
"visit_date": "2023-03-15T18:54:25.847932"
} | 2.828125 | stackv2 | import psycopg2
import sys
def q5(conn,key):
cur = conn.cursor()
query = '''
select ct.name as type, c.tag, ce.num, c.quota from classes c
join classEnroll ce on c.id = ce.class_id
join classtypes ct on ct.id = c.type_id
join courses cr on cr.id = c.course_id
join subjects s on cr.subject_id = s.id
where s.code = '{}';
'''.format(key)
# execute queury
cur.execute(query)
rows = cur.fetchall()
result = []
for (class_type, tag, num, quota) in rows:
if (num/quota) < 0.5:
result.append( (class_type, tag, num/quota) )
#print result
for class_type, tag, percen in sorted(result, key=lambda x:(x[0], x[1], x[2])):
print("{0} {1} is {2:.0%} full".format(class_type, tag.strip(), percen))
def connect(key):
try:
conn = psycopg2.connect("dbname=a3")
#run q5
q5(conn, key)
conn.close()
except Exception as e:
print("Couldn't connect the database.", e)
if __name__ == "__main__":
# get incommon number from command line
key = 'COMP1521'
if len(sys.argv) > 1:
key = sys.argv[1]
connect(key)
| 45 | 23.33 | 81 | 13 | 336 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_b5eb2eedd451c65b_48173102", "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": 16, "line_end": 16, "column_start": 3, "column_end": 21, "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/tmphvvervh1/b5eb2eedd451c65b.py", "start": {"line": 16, "col": 3, "offset": 391}, "end": {"line": 16, "col": 21, "offset": 409}, "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_b5eb2eedd451c65b_ee3d22a8", "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": 16, "line_end": 16, "column_start": 3, "column_end": 21, "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/tmphvvervh1/b5eb2eedd451c65b.py", "start": {"line": 16, "col": 3, "offset": 391}, "end": {"line": 16, "col": 21, "offset": 409}, "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.lang.security.audit.formatted-sql-query",
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"HIGH"
] | [
16,
16
] | [
16,
16
] | [
3,
3
] | [
21,
21
] | [
"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"
] | q5.py | /ass/ass3/q5.py | GaryccOps/cs3311 | MIT | |
2024-11-18T20:10:52.618210+00:00 | 1,577,084,809,000 | 6dc3075c79644f9f1fbf92635a11f10198043508 | 3 | {
"blob_id": "6dc3075c79644f9f1fbf92635a11f10198043508",
"branch_name": "refs/heads/master",
"committer_date": 1577084809000,
"content_id": "1343e02a8329067847cf1517d854cb643fd13a30",
"detected_licenses": [
"MIT"
],
"directory_id": "309391b8e1510a8e549590301188beb3306d2807",
"extension": "py",
"filename": "spellcheck.py",
"fork_events_count": 0,
"gha_created_at": 1571131746000,
"gha_event_created_at": 1618945247000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 215259463,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6272,
"license": "MIT",
"license_type": "permissive",
"path": "/spellcheckapp/spellcheck/spellcheck.py",
"provenance": "stack-edu-0054.json.gz:583723",
"repo_name": "kratel/nyu_appsec_a2",
"revision_date": 1577084809000,
"revision_id": "ade9efd8f2b5143a99e4f2da8f249884c6d4a80e",
"snapshot_id": "0988ea5996d756b759f48c7932a8a81074d8158c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kratel/nyu_appsec_a2/ade9efd8f2b5143a99e4f2da8f249884c6d4a80e/spellcheckapp/spellcheck/spellcheck.py",
"visit_date": "2021-06-22T20:47:33.125542"
} | 2.515625 | stackv2 | """
SpellCheck Module for Spellcheckapp.
Contains spell check related views.
All responses are constructed with security headers.
"""
import subprocess
import tempfile
from shlex import quote
from flask import (
Blueprint, current_app, flash, g, make_response, render_template
)
from spellcheckapp import db
from spellcheckapp.auth import models as authmodels
from spellcheckapp.auth.auth import login_required
from spellcheckapp.spellcheck import forms, models
from werkzeug.exceptions import abort
bp = Blueprint('spellcheck', __name__, template_folder="spellcheckapp/templates")
@bp.route('/')
def index():
"""
Index View.
Landing page for the app at root of the site.
"""
render = make_response(render_template('spellcheck/index.html'))
render.headers.set('Content-Security-Policy', "default-src 'self'")
render.headers.set('X-Content-Type-Options', 'nosniff')
render.headers.set('X-Frame-Options', 'SAMEORIGIN')
render.headers.set('X-XSS-Protection', '1; mode=block')
return render
@bp.route('/spell_check', methods=('GET', 'POST'))
@login_required
def spell_check():
"""
Spell Check View.
Must be logged in to access this view, otherwise redirected to login page.
Text is submitted here to be spell checked.
Text submissions and results are stored as query history for the logged in user.
"""
form = forms.SpellCheckForm()
results = {}
if form.validate_on_submit():
inputtext = quote(form.inputtext.data)
error = None
if not inputtext:
error = "Invalid input"
flash(error)
inputtext = bytes(inputtext, 'utf-8')
results["textout"] = inputtext.decode()
new_spell_check = None
if error is None:
result = None
with tempfile.NamedTemporaryFile() as inputfile:
# inputfile = tempfile.NamedTemporaryFile()
inputfile.write(inputtext)
inputfile.flush()
with tempfile.TemporaryFile() as tempf:
proc = subprocess.Popen([current_app.config['SPELLCHECK'], inputfile.name, current_app.config['WORDLIST']], stdout=tempf)
proc.wait()
tempf.seek(0)
result = tempf.read()
result = result.decode().split("\n")
result = list(filter(None, result))
if result:
results["misspelled"] = ", ".join(result)
new_spell_check = models.SpellChecks(username=g.user.username, submitted_text=results["textout"], misspelled_words=results["misspelled"])
else:
results["no_misspelled"] = "No misspelled words were found."
new_spell_check = models.SpellChecks(username=g.user.username, submitted_text=results["textout"], misspelled_words=results["no_misspelled"])
if new_spell_check is not None:
db.session.add(new_spell_check)
db.session.commit()
render = make_response(render_template('spellcheck/spell_check.html', form=form, results=results))
render.headers.set('Content-Security-Policy', "default-src 'self'")
render.headers.set('X-Content-Type-Options', 'nosniff')
render.headers.set('X-Frame-Options', 'SAMEORIGIN')
render.headers.set('X-XSS-Protection', '1; mode=block')
return render
@bp.route('/history', methods=('GET', 'POST'))
@login_required
def history():
"""
History View.
Must be logged in to access this view, otherwise redirected to login page.
This page will list links to queries that the user has submitted.
Will also show total number of queries submitted so far.
If an admin user visits this page, there will be a form available.
Admins can lookup another user's history by submitting a username.
Performs form validation and user level validation.
"""
render = None
form = forms.UserHistoryForm()
username = g.user.username
queryhistory = models.SpellChecks.query.filter_by(username=username)
numqueries = queryhistory.count()
if g.user.is_admin:
if form.validate_on_submit():
quser = form.userquery.data
error = None
if not quser:
error = "Invalid input"
flash(error)
elif authmodels.Users.query.filter_by(username=quser).first() is None:
error = "No user with this username found"
flash(error)
if error is None:
username = quser
queryhistory = models.SpellChecks.query.filter_by(username=username)
numqueries = queryhistory.count()
if g.user.is_admin:
render = make_response(render_template('spellcheck/history.html', form=form, numqueries=numqueries, queryhistory=queryhistory, username=username))
else:
render = make_response(render_template('spellcheck/history.html', numqueries=numqueries, queryhistory=queryhistory, username=username))
render.headers.set('Content-Security-Policy', "default-src 'self'")
render.headers.set('X-Content-Type-Options', 'nosniff')
render.headers.set('X-Frame-Options', 'SAMEORIGIN')
render.headers.set('X-XSS-Protection', '1; mode=block')
return render
@bp.route('/history/query<int:queryid>', methods=['GET'])
@login_required
def query(queryid):
"""
Dynamic Query View.
Must be logged in to access this view, otherwise redirected to login page.
A unique view is generated based off a query ID.
A page is only returned if the query ID is associated with a logged in user.
Otherwise a logged in user will be redirected to a 404 error page.
"""
query = models.SpellChecks.query.get(queryid)
if query is not None and ((g.user.is_admin) or (g.user.username == query.username)):
query
render = make_response(render_template('spellcheck/history_s_query.html', query=query))
render.headers.set('Content-Security-Policy', "default-src 'self'")
render.headers.set('X-Content-Type-Options', 'nosniff')
render.headers.set('X-Frame-Options', 'SAMEORIGIN')
render.headers.set('X-XSS-Protection', '1; mode=block')
return render
else:
abort(404)
| 166 | 36.78 | 156 | 20 | 1,361 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_7da4c129a5a16548_2cd23442", "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": 72, "line_end": 72, "column_start": 28, "column_end": 142, "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/tmphvvervh1/7da4c129a5a16548.py", "start": {"line": 72, "col": 28, "offset": 2080}, "end": {"line": 72, "col": 142, "offset": 2194}, "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.maintainability.is-function-without-parentheses_7da4c129a5a16548_8fd19563", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_admin\" a function or an attribute? If it is a function, you may have meant g.user.is_admin() because g.user.is_admin is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 117, "line_end": 117, "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": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmphvvervh1/7da4c129a5a16548.py", "start": {"line": 117, "col": 8, "offset": 4101}, "end": {"line": 117, "col": 23, "offset": 4116}, "extra": {"message": "Is \"is_admin\" a function or an attribute? If it is a function, you may have meant g.user.is_admin() because g.user.is_admin 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_7da4c129a5a16548_73d22296", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_admin\" a function or an attribute? If it is a function, you may have meant g.user.is_admin() because g.user.is_admin is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 134, "line_end": 134, "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": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmphvvervh1/7da4c129a5a16548.py", "start": {"line": 134, "col": 8, "offset": 4695}, "end": {"line": 134, "col": 23, "offset": 4710}, "extra": {"message": "Is \"is_admin\" a function or an attribute? If it is a function, you may have meant g.user.is_admin() because g.user.is_admin 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_7da4c129a5a16548_83dd1b4b", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_admin\" a function or an attribute? If it is a function, you may have meant g.user.is_admin() because g.user.is_admin is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 157, "line_end": 157, "column_start": 31, "column_end": 48, "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/tmphvvervh1/7da4c129a5a16548.py", "start": {"line": 157, "col": 31, "offset": 5788}, "end": {"line": 157, "col": 48, "offset": 5805}, "extra": {"message": "Is \"is_admin\" a function or an attribute? If it is a function, you may have meant g.user.is_admin() because g.user.is_admin is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "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"
] | [
72
] | [
72
] | [
28
] | [
142
] | [
"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"
] | spellcheck.py | /spellcheckapp/spellcheck/spellcheck.py | kratel/nyu_appsec_a2 | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.