added
stringdate
2024-11-18 17:59:49
2024-11-19 03:44:43
created
int64
126B
1,694B
id
stringlengths
40
40
int_score
int64
2
5
metadata
dict
score
float64
2.31
5.09
source
stringclasses
1 value
text
stringlengths
257
22.3k
num_lines
int64
16
648
avg_line_length
float64
15
61
max_line_length
int64
31
179
ast_depth
int64
8
40
length
int64
101
3.8k
lang
stringclasses
1 value
sast_semgrep_findings
stringlengths
1.56k
349k
sast_semgrep_findings_count
int64
1
162
sast_semgrep_success
bool
1 class
sast_semgrep_error
stringclasses
1 value
cwe_ids
listlengths
1
162
rule_ids
listlengths
1
162
subcategories
listlengths
1
162
confidences
listlengths
1
162
severities
listlengths
1
162
line_starts
listlengths
1
162
line_ends
listlengths
1
162
column_starts
listlengths
1
162
column_ends
listlengths
1
162
owasp_categories
listlengths
1
162
messages
listlengths
1
162
cvss_scores
listlengths
1
162
likelihoods
listlengths
1
162
impacts
listlengths
1
162
filename
stringlengths
4
105
path
stringlengths
5
372
repo_name
stringlengths
5
115
license
stringclasses
385 values
2024-11-18T20:31:20.281744+00:00
1,504,773,221,000
bda89072f26f0b0ae4c43052075e666279e072d7
2
{ "blob_id": "bda89072f26f0b0ae4c43052075e666279e072d7", "branch_name": "refs/heads/master", "committer_date": 1504773221000, "content_id": "4c865bb8a3960a06739f425b9ebe6ae852c64c44", "detected_licenses": [ "MIT" ], "directory_id": "24cbc2d5f4a522fd132f53cb0c41eefbfc4e92b2", "extension": "py", "filename": "trec_eval.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": 5839, "license": "MIT", "license_type": "permissive", "path": "/acsp/pre/trec_eval.py", "provenance": "stack-edu-0054.json.gz:574945", "repo_name": "mdmustafizurrahman/activesampling", "revision_date": 1504773221000, "revision_id": "545d72c67cfa38b9c54242ced9d254a8cf451a35", "snapshot_id": "68cd3a4eeca85ad41dab565c4a8dd3a8bdfea02d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mdmustafizurrahman/activesampling/545d72c67cfa38b9c54242ced9d254a8cf451a35/acsp/pre/trec_eval.py", "visit_date": "2021-06-24T20:12:49.464916" }
2.34375
stackv2
# coding=utf-8 from __future__ import division from __future__ import absolute_import from __future__ import print_function import subprocess from collections import defaultdict from acsp.com.common import * from acsp.com.utils import * class EvaluationResult(object): """An object that stores the results output by trec_eval.""" eval_fields = { "num_q": int, "num_ret": int, "num_rel": int, "num_rel_ret": int, "map": float, "Rprec": float, "bpref": float, "recip_rank": float, "P_10": float, "P_30": float, "P_100": float} def __init__(self, rc): """Initializes from a file which contains the output from trec_eval.""" self.runid = "" self.results = {} self.queries = {} # with open(filepath, 'r') acsp f: for line in rc.split('\n'): if line.strip() == '': continue (field, query, value) = line.split() if query == "all": # accumulated results over all queries if field == "runid": self.runid = value else: self.parse_field(field, value, self.results) else: # query is a number if query not in self.queries: self.queries[query] = {} self.parse_field(field, value, self.queries[query]) def parse_field(self, field, value, target): """Parses the value of a field and puts it in target[field].""" field_types = self.__class__.eval_fields if field in field_types: target[field] = field_types[field](value) # convert str type to target type else: pass def get_total_measure_score(self, field): """Get average measure for all queries.""" return self.results[field] def get_measure_score_by_query(self, field, query): """ Get measure by query. """ if query in self.queries.keys(): return self.queries[query].get(field, 0) else: return 0 class TrecEval(object): """Wrapper of trec_eval.""" def __init__(self, trec_name): self.dict_answer = self.calculate_metrics(trec_name=trec_name) @staticmethod def trec_eval(path_qrels_file, path_query_rt_file, path_trec_eval=TREC_EVAL_EXCUTE): """Call trec_eval via subprocess.""" # call trec_eval in command pipe = subprocess.Popen([path_trec_eval, '-q', path_qrels_file, path_query_rt_file], stdout=subprocess.PIPE) try: stdout, stderr = pipe.communicate() except subprocess.CalledProcessError as e: raise e # format result rc_str = stdout.decode() eval_result = EvaluationResult(rc_str) return eval_result def calculate_metrics(self, trec_name): """Calculate rel doc, rel doc, total doc, ap, rp, p30, rr, rbp, bpref.""" # qrel rel_dir = os.path.join(DATA_DIR, trec_name, DICT_TREC_TYPE[trec_name][1]) path_qrels_file = os.path.join(rel_dir, get_file_ids(rel_dir)[0]) # system run sysrun_dir = os.path.join(DATA_DIR, trec_name, DICT_TREC_TYPE[trec_name][0]) file_ids = get_file_ids(sysrun_dir) # get (r, ap, rp) for all topics and system runs dict_answer = defaultdict(dict) for run_id in file_ids: path_query_rt_file = os.path.join(sysrun_dir, run_id) eval_result = self.trec_eval(path_qrels_file=path_qrels_file, path_query_rt_file=path_query_rt_file) # per topic for topic_id in eval_result.queries.keys(): r = eval_result.get_measure_score_by_query('num_rel', topic_id) t = eval_result.get_measure_score_by_query('num_ret', topic_id) ap = eval_result.get_measure_score_by_query('map', topic_id) rp = eval_result.get_measure_score_by_query('Rprec', topic_id) p30 = eval_result.get_measure_score_by_query('P_30', topic_id) dcg = 0 # stub rr = eval_result.get_measure_score_by_query('recip_rank', topic_id) bpref = eval_result.get_measure_score_by_query('bpref', topic_id) dict_answer[run_id.strip()][topic_id.strip()] = (r, r, t, ap, rp, p30, dcg, rr, 0, bpref) # all total_r = eval_result.get_total_measure_score('num_rel') total_t = eval_result.get_total_measure_score('num_ret') total_ap = eval_result.get_total_measure_score('map') total_rp = eval_result.get_total_measure_score('Rprec') total_p30 = eval_result.get_total_measure_score('P_30') total_dcg = 0 # stub total_rr = eval_result.get_total_measure_score('recip_rank') total_bpref = eval_result.get_total_measure_score('bpref') dict_answer[run_id.strip()]['all_topics'] = (total_r, total_r, total_t, total_ap, total_rp, total_p30, total_dcg, total_rr, total_bpref) return dict_answer def get_answer(self, topic_id, list_sysrun_name): """Test. The result can be compared with that of Preprocess.""" list_answer = [] for run_id in list_sysrun_name: list_answer.append(self.dict_answer[run_id.strip()][topic_id.strip()]) return list_answer def get_system_answer(self): """Test. The result can be compared with the published results in TREC overview papers.""" print('system (R, AP, RP) ') for key in self.dict_answer.keys(): print('{} {} '.format(key, self.dict_answer[key]['all_topics'])) return if __name__ == '__main__': pass
169
33.55
125
17
1,361
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_cc5d4134f5a31f6f_bc0fff64", "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": 90, "line_end": 90, "column_start": 16, "column_end": 117, "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/tmprvd6_wj2/cc5d4134f5a31f6f.py", "start": {"line": 90, "col": 16, "offset": 2506}, "end": {"line": 90, "col": 117, "offset": 2607}, "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" ]
[ 90 ]
[ 90 ]
[ 16 ]
[ 117 ]
[ "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" ]
trec_eval.py
/acsp/pre/trec_eval.py
mdmustafizurrahman/activesampling
MIT
2024-11-18T20:31:22.109371+00:00
1,686,028,601,000
b4c99ac535b7af97f2b23aa02895128c857403ed
3
{ "blob_id": "b4c99ac535b7af97f2b23aa02895128c857403ed", "branch_name": "refs/heads/master", "committer_date": 1686028601000, "content_id": "8b58338fd2251f640b090c5035eb56071d95a6a6", "detected_licenses": [ "MIT" ], "directory_id": "7c6e345237c99e03d2ff7dfade38c658b9a55340", "extension": "py", "filename": "lppls_cmaes.py", "fork_events_count": 104, "gha_created_at": 1587141083000, "gha_event_created_at": 1686028602000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 256555314, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3790, "license": "MIT", "license_type": "permissive", "path": "/lppls/lppls_cmaes.py", "provenance": "stack-edu-0054.json.gz:574965", "repo_name": "Boulder-Investment-Technologies/lppls", "revision_date": 1686028601000, "revision_id": "74db49a60fa9ec3ecb417e815afb3615d45b0073", "snapshot_id": "68db2c8dc3530d19e1c55e1b3b07ad6877e42b27", "src_encoding": "UTF-8", "star_events_count": 301, "url": "https://raw.githubusercontent.com/Boulder-Investment-Technologies/lppls/74db49a60fa9ec3ecb417e815afb3615d45b0073/lppls/lppls_cmaes.py", "visit_date": "2023-06-10T03:19:03.230175" }
2.625
stackv2
import cma as cm from lppls.lppls import LPPLS # import multiprocessing as mp import numpy as np from scipy.stats import chisquare class LPPLSCMAES(LPPLS): def __init__(self, observations): super().__init__(observations) self.observations = observations def fun_restricted(self, x, obs): """ Define the objective function for the CMA-ES optimizer Args: x (List): objective variable obs (): blah Returns: float: error of the objective function """ tc, m, w = x try: rM = super().matrix_equation(obs, tc, m, w) a, b, c1, c2 = rM[:, 0].tolist() except Exception as e: a, b, c1, c2 = 0, 0, 0, 0 print(e) t = obs[0, :] res = super().lppls(t, tc, m, w, a, b, c1, c2) # make nan or inf to zero res[np.isnan(res)] = 0. res[np.isinf(res)] = 0. # calculate the chi square error, _ = chisquare(f_obs=res, f_exp=obs[1, :]) return error def fit(self, max_iteration=1000, factor_sigma=0.1, pop_size=1, obs=None): """ Runs the optimazation loop Args: max_iteration (int, optional): maximum number of iterations. Defaults to 2500. factor_sigma (float, optiona): factor to multiplying the range of the bounded values pop_size (int, optional): population size for CMA ES cores (int, optional): number of parallel runs obs (): Returns: [List]: all optimized and calculated values for tc, m, w, a, b, c, c1, c2 """ if obs is None: obs = self.observations # best guess of the starting values m = 0.5 w = 9. # INFO: so far as I've understand the tc time this cannot be smaller als the max time of the time series tc = np.max(obs[0, :]) # define options for CMAES opts = cm.CMAOptions() # here we define the initial search steps for CMAES usually I use to calculate the range of the # max and min bounds of the value and then apply a factor for sigma opts.set('CMA_stds', [factor_sigma * tc, factor_sigma * (0.9 - 0.1), factor_sigma * (13. - 6.)]) opts.set('bounds', [(tc, 0.1, 6.), (np.inf, 0.9, 13.)]) opts.set('popsize', 10 * 2 ** pop_size) es = cm.CMAEvolutionStrategy(x0=[tc, m, w], sigma0=1., inopts=opts) # here we go while not es.stop() and es.countiter <= max_iteration: solutions = es.ask() solution = [self.fun_restricted(s, obs) for s in solutions] es.tell(solutions, solution) es.logger.add() # write data to disc to be plotted es.disp() # after while loop print infos and plot the final # es.result_pretty() # cm.plot() # plt.savefig('cmaes.png', dpi=300) # get best results t1 = obs[0, 0] t2 = obs[0, -1] if es.result.xbest is not None: tc, m, w = es.result.xbest try: rM = super().matrix_equation(obs, tc, m, w) a, b, c1, c2 = rM[:, 0].tolist() except Exception as e: a, b, c1, c2 = 0, 0, 0, 0 print(e) c = self.get_c(c1, c2) # Use sklearn format for storing fit params -> original code from lppls package for coef in ['tc', 'm', 'w', 'a', 'b', 'c', 'c1', 'c2']: self.coef_[coef] = eval(coef) O = self.get_oscillations(w, tc, t1, t2) D = self.get_damping(m, w, b, c) return tc, m, w, a, b, c, c1, c2, O, D else: return 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
115
31.96
112
16
1,088
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_d95149cdc75c43c9_1d20d8b8", "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": 108, "line_end": 108, "column_start": 36, "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/tmprvd6_wj2/d95149cdc75c43c9.py", "start": {"line": 108, "col": 36, "offset": 3566}, "end": {"line": 108, "col": 46, "offset": 3576}, "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" ]
[ 108 ]
[ 108 ]
[ 36 ]
[ 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" ]
lppls_cmaes.py
/lppls/lppls_cmaes.py
Boulder-Investment-Technologies/lppls
MIT
2024-11-18T20:31:22.319733+00:00
1,498,587,722,000
b7d2d97b879fde8e04bdb2409d7884703d39aaf3
2
{ "blob_id": "b7d2d97b879fde8e04bdb2409d7884703d39aaf3", "branch_name": "refs/heads/master", "committer_date": 1498587722000, "content_id": "855b471ecedeb7a8a6ce38bf5830a9135337fd2a", "detected_licenses": [ "Apache-2.0" ], "directory_id": "b46d9132d9f33556770a16dea15582e58b8a8963", "extension": "py", "filename": "star.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": 5228, "license": "Apache-2.0", "license_type": "permissive", "path": "/build/lib/hydra_pkg/star.py", "provenance": "stack-edu-0054.json.gz:574969", "repo_name": "tetomonti/Hydra", "revision_date": 1498587722000, "revision_id": "f4b1a1a8f1de983e963c418a159bf4d5537e7822", "snapshot_id": "897c52c7a6d201d8b780b83f1679759aaa5b6743", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tetomonti/Hydra/f4b1a1a8f1de983e963c418a159bf4d5537e7822/build/lib/hydra_pkg/star.py", "visit_date": "2021-06-20T05:32:55.522539" }
2.390625
stackv2
#Copyright 2015 Daniel Gusenleitner, Stefano Monti #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. """Star module This module contains functions for initializing all tophat specific variables and a wrapper that that runs tophat using those parameters on a single sample. """ import subprocess import os import sys from hydra_pkg import module_helper as MODULE_HELPER def init(param): """Initialization function that checks the all relevant tophat parameters :Parameter param: dictionary that contains all general RNASeq pipeline parameters """ MODULE_HELPER.check_parameter(param, key='star_exec', dtype=str) MODULE_HELPER.check_parameter(param, key='star_index', dtype=str, checkfile=True) MODULE_HELPER.check_parameter(param, key='outFilterType', dtype=str) MODULE_HELPER.check_parameter(param, key='outFilterMultimapNmax', dtype=str) MODULE_HELPER.check_parameter(param, key='alignSJoverhangMin', dtype=str) MODULE_HELPER.check_parameter(param, key='alignSJDBoverhangMin', dtype=str) MODULE_HELPER.check_parameter(param, key='outFilterMismatchNmax', dtype=str) MODULE_HELPER.check_parameter(param, key='outFilterMismatchNoverLmax', dtype=str) MODULE_HELPER.check_parameter(param, key='alignIntronMin', dtype=str) MODULE_HELPER.check_parameter(param, key='alignIntronMax', dtype=str) MODULE_HELPER.check_parameter(param, key='alignMatesGapMax', dtype=str) MODULE_HELPER.check_parameter(param, key='outputSAMtype', allowed=['BAM_SortedByCoordinate', 'BAM_unsorted'], dtype=str) def main(): """Main function that is run on each samples, which in turn calls runs star on a sample. """ param = MODULE_HELPER.initialize_module() #run create output directory outdir = param['module_dir']+param['outstub']+'/' if not os.path.exists(outdir): os.makedirs(outdir) #build tophat call: call = [param['star_exec']] #add the directory where we built the star index call.append('--genomeDir') call.append(param['star_index']) #add the number of processors to use call.append('runThreadN') call.append(param['num_processors']) #add all the optional parameters call.append('--outFilterType') call.append(param['outFilterType']) call.append('--outFilterMultimapNmax') call.append(param['outFilterMultimapNmax']) call.append('--alignSJoverhangMin') call.append(param['alignSJoverhangMin']) call.append('--alignSJDBoverhangMin') call.append(param['alignSJDBoverhangMin']) call.append('--outFilterMismatchNmax') call.append(param['outFilterMismatchNmax']) call.append('--outFilterMismatchNoverLmax') call.append(param['outFilterMismatchNoverLmax']) call.append('--alignIntronMin') call.append(param['alignIntronMin']) call.append('--alignIntronMax') call.append(param['alignIntronMax']) call.append('--alignMatesGapMax') call.append(param['alignMatesGapMax']) if (param['outputSAMtype'] == 'BAM_SortedByCoordinate'): call.append('--outSAMtype') call.append('BAM') call.append('SortedByCoordinate') outfile = 'Aligned.sortedByCoord.out.bam' elif (param['outputSAMtype'] == 'BAM_unsorted'): call.append('--outSAMtype') call.append('BAM') call.append('Unsorted') outfile = 'Aligned.out.bam' else: outfile = 'Aligned.out.sam' #add the proper output directories call.append('--outFileNamePrefix') call.append(outdir) #specify whether the fastq files are zipped if param['zipped_fastq']: call.append('--readFilesCommand') call.append('gunzip') call.append('-c') #adding the files we want to work on call.append('--readFilesIn') call.append(param['working_file']) #if paired add second working file if param['paired']: call.append(param['working_file2']) param['file_handle'].write('CALL: '+' '.join(call)+'\n') output, error = subprocess.Popen(call, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() param['file_handle'].write(error) param['file_handle'].write(output) #check if the run was successful if not os.path.exists(outdir+'SJ.out.tab'): param['file_handle'].write('Star did not run successfully...') sys.exit(0) #wrap up and return the current workingfile MODULE_HELPER.wrapup_module(param, [outdir+outfile], remove_intermediate=True)
137
37.16
85
12
1,158
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_6261fd10505a932f_6cf27600", "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": 118, "line_end": 120, "column_start": 21, "column_end": 61, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmprvd6_wj2/6261fd10505a932f.py", "start": {"line": 118, "col": 21, "offset": 4614}, "end": {"line": 120, "col": 61, "offset": 4758}, "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" ]
[ 118 ]
[ 120 ]
[ 21 ]
[ 61 ]
[ "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" ]
star.py
/build/lib/hydra_pkg/star.py
tetomonti/Hydra
Apache-2.0
2024-11-18T20:31:23.163522+00:00
1,520,533,770,000
6d1f8ebe4cd288a0c0f33a60f17c7f08cdac28d6
2
{ "blob_id": "6d1f8ebe4cd288a0c0f33a60f17c7f08cdac28d6", "branch_name": "refs/heads/master", "committer_date": 1520533770000, "content_id": "711b3ac56638cea68389cdcef0260552250c7171", "detected_licenses": [ "Apache-2.0" ], "directory_id": "fb149bf689c3e2bbca8cea4b68dc357b2d224fee", "extension": "py", "filename": "user_record.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 116425390, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6837, "license": "Apache-2.0", "license_type": "permissive", "path": "/pythiam/lib/user_record.py", "provenance": "stack-edu-0054.json.gz:574983", "repo_name": "rsutton/pythiam", "revision_date": 1520533770000, "revision_id": "fc1fd9f690bb32ca43809abdd89f0d83ad5deb7a", "snapshot_id": "331b493af53c6f504c8094b63496e4dc8ce53297", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/rsutton/pythiam/fc1fd9f690bb32ca43809abdd89f0d83ad5deb7a/pythiam/lib/user_record.py", "visit_date": "2021-09-08T08:32:45.392875" }
2.5
stackv2
import json import os.path import pickle from pythiam.lib.iam_manager import IAMManager from pythiam.lib.utils import file_age class UserRecordManager(object): def __init__(self, *args, **kwargs): self._client = None self._filename = kwargs.get('filename') or 'data.db' self._iam = None self._records = {} def with_file(self, filename): self._filename = filename self.load_data() return self def with_iam(self, iam): self._iam = iam return self @property def filename(self): return self._filename @property def iam(self): if self._iam is None: self._iam = IAMManager() return self._iam @property def records(self): return self._records @records.setter def records(self, value): self._records = value def create_user_record(self, user_name, data): record = UserRecord(user_name) self._set_iam_data(record, data) self._set_user_access_keys(record) self._set_user_groups(record) self._set_login_profile(record) self._set_inline_policies(record) self._set_attached_policies(record) self._set_mfa_devices(record) self.records[user_name] = record self.write_record_to_disk(record) return record def delete_user_record(self, user_name): new_records = dict(self.records) del new_records[user_name] self.records = new_records self.write_all_records_to_disk() def get_user_record(self, user_name): record = self._records.get(user_name) if record is None: print("User account {} not found in data file".format(user_name)) print("Looking up account in IAM") user_data = self.iam.get_user(user_name) if not user_data: print("... not found in IAM") else: record = self.create_user_record(user_name, user_data) return record def load_data(self): if not os.path.exists(self.filename): print("User record data file not found. Creating new file: {}".format(self.filename)) with open(self.filename, 'wb') as f: for u in self.iam.list_users(): n = u.get('UserName') print("Processing record: {}".format(n)) r = self.create_user_record(n, u) self.write_record_to_disk(r) if file_age(self.filename) > 2: print("Data file is more than 2 days old, consider refreshing.") with open(self.filename, 'rb') as f: while True: try: r = pickle.load(f) assert isinstance(r, UserRecord) self.records[r.user_name] = r except EOFError: break def write_all_records_to_disk(self): # replace data file with contents of new_records with open(self.filename, 'wb') as f: f.truncate() with open(self.filename, 'ab') as f: for k in self.records.keys(): pickle.dump(self.records[k], f) def write_record_to_disk(self, record): with open(self.filename, 'ab') as f: pickle.dump(record, f) @staticmethod def _set_iam_data(record, data): """ { Path: /, UserName: str, UserId: str, Arn: str, CreateDate: datetime, PasswordLastUsed: datetime } """ record.iam_data = data def _set_login_profile(self, record): record.login_profile = self.iam.get_login_profile(record.user_name) def _set_attached_policies(self, record): for p in self.iam.list_attached_policies(record.user_name): record.attached_policies.append(p.get('PolicyArn')) def _set_inline_policies(self, record): for p in self.iam.list_user_policies(record.user_name): record.inline_policies.append(p) def _set_user_access_keys(self, record): for k in self.iam.list_access_keys(record.user_name): key_id = k.get('AccessKeyId') record.access_keys[key_id] = self.iam.get_access_key_last_used(key_id) def _set_user_groups(self, record): for g in self.iam.list_groups_for_user(record.user_name): record.groups.append(g.get('GroupName')) def _set_mfa_devices(self, record): for m in self.iam.list_mfa_devices(record.user_name): record.mfa_devices.append(m.get('SerialNumber')) class UserRecord(object): def __init__(self, user_name): self._access_keys = {} self._attached_policies = [] self._groups = [] self._iam_data = {} self._inline_policies = [] self._login_profile = {} self._mfa_devices = [] self._user_name = user_name def __repr__(self): return json.dumps(self.__dict__, default=str) @property def access_keys(self): return self._access_keys @property def arn(self): return self._iam_data.get('Arn') @property def attached_policies(self): return self._attached_policies @property def creation_date(self): return self._iam_data.get('CreateDate') @property def groups(self): return self._groups @property def iam_data(self): return self._iam_data @iam_data.setter def iam_data(self, value): self._iam_data = value @property def inline_policies(self): return self._inline_policies @property def login_profile(self): return self._login_profile @login_profile.setter def login_profile(self, value): self._login_profile = value @property def mfa_devices(self): return self._mfa_devices @property def password_last_used(self): return self._iam_data.get('PasswordLastUsed') @property def user_groups(self): return self._groups @property def user_id(self): return self._iam_data.get('UserId') @property def user_name(self): return self._user_name @property def last_activity(self): events = list() # add account creation date events.append(self.iam_data.get('CreateDate')) # last password usage d = self.password_last_used if d: events.append(self.password_last_used) # last access key usage for k in self.access_keys: d = self.access_keys.get(k).get('LastUsedDate') if d: events.append(d) # return most recent events = sorted(events, reverse=True) return events[0]
240
27.49
97
18
1,502
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_46578dda894ca21b_89cdebfc", "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": 90, "line_end": 90, "column_start": 25, "column_end": 39, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmprvd6_wj2/46578dda894ca21b.py", "start": {"line": 90, "col": 25, "offset": 2744}, "end": {"line": 90, "col": 39, "offset": 2758}, "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_46578dda894ca21b_14383b72", "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": 17, "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/tmprvd6_wj2/46578dda894ca21b.py", "start": {"line": 102, "col": 17, "offset": 3193}, "end": {"line": 102, "col": 48, "offset": 3224}, "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_46578dda894ca21b_67c67c91", "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": 106, "line_end": 106, "column_start": 13, "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/tmprvd6_wj2/46578dda894ca21b.py", "start": {"line": 106, "col": 13, "offset": 3327}, "end": {"line": 106, "col": 35, "offset": 3349}, "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" ]
[ 90, 102, 106 ]
[ 90, 102, 106 ]
[ 25, 17, 13 ]
[ 39, 48, 35 ]
[ "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" ]
user_record.py
/pythiam/lib/user_record.py
rsutton/pythiam
Apache-2.0
2024-11-18T20:31:27.616188+00:00
1,509,161,824,000
72aca226faba8b40e681f1c9435ca4f06f983778
3
{ "blob_id": "72aca226faba8b40e681f1c9435ca4f06f983778", "branch_name": "refs/heads/master", "committer_date": 1509161824000, "content_id": "976c220282b4f6bb8d2ec94915e407ebd91c1703", "detected_licenses": [ "MIT" ], "directory_id": "db02393519a036f927f425fa83b87c7111d53839", "extension": "py", "filename": "temp_parsing.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 106861689, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1273, "license": "MIT", "license_type": "permissive", "path": "/src/temp_parsing.py", "provenance": "stack-edu-0054.json.gz:575000", "repo_name": "cqlanus/weather_parsing", "revision_date": 1509161824000, "revision_id": "2e90b02baa0060bb99355decacbb4c4a9e8655cb", "snapshot_id": "343f9aeeb27f3d1dffe8655ad98de98741f1602d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cqlanus/weather_parsing/2e90b02baa0060bb99355decacbb4c4a9e8655cb/src/temp_parsing.py", "visit_date": "2021-07-18T19:54:36.376356" }
2.78125
stackv2
import csv import psycopg2 import secrets def parse(filename, tableName): conn = psycopg2.connect("dbname=gardnly2 user=cqlanus password=" + secrets.password) cur = conn.cursor() with open(filename, 'rt') as csvfile: rows = csv.reader(csvfile, delimiter=' ') for row in rows: rowStr = ', '.join(row) formattedRow = rowStr.replace(' ,', '').split(', ') stationId = formattedRow[0] wpan = stationId[6:]; onlyTemps = formattedRow[2:] tempNums = list(map(parseTemp, onlyTemps)) month = int(formattedRow[1]) data = {'stationId': formattedRow[0], 'month': int(formattedRow[1]), 'days': tempNums} print(data) cur.execute("INSERT INTO " + tableName + " (station_id, wpan, month, days) VALUES (%s, %s, %s, %s)", (stationId, wpan, month, tempNums)) conn.commit() cur.close() conn.close() def parseTemp(temp): if len(temp) == 4: return float(temp[0:2] + '.' + temp[2]) elif len(temp) == 5 and temp[0].isdigit(): return float(temp[0:3] + '.' + temp[3]) parse('../data/dly-tmax-normal.csv','daily_max_temps') parse('../data/dly-tmin-normal.csv', 'daily_min_temps')
37
33.41
112
15
337
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_c745d51650c25bc0_6f4ec41d", "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": 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/tmprvd6_wj2/c745d51650c25bc0.py", "start": {"line": 10, "col": 10, "offset": 199}, "end": {"line": 10, "col": 30, "offset": 219}, "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.sqli.psycopg-sqli_c745d51650c25bc0_d9f9780a", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.sqli.psycopg-sqli", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected string concatenation with a non-literal variable in a psycopg2 Python SQL statement. This could lead to SQL injection if the variable is user-controlled and not properly sanitized. In order to prevent SQL injection, use parameterized queries or prepared statements instead. You can use prepared statements by creating a 'sql.SQL' string. You can also use the pyformat binding style to create parameterized queries. For example: 'cur.execute(SELECT * FROM table WHERE name=%s, user_input)'", "remediation": "", "location": {"file_path": "unknown", "line_start": 22, "line_end": 23, "column_start": 13, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://www.psycopg.org/docs/sql.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.sqli.psycopg-sqli", "path": "/tmp/tmprvd6_wj2/c745d51650c25bc0.py", "start": {"line": 22, "col": 13, "offset": 755}, "end": {"line": 23, "col": 56, "offset": 911}, "extra": {"message": "Detected string concatenation with a non-literal variable in a psycopg2 Python SQL statement. This could lead to SQL injection if the variable is user-controlled and not properly sanitized. In order to prevent SQL injection, use parameterized queries or prepared statements instead. You can use prepared statements by creating a 'sql.SQL' string. You can also use the pyformat binding style to create parameterized queries. For example: 'cur.execute(SELECT * FROM table WHERE name=%s, user_input)'", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "references": ["https://www.psycopg.org/docs/sql.html"], "category": "security", "technology": ["psycopg"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_c745d51650c25bc0_4ccfec29", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 22, "line_end": 23, "column_start": 13, "column_end": 56, "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/tmprvd6_wj2/c745d51650c25bc0.py", "start": {"line": 22, "col": 13, "offset": 755}, "end": {"line": 23, "col": 56, "offset": 911}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-89", "CWE-89" ]
[ "rules.python.lang.security.audit.sqli.psycopg-sqli", "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "HIGH" ]
[ 22, 22 ]
[ 23, 23 ]
[ 13, 13 ]
[ 56, 56 ]
[ "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Detected string concatenation with a non-literal variable in a psycopg2 Python SQL statement. This could lead to SQL injection if the variable is user-controlled and not properly sanitized. In order to prevent SQL injection, use parameterized queries or prepared statements instead. You can use prepared statements ...
[ 5, 7.5 ]
[ "LOW", "LOW" ]
[ "HIGH", "HIGH" ]
temp_parsing.py
/src/temp_parsing.py
cqlanus/weather_parsing
MIT
2024-11-18T20:31:34.655620+00:00
1,572,898,414,000
6884ba0c104fd259454a6aa728cef1775f03dccc
3
{ "blob_id": "6884ba0c104fd259454a6aa728cef1775f03dccc", "branch_name": "refs/heads/master", "committer_date": 1572898414000, "content_id": "b5215b27f038e98888075f0553fc323fb489e554", "detected_licenses": [ "MIT" ], "directory_id": "16aabd7d01d327815b64fe1ee39e1c42e07acdfa", "extension": "py", "filename": "print_genomic_in_final_exons.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 175061699, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1540, "license": "MIT", "license_type": "permissive", "path": "/genomic_transcripts/last_exons/print_genomic_in_final_exons.py", "provenance": "stack-edu-0054.json.gz:575080", "repo_name": "dewyman/TALON-paper-2019", "revision_date": 1572898414000, "revision_id": "8644b34573d6a5924e8d84a234fd0fcbf010c233", "snapshot_id": "b17e1139afabd350c72fcc9d7078f49de746c046", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/dewyman/TALON-paper-2019/8644b34573d6a5924e8d84a234fd0fcbf010c233/genomic_transcripts/last_exons/print_genomic_in_final_exons.py", "visit_date": "2020-04-28T06:31:33.907456" }
2.78125
stackv2
from optparse import OptionParser import os def getOptions(): parser = OptionParser() parser.add_option("--f", dest = "infile", help = "Input GTF file of genomic transcripts", metavar = "FILE", type = "string") parser.add_option("--e", dest = "exons", help = "Input BED file of final exons", metavar = "FILE", type = "string") parser.add_option("--p", dest = "prefix", help = "Prefix for intermediate files", metavar = "FILE", type = "string") (options, args) = parser.parse_args() return options def main(): options = getOptions() infile = options.infile exons = options.exons bed = options.prefix + "genomic.bed" # Get genomic transcripts in BED format cmd = """awk -v OFS='\t' '{if($3 == "transcript") print $1,$4-1,$5,".",".",$7}' """ + infile + " > " + bed os.system(cmd) # Bedtools intersect it btools_out = options.prefix + "nGenomic_intersect_lastExons.bed" bedtools_cmd = """bedtools intersect -a %s \ -b %s \ -u \ -s | wc -l > %s""" % (bed, exons, btools_out) os.system(bedtools_cmd) # Now, collect the results for output with open(btools_out) as f: overlap_size = int(f.readline().strip()) total_genomic = sum(1 for line in open(bed)) percent_overlap = round(overlap_size*100./total_genomic) print("\t".join([options.prefix, str(overlap_size), str(total_genomic), str(percent_overlap) + "%"])) if __name__ == '__main__': main()
46
32.48
110
14
410
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_f2ee3e03239176fb_39c89324", "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": 26, "line_end": 26, "column_start": 5, "column_end": 19, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/tmprvd6_wj2/f2ee3e03239176fb.py", "start": {"line": 26, "col": 5, "offset": 844}, "end": {"line": 26, "col": 19, "offset": 858}, "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_f2ee3e03239176fb_048a0c09", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 34, "line_end": 34, "column_start": 5, "column_end": 28, "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/tmprvd6_wj2/f2ee3e03239176fb.py", "start": {"line": 34, "col": 5, "offset": 1135}, "end": {"line": 34, "col": 28, "offset": 1158}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_f2ee3e03239176fb_fdb6877e", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 37, "line_end": 37, "column_start": 10, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmprvd6_wj2/f2ee3e03239176fb.py", "start": {"line": 37, "col": 10, "offset": 1211}, "end": {"line": 37, "col": 26, "offset": 1227}, "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_f2ee3e03239176fb_8b8551e4", "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": 40, "line_end": 40, "column_start": 39, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmprvd6_wj2/f2ee3e03239176fb.py", "start": {"line": 40, "col": 39, "offset": 1322}, "end": {"line": 40, "col": 48, "offset": 1331}, "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", "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" ]
[ 26, 34 ]
[ 26, 34 ]
[ 5, 5 ]
[ 19, 28 ]
[ "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" ]
print_genomic_in_final_exons.py
/genomic_transcripts/last_exons/print_genomic_in_final_exons.py
dewyman/TALON-paper-2019
MIT
2024-11-18T20:31:34.760539+00:00
1,632,480,663,000
25b301235480ca549e84db76d06f96130eb476a9
2
{ "blob_id": "25b301235480ca549e84db76d06f96130eb476a9", "branch_name": "refs/heads/main", "committer_date": 1632480663000, "content_id": "7c351a2cc83df241b48fed5d033df3f5a993e8bf", "detected_licenses": [ "MIT" ], "directory_id": "9d0e84f9478ff0095f06e3aa00c831fc9ed16485", "extension": "py", "filename": "rpc_server.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 308781804, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2126, "license": "MIT", "license_type": "permissive", "path": "/rpc_server.py", "provenance": "stack-edu-0054.json.gz:575082", "repo_name": "cyckun/abe_enc_server", "revision_date": 1632480663000, "revision_id": "5a384bb26d5c1bf5520bf4c6d531bcf30ea1ae88", "snapshot_id": "d82779839eabeab1678e1aa3dc6460133eb2dd04", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/cyckun/abe_enc_server/5a384bb26d5c1bf5520bf4c6d531bcf30ea1ae88/rpc_server.py", "visit_date": "2023-08-17T08:00:38.783230" }
2.375
stackv2
# -*- coding: utf-8 -*- """ :author: Cao YongChao :mail: cyckun@aliyun.com :copyright: © 2020 Cao YongChao :license: MIT, see LICENSE for more details. """ from __future__ import print_function import pyopenabe from xmlrpc.server import SimpleXMLRPCServer # 调用函数 def respon_string(str): return "get string:%s"%str class cpabe(): def __init__(self): self.openabe = pyopenabe.PyOpenABE() self.cpabe = self.openabe.CreateABEContext("CP-ABE") self.cpabe.generateParams() def enc(self, message, policy): print("enc service is called.") ct = self.cpabe.encrypt(policy, message.data) return ct def dec(self, ct, username): key_path = "./keys/" + username + "_sk.txt" with open(key_path, "rb") as f: sk = f.read() f.close() self.cpabe.importUserKey(username, sk) print("ddkdk, ", type(ct), type(username)) try: pt = self.cpabe.decrypt(username, ct.data) # 解析返回错误,高优 print("service dec pt =", pt) if pt == 0 or len(pt) < 2: return b"DEC FAIL" return pt except Exception as e: print(e) return b"DEC FAIL0" def generate_userkey(self, username, userattri): try: self.cpabe.keygen(userattri, username) except: return "GENKEY FAIL" uk = self.cpabe.exportUserKey(username) # should write to db; filepath = "./keys/" + username + "_sk.txt" with open(filepath, 'wb') as f: f.write(uk) f.close() return uk if __name__ == '__main__': server = SimpleXMLRPCServer(('localhost', 8888)) # 初始化 server.register_function(respon_string, "get_string") # 注册函数 alg = cpabe() server.register_function(alg.enc, "cpabe_enc_cli") server.register_function(alg.dec, "cpabe_dec_cli") server.register_function(alg.generate_userkey, "cpabe_usrkey") print ("Listening for Client") server.serve_forever() # 保持等待调用状态
71
28.14
68
13
546
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xmlrpc_261ae6209b3c3457_c9e8a458", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xmlrpc", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 11, "line_end": 11, "column_start": 1, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": "CWE-776: Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://pypi.org/project/defusedxml/", "title": null}, {"url": "https://docs.python.org/3/library/xml.html#xml-vulnerabilities", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xmlrpc", "path": "/tmp/tmprvd6_wj2/261ae6209b3c3457.py", "start": {"line": 11, "col": 1, "offset": 229}, "end": {"line": 11, "col": 45, "offset": 273}, "extra": {"message": "Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead.", "metadata": {"cwe": ["CWE-776: Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion')"], "owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "source-rule-url": "https://github.com/PyCQA/bandit/blob/07f84cb5f5e7c1055e6feaa0fe93afa471de0ac3/bandit/blacklists/imports.py#L160", "references": ["https://pypi.org/project/defusedxml/", "https://docs.python.org/3/library/xml.html#xml-vulnerabilities"], "category": "security", "technology": ["python"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-776" ]
[ "rules.python.lang.security.use-defused-xmlrpc" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 11 ]
[ 11 ]
[ 1 ]
[ 45 ]
[ "A04:2017 - XML External Entities (XXE)" ]
[ "Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead." ]
[ 7.5 ]
[ "LOW" ]
[ "MEDIUM" ]
rpc_server.py
/rpc_server.py
cyckun/abe_enc_server
MIT
2024-11-18T20:31:34.967467+00:00
1,589,080,113,000
ed759e5a170ed24f2716df3e22862840ea335725
3
{ "blob_id": "ed759e5a170ed24f2716df3e22862840ea335725", "branch_name": "refs/heads/master", "committer_date": 1589080113000, "content_id": "fee4082e6d7a93e05e42ea1c23e6618d69df525c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "cd54ada609fd16840aa5ad2979df5e33f7b14d37", "extension": "py", "filename": "safety_merge_annotations.py", "fork_events_count": 0, "gha_created_at": 1585041896000, "gha_event_created_at": 1585041897000, "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 249664315, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2126, "license": "Apache-2.0", "license_type": "permissive", "path": "/research/object_detection/dataset_tools/safety_merge_annotations.py", "provenance": "stack-edu-0054.json.gz:575085", "repo_name": "tealeeseng/models", "revision_date": 1589080113000, "revision_id": "97b8db44c99cd552621cd2e95173e54350f88034", "snapshot_id": "ff8eed1e9359cccd0b82592e8f20c706fd2fa794", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tealeeseng/models/97b8db44c99cd552621cd2e95173e54350f88034/research/object_detection/dataset_tools/safety_merge_annotations.py", "visit_date": "2021-04-20T07:05:06.037395" }
2.640625
stackv2
import glob import tensorflow as tf import sys import os import pandas as pd import shutil import xml.etree.ElementTree as ET FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string('dir1', None, 'first folder') tf.app.flags.DEFINE_string('dir2', None, '2nd folder') tf.app.flags.DEFINE_string('annotation_out', 'annotation_out', 'Merged Annotation output folder') def main(unused_argv): tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.DEBUG) dir1 = FLAGS.dir1 dir2 = FLAGS.dir2 dest_dir = FLAGS.annotation_out if dir1 is None or dir2 is None: tf.compat.v1.logging.warn('Please provides 2 folders for merging. Output folder is annotation_out by default.') tf.compat.v1.logging.warn('--dir1=dir1 --dir2=dir2') sys.exit(0) dir1_files = glob.glob(os.path.join(dir1,'**', '*.xml'), recursive=True) dir2_files = glob.glob(os.path.join(dir2, '**', '*.xml'), recursive=True) ## copying no matching files to annotation dir first dir1_set = build_set(dir1_files, dir1) dir2_set = build_set(dir2_files, dir2) os.makedirs(dest_dir, exist_ok=True) copy_files_no_matching(dir1_set, dir2_set, dir1, dest_dir ) copy_files_no_matching(dir2_set, dir1_set, dir2, dest_dir ) matched_set = dir1_set.intersection(dir2_set) for f in matched_set: tree = ET.parse(dir2+f) objects = tree.findall('object') first_tree = ET.parse(dir1+f) for o in objects: first_tree.getroot().append(o) first_tree.write(dest_dir+f) tf.logging.debug('Merged to %s', dest_dir+f) tf.logging.debug(' == END ==') def copy_files_no_matching(dir1_set, dir2_set, dir, dest_dir): files_excluded = dir1_set.difference(dir2_set) for f in files_excluded: tf.logging.debug('copied to %s',dest_dir+f) shutil.copyfile(dir+f, dest_dir+f) def build_set(dir1_files, dir1): df = pd.DataFrame(dir1_files, columns=['name']) df['name']=df['name'].str.replace(dir1,'') name_set = set(df['name']) return name_set if __name__ == '__main__': main(sys.argv)
78
26.26
119
13
554
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_da98e211732432a8_4080c3a0", "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": 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/tmprvd6_wj2/da98e211732432a8.py", "start": {"line": 7, "col": 1, "offset": 91}, "end": {"line": 7, "col": 35, "offset": 125}, "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_da98e211732432a8_1d18b29b", "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(dir2+f)", "location": {"file_path": "unknown", "line_start": 50, "line_end": 50, "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/tmprvd6_wj2/da98e211732432a8.py", "start": {"line": 50, "col": 16, "offset": 1348}, "end": {"line": 50, "col": 32, "offset": 1364}, "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(dir2+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"}}}, {"finding_id": "semgrep_rules.python.lang.security.use-defused-xml-parse_da98e211732432a8_3abc06dc", "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(dir1+f)", "location": {"file_path": "unknown", "line_start": 53, "line_end": 53, "column_start": 22, "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-parse", "path": "/tmp/tmprvd6_wj2/da98e211732432a8.py", "start": {"line": 53, "col": 22, "offset": 1428}, "end": {"line": 53, "col": 38, "offset": 1444}, "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(dir1+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"}}}]
3
true
[ "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" ]
[ "security", "security", "security" ]
[ "LOW", "MEDIUM", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH" ]
[ 7, 50, 53 ]
[ 7, 50, 53 ]
[ 1, 16, 22 ]
[ 35, 32, 38 ]
[ "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 ]
[ "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM" ]
safety_merge_annotations.py
/research/object_detection/dataset_tools/safety_merge_annotations.py
tealeeseng/models
Apache-2.0
2024-11-18T20:31:37.551815+00:00
1,535,791,374,000
b0f18afde1a0cec1f4c7614e4dbb302189895c4e
3
{ "blob_id": "b0f18afde1a0cec1f4c7614e4dbb302189895c4e", "branch_name": "refs/heads/master", "committer_date": 1535791374000, "content_id": "7fadbbd8f2944060986c967557c1101a7c8b7923", "detected_licenses": [ "MIT" ], "directory_id": "c75b05655f5671e070a799866d228a0f5ac76738", "extension": "py", "filename": "downloader.py", "fork_events_count": 0, "gha_created_at": 1535790945000, "gha_event_created_at": 1535791375000, "gha_language": null, "gha_license_id": "MIT", "github_id": 146982070, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 701, "license": "MIT", "license_type": "permissive", "path": "/framework/scrapy_plus/core/downloader.py", "provenance": "stack-edu-0054.json.gz:575116", "repo_name": "Danny2024/scrapy-3.3.3", "revision_date": 1535791374000, "revision_id": "b67c4a3c3c8f5de1aefb30312b2935b9b59afc9f", "snapshot_id": "bd01234423b523f8861800452741e34cb4f7f2bb", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Danny2024/scrapy-3.3.3/b67c4a3c3c8f5de1aefb30312b2935b9b59afc9f/framework/scrapy_plus/core/downloader.py", "visit_date": "2020-03-27T19:20:09.514263" }
2.796875
stackv2
# coding:utf8 """ 下载器模块 1.根据请求对象,发送请求,获取相应数据,封装为Reponse对象返回 """ import requests from ..http.response import Response class DownLoader(object): def get_response(self, request): if request.method.upper() == "GET": res = requests.get(request.url,headers=request.headers,params=request.params,cookies=request.cookies) elif request.method.upper() == "POST": res = requests.post(request.url,headers=request.headers, cookies=request.cookies) else: raise Exception('暂时只支持GET和POST请求') return Response(res.url,res.status_code,res.headers, res.content)
25
23.92
113
15
138
python
[{"finding_id": "semgrep_rules.python.django.security.injection.ssrf.ssrf-injection-requests_b23c93ef9acb2344_7775a4a0", "tool_name": "semgrep", "rule_id": "rules.python.django.security.injection.ssrf.ssrf-injection-requests", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Data from request object is passed to a new server-side request. This could lead to a server-side request forgery (SSRF). To mitigate, ensure that schemes and hosts are validated against an allowlist, do not forward the response to the user, and ensure proper authentication and transport-layer security in the proxied request. See https://owasp.org/www-community/attacks/Server_Side_Request_Forgery to learn more about SSRF vulnerabilities.", "remediation": "", "location": {"file_path": "unknown", "line_start": 14, "line_end": 14, "column_start": 13, "column_end": 114, "code_snippet": "requires login"}, "cwe_id": "CWE-918: Server-Side Request Forgery (SSRF)", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A10:2021 - Server-Side Request Forgery (SSRF)", "references": [{"url": "https://owasp.org/www-community/attacks/Server_Side_Request_Forgery", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.injection.ssrf.ssrf-injection-requests", "path": "/tmp/tmprvd6_wj2/b23c93ef9acb2344.py", "start": {"line": 14, "col": 13, "offset": 301}, "end": {"line": 14, "col": 114, "offset": 402}, "extra": {"message": "Data from request object is passed to a new server-side request. This could lead to a server-side request forgery (SSRF). To mitigate, ensure that schemes and hosts are validated against an allowlist, do not forward the response to the user, and ensure proper authentication and transport-layer security in the proxied request. See https://owasp.org/www-community/attacks/Server_Side_Request_Forgery to learn more about SSRF vulnerabilities.", "metadata": {"cwe": ["CWE-918: Server-Side Request Forgery (SSRF)"], "owasp": ["A10:2021 - Server-Side Request Forgery (SSRF)", "A01:2025 - Broken Access Control"], "references": ["https://owasp.org/www-community/attacks/Server_Side_Request_Forgery"], "category": "security", "technology": ["django"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "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.django.security.injection.ssrf.ssrf-injection-requests_b23c93ef9acb2344_808c8e8b", "tool_name": "semgrep", "rule_id": "rules.python.django.security.injection.ssrf.ssrf-injection-requests", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Data from request object is passed to a new server-side request. This could lead to a server-side request forgery (SSRF). To mitigate, ensure that schemes and hosts are validated against an allowlist, do not forward the response to the user, and ensure proper authentication and transport-layer security in the proxied request. See https://owasp.org/www-community/attacks/Server_Side_Request_Forgery to learn more about SSRF vulnerabilities.", "remediation": "", "location": {"file_path": "unknown", "line_start": 14, "line_end": 14, "column_start": 19, "column_end": 114, "code_snippet": "requires login"}, "cwe_id": "CWE-918: Server-Side Request Forgery (SSRF)", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A10:2021 - Server-Side Request Forgery (SSRF)", "references": [{"url": "https://owasp.org/www-community/attacks/Server_Side_Request_Forgery", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.injection.ssrf.ssrf-injection-requests", "path": "/tmp/tmprvd6_wj2/b23c93ef9acb2344.py", "start": {"line": 14, "col": 19, "offset": 307}, "end": {"line": 14, "col": 114, "offset": 402}, "extra": {"message": "Data from request object is passed to a new server-side request. This could lead to a server-side request forgery (SSRF). To mitigate, ensure that schemes and hosts are validated against an allowlist, do not forward the response to the user, and ensure proper authentication and transport-layer security in the proxied request. See https://owasp.org/www-community/attacks/Server_Side_Request_Forgery to learn more about SSRF vulnerabilities.", "metadata": {"cwe": ["CWE-918: Server-Side Request Forgery (SSRF)"], "owasp": ["A10:2021 - Server-Side Request Forgery (SSRF)", "A01:2025 - Broken Access Control"], "references": ["https://owasp.org/www-community/attacks/Server_Side_Request_Forgery"], "category": "security", "technology": ["django"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "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.requests.best-practice.use-raise-for-status_b23c93ef9acb2344_06f91c73", "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": 14, "line_end": 14, "column_start": 19, "column_end": 114, "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/tmprvd6_wj2/b23c93ef9acb2344.py", "start": {"line": 14, "col": 19, "offset": 307}, "end": {"line": 14, "col": 114, "offset": 402}, "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_b23c93ef9acb2344_8b7a6e32", "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(request.url,headers=request.headers,params=request.params,cookies=request.cookies, timeout=30)", "location": {"file_path": "unknown", "line_start": 14, "line_end": 14, "column_start": 19, "column_end": 114, "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/tmprvd6_wj2/b23c93ef9acb2344.py", "start": {"line": 14, "col": 19, "offset": 307}, "end": {"line": 14, "col": 114, "offset": 402}, "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(request.url,headers=request.headers,params=request.params,cookies=request.cookies, 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.django.security.injection.ssrf.ssrf-injection-requests_b23c93ef9acb2344_7d1c83f3", "tool_name": "semgrep", "rule_id": "rules.python.django.security.injection.ssrf.ssrf-injection-requests", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Data from request object is passed to a new server-side request. This could lead to a server-side request forgery (SSRF). To mitigate, ensure that schemes and hosts are validated against an allowlist, do not forward the response to the user, and ensure proper authentication and transport-layer security in the proxied request. See https://owasp.org/www-community/attacks/Server_Side_Request_Forgery to learn more about SSRF vulnerabilities.", "remediation": "", "location": {"file_path": "unknown", "line_start": 16, "line_end": 16, "column_start": 13, "column_end": 94, "code_snippet": "requires login"}, "cwe_id": "CWE-918: Server-Side Request Forgery (SSRF)", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A10:2021 - Server-Side Request Forgery (SSRF)", "references": [{"url": "https://owasp.org/www-community/attacks/Server_Side_Request_Forgery", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.injection.ssrf.ssrf-injection-requests", "path": "/tmp/tmprvd6_wj2/b23c93ef9acb2344.py", "start": {"line": 16, "col": 13, "offset": 462}, "end": {"line": 16, "col": 94, "offset": 543}, "extra": {"message": "Data from request object is passed to a new server-side request. This could lead to a server-side request forgery (SSRF). To mitigate, ensure that schemes and hosts are validated against an allowlist, do not forward the response to the user, and ensure proper authentication and transport-layer security in the proxied request. See https://owasp.org/www-community/attacks/Server_Side_Request_Forgery to learn more about SSRF vulnerabilities.", "metadata": {"cwe": ["CWE-918: Server-Side Request Forgery (SSRF)"], "owasp": ["A10:2021 - Server-Side Request Forgery (SSRF)", "A01:2025 - Broken Access Control"], "references": ["https://owasp.org/www-community/attacks/Server_Side_Request_Forgery"], "category": "security", "technology": ["django"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "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.django.security.injection.ssrf.ssrf-injection-requests_b23c93ef9acb2344_e587b4a8", "tool_name": "semgrep", "rule_id": "rules.python.django.security.injection.ssrf.ssrf-injection-requests", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Data from request object is passed to a new server-side request. This could lead to a server-side request forgery (SSRF). To mitigate, ensure that schemes and hosts are validated against an allowlist, do not forward the response to the user, and ensure proper authentication and transport-layer security in the proxied request. See https://owasp.org/www-community/attacks/Server_Side_Request_Forgery to learn more about SSRF vulnerabilities.", "remediation": "", "location": {"file_path": "unknown", "line_start": 16, "line_end": 16, "column_start": 19, "column_end": 94, "code_snippet": "requires login"}, "cwe_id": "CWE-918: Server-Side Request Forgery (SSRF)", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A10:2021 - Server-Side Request Forgery (SSRF)", "references": [{"url": "https://owasp.org/www-community/attacks/Server_Side_Request_Forgery", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.injection.ssrf.ssrf-injection-requests", "path": "/tmp/tmprvd6_wj2/b23c93ef9acb2344.py", "start": {"line": 16, "col": 19, "offset": 468}, "end": {"line": 16, "col": 94, "offset": 543}, "extra": {"message": "Data from request object is passed to a new server-side request. This could lead to a server-side request forgery (SSRF). To mitigate, ensure that schemes and hosts are validated against an allowlist, do not forward the response to the user, and ensure proper authentication and transport-layer security in the proxied request. See https://owasp.org/www-community/attacks/Server_Side_Request_Forgery to learn more about SSRF vulnerabilities.", "metadata": {"cwe": ["CWE-918: Server-Side Request Forgery (SSRF)"], "owasp": ["A10:2021 - Server-Side Request Forgery (SSRF)", "A01:2025 - Broken Access Control"], "references": ["https://owasp.org/www-community/attacks/Server_Side_Request_Forgery"], "category": "security", "technology": ["django"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "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.requests.best-practice.use-raise-for-status_b23c93ef9acb2344_e56539f7", "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": 19, "column_end": 94, "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/tmprvd6_wj2/b23c93ef9acb2344.py", "start": {"line": 16, "col": 19, "offset": 468}, "end": {"line": 16, "col": 94, "offset": 543}, "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_b23c93ef9acb2344_4993f736", "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(request.url,headers=request.headers, cookies=request.cookies, timeout=30)", "location": {"file_path": "unknown", "line_start": 16, "line_end": 16, "column_start": 19, "column_end": 94, "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/tmprvd6_wj2/b23c93ef9acb2344.py", "start": {"line": 16, "col": 19, "offset": 468}, "end": {"line": 16, "col": 94, "offset": 543}, "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(request.url,headers=request.headers, cookies=request.cookies, 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"}}}]
8
true
[ "CWE-918", "CWE-918", "CWE-918", "CWE-918" ]
[ "rules.python.django.security.injection.ssrf.ssrf-injection-requests", "rules.python.django.security.injection.ssrf.ssrf-injection-requests", "rules.python.django.security.injection.ssrf.ssrf-injection-requests", "rules.python.django.security.injection.ssrf.ssrf-injection-requests" ]
[ "security", "security", "security", "security" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH", "HIGH" ]
[ 14, 14, 16, 16 ]
[ 14, 14, 16, 16 ]
[ 13, 19, 13, 19 ]
[ 114, 114, 94, 94 ]
[ "A10:2021 - Server-Side Request Forgery (SSRF)", "A10:2021 - Server-Side Request Forgery (SSRF)", "A10:2021 - Server-Side Request Forgery (SSRF)", "A10:2021 - Server-Side Request Forgery (SSRF)" ]
[ "Data from request object is passed to a new server-side request. This could lead to a server-side request forgery (SSRF). To mitigate, ensure that schemes and hosts are validated against an allowlist, do not forward the response to the user, and ensure proper authentication and transport-layer security in the prox...
[ 7.5, 7.5, 7.5, 7.5 ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH", "HIGH" ]
downloader.py
/framework/scrapy_plus/core/downloader.py
Danny2024/scrapy-3.3.3
MIT
2024-11-18T20:43:21.487861+00:00
1,431,563,839,000
3ae45d7291df1dd0328eefe08e6485532fab7cce
2
{ "blob_id": "3ae45d7291df1dd0328eefe08e6485532fab7cce", "branch_name": "refs/heads/master", "committer_date": 1431563839000, "content_id": "465013c726512a437882b425ca61b1b780597a39", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "652265a7a61f64a5aad99190de9d2c18b75fd76c", "extension": "py", "filename": "ARFuncs.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 31289087, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9144, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/ARDroneSDK3/ARSDKBuildUtils-master/Utils/Python/ARFuncs.py", "provenance": "stack-edu-0054.json.gz:575198", "repo_name": "nericCU/QuadcopterProject", "revision_date": 1431563839000, "revision_id": "952f2336744511cee1a45d31399fc4bffc8e4750", "snapshot_id": "4c23c52b8a0c6912855631adce35482af16ba2d4", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/nericCU/QuadcopterProject/952f2336744511cee1a45d31399fc4bffc8e4750/ARDroneSDK3/ARSDKBuildUtils-master/Utils/Python/ARFuncs.py", "visit_date": "2020-04-22T14:34:11.178890" }
2.390625
stackv2
''' Copyright (C) 2014 Parrot SA 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 Parrot 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 OWNER 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. ''' import sys import subprocess import os import inspect import shutil import re # Print a message def ARPrint(msg, noNewLine=False): sys.stdout.write(msg) if not noNewLine: sys.stdout.write('\n') # Exit the script with an optional error code def EXIT(code): if code != 0: ARPrint('-- ABORTING --') sys.exit(code) # Class to handle 'cd' and 'cd -' class Chdir: def __init__(self, newPath, create=True, verbose=True): self.savedPath = os.getcwd() if not os.path.exists(newPath) and create: os.makedirs(newPath) os.chdir(newPath) self.verbose = verbose if verbose: try: ARLog('Entering <%(newPath)s>' % locals()) except: pass def exit(self): os.chdir(self.savedPath) if self.verbose: try: ARLog('Returning to <'+self.savedPath+'>') except: pass # Execute a bash command def ARExecute(cmdline, isShell=True, failOnError=False, printErrorMessage=True): try: if printErrorMessage: ARLog('Running <%(cmdline)s>' % locals()) subprocess.check_call(cmdline, shell=isShell) return True except subprocess.CalledProcessError as e: if printErrorMessage: ARPrint('Error while running <%(cmdline)s>' % locals()) if failOnError: EXIT(e.returncode) else: return False # Execute a bash command, and return the stdout output def ARExecuteGetStdout(args, isShell=False, failOnError=True, printErrorMessage=True): if printErrorMessage: ARLog('Running <' + ARListAsBashArg(args) + '>') p = subprocess.Popen(args, shell=isShell, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, err = p.communicate() ret = p.wait() if ret: if printErrorMessage: ARLog('Error while running <' + ARListAsBashArg(args) + '>') if failOnError: EXIT(ret) return '' return out.strip() # Checks if a given commands exists in path def ARExistsInPath(program, isShell=True): try: subprocess.check_call('which %(program)s 2>/dev/null 1>/dev/null' % locals(), shell=isShell) return True except subprocess.CalledProcessError as e: return False # Set an environment variable def ARSetEnv(var, val): os.environ[var] = val # Set an environment variable if not currenly defined # return True if the variable was added def ARSetEnvIfEmpty(var, val): if os.environ.get(var) is None: os.environ[var] = val return True return False # Unset an environment variable def ARUnsetEnv(var): if var in os.environ: os.environ.pop(var) # Set an environment variable to 'ideal' if it exists in path, else to 'fallback' def ARSetEnvIfExists(var, ideal, fallback, args=''): if ARExistsInPath(ideal): ARSetEnv(var, ideal + ' ' + args) else: ARSetEnv(var, fallback + ' ' + args) # Append a message to a file def ARAppendToFile(filename, message, doPrint=True): arfile = open(filename, 'a') arfile.write(message + '\n') arfile.close() if doPrint: ARPrint(message) # Log a message(append to the default logfile + output to console) def ARLog(message): LOGFILE = os.environ.get('ARLOGF') if not LOGFILE: LOGFILE = ARPathFromHere('build.log') ARAppendToFile(LOGFILE, message) # Init the default log file def ARInitLogFile(): LOGFILE = ARPathFromHere('build.log') ARSetEnv('ARLOGF', LOGFILE) ARDeleteIfExists(LOGFILE) # Get the absolute path from a relative path def ARPathFromHere(path): MYDIR=os.path.abspath(os.path.dirname(sys.argv[0])) if '' == MYDIR: MYDIR=os.getcwd() return '%(MYDIR)s/%(path)s' % locals() # Get the absolute path from a relative path def ARPathFromPwd(path): MYDIR=os.getcwd() return '%(MYDIR)s/%(path)s' % locals() # Transform a python list to a bash args list def ARListAsBashArg(lst): return ' '.join(lst) # Checks if file A is newer than file B def ARFileIsNewerThan(fileA, fileB): if not os.path.exists(fileA): return False if not os.path.exists(fileB): return True return os.stat(fileA).st_mtime > os.stat(fileB).st_mtime # Called at the beginning of a function to log its start with all its arguments def StartDumpArgs(**kwargs): CallerName = inspect.stack()[1][3] if len(kwargs) > 0: ARLog('Start running %(CallerName)s with args:' % locals()) else: ARLog('Start running %(CallerName)s' % locals()) for key, value in kwargs.items(): ARLog(' -- %(key)s -> %(value)s' % locals()) # Called at the end of a function to log its return status and all its arguments # (use 'return EndDumpArgs(res=True/False, args)') def EndDumpArgs(res, **kwargs): CallerName = inspect.stack()[1][3] START_MSG = 'Finished' if not res: START_MSG = 'Error while' if len(kwargs) > 0: ARLog('%(START_MSG)s running %(CallerName)s with args:' % locals()) else: ARLog('%(START_MSG)s running %(CallerName)s' % locals()) for key, value in kwargs.items(): ARLog(' -- %(key)s -> %(value)s' % locals()) return res # Copy and replace a file def ARCopyAndReplaceFile(SrcFile, DstFile): if not os.path.exists(SrcFile): raise Exception('%(SrcFile)s does not exist' % locals()) if not os.path.exists(os.path.dirname(DstFile)): os.makedirs(os.path.dirname(DstFile)) shutil.copy2(SrcFile, DstFile) # Recursive copy and replace of a directory. # Can optionnaly delete the previous content of the destination directory # instead of merging def ARCopyAndReplace(SrcRootDir, DstRootDir, deletePrevious=False): if not os.path.exists(SrcRootDir): raise Exception('%(SrcRootDir)s does not exist' % locals()) if deletePrevious: ARDeleteIfExists(DstRootDir) shutil.copytree(SrcRootDir, DstRootDir, symlinks=True) else: if not os.path.exists(DstRootDir): os.makedirs(DstRootDir) for SrcDir, directories, files in os.walk(SrcRootDir): DstDir = SrcDir.replace(SrcRootDir, DstRootDir) if not os.path.exists(DstDir): os.mkdir(DstDir) for _file in files: SrcFile = os.path.join(SrcDir, _file) DstFile = os.path.join(DstDir, _file) ARDeleteIfExists(DstFile) shutil.copy2(SrcFile, DstFile) # Delete one or multiple files/directories # Do not throw an error if the file/directory does not exists def ARDeleteIfExists(*args): for fileOrDir in args: if os.path.exists(fileOrDir): if os.path.isdir(fileOrDir): shutil.rmtree(fileOrDir) else: os.remove(fileOrDir) # Gets the number of available CPUs # If the real number can not be determined, return 1 def ARGetNumberOfCpus(): try: import multiprocessing return multiprocessing.cpu_count() except (ImportError, NotImplementedError): pass return 1 def ARReplaceEnvVars(source): envMatches = re.findall(r'%\{.*?\}%', source) for _match in envMatches: Match = _match.replace('%{', '').replace('}%', '') try: EnvMatch = os.environ[Match] source = source.replace(_match, EnvMatch) except (KeyError): ARLog('Environment variable %(Match)s is not set !' % locals()) return None return source
267
33.25
100
16
2,185
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_6487f0d636e8e6a5_fe82dd64", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 76, "line_end": 76, "column_start": 9, "column_end": 54, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"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/tmprvd6_wj2/6487f0d636e8e6a5.py", "start": {"line": 76, "col": 9, "offset": 2736}, "end": {"line": 76, "col": 54, "offset": 2781}, "extra": {"message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_6487f0d636e8e6a5_80f393e5", "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": 90, "line_end": 90, "column_start": 9, "column_end": 96, "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/tmprvd6_wj2/6487f0d636e8e6a5.py", "start": {"line": 90, "col": 9, "offset": 3275}, "end": {"line": 90, "col": 96, "offset": 3362}, "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_6487f0d636e8e6a5_df850168", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 104, "line_end": 104, "column_start": 9, "column_end": 101, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"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/tmprvd6_wj2/6487f0d636e8e6a5.py", "start": {"line": 104, "col": 9, "offset": 3720}, "end": {"line": 104, "col": 101, "offset": 3812}, "extra": {"message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_6487f0d636e8e6a5_ae6991b7", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 135, "line_end": 135, "column_start": 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/tmprvd6_wj2/6487f0d636e8e6a5.py", "start": {"line": 135, "col": 14, "offset": 4678}, "end": {"line": 135, "col": 33, "offset": 4697}, "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", "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.dangerous-subprocess-use-audit" ]
[ "security", "security", "security" ]
[ "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH" ]
[ 76, 90, 104 ]
[ 76, 90, 104 ]
[ 9, 9, 9 ]
[ 54, 96, 101 ]
[ "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "Detected subprocess ...
[ 7.5, 7.5, 7.5 ]
[ "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH" ]
ARFuncs.py
/ARDroneSDK3/ARSDKBuildUtils-master/Utils/Python/ARFuncs.py
nericCU/QuadcopterProject
BSD-3-Clause
2024-11-18T20:43:23.483418+00:00
1,632,633,716,000
a8a045266aa386a14eafdf0d91a299f0bdb8f843
3
{ "blob_id": "a8a045266aa386a14eafdf0d91a299f0bdb8f843", "branch_name": "refs/heads/master", "committer_date": 1632633716000, "content_id": "f7d7215d6cfd438dd997e2776310c596c1d0bea1", "detected_licenses": [ "MIT" ], "directory_id": "68480f3a19bf4e14f7df15caabb1347e9d30070c", "extension": "py", "filename": "run.py", "fork_events_count": 1, "gha_created_at": 1624255416000, "gha_event_created_at": 1629347153000, "gha_language": "C++", "gha_license_id": "MIT", "github_id": 378823531, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1750, "license": "MIT", "license_type": "permissive", "path": "/benchmarks/run.py", "provenance": "stack-edu-0054.json.gz:575222", "repo_name": "ljcc0930/taichi", "revision_date": 1632633716000, "revision_id": "c9b8166d7b019734438232d9b247eb3555e0d6f0", "snapshot_id": "cfcd0d8b043afe1148022fc56474462d474507e9", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/ljcc0930/taichi/c9b8166d7b019734438232d9b247eb3555e0d6f0/benchmarks/run.py", "visit_date": "2023-08-16T21:58:14.811036" }
2.5625
stackv2
import os import taichi as ti def get_benchmark_dir(): return os.path.join(ti.core.get_repo_dir(), 'benchmarks') class Case: def __init__(self, name, func): self.name = name self.func = func self.records = {} def __lt__(self, other): return self.name < other.name def __eq__(self, other): return self.name == other.name def run(self): print(f'==> {self.name}:') os.environ['TI_CURRENT_BENCHMARK'] = self.name self.func() class Suite: def __init__(self, filename): self.cases = [] print(filename) self.name = filename[:-3] loc = {} exec(f'import {self.name} as suite', {}, loc) suite = loc['suite'] case_keys = list( sorted(filter(lambda x: x.startswith('benchmark_'), dir(suite)))) self.cases = [Case(k, getattr(suite, k)) for k in case_keys] def run(self): print(f'{self.name}:') for case in sorted(self.cases): case.run() class TaichiBenchmark: def __init__(self): self.suites = [] benchmark_dir = get_benchmark_dir() for f in map(os.path.basename, sorted(os.listdir(benchmark_dir))): if f != 'run.py' and f.endswith('.py') and f[0] != '_': self.suites.append(Suite(f)) def run(self): output_dir = os.environ.get('TI_BENCHMARK_OUTPUT_DIR', '.') filename = f'{output_dir}/benchmark.yml' try: with open(filename, 'r+') as f: f.truncate() # clear the previous result except FileNotFoundError: pass print("Running...") for s in self.suites: s.run() b = TaichiBenchmark() b.run()
68
24.74
77
18
418
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.exec-detected_bfc3723add3e6562_a9b6ec54", "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": 34, "line_end": 34, "column_start": 9, "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/tmprvd6_wj2/bfc3723add3e6562.py", "start": {"line": 34, "col": 9, "offset": 669}, "end": {"line": 34, "col": 54, "offset": 714}, "extra": {"message": "Detected the use of exec(). exec() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.return-in-init_bfc3723add3e6562_be18e322", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.return-in-init", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "`return` should never appear inside a class __init__ function. This will cause a runtime error.", "remediation": "", "location": {"file_path": "unknown", "line_start": 37, "line_end": 37, "column_start": 37, "column_end": 63, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.return-in-init", "path": "/tmp/tmprvd6_wj2/bfc3723add3e6562.py", "start": {"line": 37, "col": 37, "offset": 806}, "end": {"line": 37, "col": 63, "offset": 832}, "extra": {"message": "`return` should never appear inside a class __init__ function. This will cause a runtime error.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_bfc3723add3e6562_220a6465", "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": 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/tmprvd6_wj2/bfc3723add3e6562.py", "start": {"line": 58, "col": 18, "offset": 1504}, "end": {"line": 58, "col": 38, "offset": 1524}, "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" ]
[ 34 ]
[ 34 ]
[ 9 ]
[ 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" ]
run.py
/benchmarks/run.py
ljcc0930/taichi
MIT
2024-11-18T20:43:27.169363+00:00
1,654,066,172,000
9cca9498a338bb3cd64b6ddce626016d915791b6
3
{ "blob_id": "9cca9498a338bb3cd64b6ddce626016d915791b6", "branch_name": "refs/heads/master", "committer_date": 1654066172000, "content_id": "48ae18a6ade1bfc64a05e8031adfe3c9e8031a40", "detected_licenses": [ "MIT" ], "directory_id": "4b8013544bd89210d60a140b82828fabc6399959", "extension": "py", "filename": "GetTintriDashboard.py", "fork_events_count": 4, "gha_created_at": 1486428643000, "gha_event_created_at": 1563580765000, "gha_language": null, "gha_license_id": "MIT", "github_id": 81149591, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8649, "license": "MIT", "license_type": "permissive", "path": "/docs/client/http/samples/python/GetTintriDashboard.py", "provenance": "stack-edu-0054.json.gz:575271", "repo_name": "Tintri/tintri-rest-api", "revision_date": 1654066172000, "revision_id": "b2918838f318e434730b8dedf865a58aefdb7a60", "snapshot_id": "39d812c06150f700448eb0e7fce5f4f8a8f30378", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/Tintri/tintri-rest-api/b2918838f318e434730b8dedf865a58aefdb7a60/docs/client/http/samples/python/GetTintriDashboard.py", "visit_date": "2022-06-13T22:31:53.477698" }
2.703125
stackv2
#!/usr/bin/env python # -*- coding: utf-8 -*- # # The code example provided here is for reference only to illustrate # sample workflows and may not be appropriate for use in actual operating # environments. # Support will be provided by Tintri for the Tintri APIs, but theses # examples are for illustrative purposes only and are not supported. # Tintri is not responsible for any outcome resulting from the use # of these scripts. # from datetime import date, datetime import requests import json import sys import time from prettytable import PrettyTable """ This Python script is responsible for getting the Dashboard information (Appliance info and Datastore stats) for VMstore and showing it on console. A user can make changes in the configuration section to change the configurations like debug_mode if debug_mode is set to False; then JSON response won't be printed on console Command usage: GetTintriDashboard <serverName> <userName> <password> """ ##### ************** Configurations to be done by end user ************** ######## # For exhaustive messages on console, make it to True; otherwise keep it False debug_mode = False ##### ************** End of Configuration Section ************** ######## debug_prefix = "[DEBUG] : " info_prefix = "[INFO] : " error_prefix = "[ERROR] : " if len(sys.argv) < 4: print(error_prefix+"Insufficient parameters passed for getting VMstore Dashboard info.") print(info_prefix+"COMMAND USAGE : GetTintriDashboard serverName userName password") sys.exit(-5) header = "********************************* Tintri Ic. *********************************" sub_heading = " ------- Get VMstore Dashboard info. ------- " serverName = sys.argv[1] userName = sys.argv[2] password = sys.argv[3] if debug_mode: print() print("Arguments fetched from commandline") print(debug_prefix+"ServerName fetched : "+serverName) print(debug_prefix+"UserName fetched : "+userName) print(debug_prefix+"Password fetched : ********") print() # Login to VMstore #Payload, header and URL for login call payload = {"newPassword": None, "username": userName, "roles": None, "password": password, "typeId": "com.tintri.api.rest.vcommon.dto.rbac.RestApiCredentials"} headers = {'content-type': 'application/json'} urlLogin = 'https://'+serverName+'/api/v310/session/login' print() print(header) print() print(sub_heading) print() print("SERVER NAME : "+serverName) print() print("STEP 1: Login to VMstore") # Debug Logs to console if debug_mode: print("\t"+debug_prefix+"Going to make the Login call to server : "+serverName) print("\t"+debug_prefix+"The URL being used for login is : "+urlLogin) try: r = requests.post(urlLogin, json.dumps(payload), headers=headers, verify=False) except requests.ConnectionError: print("\t"+error_prefix+"API Connection error occurred") sys.exit(-1) except requests.HTTPError: print("\t"+error_prefix+"HTTP error occurred") sys.exit(-2) except requests.Timeout: print("\t"+error_prefix+"Request timed out") sys.exit(-3) except Exception: print("\t"+error_prefix+"An unexpected error occurred") sys.exit(-4) if debug_mode: print("\t"+debug_prefix+"The HTTP Status code for login call to the server "+serverName + " is: "+str(r.status_code)) # if Http Response is not 200 then raise an exception if r.status_code is not 200: print("\t"+error_prefix+"The HTTP response for login call to the server "+serverName+" is not 200") sys.exit(-6) # Debug Logs to console if debug_mode: print("\t"+debug_prefix+"The Json response of login call to the server "+serverName+" is: "+r.text) # Fetch SessionId from Cookie session_id = r.cookies['JSESSIONID'] # Fetch Appliance info from VMStore print() print("STEP 2: Fetch and display Appliance info from VMStore") #Header and URL for getApplianceInfo call headers = {'content-type': 'application/json','cookie': 'JSESSIONID='+session_id} urlGetApplianceInfo = 'https://'+serverName+'/api/v310/appliance/default/info' print("\t"+info_prefix+"Fetching appliance info. by REST request: GET " + urlGetApplianceInfo) r=requests.get(urlGetApplianceInfo,headers=headers, verify=False) if debug_mode: print("\t"+debug_prefix+"The HTTP Status code for getApplianceInfo call to the server "+serverName + " is: "+str(r.status_code)) # if Http Response is not 200 then raise an exception if r.status_code is not 200: print("\t"+error_prefix+"The HTTP response for getApplianceInfo call to the server "+serverName+" is not 200") sys.exit(-6) if debug_mode: print("\t"+debug_prefix+"The Json response of getApplianceInfo call to the server "+serverName+" is: "+r.text) #loads the appliance info result applianceInfo_result = json.loads(r.text) print() #Printing appliance info. in tabular format header = ['Serial No.', 'Model Name', 'Tintri OS version'] print("\t"+info_prefix+"---------- Appliance Information ----------") x = PrettyTable(header) row = [applianceInfo_result["serialNumber"], applianceInfo_result["modelName"], applianceInfo_result["osVersion"]] x.add_row(row) print(x) print() print("STEP 3: Fetch and display datastore stat from VMstore") #Header and URL for getDatastoreInfo call headers = {'content-type': 'application/json','cookie': 'JSESSIONID='+session_id} urlDatastoreStat = 'https://'+serverName+'/api/v310/datastore/default/statsRealtime' print("\t"+info_prefix+"Fetching Datastore stat by REST request: GET " + urlDatastoreStat) r=requests.get(urlDatastoreStat,headers=headers, verify=False) if debug_mode: print("\t"+debug_prefix+"The HTTP Status code for getDatastoreStat call to the server "+serverName + " is: "+str(r.status_code)) # if Http Response is not 200 then raise an exception if r.status_code is not 200: print("\t"+error_prefix+"The HTTP response for getDatastoreStat call to the server "+serverName+" is not 200") sys.exit(-6) if debug_mode: print("\t"+debug_prefix+"The Json response of getDatastoreStat call to the server "+serverName+" is: "+r.text) #loads the paginated result for datastore stats datastoreStat_result = json.loads(r.text) # get the filteredtotal number of datastore stats number_of_dsStats=int(datastoreStat_result['filteredTotal']) print() #Printing datastore stat in tabular format if number_of_dsStats > 0: print() header = ['Flash hit Ratio (%)', 'Network latency (ms)', 'Storage latency (ms)', 'Disk latency (ms)', 'Host latency (ms)', 'Total latency (ms)', 'Perf. Reserves allocated', 'Space used live Physical (GiB)', 'Space used other (GiB)', 'Read IOPS', 'Write IOPS', 'Throughput Read (MBps)', 'Throughput Write (MBps)'] stats = datastoreStat_result["items"][0]["sortedStats"] print("\t"+info_prefix+"---------- Datastore stats ----------") x = PrettyTable() x.add_column("Attributes", header) x.add_column("Values", [stats[0]["flashHitPercent"], stats[0]["latencyNetworkMs"], stats[0]["latencyStorageMs"], stats[0]["latencyDiskMs"], stats[0]["latencyHostMs"], stats[0]["latencyTotalMs"], stats[0]["performanceReserveAutoAllocated"], stats[0]["spaceUsedLivePhysicalGiB"], stats[0]["spaceUsedOtherGiB"], stats[0]["operationsReadIops"], stats[0]["operationsWriteIops"], stats[0]["throughputReadMBps"], stats[0]["throughputWriteMBps"] ] ) print(x) print() # Logout of VMStore print() print("STEP 4: Logout from VMstore") #Header and URL for logout call headers = {'content-type': 'application/json','cookie': 'JSESSIONID='+session_id} url_VMStore_logout = 'https://'+serverName+'/api/v310/session/logout' if debug_mode: print("\t"+debug_prefix+"The URL being used for logout is : "+url_VMStore_logout) r = requests.get(url_VMStore_logout,headers=headers, verify=False) if debug_mode: print("\t"+debug_prefix+"The HTTP Status code for logout call to the server "+serverName + " is: "+str(r.status_code)) # if Http Response is not 204 then raise an exception if r.status_code is not 204: print("\t"+error_prefix+"The HTTP response for logout call to the server "+serverName+" is not 204") sys.exit(-6) print() print("**********End of Get VMstore Dashboard Sample Client Script**********")
222
36.96
159
14
2,029
python
[{"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_48c378697b6cf346_b4e1f6dd", "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": 81, "line_end": 81, "column_start": 9, "column_end": 84, "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/tmprvd6_wj2/48c378697b6cf346.py", "start": {"line": 81, "col": 9, "offset": 2686}, "end": {"line": 81, "col": 84, "offset": 2761}, "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_48c378697b6cf346_ad27cd28", "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(urlLogin, json.dumps(payload), headers=headers, verify=False, timeout=30)", "location": {"file_path": "unknown", "line_start": 81, "line_end": 81, "column_start": 9, "column_end": 84, "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/tmprvd6_wj2/48c378697b6cf346.py", "start": {"line": 81, "col": 9, "offset": 2686}, "end": {"line": 81, "col": 84, "offset": 2761}, "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(urlLogin, json.dumps(payload), headers=headers, verify=False, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.security.disabled-cert-validation_48c378697b6cf346_69874b15", "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(urlLogin, json.dumps(payload), headers=headers, verify=True)", "location": {"file_path": "unknown", "line_start": 81, "line_end": 81, "column_start": 9, "column_end": 84, "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/tmprvd6_wj2/48c378697b6cf346.py", "start": {"line": 81, "col": 9, "offset": 2686}, "end": {"line": 81, "col": 84, "offset": 2761}, "extra": {"message": "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "fix": "requests.post(urlLogin, json.dumps(payload), headers=headers, verify=True)", "metadata": {"cwe": ["CWE-295: Improper Certificate Validation"], "owasp": ["A03:2017 - Sensitive Data Exposure", "A07:2021 - Identification and Authentication Failures", "A07:2025 - Authentication Failures"], "references": ["https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib"], "category": "security", "technology": ["requests"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_48c378697b6cf346_367102d3", "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": 119, "line_end": 119, "column_start": 3, "column_end": 66, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmprvd6_wj2/48c378697b6cf346.py", "start": {"line": 119, "col": 3, "offset": 4119}, "end": {"line": 119, "col": 66, "offset": 4182}, "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_48c378697b6cf346_0fad0613", "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(urlGetApplianceInfo,headers=headers, verify=False, timeout=30)", "location": {"file_path": "unknown", "line_start": 119, "line_end": 119, "column_start": 3, "column_end": 66, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmprvd6_wj2/48c378697b6cf346.py", "start": {"line": 119, "col": 3, "offset": 4119}, "end": {"line": 119, "col": 66, "offset": 4182}, "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(urlGetApplianceInfo,headers=headers, verify=False, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.security.disabled-cert-validation_48c378697b6cf346_034a6b1c", "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(urlGetApplianceInfo,headers=headers, verify=True)", "location": {"file_path": "unknown", "line_start": 119, "line_end": 119, "column_start": 3, "column_end": 66, "code_snippet": "requires login"}, "cwe_id": "CWE-295: Improper Certificate Validation", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.security.disabled-cert-validation", "path": "/tmp/tmprvd6_wj2/48c378697b6cf346.py", "start": {"line": 119, "col": 3, "offset": 4119}, "end": {"line": 119, "col": 66, "offset": 4182}, "extra": {"message": "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "fix": "requests.get(urlGetApplianceInfo,headers=headers, verify=True)", "metadata": {"cwe": ["CWE-295: Improper Certificate Validation"], "owasp": ["A03:2017 - Sensitive Data Exposure", "A07:2021 - Identification and Authentication Failures", "A07:2025 - Authentication Failures"], "references": ["https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib"], "category": "security", "technology": ["requests"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.python.requests.best-practice.use-response-json-shortcut_48c378697b6cf346_2905f533", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.python.requests.best-practice.use-response-json-shortcut", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "The requests library has a convenient shortcut for reading JSON responses, which lets you stop worrying about deserializing the response yourself.", "remediation": "r.json()", "location": {"file_path": "unknown", "line_start": 134, "line_end": 134, "column_start": 24, "column_end": 42, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/stable/user/quickstart/#json-response-content", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.python.requests.best-practice.use-response-json-shortcut", "path": "/tmp/tmprvd6_wj2/48c378697b6cf346.py", "start": {"line": 134, "col": 24, "offset": 4737}, "end": {"line": 134, "col": 42, "offset": 4755}, "extra": {"message": "The requests library has a convenient shortcut for reading JSON responses, which lets you stop worrying about deserializing the response yourself.", "fix": "r.json()", "metadata": {"references": ["https://requests.readthedocs.io/en/stable/user/quickstart/#json-response-content"], "category": "best-practice", "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_48c378697b6cf346_e9439382", "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": 153, "line_end": 153, "column_start": 3, "column_end": 63, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://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/tmprvd6_wj2/48c378697b6cf346.py", "start": {"line": 153, "col": 3, "offset": 5477}, "end": {"line": 153, "col": 63, "offset": 5537}, "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_48c378697b6cf346_ee27db12", "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(urlDatastoreStat,headers=headers, verify=False, timeout=30)", "location": {"file_path": "unknown", "line_start": 153, "line_end": 153, "column_start": 3, "column_end": 63, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://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/tmprvd6_wj2/48c378697b6cf346.py", "start": {"line": 153, "col": 3, "offset": 5477}, "end": {"line": 153, "col": 63, "offset": 5537}, "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(urlDatastoreStat,headers=headers, verify=False, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.security.disabled-cert-validation_48c378697b6cf346_5968a219", "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(urlDatastoreStat,headers=headers, verify=True)", "location": {"file_path": "unknown", "line_start": 153, "line_end": 153, "column_start": 3, "column_end": 63, "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/tmprvd6_wj2/48c378697b6cf346.py", "start": {"line": 153, "col": 3, "offset": 5477}, "end": {"line": 153, "col": 63, "offset": 5537}, "extra": {"message": "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "fix": "requests.get(urlDatastoreStat,headers=headers, verify=True)", "metadata": {"cwe": ["CWE-295: Improper Certificate Validation"], "owasp": ["A03:2017 - Sensitive Data Exposure", "A07:2021 - Identification and Authentication Failures", "A07:2025 - Authentication Failures"], "references": ["https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib"], "category": "security", "technology": ["requests"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.python.requests.best-practice.use-response-json-shortcut_48c378697b6cf346_9c90c990", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.python.requests.best-practice.use-response-json-shortcut", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "The requests library has a convenient shortcut for reading JSON responses, which lets you stop worrying about deserializing the response yourself.", "remediation": "r.json()", "location": {"file_path": "unknown", "line_start": 168, "line_end": 168, "column_start": 24, "column_end": 42, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/stable/user/quickstart/#json-response-content", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.python.requests.best-practice.use-response-json-shortcut", "path": "/tmp/tmprvd6_wj2/48c378697b6cf346.py", "start": {"line": 168, "col": 24, "offset": 6107}, "end": {"line": 168, "col": 42, "offset": 6125}, "extra": {"message": "The requests library has a convenient shortcut for reading JSON responses, which lets you stop worrying about deserializing the response yourself.", "fix": "r.json()", "metadata": {"references": ["https://requests.readthedocs.io/en/stable/user/quickstart/#json-response-content"], "category": "best-practice", "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_48c378697b6cf346_aafa4fe6", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-raise-for-status", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "remediation": "", "location": {"file_path": "unknown", "line_start": 210, "line_end": 210, "column_start": 5, "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://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/tmprvd6_wj2/48c378697b6cf346.py", "start": {"line": 210, "col": 5, "offset": 7930}, "end": {"line": 210, "col": 67, "offset": 7992}, "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_48c378697b6cf346_9302d694", "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_VMStore_logout,headers=headers, verify=False, timeout=30)", "location": {"file_path": "unknown", "line_start": 210, "line_end": 210, "column_start": 5, "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://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/tmprvd6_wj2/48c378697b6cf346.py", "start": {"line": 210, "col": 5, "offset": 7930}, "end": {"line": 210, "col": 67, "offset": 7992}, "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_VMStore_logout,headers=headers, verify=False, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.security.disabled-cert-validation_48c378697b6cf346_6bd83b5f", "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_VMStore_logout,headers=headers, verify=True)", "location": {"file_path": "unknown", "line_start": 210, "line_end": 210, "column_start": 5, "column_end": 67, "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/tmprvd6_wj2/48c378697b6cf346.py", "start": {"line": 210, "col": 5, "offset": 7930}, "end": {"line": 210, "col": 67, "offset": 7992}, "extra": {"message": "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "fix": "requests.get(url_VMStore_logout,headers=headers, verify=True)", "metadata": {"cwe": ["CWE-295: Improper Certificate Validation"], "owasp": ["A03:2017 - Sensitive Data Exposure", "A07:2021 - Identification and Authentication Failures", "A07:2025 - Authentication Failures"], "references": ["https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib"], "category": "security", "technology": ["requests"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
14
true
[ "CWE-295", "CWE-295", "CWE-295", "CWE-295" ]
[ "rules.python.requests.security.disabled-cert-validation", "rules.python.requests.security.disabled-cert-validation", "rules.python.requests.security.disabled-cert-validation", "rules.python.requests.security.disabled-cert-validation" ]
[ "security", "security", "security", "security" ]
[ "LOW", "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH", "HIGH" ]
[ 81, 119, 153, 210 ]
[ 81, 119, 153, 210 ]
[ 9, 3, 3, 5 ]
[ 84, 66, 63, 67 ]
[ "A03:2017 - Sensitive Data Exposure", "A03:2017 - Sensitive Data Exposure", "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.", "Certificate v...
[ 7.5, 7.5, 7.5, 7.5 ]
[ "LOW", "LOW", "LOW", "LOW" ]
[ "LOW", "LOW", "LOW", "LOW" ]
GetTintriDashboard.py
/docs/client/http/samples/python/GetTintriDashboard.py
Tintri/tintri-rest-api
MIT
2024-11-18T20:43:35.376435+00:00
1,635,315,024,000
18c810361ce85b5d4a2bd5c5d6a3893d256d3c93
3
{ "blob_id": "18c810361ce85b5d4a2bd5c5d6a3893d256d3c93", "branch_name": "refs/heads/master", "committer_date": 1635315024000, "content_id": "f0f6535b25b484ff228919154bea07e98caeb458", "detected_licenses": [ "Apache-2.0" ], "directory_id": "3a247363c5acb97a22eb61d557e11aeb89edd701", "extension": "py", "filename": "healthcheckd.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 174799356, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2936, "license": "Apache-2.0", "license_type": "permissive", "path": "/healthcheckd.py", "provenance": "stack-edu-0054.json.gz:575348", "repo_name": "jordiprats/python-healthcheckd", "revision_date": 1635315024000, "revision_id": "c3e46d791bde750ff884eea1154a0cdc81840dca", "snapshot_id": "df6aca773fc95c08edaddc680365d97a6caf6ac5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jordiprats/python-healthcheckd/c3e46d791bde750ff884eea1154a0cdc81840dca/healthcheckd.py", "visit_date": "2021-11-04T03:08:13.578408" }
2.6875
stackv2
import sys import logging import subprocess from pid import PidFile from configparser import ConfigParser from http.server import BaseHTTPRequestHandler,HTTPServer #This class will handles any incoming request from #the browser class HealthCheckHandler(BaseHTTPRequestHandler): def check_status(self): global command p = subprocess.Popen('bash -c \''+command+"'", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.communicate()[0] print(p.returncode) return p.returncode==0 def do_healthcheck(self): if self.check_status(): self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write(bytes("OK", "utf-8")) else: self.send_response(503) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write(bytes("ERROR", "utf-8")) #Handler for the GET requests def do_GET(self): self.do_healthcheck() return #Handler for the HEAD requests def do_HEAD(self): self.do_healthcheck() return if __name__ == "__main__": try: configfile = sys.argv[1] except IndexError: configfile = '/etc/healthcheckd.config' try: config = ConfigParser() config.read(configfile) try: pidfile = config.get('healthcheckd', 'pidfile').strip('"').strip("'").strip() except: pidfile = 'healthcheckd' try: piddir = config.get('healthcheckd', 'piddir').strip('"').strip("'").strip() except: piddir = '/tmp' try: port_number = int(config.get('healthcheckd', 'port').strip('"').strip("'").strip()) except: port_number = 17 try: command = config.get('healthcheckd', 'command').strip('"').strip("'").strip() except Exception as e: command = '/bin/true' print('INFO: setting default command: '+command) with PidFile(piddir=piddir, pidname=pidfile) as pidfile: logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') try: #Create a web server and define the handler to manage the #incoming request server = HTTPServer(('', port_number), HealthCheckHandler) print('Started httpserver on port '+str(port_number)) #Wait forever for incoming htto requests server.serve_forever() except KeyboardInterrupt: logging.info('shutting down healthcheckd') server.socket.close() sys.exit() except Exception as e: msg = 'Global ERROR: '+str(e) logging.error(msg) sys.exit(msg+'\n')
93
30.57
114
21
633
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_3bb3e621d1f2bc4e_13bdd5ea", "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": 15, "line_end": 15, "column_start": 13, "column_end": 115, "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/tmprvd6_wj2/3bb3e621d1f2bc4e.py", "start": {"line": 15, "col": 13, "offset": 344}, "end": {"line": 15, "col": 115, "offset": 446}, "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_3bb3e621d1f2bc4e_b91ea5fa", "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": 15, "line_end": 15, "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/tmprvd6_wj2/3bb3e621d1f2bc4e.py", "start": {"line": 15, "col": 62, "offset": 393}, "end": {"line": 15, "col": 66, "offset": 397}, "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"}}}]
2
true
[ "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.subprocess-shell-true" ]
[ "security", "security" ]
[ "LOW", "MEDIUM" ]
[ "HIGH", "HIGH" ]
[ 15, 15 ]
[ 15, 15 ]
[ 13, 62 ]
[ 115, 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" ]
healthcheckd.py
/healthcheckd.py
jordiprats/python-healthcheckd
Apache-2.0
2024-11-18T20:43:40.741314+00:00
1,513,539,361,000
ac11dd9c1ec5ed8972d07414db7e484b608a6f49
3
{ "blob_id": "ac11dd9c1ec5ed8972d07414db7e484b608a6f49", "branch_name": "refs/heads/master", "committer_date": 1513539361000, "content_id": "bf54c37a1afc344bfe8e5602199f8b31df44de03", "detected_licenses": [ "MIT" ], "directory_id": "f0dbd873d1cf1052bc988d06d7d8fbbb26b42e08", "extension": "py", "filename": "server.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 110651417, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3726, "license": "MIT", "license_type": "permissive", "path": "/server.py", "provenance": "stack-edu-0054.json.gz:575416", "repo_name": "FMI-VT/Simplest-OT-Python-Implementation", "revision_date": 1513539361000, "revision_id": "3124a403313824c54ae6b10e0765bb9ceb1783b7", "snapshot_id": "ea81c2e40de934c8df26f91f3e6461326a829788", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/FMI-VT/Simplest-OT-Python-Implementation/3124a403313824c54ae6b10e0765bb9ceb1783b7/server.py", "visit_date": "2021-08-30T11:36:00.513700" }
2.734375
stackv2
#server # TCP Server Code from Crypto.Cipher import AES from Crypto.Cipher import DES from Crypto.Cipher import DES3 from Crypto.Cipher import Blowfish from Crypto.Cipher import ChaCha20 import hashlib from hashlib import blake2s import pickle import random import sys import Crypto from ecc import getcurvebyname from array import array import socket from socket import * import time import argparse host="127.0.0.1" port=4446 #port=12345 parser = argparse.ArgumentParser() parser.add_argument("e", type=int, choices=[0, 1, 2, 3, 4], help="symmetric encryption algorithm [ 0 - AES, 1 - DES, 2 - 3DES, 3 - Blowfish, 4 - ChaCha20]") parser.add_argument("-d", "--hash", type=int, choices=[0, 1, 2], help="hash function [0 - md5, 1 - blake2s, 2 - SHA256 ]") args = parser.parse_args() def decryptData( secret, msg): "Decrypts the data based on the used cipher" msg_nonce = msg[:8] ciphertext = msg[8:] cipher = ChaCha20.new(key=secret, nonce=msg_nonce) decryptedData = cipher.decrypt(ciphertext) return decryptedData def getCipher( key ): "This returns the Cipher based on the preffered algorithm -AES, DES, 3DES" if args.e == 0: tempCipher = AES.new(key, AES.MODE_ECB) elif args.e == 1: tempCipher = DES.new(key, DES.MODE_ECB) elif args.e == 2: tempCipher = DES3.new(key, DES3.MODE_ECB) elif args.e == 3: tempCipher = Blowfish.new(key, Blowfish.MODE_ECB) elif args.e == 4: tempCipher = ChaCha20.new(key=key) return tempCipher def getKey( strValue ): "Returns the key based on the chosen symmetric function" if args.e == 0: #AES if args.hash == 0: tempKey=hashlib.md5() elif args.hash == 1: tempKey=hashlib.blake2s(digest_size=16) else: tempKey=hashlib.md5() elif args.e == 1: tempKey=hashlib.blake2s(digest_size=8) #DES elif args.e == 2: tempKey=hashlib.blake2s(digest_size=16) #3DES elif args.e == 3: tempKey=hashlib.blake2s() #Blowfish elif args.e == 4: tempKey=hashlib.blake2s(digest_size=32) #ChaCha20 tempKey.update(strValue) tempKey=tempKey.digest() return tempKey def readFromClient(): c=random.randint(0,1) curve=getcurvebyname("ed25519") g=curve.G b=random.randint(1,2**255-19) Alice=pickle.loads(q.recv(4096)) if (c==0): Bob=(g.__mul__(b)) else: Bob=(Alice.__mul__(c)).__add__(g.__mul__(b)) q.send(pickle.dumps(Bob,pickle.HIGHEST_PROTOCOL)) k = getKey(str(Alice.__mul__(b)).encode()) cipher1 = getCipher(k) message=[1]*2 for i in range (2): en=q.recv(1024) if args.e == 4: message[i] = decryptData(k, en) else: message[i]=cipher1.decrypt(en) print ('Message [',i,']',message[i].decode('iso-8859-15')) print('#########################################################') return; s=socket(AF_INET, SOCK_STREAM) s.bind((host,port)) s.listen(1) print ("Listening for connections.. ") if args.e == 0: print ("AES encryption") elif args.e == 1: print ("DES encryption") elif args.e == 2: print ("3DES encryption") elif args.e == 3: print ("Blowfish encryption") elif args.e == 4: print ("ChaCha20 encryption") q,addr=s.accept() start_time = time.time() for i in range (10): start_time = time.time() readFromClient() print("----- %s seconds ----" %(time.time() - start_time)) s.close() # Closes the socket # End of code
149
23.01
116
14
1,061
python
[{"finding_id": "semgrep_rules.python.pycryptodome.security.insecure-cipher-algorithm-des_f826ef47fc86e604_9ab018d5", "tool_name": "semgrep", "rule_id": "rules.python.pycryptodome.security.insecure-cipher-algorithm-des", "finding_type": "security", "severity": "medium", "confidence": "high", "message": "Detected DES cipher or Triple DES algorithm which is considered insecure. This algorithm is not cryptographically secure and can be reversed easily. Use a secure symmetric cipher from the cryptodome package instead. Use secure stream ciphers such as ChaCha20, XChaCha20 and Salsa20, or a block cipher such as AES with a block size of 128 bits. When using a block cipher, use a modern mode of operation that also provides authentication, such as GCM.", "remediation": "", "location": {"file_path": "unknown", "line_start": 47, "line_end": 47, "column_start": 18, "column_end": 44, "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://cwe.mitre.org/data/definitions/326.html", "title": null}, {"url": "https://www.pycryptodome.org/src/cipher/cipher", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.pycryptodome.security.insecure-cipher-algorithm-des", "path": "/tmp/tmprvd6_wj2/f826ef47fc86e604.py", "start": {"line": 47, "col": 18, "offset": 1315}, "end": {"line": 47, "col": 44, "offset": 1341}, "extra": {"message": "Detected DES cipher or Triple DES algorithm which is considered insecure. This algorithm is not cryptographically secure and can be reversed easily. Use a secure symmetric cipher from the cryptodome package instead. Use secure stream ciphers such as ChaCha20, XChaCha20 and Salsa20, or a block cipher such as AES with a block size of 128 bits. When using a block cipher, use a modern mode of operation that also provides authentication, such as GCM.", "metadata": {"source-rule-url": "https://github.com/PyCQA/bandit/blob/d5f8fa0d89d7b11442fc6ec80ca42953974354c8/bandit/blacklists/calls.py#L84", "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": "B304", "references": ["https://cwe.mitre.org/data/definitions/326.html", "https://www.pycryptodome.org/src/cipher/cipher"], "category": "security", "technology": ["pycryptodome"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "HIGH", "functional-categories": ["crypto::search::symmetric-algorithm::pycryptodome", "crypto::search::symmetric-algorithm::pycryptodomex"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.pycryptodome.security.insecure-cipher-algorithm-des_f826ef47fc86e604_f7ddbd91", "tool_name": "semgrep", "rule_id": "rules.python.pycryptodome.security.insecure-cipher-algorithm-des", "finding_type": "security", "severity": "medium", "confidence": "high", "message": "Detected DES cipher or Triple DES algorithm which is considered insecure. This algorithm is not cryptographically secure and can be reversed easily. Use a secure symmetric cipher from the cryptodome package instead. Use secure stream ciphers such as ChaCha20, XChaCha20 and Salsa20, or a block cipher such as AES with a block size of 128 bits. When using a block cipher, use a modern mode of operation that also provides authentication, such as GCM.", "remediation": "", "location": {"file_path": "unknown", "line_start": 49, "line_end": 49, "column_start": 18, "column_end": 46, "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://cwe.mitre.org/data/definitions/326.html", "title": null}, {"url": "https://www.pycryptodome.org/src/cipher/cipher", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.pycryptodome.security.insecure-cipher-algorithm-des", "path": "/tmp/tmprvd6_wj2/f826ef47fc86e604.py", "start": {"line": 49, "col": 18, "offset": 1380}, "end": {"line": 49, "col": 46, "offset": 1408}, "extra": {"message": "Detected DES cipher or Triple DES algorithm which is considered insecure. This algorithm is not cryptographically secure and can be reversed easily. Use a secure symmetric cipher from the cryptodome package instead. Use secure stream ciphers such as ChaCha20, XChaCha20 and Salsa20, or a block cipher such as AES with a block size of 128 bits. When using a block cipher, use a modern mode of operation that also provides authentication, such as GCM.", "metadata": {"source-rule-url": "https://github.com/PyCQA/bandit/blob/d5f8fa0d89d7b11442fc6ec80ca42953974354c8/bandit/blacklists/calls.py#L84", "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": "B304", "references": ["https://cwe.mitre.org/data/definitions/326.html", "https://www.pycryptodome.org/src/cipher/cipher"], "category": "security", "technology": ["pycryptodome"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "HIGH", "functional-categories": ["crypto::search::symmetric-algorithm::pycryptodome", "crypto::search::symmetric-algorithm::pycryptodomex"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.pycryptodome.security.insecure-cipher-algorithm-blowfish_f826ef47fc86e604_ce964892", "tool_name": "semgrep", "rule_id": "rules.python.pycryptodome.security.insecure-cipher-algorithm-blowfish", "finding_type": "security", "severity": "medium", "confidence": "high", "message": "Detected Blowfish cipher algorithm which is considered insecure. This algorithm is not cryptographically secure and can be reversed easily. Use secure stream ciphers such as ChaCha20, XChaCha20 and Salsa20, or a block cipher such as AES with a block size of 128 bits. When using a block cipher, use a modern mode of operation that also provides authentication, such as GCM.", "remediation": "", "location": {"file_path": "unknown", "line_start": 51, "line_end": 51, "column_start": 18, "column_end": 54, "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://stackoverflow.com/questions/1135186/whats-wrong-with-xor-encryption", "title": null}, {"url": "https://www.pycryptodome.org/src/cipher/cipher", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.pycryptodome.security.insecure-cipher-algorithm-blowfish", "path": "/tmp/tmprvd6_wj2/f826ef47fc86e604.py", "start": {"line": 51, "col": 18, "offset": 1447}, "end": {"line": 51, "col": 54, "offset": 1483}, "extra": {"message": "Detected Blowfish cipher algorithm which is considered insecure. This algorithm is not cryptographically secure and can be reversed easily. Use secure stream ciphers such as ChaCha20, XChaCha20 and Salsa20, or a block cipher such as AES with a block size of 128 bits. When using a block cipher, use a modern mode of operation that also provides authentication, such as GCM.", "metadata": {"source-rule-url": "https://github.com/PyCQA/bandit/blob/d5f8fa0d89d7b11442fc6ec80ca42953974354c8/bandit/blacklists/calls.py#L84", "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": "B304", "references": ["https://stackoverflow.com/questions/1135186/whats-wrong-with-xor-encryption", "https://www.pycryptodome.org/src/cipher/cipher"], "category": "security", "technology": ["pycryptodome"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "HIGH", "functional-categories": ["crypto::search::symmetric-algorithm::pycryptodome", "crypto::search::symmetric-algorithm::pycryptodomex"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.insecure-hash-algorithm-md5_f826ef47fc86e604_f0afa567", "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": 62, "line_end": 62, "column_start": 18, "column_end": 31, "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/tmprvd6_wj2/f826ef47fc86e604.py", "start": {"line": 62, "col": 18, "offset": 1723}, "end": {"line": 62, "col": 31, "offset": 1736}, "extra": {"message": "Detected MD5 hash algorithm which is considered insecure. MD5 is not collision resistant and is therefore not suitable as a cryptographic signature. Use SHA256 or SHA3 instead.", "metadata": {"source-rule-url": "https://github.com/PyCQA/bandit/blob/d5f8fa0d89d7b11442fc6ec80ca42953974354c8/bandit/blacklists/calls.py#L59", "cwe": ["CWE-327: Use of a Broken or Risky Cryptographic Algorithm"], "owasp": ["A03:2017 - Sensitive Data Exposure", "A02:2021 - Cryptographic Failures", "A04:2025 - Cryptographic Failures"], "bandit-code": "B303", "asvs": {"control_id": "6.2.2 Insecure Custom Algorithm", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x14-V6-Cryptography.md#v62-algorithms", "section": "V6 Stored Cryptography Verification Requirements", "version": "4"}, "references": ["https://www.schneier.com/blog/archives/2012/10/when_will_we_se.html", "https://www.trendmicro.com/vinfo/us/security/news/vulnerabilities-and-exploits/sha-1-collision-signals-the-end-of-the-algorithm-s-viability", "http://2012.sharcs.org/slides/stevens.pdf", "https://pycryptodome.readthedocs.io/en/latest/src/hash/sha3_256.html"], "category": "security", "technology": ["python"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.insecure-hash-algorithm-md5_f826ef47fc86e604_80b7b15f", "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": 66, "line_end": 66, "column_start": 18, "column_end": 31, "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/tmprvd6_wj2/f826ef47fc86e604.py", "start": {"line": 66, "col": 18, "offset": 1840}, "end": {"line": 66, "col": 31, "offset": 1853}, "extra": {"message": "Detected MD5 hash algorithm which is considered insecure. MD5 is not collision resistant and is therefore not suitable as a cryptographic signature. Use SHA256 or SHA3 instead.", "metadata": {"source-rule-url": "https://github.com/PyCQA/bandit/blob/d5f8fa0d89d7b11442fc6ec80ca42953974354c8/bandit/blacklists/calls.py#L59", "cwe": ["CWE-327: Use of a Broken or Risky Cryptographic Algorithm"], "owasp": ["A03:2017 - Sensitive Data Exposure", "A02:2021 - Cryptographic Failures", "A04:2025 - Cryptographic Failures"], "bandit-code": "B303", "asvs": {"control_id": "6.2.2 Insecure Custom Algorithm", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x14-V6-Cryptography.md#v62-algorithms", "section": "V6 Stored Cryptography Verification Requirements", "version": "4"}, "references": ["https://www.schneier.com/blog/archives/2012/10/when_will_we_se.html", "https://www.trendmicro.com/vinfo/us/security/news/vulnerabilities-and-exploits/sha-1-collision-signals-the-end-of-the-algorithm-s-viability", "http://2012.sharcs.org/slides/stevens.pdf", "https://pycryptodome.readthedocs.io/en/latest/src/hash/sha3_256.html"], "category": "security", "technology": ["python"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_f826ef47fc86e604_219a394d", "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": 95, "line_end": 95, "column_start": 8, "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/tmprvd6_wj2/f826ef47fc86e604.py", "start": {"line": 95, "col": 8, "offset": 2367}, "end": {"line": 95, "col": 34, "offset": 2393}, "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_f826ef47fc86e604_d4a3b620", "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": 9, "column_end": 50, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmprvd6_wj2/f826ef47fc86e604.py", "start": {"line": 100, "col": 9, "offset": 2490}, "end": {"line": 100, "col": 50, "offset": 2531}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
7
true
[ "CWE-502", "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 95, 100 ]
[ 95, 100 ]
[ 8, 9 ]
[ 34, 50 ]
[ "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "Avoid using `pickle`, which is known to lead to...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
server.py
/server.py
FMI-VT/Simplest-OT-Python-Implementation
MIT
2024-11-18T20:43:47.561425+00:00
1,674,736,871,000
22a558b69315ec39129d3126a007881c89124d3e
3
{ "blob_id": "22a558b69315ec39129d3126a007881c89124d3e", "branch_name": "refs/heads/main", "committer_date": 1674736871000, "content_id": "92ded8f93ff4d206c5b947787ae2a16304e1303b", "detected_licenses": [ "MIT" ], "directory_id": "e3db4c51862ae9d2504db4ca9693e758d2add747", "extension": "py", "filename": "topic_extraction_lda.py", "fork_events_count": 11, "gha_created_at": 1615731256000, "gha_event_created_at": 1625215400000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 347655676, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1861, "license": "MIT", "license_type": "permissive", "path": "/src/analysis/topic_extraction_lda.py", "provenance": "stack-edu-0054.json.gz:575467", "repo_name": "rajaswa/DRIFT", "revision_date": 1674736871000, "revision_id": "21977752ac2468057b7661e460d6a5bd5e5fe73c", "snapshot_id": "59f2398ca2d42958c8dd25dea159259b9b13d23f", "src_encoding": "UTF-8", "star_events_count": 115, "url": "https://raw.githubusercontent.com/rajaswa/DRIFT/21977752ac2468057b7661e460d6a5bd5e5fe73c/src/analysis/topic_extraction_lda.py", "visit_date": "2023-05-23T19:34:52.967311" }
2.578125
stackv2
import os import numpy as np import streamlit as st from gensim import corpora, models def lda_basic(list_of_list_of_tokens, num_topics): dictionary_LDA = corpora.Dictionary(list_of_list_of_tokens) dictionary_LDA.filter_extremes(no_below=2) corpus = [ dictionary_LDA.doc2bow(list_of_tokens) for list_of_tokens in list_of_list_of_tokens ] lda_model = models.LdaModel( corpus, num_topics=num_topics, id2word=dictionary_LDA, passes=20, alpha="auto", eta="auto", random_state=42, ) cm = models.CoherenceModel(model=lda_model, corpus=corpus, coherence="u_mass") coherence = cm.get_coherence() # get coherence value return corpus, lda_model, coherence @st.cache(persist=eval(os.getenv("PERSISTENT"))) def extract_topics_lda(text_file_paths, num_topics=0, num_words=10): list_of_list_of_tokens = [] for text_file_path in text_file_paths: with open(text_file_path, "r") as f: text = f.read() doc_words = text.replace("\n", " ").split(" ") list_of_list_of_tokens.append(doc_words) if num_topics == 0: coherence_scores = [] range_of_topics = list(range(5, 31)) for num_topics_in_lst in range_of_topics: _, lda_model, coherence = lda_basic( list_of_list_of_tokens, num_topics_in_lst ) coherence_scores.append(abs(coherence)) num_topics = 3 + np.argmin(coherence_scores) corpus, lda_model, _ = lda_basic(list_of_list_of_tokens, num_topics) year_wise_topics = [] for i, list_of_tokens in enumerate(list_of_list_of_tokens): year_wise_topics.append(lda_model[corpus[i]]) return year_wise_topics, lda_model.show_topics( formatted=True, num_topics=num_topics, num_words=num_words )
58
31.09
82
17
450
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_65e48e4b1d5007d4_ebd8b384", "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": 31, "line_end": 31, "column_start": 19, "column_end": 48, "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/tmprvd6_wj2/65e48e4b1d5007d4.py", "start": {"line": 31, "col": 19, "offset": 780}, "end": {"line": 31, "col": 48, "offset": 809}, "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_65e48e4b1d5007d4_2140dffb", "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": 35, "line_end": 35, "column_start": 14, "column_end": 39, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmprvd6_wj2/65e48e4b1d5007d4.py", "start": {"line": 35, "col": 14, "offset": 968}, "end": {"line": 35, "col": 39, "offset": 993}, "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.eval-detected" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 31 ]
[ 31 ]
[ 19 ]
[ 48 ]
[ "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" ]
topic_extraction_lda.py
/src/analysis/topic_extraction_lda.py
rajaswa/DRIFT
MIT
2024-11-18T20:43:49.966903+00:00
1,573,216,143,000
182a1c07177697f88b529d603fd730dde5edbd0c
2
{ "blob_id": "182a1c07177697f88b529d603fd730dde5edbd0c", "branch_name": "refs/heads/master", "committer_date": 1573216143000, "content_id": "c8466ebf3f0c2decf20ab41307b4103561b10eb4", "detected_licenses": [ "Apache-2.0" ], "directory_id": "4ac62d379f364e0a66e798b649effb2e60387ccc", "extension": "py", "filename": "machine_checkin.py", "fork_events_count": 0, "gha_created_at": 1573214499000, "gha_event_created_at": 1573214499000, "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 220458264, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4636, "license": "Apache-2.0", "license_type": "permissive", "path": "/payload/usr/local/sal/checkin_modules/machine_checkin.py", "provenance": "stack-edu-0054.json.gz:575498", "repo_name": "asemak/sal-scripts", "revision_date": 1573216143000, "revision_id": "4204654f91c4e690bfcdb505ede0b354c540bc3b", "snapshot_id": "b91957880c612a5d0e4cf041bf24838b42b0d4af", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/asemak/sal-scripts/4204654f91c4e690bfcdb505ede0b354c540bc3b/payload/usr/local/sal/checkin_modules/machine_checkin.py", "visit_date": "2020-09-06T14:54:56.006251" }
2.3125
stackv2
#!/usr/bin/python import subprocess import sys from SystemConfiguration import ( SCDynamicStoreCreate, SCDynamicStoreCopyValue, SCDynamicStoreCopyConsoleUser) sys.path.insert(0, '/usr/local/munki') from munkilib import FoundationPlist sys.path.insert(0, '/usr/local/sal') import macmodelshelf import utils MEMORY_EXPONENTS = {'KB': 0, 'MB': 1, 'GB': 2, 'TB': 3} __version__ = '1.0.0' def main(): machine_results = {'facts': {'checkin_module_version': __version__}} extras = {} extras['hostname'] = get_hostname() extras['os_family'] = 'Darwin' extras['console_user'] = get_console_user()[0] extras.update(process_system_profile()) machine_results['extra_data'] = extras utils.set_checkin_results('Machine', machine_results) def process_system_profile(): machine_results = {} system_profile = get_sys_profile() if not system_profile: # We can't continue if system_profiler dies. return machine_results machine_results['serial'] = system_profile['SPHardwareDataType'][0]['serial_number'] os_version = system_profile['SPSoftwareDataType'][0]['os_version'].split()[1] if os_version == 'X': os_version = system_profile['SPSoftwareDataType'][0]['os_version'].split()[2] machine_results['operating_system'] = os_version machine_results['machine_model'] = system_profile['SPHardwareDataType'][0]['machine_model'] friendly_model = get_friendly_model(machine_results['serial']) if friendly_model: machine_results['machine_model_friendly'] = friendly_model machine_results['cpu_type'] = system_profile['SPHardwareDataType'][0].get('cpu_type', '') machine_results['cpu_speed'] = ( system_profile['SPHardwareDataType'][0]['current_processor_speed']) machine_results['memory'] = system_profile['SPHardwareDataType'][0]['physical_memory'] machine_results['memory_kb'] = process_memory(machine_results['memory']) for device in system_profile['SPStorageDataType']: if device['mount_point'] == '/': # div by 1000.0 to # a) Convert to Apple base 10 kilobytes # b) Cast to python floats machine_results['hd_space'] = device['free_space_in_bytes'] machine_results['hd_total'] = device['size_in_bytes'] # We want the % used, not of free space, so invert. machine_results['hd_percent'] = '{:.2f}'.format( abs(float(machine_results['hd_space']) / machine_results['hd_total'] - 1) * 100) return machine_results def get_hostname(): _, name_type, _ = utils.get_server_prefs() net_config = SCDynamicStoreCreate(None, "net", None, None) return get_machine_name(net_config, name_type) def get_machine_name(net_config, nametype): """Return the ComputerName of this Mac.""" sys_info = SCDynamicStoreCopyValue(net_config, "Setup:/System") if sys_info: return sys_info.get(nametype) return subprocess.check_output(['/usr/sbin/scutil', '--get', 'ComputerName']) def get_friendly_model(serial): """Return friendly model name""" model_code = macmodelshelf.model_code(serial) model_name = macmodelshelf.model(model_code) return model_name def process_memory(amount): """Convert the amount of memory like '4 GB' to the size in kb as int""" try: memkb = int(amount[:-3]) * 1024 ** MEMORY_EXPONENTS[amount[-2:]] except ValueError: memkb = int(float(amount[:-3])) * 1024 ** MEMORY_EXPONENTS[amount[-2:]] return memkb def get_sys_profile(): """Get sysprofiler info. Returns: System Profiler report for networking, drives, and hardware as a plist dict, or an empty dict. """ command = [ '/usr/sbin/system_profiler', '-xml', 'SPHardwareDataType', 'SPStorageDataType', 'SPSoftwareDataType'] try: output = subprocess.check_output(command) except subprocess.CalledProcessError: return {} try: system_profile = FoundationPlist.readPlistFromString(output) except FoundationPlist.FoundationPlistException: system_profile = {} # sytem_profiler gives us back an array; convert to a dict with just # the data we care about. results = {} for data_type in system_profile: key = data_type['_dataType'] results[key] = data_type['_items'] return results def get_console_user(): """Get informatino about the console user Returns: 3-Tuple of (str) username, (int) uid, (int) gid """ return SCDynamicStoreCopyConsoleUser(None, None, None) if __name__ == "__main__": main()
139
32.35
96
21
1,106
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_e28dceb7eb1889d2_8f4a082e", "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": 110, "line_end": 110, "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/tmprvd6_wj2/e28dceb7eb1889d2.py", "start": {"line": 110, "col": 18, "offset": 3876}, "end": {"line": 110, "col": 50, "offset": 3908}, "extra": {"message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 110 ]
[ 110 ]
[ 18 ]
[ 50 ]
[ "A01:2017 - Injection" ]
[ "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'." ]
[ 7.5 ]
[ "LOW" ]
[ "HIGH" ]
machine_checkin.py
/payload/usr/local/sal/checkin_modules/machine_checkin.py
asemak/sal-scripts
Apache-2.0
2024-11-18T20:43:51.247714+00:00
1,544,186,864,000
44902baf973d6acb5e80978dbafcb88041ef68e5
3
{ "blob_id": "44902baf973d6acb5e80978dbafcb88041ef68e5", "branch_name": "refs/heads/master", "committer_date": 1544186864000, "content_id": "35db1fc6286bae472f33adf3041b73d1db8aaf09", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "7cd4a71b9be9ccb015034a0f7667edff00228741", "extension": "py", "filename": "trainer.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 151729665, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5485, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/Node/trainer.py", "provenance": "stack-edu-0054.json.gz:575513", "repo_name": "TechMatt1337/Bastion", "revision_date": 1544186864000, "revision_id": "1e89143905babc06ace4f0ae7ab59750427b0f03", "snapshot_id": "7af01a3e9e9e68e15533dbe429e9d3dbec76465c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/TechMatt1337/Bastion/1e89143905babc06ace4f0ae7ab59750427b0f03/Node/trainer.py", "visit_date": "2020-03-31T00:11:32.008299" }
2.984375
stackv2
#Interface with SQL Database import sqlite3 #Pickle objects import pickle #CV to train import cv2 #Base64 encode images import base64 #For exit import sys #For numpy arrays import numpy as np #For file system interaction import os #If you decide to train based on the file system, this code is from the same location as the code in #OpenCV-Face-Recognition-Python def prepare_training_data(data_folder_path): #------STEP-1-------- #get the directories (one directory for each subject) in data folder dirs = os.listdir(data_folder_path) #list to hold all subject faces faces = [] #list to hold labels for all subjects labels = [] #let's go through each directory and read images within it for dir_name in dirs: #our subject directories start with letter 's' so #ignore any non-relevant directories if any if not dir_name.startswith("s"): continue; #------STEP-2-------- #extract label number of subject from dir_name #format of dir name = slabel #, so removing letter 's' from dir_name will give us label label = int(dir_name.replace("s", "")) #build path of directory containin images for current subject subject #sample subject_dir_path = "training-data/s1" subject_dir_path = data_folder_path + "/" + dir_name #get the images names that are inside the given subject directory subject_images_names = os.listdir(subject_dir_path) #------STEP-3-------- #go through each image name, read image, #detect face and add face to list of faces for image_name in subject_images_names: #ignore system files like .DS_Store if image_name.startswith("."): continue; #build image path #sample image path = training-data/s1/1.pgm image_path = subject_dir_path + "/" + image_name #read image image = cv2.imread(image_path) #display an image window to show the image #cv2.imshow("Training on image...", cv2.resize(image, (400, 500))) #cv2.waitKey(100) #detect face face, rect = detect_face(image) #------STEP-4-------- #for the purpose of this tutorial #we will ignore faces that are not detected if face is not None: #add face to list of faces faces.append(face) #add label for this face labels.append(label) #cv2.destroyAllWindows() #cv2.waitKey(1) #cv2.destroyAllWindows() return faces, labels #function to detect face using OpenCV def detect_face(img): #convert the test image to gray image as opencv face detector expects gray images gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #cv2.imshow("Training on image...", cv2.resize(gray, (400, 500))) #cv2.waitKey(100) #load OpenCV face detector, I am using LBP which is fast #there is also a more accurate but slow Haar classifier face_cascade = cv2.CascadeClassifier('opencv-files/lbpcascade_frontalface.xml') #let's detect multiscale (some images may be closer to camera than others) images #result is a list of faces faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5); #if no faces are detected then return original img if (len(faces) == 0): return None, None #under the assumption that there will be only one face, #extract the face area (x, y, w, h) = faces[0] #return only the face part of the image return gray[y:y+w, x:x+h], faces[0] #Connect to the database conn = sqlite3.connect('targets.db') c = conn.cursor() labels = [] names = [] faces = [] label = 1 #Read all face/labels into lists #LAST FIRST, I0, ..., LAST_UPDATED for row in c.execute('SELECT * FROM images'): name = row[0] + " " + row[1] for i in range(2,8): buff = base64.b64decode(row[i]) arr = np.asarray(bytearray(buff), dtype=np.uint8) frame = cv2.imdecode(arr, cv2.IMREAD_COLOR) if frame is None: c.close() conn.close() sys.exit() face, rect = detect_face(frame) if face is not None: #If a face is detected, add to the training set labels.append(label) faces.append(face) if labels[-1] != label: print("Unable to get good face of " + name) c.close() conn.close() sys.exit() names.append(name) label = label + 1 #Finish the connection c.close() conn.close() #create our LBPH face recognizer face_recognizer = cv2.face.LBPHFaceRecognizer_create() #face_recognizer = cv2.face.createLBPHFaceRecognizer() #or use EigenFaceRecognizer by replacing above line with #face_recognizer = cv2.face.EigenFaceRecognizer_create() #or use FisherFaceRecognizer by replacing above line with #face_recognizer = cv2.face.FisherFaceRecognizer_create() #train our face recognizer of our training faces face_recognizer.train(faces, np.array(labels)) face_recognizer.save("tmp") #Read in result of the dump and remove the dump buf = open("tmp").read() os.remove("tmp") result = {'model': buf, 'names': names} #Give result to standard out print(base64.b64encode(pickle.dumps(result)))
179
29.64
100
13
1,313
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_d12298c669655447_72f50c6b", "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": 173, "line_end": 173, "column_start": 7, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://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/tmprvd6_wj2/d12298c669655447.py", "start": {"line": 173, "col": 7, "offset": 5332}, "end": {"line": 173, "col": 18, "offset": 5343}, "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_d12298c669655447_e207cc94", "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": 179, "line_end": 179, "column_start": 24, "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/tmprvd6_wj2/d12298c669655447.py", "start": {"line": 179, "col": 24, "offset": 5462}, "end": {"line": 179, "col": 44, "offset": 5482}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 179 ]
[ 179 ]
[ 24 ]
[ 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" ]
trainer.py
/Node/trainer.py
TechMatt1337/Bastion
BSD-3-Clause
2024-11-18T20:44:01.635203+00:00
1,679,597,405,000
f26bc83e65aa4622ba13805edca1cbbd55ea8d29
3
{ "blob_id": "f26bc83e65aa4622ba13805edca1cbbd55ea8d29", "branch_name": "refs/heads/main", "committer_date": 1679597405000, "content_id": "9330a2bf32a5430f3f7ef8cb1fe386da192ea869", "detected_licenses": [ "MIT" ], "directory_id": "f1c93e8553d7b7ce1218c3779d793d0d7d5dca8c", "extension": "py", "filename": "plot_benchmarks_samplesloss_3D.py", "fork_events_count": 53, "gha_created_at": 1551378494000, "gha_event_created_at": 1679395274000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 173165841, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5907, "license": "MIT", "license_type": "permissive", "path": "/geomloss/examples/performances/plot_benchmarks_samplesloss_3D.py", "provenance": "stack-edu-0054.json.gz:575620", "repo_name": "jeanfeydy/geomloss", "revision_date": 1679597405000, "revision_id": "5804ca57f84bd95226efd1d44929022deb9cd23a", "snapshot_id": "e38a848816b6e2b0b2f11aa7a0c3141039fae8bd", "src_encoding": "UTF-8", "star_events_count": 510, "url": "https://raw.githubusercontent.com/jeanfeydy/geomloss/5804ca57f84bd95226efd1d44929022deb9cd23a/geomloss/examples/performances/plot_benchmarks_samplesloss_3D.py", "visit_date": "2023-05-10T18:55:44.179300" }
3.28125
stackv2
""" Benchmark SamplesLoss in 3D ===================================== Let's compare the performances of our losses and backends as the number of samples grows from 100 to 1,000,000. """ ############################################## # Setup # --------------------- import numpy as np import time from matplotlib import pyplot as plt import importlib import torch use_cuda = torch.cuda.is_available() from geomloss import SamplesLoss MAXTIME = 10 if use_cuda else 1 # Max number of seconds before we break the loop REDTIME = ( 2 if use_cuda else 0.2 ) # Decrease the number of runs if computations take longer than 2s... D = 3 # Let's do this in 3D # Number of samples that we'll loop upon NS = [ 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 200000, 500000, 1000000, ] ############################################## # Synthetic dataset. Feel free to use # a Stanford Bunny, or whatever! def generate_samples(N, device): """Create point clouds sampled non-uniformly on a sphere of diameter 1.""" x = torch.randn(N, D, device=device) x[:, 0] += 1 x = x / (2 * x.norm(dim=1, keepdim=True)) y = torch.randn(N, D, device=device) y[:, 1] += 2 y = y / (2 * y.norm(dim=1, keepdim=True)) x.requires_grad = True # Draw random weights: a = torch.randn(N, device=device) b = torch.randn(N, device=device) # And normalize them: a = a.abs() b = b.abs() a = a / a.sum() b = b / b.sum() return a, x, b, y ############################################## # Benchmarking loops. def benchmark(Loss, dev, N, loops=10): """Times a loss computation+gradient on an N-by-N problem.""" importlib.reload(torch) # In case we had a memory overflow just before... device = torch.device(dev) a, x, b, y = generate_samples(N, device) # We simply benchmark a Loss + gradien wrt. x code = "L = Loss( a, x, b, y ) ; L.backward()" Loss.verbose = True exec(code, locals()) # Warmup run, to compile and load everything Loss.verbose = False t_0 = time.perf_counter() # Actual benchmark -------------------- if use_cuda: torch.cuda.synchronize() for i in range(loops): exec(code, locals()) if use_cuda: torch.cuda.synchronize() elapsed = time.perf_counter() - t_0 # --------------------------- print( "{:3} NxN loss, with N ={:7}: {:3}x{:3.6f}s".format( loops, N, loops, elapsed / loops ) ) return elapsed / loops def bench_config(Loss, dev): """Times a loss computation+gradient for an increasing number of samples.""" print("Backend : {}, Device : {} -------------".format(Loss.backend, dev)) times = [] def run_bench(): try: Nloops = [100, 10, 1] nloops = Nloops.pop(0) for n in NS: elapsed = benchmark(Loss, dev, n, loops=nloops) times.append(elapsed) if (nloops * elapsed > MAXTIME) or ( nloops * elapsed > REDTIME and len(Nloops) > 0 ): nloops = Nloops.pop(0) except IndexError: print("**\nToo slow !") try: run_bench() except RuntimeError as err: if str(err)[:4] == "CUDA": print("**\nMemory overflow !") else: # CUDA memory overflows semi-break the internal # torch state and may cause some strange bugs. # In this case, best option is simply to re-launch # the benchmark. run_bench() return times + (len(NS) - len(times)) * [np.nan] def full_bench(loss, *args, **kwargs): """Benchmarks the varied backends of a geometric loss function.""" print("Benchmarking : ===============================") lines = [NS] backends = ["tensorized", "online", "multiscale"] for backend in backends: Loss = SamplesLoss(*args, **kwargs, backend=backend) lines.append(bench_config(Loss, "cuda" if use_cuda else "cpu")) benches = np.array(lines).T # Creates a pyplot figure: plt.figure() linestyles = ["o-", "s-", "^-"] for i, backend in enumerate(backends): plt.plot( benches[:, 0], benches[:, i + 1], linestyles[i], linewidth=2, label='backend="{}"'.format(backend), ) plt.title('Runtime for SamplesLoss("{}") in dimension {}'.format(Loss.loss, D)) plt.xlabel("Number of samples per measure") plt.ylabel("Seconds") plt.yscale("log") plt.xscale("log") plt.legend(loc="upper left") plt.grid(True, which="major", linestyle="-") plt.grid(True, which="minor", linestyle="dotted") plt.axis([NS[0], NS[-1], 1e-3, MAXTIME]) plt.tight_layout() # Save as a .csv to put a nice Tikz figure in the papers: header = "Npoints " + " ".join(backends) np.savetxt( "output/benchmark_" + Loss.loss + "_3D.csv", benches, fmt="%-9.5f", header=header, comments="", ) ############################################## # Gaussian MMD, with a small blur # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # full_bench(SamplesLoss, "gaussian", blur=0.1, truncate=3) ############################################## # Energy Distance MMD # ~~~~~~~~~~~~~~~~~~~~~~ # full_bench(SamplesLoss, "energy") ############################################## # Sinkhorn divergence # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # With a medium blurring scale, at one twentieth of the # configuration's diameter: full_bench(SamplesLoss, "sinkhorn", p=2, blur=0.05, diameter=1) ############################################## # With a small blurring scale, at one hundredth of the # configuration's diameter: full_bench(SamplesLoss, "sinkhorn", p=2, blur=0.01, diameter=1) plt.show()
233
24.35
83
17
1,552
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.exec-detected_4b645e6d63fb914e_ead18d1d", "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": 94, "line_end": 94, "column_start": 5, "column_end": 25, "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/tmprvd6_wj2/4b645e6d63fb914e.py", "start": {"line": 94, "col": 5, "offset": 2015}, "end": {"line": 94, "col": 25, "offset": 2035}, "extra": {"message": "Detected the use of exec(). exec() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.exec-detected_4b645e6d63fb914e_19177172", "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": 101, "line_end": 101, "column_start": 9, "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.exec-detected", "path": "/tmp/tmprvd6_wj2/4b645e6d63fb914e.py", "start": {"line": 101, "col": 9, "offset": 2264}, "end": {"line": 101, "col": 29, "offset": 2284}, "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"}}}]
2
true
[ "CWE-95", "CWE-95" ]
[ "rules.python.lang.security.audit.exec-detected", "rules.python.lang.security.audit.exec-detected" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 94, 101 ]
[ 94, 101 ]
[ 5, 9 ]
[ 25, 29 ]
[ "A03:2021 - Injection", "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.", "Detected the use of exec(). exec() can be dangerous if used...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "HIGH", "HIGH" ]
plot_benchmarks_samplesloss_3D.py
/geomloss/examples/performances/plot_benchmarks_samplesloss_3D.py
jeanfeydy/geomloss
MIT
2024-11-18T20:44:07.584358+00:00
1,485,810,103,000
62977f7ee225ee575a2f3813c47ecbc391c84558
3
{ "blob_id": "62977f7ee225ee575a2f3813c47ecbc391c84558", "branch_name": "refs/heads/master", "committer_date": 1485810103000, "content_id": "ff50de263a2898143330ca8a2d94510d6098959f", "detected_licenses": [ "MIT" ], "directory_id": "56cac9506b9870474c620639ba71129d78f5745c", "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": 1394, "license": "MIT", "license_type": "permissive", "path": "/simple_site_crawler/utils.py", "provenance": "stack-edu-0054.json.gz:575679", "repo_name": "Adel-B/simple-site-crawler", "revision_date": 1485810103000, "revision_id": "ddb2db60308cb091e09732d0f0527145fb346c75", "snapshot_id": "fd1a4864056a6bbe8cc874c7b7e97fe199950bf5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Adel-B/simple-site-crawler/ddb2db60308cb091e09732d0f0527145fb346c75/simple_site_crawler/utils.py", "visit_date": "2021-01-08T10:45:52.664015" }
3.140625
stackv2
""" Test `simple_site_crawler.site_crawler` file """ import xml.etree.cElementTree as ET from xml.dom import minidom def generate_sitemap_xml(urls, filename='sitemap.xml'): """ Generate 'sitemap.xml' file based on passed urls :param urls: list of URLs :type urls: list of str :param filename: output file name :type filename: str """ urlset = ET.Element( 'urlset', xmlns='http://www.sitemaps.org/schemas/sitemap/0.9', ) for webpage_url in urls: url = ET.SubElement(urlset, 'url') ET.SubElement(url, 'loc').text = webpage_url pretty_xml = minidom.parseString( ET.tostring(urlset), ).toprettyxml( encoding='UTF-8', ) with open(filename, 'wb') as f: f.write(pretty_xml) def render_children(children, prefix='│ ├── ', last_item_prefix='│ └── '): """ Simple helper for rendering element children :param children: children container :type children: iterable object :param prefix: string that will prefix the child element :type prefix: str :param last_item_prefix: string that will prefix the last child elemment :return: rendered children string :rtype: str """ s = '' for item in children[:-1]: s += '{}{}\n'.format(prefix, item) s += '{}{}'.format(last_item_prefix, children[-1]) return s
55
24.05
78
12
351
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_cde5800f545af206_08ae678a", "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": 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/tmpr7mo7ysm/cde5800f545af206.py", "start": {"line": 4, "col": 1, "offset": 53}, "end": {"line": 4, "col": 36, "offset": 88}, "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_cde5800f545af206_a1921ac7", "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": 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/tmpr7mo7ysm/cde5800f545af206.py", "start": {"line": 5, "col": 1, "offset": 89}, "end": {"line": 5, "col": 28, "offset": 116}, "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" ]
[ 4, 5 ]
[ 4, 5 ]
[ 1, 1 ]
[ 36, 28 ]
[ "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" ]
utils.py
/simple_site_crawler/utils.py
Adel-B/simple-site-crawler
MIT
2024-11-18T20:44:08.375538+00:00
1,378,847,047,000
4c7c92161011767a0435760d46768d4300524937
3
{ "blob_id": "4c7c92161011767a0435760d46768d4300524937", "branch_name": "refs/heads/master", "committer_date": 1378847047000, "content_id": "9261ba4838a2c592d4cf63c6b739efb8e5fa43ed", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "8f37ab37716d3503ba6836e4bf81253e6f635d70", "extension": "py", "filename": "__init__.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 3586640, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3110, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/flask_mustache/__init__.py", "provenance": "stack-edu-0054.json.gz:575689", "repo_name": "bradwright/flask-mustachejs", "revision_date": 1378847047000, "revision_id": "acdc2f5af982c725f311dea86d5a1dab9fb7d38a", "snapshot_id": "61c7e00e154f11c64e4630664a4730dd4755611e", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/bradwright/flask-mustachejs/acdc2f5af982c725f311dea86d5a1dab9fb7d38a/flask_mustache/__init__.py", "visit_date": "2020-04-10T03:56:09.801126" }
2.671875
stackv2
"flask-mustache Flask plugin" from jinja2 import Template import pystache from flask import current_app, Blueprint __all__ = ('FlaskMustache',) mustache_app = Blueprint('mustache', __name__, template_folder='templates', static_folder='static') class FlaskMustache(object): "Wrapper to inject Mustache stuff into Flask" def __init__(self, app=None): self.app = app if app is not None: self.init_app(app) def init_app(self, app): "Wrapper around the app so that we can instantiate it from different places" self.app = app # XXX: this url_prefix is due to a bug in Blueprints where the # static assets aren't available until they have a `url_prefix` app.register_blueprint(mustache_app, url_prefix='/_mustache') # set up global `mustache` function app.jinja_env.globals['mustache'] = mustache # attach context processor with template content app.context_processor(mustache_templates) @staticmethod def attach(app): "This is written so it can work like WSGI middleware" # noop _ = FlaskMustache(app) return app def get_template(name): # throw away everything except the file content template, _, _ = current_app.jinja_env.loader.get_source(current_app.jinja_env, name) return template # context processor def mustache_templates(): "Returns the content of all Mustache templates in the Jinja environment" # TODO: add a config option to load mustache templates into the # global context # get all the templates this env knows about all_templates = current_app.jinja_env.loader.list_templates() ctx_mustache_templates = {} for template_name in all_templates: # TODO: make this configurable # we only want a specific extension if template_name.endswith('mustache'): ctx_mustache_templates[template_name] = get_template(template_name) # prepare context for Jinja context = { 'mustache_templates': ctx_mustache_templates } # returns the full HTML, ready to use in JavaScript template = current_app.jinja_env.get_template('_template_script_block.jinja') return {'mustache_templates': template.render(context)} # template helper function def mustache(template, partials=None, **kwargs): """Usage: {{ mustache('path/to/whatever.mustache', key=value, key1=value1.. keyn=valuen) }} or, with partials {{ mustache('path/to/whatever.mustache', partials={'partial_name': 'path/to/partial.mustache'}, \ key1=value1.. keyn=valuen) }} This uses the regular Jinja2 loader to find the templates, so your *.mustache files will need to be available in that path. """ # TODO: cache loaded templates template = get_template(template) _partials = None if partials: _partials = dict((name, get_template(path)) for name, path in partials.iteritems()) renderer = pystache.Renderer(partials=_partials) return renderer.render(template, kwargs, encoding='utf-8')
98
30.73
105
13
708
python
[{"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_a92d80b1f402d9b6_6c186031", "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": 74, "line_end": 74, "column_start": 35, "column_end": 59, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "path": "/tmp/tmpr7mo7ysm/a92d80b1f402d9b6.py", "start": {"line": 74, "col": 35, "offset": 2255}, "end": {"line": 74, "col": 59, "offset": 2279}, "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"}}}]
1
true
[ "CWE-79" ]
[ "rules.python.flask.security.xss.audit.direct-use-of-jinja2" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 74 ]
[ 74 ]
[ 35 ]
[ 59 ]
[ "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" ]
__init__.py
/flask_mustache/__init__.py
bradwright/flask-mustachejs
BSD-3-Clause
2024-11-18T20:44:10.207936+00:00
1,689,877,491,000
105dbf43b674597e6e824c1cb6087c0fe3a64d5f
2
{ "blob_id": "105dbf43b674597e6e824c1cb6087c0fe3a64d5f", "branch_name": "refs/heads/master", "committer_date": 1689877491000, "content_id": "7b52039b9046fdffc5ab90f350a33ce25236e8e3", "detected_licenses": [ "MIT" ], "directory_id": "5d456c15459f088cc92fd9a8dcd8d4d2f6382107", "extension": "py", "filename": "mvtcae.py", "fork_events_count": 1, "gha_created_at": 1611605330000, "gha_event_created_at": 1694435902000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 332869557, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8240, "license": "MIT", "license_type": "permissive", "path": "/multiviewae/models/mvtcae.py", "provenance": "stack-edu-0054.json.gz:575715", "repo_name": "alawryaguila/multi-view-AE", "revision_date": 1689877491000, "revision_id": "b9372d409666a3a93007fa4b9900e1d6a5a21e61", "snapshot_id": "3e6453934b50aacf1e3b515eeb4e717cd7b00fbf", "src_encoding": "UTF-8", "star_events_count": 15, "url": "https://raw.githubusercontent.com/alawryaguila/multi-view-AE/b9372d409666a3a93007fa4b9900e1d6a5a21e61/multiviewae/models/mvtcae.py", "visit_date": "2023-08-08T10:39:27.177913" }
2.484375
stackv2
import torch import hydra from ..base.constants import MODEL_MVTCAE from ..base.base_model import BaseModelVAE from ..base.representations import ProductOfExperts class mvtCAE(BaseModelVAE): r""" Multi-View Total Correlation Auto-Encoder (MVTCAE). Code is based on: https://github.com/gr8joo/MVTCAE NOTE: This implementation currently only caters for a PoE posterior distribution. MoE and MoPoE posteriors will be included in further work. Args: cfg (str): Path to configuration file. Model specific parameters in addition to default parameters: - model.beta (int, float): KL divergence weighting term. - model.alpha (int, float): Log likelihood, Conditional VIB and VIB weighting term. - encoder.default._target_ (multiviewae.architectures.mlp.VariationalEncoder): Type of encoder class to use. - encoder.default.enc_dist._target_ (multiviewae.base.distributions.Normal, multiviewae.base.distributions.MultivariateNormal): Encoding distribution. - decoder.default._target_ (multiviewae.architectures.mlp.VariationalDecoder): Type of decoder class to use. - decoder.default.init_logvar(int, float): Initial value for log variance of decoder. - decoder.default.dec_dist._target_ (multiviewae.base.distributions.Normal, multiviewae.base.distributions.MultivariateNormal): Decoding distribution. input_dim (list): Dimensionality of the input data. z_dim (int): Number of latent dimensions. References ---------- Hwang, HyeongJoo and Kim, Geon-Hyeong and Hong, Seunghoon and Kim, Kee-Eung. Multi-View Representation Learning via Total Correlation Objective. 2021. NeurIPS """ def __init__( self, cfg = None, input_dim = None, z_dim = None ): super().__init__(model_name=MODEL_MVTCAE, cfg=cfg, input_dim=input_dim, z_dim=z_dim) def encode(self, x): r"""Forward pass through encoder networks. Args: x (list): list of input data of type torch.Tensor. Returns: Returns either the joint or separate encoding distributions depending on whether the model is in the training stage: qz_xs (list): list containing separate encoding distributions. qz_x (list): Single element list containing PoE joint encoding distribution. """ if self._training: qz_xs = [] for i in range(self.n_views): mu, logvar = self.encoders[i](x[i]) qz_x = hydra.utils.instantiate( eval(f"self.cfg.encoder.enc{i}.enc_dist"), loc=mu, scale=logvar.exp().pow(0.5) ) qz_xs.append(qz_x) return qz_xs else: mu = [] logvar = [] for i in range(self.n_views): mu_, logvar_ = self.encoders[i](x[i]) mu.append(mu_) logvar.append(logvar_) mu = torch.stack(mu) logvar = torch.stack(logvar) mu, logvar = ProductOfExperts()(mu, logvar) qz_x = hydra.utils.instantiate( self.cfg.encoder.default.enc_dist, loc=mu, scale=logvar.exp().pow(0.5) ) qz_x = [qz_x] return qz_x def decode(self, qz_xs): r"""Forward pass of joint latent dimensions through decoder networks. Args: x (list): list of input data of type torch.Tensor. Returns: (list): A nested list of decoding distributions, px_zs. The outer list has a single element indicating the shared latent dimensions. The inner list is a n_view element list with the position in the list indicating the decoder index. """ if self._training: mu = [qz_x.loc for qz_x in qz_xs] var = [qz_x.variance for qz_x in qz_xs] mu = torch.stack(mu) var = torch.stack(var) mu, logvar = ProductOfExperts()(mu, torch.log(var)) px_zs = [] for i in range(self.n_views): px_z = self.decoders[i]( hydra.utils.instantiate( self.cfg.encoder.default.enc_dist, loc=mu, scale=logvar.exp().pow(0.5) ).rsample() ) px_zs.append(px_z) return [px_zs] else: px_zs = [] for i in range(self.n_views): px_z = self.decoders[i](qz_xs[0].loc) px_zs.append(px_z) return [px_zs] def forward(self, x): r"""Apply encode and decode methods to input data to generate the joint latent dimensions and data reconstructions. Args: x (list): list of input data of type torch.Tensor. Returns: fwd_rtn (dict): dictionary containing encoding and decoding distributions. """ qz_xs = self.encode(x) px_zs = self.decode(qz_xs) fwd_rtn = {"px_zs": px_zs, "qz_xs": qz_xs} return fwd_rtn def loss_function(self, x, fwd_rtn): r"""Calculate MVTCAE loss. Args: x (list): list of input data of type torch.Tensor. fwd_rtn (dict): dictionary containing encoding and decoding distributions. Returns: losses (dict): dictionary containing each element of the MVTCAE loss. """ px_zs = fwd_rtn["px_zs"] qz_xs = fwd_rtn["qz_xs"] rec_weight = (self.n_views - self.alpha) / self.n_views cvib_weight = self.alpha / self.n_views vib_weight = 1 - self.alpha grp_kl = self.calc_kl_groupwise(qz_xs) cvib_kl = self.calc_kl_cvib(qz_xs) ll = self.calc_ll(x, px_zs) kld_weighted = cvib_weight * cvib_kl + vib_weight * grp_kl total = -rec_weight * ll + self.beta * kld_weighted losses = {"loss": total, "kl_cvib": cvib_kl, "kl_grp": grp_kl, "ll": ll} return losses def calc_kl_cvib(self, qz_xs): r"""Calculate KL-divergence between PoE joint encoding distribution and the encoding distribution for each view. Args: qz_xs (list): list of encoding distributions of each view. Returns: kl (torch.Tensor): KL-divergence loss. """ mu = [qz_x.loc for qz_x in qz_xs] var = [qz_x.variance for qz_x in qz_xs] mu = torch.stack(mu) var = torch.stack(var) mu, logvar = ProductOfExperts()(mu, torch.log(var)) kl = 0 for i in range(self.n_views): kl += ( hydra.utils.instantiate( eval(f"self.cfg.encoder.enc{i}.enc_dist"), loc=mu, scale=logvar.exp().pow(0.5) ) .kl_divergence(qz_xs[i]).sum(1, keepdims=True).mean(0) ) return kl def calc_kl_groupwise(self, qz_xs): r"""Calculate KL-divergence between the encoding distribution for each view and the prior distribution. Args: qz_xs (list): list of encoding distributions of each view. Returns: kl (torch.Tensor): KL-divergence loss. """ mu = [qz_x.loc for qz_x in qz_xs] var = [qz_x.variance for qz_x in qz_xs] mu = torch.stack(mu) var = torch.stack(var) mu, logvar = ProductOfExperts()(mu, torch.log(var)) return ( hydra.utils.instantiate( self.cfg.encoder.default.enc_dist, loc=mu, scale=logvar.exp().pow(0.5) ) .kl_divergence(self.prior).sum(1, keepdims=True).mean(0) ) def calc_ll(self, x, px_zs): r"""Calculate log-likelihood loss. Args: x (list): list of input data of type torch.Tensor. px_zs (list): list of decoding distributions. Returns: ll (torch.Tensor): Log-likelihood loss. """ ll = 0 for i in range(self.n_views): ll += px_zs[0][i].log_likelihood(x[i]).mean(0).sum() #first index is latent, second index is view return ll
217
36.97
162
24
1,972
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_ef488c1853069b67_1cc85e11", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 65, "line_end": 65, "column_start": 21, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpr7mo7ysm/ef488c1853069b67.py", "start": {"line": 65, "col": 21, "offset": 2711}, "end": {"line": 65, "col": 62, "offset": 2752}, "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_ef488c1853069b67_26c9881c", "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": 177, "line_end": 177, "column_start": 21, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpr7mo7ysm/ef488c1853069b67.py", "start": {"line": 177, "col": 21, "offset": 6800}, "end": {"line": 177, "col": 62, "offset": 6841}, "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" ]
[ 65, 177 ]
[ 65, 177 ]
[ 21, 21 ]
[ 62, 62 ]
[ "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" ]
mvtcae.py
/multiviewae/models/mvtcae.py
alawryaguila/multi-view-AE
MIT
2024-11-18T20:44:12.600072+00:00
1,676,139,610,000
f3f1454fd7b5dc4c3db60a4871bf8cc0b9f00f3d
3
{ "blob_id": "f3f1454fd7b5dc4c3db60a4871bf8cc0b9f00f3d", "branch_name": "refs/heads/master", "committer_date": 1676139610000, "content_id": "271c88e82ca2fb56bd071680f5987c5fa4bf59b8", "detected_licenses": [ "MIT" ], "directory_id": "255e19ddc1bcde0d3d4fe70e01cec9bb724979c9", "extension": "py", "filename": "snippet.py", "fork_events_count": 19, "gha_created_at": 1517501964000, "gha_event_created_at": 1595733295000, "gha_language": "Python", "gha_license_id": null, "github_id": 119861038, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2673, "license": "MIT", "license_type": "permissive", "path": "/all-gists/235395/snippet.py", "provenance": "stack-edu-0054.json.gz:575743", "repo_name": "gistable/gistable", "revision_date": 1676139610000, "revision_id": "665d39a2bd82543d5196555f0801ef8fd4a3ee48", "snapshot_id": "26c1e909928ec463026811f69b61619b62f14721", "src_encoding": "UTF-8", "star_events_count": 76, "url": "https://raw.githubusercontent.com/gistable/gistable/665d39a2bd82543d5196555f0801ef8fd4a3ee48/all-gists/235395/snippet.py", "visit_date": "2023-02-17T21:33:55.558398" }
3.0625
stackv2
#!/usr/bin/env python """Measure performance for 3 cases: 1. dict has key at the start of list 2. dict has key at the end of list 3. dict has no key in a list See http://stackoverflow.com/questions/1737778/dict-has-key-from-list """ from functools import wraps from itertools import imap def to_compare(function): """Decorator to add `function` to global comparison registry. NOTE: It changes interface of the `function` in order to use make-figure.py """ if not hasattr(to_compare, 'functions'): to_compare.functions = [] @wraps(function) def wrapper(args): # transform interface for make-figure.py return function(args[0], args[1]) to_compare.functions.append(wrapper) return wrapper @to_compare def mgag_loop(myDict, myList): for i in myList: if i in myDict: return True return False @to_compare def ronny_any(myDict, myList): return any(x in myDict for x in myList) @to_compare def ronny_set(myDict, myList): return set(myDict) & set(myList) @to_compare def pablo_len(myDict, myList): return len([x for x in myList if x in myDict]) > 0 @to_compare def jfs_map(my_dict, my_list): return any(map(my_dict.__contains__, my_list)) @to_compare def jfs_imap(my_dict, my_list): return any(imap(my_dict.__contains__, my_list)) def args_key_at_start(n): 'Make args for comparison functions "key at start" case.' d, lst = args_no_key(n) lst.insert(0, n//2) assert (n//2) in d and lst[0] == (n//2) return (d, lst) def args_key_at_end(n): 'Make args for comparison functions "key at end" case.' d, lst = args_no_key(n) lst.append(n//2) assert (n//2) in d and lst[-1] == (n//2) return (d, lst) def args_no_key(n): 'Make args for comparison functions "no key" case.' d = dict.fromkeys(xrange(n)) lst = range(n, 2*n+1) assert not any(x in d for x in lst) return (d, lst) if __name__ == '__main__': from subprocess import check_call import sys # check that all function produce expected result assert all(f(make_args(5)) for f in to_compare.functions for make_args in [args_key_at_start, args_key_at_end]) assert not any(f(make_args(5)) for f in to_compare.functions for make_args in [args_no_key]) # measure performance and plot it check_call( ["python", "make-figures.py"] + ["--sort-function=main." + f.__name__ for f in to_compare.functions] + ["--sequence-creator=main." + f.__name__ for f in (args_key_at_start, args_key_at_end, args_no_key)] + sys.argv[1:])
96
26.84
79
13
714
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_04c061658bcad606_babcf37d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 91, "line_end": 96, "column_start": 5, "column_end": 22, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/04c061658bcad606.py", "start": {"line": 91, "col": 5, "offset": 2400}, "end": {"line": 96, "col": 22, "offset": 2672}, "extra": {"message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 91 ]
[ 96 ]
[ 5 ]
[ 22 ]
[ "A01:2017 - Injection" ]
[ "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'." ]
[ 7.5 ]
[ "LOW" ]
[ "HIGH" ]
snippet.py
/all-gists/235395/snippet.py
gistable/gistable
MIT
2024-11-18T20:44:14.916340+00:00
1,467,068,014,000
1c981f27c0e397a4141b5c9583ca8140c8fe771e
2
{ "blob_id": "1c981f27c0e397a4141b5c9583ca8140c8fe771e", "branch_name": "refs/heads/master", "committer_date": 1467068014000, "content_id": "8b3ab12bab1cb6fb5e21c723af5c123731f54990", "detected_licenses": [ "MIT" ], "directory_id": "8aa8635ece403d3ca38c7cb6c8f2f0614962f558", "extension": "py", "filename": "DataSource.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 62093548, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12269, "license": "MIT", "license_type": "permissive", "path": "/event-detection-master/Utils/DataSource.py", "provenance": "stack-edu-0054.json.gz:575751", "repo_name": "a-raina/Event-Detection-using-NLP", "revision_date": 1467068014000, "revision_id": "0f68e90635cb64745083bdaa39c4e4617b490509", "snapshot_id": "e1740281d01550f007c73d72b9b6c3a130411bf5", "src_encoding": "UTF-8", "star_events_count": 13, "url": "https://raw.githubusercontent.com/a-raina/Event-Detection-using-NLP/0f68e90635cb64745083bdaa39c4e4617b490509/event-detection-master/Utils/DataSource.py", "visit_date": "2021-01-20T20:32:38.743272" }
2.421875
stackv2
#!/usr/bin/python # import cgitb # cgitb.enable() import sys; import os sys.path.insert(0, os.path.abspath('..')) sys.path.insert(0, os.path.abspath('.')) import psycopg2 import re from Utils.Globals import * class DataSource: def __init__(self): """ Create a DataSource object :return: None """ db = database try: # create a connection to event_detection database conn = psycopg2.connect(user='root', database=db) conn.autocommit = True except: print("Error: cannot connect to event_detection database") sys.exit() try: self.cursor = conn.cursor() except: print("Error: cannot create cursor") sys.exit() def get_unprocessed_queries(self): """ Gets all queries from the database that are not yet marked as processed :return: all unprocessed queries """ self.cursor.execute("SELECT q.id, q.subject, q.verb, q.direct_obj, q.indirect_obj, q.loc \ FROM queries q \ WHERE q.processed = false") return self.cursor.fetchall() def get_unprocessed_query_article_pairs(self): """ Gets all query-article pairs that are not marked as processed :return: all unprocessed query-article pairs """ self.cursor.execute("SELECT qa.query, qa.article FROM query_articles qa\ WHERE qa.processed = false") return self.cursor.fetchall() def get_query_synonyms(self, query_id): """ Gets information about a query :param query_id: the query to retrieve synonyms for :return: word, pos, sense and synonyms for the query """ self.cursor.execute("SELECT word, pos, sense, synonyms FROM query_words WHERE query=%s", (query_id,)) return self.cursor.fetchall() def get_article_keywords(self, article_id): """ Gets keywords for an article :param article_id: the id to retrieve keywords for :return: the keywords for the article """ self.cursor.execute("SELECT keywords FROM articles WHERE id=%s", (article_id, )) words = self.cursor.fetchone() return words def get_all_article_keywords(self): """ Gets keywords for all articles :return: the keywords for all articles """ self.cursor.execute("SELECT keywords FROM articles WHERE keywords IS NOT null;") return self.cursor.fetchall() def get_all_titles_and_keywords(self): """ Gets titles and keywords for all articles Does not retrieve these if the keywords are null (article unprocessed) :return: titles and keywords for all articles """ self.cursor.execute("SELECT title, keywords FROM articles WHERE keywords IS NOT null;") return self.cursor.fetchall() def get_all_article_ids_and_keywords(self): """ Gets ids and keywords for all articles Does not retrieve these if the keywords are null (article unprocessed) :return: ids and keywords for all articles """ self.cursor.execute("SELECT id, keywords FROM articles WHERE keywords IS NOT null;") return self.cursor.fetchall() def get_articles(self): """ Gets all article ids :return: ids for all articles """ self.cursor.execute("SELECT id FROM articles") return self.cursor.fetchall() def get_all_article_ids_and_filenames(self): """ Gets ids and filenames for all articles :return: ids and filenames for all articles """ self.cursor.execute("SELECT id, filename FROM articles;") return self.cursor.fetchall() def get_article_ids_titles_filenames(self): """ Gets ids, titles and filenames for all articles :return: ids, titles and filenames for all articles """ self.cursor.execute("SELECT id, title, filename FROM articles;") return self.cursor.fetchall() def insert_query_word_synonym(self, query_id, query_word, pos_group, synonyms): """ Inserts information about a query into query words :param query_id: the id of the query :param query_word: the word from the query :param pos_group: to POS for the query word :param synonyms: the synonyms for the query word :return: None """ self.cursor.execute("INSERT INTO query_words (query, word, pos, sense, synonyms) VALUES (%s, %s ,%s, '',%s)", \ (query_id, query_word, pos_group, synonyms)) def post_validator_update(self, matching_prob, query_id, article_id): """ Updates query articles after the validator is run :param matching_prob: the probability of the match :param query_id: the query id :param article_id: the article id :return: None """ self.cursor.execute("UPDATE query_articles SET processed=true, accuracy=%s WHERE query=%s AND article=%s",\ (matching_prob, query_id, article_id)) def post_query_processor_update(self, query_id): """ Sets a query to processed in the database This involves setting it to processed in the queries table and adding a row with it and all articles in the query_articles table :param query_id: the query id :return: None """ self.cursor.execute("UPDATE queries SET processed=true WHERE id=%s", (query_id, )) for article_id in self.get_articles(): self.cursor.execute("INSERT INTO query_articles (query, article) VALUES (%s, %s) ON CONFLICT DO NOTHING", (query_id, article_id)) def get_query_elements(self, query_id): """ Gets the subject, verb, direct object, indirect object and location for a query :param query_id: the query id :return: the subject, verb, direct object, indirect object and location """ self.cursor.execute("SELECT subject, verb, direct_obj, indirect_obj, loc FROM queries WHERE id=%s", (query_id, )) elements = self.cursor.fetchone() elements = [element for element in elements if element is not None or element is not ""] return elements def get_article_url(self, article_id): """ Gets the URL for an article :param article_id: the article id :return: the article URL """ self.cursor.execute("SELECT url FROM articles WHERE id=%s", (article_id, )) return str(self.cursor.fetchone()[0]) def get_article_title(self, article_id): """ Gets the title for an article :param article_id: the article id :return: the article title """ self.cursor.execute("SELECT title FROM articles WHERE id=%s", (article_id, )) return str(self.cursor.fetchone()[0]) def get_email_and_phone(self, query_id): """ Gets the article and phone number associated to a query :param query_id: the query id :return: the phone number and email """ self.cursor.execute("SELECT userid FROM queries WHERE id="+str(query_id)) user_id = self.cursor.fetchone()[0] self.cursor.execute("SELECT phone FROM users WHERE id="+str(user_id)) phone = str(self.cursor.fetchone()[0]) if phone is not None: phone = re.sub(r'-', '', phone) phone = "+1" + phone self.cursor.execute("SELECT email FROM users WHERE id="+str(user_id)) email = str(self.cursor.fetchone()[0]) return phone, email def get_unprocessed_articles(self): """ Gets all unprocessed articles that need keyword extraction to be performed :return: id, title, filename, url and source for all unprocessed articles """ self.cursor.execute("SELECT id, title, filename, url, source FROM articles WHERE keywords is null;") return self.cursor.fetchall() def add_keywords_to_article(self, article_id, keyword_string): """ Adds keyword JSON string to an article :param article_id: the article id :param keyword_string: the JSON string of keywords :return: None """ self.cursor.execute("UPDATE articles SET keywords = %s WHERE id = %s", (keyword_string, article_id)) def article_processed(self, article_id): """ Checks if an article has been processed :param article_id: the id of the article :return: True if the article has been processed, False otherwise """ self.cursor.execute("SELECT keywords FROM articles WHERE id = %s;", (article_id, )) return self.cursor.fetchone()[0] is not None def query_route(self, query_id): """ Gets a query for web app with validating article counts :param query_id: the id of the query :return: the query """ self.cursor.execute("SELECT a.title, s.source_name as source, a.url \ FROM queries q \ INNER JOIN query_articles qa on q.id = qa.query \ INNER JOIN articles a on qa.article = a.id \ INNER JOIN sources s on s.id = a.source \ WHERE q.id = %s and qa.notification_sent = true;", (query_id,)) articles = self.cursor.fetchall() self.cursor.execute("SELECT id, subject, verb, direct_obj, indirect_obj, loc FROM queries where id = %s;", (query_id,)) query = self.cursor.fetchone() return articles, query def queries_route(self): """ Gets all queries for web app with validating article counts :return: all queries """ self.cursor.execute("SELECT q.id, q.subject, q.verb, q.direct_obj, q.indirect_obj, \ q.loc, count(qa.article) as article_count \ FROM queries q \ LEFT JOIN query_articles qa on q.id = qa.query and qa.notification_sent = true \ GROUP BY(q.id);") return self.cursor.fetchall() def new_query(self, email, phone, subject, verb, direct_obj, indirect_obj, loc): """ Add a query to the database for a user :param email: the user's email :param phone: the user's phone number :param subject: the query subject :param verb: the query verb :param direct_obj: the query direct object :param indirect_obj: the query indirect object :param loc: the query location :return: True if no error """ self.cursor.execute("SELECT id from users where email = %s and phone = %s", (email, phone)) # use existing user if it exists user_id = self.cursor.fetchone() if user_id: user_id = user_id[0] else: self.cursor.execute("INSERT INTO users (email, phone) VALUES (%s, %s) RETURNING id;", (email, phone)) user_id = self.cursor.fetchone()[0] try: self.cursor.execute("INSERT INTO queries (subject, verb, direct_obj, indirect_obj, loc, userid) \ VALUES (%s, %s, %s, %s, %s, %s);", (subject, verb, direct_obj, indirect_obj, loc, user_id)) except psycopg2.IntegrityError: return False return True def add_article_to_query_articles(self, article_id): self.cursor.execute("SELECT id FROM queries;") query_ids = self.cursor.fetchall() for query_id in query_ids: self.cursor.execute("INSERT INTO query_articles (query, article) VALUES (%s, %s) ON CONFLICT DO NOTHING", (query_id, article_id)) # query | article | accuracy | processed def articles_route(self): """ Gets all queries for web app with source name strings :return: the article titles, source names and URLs """ self.cursor.execute("SELECT title, s.source_name as source, url FROM articles a \ INNER JOIN sources s on s.id = a.source;") return self.cursor.fetchall()
301
39.76
142
15
2,565
python
[{"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_a7fb2255c31a2634_4d602ae4", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 192, "line_end": 192, "column_start": 9, "column_end": 82, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpr7mo7ysm/a7fb2255c31a2634.py", "start": {"line": 192, "col": 9, "offset": 7277}, "end": {"line": 192, "col": 82, "offset": 7350}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_a7fb2255c31a2634_60cdbc08", "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": 194, "line_end": 194, "column_start": 9, "column_end": 78, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpr7mo7ysm/a7fb2255c31a2634.py", "start": {"line": 194, "col": 9, "offset": 7403}, "end": {"line": 194, "col": 78, "offset": 7472}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_a7fb2255c31a2634_61aa5639", "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": 199, "line_end": 199, "column_start": 9, "column_end": 78, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpr7mo7ysm/a7fb2255c31a2634.py", "start": {"line": 199, "col": 9, "offset": 7635}, "end": {"line": 199, "col": 78, "offset": 7704}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-89", "CWE-89", "CWE-89" ]
[ "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query" ]
[ "security", "security", "security" ]
[ "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH" ]
[ 192, 194, 199 ]
[ 192, 194, 199 ]
[ 9, 9, 9 ]
[ 82, 78, 78 ]
[ "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expre...
[ 7.5, 7.5, 7.5 ]
[ "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH" ]
DataSource.py
/event-detection-master/Utils/DataSource.py
a-raina/Event-Detection-using-NLP
MIT
2024-11-18T20:44:16.583712+00:00
1,560,361,383,000
b6eed866fb4711d3adfab506b0107f6029cac779
2
{ "blob_id": "b6eed866fb4711d3adfab506b0107f6029cac779", "branch_name": "refs/heads/master", "committer_date": 1560361383000, "content_id": "9e394c94dc2bf50a5709592d4eb10424b771ae42", "detected_licenses": [ "Apache-2.0" ], "directory_id": "94e9da5e4f3232fe19c96cb463fe7c885e5fdab7", "extension": "py", "filename": "query_graph_utils.py", "fork_events_count": 2, "gha_created_at": 1537475301000, "gha_event_created_at": 1542040253000, "gha_language": "Python", "gha_license_id": "Apache-2.0", "github_id": 149666791, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9261, "license": "Apache-2.0", "license_type": "permissive", "path": "/omniscient/utils/query_graph_utils.py", "provenance": "stack-edu-0054.json.gz:575777", "repo_name": "Impavidity/Omniscient", "revision_date": 1560361383000, "revision_id": "4e51791739dc9c1b1399df42ff36e0920b4c1c5c", "snapshot_id": "58af14e838467d689ca6f5aeaef11ab5a9bdf3e2", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/Impavidity/Omniscient/4e51791739dc9c1b1399df42ff36e0920b4c1c5c/omniscient/utils/query_graph_utils.py", "visit_date": "2020-03-29T07:29:18.925158" }
2.421875
stackv2
import copy import json import logging import os import uuid import subprocess from omniscient.structure.query_graph import QueryGraph from omniscient.structure.stage import Stage from omniscient.structure.sentence import Sentence from omniscient.structure.mention import Mention from omniscient.structure import constant try: from omniscient.kg.tdb_query import TDBQuery except: pass TMP_DIR = "sparql_tmp" LOGGER = logging.getLogger("QueryGraphUtils") LOGGER.setLevel(logging.INFO) def reverse_direction(direction): if direction == constant.P_FORWARD: return constant.P_BACKWARD if direction == constant.P_BACKWARD: return constant.P_FORWARD raise ValueError("Error argument on {}".format(direction)) class QueryGraphUtils(object): def __init__( self, use_tdb_query=False, kb_type=None, kb_index_path=None): self.use_tdb_query = use_tdb_query self.kb_type = kb_type self.kb_index_path = kb_index_path self.query_client = None if use_tdb_query and kb_type and kb_index_path: self.query_client = TDBQuery(path=self.kb_index_path) def sparql_to_json(self, sparql): """ Args: sparql: Returns: """ if not os.path.exists(TMP_DIR): os.mkdir(TMP_DIR) tmp_file_path = os.path.join(TMP_DIR, str(uuid.uuid4())) with open(tmp_file_path, "w") as query_fout: refined_sparql = "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n{}\n".format( sparql.strip().replace(" OR ", " || ")) query_fout.write(refined_sparql) json_string = subprocess.check_output( 'sparql-to-json {}'.format(tmp_file_path), shell=True).decode("utf-8") json_dict = json.loads(json_string) os.remove(tmp_file_path) return json_dict, refined_sparql def json_to_graph(self, json_dict, sparql=None): """ This function is to convert the json dict into `QueryGraph` Args: json_dict (dict): the output of sparql2json Returns: QueryGraph """ query_graph = QueryGraph(sparql) for where_args in json_dict["where"]: if where_args["type"] == "bgp": for triple in where_args["triples"]: query_graph.add_edge((triple["subject"], triple["predicate"], triple["object"])) return query_graph def sparql_to_graph(self, sparql, is_grounding=False, grounded_results=None): """ This function is to convert full sparql query into `QueryGraph` Args: sparql (str): sparql query Returns: Tuple(json_dict, `QueryGraph`) """ sparql_parse_json, refined_sparql = self.sparql_to_json(sparql=sparql) graph = self.json_to_graph(json_dict=sparql_parse_json, sparql=refined_sparql) if is_grounding: if grounded_results: graph.grounding(grounded_results=grounded_results) elif self.query_client: results = self.query_client.query(refined_sparql.replace( "DISTINCT ?x", "DISTINCT *").encode("utf-8")) if results: graph.grounding(grounded_results=results) else: LOGGER.info("grounding failed with \n{}\n".format(refined_sparql)) else: raise ValueError("Grounded results are needed or the query client should be initialized") return sparql_parse_json, graph def batch_grounding(self, graphs): """ Args: graphs: Batching all graphs for parallel grounding Returns: """ raise NotImplementedError def apply_action(self, query_graph, action): """ Apply the action on a graph. We use the value of standpoint(Vertex), predicate(Edge) and target(Vertex) build the query graph step by step. We will not reuse the Vertex and Edge object because the `id` might be different from the original graph Args: query_graph (:obj:QueryGraph): Partial query graph action (:obj:Action): The action would be applied to the query graph Returns: QueryGraph """ query_graph_new = copy.deepcopy(query_graph) if action.p_direction == constant.P_FORWARD: query_graph_new.add_edge(( action.standpoint.value, action.predicate.value, action.target.value)) elif action.p_direction == constant.P_BACKWARD: query_graph_new.add_edge(( action.target.value, action.predicate.value, action.standpoint.value)) return query_graph_new def query_graph_stage_generation(self, sentence, query_graph): """ This function is to convert the `query_graph` (using the actions) into list of `stages`. Args: sentence (str) query_graph (QueryGraph) Returns: List[Stage] """ actions = query_graph.graph_to_actions() query_graph = QueryGraph() stages = [] variable_pool = [] sent = Sentence(sentence) black_predicate_dict = {} for action in actions: # TODO: fix the mention here if action.standpoint.type == constant.URI: mention = None else: mention = None query_graph_new = self.apply_action(query_graph, action) black_predicate_dict_ = copy.deepcopy(black_predicate_dict) stage = Stage( sentence=sent, query_graph=query_graph_new, standpoint=action.standpoint, variable_pool=copy.deepcopy(variable_pool), mention=mention, gold_predicate=action.predicate, action=action, black_predicate_dict=black_predicate_dict_) if action.standpoint.value not in black_predicate_dict: black_predicate_dict[action.standpoint.value] = [] black_predicate_dict[action.standpoint.value].append((action.predicate.value, action.p_direction)) if action.target.value not in black_predicate_dict: black_predicate_dict[action.target.value] = [] black_predicate_dict[action.target.value].append((action.predicate.value, reverse_direction(action.p_direction))) stages.append(stage) if action == constant.GEN_VAR: variable_pool.append(len(variable_pool)) """Update the variable pool""" query_graph = query_graph_new return stages def retrieve_neighbourhood_with_batch_graph(self, graphs, output_path): """ Because of the problem of parallel TDBQuery, this will stage all the results in memory. Args: graphs: output_path: Returns: """ raise NotImplementedError def retrieve_forward_neighbourhood_with_entity(self, entity): forward_result = self.query_client.query( constant.FORWARD_QUERY_TEMPLATE.format("<{}>".format(entity)).encode("utf-8")) return forward_result def retrieve_backward_neighbourhood_with_entity(self, entity): backward_result = self.query_client.query( constant.BACKWARD_QUERY_TEMPLATE.format("<{}>".format(entity)).encode("utf-8")) return backward_result def retrieve_neighbourhood_with_entity_list(self, entity_list, output_path=None, num_threads=30): batch_forward_queries = [] batch_backward_queries = [] for entity in entity_list: batch_forward_queries.append( constant.FORWARD_QUERY_TEMPLATE.format("<{}>".format(entity)).encode("utf-8")) batch_backward_queries.append( constant.BACKWARD_QUERY_TEMPLATE.format("<{}>".format(entity)).encode("utf-8")) if self.query_client: forward_results = self.query_client.parallel_query(batch_forward_queries, num_threads=num_threads) backward_results = self.query_client.parallel_query(batch_backward_queries, num_threads=num_threads) else: raise ValueError("The query client is not initialized") if output_path: with open(output_path, "w") as fout: for entity, forward_result, backward_result in zip(entity_list, forward_results, backward_results): fout.write(json.dumps({ entity: { "forward_result": forward_result, "backward_result": backward_result }}) + "\n") else: return forward_results, backward_results def is_valid_predicate(self, predicate): if (predicate.startswith("http://rdf.freebase.com/ns/common") or predicate.startswith("http://rdf.freebase.com/ns/type") or predicate.startswith("http://rdf.freebase.com/key")): return False return True if __name__ == "__main__": utils = QueryGraphUtils() query_graph = QueryGraph() query_graph.add_edge(( "?c", "http://rdf.freebase.com/ns/location.country.administrative_divisions", "http://rdf.freebase.com/ns/m.010vz")) query_graph.add_edge(( "?c", "http://rdf.freebase.com/ns/government.governmental_jurisdiction.governing_officials", "?y")) query_graph.add_edge(( "?y", "http://rdf.freebase.com/ns/government.government_position_held.office_holder", "?x")) query_graph.add_edge(( "?y", "http://rdf.freebase.com/ns/government.government_position_held.basic_title", "http://rdf.freebase.com/ns/m.060c4")) query_graph_stages = utils.query_graph_stage_generation( sentence="Who was the president in 1980 of the country that has Azad Kashmir?", query_graph=query_graph) pair = False for stage in query_graph_stages: if pair: stage_examples = stage.to_training_example() else: stage_examples = stage.to_testing_example() print(stage_examples)
271
33.18
119
23
2,103
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_b4772ae019a32771_44ecac82", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 54, "line_end": 54, "column_start": 10, "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/tmpr7mo7ysm/b4772ae019a32771.py", "start": {"line": 54, "col": 10, "offset": 1335}, "end": {"line": 54, "col": 34, "offset": 1359}, "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_b4772ae019a32771_3fc48c28", "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": 58, "line_end": 59, "column_start": 19, "column_end": 61, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/b4772ae019a32771.py", "start": {"line": 58, "col": 19, "offset": 1567}, "end": {"line": 59, "col": 61, "offset": 1652}, "extra": {"message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_b4772ae019a32771_a7fde8e7", "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": 59, "line_end": 59, "column_start": 56, "column_end": 60, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpr7mo7ysm/b4772ae019a32771.py", "start": {"line": 59, "col": 56, "offset": 1647}, "end": {"line": 59, "col": 60, "offset": 1651}, "extra": {"message": "Found 'subprocess' function 'check_output' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-if-body_b4772ae019a32771_d8f7259e", "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": 157, "line_end": 160, "column_start": 7, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"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/tmpr7mo7ysm/b4772ae019a32771.py", "start": {"line": 157, "col": 7, "offset": 4872}, "end": {"line": 160, "col": 23, "offset": 4972}, "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.best-practice.unspecified-open-encoding_b4772ae019a32771_0debc720", "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": 224, "line_end": 224, "column_start": 12, "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/tmpr7mo7ysm/b4772ae019a32771.py", "start": {"line": 224, "col": 12, "offset": 7590}, "end": {"line": 224, "col": 34, "offset": 7612}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
5
true
[ "CWE-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" ]
[ 58, 59 ]
[ 59, 59 ]
[ 19, 56 ]
[ 61, 60 ]
[ "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" ]
query_graph_utils.py
/omniscient/utils/query_graph_utils.py
Impavidity/Omniscient
Apache-2.0
2024-11-18T20:44:17.709162+00:00
1,647,338,190,000
1270cf51441e064b2d7a672c21731725f813322f
2
{ "blob_id": "1270cf51441e064b2d7a672c21731725f813322f", "branch_name": "refs/heads/main", "committer_date": 1647338278000, "content_id": "d0f228286774fb46c5089d270120ffaf8202afe7", "detected_licenses": [ "MIT" ], "directory_id": "878b8ec345003f40fbbfcdbb591bd132b24241cf", "extension": "py", "filename": "dataset.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 393751151, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2846, "license": "MIT", "license_type": "permissive", "path": "/vmodel/dataset.py", "provenance": "stack-edu-0054.json.gz:575790", "repo_name": "lis-epfl/vmodel", "revision_date": 1647338190000, "revision_id": "d8860087b94ffc3582f187523864550ecf135b24", "snapshot_id": "38c6967c7a150c904a02e698bc655850de2f9d09", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/lis-epfl/vmodel/d8860087b94ffc3582f187523864550ecf135b24/vmodel/dataset.py", "visit_date": "2023-04-17T19:52:52.133121" }
2.328125
stackv2
import pickle from datetime import datetime import numpy as np import pandas as pd import xarray as xr import yaml from vmodel.util.util import clean_attrs def generate_filename(args): # Construct output file name time_str = datetime.now().strftime('%Y-%m-%d-%H-%M-%S') fnamedict = { 'agents': args.num_agents, 'runs': args.num_runs, 'times': args.num_timesteps, 'dist': args.ref_distance, 'perc': args.perception_radius, 'topo': args.max_agents, 'rngstd': args.range_std, } formatexts = {'netcdf': 'nc', 'pickle': 'pkl'} args_str = '_'.join(f'{k}_{v}' for k, v in fnamedict.items()) return f'{time_str}_{args_str}.states.{formatexts[args.format]}' def create_dataset(datas, args): ds = xr.Dataset() # Clean up attrs dict to be compatible with YAML and NETCDF ds.attrs = clean_attrs(vars(args)) time = np.array(datas[0].time) pos = np.array([d.pos for d in datas]) vel = np.array([d.vel for d in datas]) coord_run = np.arange(args.num_runs, dtype=int) + 1 coord_time = pd.to_timedelta(time, unit='s') coord_agent = np.arange(args.num_agents, dtype=int) + 1 coord_space = np.array(['x', 'y']) coords_rtas = { 'run': coord_run, 'time': coord_time, 'agent': coord_agent, 'space': coord_space } dapos = xr.DataArray(pos, dims=coords_rtas.keys(), coords=coords_rtas) dapos.attrs['units'] = 'meters' dapos.attrs['long_name'] = 'position' ds['position'] = dapos davel = xr.DataArray(vel, dims=coords_rtas.keys(), coords=coords_rtas) davel.attrs['units'] = 'meters/second' davel.attrs['long_name'] = 'velocity' ds['velocity'] = davel ds = ds.transpose('run', 'agent', 'space', 'time') # Return only state (position and velocity) if args.no_save_precomputed: return ds coords_rtaa = { 'run': coord_run, 'time': coord_time, 'agent': coord_agent, 'agent2': coord_agent } vis = np.array([d.vis for d in datas]) davis = xr.DataArray(vis, dims=coords_rtaa.keys(), coords=coords_rtaa) davis.attrs['units'] = 'boolean' davis.attrs['long_name'] = 'visibility' ds['visibility'] = davis # Tranpose to match data generated from Gazebo ds = ds.transpose('run', 'agent', 'agent2', 'space', 'time') return ds def save_dataset(ds, fname, args): if args.format == 'pickle': with open(fname, 'wb') as f: pickle.dump(ds, f, protocol=pickle.HIGHEST_PROTOCOL) elif args.format == 'netcdf': comp = dict(zlib=True, complevel=5) encoding = None if args.no_compress else {v: comp for v in ds.data_vars} ds.to_netcdf(fname, encoding=encoding) with open(f'{fname}.yaml', 'w') as f: yaml.dump(ds.attrs, f)
99
27.75
80
13
786
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_29d0399439091257_6ddadd3e", "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": 92, "line_end": 92, "column_start": 13, "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/tmpr7mo7ysm/29d0399439091257.py", "start": {"line": 92, "col": 13, "offset": 2513}, "end": {"line": 92, "col": 65, "offset": 2565}, "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_29d0399439091257_3b9cbfbe", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 98, "line_end": 98, "column_start": 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/tmpr7mo7ysm/29d0399439091257.py", "start": {"line": 98, "col": 10, "offset": 2782}, "end": {"line": 98, "col": 36, "offset": 2808}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 92 ]
[ 92 ]
[ 13 ]
[ 65 ]
[ "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" ]
dataset.py
/vmodel/dataset.py
lis-epfl/vmodel
MIT
2024-11-18T20:57:32.139227+00:00
1,378,156,025,000
8b63ac086743f192e52822c989e3eab9c2e4aa1e
2
{ "blob_id": "8b63ac086743f192e52822c989e3eab9c2e4aa1e", "branch_name": "refs/heads/master", "committer_date": 1378156644000, "content_id": "31622d72198902d8fa2ac2800e7f5aa61b1b6b10", "detected_licenses": [ "Python-2.0" ], "directory_id": "ce083dda93d5698952cdde25a69196483c8255e4", "extension": "py", "filename": "gorun.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 12548900, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6697, "license": "Python-2.0", "license_type": "permissive", "path": "/gorun.py", "provenance": "stack-edu-0054.json.gz:575863", "repo_name": "AndreaCrotti/python-gorun", "revision_date": 1378156025000, "revision_id": "618f46b8961b44559632594385eb9a94f8aedeb8", "snapshot_id": "89838300fbe63c506262a934ff6cb6ddfdd93dd7", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/AndreaCrotti/python-gorun/618f46b8961b44559632594385eb9a94f8aedeb8/gorun.py", "visit_date": "2021-01-18T12:39:18.509074" }
2.359375
stackv2
#!/usr/bin/env python # # Wrapper on pyinotify for running commands # (c) 2009 Peter Bengtsson, peter@fry-it.com # # TODO: Ok, now it does not start a command while another is runnnig # But! then what if you actually wanted to test a modification you # saved while running another test # Yes, we could stop the running command and replace it by the new test # But! django tests will complain that a test db is already here import argparse import os from subprocess import Popen from threading import Lock, Thread __version__='1.6' class SettingsClass(object): VERBOSE = False settings = SettingsClass() try: from pyinotify import WatchManager, Notifier, ThreadedNotifier, ProcessEvent, EventsCodes except ImportError: print "pyinotify not installed. Try: easy_install pyinotify" raise def _find_command(path): # path is a file assert os.path.isfile(path) # in dictionary lookup have keys as files and directories. # if this path exists in there, it's a simple match try: return lookup[path] except KeyError: pass # is the parent directory in there? while path != '/': path = os.path.dirname(path) try: return lookup[path] except KeyError: pass def _ignore_file(path): if path.endswith('.pyc'): return True if path.endswith('~'): return True basename = os.path.basename(path) if basename.startswith('.#'): return True if basename.startswith('#') and basename.endswith('#'): return True if '.' in os.path.basename(path) and \ basename.split('.')[-1] in settings.IGNORE_EXTENSIONS: return True if os.path.split(os.path.dirname(path))[-1] in settings.IGNORE_DIRECTORIES: return True if not os.path.isfile(path): return True class PTmp(ProcessEvent): def __init__(self): super(PTmp, self).__init__() self.lock = Lock() def process_IN_CREATE(self, event): if os.path.basename(event.pathname).startswith('.#'): # backup file return print "Creating:", event.pathname command = _find_command(event.pathname) #def process_IN_DELETE(self, event): # print "Removing:", event.pathname # command = _find_command(event.pathname) def process_IN_MODIFY(self, event): if _ignore_file(event.pathname): return def execute_command(event, lock): # By default trying to acquire a lock is blocking # In this case it will create a queue of commands to run # # If you try to acquire the lock in the locked state non-blocking # style, it will immediatly returns False and you know that a # command is already running, and in this case we don't want to run # this command at all. block = settings.RUN_ON_EVERY_EVENT if not lock.acquire(block): # in this case we just want to not execute the command return print "Modifying:", event.pathname command = _find_command(event.pathname) if command: if settings.VERBOSE: print "Command: ", print command p = Popen(command, shell=True) sts = os.waitpid(p.pid, 0) lock.release() command_thread = Thread(target=execute_command, args=[event, self.lock]) command_thread.start() def start(actual_directories): wm = WatchManager() flags = EventsCodes.ALL_FLAGS mask = flags['IN_MODIFY'] #| flags['IN_CREATE'] p = PTmp() notifier = Notifier(wm, p) for actual_directory in actual_directories: print "DIRECTORY", actual_directory wdd = wm.add_watch(actual_directory, mask, rec=True) # notifier = Notifier(wm, p, timeout=10) try: print "Waiting for stuff to happen..." notifier.loop() except KeyboardInterrupt: pass return 0 lookup = {} def configure_more(directories): actual_directories = set() #print "directories", directories # Tune the configured directories a bit for i, (path, cmd) in enumerate(directories): if isinstance(path, (list, tuple)): actual_directories.update(configure_more( [(x, cmd) for x in path])) continue if not path.startswith('/'): path = os.path.join(os.path.abspath(os.path.dirname('.')), path) if not (os.path.isfile(path) or os.path.isdir(path)): raise OSError, "%s neither a file or a directory" % path path = os.path.normpath(path) if os.path.isdir(path): if path.endswith('/'): # tidy things up path = path[:-1] if path == '.': path = '' actual_directories.add(path) else: # because we can't tell pyinotify to monitor files, # when a file is configured, add it's directory actual_directories.add(os.path.dirname(path)) lookup[path] = cmd return actual_directories def get_settings_file(): """Return a setting file path or exit if not passed in and no defaults settings files are found. """ parser = argparse.ArgumentParser(description="Gorun") path_files = [os.path.expanduser('~/.gorun_settings.py'), os.path.expanduser('~/.gorunsettings.py')] parser.add_argument('-c', '--conf', help='Full path to the configuration file') ns = parser.parse_args() settings_file = None if ns.conf: settings_file = ns.conf else: for path in path_files: if os.path.isfile(path): settings_file = path print("Using configuration file %s" % settings_file) break if settings_file is None: parser.print_help() sys.exit(1) return settings_file if __name__ == '__main__': import sys import imp settings_file = get_settings_file() sys.path.append(os.path.abspath(os.curdir)) x = imp.load_source('gorun_settings', settings_file) settings.DIRECTORIES = x.DIRECTORIES settings.VERBOSE = getattr(x, 'VERBOSE', settings.VERBOSE) settings.IGNORE_EXTENSIONS = getattr(x, 'IGNORE_EXTENSIONS', tuple()) settings.IGNORE_DIRECTORIES = getattr(x, 'IGNORE_DIRECTORIES', tuple()) settings.RUN_ON_EVERY_EVENT = getattr(x, 'RUN_ON_EVERY_EVENT', False) actual_directories = configure_more(settings.DIRECTORIES) sys.exit(start(actual_directories))
213
30.44
93
17
1,461
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_7fb489c6284f572d_2320a828", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 106, "line_end": 106, "column_start": 21, "column_end": 47, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/7fb489c6284f572d.py", "start": {"line": 106, "col": 21, "offset": 3350}, "end": {"line": 106, "col": 47, "offset": 3376}, "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" ]
[ 106 ]
[ 106 ]
[ 21 ]
[ 47 ]
[ "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" ]
gorun.py
/gorun.py
AndreaCrotti/python-gorun
Python-2.0
2024-11-18T20:57:33.584756+00:00
1,579,511,800,000
e0989b47c11bccf0129df1d9fdccf909c0b12db9
3
{ "blob_id": "e0989b47c11bccf0129df1d9fdccf909c0b12db9", "branch_name": "refs/heads/master", "committer_date": 1579511800000, "content_id": "448877cb19cb944acd2f74080b11e07cbc2d8d34", "detected_licenses": [ "MIT" ], "directory_id": "d7c339e1c3f40d358b6463e8ebd813d76761c5a4", "extension": "py", "filename": "add_accents.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 180301574, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 997, "license": "MIT", "license_type": "permissive", "path": "/vicorrect/model/add_accents.py", "provenance": "stack-edu-0054.json.gz:575876", "repo_name": "lvhanh270597/correct_vietnamese_sentence", "revision_date": 1579511800000, "revision_id": "265e82262c115a3c79e8611a8fc73767af6efd25", "snapshot_id": "c01ff8746904a68ac0d479846e62d95b00d7d2e3", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/lvhanh270597/correct_vietnamese_sentence/265e82262c115a3c79e8611a8fc73767af6efd25/vicorrect/model/add_accents.py", "visit_date": "2020-05-07T06:05:03.715647" }
2.828125
stackv2
import pickle from vicorrect.machine_learning.hmm import HiddenMarkovModel class CorrectVietnameseSentence(): def __init__(self, listNgrams=[2, 3, 4], eta=0.000001, verbose=True): self.__listNgrams = listNgrams self.__eta = eta self.__loaded = False self.__verbose = verbose def load(self, filePath): try: self.__model = pickle.load(open(filePath, 'rb')) self.__loaded = True print("OK!") except Exception as E: print("Error: %s" % E) return None def __initModel(self): self.__model = HiddenMarkovModel(self.__listNgrams, self.__eta, self.__verbose) def fit(self, data): if self.__loaded: print("Done!") return self.__initModel() self.__model.setData(data) self.__model.fit() def predict(self, testcase, lim_per_index=[5], output_size=1): return self.__model.fastPredict(testcase, lim_per_index, output_size) def score(self, inp_list, label_list, list_of_indices=[5]): return self.__model.score(inp_list, label_list, list_of_indices)
35
27.51
81
15
278
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_78b95b93216200ec_aeb07195", "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": 13, "line_end": 13, "column_start": 19, "column_end": 52, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/78b95b93216200ec.py", "start": {"line": 13, "col": 19, "offset": 338}, "end": {"line": 13, "col": 52, "offset": 371}, "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" ]
[ 13 ]
[ 13 ]
[ 19 ]
[ 52 ]
[ "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format." ]
[ 5 ]
[ "LOW" ]
[ "MEDIUM" ]
add_accents.py
/vicorrect/model/add_accents.py
lvhanh270597/correct_vietnamese_sentence
MIT
2024-11-18T20:57:34.271453+00:00
1,551,126,716,000
0913054b93ba0bb0e92294cb0b3721da80836989
2
{ "blob_id": "0913054b93ba0bb0e92294cb0b3721da80836989", "branch_name": "refs/heads/master", "committer_date": 1551126716000, "content_id": "0aa1a04b8807b6215a7f2ef1ec460ced28bb2cd4", "detected_licenses": [ "MIT" ], "directory_id": "edffb6fcb86ede4bd5eda957074a3d8ad820b86d", "extension": "py", "filename": "encode.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 170593490, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2182, "license": "MIT", "license_type": "permissive", "path": "/encode.py", "provenance": "stack-edu-0054.json.gz:575884", "repo_name": "ec500-software-engineering/exercise-2-ffmpeg-BrefCool", "revision_date": 1551126716000, "revision_id": "9c0f7819f9f3b0e50d41541239b40b40691fa7a7", "snapshot_id": "77e3a1b0ede2b0ac181af657a16f0d4ef3154eec", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ec500-software-engineering/exercise-2-ffmpeg-BrefCool/9c0f7819f9f3b0e50d41541239b40b40691fa7a7/encode.py", "visit_date": "2020-04-22T18:57:51.490287" }
2.328125
stackv2
import os import json import subprocess def ffprobe(fin, fout): ffp_in = subprocess.check_output(['ffprobe', '-v', 'warning', '-print_format', 'json', '-show_streams', '-show_format', fin]) ffp_out = subprocess.check_output(['ffprobe', '-v', 'warning', '-print_format', 'json', '-show_streams', '-show_format', fout]) ffp_in = json.loads(ffp_in) ffp_out = json.loads(ffp_out) duration_in = int(ffp_in['format']['duration'].split('.')[0]) duration_out = int(ffp_out['format']['duration'].split('.')[0]) if duration_in == duration_out: return True else: return False def encode_c480(fin, fout): if os.path.exists(fout): os.remove(fout) output = "" cmd = ['ffmpeg', '-i', fin, '-r', '30', '-s', 'hd480', '-b:v', '1024k', '-loglevel', 'quiet', fout] try: subprocess.check_call(cmd) except OSError: output += "cmd ffmpeg not found. please install ffmpeg first." return False, output except subprocess.CalledProcessError as e: output += "error converting. msg: {}".format(e) return False, output succeed = ffprobe(fin, fout) if succeed: output += "finished(480p)" return True, output else: output += "failed(480p)" return False, output def encode_c720(fin, fout): if os.path.exists(fout): os.remove(fout) output = "" cmd = ['ffmpeg', '-i', fin, '-r', '30', '-s', 'hd720', '-b:v', '2048k', '-loglevel', 'quiet', fout] try: subprocess.check_call(cmd) except OSError: output += "cmd ffmpeg not found. please install ffmpeg first." return False, output except subprocess.CalledProcessError as e: output += "error converting. msg: {}".format(e) return False, output succeed = ffprobe(fin, fout) if succeed: output += "finished(720p)" return True, output else: output += "failed(480p)" return False, output
88
23.81
67
14
536
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_6dfa583feb614630_a83db6b9", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 43, "line_end": 43, "column_start": 3, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/6dfa583feb614630.py", "start": {"line": 43, "col": 3, "offset": 1153}, "end": {"line": 43, "col": 29, "offset": 1179}, "extra": {"message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_6dfa583feb614630_b7f51918", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 74, "line_end": 74, "column_start": 3, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/6dfa583feb614630.py", "start": {"line": 74, "col": 3, "offset": 1782}, "end": {"line": 74, "col": 29, "offset": 1808}, "extra": {"message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.dangerous-subprocess-use-audit" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "HIGH", "HIGH" ]
[ 43, 74 ]
[ 43, 74 ]
[ 3, 3 ]
[ 29, 29 ]
[ "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "Detected subprocess ...
[ 7.5, 7.5 ]
[ "LOW", "LOW" ]
[ "HIGH", "HIGH" ]
encode.py
/encode.py
ec500-software-engineering/exercise-2-ffmpeg-BrefCool
MIT
2024-11-18T20:57:34.958615+00:00
1,580,165,283,000
5626835ccc8b27583b60ffe1b08306d2d999e9c6
3
{ "blob_id": "5626835ccc8b27583b60ffe1b08306d2d999e9c6", "branch_name": "refs/heads/master", "committer_date": 1580165283000, "content_id": "28ae91e9ce1dceb2a99552a316ed5518895afe22", "detected_licenses": [ "MIT" ], "directory_id": "c9d7aa1fca69a667a04d97c5870f44796b97a29b", "extension": "py", "filename": "egybest.py", "fork_events_count": 0, "gha_created_at": 1581105294000, "gha_event_created_at": 1581105295000, "gha_language": null, "gha_license_id": null, "github_id": 239011526, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14229, "license": "MIT", "license_type": "permissive", "path": "/egybest.py", "provenance": "stack-edu-0054.json.gz:575891", "repo_name": "ahmed081/EgyBest-Downloader", "revision_date": 1580165283000, "revision_id": "271ef483e19ec5299f55b6ff8b4e4f3e55ee9424", "snapshot_id": "3614c38cb8844a6e78cc2fec34fcb831d7a8dd08", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/ahmed081/EgyBest-Downloader/271ef483e19ec5299f55b6ff8b4e4f3e55ee9424/egybest.py", "visit_date": "2020-12-31T11:04:47.506470" }
2.609375
stackv2
import os import sys import requests from bs4 import BeautifulSoup from pySmartDL import SmartDL from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities class EgyBest: search_base_url = "https://nero.egybest.site/explore/?q=" chrome_driver = None def __init__(self): self.search_url = None self.content_url = None self.content_type = None self.content_name = None self.chosen_seasons_numbers_list = [] self.chosen_seasons_url_list = [] self.chosen_episodes_number_list = [] self.chosen_episodes_url_list = [] self.downloadable_episodes_url_list = [] def reset(self): self.__init__() def get_search_url(self): try: self.search_url = self.search_base_url + \ self.get_string_input("What are you searching for ? :") # print(self.search_url) except: exit("search url") # function to get the download content def get_content_url(self): print("Searching for results !!!") res = self.get_bs4_result(self.search_url, "a", "movie") # Displaying the fitched linked for i, link in enumerate(res, 1): content_type = None try: content_type = self.get_url_type(link['href']).upper() print(i, " ->", link.contents[4].text, ", Type : ", content_type, ",", "IMDB Rating :", link.contents[0].i.i.text,'\n') except: print(i, " ->", link.contents[2].text, ", Type : ", content_type) # looking for user choice while res: try: self.content_url = res[self.get_int_input( "Enter link number :") - 1]['href'] break except: retry = self.get_string_input( "Non valid input ,retry ? (y/n) :") if retry != "y": self.content_type = None return if not res: print("Didn't found a thing") elif self.content_url: self.content_type = self.get_url_type(self.content_url) # initializing chrome drivers def init_chrome_driver(self): if not self.chrome_driver: print("Initializing chrome driver") try: caps = DesiredCapabilities().CHROME caps["pageLoadStrategy"] = "eager" chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--log-level=3') chrome_options.add_argument('--disable-logging') chrome_options.add_argument('--headless') self.chrome_driver = webdriver.Chrome(executable_path="./Driver/chromedriver.exe", options=chrome_options) except: print("Couldn't init chrome drivers") self.exit("init_chrome") # closing and destroying chrome driver instant def destroy_chrome_driver(self): try: if self.chrome_driver is not None: self.chrome_driver.close() print("Driver Closed") else: print("Driver already closed") except Exception as e: print(e) def gather_download_link(self): self.init_chrome_driver() print("Accessing EgyBest page") self.chrome_driver.get(self.chosen_episodes_url_list[-1]) self.chose_quality() print("Accessing the download page") self.chrome_driver.close() self.chrome_driver.switch_to.window( self.chrome_driver.window_handles[0]) while 1: try: target_button = self.chrome_driver.find_element_by_xpath( "/html/body/div[1]/div/p[2]/a[1]") if not target_button.get_attribute("href"): print("Closing ads tab") target_button.click() self.chrome_driver.switch_to.window( self.chrome_driver.window_handles[1]) self.chrome_driver.close() self.chrome_driver.switch_to.window( self.chrome_driver.window_handles[0]) else: print("Obtaining the download link") url = target_button.get_attribute("href") if url: self.downloadable_episodes_url_list.append(url) return except Exception as e: print(e) self.chrome_driver.switch_to.window( self.chrome_driver.window_handles[0]) def download_seasons(self, url=None): if url is None: url = self.content_url res = self.get_bs4_result(url, "div", "movies_small")[0] seasons_list = res.find_all("a") number_of_seasons = len(seasons_list) all_eps = False while number_of_seasons: print(F"There're {number_of_seasons} seasons ") choice = self.get_string_input( "Do you want to download all seasons or specific ones, type['all' or 'spec']:") if choice == 'all': all_eps = True self.chosen_seasons_numbers_list = [ i for i in range(1, number_of_seasons + 1)] break elif choice == 'spec': while 1: chosen_number_seasons = self.get_int_input( "Choose how many seasons :") try: if number_of_seasons >= chosen_number_seasons > 0: break except: pass print("Add the seasons you want to download") for i in range(1, chosen_number_seasons + 1): while 1: choice = self.get_int_input( F"{i} --> Choose a season from 1 to {number_of_seasons}:") if not None else 0 try: if number_of_seasons >= choice >= 1: print(F"Season {choice} Added") self.chosen_seasons_numbers_list.append(choice) break else: print("Non valid option") except: pass break print("Non valid option") self.chosen_seasons_numbers_list.sort() for i in self.chosen_seasons_numbers_list: self.chosen_seasons_url_list.append(seasons_list[-i]['href']) print("Gathering episodes Urls") # print("chosen_seasons_url_list", self.chosen_seasons_url_list) for url in self.chosen_seasons_url_list: res = self.get_bs4_result(url, "div", "movies_small")[0] episodes_list = res.find_all("a") number_of_eps = len(episodes_list) if number_of_eps: print(F"There're {number_of_eps} episodes in {' '.join(url.split('/')[-2].split('-')[1:])}") if all_eps: choice = 'all' else: choice = self.get_string_input( "Do you want to download all episodes or specific ones, type['all' or 'spec']:") if choice == 'all': self.chosen_episodes_number_list = [ i for i in range(1, number_of_eps + 1)] elif choice == 'spec': while 1: chosen_number_episodes = self.get_int_input( "Choose how many episodes :") try: if number_of_eps >= chosen_number_episodes > 0: break except: pass print("Add the episodes you want to download") for i in range(1, chosen_number_episodes + 1): while 1: choice = self.get_int_input( F"{i} --> Choose an episode from 1 to {number_of_eps}:") try: if number_of_eps >= choice >= 1: print(F"Episode {choice} Added") self.chosen_episodes_number_list.append( choice) break else: print("Non valid option") except: pass # print("chosen_episodes_number_list", # self.chosen_episodes_number_list) # print("episodes_list", episodes_list) self.chosen_episodes_number_list.sort() for i in self.chosen_episodes_number_list: self.chosen_episodes_url_list.append(episodes_list[-i]["href"]) self.gather_download_link() # print(self.downloadable_episodes_url_list) # print(self.chosen_episodes_url_list) return True def start(self, link=None): # Check if link provided is valid valid_link = False if link: self.content_type = self.get_url_type(link) if self.content_type: valid_link = True # if it's valid it wont enter the loop while not self.content_type: # shows that the link is trash if link: print("None valid link") # getting user input self.get_search_url() self.get_content_url() self.content_name = self.get_content_name(self.content_url if not valid_link else link) if self.content_type == "series": self.download_seasons() elif self.content_type == "movie": self.chosen_episodes_url_list.append(self.content_url if not valid_link else link) # print(self.chosen_episodes_url_list) self.gather_download_link() self.save_links_to_file() self.get_user_download_choice() @staticmethod def get_int_input(output_msg): try: return int(input(output_msg)) except: return None @staticmethod def get_string_input(output_msg): try: return str(input(output_msg)).lower() except: exit("strig input") @staticmethod def get_bs4_result(url, html_tag, class_name): print("Requesting link !") r = requests.get(url) soup = BeautifulSoup(r.text, "html.parser") return soup.find_all(html_tag, class_=class_name) @staticmethod def get_url_type(url): # print(url) try: return url.split("/")[3] except: print("None valid link in get_url_type") return None @staticmethod def get_content_name(url): # print(url) try: return url.split("/")[4] except: print("None valid link in get_content_name") return None def exit(self, code): self.destroy_chrome_driver() sys.exit("\n Exited " + code) def chose_quality(self): target_button = self.chrome_driver.find_elements_by_class_name( 'btn.g.dl.nop._open_window')[0] target_button.click() def get_user_download_choice(self): while 1: choice = self.get_string_input( "---> Links saved to file , Do you want to start [d]ownloading ,[a]ppend to IDM or [q]uit?," "chose: (d/a/q)") if choice == "d": self.start_downloading() break if choice == "a": self.append_to_idm() break if choice == "q": break print("None valid option !") def start_downloading(self): print("Note : if your're using pycharm console, it won't show you progress bar !") if not self.downloadable_episodes_url_list: print("Array is empty") for i, ep_link in enumerate(self.downloadable_episodes_url_list): print("Starting to download :", ep_link) obj = SmartDL(ep_link, "./Downloads" + os.sep) obj.start() print("Download location :" + obj.get_dest()) def append_to_idm(self): for i, ep_link in enumerate(self.downloadable_episodes_url_list): try: os.system( F'"C:\\Program Files (x86)\\Internet Download Manager\\IDMan.exe" /d {ep_link} /n /a') print("+1 :", ep_link) except Exception as excep: print(F"Couldn't add {self.chosen_episodes_url_list[i]} \nException :{excep}") print("Saving them to a file !") def save_links_to_file(self): base_dic = "LinkSaves/" os.makedirs(os.path.dirname(base_dic), exist_ok=True) # print(self.downloadable_episodes_url_list) with open(F"{base_dic}/{self.content_type}-{self.content_name}.txt", "w+") as f: for ep in self.downloadable_episodes_url_list: f.write(F"{ep}\n") def reset_chrome_driver(self): self.destroy_chrome_driver() self.init_chrome_driver() if __name__ == "__main__": egy = EgyBest() link = "https://nero.egybest.site/movie/joker-2019/" try: while 1: egy.start() try: choice = egy.get_int_input("Do you want to restart ? : (1/0)") if choice == 0: break egy.reset() except: break except Exception as e: egy.reset_chrome_driver() print(e) finally: egy.destroy_chrome_driver()
365
37.98
108
26
2,780
python
[{"finding_id": "semgrep_rules.python.lang.correctness.use-sys-exit_da06b18664d193a7_46aa0de5", "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(\"search url\")", "location": {"file_path": "unknown", "line_start": 35, "line_end": 35, "column_start": 13, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.use-sys-exit", "path": "/tmp/tmpr7mo7ysm/da06b18664d193a7.py", "start": {"line": 35, "col": 13, "offset": 988}, "end": {"line": 35, "col": 31, "offset": 1006}, "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(\"search url\")", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.use-sys-exit_da06b18664d193a7_37b2adef", "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(\"strig input\")", "location": {"file_path": "unknown", "line_start": 263, "line_end": 263, "column_start": 13, "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://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.use-sys-exit", "path": "/tmp/tmpr7mo7ysm/da06b18664d193a7.py", "start": {"line": 263, "col": 13, "offset": 10816}, "end": {"line": 263, "col": 32, "offset": 10835}, "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(\"strig input\")", "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.requests.best-practice.use-raise-for-status_da06b18664d193a7_ff621342", "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": 268, "line_end": 268, "column_start": 13, "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://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmpr7mo7ysm/da06b18664d193a7.py", "start": {"line": 268, "col": 13, "offset": 10953}, "end": {"line": 268, "col": 30, "offset": 10970}, "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_da06b18664d193a7_9c713471", "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": 268, "line_end": 268, "column_start": 13, "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://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpr7mo7ysm/da06b18664d193a7.py", "start": {"line": 268, "col": 13, "offset": 10953}, "end": {"line": 268, "col": 30, "offset": 10970}, "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.dangerous-system-call-audit_da06b18664d193a7_e88b84cb", "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": 328, "line_end": 329, "column_start": 17, "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://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpr7mo7ysm/da06b18664d193a7.py", "start": {"line": 328, "col": 17, "offset": 12918}, "end": {"line": 329, "col": 107, "offset": 13035}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_da06b18664d193a7_6f42826d", "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": 339, "line_end": 339, "column_start": 14, "column_end": 83, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/da06b18664d193a7.py", "start": {"line": 339, "col": 14, "offset": 13445}, "end": {"line": 339, "col": 83, "offset": 13514}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
6
true
[ "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-system-call-audit" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 328 ]
[ 329 ]
[ 17 ]
[ 107 ]
[ "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" ]
egybest.py
/egybest.py
ahmed081/EgyBest-Downloader
MIT
2024-11-18T20:57:52.820940+00:00
1,505,503,412,000
a9bd3d5686b67a0c78b7060194ac3103e352eb56
2
{ "blob_id": "a9bd3d5686b67a0c78b7060194ac3103e352eb56", "branch_name": "refs/heads/master", "committer_date": 1505503412000, "content_id": "ad31e069a32dab9fd67258a3fe57488d0840a14b", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "4f12b9226ae6b3ce14a1ba46e188484d62e6cac1", "extension": "py", "filename": "wfs.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 6159463, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5320, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/validation/validators/wfs.py", "provenance": "stack-edu-0054.json.gz:575985", "repo_name": "usgin/ContentModelCMS", "revision_date": 1505503412000, "revision_id": "ac9a7824d5e79014d873fb84803788474d40b6ce", "snapshot_id": "d6f3fb9874595b7e418866f5bf43d5c28f66540b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/usgin/ContentModelCMS/ac9a7824d5e79014d873fb84803788474d40b6ce/validation/validators/wfs.py", "visit_date": "2021-01-13T14:20:25.101532" }
2.375
stackv2
from contentmodels.models import ContentModel, ModelVersion from WfsCapabilities import WfsCapabilities from WfsGetFeature import WfsGetFeature from django import forms from django.http import HttpResponseNotAllowed from django.shortcuts import render #-------------------------------------------------------------------------------------- # A Form to gather user's input: Just the WFS URL # Also validates that the URL returns a GetCapabilities doc and that the WFS # provides some FeatureTypes #-------------------------------------------------------------------------------------- class WfsSelectionForm(forms.Form): wfs_get_capabilities_url = forms.URLField( widget=forms.TextInput(attrs={'class':'span10', 'placeholder':'Enter a WFS GetCapabilities URL'}) ) # Just one field in this form: the WFS GetCapabilities URL # Function to validate the wfs_get_capabilites_url def clean_wfs_get_capabilities_url(self): # Get the URL that the user provided url = self.cleaned_data['wfs_get_capabilities_url'] # Check the validity of the given URL capabilities = WfsCapabilities(url) if not capabilities.url_is_valid: raise forms.ValidationError('The URL given is invalid') # Check that the WFS provides some FeatureTypes if len(capabilities.feature_types) is 0: raise forms.ValidationError('The WFS you specified does not provide any FeatureTypes') #-------------------------------------------------------------------------------------- # A Form to gather user's input required to validate a WFS against some ModelVersion # Note that the constructor for the form requires a URL #-------------------------------------------------------------------------------------- class WfsValidationParametersForm(forms.Form): # Redefine the constructor for this form to accomodate an input URL def __init__(self, url, *args, **kwargs): super(forms.Form, self).__init__(*args, **kwargs) # Set the feature_type field's choices to the available WFS FeatureTypes self.capabilities = WfsCapabilities(url) self.fields['feature_type'].choices = [ (typename, typename) for typename in self.capabilities.feature_types ] # Set the initial URL self.fields['url'].initial = url # Define form fields url = forms.URLField(widget=forms.HiddenInput) content_model = forms.ModelChoiceField(queryset=ContentModel.objects.all(), widget=forms.Select(attrs={'class':'span4'}) ) version = forms.ModelChoiceField(queryset=ModelVersion.objects.all(), widget=forms.Select(attrs={'class':'span4'}) ) feature_type = forms.ChoiceField(choices=[], widget=forms.Select(attrs={'class':'span4'}) ) number_of_features = forms.IntegerField( widget=forms.Select( attrs={'class':'span1'}, choices=((1,1), (10,10), (50, 50)) ) ) #-------------------------------------------------------------------------------------- # Here is the actual view function for /validate/wfs #-------------------------------------------------------------------------------------- def validate_wfs_form(req): # Insure that HTTP requests are of the proper type allowed = [ 'GET', 'POST' ] if req.method not in allowed: return HttpResponseNotAllowed(allowed) # When a data is passed in during a POST request... if req.method == 'POST': # ... determine if the req.POST contains WfsSelectionForm or WfsValidationParametersForm # This is a WfsValidationParametersForm if 'version' in req.POST: form = WfsValidationParametersForm(req.POST['url'], req.POST) # Check the form's validity if form.is_valid(): # Perform WFS Validation feature_type = form.cleaned_data['feature_type'] number_of_features = form.cleaned_data['number_of_features'] modelversion = form.cleaned_data['version'] get_feature_validator = WfsGetFeature(form.capabilities, feature_type, number_of_features) result = get_feature_validator.validate(modelversion) # Setup hash table for results rendering context = { "valid": result.valid, "valid_elements": result.valid_count(), "url": get_feature_validator.url, "errors": result.errors, "modelversion": modelversion, "feature_type": feature_type, "number_of_features": number_of_features, "wfs_base_url": get_feature_validator.url.split('?')[0] } # Render the results as HTML return render(req, 'wfs-results-bootstrap.html', context) # Otherwise it is treated as a WfsSelectionForm else: form = WfsSelectionForm(req.POST) # Check the form's validity if form.is_valid(): # We need to send back a WfsValidationParametersForm, which takes a URL as input url = form.data['wfs_get_capabilities_url'] second_form = WfsValidationParametersForm(url) return render(req, 'wfs-form-bootstrap.html', { 'form': second_form, 'url': url }) # A GET request should just a data-free WfsSelectionForm else: form = WfsSelectionForm() # You'll get here if it was a GET request, or if form validation failed return render(req, 'wfs-form-bootstrap.html', { 'form': form })
123
42.26
114
18
1,109
python
[{"finding_id": "semgrep_rules.python.django.security.audit.xss.direct-use-of-httpresponse_71c11ff15b183e13_f8d6879f", "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": 73, "line_end": 73, "column_start": 12, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "title": null}, {"url": "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "path": "/tmp/tmpr7mo7ysm/71c11ff15b183e13.py", "start": {"line": 73, "col": 12, "offset": 3234}, "end": {"line": 73, "col": 43, "offset": 3265}, "extra": {"message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render"], "category": "security", "technology": ["django"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-79" ]
[ "rules.python.django.security.audit.xss.direct-use-of-httpresponse" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 73 ]
[ 73 ]
[ 12 ]
[ 43 ]
[ "A07:2017 - Cross-Site Scripting (XSS)" ]
[ "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML." ]
[ 5 ]
[ "LOW" ]
[ "MEDIUM" ]
wfs.py
/validation/validators/wfs.py
usgin/ContentModelCMS
BSD-2-Clause
2024-11-18T20:57:55.621220+00:00
1,599,161,633,000
c4d300ac44be246bd48a2368579df593027789a0
3
{ "blob_id": "c4d300ac44be246bd48a2368579df593027789a0", "branch_name": "refs/heads/master", "committer_date": 1599161633000, "content_id": "155e00c7753b2d1496130ee5e9857e4ec88681bc", "detected_licenses": [ "Apache-2.0" ], "directory_id": "9db0a42f6e09372d8d937596cbb7adaea691cf0c", "extension": "py", "filename": "word.py", "fork_events_count": 1, "gha_created_at": 1596707997000, "gha_event_created_at": 1605382480000, "gha_language": "Python", "gha_license_id": "Apache-2.0", "github_id": 285536054, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9960, "license": "Apache-2.0", "license_type": "permissive", "path": "/imsnpars/repr/word.py", "provenance": "stack-edu-0054.json.gz:576017", "repo_name": "zentrum-lexikographie/IMSnPars", "revision_date": 1599161633000, "revision_id": "8d19aa1fc76b0277c861cec774ad81f62cd4e244", "snapshot_id": "b9306eb399902373e2e5c8cbe0278108591712b1", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/zentrum-lexikographie/IMSnPars/8d19aa1fc76b0277c861cec774ad81f62cd4e244/imsnpars/repr/word.py", "visit_date": "2023-01-19T17:28:10.501774" }
2.703125
stackv2
''' Created on Jun 29, 2018 @author: falensaa ''' import dynet import logging import abc import pickle import random class TokenReprBuilder(object): __metaclass__ = abc.ABCMeta ## # word2i dictionaries operations @abc.abstractmethod def addToken(self, token): pass @abc.abstractmethod def save(self, pickleOut): pass @abc.abstractmethod def load(self, pickleIn): pass @abc.abstractmethod def getFeatInfo(self): pass ## # instance operations @abc.abstractmethod def initializeParameters(self, model): pass @abc.abstractmethod def buildInstance(self, token): pass ## # vector operations @abc.abstractmethod def getDim(self): pass @abc.abstractmethod def getTokenVector(self, tokInstance, isTraining): pass @abc.abstractmethod def getRootVector(self): pass ################################################################ # TokenReprBuilders ################################################################ class WordReprBuilder(TokenReprBuilder): def __init__(self, dim, wordDropout): self.__dim = dim self.__vocab = { } self.__wordsFreq = { } self.__wordDropout = wordDropout self.__logger = logging.getLogger(self.__class__.__name__) # additional entries - root, unknown self.__addEntries = 2 self.__lookup = None ## # word2i operations def addToken(self, token): norm = token.getNorm() wId = self.__vocab.get(norm, None) if wId == None: wId = len(self.__vocab) self.__vocab[norm] = wId if self.__wordDropout: if wId not in self.__wordsFreq: self.__wordsFreq[wId] = 1 else: self.__wordsFreq[wId] += 1 def save(self, pickleOut): pickle.dump((self.__vocab, self.__wordsFreq), pickleOut) def load(self, pickleIn): self.__vocab, self.__wordsFreq = pickle.load(pickleIn) def getFeatInfo(self): return "Words: %i" % len(self.__vocab) ## # instance opeations def initializeParameters(self, model): self.__lookup = model.add_lookup_parameters((len(self.__vocab) + self.__addEntries, self.__dim)) def buildInstance(self, token): return self.__vocab.get(token.getNorm()) ## # vector operations def getDim(self): return self.__dim def getTokenVector(self, wordId, isTraining): if isTraining: wordId = self.__wordIdWithDropout(wordId) if wordId == None: return self.__getUnknVector() else: return self.__lookup[wordId] def getRootVector(self): return self.__lookup[len(self.__vocab) + 1] def __getUnknVector(self): return self.__lookup[len(self.__vocab)] def __wordIdWithDropout(self, wordId): if self.__wordDropout == None or wordId == None: return wordId dropProb = self.__wordDropout / ( self.__wordDropout + self.__wordsFreq.get(wordId)) if random.random() < dropProb: return None return wordId class POSReprBuilder(TokenReprBuilder): def __init__(self, dim): self.__logger = logging.getLogger(self.__class__.__name__) self.__dim = dim self.__pos = { } # additional entries - root, unknown self.__addEntries = 2 self.__lookup = None ## # word2i operations def addToken(self, token): posId = self.__pos.get(token.pos, None) if posId == None: posId = len(self.__pos) self.__pos[token.pos] = posId def save(self, pickleOut): pickle.dump(self.__pos, pickleOut) def load(self, pickleIn): self.__pos = pickle.load(pickleIn) def getFeatInfo(self): return "POS: %i" % len(self.__pos) ## # instance opeations def initializeParameters(self, model): self.__lookup = model.add_lookup_parameters((len(self.__pos) + self.__addEntries, self.__dim)) def buildInstance(self, token): return self.__pos.get(token.pos) ## # vector operations def getDim(self): return self.__dim def getTokenVector(self, posId, _): if posId == None: return self.__getUnknVector() else: return self.__lookup[posId] def getRootVector(self): return self.__lookup[len(self.__pos) + 1] def __getUnknVector(self): return self.__lookup[len(self.__pos)] class MorphReprBuilder(TokenReprBuilder): def __init__(self, dim): self.__dim = dim self.__morph = { } # additional entries - root, unknown self.__addEntries = 2 self.__lookup = None ## # word2i operations def addToken(self, token): morphId = self.__morph.get(token.morph, None) if morphId == None: morphId = len(self.__morph) self.__morph[token.morph] = morphId def save(self, pickleOut): pickle.dump(self.__morph, pickleOut) def load(self, pickleIn): self.__morph = pickle.load(pickleIn) def getFeatInfo(self): return "Morph: %i" % len(self.__morph) ## # instance opeations def initializeParameters(self, model): self.__lookup = model.add_lookup_parameters((len(self.__morph) + self.__addEntries, self.__dim)) def buildInstance(self, token): return self.__morph.get(token.morph) ## # vector operations def getDim(self): return self.__dim def getTokenVector(self, morphId, _): if morphId == None: return self.__getUnknVector() else: return self.__lookup[morphId] def getRootVector(self): return self.__lookup[len(self.__morph) + 1] def __getUnknVector(self): return self.__lookup[len(self.__morph)] class CharLstmReprBuilder(TokenReprBuilder): def __init__(self, dim, lstmDim, charDropout=None, lstmDropout=None): self.__dim = dim self.__lstmDim = lstmDim self.__chars = { } self.__charFreq = { } # additional entries - unknown, <w>, </w> self.__addEntries = 3 self.__lookup = None self.__forwardLstm = None self.__backwardLstm = None self.__rootVec = None self.__dropout = lstmDropout self.__charDropout = charDropout ## # word2i operations def addToken(self, token): for c in token.orth: if c not in self.__chars: cId = len(self.__chars) self.__chars[c] = cId else: cId = self.__chars[c] if self.__charDropout: if cId not in self.__charFreq: self.__charFreq[cId] = 1 else: self.__charFreq[cId] += 1 def save(self, pickleOut): pickle.dump((self.__chars, self.__charFreq), pickleOut) def load(self, pickleIn): self.__chars, self.__charFreq = pickle.load(pickleIn) def getFeatInfo(self): return "Chars [BiLSTM]: %i" % len(self.__chars) ## # instance opeations def initializeParameters(self, model): self.__lookup = model.add_lookup_parameters((len(self.__chars) + self.__addEntries, self.__dim)) self.__rootVec = model.add_parameters((self.getDim())) self.__forwardLstm = dynet.VanillaLSTMBuilder(1, self.__dim, self.__lstmDim, model) self.__backwardLstm = dynet.VanillaLSTMBuilder(1, self.__dim, self.__lstmDim, model) def buildInstance(self, token): return [ self.__chars.get(c) for c in token.orth ] ## # vector operations def getDim(self): return 2 * self.__lstmDim def getTokenVector(self, charIds, isTraining): self.__setDropout(isTraining) if isTraining and self.__charDropout: charIds = [ self.__charIdWithDropout(cId) for cId in charIds ] charVecs = [ self.__getBegVector() ] charVecs += [ self.__lookup[cId] if cId != None else self.__getUnknCVector() for cId in charIds ] charVecs.append( self.__getEndVector() ) forwardInit = self.__forwardLstm.initial_state() backwardInit = self.__backwardLstm.initial_state() result = [ ] result.append(forwardInit.add_inputs(charVecs)[-1].output()) result.append(backwardInit.add_inputs(reversed(charVecs))[-1].output()) return dynet.concatenate(result) def getRootVector(self): return self.__rootVec.expr() def __getBegVector(self): return self.__lookup[len(self.__chars)] def __getEndVector(self): return self.__lookup[len(self.__chars) + 1] def __getUnknCVector(self): return self.__lookup[len(self.__chars) + 2] def __setDropout(self, isTraining): if not self.__dropout: return if isTraining: self.__forwardLstm.set_dropout(self.__dropout) self.__backwardLstm.set_dropout(self.__dropout) else: self.__forwardLstm.disable_dropout() self.__backwardLstm.disable_dropout() def __charIdWithDropout(self, cId): if self.__charDropout == None or cId == None: return cId dropProb = self.__charDropout / ( self.__charDropout + self.__charFreq.get(cId)) if random.random() < dropProb: return None return cId
366
26.21
106
17
2,390
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_8c86cbec026d3307_c85cfdd4", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 97, "line_end": 97, "column_start": 9, "column_end": 65, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/8c86cbec026d3307.py", "start": {"line": 97, "col": 9, "offset": 2027}, "end": {"line": 97, "col": 65, "offset": 2083}, "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_8c86cbec026d3307_0ef78daf", "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": 42, "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-pickle", "path": "/tmp/tmpr7mo7ysm/8c86cbec026d3307.py", "start": {"line": 100, "col": 42, "offset": 2160}, "end": {"line": 100, "col": 63, "offset": 2181}, "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_8c86cbec026d3307_f3a3c5e8", "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": 165, "line_end": 165, "column_start": 9, "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/tmpr7mo7ysm/8c86cbec026d3307.py", "start": {"line": 165, "col": 9, "offset": 3977}, "end": {"line": 165, "col": 43, "offset": 4011}, "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_8c86cbec026d3307_41dbba43", "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": 168, "line_end": 168, "column_start": 22, "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/tmpr7mo7ysm/8c86cbec026d3307.py", "start": {"line": 168, "col": 22, "offset": 4068}, "end": {"line": 168, "col": 43, "offset": 4089}, "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_8c86cbec026d3307_c93119fd", "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": 218, "line_end": 218, "column_start": 9, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/8c86cbec026d3307.py", "start": {"line": 218, "col": 9, "offset": 5365}, "end": {"line": 218, "col": 45, "offset": 5401}, "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_8c86cbec026d3307_8eed93a6", "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": 221, "line_end": 221, "column_start": 24, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/8c86cbec026d3307.py", "start": {"line": 221, "col": 24, "offset": 5460}, "end": {"line": 221, "col": 45, "offset": 5481}, "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_8c86cbec026d3307_7a6b56ca", "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": 290, "line_end": 290, "column_start": 9, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/8c86cbec026d3307.py", "start": {"line": 290, "col": 9, "offset": 7319}, "end": {"line": 290, "col": 64, "offset": 7374}, "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_8c86cbec026d3307_98bd5b02", "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": 293, "line_end": 293, "column_start": 41, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/8c86cbec026d3307.py", "start": {"line": 293, "col": 41, "offset": 7450}, "end": {"line": 293, "col": 62, "offset": 7471}, "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"}}}]
8
true
[ "CWE-502", "CWE-502", "CWE-502", "CWE-502", "CWE-502", "CWE-502", "CWE-502", "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.pyth...
[ "security", "security", "security", "security", "security", "security", "security", "security" ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 97, 100, 165, 168, 218, 221, 290, 293 ]
[ 97, 100, 165, 168, 218, 221, 290, 293 ]
[ 9, 42, 9, 22, 9, 24, 9, 41 ]
[ 65, 63, 43, 43, 45, 45, 64, 62 ]
[ "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserial...
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "Avoid using `pickle`, which is known to lead to...
[ 5, 5, 5, 5, 5, 5, 5, 5 ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
word.py
/imsnpars/repr/word.py
zentrum-lexikographie/IMSnPars
Apache-2.0
2024-11-18T20:57:59.147728+00:00
1,538,344,607,000
ba4406694e7d3aa75ee353675f6943f2d5989733
3
{ "blob_id": "ba4406694e7d3aa75ee353675f6943f2d5989733", "branch_name": "refs/heads/master", "committer_date": 1538344607000, "content_id": "64f01dd2904395d797a3ccd6dbb036b08b538108", "detected_licenses": [ "Apache-2.0" ], "directory_id": "19e8cfa283b2545d3155bc1e2e6190af6d380671", "extension": "py", "filename": "kicad_bom_seeedstudio.py", "fork_events_count": 0, "gha_created_at": 1538151384000, "gha_event_created_at": 1538344607000, "gha_language": "Python", "gha_license_id": null, "github_id": 150765905, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3662, "license": "Apache-2.0", "license_type": "permissive", "path": "/kicad_bom_seeedstudio.py", "provenance": "stack-edu-0054.json.gz:576043", "repo_name": "leoheck/kicad-bom-seeedstudio", "revision_date": 1538344607000, "revision_id": "ddcb36cde7f1d2fbc7e1984daf3dac15be57a5a9", "snapshot_id": "62268acd17a3720cf643987f3a32b929e159849a", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/leoheck/kicad-bom-seeedstudio/ddcb36cde7f1d2fbc7e1984daf3dac15be57a5a9/kicad_bom_seeedstudio.py", "visit_date": "2020-03-30T04:51:32.725699" }
3.15625
stackv2
#!/usr/bin/env python3 """Kicad script to create a BOM according to the Seeed Studio Fusion PCBA.""" import csv import sys import xml.etree.ElementTree as ET # Natural key sorting for orders like: # C1, C5, C10, C12 ... (instead of C1, C10, C12, C5...) # http://stackoverflow.com/a/5967539 import re def atoi(text): """Atoi.""" return int(text) if text.isdigit() else text def natural_keys(text): """ alist.sort(key=natural_keys) sorts in human order. http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's implementation in the comments) """ return [atoi(c) for c in re.split('(\d+)', text)] def parse_kicad_xml(input_file): """ Kicad XML parser. Parse the KiCad XML file and look for the part designators as done in the case of the official KiCad Open Parts Library: * OPL parts are designated with "SKU" (preferred) * other parts are designated with "MPN" """ components = {} parts = {} missing = [] dnm_components = [] tree = ET.parse(input_file) root = tree.getroot() for f in root.findall('./components/'): name = f.attrib['ref'] info = {} fields = f.find('fields') opl, mpn, dnm = None, None, False if fields is not None: dnm = False for x in fields: if x.attrib['name'].upper() == 'DNM': dnm = True if x.attrib['name'].upper() == 'SKU': opl = x.text elif x.attrib['name'].upper() == 'MPN': mpn = x.text if not dnm: if opl: components[name] = opl elif mpn: components[name] = mpn else: missing += [name] continue else: dnm_components += [name] continue if components[name] not in parts: parts[components[name]] = [] parts[components[name]] += [name] return components, missing, dnm_components def write_bom_seeed(output_file_slug, components): """ Write the BOM according to the Seeed Studio Fusion PCBA. Template available at: https://statics3.seeedstudio.com/assets/file/fusion/bom_template_2016-08-18.csv ``` Ref,MPN/SKU,Qtd C1,RHA,1 "D1,D2",CC0603KRX7R9BB102,2 ``` The output is a CSV file at the `output_file_slug`.csv location. """ parts = {} for c in components: if components[c] not in parts: parts[components[c]] = [] parts[components[c]] += [c] field_names = ['Ref', 'MPN/SKU', 'Qtd'] with open("{}.csv".format(output_file_slug), 'w') as csvfile: bomwriter = csv.DictWriter( csvfile, fieldnames=field_names, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) bomwriter.writeheader() for p in sorted(parts.keys()): pieces = sorted(parts[p], key=natural_keys) designators = ",".join(pieces) bomwriter.writerow({'Ref': designators, 'MPN/SKU': p, 'Qtd': len(pieces)}) if __name__ == "__main__": input_file = sys.argv[1] output_file = sys.argv[2] components, missing, dnm_components = parse_kicad_xml(input_file) write_bom_seeed(output_file, components) if len(dnm_components) > 0: print("\n** Info **:parts with do not mount (DNM) atributte were not included") print(dnm_components) if len(missing) > 0: print("\n** Warning **: there were parts with missing SKU/MFP") print(missing)
123
28.77
87
17
954
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_145b4e8429191b37_fc5dd4a4", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 6, "line_end": 6, "column_start": 1, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpr7mo7ysm/145b4e8429191b37.py", "start": {"line": 6, "col": 1, "offset": 124}, "end": {"line": 6, "col": 35, "offset": 158}, "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_145b4e8429191b37_36a0d992", "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(input_file)", "location": {"file_path": "unknown", "line_start": 41, "line_end": 41, "column_start": 12, "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/tmpr7mo7ysm/145b4e8429191b37.py", "start": {"line": 41, "col": 12, "offset": 1034}, "end": {"line": 41, "col": 32, "offset": 1054}, "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(input_file)", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_145b4e8429191b37_95e8cd19", "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": 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/tmpr7mo7ysm/145b4e8429191b37.py", "start": {"line": 99, "col": 10, "offset": 2660}, "end": {"line": 99, "col": 54, "offset": 2704}, "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-parse" ]
[ "security", "security" ]
[ "LOW", "MEDIUM" ]
[ "HIGH", "HIGH" ]
[ 6, 41 ]
[ 6, 41 ]
[ 1, 12 ]
[ 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" ]
kicad_bom_seeedstudio.py
/kicad_bom_seeedstudio.py
leoheck/kicad-bom-seeedstudio
Apache-2.0
2024-11-18T20:57:59.226377+00:00
1,634,030,840,000
cfc573a3cf3dcedc4e0542f02f07c97ec75d3916
2
{ "blob_id": "cfc573a3cf3dcedc4e0542f02f07c97ec75d3916", "branch_name": "refs/heads/main", "committer_date": 1634030840000, "content_id": "ba106acfb69af587acce3bd2ee5951bb1cf016b7", "detected_licenses": [ "MIT-0" ], "directory_id": "b397aa55e978c580ed82cc49b5b93a8c0ae2c394", "extension": "py", "filename": "metric.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 416247725, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4071, "license": "MIT-0", "license_type": "permissive", "path": "/lambda_function_code/metric.py", "provenance": "stack-edu-0054.json.gz:576044", "repo_name": "aws-samples/ds-dashboard", "revision_date": 1634030840000, "revision_id": "1f7b8d8fbeda55917d51f98d5a0a38392a392924", "snapshot_id": "ea70e031463d394a605823fb5b1bbc29dfb98494", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/aws-samples/ds-dashboard/1f7b8d8fbeda55917d51f98d5a0a38392a392924/lambda_function_code/metric.py", "visit_date": "2023-08-13T21:27:19.709156" }
2.3125
stackv2
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 import datetime import boto3 import json events_client = boto3.client("events") sagemaker_client = boto3.client("sagemaker") ssm_client = boto3.client("ssm") class Metric: _iam_permissions = [ { "Action": ["events:PutEvents"], "Resource": "arn:aws:events:**REGION**:**ACCOUNT_ID**:event-bus/default", } ] def __init__(self, metric_name, project_name, metadata, environment): """Class constructor. child classes should not need to implement this. Args: metric_name (str): the name of this metric project_name (str): the project the metric belongs to metadata (dict): the metadata """ self.metric_name = metric_name self.project_name = project_name self.metadata = metadata self.environment = environment def get_iam_permissions(self, region, account_id): replaced_list = [] for p in self._iam_permissions: p = ( str(p) .replace("**REGION**", region) .replace("**ACCOUNT_ID**", account_id) ) replaced_list.append(eval(p)) return replaced_list def extract(self): """The method that calculates the value of the metric and formats the output. child classes should not need to implement this.""" return { "MetricName": self.metric_name, "MetricValue": self._compute_value(), "ExtractionDate": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"), "Metadata": self.metadata, "Environment": self.environment, "ProjectName": self.project_name, } def emit_event(self, payload): """emit an event with a given payload. child classes should not need to implement this. Args: payload (dict): the payload of the event to be emitted """ response = events_client.put_events( Entries=[ { "Source": "metric_extractor", "Resources": [], "DetailType": "metric_extractor", "Detail": json.dumps(payload), } ] ) def _compute_value(self): """This is where the actual calculation happens. Child classes MUST implement this""" raise NotImplementedError class TotalCompletedTrainingJobs(Metric): _iam_permissions = Metric._iam_permissions + [ {"Action": ["sagemaker:ListTrainingJobs"], "Resource": "*"} ] def _compute_value(self): jobs = sagemaker_client.list_training_jobs( StatusEquals="Completed", )["TrainingJobSummaries"] return len(jobs) class CompletedTrainingJobs24h(Metric): _iam_permissions = Metric._iam_permissions + [ {"Action": ["sagemaker:ListTrainingJobs"], "Resource": "*"} ] def _compute_value(self): today = datetime.datetime.now() yesterday = today - datetime.timedelta(days=1) jobs = sagemaker_client.list_training_jobs( StatusEquals="Completed", LastModifiedTimeAfter=yesterday, LastModifiedTimeBefore=today, )["TrainingJobSummaries"] return len(jobs) class NumberEndPointsInService(Metric): _iam_permissions = Metric._iam_permissions + [ {"Action": "sagemaker:ListEndpoints", "Resource": "*"} ] def _compute_value(self): eps = sagemaker_client.list_endpoints( StatusEquals="InService", )["Endpoints"] return len(eps) class SSMParamStoreValueMyName(Metric): _iam_permissions = Metric._iam_permissions + [ { "Action": "ssm:GetParameter", "Resource": "arn:aws:ssm:*:**ACCOUNT_ID**:parameter/MyName", } ] def _compute_value(self): return ssm_client.get_parameter(Name="MyName")["Parameter"]["Value"]
142
27.67
137
17
852
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_beac715f08faa92b_4e843cef", "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": 34, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpr7mo7ysm/beac715f08faa92b.py", "start": {"line": 45, "col": 34, "offset": 1271}, "end": {"line": 45, "col": 41, "offset": 1278}, "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" ]
[ 45 ]
[ 45 ]
[ 34 ]
[ 41 ]
[ "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" ]
metric.py
/lambda_function_code/metric.py
aws-samples/ds-dashboard
MIT-0
2024-11-18T20:58:01.411377+00:00
1,459,384,210,000
78b87251a1ac38c648cf6fb7a30851e8a6e6fb30
3
{ "blob_id": "78b87251a1ac38c648cf6fb7a30851e8a6e6fb30", "branch_name": "refs/heads/master", "committer_date": 1459384210000, "content_id": "6658dfe78c297c5831eaeff4906cd5e6edcd55b3", "detected_licenses": [ "MIT" ], "directory_id": "466b016d2f4c5633f3ab792cb1b8cfa2f24a53a2", "extension": "py", "filename": "problems.py", "fork_events_count": 0, "gha_created_at": 1456605691000, "gha_event_created_at": 1459384211000, "gha_language": "Python", "gha_license_id": null, "github_id": 52687750, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10400, "license": "MIT", "license_type": "permissive", "path": "/src/auacm/problems.py", "provenance": "stack-edu-0054.json.gz:576063", "repo_name": "BrandonLMorris/auacm-cli", "revision_date": 1459384210000, "revision_id": "192b778a04efddaf0cb8ce4e5231bd76588d66a2", "snapshot_id": "2f33c288961e7e76a7ab5abd0ec2ac67c595a129", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/BrandonLMorris/auacm-cli/192b778a04efddaf0cb8ce4e5231bd76588d66a2/src/auacm/problems.py", "visit_date": "2021-01-13T01:00:07.384471" }
2.875
stackv2
""" problems.py Module for handling problem related commands """ import requests, argparse, textwrap, os, string, glob, re import auacm from auacm.utils import subcommand, _find_pid_from_name, format_str_len import subprocess from subprocess import PIPE, STDOUT from shlex import split ALLOWED_EXTENSIONS = ['java', 'c', 'cpp', 'py', 'go'] COMPILE_COMMAND = { 'java': 'javac {0}.java', 'py': 'NO COMPILE', 'py3': 'NO COMPILE', 'c': 'gcc {0}.c -o {0}', 'cpp': 'g++ {0}.cpp -o {0}', 'go': 'go build -o {0} {0}.go' } RUN_COMMAND = { 'java': 'java -cp {0} {1}', 'py3': 'python2.7 {0}/{1}.py', 'py': 'python3 {0}/{1}.py', 'c': '{0}/{1}', 'cpp': '{0}/{1}', 'go': '{0}/{1}' } @subcommand('problem') def problems(args=None): """Get all the problems, or search for a specific one""" # Some minimal argument parsing parser = argparse.ArgumentParser( add_help=False, usage='problem [-v/--verbose] [-i/--id] <problem>' ) parser.add_argument('-v', '--verbose', action='store_true') parser.add_argument('-i', '--id', action='store_true') parser.add_argument('problem', nargs='?', default='') args = parser.parse_args(args) query = args.problem # GET request to the API request = requests.get(auacm.BASE_URL + 'problems') if not request.ok: raise auacm.exceptions.ConnectionError( 'There was an error getting the problems') # Filter out problems that aren't similar to the query problem_data = request.json()['data'] results = list() for problem in problem_data: if not args.id and query.lower() in problem['name'].lower(): results.append(problem) elif args.id and query == str(problem['pid']): results.append(problem) if not results and query: raise auacm.exceptions.ProblemNotFoundError( 'Could not find problem named {}'.format(query)) # Print the results return_value = '' for result in results: return_value += result['name'] + '\n' if args.verbose: return_value += textwrap.dedent("""\ | added: {} | appeared: {} | difficulty: {} | pid: {} | shortname: {} | solved: {} | url: {}\n """.format( result['added'], result['appeared'], result['difficulty'], result['pid'], result['shortname'], result['solved'], result['url'])) return return_value.strip() @subcommand('problem-info') def get_problem_info(args=None): """Get detailed data on a problem (description, input, etc.)""" parser = argparse.ArgumentParser( add_help=False, usage='problem-info [-i/--id] problem' ) parser.add_argument('problem') parser.add_argument('-i', '--id', action='store_true') args = parser.parse_args(args) if args.id: pid = args.problem else: pid = _find_pid_from_name(args.problem) if pid == -1: raise auacm.exceptions.ProblemNotFoundError( 'Could not find problem named {}'.format(args.problem)) response = requests.get(auacm.BASE_URL + 'problems/ ' + str(pid)) if not response.ok: raise auacm.exceptions.ProblemNotFoundError( 'There was an error getting problem id {}'.format(pid)) data = response.json()['data'] # Gather all the results return_value = textwrap.dedent(''' Name: {} Description {} Input {} Output {} ''').format( data['name'], format_str_len(data['description'], 80), format_str_len(data['input_desc'], 80), format_str_len(data['output_desc'], 80) ) for case in data['sample_cases']: return_value += textwrap.dedent(''' Sample Case {} Input: {} Output: {} ''').format(case['case_num'], case['input'], case['output']) return return_value.strip() @subcommand('init') def init_problem_directory(args=None): """Create an initial directory and files for a problem""" parser = argparse.ArgumentParser( add_help=False, usage='init [-i/--id] problem' ) parser.add_argument('problem') parser.add_argument('-i', '--id', action='store_true') args = parser.parse_args(args) if args.id: pid = args.problem else: pid = _find_pid_from_name(args.problem) if pid == -1: raise auacm.exceptions.ProblemNotFoundError( 'Could not find problem: ' + args.problem) response = requests.get(auacm.BASE_URL + 'problems/' + str(pid)) if not response.ok: raise auacm.exceptions.ProblemNotFoundError( 'There was an error getting problem id {}'.format(pid)) data = response.json()['data'] # Save everything to files dir_name = string.capwords(data['name']).replace(' ', '') os.mkdir(dir_name) desc_file = open(os.path.join(dir_name, 'description.md'), 'w') desc_file.write(get_problem_info(['-i', str(pid)])) desc_file.close() os.mkdir(os.path.join(dir_name, 'tests')) for case in data['sample_cases']: in_file = open(os.path.join(os.path.join( dir_name, 'tests', 'in' + str(case['case_num']) + '.txt')), 'w') in_file.write(case['input']) in_file.close() out_file = open(os.path.join(os.path.join( dir_name, 'tests', 'out' + str(case['case_num']) + '.txt')), 'w') out_file.write(case['output']) out_file.close() return 'Done!' @subcommand('test') def test_solution(args=None): """Run a solution against sample cases""" parser = argparse.ArgumentParser( add_help=False, usage='test [-p {2,3}] <solution> [-i [<problem>]]' ) parser.add_argument('-p', '--python', type=int, choices=[2, 3]) parser.add_argument('solution') parser.add_argument('-i', '--id', action='store_true') parser.add_argument('-l', '--local', action='store_true') parser.add_argument('problem', nargs='?', default=None) args = parser.parse_args(args) # Make sure that we can support this filetype if not args.solution.split('.')[1] in ALLOWED_EXTENSIONS: raise Exception('Filetype not supported') # Get the sample cases for the problem solution_name = args.solution.split('/')[-1] cases = (_get_remote_sample_cases(args.problem, solution_name, args.id) if not args.local else _get_local_sample_cases()) # Compile the solution, if necessary compiled = _compile(args.solution, args.python == 3) if not compiled: return 'Compilation error' filename, filetype = args.solution.split('.') if filetype == 'py' and not args.python or args.python == 3: filetype = 'py3' run_cmd = RUN_COMMAND[filetype].format(os.getcwd(), filename) for case in cases: # Execute the test solution proc = subprocess.Popen( split(run_cmd), stdout=PIPE, stdin=PIPE, stderr=STDOUT, universal_newlines=True) result = proc.communicate(input=case['input'])[0] if proc.returncode != 0: return 'Runtime error\n' + str(result) # Compare the results to the solution result_lines = result.splitlines() answer_lines = case['output'].splitlines() if len(result_lines) != len(answer_lines): return textwrap.dedent(""" Wrong number of lines Expected {} line(s) Found {} line(s) """).strip().format(len(answer_lines), len(result_lines)) for i in range(len(result_lines)): if result_lines[i] != answer_lines[i]: return textwrap.dedent(""" Wrong answer Expected: {} Found: {}""").strip().format(answer_lines[i], result_lines[i]) return 'Passed all sample cases' def _compile(solution, py2=False): """Attempt to compile a solution, return True if successful""" filename, filetype = solution.split('.') if COMPILE_COMMAND[filetype] == 'NO COMPILE': return True # Execute compilation and return success return subprocess.call( split(COMPILE_COMMAND[filetype].format(filename))) == 0 def _get_remote_sample_cases(problem, solution, is_id): """ Retrieve the sample cases from the server for a problem for local testing. :param problem: The problem name to get the test cases for, or None :param solution: the file name of the local solution, if problem is None :param is_id: True if the problem argument :throws auacm.exceptions.ProblemNotFoundError: if cannot locate the problem """ if problem: if is_id: pid = int(problem) else: pid = _find_pid_from_name(problem) else: # Get the problem name from the solution file pid = _find_pid_from_name(solution.split('.')[0]) if pid == -1: raise auacm.exceptions.ProblemNotFoundError( 'Could not frind problem: ' + problem or solution.split('.')[0]) response = requests.get(auacm.BASE_URL + 'problems/' + str(pid)) return response.json()['data']['sample_cases'] def _get_local_sample_cases(): """Retrieve the sample cases locally from the tests/ directory""" test_dir = os.path.join(os.getcwd(), 'tests') in_files = glob.glob(os.path.join(test_dir, 'in*')) if not in_files: raise Exception('No test cases found in tests/ directory') cases = list() for in_file in in_files: # Find the corresponding output file match = re.search(r'in(\d+).txt', in_file) if not match: raise Exception('Test files not properly named.' 'Should be in1.txt, in2.txt, ...') test_num = match.group(1) out_file = os.path.join(test_dir, 'out' + test_num + '.txt') with open(out_file, 'r') as out_f, open(in_file, 'r') as in_f: cases.append({ 'input': in_f.read() + '\n', 'output': out_f.read() }) return cases
325
31
79
21
2,396
python
[{"finding_id": "semgrep_rules.python.requests.best-practice.use-timeout_f7d07ee15e061bf8_291f3863", "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(auacm.BASE_URL + 'problems', timeout=30)", "location": {"file_path": "unknown", "line_start": 48, "line_end": 48, "column_start": 15, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpr7mo7ysm/f7d07ee15e061bf8.py", "start": {"line": 48, "col": 15, "offset": 1279}, "end": {"line": 48, "col": 56, "offset": 1320}, "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(auacm.BASE_URL + 'problems', 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-timeout_f7d07ee15e061bf8_eb290a0c", "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(auacm.BASE_URL + 'problems/ ' + str(pid), timeout=30)", "location": {"file_path": "unknown", "line_start": 107, "line_end": 107, "column_start": 16, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpr7mo7ysm/f7d07ee15e061bf8.py", "start": {"line": 107, "col": 16, "offset": 3245}, "end": {"line": 107, "col": 71, "offset": 3300}, "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(auacm.BASE_URL + 'problems/ ' + str(pid), 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-timeout_f7d07ee15e061bf8_493a86c2", "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(auacm.BASE_URL + 'problems/' + str(pid), timeout=30)", "location": {"file_path": "unknown", "line_start": 167, "line_end": 167, "column_start": 16, "column_end": 69, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpr7mo7ysm/f7d07ee15e061bf8.py", "start": {"line": 167, "col": 16, "offset": 4738}, "end": {"line": 167, "col": 69, "offset": 4791}, "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(auacm.BASE_URL + 'problems/' + str(pid), 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_f7d07ee15e061bf8_e3d06711", "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": 178, "line_end": 178, "column_start": 17, "column_end": 68, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/f7d07ee15e061bf8.py", "start": {"line": 178, "col": 17, "offset": 5107}, "end": {"line": 178, "col": 68, "offset": 5158}, "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_f7d07ee15e061bf8_a095e769", "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": 184, "line_end": 185, "column_start": 19, "column_end": 77, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/f7d07ee15e061bf8.py", "start": {"line": 184, "col": 19, "offset": 5340}, "end": {"line": 185, "col": 77, "offset": 5448}, "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_f7d07ee15e061bf8_584fbbc1", "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": 189, "line_end": 190, "column_start": 20, "column_end": 78, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/f7d07ee15e061bf8.py", "start": {"line": 189, "col": 20, "offset": 5530}, "end": {"line": 190, "col": 78, "offset": 5639}, "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_f7d07ee15e061bf8_1773f742", "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": 232, "line_end": 237, "column_start": 16, "column_end": 37, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/f7d07ee15e061bf8.py", "start": {"line": 232, "col": 16, "offset": 7095}, "end": {"line": 237, "col": 37, "offset": 7253}, "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_f7d07ee15e061bf8_020f901b", "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": 269, "line_end": 270, "column_start": 12, "column_end": 59, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/f7d07ee15e061bf8.py", "start": {"line": 269, "col": 12, "offset": 8450}, "end": {"line": 270, "col": 59, "offset": 8525}, "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.requests.best-practice.use-raise-for-status_f7d07ee15e061bf8_e139d1a7", "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": 297, "line_end": 297, "column_start": 16, "column_end": 69, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmpr7mo7ysm/f7d07ee15e061bf8.py", "start": {"line": 297, "col": 16, "offset": 9387}, "end": {"line": 297, "col": 69, "offset": 9440}, "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_f7d07ee15e061bf8_b56a13a9", "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(auacm.BASE_URL + 'problems/' + str(pid), timeout=30)", "location": {"file_path": "unknown", "line_start": 297, "line_end": 297, "column_start": 16, "column_end": 69, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpr7mo7ysm/f7d07ee15e061bf8.py", "start": {"line": 297, "col": 16, "offset": 9387}, "end": {"line": 297, "col": 69, "offset": 9440}, "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(auacm.BASE_URL + 'problems/' + str(pid), 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_f7d07ee15e061bf8_1c6ecdab", "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": 318, "line_end": 318, "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/tmpr7mo7ysm/f7d07ee15e061bf8.py", "start": {"line": 318, "col": 14, "offset": 10197}, "end": {"line": 318, "col": 33, "offset": 10216}, "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_f7d07ee15e061bf8_f9ec4b7d", "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": 318, "line_end": 318, "column_start": 44, "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/tmpr7mo7ysm/f7d07ee15e061bf8.py", "start": {"line": 318, "col": 44, "offset": 10227}, "end": {"line": 318, "col": 62, "offset": 10245}, "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"}}}]
12
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" ]
[ 232, 269 ]
[ 237, 270 ]
[ 16, 12 ]
[ 37, 59 ]
[ "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" ]
problems.py
/src/auacm/problems.py
BrandonLMorris/auacm-cli
MIT
2024-11-18T20:58:02.832007+00:00
1,569,953,362,000
50dedba6c5ac39acb836381ed3886f6f392f18db
3
{ "blob_id": "50dedba6c5ac39acb836381ed3886f6f392f18db", "branch_name": "refs/heads/master", "committer_date": 1569953362000, "content_id": "b1e92be1b46fbeffbaee50ca0955f45cc21adc23", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "ac216a2cc36f91625e440247986ead2cd8cce350", "extension": "py", "filename": "trigger_tasks.py", "fork_events_count": 1, "gha_created_at": 1569954164000, "gha_event_created_at": 1673086683000, "gha_language": "Python", "gha_license_id": "BSD-3-Clause", "github_id": 212168656, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5882, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/appengine/findit/util_scripts/experiments/trigger_tasks.py", "provenance": "stack-edu-0054.json.gz:576073", "repo_name": "xinghun61/infra", "revision_date": 1569953362000, "revision_id": "b5d4783f99461438ca9e6a477535617fadab6ba3", "snapshot_id": "b77cdc566d9a63c5d97f9e30e8d589982b1678ab", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/xinghun61/infra/b5d4783f99461438ca9e6a477535617fadab6ba3/appengine/findit/util_scripts/experiments/trigger_tasks.py", "visit_date": "2023-01-12T21:36:49.360274" }
2.625
stackv2
#!/usr/bin/env python # Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Flakiness Swarming Task Experiment - Task Triggering Script Triggers the needed tasks to run the experiment described by the input file. Expects as an argument a path to a json file with the following structure: { "experiment_id": "experiment-20180926-30331", "experiment_start": 1536000000, "dimensions": "os:Windows-7-SP1,pool:Chrome", "additional_args_template": "--gtest_repeat=%d <...more args...>", "task_count": 100, "repeats_per_task": 1, "rows": [ { "isolate_hash": "fd4454258e116e999f16ccd6de5faca7b737fbf4", }, { "isolate_hash": "ca8c6b3c106f5fd03df487ab062479ff315ee9a4" }, { "isolate_hash": "4ff8e831b038aa18c40715eccf45eda7820484a5" }, { "isolate_hash": "d18714f2fe36f603836b8592fbfdc486fe661de5" } ] } This script will read the file, trigger the swarming tasks tagging them with the experiment name. If there are tasks already with the given experiment name, only trigger the needed amount to reach the specified task count, so as to increment the task count if necessary without losing the previous ones. A separate script will read this file and get the results from swarming server and aggregate them. see https://docs.google.com/document/d/1zHGwa2bcCY8galQmWMc0fiogCj_p3aiC3KUBgXMUQTg/edit?usp=sharing """ import os import sys import subprocess import json REQUIRED_EXPERIMENT_PARAMETERS = ('dimensions', 'additional_args_template', 'task_count', 'repeats_per_task', 'rows') class NoSwarmingTaskIdException(Exception): pass def ParseSwarmingCommandResult(output): """Gets the task id from the trigger command output""" for line in output.splitlines(): if line.strip().startswith('swarming.py collect'): result = line.strip().split()[-1] print 'Triggered swarming task:', result return result raise NoSwarmingTaskIdException(output) def ComposeSwarmingTaskTriggerCommand(experiment_id, dimensions, isolate_hash, repeat_count, additional_args_template): """Composes the command line invocation for swarming.py . Note that the environment variable SWARMING_PY is expected to have been set to local checkout path of the following file: https://cs.chromium.org/chromium/infra/luci/client/swarming.py Args: experiment_id (str): The value of the tag to use to identify the task runs as part of a given experiment. dimensions (str): A string like "os:Mac,pool:Chrome" specifying the dimensions needed to serve the request. isolate_hash (str): Input isolate for the task. repeat_count (int): Number of times the test needs to be repeated. This is used to populate the template containing additional args. additional_args_template (str): A template containing the additional arguments to pass to the command line. It is expected to contain %d in place of the repeat count. Returns: A list of strings representing the command parts, suitable for passing to subprocess lib. """ def DimensionFlags(dimensions): """E.g. convert `os:Mac,pool:Chrome` to `-d os Mac -d pool Chrome`.""" result = [] for d in dimensions.split(','): k, v = d.split(':') result.append('-d {0} {1}'.format(k, v)) return ' '.join(result) command_template = ' '.join([ 'python {swarming_py} trigger', '-I isolateserver.appspot.com', '-S chromium-swarm.appspot.com', '{dimension_flags}', '-s {isolate_hash}', '--priority=190', '--expiration=86399', # 23:59:59 '--tags=experiment_id:{experiment_id}', '-- {additional_args}', ]) command = command_template.format( experiment_id=experiment_id + isolate_hash[:4], swarming_py=os.environ.get('SWARMING_PY', 'swarming.py'), dimension_flags=DimensionFlags(dimensions), isolate_hash=isolate_hash, additional_args=additional_args_template % repeat_count, ) return command.split() def GetTaskCount(experiment_id, isolate_hash, experiment_start): """Determines number of swarming tasks with experiment name.""" query_command = [ 'python', os.environ.get('SWARMING_PY', 'swarming.py'), 'query', '-S', 'chromium-swarm.appspot.com', 'tasks/count?tags=experiment_id%%3A%s&start=%d' % (experiment_id + isolate_hash[:4], experiment_start) ] return int(json.loads(subprocess.check_output(query_command))['count']) def main(experiment_path): experiment = json.load(open(experiment_path)) for parameter in REQUIRED_EXPERIMENT_PARAMETERS: assert parameter in experiment, \ '"%s" is a required parameter, and missing from %s' % ( parameter, experiment_path) dimensions = experiment['dimensions'] additional_args_template = experiment['additional_args_template'] task_count = experiment['task_count'] repeats_per_task = experiment['repeats_per_task'] rows = experiment['rows'] experiment_id = experiment['experiment_id'] experiment_start = experiment['experiment_start'] for row in rows: current_task_count = GetTaskCount(experiment_id, row['isolate_hash'], experiment_start) if current_task_count < task_count: remaining_tasks = task_count - current_task_count for _ in range(remaining_tasks): subprocess.check_output( ComposeSwarmingTaskTriggerCommand( experiment_id, dimensions, row['isolate_hash'], repeats_per_task, additional_args_template)) return 0 if __name__ == '__main__': assert len(sys.argv) == 2, 'Path to a json file expected as first argument' sys.exit(main(sys.argv[1]))
160
35.76
96
17
1,491
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_5305f978d78e4be3_723953e1", "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": 129, "line_end": 129, "column_start": 25, "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/tmpr7mo7ysm/5305f978d78e4be3.py", "start": {"line": 129, "col": 25, "offset": 4599}, "end": {"line": 129, "col": 63, "offset": 4637}, "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.dangerous-subprocess-use-tainted-env-args_5305f978d78e4be3_202f8092", "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 'check_output' 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": 129, "line_end": 129, "column_start": 49, "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/tmpr7mo7ysm/5305f978d78e4be3.py", "start": {"line": 129, "col": 49, "offset": 4623}, "end": {"line": 129, "col": 62, "offset": 4636}, "extra": {"message": "Detected subprocess function 'check_output' with user controlled data. A malicious actor could leverage this to perform command injection. You may consider using 'shlex.quote()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_5305f978d78e4be3_e7c32975", "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": 133, "line_end": 133, "column_start": 26, "column_end": 47, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/5305f978d78e4be3.py", "start": {"line": 133, "col": 26, "offset": 4703}, "end": {"line": 133, "col": 47, "offset": 4724}, "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_5305f978d78e4be3_d3f3f2b8", "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": 151, "line_end": 154, "column_start": 9, "column_end": 61, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/5305f978d78e4be3.py", "start": {"line": 151, "col": 9, "offset": 5537}, "end": {"line": 154, "col": 61, "offset": 5733}, "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"}}}]
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.dangerous-subprocess-use-audit" ]
[ "security", "security", "security" ]
[ "LOW", "MEDIUM", "LOW" ]
[ "HIGH", "HIGH", "HIGH" ]
[ 129, 129, 151 ]
[ 129, 129, 154 ]
[ 25, 49, 9 ]
[ 63, 62, 61 ]
[ "A01:2017 - Injection", "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()'.", "Detected subproces...
[ 7.5, 7.5, 7.5 ]
[ "LOW", "MEDIUM", "LOW" ]
[ "HIGH", "MEDIUM", "HIGH" ]
trigger_tasks.py
/appengine/findit/util_scripts/experiments/trigger_tasks.py
xinghun61/infra
BSD-3-Clause
2024-11-18T20:58:05.648482+00:00
1,587,241,026,000
b64ec12cb58308d58d6093eb61b0989a7703982b
3
{ "blob_id": "b64ec12cb58308d58d6093eb61b0989a7703982b", "branch_name": "refs/heads/master", "committer_date": 1587241026000, "content_id": "8d17da0b45769dfda21531b6462bc32fdb00e52f", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c065661d932b8368ba325fb2880df37b8fe74c77", "extension": "py", "filename": "aserver.py", "fork_events_count": 0, "gha_created_at": 1599767855000, "gha_event_created_at": 1599767857000, "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 294509564, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2153, "license": "Apache-2.0", "license_type": "permissive", "path": "/commandlist/aserver.py", "provenance": "stack-edu-0054.json.gz:576108", "repo_name": "dAYOShACKER505/htk-lite", "revision_date": 1587241026000, "revision_id": "b3cd8c4890061e25abcae9ed38429d84efd16cd2", "snapshot_id": "6c1c247f90aa99ab254f10598570db313777adf3", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/dAYOShACKER505/htk-lite/b3cd8c4890061e25abcae9ed38429d84efd16cd2/commandlist/aserver.py", "visit_date": "2022-04-22T11:45:56.884954" }
2.609375
stackv2
#!/usr/local/bin/python # coding: latin-1 #if you use this code give me credit @tuf_unkn0wn #i do not give you permission to show / edit this script without my credit #to ask questions or report a problem message me on instagram @tuf_unkn0wn """ ██░ ██ ▄▄▄ ▄████▄ ██ ▄█▀▓█████ ▓█████▄ ▓██░ ██▒▒████▄ ▒██▀ ▀█ ██▄█▒ ▓█ ▀ ▒██▀ ██▌ ▒██▀▀██░▒██ ▀█▄ ▒▓█ ▄ ▓███▄░ ▒███ ░██ █▌ ░▓█ ░██ ░██▄▄▄▄██ ▒▓▓▄ ▄██▒▓██ █▄ ▒▓█ ▄ ░▓█▄ ▌ ░▓█▒░██▓ ▓█ ▓██▒▒ ▓███▀ ░▒██▒ █▄░▒████▒░▒████▓ ▒ ▒░▒ ▒▒ ▓▒█ ░▒ ▒ ░▒ ▒▒ ▓▒ ▒░ ░ ▒▒▓ ▒ ▒ ░▒░ ░ ▒ ▒▒ ░ ░ ▒ ░ ░▒ ▒░ ░ ░ ░ ░ ▒ ▒ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ """ import os import sys import random import socks import socket lred = '\033[91m' lblue = '\033[94m' lgreen = '\033[92m' yellow = '\033[93m' cyan = '\033[1;36m' purple = '\033[95m' red = '\033[31m' green = '\033[32m' blue = '\033[34m' orange = '\033[33m' colorlist = [red, blue, green, yellow, lblue, purple, cyan, lred, lgreen, orange] randomcolor = random.choice(colorlist) banner3list = [red, blue, green, purple] def aserver(): gw = os.popen("ip -4 route show default").read().split() s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((gw[2], 0)) ipaddr = s.getsockname()[0] print "\033[93mStarting Server\033[0m..." os.system("service apache2 start") br = raw_input("\033[92mBrowser: \033[0m") a = '{0} {1}'.format(br,ipaddr) os.system(a) stop = raw_input("\033[1mhit enter to stop server:\033[0m ") print "\033[93mStopping Server\033[0m..." os.system("service apache2 stop") aserver()
56
28.62
81
13
723
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_1538cc16c27e5dc9_4ec79fc9", "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": 2, "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/tmpr7mo7ysm/1538cc16c27e5dc9.py", "start": {"line": 51, "col": 2, "offset": 1989}, "end": {"line": 51, "col": 14, "offset": 2001}, "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" ]
[ 51 ]
[ 51 ]
[ 2 ]
[ 14 ]
[ "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" ]
aserver.py
/commandlist/aserver.py
dAYOShACKER505/htk-lite
Apache-2.0
2024-11-18T20:58:08.900356+00:00
1,590,647,484,000
f36c1553ba060fd7892ff1ff5e7e43aeef7997b4
3
{ "blob_id": "f36c1553ba060fd7892ff1ff5e7e43aeef7997b4", "branch_name": "refs/heads/master", "committer_date": 1590647484000, "content_id": "5b28e16a53d70121ecb97cc41b06d60e33a79dd1", "detected_licenses": [ "MIT" ], "directory_id": "7a11eeb3d3c0381d91f81c9795b417f0ade5e26a", "extension": "py", "filename": "NN_using_Tensorflow.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 266443328, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2022, "license": "MIT", "license_type": "permissive", "path": "/src/NN_using_Tensorflow.py", "provenance": "stack-edu-0054.json.gz:576150", "repo_name": "sirine-chahma/parking_space_detection", "revision_date": 1590647484000, "revision_id": "290ad6dfe7fea8740fed83f14500ac75c365ed2b", "snapshot_id": "f9663549c4bc3743aca2747aab598578650fa221", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/sirine-chahma/parking_space_detection/290ad6dfe7fea8740fed83f14500ac75c365ed2b/src/NN_using_Tensorflow.py", "visit_date": "2022-09-06T01:58:54.037276" }
2.859375
stackv2
#Algorithme de réseau de neuronne fully connected sans utilisation de Keras from __future__ import print_function import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import pickle import tensorflow as tf import matplotlib.pyplot as plt X = tf.placeholder(tf.float32, [None, 28, 28, 1]) #Matrice contenant un lot d'images W = tf.Variable(tf.zeros([28 * 28, 2])) #Matrice des poids b = tf.Variable(tf.zeros([2])) #Matrice des biais init = tf.global_variables_initializer() # modèle Y = tf.nn.softmax(tf.matmul(tf.reshape(X, [-1, 28 * 28]), W) + b) # Matrice pour les valeurs correctes Y_ = tf.placeholder(tf.float32, [None, 2]) # loss function cross_entropy = -tf.reduce_sum(Y_ * tf.log(Y)) # % de réponses correctes dans un lot d'images is_correct = tf.equal(tf.argmax(Y, 1), tf.argmax(Y_, 1)) accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32)) #Optimisation par descente de gradient optimizer = tf.train.GradientDescentOptimizer(0.0003) train_step = optimizer.minimize(cross_entropy) #Lancement de la session sess = tf.Session() sess.run(init) #Chargement des images de la base de données pickle_in = open("X.pickle", "rb") Xpickle = pickle.load(pickle_in) #Chargement des labels de la base de données pickle_in = open("y.pickle", "rb") Ypickle_init = pickle.load(pickle_in) #Modification des labels pour que une place busy ne soit plus 0 mais [1,0] et une place free ne soit plus 1 mais [0,1] def modif_Y(Ypickle_init): Ypickle = [] for i in range(len(Ypickle_init)): if Ypickle_init[i] == 0: Ypickle.append([1, 0]) if Ypickle_init[i] == 1: Ypickle.append([0, 1]) return Ypickle # Compilation du modèle A = [] index = [] for j in range(1): train_data = {X: Xpickle[j: j+100], Y_: modif_Y(Ypickle_init)[j: j+100]} _, loss_val, a = sess.run([train_step, cross_entropy, accuracy], feed_dict = train_data) # Enregistrement de l'accuracy A.append(a) index.append(j) #Affichage de l'accuracy plt.plot(index, A) plt.show()
75
25.88
118
13
593
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.open-never-closed_41001702859be142_0b3b67bc", "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": 41, "line_end": 41, "column_start": 1, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmpr7mo7ysm/41001702859be142.py", "start": {"line": 41, "col": 1, "offset": 1115}, "end": {"line": 41, "col": 35, "offset": 1149}, "extra": {"message": "file object opened without corresponding close", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.file-object-redefined-before-close_41001702859be142_f2454c8d", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.file-object-redefined-before-close", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Detected a file object that is redefined and never closed. This could leak file descriptors and unnecessarily consume system resources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 41, "line_end": 45, "column_start": 1, "column_end": 35, "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.correctness.file-object-redefined-before-close", "path": "/tmp/tmpr7mo7ysm/41001702859be142.py", "start": {"line": 41, "col": 1, "offset": 1115}, "end": {"line": 45, "col": 35, "offset": 1264}, "extra": {"message": "Detected a file object that is redefined and never closed. This could leak file descriptors and unnecessarily consume system resources.", "metadata": {"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.deserialization.avoid-pickle_41001702859be142_505f1ae2", "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": 11, "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/tmpr7mo7ysm/41001702859be142.py", "start": {"line": 42, "col": 11, "offset": 1160}, "end": {"line": 42, "col": 33, "offset": 1182}, "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_41001702859be142_a63b654d", "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": 45, "line_end": 45, "column_start": 1, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmpr7mo7ysm/41001702859be142.py", "start": {"line": 45, "col": 1, "offset": 1230}, "end": {"line": 45, "col": 35, "offset": 1264}, "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_41001702859be142_edabc2f3", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 46, "line_end": 46, "column_start": 16, "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/tmpr7mo7ysm/41001702859be142.py", "start": {"line": 46, "col": 16, "offset": 1280}, "end": {"line": 46, "col": 38, "offset": 1302}, "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-pickle", "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 42, 46 ]
[ 42, 46 ]
[ 11, 16 ]
[ 33, 38 ]
[ "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "Avoid using `pickle`, which is known to lead to...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
NN_using_Tensorflow.py
/src/NN_using_Tensorflow.py
sirine-chahma/parking_space_detection
MIT
2024-11-18T20:58:14.143086+00:00
1,609,002,362,000
12c961c49a98ffb2bb2f555656de2c30e2622af7
2
{ "blob_id": "12c961c49a98ffb2bb2f555656de2c30e2622af7", "branch_name": "refs/heads/master", "committer_date": 1609002362000, "content_id": "745ee58e7d1034bd19b5016baf9d174d9112cbe9", "detected_licenses": [ "MIT" ], "directory_id": "8fd504b3f5ebc955c339cb2cc8c025a5d0116a82", "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": 281693015, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2585, "license": "MIT", "license_type": "permissive", "path": "/app/contacts/views.py", "provenance": "stack-edu-0054.json.gz:576215", "repo_name": "Akshaychdev/Usedbrains-E-market-project", "revision_date": 1609002362000, "revision_id": "1af1d5d94a409c5a2dd1dad80d28a52073f0ac49", "snapshot_id": "5b5762070186d0106d65c07659f2e93ad11b3380", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Akshaychdev/Usedbrains-E-market-project/1af1d5d94a409c5a2dd1dad80d28a52073f0ac49/app/contacts/views.py", "visit_date": "2023-02-07T09:10:30.750391" }
2.390625
stackv2
from django.shortcuts import redirect from django.contrib import messages # from django.core.mail import send_mail from contacts.models import Contact def contact(request): ''' View for the inquiry form ''' if request.method == 'POST': # The data that are get posted from the form: user_id, seller_email # listing_id, listing(title), name(user), email, phone, message listing_id = request.POST['listing_id'] user_id = request.POST['user_id'] # seller_email = request.POST['seller_email'] listing_title = request.POST['listing_title'] user_name = request.POST['name'] user_email = request.POST['email'] user_phone = request.POST['phone'] user_message = request.POST['message'] # Check if user has made an inquiry already if request.user.is_authenticated: user_id = request.user.id has_contacted = Contact.objects.all().filter(listing_id=listing_id, user_id=user_id) if has_contacted: messages.error(request, "You have already made an inquiry \ for this item") return redirect(f'/listings/{listing_id}') # Inquiry check for not authenticated users, check the email and phone else: email_check = Contact.objects.all().filter(email=user_email) phone_check = Contact.objects.all().filter(phone=user_phone) if email_check or phone_check: messages.error(request, "An inquiry with this email or phone \ done already") return redirect(f'/listings/{listing_id}') contact = Contact(listing=listing_title, listing_id=listing_id, name=user_name, email=user_email, phone=user_phone, message=user_message, user_id=user_id) contact.save() # Send mail # send_mail( # 'Usedbrains Listing Inquiry', # 'There has been an inquiry for ' + listing_title + '. Sign in to \ # the admin panel for more info', # 'akshaych.dev@gmail.com', # [seller_email, 'akshaych203@gmail.com'], # fail_silently=False # ) messages.success(request, "Your interest recorded, the seller will \ get back to you soon") return redirect(f'/listings/{listing_id}')
65
38.77
80
16
497
python
[{"finding_id": "semgrep_rules.python.django.security.injection.open-redirect_2fa7be4d5edba1d6_2eb82a3b", "tool_name": "semgrep", "rule_id": "rules.python.django.security.injection.open-redirect", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Data from request (listing_id) is passed to redirect(). This is an open redirect and could be exploited. Ensure you are redirecting to safe URLs by using django.utils.http.is_safe_url(). See https://cwe.mitre.org/data/definitions/601.html for more information.", "remediation": "", "location": {"file_path": "unknown", "line_start": 14, "line_end": 41, "column_start": 9, "column_end": 59, "code_snippet": "requires login"}, "cwe_id": "CWE-601: URL Redirection to Untrusted Site ('Open Redirect')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2021 - Broken Access Control", "references": [{"url": "https://www.djm.org.uk/posts/djangos-little-protections-word-redirect-dangers/", "title": null}, {"url": "https://github.com/django/django/blob/d1b7bd030b1db111e1a3505b1fc029ab964382cc/django/utils/http.py#L231", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.injection.open-redirect", "path": "/tmp/tmpr7mo7ysm/2fa7be4d5edba1d6.py", "start": {"line": 14, "col": 9, "offset": 410}, "end": {"line": 41, "col": 59, "offset": 1718}, "extra": {"message": "Data from request (listing_id) is passed to redirect(). This is an open redirect and could be exploited. Ensure you are redirecting to safe URLs by using django.utils.http.is_safe_url(). See https://cwe.mitre.org/data/definitions/601.html for more information.", "metadata": {"cwe": ["CWE-601: URL Redirection to Untrusted Site ('Open Redirect')"], "owasp": ["A01:2021 - Broken Access Control", "A01:2025 - Broken Access Control"], "references": ["https://www.djm.org.uk/posts/djangos-little-protections-word-redirect-dangers/", "https://github.com/django/django/blob/d1b7bd030b1db111e1a3505b1fc029ab964382cc/django/utils/http.py#L231"], "category": "security", "technology": ["django"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.django.security.injection.open-redirect_2fa7be4d5edba1d6_6ba1dbae", "tool_name": "semgrep", "rule_id": "rules.python.django.security.injection.open-redirect", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Data from request (listing_id) is passed to redirect(). This is an open redirect and could be exploited. Ensure you are redirecting to safe URLs by using django.utils.http.is_safe_url(). See https://cwe.mitre.org/data/definitions/601.html for more information.", "remediation": "", "location": {"file_path": "unknown", "line_start": 14, "line_end": 65, "column_start": 9, "column_end": 51, "code_snippet": "requires login"}, "cwe_id": "CWE-601: URL Redirection to Untrusted Site ('Open Redirect')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2021 - Broken Access Control", "references": [{"url": "https://www.djm.org.uk/posts/djangos-little-protections-word-redirect-dangers/", "title": null}, {"url": "https://github.com/django/django/blob/d1b7bd030b1db111e1a3505b1fc029ab964382cc/django/utils/http.py#L231", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.injection.open-redirect", "path": "/tmp/tmpr7mo7ysm/2fa7be4d5edba1d6.py", "start": {"line": 14, "col": 9, "offset": 410}, "end": {"line": 65, "col": 51, "offset": 2584}, "extra": {"message": "Data from request (listing_id) is passed to redirect(). This is an open redirect and could be exploited. Ensure you are redirecting to safe URLs by using django.utils.http.is_safe_url(). See https://cwe.mitre.org/data/definitions/601.html for more information.", "metadata": {"cwe": ["CWE-601: URL Redirection to Untrusted Site ('Open Redirect')"], "owasp": ["A01:2021 - Broken Access Control", "A01:2025 - Broken Access Control"], "references": ["https://www.djm.org.uk/posts/djangos-little-protections-word-redirect-dangers/", "https://github.com/django/django/blob/d1b7bd030b1db111e1a3505b1fc029ab964382cc/django/utils/http.py#L231"], "category": "security", "technology": ["django"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_2fa7be4d5edba1d6_2aed828b", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_authenticated\" a function or an attribute? If it is a function, you may have meant request.user.is_authenticated() because request.user.is_authenticated is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 24, "line_end": 24, "column_start": 12, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpr7mo7ysm/2fa7be4d5edba1d6.py", "start": {"line": 24, "col": 12, "offset": 838}, "end": {"line": 24, "col": 41, "offset": 867}, "extra": {"message": "Is \"is_authenticated\" a function or an attribute? If it is a function, you may have meant request.user.is_authenticated() because request.user.is_authenticated 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-601", "CWE-601" ]
[ "rules.python.django.security.injection.open-redirect", "rules.python.django.security.injection.open-redirect" ]
[ "security", "security" ]
[ "MEDIUM", "MEDIUM" ]
[ "MEDIUM", "MEDIUM" ]
[ 14, 14 ]
[ 41, 65 ]
[ 9, 9 ]
[ 59, 51 ]
[ "A01:2021 - Broken Access Control", "A01:2021 - Broken Access Control" ]
[ "Data from request (listing_id) is passed to redirect(). This is an open redirect and could be exploited. Ensure you are redirecting to safe URLs by using django.utils.http.is_safe_url(). See https://cwe.mitre.org/data/definitions/601.html for more information.", "Data from request (listing_id) is passed to redir...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
views.py
/app/contacts/views.py
Akshaychdev/Usedbrains-E-market-project
MIT
2024-11-18T20:58:19.497949+00:00
1,602,041,927,000
8a4c847e89626158645daad76b9e92e10bdbdae4
3
{ "blob_id": "8a4c847e89626158645daad76b9e92e10bdbdae4", "branch_name": "refs/heads/master", "committer_date": 1602041927000, "content_id": "eda49c887d8a473117b49d9bc3af01beab4f09e7", "detected_licenses": [ "MIT" ], "directory_id": "3ff4b55ab15558ebaa62ef8e1f607b2dd1dd6e0b", "extension": "py", "filename": "process_sumo_data.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 279502710, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 851, "license": "MIT", "license_type": "permissive", "path": "/process_data/process_sumo_data.py", "provenance": "stack-edu-0054.json.gz:576256", "repo_name": "TwelveYC/road-network-modeling", "revision_date": 1602041927000, "revision_id": "a55de12c6f11c7aa4b994fee9a8dd1f31e0775fb", "snapshot_id": "d0ebe8c9a90fff9b85765d9da65952526d0ce699", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/TwelveYC/road-network-modeling/a55de12c6f11c7aa4b994fee9a8dd1f31e0775fb/process_data/process_sumo_data.py", "visit_date": "2022-12-28T05:55:48.204468" }
2.53125
stackv2
import networkx as nx import matplotlib.pyplot as plt from xml.dom import minidom def get_sumo_data(): g = nx.grid_2d_graph(6, 6) dom = minidom.Document() nodes = dom.createElement("nodes") nodes.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance") nodes.setAttribute("xsi:noNamespaceSchemaLocation", "http://sumo.dlr.de/xsd/nodes_file.xsd") vs = g.nodes index = 0 def get_index(i): return str(6*i[0]+i[1]) for i in vs: node = dom.createElement("node") node.setAttribute("id", str(index)) node.setAttribute("x", str(i[0]*250)) node.setAttribute("y", str(i[1]*250)) nodes.appendChild(node) index += 1 dom.appendChild(nodes) with open("sumo.nod.xml", "w") as fp: dom.writexml(fp, indent="\t", newl="\n", encoding="utf-8")
28
29.39
96
13
245
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_af5dafcff8fda5a5_a2ece099", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 3, "line_end": 3, "column_start": 1, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpr7mo7ysm/af5dafcff8fda5a5.py", "start": {"line": 3, "col": 1, "offset": 54}, "end": {"line": 3, "col": 28, "offset": 81}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-inner-function_af5dafcff8fda5a5_269ec7a7", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-inner-function", "finding_type": "maintainability", "severity": "high", "confidence": "medium", "message": "function `get_index` is defined inside a function but never used", "remediation": "", "location": {"file_path": "unknown", "line_start": 15, "line_end": 16, "column_start": 5, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-inner-function", "path": "/tmp/tmpr7mo7ysm/af5dafcff8fda5a5.py", "start": {"line": 15, "col": 5, "offset": 418}, "end": {"line": 16, "col": 32, "offset": 467}, "extra": {"message": "function `get_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.lang.best-practice.unspecified-open-encoding_af5dafcff8fda5a5_72bcf57e", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 26, "line_end": 26, "column_start": 10, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/af5dafcff8fda5a5.py", "start": {"line": 26, "col": 10, "offset": 750}, "end": {"line": 26, "col": 35, "offset": 775}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-611" ]
[ "rules.python.lang.security.use-defused-xml" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 3 ]
[ 3 ]
[ 1 ]
[ 28 ]
[ "A04:2017 - XML External Entities (XXE)" ]
[ "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service." ]
[ 7.5 ]
[ "LOW" ]
[ "MEDIUM" ]
process_sumo_data.py
/process_data/process_sumo_data.py
TwelveYC/road-network-modeling
MIT
2024-11-18T20:58:30.561276+00:00
1,622,726,388,000
6c9776da0c9f20ac02d892e93d0fcded5634db47
3
{ "blob_id": "6c9776da0c9f20ac02d892e93d0fcded5634db47", "branch_name": "refs/heads/master", "committer_date": 1622726388000, "content_id": "9df1a1e56595dbc2943178e129227c8fd3ef776a", "detected_licenses": [ "MIT" ], "directory_id": "43e87cb1946dddf5fd53f848192fe8c02d0f15bd", "extension": "py", "filename": "dataset.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": 11342, "license": "MIT", "license_type": "permissive", "path": "/e3d/segpose/dataset.py", "provenance": "stack-edu-0054.json.gz:576291", "repo_name": "tlwzzy/e3d", "revision_date": 1622726388000, "revision_id": "2efd01167350c29423babb6233907fa54156268f", "snapshot_id": "001384516c2ebca42a86392a31524f191597ea84", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tlwzzy/e3d/2efd01167350c29423babb6233907fa54156268f/e3d/segpose/dataset.py", "visit_date": "2023-05-14T18:29:35.245146" }
2.65625
stackv2
import os import random from collections import OrderedDict import cv2 import numpy as np import pytorch3d.transforms.rotation_conversions as rc import torch from PIL import Image from pytorch3d.renderer.cameras import get_world_to_view_transform from pytorch3d.transforms import Transform3d, Rotate from utils.params import Params from torch.utils.data import (BatchSampler, ConcatDataset, Dataset, Sampler, SubsetRandomSampler) from utils.manager import RenderManager import json class ConcatDataSampler(Sampler): def __init__( self, dataset: ConcatDataset, batch_size: int = 0, shuffle: bool = True, drop_last: bool = True, ): """A Custom sampler that does the very simple yet incredibly unthought of following: -Takes in a set of datasets in the form of ConcatDataset -Creates a batched random sampler FOR EACH dataset -returns batches from each INDIVIDUAL dataset during iteration -Shuffle: True if you want to sample the shufflers randomly """ self.dataset = dataset self.batch_size = batch_size self.shuffle = shuffle self.drop_last = drop_last self.samplers: list = [] self.generate_new_samplers() def generate_new_samplers(self): prev_end = 0 for num, dset in enumerate(self.dataset.datasets): end = prev_end + len(dset) sampler = iter( BatchSampler( SubsetRandomSampler(list(range(prev_end, end))), self.batch_size, self.drop_last, ) ) prev_end = end self.samplers.append(sampler) self.cum_size = end self.curr_sampler = 0 def fetch_batch(self) -> list: batch_idx = next(self.samplers[self.curr_sampler]) # batch_idx *= (self.curr_sampler + 1) return batch_idx def __iter__(self): retries = 0 while retries < len(self.samplers): if self.shuffle: self.curr_sampler = random.choice(range(len(self.samplers))) try: # Fetch a batch of indices yield self.fetch_batch() retries = 0 except StopIteration: self.curr_sampler += 1 retries += 1 # We've reached the end of the epoch - generate a new set of samplers self.generate_new_samplers() def __len__(self): return self.cum_size // self.batch_size class EvMaskPoseDataset(Dataset): def __init__(self, dir_num: int, params, transforms: list = []): self.img_size = params.img_size self.transforms = transforms try: self.render_manager = RenderManager.from_directory( dir_num=dir_num, render_folder=params.train_dir ) self.render_manager.rectify_paths(base_folder=params.train_dir) except: self.render_manager = None if self.render_manager is not None: self.poses = self.preprocess_poses(self.render_manager._trajectory) @classmethod def preprocess_poses(cls, poses: tuple): """Generates (N, 6) vector of absolute poses Args: Tuple of batched rotations (N, 3, 3) and translations (N, 3) in Pytorch3d view-to-world coordinates. usually returned from a call to RenderManager._trajectory More information about Pytorch3D's coordinate system: https://github.com/facebookresearch/pytorch3d/blob/master/docs/notes/cameras.md 1. Computes rotation and translation matrices in view-to-world coordinates. 2. Generates unit quaternion from R and computes log q repr 3. Normalizes translation according to mean and stdev Returns: (N, 6) vector: [t1, t2, t3, logq1, logq2, logq3] """ R, T = poses cam_wvt = get_world_to_view_transform(R=R, T=T) pose_transform = cam_wvt.inverse().get_matrix() T = pose_transform[:, 3, :3] R = pose_transform[:, :3, :3] # Compute pose stats std_R, mean_R = torch.std_mean(R) std_T, mean_T = torch.std_mean(T) q = rc.matrix_to_quaternion(R) # q /= torch.norm(q) # q *= torch.sign(q[0]) # hemisphere constraint # logq = qlog(q) T -= mean_T T /= std_T return torch.cat((T, q), dim=1) @classmethod def preprocess_images(self, img: Image, img_size) -> np.ndarray: """Resize and normalize the images to range 0, 1 """ img = img.resize(img_size) img_np = np.array(img) if len(img_np.shape) == 2: img_np = np.expand_dims(img_np, axis=2) # HWC to CHW img_trans = img_np.transpose((2, 0, 1)) if img_trans.max() > 1: img_trans = img_trans / 255 return img_trans def __len__(self): return len(self.render_manager) def add_noise_to_frame(self, frame, noise_std=0.1, noise_fraction=0.1): """Gaussian noise + hot pixels """ size = frame.size noise = noise_std * np.random.randn(*size) * 255 if noise_fraction < 1.0: noise[np.random.rand(*size) >= noise_fraction] = 0 return Image.fromarray((frame + noise).astype('uint8')).convert('L') def __getitem__(self, index: int): mask = self.render_manager.get_image("silhouette", index) event_frame = self.render_manager.get_event_frame(index) event_frame = self.add_noise_to_frame(event_frame) R, T = self.render_manager.get_trajectory_point(index) tq = self.poses[index: index + 1] assert mask.size == event_frame.size, "Mask and event frame must be same size" mask = torch.from_numpy(self.preprocess_images(mask, self.img_size)).type( torch.FloatTensor ) event_frame = torch.from_numpy( self.preprocess_images(event_frame, self.img_size) ).type(torch.FloatTensor) return event_frame, mask, R, T, tq class EvimoDataset(Dataset): """Dataset to manage Evimo Data""" def __init__(self, path: str, obj_id="1", is_train=True, slice_name=''): self.new_camera = None self.map1 = None self.map2 = None self.K = None self.discoef = None self.obj_id = obj_id self.slices_path = os.path.join(path, slice_name) self.frames_path = os.path.join(self.slices_path, 'slices') if not os.path.exists(self.slices_path) or not os.path.exists(self.frames_path): raise ValueError(f'Unavailable data in {self.slices_path}') if is_train: dataset_txt = eval(open(os.path.join(self.slices_path, "meta_train.txt")).read()) else: dataset_txt = eval(open(os.path.join(self.slices_path, "meta_test.txt")).read()) self.calib = dataset_txt["meta"] self.frames_dict = dataset_txt["frames"] self.set_undistorted_camera() @classmethod def preprocess_images(cls, img: np.ndarray) -> torch.Tensor: """Normalize and convert to torch""" if img.dtype == np.uint16: img = img.astype(np.uint8) if img.max() > 1: img = img / 255 if len(img.shape) == 2: img = np.expand_dims(img, axis=2) torch_img = torch.from_numpy(img) torch_img = torch_img.permute(2, 0, 1).float() return torch_img def set_undistorted_camera(self): # evimo data is fisheye camera K = np.zeros([3, 3]) K[0, 0] = self.calib['fy'] K[0, 2] = self.calib['cy'] K[1, 1] = self.calib['fx'] K[1, 2] = self.calib['cx'] K[2, 2] = 1.0 # for fisheye # self.discoef = np.array([self.calib['k1'], # self.calib['k2'], self.calib['k3'], self.calib['k4']]) # self.new_camera = cv2.fisheye.estimateNewCameraMatrixForUndistortRectify( # K, self.discoef, (w, h), R=None, new_size=(w, h)) # self.map1, self.map2 = cv2.fisheye.initUndistortRectifyMap( # K, self.discoef, R=np.eye(3), P=self.new_camera, size=(w, h), m1type=cv2.CV_32FC1) w, h = self.calib['res_y'], self.calib['res_x'] self.K = K # for rodtan undistortion alpha = 0.0 self.discoef = np.array([self.calib['k1'], self.calib['k2'], 0.0, 0.0, self.calib['k3']]) self.new_camera, _ = cv2.getOptimalNewCameraMatrix(K, self.discoef, (w, h), alpha, (w, h)) self.map1, self.map2 = cv2.initUndistortRectifyMap(K, self.discoef, np.eye(3), self.new_camera, (w, h), cv2.CV_32FC1) @classmethod def evimo_to_pytorch3d_xyz(self, p: dict): x_pt3d = float(p["t"]["y"]) y_pt3d = float(p["t"]["x"]) z_pt3d = -float(p["t"]["z"]) t = torch.Tensor([x_pt3d, y_pt3d, z_pt3d]).unsqueeze(0) return t @classmethod def evimo_to_pytorch3d_Rotation(self, p: dict): pos_q = torch.Tensor([float(e) for e in p['q'].values()]) pos_R = rc.quaternion_to_matrix(pos_q) pos_R = pos_R.transpose(1, 0) R = torch.Tensor(np.zeros((3, 3), dtype=float)) R[0, 0], R[0, 1], R[0, 2] = pos_R[1, 1], pos_R[1, 0], -pos_R[1, 2] R[1, 0], R[1, 1], R[1, 2] = pos_R[0, 1], pos_R[0, 0], -pos_R[0, 2] R[2, 0], R[2, 1], R[2, 2] = -pos_R[2, 1], -pos_R[2, 0], pos_R[2, 2] return R def prepare_pose(self, p: dict) -> Transform3d: # transform evimo coordinate system to pytorch3d coordinate system pos_t = self.evimo_to_pytorch3d_xyz(p) pos_R = self.evimo_to_pytorch3d_Rotation(p) R_tmp = Rotate(pos_R) w2v_transform = R_tmp.translate(pos_t) return Transform3d(matrix=w2v_transform.get_matrix()) def get_new_camera(self): return self.new_camera def __len__(self): return len(self.frames_dict) def __getitem__(self, idx: int): # Get Event Frame and mask event_path = os.path.join(self.frames_path, self.frames_dict[idx]["event_frame"]) event_frame = cv2.imread(event_path, cv2.IMREAD_UNCHANGED) event_frame = cv2.remap(event_frame, self.map1, self.map2, cv2.INTER_LINEAR) mask_path = os.path.join(self.frames_path, self.frames_dict[idx]["mask_frame"]) mask = cv2.imread(mask_path, cv2.IMREAD_UNCHANGED) mask = cv2.remap(mask, self.map1, self.map2, cv2.INTER_LINEAR) # mask = mask[:, :, 2] mask[mask > 1] = 1 event_frame = self.preprocess_images(event_frame) mask = self.preprocess_images(mask) # Cam Pose and Object Pose curr_frame = self.frames_dict[idx] obj_pos = self.prepare_pose(curr_frame[self.obj_id]["pos"]) o2c_mat = obj_pos.get_matrix() R = o2c_mat[:, :3, :3] t = o2c_mat[:, 3, :3] return event_frame, mask, R, t def test_sampler(): dt1 = EvMaskPoseDataset(1, Params()) dt2 = EvMaskPoseDataset(2, Params()) dt3 = EvMaskPoseDataset(3, Params()) dt4 = EvMaskPoseDataset(4, Params()) cdt = ConcatDataset([dt1, dt2, dt3, dt4]) custom_sampler = ConcatDataSampler(cdt, 4, True) assert len(custom_sampler) == len(cdt) // 4 for n in custom_sampler: assert n is not None
321
34.33
170
20
2,997
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_44c4fb4e32203af4_c3ec49cf", "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": 198, "line_end": 198, "column_start": 27, "column_end": 94, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpr7mo7ysm/44c4fb4e32203af4.py", "start": {"line": 198, "col": 27, "offset": 6765}, "end": {"line": 198, "col": 94, "offset": 6832}, "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_44c4fb4e32203af4_28858bf3", "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": 198, "line_end": 198, "column_start": 32, "column_end": 86, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/44c4fb4e32203af4.py", "start": {"line": 198, "col": 32, "offset": 6770}, "end": {"line": 198, "col": 86, "offset": 6824}, "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_44c4fb4e32203af4_e969fd75", "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": 200, "line_end": 200, "column_start": 27, "column_end": 93, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpr7mo7ysm/44c4fb4e32203af4.py", "start": {"line": 200, "col": 27, "offset": 6873}, "end": {"line": 200, "col": 93, "offset": 6939}, "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_44c4fb4e32203af4_1b2330b0", "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": 200, "line_end": 200, "column_start": 32, "column_end": 85, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/44c4fb4e32203af4.py", "start": {"line": 200, "col": 32, "offset": 6878}, "end": {"line": 200, "col": 85, "offset": 6931}, "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-95", "CWE-95" ]
[ "rules.python.lang.security.audit.eval-detected", "rules.python.lang.security.audit.eval-detected" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 198, 200 ]
[ 198, 200 ]
[ 27, 27 ]
[ 94, 93 ]
[ "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" ]
dataset.py
/e3d/segpose/dataset.py
tlwzzy/e3d
MIT
2024-11-18T20:58:37.837787+00:00
1,494,244,668,000
a5bcac60d86198e9f0c13becbfa5e4f8f422ec8f
3
{ "blob_id": "a5bcac60d86198e9f0c13becbfa5e4f8f422ec8f", "branch_name": "refs/heads/master", "committer_date": 1494244668000, "content_id": "75df9794d2d61ebafee4b3f95037bb1175bd1a69", "detected_licenses": [ "MIT" ], "directory_id": "4461a16d85572e9399670844ba15cf4f314ae6d4", "extension": "py", "filename": "Start.py", "fork_events_count": 0, "gha_created_at": 1516180902000, "gha_event_created_at": 1516180902000, "gha_language": null, "gha_license_id": null, "github_id": 117813585, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8736, "license": "MIT", "license_type": "permissive", "path": "/Start.py", "provenance": "stack-edu-0054.json.gz:576368", "repo_name": "Autohome2/Eagle2Kicad", "revision_date": 1494244668000, "revision_id": "1047f8a6610ef753af3fa1a47c0deba2cb99c907", "snapshot_id": "07a987cc7dd750794a988dc11121064d289dd7ba", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Autohome2/Eagle2Kicad/1047f8a6610ef753af3fa1a47c0deba2cb99c907/Start.py", "visit_date": "2021-05-11T18:01:27.851642" }
2.765625
stackv2
import logging import traceback import os.path from datetime import datetime from argparse import ArgumentParser from Board.Board import Board from Library.Library import Library # from Schematic.Schematic import Schematic from xml.etree.ElementTree import ElementTree from xml.etree.ElementTree import XMLParser # noinspection PyUnresolvedReferences def import_tk(): global Tk, Frame, Label, Button, RIDGE, BOTH, X, askopenfilename, asksaveasfilename, showinfo, showerror from tkinter import Tk, Frame, Label, Button, RIDGE, BOTH, X from tkinter.filedialog import askopenfilename from tkinter.filedialog import asksaveasfilename from tkinter.messagebox import showinfo, showerror def startGui(): try: import_tk() except: logging.error("Error Starting GUI. Could Not Find Tkinter module" + "Please install the Python Tkinter module") return root = Tk() root.wm_title("Eagle V6 to KiCad Converter") root.wm_minsize(400, 200) frame = Frame(root, relief=RIDGE, bg="BLUE", borderwidth=2) frame.pack(fill=BOTH, expand=1) label = Label(frame, font=20, bg="BLUE", text="What Would You Like to Do:") label.pack(fill=X, expand=1) butBrd = Button(frame, text="Convert Board", command=convertBoardGUI) butBrd.pack(fill=X, expand=1) butLib = Button(frame, text="Convert Library", command=convertLibGUI) butLib.pack(fill=X, expand=1) butSch = Button(frame, text="Convert Schematic", command=convertSchGUI) butSch.pack(fill=X, expand=1) label = Label(frame, bg="BLUE", text="www.github.com/Trump211") label.pack(fill=X, expand=1) root.mainloop() def startCmdLine(args): if args.Schem is not None: for sch in args.Schem: convertSch(sch[0], sch[1]) if args.Board is not None: for brd in args.Board: convertBoard(brd[0], brd[1]) if args.Library is not None: for lib in args.Library: convertLib(lib[0], lib[1], lib[2]) def getRootNode(fileName): parser = XMLParser(encoding="UTF-8") node = ElementTree() node.parse(fileName, parser) node = node.getroot() return node def convertBoardGUI(): fileName = askopenfilename(title="Board Input", filetypes=[('Eagle V6 Board', '.brd'), ('all files', '.*')], defaultextension='.brd') if not fileName: return outFileName = asksaveasfilename(title="Board Output", filetypes=[('KiCad Board', '.brd'), ('all files', '.*')], defaultextension='.brd', initialfile=os.path.splitext(fileName)[0] + "KiCad") if not outFileName: return val = convertBoard(fileName, outFileName) if val[0]: showinfo("Conversion Complete", val[1]) else: showerror("Error", val[1]) def convertBoard(fileName, outFileName): logging.info("*******************************************") logging.info("Converting: " + fileName) logging.info("Outputing: " + outFileName + "\n") try: node = getRootNode(fileName) brd = Board(node) open(outFileName, 'w').close() outFile = open(outFileName, "a") brd.write(outFile) outFile.close() except BaseException as e: logging.error("Conversion Failed") logging.error(traceback.format_exc()) logging.info("*******************************************\n\n") return False, "Error Converting Board \n" + str(e) + "\nSee Log.txt for more info" logging.info("Conversion Successfull") logging.info("*******************************************\n\n") return True, "The Board Has Finished Converting" def convertLibGUI(): fileName = askopenfilename(title="Input Library", filetypes=[('Eagle V6 Library', '.lbr'), ('all files', '.*')], defaultextension='.lbr') if not fileName: return modFileName = asksaveasfilename(title="Module Output Filename", filetypes=[('KiCad Module', '.mod'), ('all files', '.*')], defaultextension='.mod', initialfile=os.path.splitext(fileName)[0]) if not modFileName: return symFileName = asksaveasfilename(title="Symbol Output Filename", filetypes=[('KiCad Symbol', '.lib'), ('all files', '.*')], defaultextension='.lib', initialfile=os.path.splitext(fileName)[0]) if not symFileName: return val = convertLib(fileName, symFileName, modFileName) if val[0]: showinfo("Conversion Complete", val[1]) else: showerror("Error", val[1]) def convertLib(fileName, symFileName, modFileName): logging.info("*******************************************") logging.info("Converting Lib: " + fileName) logging.info("Module Output: " + modFileName) logging.info("Symbol Output: " + symFileName) name = fileName.replace("/", "\\") name = name.split("\\")[-1] name = name.split(".")[0] logging.info("Lib Name: " + name + "\n") try: node = getRootNode(fileName) node = node.find("drawing").find("library") lib = Library(node, name) open(modFileName, 'w').close() open(symFileName, 'w').close() modFile = open(modFileName, "a") symFile = open(symFileName, "a") lib.writeLibrary(modFile, symFile) modFile.close() symFile.close() except BaseException as e: logging.error("Error Converting Library: '" + name + "'") logging.error(traceback.format_exc()) logging.info("*******************************************\n\n") return False, "Error Converting Library \n" + str(e) + "\nSee Log.txt for more info" logging.info("Conversion Successfull") logging.info("*******************************************\n\n") return True, "Conversion of Library '" + name + "' Complete" def convertSchGUI(): val = convertSch("N/A", "N/A") if val[0]: showinfo("Conversion Complete", val[1]) else: showerror("Error", val[1]) def convertSch(schFile, outFile): logging.info("*******************************************") logging.info("Converting Schem: " + schFile) logging.info("Outputing: " + outFile) logging.error("Error Converting " + schFile + ":") logging.error("Schematic Conversion not yet Supported") logging.info("*******************************************\n\n") return False, "Converting Schematics is not yet supported" def parseargs(): # Setup argument parser parser = ArgumentParser(prog="Eagle2KiCad") parser.add_argument("-l", "-L", "--Library", dest="Library", nargs=3, metavar=("inFile", "symFile", "modFile"), help="Convert an Eagle Library", action="append", type=str) parser.add_argument("-b", "-B", "--Board", dest="Board", nargs=2, metavar=("inFile", "brdFile"), help="Convert an Eagle Board", action="append", type=str) parser.add_argument("-s", "-S", "--Schematic", dest="Schem", nargs=2, metavar=("inFile", "schFile"), help="Convert an Eagle Schematic", action="append", type=str) parser.add_argument('-v', '--verbosity', dest="Verbosity", choices=(0, 1), default=0, type=int, help="Verbosity Level ") # Process arguments return parser.parse_args() def setupLogging(verbosity, use_console): lvl = (logging.INFO, logging.DEBUG)[verbosity] logging.getLogger().setLevel(0) fh = logging.FileHandler("Log.txt") fh.setLevel(lvl) logging.getLogger().addHandler(fh) ch = logging.StreamHandler() ch.setLevel(logging.WARNING) # always show Warnings and Errors in the Console if use_console: ch.setLevel(lvl) # Use user preference if in non-gui mode logging.getLogger().addHandler(ch) logging.info("###############################################################################") logging.info("#Session: " + datetime.now().strftime("%Y-%m-%d %H:%M:%S")) logging.info("###############################################################################") logging.log(lvl, "Logging at Level: " + logging.getLevelName(lvl) + "\n\n") def shutdownLogging(): for handler in logging.root.handlers[:]: handler.close() logging.root.removeHandler(handler) def main(): args = parseargs() use_console = not (args.Board is None and args.Library is None and args.Schem is None) setupLogging(args.Verbosity, use_console) if use_console: startCmdLine(args) else: startGui() shutdownLogging() if __name__ == "__main__": main()
262
32.34
119
14
2,022
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_9465b6f99b3fc6f9_9ffc0185", "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": 46, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpr7mo7ysm/9465b6f99b3fc6f9.py", "start": {"line": 11, "col": 1, "offset": 225}, "end": {"line": 11, "col": 46, "offset": 270}, "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_9465b6f99b3fc6f9_189bd128", "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": 1, "column_end": 44, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpr7mo7ysm/9465b6f99b3fc6f9.py", "start": {"line": 12, "col": 1, "offset": 271}, "end": {"line": 12, "col": 44, "offset": 314}, "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_9465b6f99b3fc6f9_feef7138", "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": 9, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/9465b6f99b3fc6f9.py", "start": {"line": 101, "col": 9, "offset": 3114}, "end": {"line": 101, "col": 31, "offset": 3136}, "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_9465b6f99b3fc6f9_f6bf8f54", "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": 102, "line_end": 102, "column_start": 19, "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/tmpr7mo7ysm/9465b6f99b3fc6f9.py", "start": {"line": 102, "col": 19, "offset": 3163}, "end": {"line": 102, "col": 41, "offset": 3185}, "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_9465b6f99b3fc6f9_65f2360e", "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": 157, "line_end": 157, "column_start": 9, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/9465b6f99b3fc6f9.py", "start": {"line": 157, "col": 9, "offset": 5231}, "end": {"line": 157, "col": 31, "offset": 5253}, "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_9465b6f99b3fc6f9_4ab1a614", "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": 158, "line_end": 158, "column_start": 9, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/9465b6f99b3fc6f9.py", "start": {"line": 158, "col": 9, "offset": 5270}, "end": {"line": 158, "col": 31, "offset": 5292}, "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_9465b6f99b3fc6f9_5d7073e0", "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": 160, "line_end": 160, "column_start": 19, "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/tmpr7mo7ysm/9465b6f99b3fc6f9.py", "start": {"line": 160, "col": 19, "offset": 5320}, "end": {"line": 160, "col": 41, "offset": 5342}, "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_9465b6f99b3fc6f9_6262b94f", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 161, "line_end": 161, "column_start": 19, "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/tmpr7mo7ysm/9465b6f99b3fc6f9.py", "start": {"line": 161, "col": 19, "offset": 5361}, "end": {"line": 161, "col": 41, "offset": 5383}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
8
true
[ "CWE-611", "CWE-611" ]
[ "rules.python.lang.security.use-defused-xml", "rules.python.lang.security.use-defused-xml" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "HIGH", "HIGH" ]
[ 11, 12 ]
[ 11, 12 ]
[ 1, 1 ]
[ 46, 44 ]
[ "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" ]
Start.py
/Start.py
Autohome2/Eagle2Kicad
MIT
2024-11-18T20:58:41.719916+00:00
1,601,719,836,000
5d2dc019eea7061ab4ea9a75fa2bbfc65dd2ff51
3
{ "blob_id": "5d2dc019eea7061ab4ea9a75fa2bbfc65dd2ff51", "branch_name": "refs/heads/master", "committer_date": 1601719836000, "content_id": "0bbb8070555dd20817193137e8b879d492c0b3a7", "detected_licenses": [ "Apache-2.0" ], "directory_id": "f278811c8718ee20de20754854120334dc5c09f0", "extension": "py", "filename": "h2dbgtfs.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 260404750, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5676, "license": "Apache-2.0", "license_type": "permissive", "path": "/h2dbgtfs.py", "provenance": "stack-edu-0054.json.gz:576411", "repo_name": "niyalist/GTFSDiff", "revision_date": 1601719836000, "revision_id": "21c6fc2372dbecc765f30548d5f6bafc1c1e9084", "snapshot_id": "1ac0aeda2f000e453f9a051849d002822defc39d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/niyalist/GTFSDiff/21c6fc2372dbecc765f30548d5f6bafc1c1e9084/h2dbgtfs.py", "visit_date": "2022-12-25T20:22:21.677284" }
2.71875
stackv2
""" 本ライブラリ実行前に、h2dbを以下のオプションで起動する java -cp h2-1.4.200.jar org.h2.tools.Server -webAllowOthers -tcpAllowOthers -pgAllowOthers -baseDir ../data/ -ifNotExists -tcpAllowOthers 外部からの接続を許す -pgAllowOthers postgresql互換形式 -baseDir データが保存される先のDB DB名を mem:hoge とすることで、インメモリDBとして動くので何も保存されない -ifNotExists 外部接続時にテーブル作成を許可する """ import psycopg2 #import copy import psycopg2.extras from pathlib import Path from datetime import datetime, date, timedelta db_connection_info = {} #GTFSデータが対応している期間を取得する def get_data_duration(cursor): sql = """ select min(start_date) as min_start_date, max(end_date) as max_end_date from calendar """ cursor.execute(sql) results = cursor.fetchall() for row in results: min_start_date = row['min_start_date'] max_end_date = row['max_end_date'] sql = """ select feed_start_date, feed_end_date from feed_info """ cursor.execute(sql) results = cursor.fetchall() for row in results: feed_start_date = row['feed_start_date'] feed_end_date = row['feed_end_date'] # print("{}, {}, {}, {}".format(min_start_date, max_end_date, feed_start_date, feed_end_date)) # feed_info の start_date と calendar の start_date の遅い方を start_date に # feed_info の end_date と calendar の end_date の早いを end_date に start_date = feed_start_date if feed_start_date >= min_start_date else min_start_date end_date = feed_end_date if feed_end_date <= max_end_date else max_end_date return { "start_date": datetime.strptime(start_date, "%Y%m%d").date(), "end_date" : datetime.strptime(end_date, "%Y%m%d").date() } #順序あり辞書(dictionary)として、key: date, value 空のlist のオブジェクトを返す def expand_date(from_date, to_date): next_date = from_date return_dict = {} while next_date <= to_date: return_dict[next_date] = set() next_date = next_date + timedelta(days=1) #1日加える return return_dict # calendar.txt を読み、日付とservice_idのsetというデータ構造を作る def expand_service_id_in_calendar(date_dict, cursor): sql = "select * from calendar" date_map = {0: "monday",1:"tuesday",2:"wednesday",3:"thursday",4:"friday",5:"saturday",6:"sunday"} cursor.execute(sql) results = cursor.fetchall() for row in results: service_id = row["service_id"] start_date = datetime.strptime(row["start_date"], "%Y%m%d").date() end_date = datetime.strptime(row["end_date"], "%Y%m%d").date() for date, service_set in date_dict.items(): state = row[date_map[date.weekday()]] if state == "1" and date >= start_date and date <= end_date: service_set.add(service_id) def process_exception_in_calendar_dates(date_dict, cursor): sql = "select * from calendar_dates order by date, exception_type" cursor.execute(sql) results = cursor.fetchall() for row in results: try: date_info = date_dict[datetime.strptime(row["date"], "%Y%m%d").date()] if row["exception_type"] == "1": date_info.add(row["service_id"]) elif row["exception_type"] == "2": date_info.remove(row["service_id"]) except KeyError: print("{} in calendar_date is out of duration.".format(row)) def create_universal_calendar(date_dict, cursor): sql = """ create table universal_calendar( service_id char(255), date date ) """ cursor.execute(sql) insert_sql = "insert into universal_calendar (service_id, date) values (%(service_id)s, %(date)s)" for date, service_array in date_dict.items(): for service_id in service_array: # print("{}: {}".format(date, service_id)) cursor.execute(insert_sql, {"service_id": service_id, "date":date}) def load_gtfs(dbname, base_dir): #postgreSQLに接続(接続情報は環境変数、PG_XXX) connection = psycopg2.connect("dbname=mem:{} user=sa password='sa' host=localhost port=5435".format(dbname)) #クライアントプログラムのエンコードを設定(DBの文字コードから自動変換してくれる) connection.set_client_encoding('utf-8') #select結果を辞書形式で取得するように設定 connection.cursor_factory=psycopg2.extras.DictCursor #カーソルの取得 cursor = connection.cursor() gtfs_files = ['agency','calendar','calendar_dates','feed_info','routes','shapes','stop_times','stops','translations','trips'] for file in gtfs_files: gtfs_file = Path(base_dir,file + ".txt") sql = "CREATE TABLE {} AS SELECT * FROM CSVREAD('{}')".format(file, str(gtfs_file)) cursor.execute(sql) duration = get_data_duration(cursor) date_dict = expand_date(duration['start_date'], duration['end_date']) expand_service_id_in_calendar(date_dict, cursor) process_exception_in_calendar_dates(date_dict, cursor) create_universal_calendar(date_dict, cursor) db_connection_info[dbname] = {'connection': connection, 'cursor': cursor} return {'cursor':cursor, 'start': duration['start_date'], 'end':duration['end_date']} #切断 def close_gtfs(dbname): info = db_connection_info.pop(dbname) #delete info['cursor'].close() info['connection'].close()
144
34.88
129
17
1,373
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_ba954e943dbb8a8a_2ffd6fa3", "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": 129, "line_end": 129, "column_start": 9, "column_end": 28, "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/tmpr7mo7ysm/ba954e943dbb8a8a.py", "start": {"line": 129, "col": 9, "offset": 5069}, "end": {"line": 129, "col": 28, "offset": 5088}, "extra": {"message": "Detected possible formatted SQL query. Use parameterized queries instead.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "references": ["https://stackoverflow.com/questions/775296/mysql-parameterized-queries"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.sqli.psycopg-sqli_ba954e943dbb8a8a_1cd5ebc0", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.sqli.psycopg-sqli", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected string concatenation with a non-literal variable in a psycopg2 Python SQL statement. This could lead to SQL injection if the variable is user-controlled and not properly sanitized. In order to prevent SQL injection, use parameterized queries or prepared statements instead. You can use prepared statements by creating a 'sql.SQL' string. You can also use the pyformat binding style to create parameterized queries. For example: 'cur.execute(SELECT * FROM table WHERE name=%s, user_input)'", "remediation": "", "location": {"file_path": "unknown", "line_start": 129, "line_end": 129, "column_start": 9, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://www.psycopg.org/docs/sql.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.sqli.psycopg-sqli", "path": "/tmp/tmpr7mo7ysm/ba954e943dbb8a8a.py", "start": {"line": 129, "col": 9, "offset": 5069}, "end": {"line": 129, "col": 28, "offset": 5088}, "extra": {"message": "Detected string concatenation with a non-literal variable in a psycopg2 Python SQL statement. This could lead to SQL injection if the variable is user-controlled and not properly sanitized. In order to prevent SQL injection, use parameterized queries or prepared statements instead. You can use prepared statements by creating a 'sql.SQL' string. You can also use the pyformat binding style to create parameterized queries. For example: 'cur.execute(SELECT * FROM table WHERE name=%s, user_input)'", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "references": ["https://www.psycopg.org/docs/sql.html"], "category": "security", "technology": ["psycopg"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_ba954e943dbb8a8a_4e725dc4", "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": 129, "line_end": 129, "column_start": 9, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpr7mo7ysm/ba954e943dbb8a8a.py", "start": {"line": 129, "col": 9, "offset": 5069}, "end": {"line": 129, "col": 28, "offset": 5088}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-89", "CWE-89", "CWE-89" ]
[ "rules.python.lang.security.audit.formatted-sql-query", "rules.python.lang.security.audit.sqli.psycopg-sqli", "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query" ]
[ "security", "security", "security" ]
[ "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "HIGH" ]
[ 129, 129, 129 ]
[ 129, 129, 129 ]
[ 9, 9, 9 ]
[ 28, 28, 28 ]
[ "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Detected possible formatted SQL query. Use parameterized queries instead.", "Detected string concatenation with a non-literal variable in a psycopg2 Python SQL statement. This could lead to SQL injection if the variable is user-controlled and not properly sanitized. In order to prevent SQL injection, use paramet...
[ 5, 5, 7.5 ]
[ "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH" ]
h2dbgtfs.py
/h2dbgtfs.py
niyalist/GTFSDiff
Apache-2.0
2024-11-18T20:58:42.543550+00:00
1,593,831,890,000
3cda5108dccda53a5124c3463fa00c6f2ff3d582
3
{ "blob_id": "3cda5108dccda53a5124c3463fa00c6f2ff3d582", "branch_name": "refs/heads/master", "committer_date": 1593831890000, "content_id": "b89e0f426bd0e934d448dfbbb71ec87eb77fc932", "detected_licenses": [ "MIT" ], "directory_id": "25ac6df0589c6e1b79be79847061ba039c9e07fb", "extension": "py", "filename": "scientificCalculator.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 248876247, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10143, "license": "MIT", "license_type": "permissive", "path": "/scientificCalculator.py", "provenance": "stack-edu-0054.json.gz:576422", "repo_name": "PatrickAttankurugu/Scientific-Calculator", "revision_date": 1593831890000, "revision_id": "92902e364dbec33b9efdd4d443891120fcf68b98", "snapshot_id": "444d23dba8e4ab7cdc4850d7e18568a7dd91c523", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/PatrickAttankurugu/Scientific-Calculator/92902e364dbec33b9efdd4d443891120fcf68b98/scientificCalculator.py", "visit_date": "2021-04-09T23:10:16.434993" }
2.984375
stackv2
from tkinter import * from tkinter import messagebox from math import * root = Tk() root.title("Scientific Calculator") root.configure(background="powder blue") calc=Frame(root,bg="grey") calc.grid() equa = "" equation = StringVar() calculation = Entry(calc, textvariable = equation,fg="black",font=('arial',15,'bold'),bg="powder blue",bd=30,width=50,justify=LEFT) calculation.grid(row=0, columnspan=4,column=0,pady=1) def btnPress(num): global equa equa = equa + str(num) equation.set(equa) def EqualPress(): global equa x=calculation.get() if(equa==""): equa=equa+x try: total = str(eval(equa)) equation.set(total) if(float(total)==0): equa="" else: equa=total except: equation.set("Syntax Error") equa="" pass def ClearPress(): global equa equa = "" equation.set("") Button0 = Button(calc, text="0", command = lambda:btnPress(0),bd=4,width=6,height=1,bg="white",relief=SOLID) Button1 = Button(calc, text="1", command = lambda:btnPress(1), borderwidth=1,bd=4,width=6,height=1,bg="white",relief=SOLID) Button14 = Button(calc, text="(", command = lambda:btnPress("("), borderwidth=1,bd=4,width=6,height=1,bg="white",relief=SOLID) Button2 = Button(calc, text="2", command = lambda:btnPress(2), borderwidth=1,bd=4,width=6,height=1,bg="white",relief=SOLID) Button3 = Button(calc, text="3", command = lambda:btnPress(3), borderwidth=1,bd=4,width=6,height=1,bg="white",relief=SOLID) Button13 = Button(calc, text="sqrt", command = lambda:btnPress("sqrt("), borderwidth=1,bd=4,width=6,height=1,bg="powder blue", relief=SOLID) Button4 = Button(calc, text="4", command = lambda:btnPress(4), borderwidth=1,bd=4,width=6,height=1,bg="white",relief=SOLID) Button15 = Button(calc, text=")", command = lambda:btnPress(")"), borderwidth=1,bd=4,width=6,height=1,bg="white", relief=SOLID) Button5 = Button(calc, text="5", command = lambda:btnPress(5), borderwidth=1,bd=4,width=6,height=1,bg="white", relief=SOLID) Button6 = Button(calc, text="6", command = lambda:btnPress(6), borderwidth=1,bd=4,width=6,height=1,bg="white", relief=SOLID) Button7 = Button(calc, text="7", command = lambda:btnPress(7), borderwidth=1,bd=4,width=6,height=1,bg="white", relief=SOLID) Button16 = Button(calc, text=".", command = lambda:btnPress("."), borderwidth=1,bd=4,width=6,height=1,bg="white", relief=SOLID) Button8 = Button(calc, text="8", command = lambda:btnPress(8), borderwidth=1,bd=4,width=6,height=1,bg="white", relief=SOLID) Button9 = Button(calc, text="9", command = lambda:btnPress(9), borderwidth=1,bd=4,width=6,height=1,bg="white", relief=SOLID) Plus = Button(calc, text="+", command = lambda:btnPress("+"), borderwidth=1,bd=4,width=6,height=1,bg="powder blue", relief=SOLID) Minus = Button(calc, text="-", command = lambda:btnPress("-"), borderwidth=1,bd=4,width=6,height=1,bg="powder blue", relief=SOLID) Button18 = Button(calc, text="sin", command = lambda:btnPress("sin("), borderwidth=1,bd=4,width=6,height=1,bg="powder blue", relief=SOLID) Button22 = Button(calc, text="log", command = lambda:btnPress("log("), borderwidth=1,bd=4,width=6,height=1,bg="powder blue", relief=SOLID) Multiply = Button(calc, text="*", command = lambda:btnPress("*"), borderwidth=1,bd=4,width=6,height=1,bg="powder blue", relief=SOLID) Button19 = Button(calc, text="cos", command = lambda:btnPress("cos("), borderwidth=1,bd=4,width=6,height=1,bg="powder blue", relief=SOLID) Button23 = Button(calc, text="pi", command = lambda:btnPress("pi"), borderwidth=1,bd=4,width=6,height=1,bg="pink", relief=SOLID) Divide = Button(calc, text="/", command = lambda:btnPress("/"), borderwidth=1,bd=4,width=6,height=1,bg="pink", relief=SOLID) Button20 = Button(calc, text="factorial", command = lambda:btnPress("factorial("), borderwidth=1,bd=4,width=6,height=1,bg="pink", relief=SOLID) Equal = Button(calc, text="=", command = EqualPress, borderwidth=1,bd=4,width=6,height=1,bg="pink", relief=SOLID) Clear = Button(calc, text="MC", command = ClearPress, borderwidth=1,bd=4,width=6,height=1,bg="pink", relief=SOLID) Button17 = Button(calc, text="%", command = lambda:btnPress("%"), borderwidth=1,bd=4,width=6,height=1,bg="powder blue", relief=SOLID) Button25 = Button(calc, text="degrees", command = lambda:btnPress("degrees("), borderwidth=1,bd=4,width=6,height=1,bg="powder blue", relief=SOLID) Button26 = Button(calc, text="log", command = lambda:btnPress("log10("), borderwidth=1,bd=4,width=6,height=1,bg="powder blue", relief=SOLID) Button27 = Button(calc, text="log1p", command = lambda:btnPress("log1p("), borderwidth=1,bd=4,width=6,height=1,bg="powder blue", relief=SOLID) Button28 = Button(calc, text="radians", command = lambda:btnPress("radians("), borderwidth=1,bd=4,width=6,height=1,bg="powder blue", relief=SOLID) Button29 = Button(calc, text="sinh", command = lambda:btnPress("sinh("), borderwidth=1,bd=4,width=6,height=1,bg="powder blue", relief=SOLID) Button30 = Button(calc, text="cosh", command = lambda:btnPress("cosh("), borderwidth=1,bd=4,width=6,height=1,bg="powder blue", relief=SOLID) Button31 = Button(calc, text="tan", command = lambda:btnPress("tan("), borderwidth=1,bd=4,width=6,height=1,bg="powder blue", relief=SOLID) Button32 = Button(calc, text="tanh", command = lambda:btnPress("tanh("), borderwidth=1,bd=4,width=6,height=1,bg="powder blue", relief=SOLID) Button33 = Button(calc, text="E", command = lambda:btnPress("e"), borderwidth=1,bd=4,width=6,height=1,bg="pink", relief=SOLID) Button34 = Button(calc, text="atan", command = lambda:btnPress("atan("), borderwidth=1,bd=4,width=6,height=1,bg="powder blue", relief=SOLID) Button36 = Button(calc, text="exp", command = lambda:btnPress("exp("), borderwidth=1,bd=4,width=6,height=1,bg="pink", relief=SOLID) Button38 = Button(calc, text="asin", command = lambda:btnPress("asin("), borderwidth=1,bd=4,width=6,height=1,bg="powder blue", relief=SOLID) Button39 = Button(calc, text="acos", command = lambda:btnPress("acos("), borderwidth=1,bd=4,width=6,height=1,bg="powder blue", relief=SOLID) Button46 = Button(calc, text="ceil", command = lambda:btnPress("ceil("), borderwidth=1,bd=4,width=6,height=1,bg="pink", relief=SOLID) Button47 = Button(calc, text="floor", command = lambda:btnPress("floor("), borderwidth=1,bd=4,width=6,height=1,bg="pink", relief=SOLID) Button49 = Button(calc, text="abs", command = lambda:btnPress("abs("), borderwidth=1,bd=4,width=6,height=1,bg="powder blue", relief=SOLID) Button50 = Button(calc, text="int", command = lambda:btnPress("int("), borderwidth=1,bd=4,width=6,height=1,bg="pink", relief=SOLID) Button51 = Button(calc, text="float", command = lambda:btnPress("float("), borderwidth=1,bd=4,width=6,height=1,bg="pink", relief=SOLID) Button13.grid(row = 2, column = 0, padx=10, pady=10) Button28.grid(row = 2, column =1, padx=10, pady=10) Button25.grid(row = 2, column = 2, padx=10, pady=10) Button32.grid(row = 2, column = 3, padx=10, pady=10) Button26.grid(row = 3, column = 0, padx=10, pady=10) Button27.grid(row = 3, column = 1, padx=10, pady=10) Button29.grid(row = 3, column = 2, padx=10, pady=10) Button30.grid(row = 3, column = 3, padx=10, pady=10) Button31.grid(row = 4, column = 0, padx=10, pady=10) Button19.grid(row = 4, column = 1, padx=10, pady=10) Button18.grid(row = 4, column = 2, padx=10, pady=10) Button22.grid(row = 4, column = 3, padx=10, pady=10) Button1.grid(row = 5, column = 0, padx=10, pady=10) Button2.grid(row = 5, column = 1, padx=10, pady=10) Button3.grid(row = 5, column = 2, padx=10, pady=10) Plus.grid(row = 5, column = 3, padx=10, pady=10) Button4.grid(row = 6, column = 0, padx=10, pady=10) Button5.grid(row = 6, column = 1, padx=10, pady=10) Button6.grid(row = 6, column = 2, padx=10, pady=10) Minus.grid(row = 6, column = 3, padx=10, pady=10) Button7.grid(row = 7, column = 0, padx=10, pady=10) Button8.grid(row = 7, column = 1, padx=10, pady=10) Button9.grid(row = 7, column = 2, padx=10, pady=10) Multiply.grid(row = 7, column = 3, padx=10, pady=10) Button14.grid(row = 8, column = 0, padx=10, pady=10) Button15.grid(row = 8, column = 1, padx=10, pady=10) Button0.grid(row = 8, column = 2, padx=10, pady=10) Button17.grid(row = 8, column = 3, padx=10, pady=10) Clear.grid(row = 9, column = 0, padx=10, pady=10) Equal.grid(row=9, column=1, padx=10, pady=10) Button16.grid(row = 9, column = 2, padx=10, pady=10) Divide.grid(row = 9, column = 3, padx=10, pady=10) Button23.grid(row = 10, column = 0, padx=10, pady=10) Button50.grid(row = 10, column = 1, padx=10, pady=10) Button51.grid(row = 10, column = 2, padx=10, pady=10) Button20.grid(row = 10, column = 3, padx=10, pady=10) #Button44.grid(row = 10, column = 3, padx=10, pady=10) #Button38.grid(row = 10, column = 4, padx=10, pady=10) #Button39.grid(row = 10, column = 5, padx=10, pady=10) Button33.grid(row = 11, column = 0, padx=10, pady=10) Button46.grid(row = 11, column = 1, padx=10, pady=10) Button47.grid(row = 11, column = 2, padx=10, pady=10) Button36.grid(row = 11, column = 3, padx=10, pady=10) #Button42.grid(row = 11, column = 4, padx=10, pady=10) #Button43.grid(row = 11, column = 3, padx=10, pady=10) #Button48.grid(row = 10, column = 6, padx=10, pady=10) #Button49.grid(row = 10, column = 7, padx=10, pady=10) def exit(): root.quit() def scientific(): root.resizable(width=False,height=False) root.geometry("940x568+0+0") def standard(): root.resizable(width=False,height=False) root.geometry("466x568+0+0") menubar=Menu(calc) filemenu=Menu(menubar,tearoff=0) menubar.add_cascade(label="Manu",menu=filemenu) filemenu.add_command(label="standard",command=standard) filemenu.add_command(label="scientific",command=scientific) filemenu.add_separator() filemenu.add_command(label="exit",command=exit) Author=Label(root,text="Created by : Patrick Attankurugu",fg="black",font=('arial',10,'bold'),borderwidth=1,bd=4,width=30,height=2,bg="white",relief=SOLID) Author.grid(row=11,columnspan=8) root.config(menu=menubar) root.mainloop()
202
49.22
155
12
3,513
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_a25fec928307f954_02193afb", "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": 31, "line_end": 31, "column_start": 28, "column_end": 38, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 31, "col": 28, "offset": 669}, "end": {"line": 31, "col": 38, "offset": 679}, "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_a25fec928307f954_f5047888", "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": 46, "line_end": 46, "column_start": 51, "column_end": 62, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 46, "col": 51, "offset": 1108}, "end": {"line": 46, "col": 62, "offset": 1119}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_d7775973", "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": 47, "line_end": 47, "column_start": 51, "column_end": 62, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 47, "col": 51, "offset": 1217}, "end": {"line": 47, "col": 62, "offset": 1228}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_d57e9ba3", "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": 48, "line_end": 48, "column_start": 52, "column_end": 65, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 48, "col": 52, "offset": 1342}, "end": {"line": 48, "col": 65, "offset": 1355}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_d698cf54", "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": 49, "line_end": 49, "column_start": 51, "column_end": 62, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 49, "col": 51, "offset": 1468}, "end": {"line": 49, "col": 62, "offset": 1479}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_107119dc", "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": 50, "line_end": 50, "column_start": 51, "column_end": 62, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 50, "col": 51, "offset": 1592}, "end": {"line": 50, "col": 62, "offset": 1603}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_3d290bd8", "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": 51, "line_end": 51, "column_start": 55, "column_end": 72, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 51, "col": 55, "offset": 1720}, "end": {"line": 51, "col": 72, "offset": 1737}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_fe54c803", "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": 52, "line_end": 52, "column_start": 51, "column_end": 62, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 52, "col": 51, "offset": 1857}, "end": {"line": 52, "col": 62, "offset": 1868}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_80c8f676", "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": 53, "line_end": 53, "column_start": 52, "column_end": 65, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 53, "col": 52, "offset": 1982}, "end": {"line": 53, "col": 65, "offset": 1995}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_2f4b6a94", "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": 54, "line_end": 54, "column_start": 51, "column_end": 62, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 54, "col": 51, "offset": 2109}, "end": {"line": 54, "col": 62, "offset": 2120}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_bc012c0f", "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": 55, "line_end": 55, "column_start": 51, "column_end": 62, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 55, "col": 51, "offset": 2234}, "end": {"line": 55, "col": 62, "offset": 2245}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_17a0fc45", "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": 56, "line_end": 56, "column_start": 51, "column_end": 62, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 56, "col": 51, "offset": 2359}, "end": {"line": 56, "col": 62, "offset": 2370}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_8525228a", "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": 57, "line_end": 57, "column_start": 52, "column_end": 65, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 57, "col": 52, "offset": 2485}, "end": {"line": 57, "col": 65, "offset": 2498}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_ff4c678b", "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": 58, "line_end": 58, "column_start": 51, "column_end": 62, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 58, "col": 51, "offset": 2612}, "end": {"line": 58, "col": 62, "offset": 2623}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_979b45ae", "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": 59, "line_end": 59, "column_start": 51, "column_end": 62, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 59, "col": 51, "offset": 2737}, "end": {"line": 59, "col": 62, "offset": 2748}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_1271945b", "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": 60, "line_end": 60, "column_start": 48, "column_end": 61, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 60, "col": 48, "offset": 2859}, "end": {"line": 60, "col": 61, "offset": 2872}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_d450a2ec", "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": 61, "line_end": 61, "column_start": 49, "column_end": 62, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 61, "col": 49, "offset": 2990}, "end": {"line": 61, "col": 62, "offset": 3003}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_e0524a4a", "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": 62, "line_end": 62, "column_start": 54, "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.return-not-in-function", "path": "/tmp/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 62, "col": 54, "offset": 3126}, "end": {"line": 62, "col": 70, "offset": 3142}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_0127e25f", "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": 63, "line_end": 63, "column_start": 54, "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.return-not-in-function", "path": "/tmp/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 63, "col": 54, "offset": 3265}, "end": {"line": 63, "col": 70, "offset": 3281}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_05a1b388", "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": 64, "line_end": 64, "column_start": 52, "column_end": 65, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 64, "col": 52, "offset": 3402}, "end": {"line": 64, "col": 65, "offset": 3415}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_4b534d74", "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": 65, "line_end": 65, "column_start": 54, "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.return-not-in-function", "path": "/tmp/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 65, "col": 54, "offset": 3538}, "end": {"line": 65, "col": 70, "offset": 3554}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_0a45812e", "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": 66, "line_end": 66, "column_start": 53, "column_end": 67, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 66, "col": 53, "offset": 3676}, "end": {"line": 66, "col": 67, "offset": 3690}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_7281d21e", "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": 67, "line_end": 67, "column_start": 50, "column_end": 63, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 67, "col": 50, "offset": 3802}, "end": {"line": 67, "col": 63, "offset": 3815}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_2777939b", "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": 68, "line_end": 68, "column_start": 60, "column_end": 82, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 68, "col": 60, "offset": 3937}, "end": {"line": 68, "col": 82, "offset": 3959}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_7d4a1efa", "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": 71, "line_end": 71, "column_start": 52, "column_end": 65, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 71, "col": 52, "offset": 4302}, "end": {"line": 71, "col": 65, "offset": 4315}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_fd6bea2c", "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": 72, "line_end": 72, "column_start": 58, "column_end": 78, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 72, "col": 58, "offset": 4442}, "end": {"line": 72, "col": 78, "offset": 4462}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_4de6bf11", "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": 73, "line_end": 73, "column_start": 54, "column_end": 72, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 73, "col": 54, "offset": 4585}, "end": {"line": 73, "col": 72, "offset": 4603}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_cca88b4f", "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": 74, "line_end": 74, "column_start": 56, "column_end": 74, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 74, "col": 56, "offset": 4728}, "end": {"line": 74, "col": 74, "offset": 4746}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_5bd02be4", "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": 75, "line_end": 75, "column_start": 58, "column_end": 78, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 75, "col": 58, "offset": 4873}, "end": {"line": 75, "col": 78, "offset": 4893}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_f5182d06", "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": 76, "line_end": 76, "column_start": 55, "column_end": 72, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 76, "col": 55, "offset": 5017}, "end": {"line": 76, "col": 72, "offset": 5034}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_a6f75568", "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": 77, "line_end": 77, "column_start": 55, "column_end": 72, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 77, "col": 55, "offset": 5158}, "end": {"line": 77, "col": 72, "offset": 5175}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_aa8b20cc", "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": 78, "line_end": 78, "column_start": 54, "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.return-not-in-function", "path": "/tmp/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 78, "col": 54, "offset": 5298}, "end": {"line": 78, "col": 70, "offset": 5314}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_5906649f", "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": 79, "line_end": 79, "column_start": 55, "column_end": 72, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 79, "col": 55, "offset": 5438}, "end": {"line": 79, "col": 72, "offset": 5455}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_b2b5c2cb", "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": 80, "line_end": 80, "column_start": 52, "column_end": 65, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 80, "col": 52, "offset": 5576}, "end": {"line": 80, "col": 65, "offset": 5589}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_8c9592f1", "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": 81, "line_end": 81, "column_start": 55, "column_end": 72, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 81, "col": 55, "offset": 5706}, "end": {"line": 81, "col": 72, "offset": 5723}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_80af1598", "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": 82, "line_end": 82, "column_start": 54, "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.return-not-in-function", "path": "/tmp/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 82, "col": 54, "offset": 5846}, "end": {"line": 82, "col": 70, "offset": 5862}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_43fc725b", "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": 83, "line_end": 83, "column_start": 55, "column_end": 72, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 83, "col": 55, "offset": 5979}, "end": {"line": 83, "col": 72, "offset": 5996}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_7958d096", "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": 84, "line_end": 84, "column_start": 55, "column_end": 72, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 84, "col": 55, "offset": 6120}, "end": {"line": 84, "col": 72, "offset": 6137}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_74ea97b2", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 85, "line_end": 85, "column_start": 55, "column_end": 72, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 85, "col": 55, "offset": 6261}, "end": {"line": 85, "col": 72, "offset": 6278}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_368d2f18", "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": 86, "line_end": 86, "column_start": 56, "column_end": 74, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 86, "col": 56, "offset": 6396}, "end": {"line": 86, "col": 74, "offset": 6414}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_b9880e22", "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": 87, "line_end": 87, "column_start": 54, "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.return-not-in-function", "path": "/tmp/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 87, "col": 54, "offset": 6530}, "end": {"line": 87, "col": 70, "offset": 6546}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_eea85ef6", "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": 88, "line_end": 88, "column_start": 54, "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.return-not-in-function", "path": "/tmp/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 88, "col": 54, "offset": 6669}, "end": {"line": 88, "col": 70, "offset": 6685}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a25fec928307f954_e8bfbc06", "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": 89, "line_end": 89, "column_start": 56, "column_end": 74, "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/tmpr7mo7ysm/a25fec928307f954.py", "start": {"line": 89, "col": 56, "offset": 6803}, "end": {"line": 89, "col": 74, "offset": 6821}, "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"}}}]
43
true
[ "CWE-95" ]
[ "rules.python.lang.security.audit.eval-detected" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 31 ]
[ 31 ]
[ 28 ]
[ 38 ]
[ "A03:2021 - Injection" ]
[ "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources." ]
[ 5 ]
[ "LOW" ]
[ "HIGH" ]
scientificCalculator.py
/scientificCalculator.py
PatrickAttankurugu/Scientific-Calculator
MIT
2024-11-18T21:10:19.640376+00:00
1,639,520,358,000
80cd04b32ee1352f90a129290f1bbd58f7ede3be
3
{ "blob_id": "80cd04b32ee1352f90a129290f1bbd58f7ede3be", "branch_name": "refs/heads/master", "committer_date": 1639520358000, "content_id": "f849de365b2df211c255e43a244c901754c5ff24", "detected_licenses": [ "MIT" ], "directory_id": "28b51017bcf7f1535b6b2d0fe47c30d9f40859d6", "extension": "py", "filename": "__main__.py", "fork_events_count": 12, "gha_created_at": 1558123276000, "gha_event_created_at": 1639520704000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 187274716, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1998, "license": "MIT", "license_type": "permissive", "path": "/src/markdown_katex/__main__.py", "provenance": "stack-edu-0054.json.gz:576562", "repo_name": "mbarkhau/markdown-katex", "revision_date": 1639520358000, "revision_id": "4245dc101fe6c9e830f83fc8d12b1397c1dff29d", "snapshot_id": "5c91973f09f1f18e05f6282da87646e625e09908", "src_encoding": "UTF-8", "star_events_count": 10, "url": "https://raw.githubusercontent.com/mbarkhau/markdown-katex/4245dc101fe6c9e830f83fc8d12b1397c1dff29d/src/markdown_katex/__main__.py", "visit_date": "2021-12-31T08:45:51.429647" }
2.53125
stackv2
#!/usr/bin/env python # This file is part of the markdown-katex project # https://github.com/mbarkhau/markdown-katex # # Copyright (c) 2019-2021 Manuel Barkhau (mbarkhau@gmail.com) - MIT License # SPDX-License-Identifier: MIT import sys import json import typing as typ import subprocess as sp import markdown_katex from markdown_katex import html try: import pretty_traceback pretty_traceback.install() except ImportError: pass # no need to fail because of missing dev dependency ExitCode = int def _selftest() -> ExitCode: # pylint:disable=import-outside-toplevel ; lazy import to improve cli responsiveness from markdown_katex import wrapper print("Command options:") print(json.dumps(wrapper.parse_options(), indent=4)) print() html_parts: typ.List[str] = [] test_formulas = markdown_katex.TEST_FORMULAS for tex_formula in test_formulas: html_part = wrapper.tex2html(tex_formula) if not html_part: return 1 html_parts.append(html_part) formula_html = "\n<hr/>\n".join(html_parts) html_text = html.HTML_TEMPLATE.replace("{{content}}", formula_html) with open("test.html", mode="wb") as fobj: fobj.write(html_text.encode("utf-8")) print("Created 'test.html'") return 0 def main(args: typ.Sequence[str] = sys.argv[1:]) -> ExitCode: """Basic wrapper around the katex command. This is mostly just used for self testing. $ python -m markdown_katex """ # pylint:disable=dangerous-default-value ; mypy will catch mutations of args if "--markdown-katex-selftest" in args: return _selftest() bin_cmd = markdown_katex.get_bin_cmd() if "--version" in args or "-V" in args: version = markdown_katex.__version__ bin_str = " ".join(bin_cmd) print("markdown-katex version: ", version, f"(using binary: {bin_str})") return sp.check_call(bin_cmd + list(args)) if __name__ == '__main__': sys.exit(main())
76
25.29
89
12
510
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_fdc11466778164a7_5bb6c51d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 72, "line_end": 72, "column_start": 12, "column_end": 47, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/fdc11466778164a7.py", "start": {"line": 72, "col": 12, "offset": 1912}, "end": {"line": 72, "col": 47, "offset": 1947}, "extra": {"message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 72 ]
[ 72 ]
[ 12 ]
[ 47 ]
[ "A01:2017 - Injection" ]
[ "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'." ]
[ 7.5 ]
[ "LOW" ]
[ "HIGH" ]
__main__.py
/src/markdown_katex/__main__.py
mbarkhau/markdown-katex
MIT
2024-11-18T21:10:19.750578+00:00
1,447,878,174,000
04cedd90f230da67eb025fcf221f36f7625cb56e
3
{ "blob_id": "04cedd90f230da67eb025fcf221f36f7625cb56e", "branch_name": "refs/heads/master", "committer_date": 1447878174000, "content_id": "26f57599e9ac1b4f93408c85e51e609105313ed2", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "3cacaa667c7dba168ad21548998c34e5eda6b0ce", "extension": "py", "filename": "kalman.py", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 3620365, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6229, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/mvn/examples/kalman.py", "provenance": "stack-edu-0054.json.gz:576563", "repo_name": "MarkDaoust/mvn", "revision_date": 1447878174000, "revision_id": "2c82cbfa898fd063c08752f03c08a2a043c245f9", "snapshot_id": "cf31a393d85ceef114fa053d7c6c5715e1362177", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/MarkDaoust/mvn/2c82cbfa898fd063c08752f03c08a2a043c245f9/mvn/examples/kalman.py", "visit_date": "2020-04-15T18:30:30.563983" }
2.640625
stackv2
#! /usr/bin/env python print 'starting' import os import sys import numpy import matplotlib #matplotlib.use('cairo') from matplotlib.gridspec import GridSpec from matplotlib.ticker import MultipleLocator import pylab from mvn import Mvn from mvn.matrix import Matrix import mvn.plotTools from collections import OrderedDict colors = OrderedDict([ ['Actual' , [1, 1, 0]], ['Updated' , [0, 0, 1]], ['Noise' , [1, 0, 0]], ['Updated+Noise', [1, 0, 1]], ['Measurement' , [0, 1, 0]], ['Filter Result', [0, 1, 1]], ]) actualParams = { 'marker':'*', 'markersize':20, 'color':colors['Actual'], } otherParams = { 'minalpha':0.5, 'slope':0.333 } class Publisher(object): def __init__(self, targetDir, formats=('png','svg')): self.n = 0 self.formats = formats self.targetDir = targetDir try: os.stat(self.targetDir) except OSError: os.mkdir(self.targetDir) def publish(self, fig): for format in self.formats: fig.savefig( "%s/%0.3d.%s" % (self.targetDir, self.n, format), format=format ) self.n += 1 def seed(path): if len(sys.argv) > 1: seed = int(sys.argv[1]) else: seed = numpy.random.randint(10000) print 'seed: %d' % seed numpy.random.seed(seed) open('%s/seed' % path, 'w').write(str(seed)) def drawLegend(ax): patch = lambda color:matplotlib.patches.Ellipse( [0, 0], width=0, height=0, facecolor=color ) patches = [patch(color) for [name,color] in colors.iteritems()] ax.legend( patches, list(colors.keys()), loc='lower center', ncol = 2 ) def newAx(fig, transform = Matrix.eye(2)): fig.clear() axgrid = GridSpec(1, 1) #get axes ax = pylab.subplot( axgrid[:, :], projection = 'custom', transform = transform, ) ax.autoscale(False) # ax.set_xticks(numpy.arange(-10., 35., 5.)) # ax.set_yticks(numpy.arange(-10., 35., 5.)) ax.set_xlim([-5, 20]) ax.set_ylim([-5, 10]) ax.xaxis.set_major_locator(MultipleLocator(5)) ax.grid('on') drawLegend(ax) return ax if __name__ == '__main__': if not os.path.exists('kalman'): os.mkdir('kalman') ## figure setup #directory for resulting figures path = 'kalman' #seed the rng so results are reproducible. seed(path) #create publisher P = Publisher(path) #create figure fig = pylab.figure(figsize = (6, 6)) ## kalman filter parameters #the actual, hidden state actual = numpy.array([[0, 5]]) #the sensor sensor = Mvn(vectors = [[1, 0], [0, 1]],var = [1, numpy.inf]) #the system noise noise = Mvn(vectors = [[1, 0], [0, 1]], var = numpy.array([0.5, 1])**2) #the shear transform to move the system forward transform = Matrix([[1, 0], [0.5, 1]]) filtered = sensor.measure(actual) ## initial plot ax = newAx(fig) #plot the initial actual position ax.plot(actual[:, 0], actual[:, 1], **actualParams) ax.set_title('Kalman Filtering: Start') pylab.xlabel('Position') pylab.ylabel('Velocity') P.publish(fig) #measure the actual position, and plot the measurment filtered.plot(facecolor=colors['Filter Result'], **otherParams) ax.set_title('Initialize to first measurement') pylab.xlabel('Position') pylab.ylabel('Velocity') P.publish(fig) for n in range(6): ## plot immediately after the step foreward #create a transformed axis ax = newAx(fig)#,transform) #update the system actual = actual*transform filtered = filtered*transform #plot the updated system ax.plot(actual[:, 0], actual[:, 1], **actualParams) filtered.plot(facecolor=colors['Updated'], **otherParams) ax.set_title('Update') pylab.xlabel('Position') pylab.ylabel('Velocity') P.publish(fig) #realign the axes ax = newAx(fig) #re-plot the filter result filtered.plot(facecolor=colors['Updated'], **otherParams) #add noise and plot the actual and filtered values actual_noise = noise+actual filtered_noise = noise+filtered actual_noise.plot(facecolor = colors['Noise'], **otherParams) filtered_noise.plot(facecolor = colors['Noise'], **otherParams) # sample the position of the actual distribution, to find it's new position ax.plot(actual[:, 0], actual[:, 1], **actualParams) actual=actual_noise.sample() ax.plot(actual[:, 0], actual[:, 1], **actualParams) ax.set_title('Add process noise') pylab.xlabel('Position') pylab.ylabel('Velocity') P.publish(fig) ax = newAx(fig) filtered = filtered_noise ax.plot(actual[:, 0], actual[:, 1], **actualParams) filtered.plot(facecolor=colors['Updated+Noise'], **otherParams) ax.set_title('Add process noise') pylab.xlabel('Position') pylab.ylabel('Velocity') P.publish(fig) measure=sensor.measure(actual) measure.plot(facecolor = colors['Measurement'], **otherParams) ax.set_title('Measure') P.publish(fig) filtered = filtered&measure filtered.plot(facecolor = colors['Filter Result'], **otherParams) ax.set_title('Merge') pylab.xlabel('Position') pylab.ylabel('Velocity') P.publish(fig) ax = newAx(fig) ax.plot(actual[:, 0], actual[:, 1], **actualParams) filtered.plot(facecolor=colors['Filter Result'], **otherParams) pylab.xlabel('Position') pylab.ylabel('Velocity') ax.set_title('Merge') P.publish(fig) # os.system('convert -limit memory 32 -delay 100 %s/*.png kalman.gif' % path) os.system('convert -delay 150 %s/*.png kalman.gif' % path)
248
24.12
84
14
1,586
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_3f5d8e0f0eebddb4_2cdba0fa", "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": 5, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/3f5d8e0f0eebddb4.py", "start": {"line": 72, "col": 5, "offset": 1430}, "end": {"line": 72, "col": 32, "offset": 1457}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_3f5d8e0f0eebddb4_df007d71", "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": 247, "line_end": 247, "column_start": 5, "column_end": 63, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpr7mo7ysm/3f5d8e0f0eebddb4.py", "start": {"line": 247, "col": 5, "offset": 6169}, "end": {"line": 247, "col": 63, "offset": 6227}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-system-call-audit" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 247 ]
[ 247 ]
[ 5 ]
[ 63 ]
[ "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" ]
kalman.py
/mvn/examples/kalman.py
MarkDaoust/mvn
BSD-2-Clause
2024-11-18T21:10:19.928457+00:00
1,622,451,798,000
e899ce0fdb0486a599691eae5badd2734a65f5fc
3
{ "blob_id": "e899ce0fdb0486a599691eae5badd2734a65f5fc", "branch_name": "refs/heads/main", "committer_date": 1622451798000, "content_id": "0c20ad4a496883c040336b54a9a98dcdea0f543d", "detected_licenses": [ "Unlicense" ], "directory_id": "620f5eda6202087ffa190caf9fad8379e166eeff", "extension": "py", "filename": "get_mean_std.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 372433927, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2630, "license": "Unlicense", "license_type": "permissive", "path": "/MT-CNV/get_mean_std.py", "provenance": "stack-edu-0054.json.gz:576566", "repo_name": "Wangzheaos/DARD-Net", "revision_date": 1622451798000, "revision_id": "4b0dc7e87c82c7f6f5892c257fd397d7217fd7f1", "snapshot_id": "bcd34243ddcc2209d5b249e15d66d15d98c144a3", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Wangzheaos/DARD-Net/4b0dc7e87c82c7f6f5892c257fd397d7217fd7f1/MT-CNV/get_mean_std.py", "visit_date": "2023-05-14T16:03:45.611123" }
3.0625
stackv2
# coding:utf-8 import os import numpy as np from torchvision.datasets import ImageFolder import torchvision.transforms as transforms import pickle """ 在训练前先运行该函数获得数据的均值和标准差 """ class Dataloader(): def __init__(self, isize, dataroot): # 训练,验证,测试数据集文件夹名 self.isize = isize self.dataroot = dataroot self.dirs = ['train', 'test', 'val', 'center_v'] self.means = [0, 0, 0] self.stdevs = [0, 0, 0] self.transform = transforms.Compose([transforms.Resize(self.isize), transforms.CenterCrop(self.isize), transforms.ToTensor(), # 数据值从[0,255]范围转为[0,1],相当于除以255操作 # transforms.Normalize((0.485,0.456,0.406), (0.229,0.224,0.225)) ]) # 因为这里使用的是ImageFolder,按文件夹给数据分类,一个文件夹为一类,label会自动标注好 self.dataset = {x: ImageFolder(os.path.join(self.dataroot, x), self.transform) for x in self.dirs} def get_mean_std(self, type, mean_std_path): """ 计算数据集的均值和标准差 :param type: 使用的是那个数据集的数据,有'train', 'test', 'testing' :param mean_std_path: 计算出来的均值和标准差存储的文件 :return: """ num_imgs = len(self.dataset[type]) for data in self.dataset[type]: img = data[0] for i in range(3): # 一个通道的均值和标准差 self.means[i] += img[i, :, :].mean() self.stdevs[i] += img[i, :, :].std() self.means = np.asarray(self.means) / num_imgs self.stdevs = np.asarray(self.stdevs) / num_imgs print("{} : normMean = {}".format(type, self.means)) print("{} : normstdevs = {}".format(type, self.stdevs)) # 将得到的均值和标准差写到文件中,之后就能够从中读取 with open(mean_std_path, 'wb') as f: pickle.dump(self.means, f) pickle.dump(self.stdevs, f) print('pickle done') if __name__ == '__main__': isize = 32 dataroot = './data-local/images/ruxian/' dataloader = Dataloader(isize, dataroot) for x in dataloader.dirs: mean_std_path = 'mean_std_value_' + x + '.pkl' dataloader.get_mean_std(x, mean_std_path)
66
32.91
109
16
661
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e4b21c77e39e224d_b02e522e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 55, "line_end": 55, "column_start": 13, "column_end": 39, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/e4b21c77e39e224d.py", "start": {"line": 55, "col": 13, "offset": 2197}, "end": {"line": 55, "col": 39, "offset": 2223}, "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_e4b21c77e39e224d_963ad9b7", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 56, "line_end": 56, "column_start": 13, "column_end": 40, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/e4b21c77e39e224d.py", "start": {"line": 56, "col": 13, "offset": 2236}, "end": {"line": 56, "col": 40, "offset": 2263}, "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" ]
[ 55, 56 ]
[ 55, 56 ]
[ 13, 13 ]
[ 39, 40 ]
[ "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "Avoid using `pickle`, which is known to lead to...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
get_mean_std.py
/MT-CNV/get_mean_std.py
Wangzheaos/DARD-Net
Unlicense
2024-11-18T21:10:21.975356+00:00
1,596,189,140,000
ff6b4ec967a5e216c45cd97dd0c7124359fd0361
3
{ "blob_id": "ff6b4ec967a5e216c45cd97dd0c7124359fd0361", "branch_name": "refs/heads/master", "committer_date": 1596189140000, "content_id": "e6db946e3bae461274bb74d4d4c090b67ed40c52", "detected_licenses": [ "MIT" ], "directory_id": "6ca9a7ed179ed96857c86dd91d5f81ad07be4690", "extension": "py", "filename": "run.py", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 108302688, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1788, "license": "MIT", "license_type": "permissive", "path": "/MixNotes/电影简介_贝叶斯/run.py", "provenance": "stack-edu-0054.json.gz:576589", "repo_name": "nickliqian/keep_learning", "revision_date": 1596189140000, "revision_id": "be120ce2bb94a8e8395630218985f5e51ae087d9", "snapshot_id": "ede172048cb1473013aa506a943ebe0c7c416065", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/nickliqian/keep_learning/be120ce2bb94a8e8395630218985f5e51ae087d9/MixNotes/电影简介_贝叶斯/run.py", "visit_date": "2021-04-25T18:23:47.808870" }
3.28125
stackv2
from sqlite3 import * from math import * def init_db(): db = connect(database='world.db') return db.cursor(), db def query_data(country_name, count, db_cursor): sql = "select city.Name from country,city where city.CountryCode=country.code" \ " and country.name='{}' and city.population>={} order by city.Population".format(country_name, count) db_cursor.execute(sql) results = db_cursor.fetchall() print(results) return results, len(results) def get_color(num): colours = ['aqua', 'black', 'blue', 'fuchsia', 'gray', 'green', 'lime', 'maroon', 'navy', 'olive', 'purple', 'red', 'silver', 'teal', 'yellow'] return colours[(len(colours) % (num+1))-1] def show_population(country_list, count, test): db_cursor, db = init_db() for country in country_list: results, city_count = query_data(country, count, db_cursor) filename = open(test + "_" + country + ".html", 'w') filename.write("<html><body><h1 align='center'>cities of{}</h1>" "<h3 align='center'>with population>={}</h3>" "<h3 align='center'>city count:{}</h3><hr><p>" .format(country, count, city_count)) for i in range(len(results)): filename.write('<span style="font-size:{}px; color:{}"> {}</span>' .format(city_count - i, get_color(i), results[i][0])) filename.write('</p><div><a href="" align="right">Previous Page</a>' '<a href="" align="left">Next Page</a></div></body></html>') filename.close() db_cursor.close() db.close() if __name__ == "__main__": show_population(['Germany', 'New Zealand', 'Austria', 'Australia'], 1000000, 'Test05')
49
35.51
111
15
445
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_bb79353fa5826c31_27757485", "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": 13, "line_end": 13, "column_start": 5, "column_end": 27, "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/tmpr7mo7ysm/bb79353fa5826c31.py", "start": {"line": 13, "col": 5, "offset": 374}, "end": {"line": 13, "col": 27, "offset": 396}, "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_bb79353fa5826c31_7c8706e1", "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": 13, "line_end": 13, "column_start": 5, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpr7mo7ysm/bb79353fa5826c31.py", "start": {"line": 13, "col": 5, "offset": 374}, "end": {"line": 13, "col": 27, "offset": 396}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_bb79353fa5826c31_46cbd5c6", "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": 20, "column_end": 61, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/bb79353fa5826c31.py", "start": {"line": 33, "col": 20, "offset": 934}, "end": {"line": 33, "col": 61, "offset": 975}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-89", "CWE-89" ]
[ "rules.python.lang.security.audit.formatted-sql-query", "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "HIGH" ]
[ 13, 13 ]
[ 13, 13 ]
[ 5, 5 ]
[ 27, 27 ]
[ "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" ]
run.py
/MixNotes/电影简介_贝叶斯/run.py
nickliqian/keep_learning
MIT
2024-11-18T21:10:23.271528+00:00
1,690,569,342,000
99104e1f5f3d9f194dddfbe455aff487f16a77ad
3
{ "blob_id": "99104e1f5f3d9f194dddfbe455aff487f16a77ad", "branch_name": "refs/heads/master", "committer_date": 1690569342000, "content_id": "2a32b19ec626ac2de8509cb3fd2593cd6dcb18a7", "detected_licenses": [ "MIT" ], "directory_id": "4f85b712215f5f1d8cdfa22199da5bde970c072e", "extension": "py", "filename": "plot_data_interactive_aerobotany.py", "fork_events_count": 40, "gha_created_at": 1448368018000, "gha_event_created_at": 1682631478000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 46790207, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9921, "license": "MIT", "license_type": "permissive", "path": "/other_code/Building_blocks/Plot_overlays/plot_data_interactive_aerobotany.py", "provenance": "stack-edu-0054.json.gz:576604", "repo_name": "zooniverse/Data-digging", "revision_date": 1690569342000, "revision_id": "4f79b8807a8dfa3718567311f3b2bfbf412ddee0", "snapshot_id": "fbf0a1051730ef983c896f449865101f5c266f60", "src_encoding": "UTF-8", "star_events_count": 47, "url": "https://raw.githubusercontent.com/zooniverse/Data-digging/4f79b8807a8dfa3718567311f3b2bfbf412ddee0/other_code/Building_blocks/Plot_overlays/plot_data_interactive_aerobotany.py", "visit_date": "2023-08-08T00:05:14.122187" }
2.890625
stackv2
"""This script plot_data_interactive_aerobotany.py takes the output from aggregate_drawing_demo.csv which is the clustered circle centres for the original Aerobotany project. It plots the data points and circles the clusters on the original subject image at the appropriate scale. A legend and title are added. The source for the subject image which is used for the plot background is the actual zooniverse hosted subject. Using lookup_url.py, a lookup table of subject-url is created from the subject download from the project. This uses subject set and workflow_id to select the appropriate subjects and their urls. We then use this lookup table keyed by subject to find the url for the zooniverse hosted image, and used the url to download the image to our plot background. Once the plot has been created and displayed, there are two options to save it. One saves the plot as a jpeg file with approximately the same resolution as the original image. The down side to this approach is the points and circles plotted on the image are a fixed size in the pixels of the image - zooming the image increases the size of the point markers and circle line width, obscuring the image. The second way to store the image is as a pickle file – sort of an interrupted python script where the plot is put on hold. To reactivate it, it must be loaded with a Python script that unpacks the pickled file, essentially returning us to the point the file was put on hold. The advantage of this approach is the background image is the original subject image with no resolution loss and the pan and zoom widgets of the original plot work as before. Now if one zooms in the point size and circle line widths do not change in on-screen pixels so the image is not obscured by large points and thick lines. """ import csv import json import sys import matplotlib.pyplot as plt from matplotlib.patches import Circle import os from PIL import Image import pickle import requests csv.field_size_limit(sys.maxsize) # these paths and file names need to be modified for your application: data_path = 'C:\\py\\Data_digging\\' # Note the double slashes are required file_name = 'aggregate_drawing_demo.csv' data_location = data_path + file_name subject_url = r'C:\py\AASubject\lookup_list_subject_url.csv' save_location = 'C:\\py\\Data_digging\\Plots\\' # build a dictionary of subject-url pairs (executed once and held in memory) def look_up_url(subject_file): with open(subject_file, 'r') as l_up_file: r = csv.DictReader(l_up_file) look_up = {} for row in r: look_up[row['subject_id']] = row['url'] return look_up # one of two save options, this one is a jpg file, with a scaled dpi and crop to # retain as much resolution as possible in the smallest image file. The os operations # ensure the files can be recreated if they already exist. def save_plot(subject_name, w, h): temp_file = 'temp.png' if os.path.isfile(temp_file): os.remove(temp_file) plt.savefig(temp_file, dpi=160 * im.size[0] / 795) file = Image.open(temp_file) box = (127 * w / 795, .516 * (.966 * w - h), 127 * w / 795 + w, .516 * (.966 * w - h) + h) region = file.crop(box) if os.path.isfile(save_location + subject_name + '.jpg'): os.remove(save_location + subject_name + '.jpg') region.save(save_location + subject_name + '.jpg') # The second save option is to save the plot as a pickle file. This requires the use # of a script to open it later, but preserves all the plot functionality and resolution. def save_pickles(subject_name): pickle_name = save_location + subject_name + '.fig.pickle' if os.path.isfile(pickle_name): os.remove(pickle_name) fig = plt.gca() pickle.dump(fig, open(pickle_name, 'wb')) # This function acquires the data to overlay on the image from the aggregated csv. def get_data(subject_ids): with open(data_location, 'r') as data_file: r = csv.DictReader(data_file) for row in r: if subject_ids == row['subject_ids']: print('Data found') data = {'H_palm_clusters': json.loads(row['H_palm_clusters']), 'Hclusters': json.loads(row['Hclusters']), 'Hnoise': json.loads(row['Hnoise']), 'flowering_clusters': json.loads(row['flowering_clusters']), 'fclusters': json.loads(row['fclusters']), 'fnoise': json.loads(row['fnoise']), 'leafless_clusters': json.loads(row['leafless_clusters']), 'lclusters': json.loads(row['lclusters']), 'lnoise': json.loads(row['lnoise'])} return data continue print('Data Not found!') return None # This function calculates a suitable location for the label for each circle that is plotted, # so the label does not run off the top or right edge of the plot. def location(centre, r, size): xlocate = centre[0] + .7 * r ylocate = centre[1] - .7 * r if xlocate >= size[0] - .035 * size[0]: xlocate = centre[0] - .7 * r - .030 * size[0] if ylocate <= .015 * size[0]: ylocate = centre[1] + .7 * r + .01*size[0] return [xlocate, ylocate] # call the function to build the look_up dictionary lookup = look_up_url(subject_url) # begin a loop to input a subject and produce the plot for that subject. while True: # get the subject: subject = str(input('Enter a valid Subject Number:' + '\n')) try: url = lookup[subject] print('Subject found') except KeyError: print('Subject not found') flag = input('Do you want to try again? y or n' + '\n') if flag != 'y': break continue # acquire the data: data_points = get_data(subject) if data_points is None: flag = input('Do you want to try again? y or n' + '\n') if flag != 'y': break continue print('Requesting Image') # acquire the image directly from the zooniverse url for the chosen subject and create the basic plot. im = Image.open(requests.get(url, stream=True).raw) plt.axis([0.0, im.size[0], im.size[1], 0.0]) plt.imshow(im) plt.title(subject + ' ' + file_name) ax = plt.gca() ax.axis('off') print('Acquired image') # This section accumulates all the points we want to plot in both the clusters # and the noise points and plots them using ax.scatter for each point type. font = {'family': 'sans serif', 'color': 'yellow', 'weight': 'normal', 'size': 9} xh = [] yh = [] xf = [] yf = [] xl = [] yl = [] for cluster in data_points['Hclusters']: for point in cluster[1]: xh.append(point[0]) yh.append(point[1]) for point in data_points['Hnoise']: xh.append(point[0]) yh.append(point[1]) ax.scatter(xh, yh, s=4, c="white", marker='s', label='H. palm', alpha=1) for cluster in data_points['fclusters']: for point in cluster[1]: xf.append(point[0]) yf.append(point[1]) for point in data_points['fnoise']: xf.append(point[0]) yf.append(point[1]) ax.scatter(xf, yf, s=4, c="cyan", marker='s', label='Flowering', alpha=1) for cluster in data_points['lclusters']: for point in cluster[1]: xl.append(point[0]) yl.append(point[1]) for point in data_points['lnoise']: xl.append(point[0]) yl.append(point[1]) ax.scatter(xl, yl, s=4, c="red", marker='s', label='Leafless', alpha=1) # add a legend ax.legend(loc='upper right', bbox_to_anchor=(1.0, 0.13), fontsize='xx-small') # this section adds the circles for the clustered points using ax.add.artist(Circle.... # The cluster labels are added using ax.text. for cluster in data_points['H_palm_clusters']: radius = 2 * cluster[2] # for eps = .5 of median ax.add_artist(Circle((cluster[1][0], cluster[1][1]), radius, clip_on=False, zorder=10, linewidth=1, edgecolor='white', facecolor=(0, 0, 0, 0))) text_location = location(cluster[1], radius, im.size) ax.text(text_location[0], text_location[1], str(cluster[0]), fontdict=font, alpha=1) for cluster in data_points['flowering_clusters']: radius = 2 * cluster[2] # for eps = .5 of median ax.add_artist(Circle((cluster[1][0], cluster[1][1]), radius, clip_on=False, zorder=10, linewidth=1, edgecolor='cyan', facecolor=(0, 0, 0, 0))) text_location = location(cluster[1], radius, im.size) ax.text(text_location[0], text_location[1], str(cluster[0]), fontdict=font, alpha=1) for cluster in data_points['leafless_clusters']: radius = 2 * cluster[2] # for eps = .5 of median ax.add_artist(Circle((cluster[1][0], cluster[1][1]), radius, clip_on=False, zorder=10, linewidth=1, edgecolor='red', facecolor=(0, 0, 0, 0))) text_location = location(cluster[1], radius, im.size) ax.text(text_location[0], text_location[1], str(cluster[0]), fontdict=font, alpha=1) # the two save options are the called in the lines directly below. One or the other (or both) # can be commented out if that option is not required. save_plot(subject, im.size[0], im.size[1]) save_pickles(subject) # actually show the plot zoomed to full screen: mng = plt.get_current_fig_manager() mng.window.state('zoomed') plt.show() # Close the plot and move to the next subject selection when finished viewing the current plot plt.close() print('Session terminated')
213
44.57
107
18
2,480
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_58e7fce1240429ea_812a8ee2", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 46, "line_end": 46, "column_start": 10, "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/tmpr7mo7ysm/58e7fce1240429ea.py", "start": {"line": 46, "col": 10, "offset": 2460}, "end": {"line": 46, "col": 33, "offset": 2483}, "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_58e7fce1240429ea_b5718620", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 78, "line_end": 78, "column_start": 5, "column_end": 46, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/58e7fce1240429ea.py", "start": {"line": 78, "col": 5, "offset": 3769}, "end": {"line": 78, "col": 46, "offset": 3810}, "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_58e7fce1240429ea_44741f3f", "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": 10, "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/tmpr7mo7ysm/58e7fce1240429ea.py", "start": {"line": 83, "col": 10, "offset": 3933}, "end": {"line": 83, "col": 34, "offset": 3957}, "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_58e7fce1240429ea_cdf2d9b5", "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": 137, "line_end": 137, "column_start": 21, "column_end": 51, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmpr7mo7ysm/58e7fce1240429ea.py", "start": {"line": 137, "col": 21, "offset": 6134}, "end": {"line": 137, "col": 51, "offset": 6164}, "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_58e7fce1240429ea_c5fc0e84", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "requests.get(url, stream=True, timeout=30)", "location": {"file_path": "unknown", "line_start": 137, "line_end": 137, "column_start": 21, "column_end": 51, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpr7mo7ysm/58e7fce1240429ea.py", "start": {"line": 137, "col": 21, "offset": 6134}, "end": {"line": 137, "col": 51, "offset": 6164}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "requests.get(url, stream=True, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
5
true
[ "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 78 ]
[ 78 ]
[ 5 ]
[ 46 ]
[ "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" ]
plot_data_interactive_aerobotany.py
/other_code/Building_blocks/Plot_overlays/plot_data_interactive_aerobotany.py
zooniverse/Data-digging
MIT
2024-11-18T21:10:26.430761+00:00
1,510,780,875,000
495f4e6b34a95e523078f50fba8270668c10262c
2
{ "blob_id": "495f4e6b34a95e523078f50fba8270668c10262c", "branch_name": "refs/heads/master", "committer_date": 1510780875000, "content_id": "86105278129bcccd3f35f634b19d94e27d8a7c58", "detected_licenses": [ "MIT" ], "directory_id": "1a34472e45df99176ba0731f9dbdd5fa2fe9fe13", "extension": "py", "filename": "prof_blas.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 108782420, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9103, "license": "MIT", "license_type": "permissive", "path": "/prof_blas.py", "provenance": "stack-edu-0054.json.gz:576642", "repo_name": "doublsky/MLProfile", "revision_date": 1510780875000, "revision_id": "0c43563488b0dc9982f33de15b5408336db107a5", "snapshot_id": "91f6d7ae692d841288a93e9eafd5c1f077ce38f8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/doublsky/MLProfile/0c43563488b0dc9982f33de15b5408336db107a5/prof_blas.py", "visit_date": "2021-05-07T18:05:51.152880" }
2.421875
stackv2
""" Profile all bench_list """ import subprocess as sp import pandas as pd import argparse from util import * import socket rpt_cmd = "opreport -l -n".split() # read a list of interested kernels def trim_func_param(infile, outfile): with open(infile, "r") as inf, open(outfile, "w") as outf: for line in inf: remainder = line.split("(")[0] outf.write(remainder + "\n") def process_rpt(rpt, results_df, idx): # global results_df, idx # read results into a datafram rpt_df = pd.read_table(rpt, delim_whitespace=True, header=None, index_col=False, names=["samples", "percent", "image_name", "symbol_name"]) # select kernels / exclude kernels if args.kexclude: for kernel in kernel_list: rpt_df = rpt_df[~(rpt_df["symbol_name"].str.contains(kernel))] # copy rest kernels for _, row in rpt_df.iterrows(): if args.kexclude: results_df.set_value(idx, row["symbol_name"], row["percent"]) else: if row["symbol_name"] in kernel_list: results_df.set_value(idx, row["symbol_name"], row["percent"]) # move to next record return idx + 1 def test_bench(args): # iterate through all benchmarks with open(args.blist, "r") as bench_list: for bench in bench_list: if bench.startswith("#"): # allow commenting in benchmark list continue test_cmd = ["timeout", "-k", "3", "3", "python", benchfile] config_file = get_config_file(benchfile, args.tool) with open(config_file, "r") as config_list, open(args.output, "w") as outfile: for config in config_list: maybe_create_dataset(config) sp.call(test_cmd + config.split(), stdout=outfile, stderr=outfile) def perf_bench(args): # iterate through all benchmarks with open(args.blist, "r") as bench_list: for bench in bench_list: if bench.startswith("#"): # allow commenting in benchmark list continue # init benchfile = "benchmark/" + bench.rstrip() perf_cmd = ["operf", "--event=CPU_CLK_UNHALTED:3000000", "python", benchfile] results_df = pd.DataFrame() idx = 0 with open(get_config_file(benchfile, "perf"), "r") as config_list: for config in config_list: maybe_create_dataset(config) try: sp.check_call(perf_cmd + config.split()) sp.check_call(rpt_cmd + ["-o", "/tmp/blasrpt.tmp"]) trim_func_param("/tmp/blasrpt.tmp", "/tmp/blasrpt_trimmed.tmp") idx = process_rpt("/tmp/blasrpt_trimmed.tmp", results_df, idx) finally: # post processing (generate signature) #for index, row in results_df.iterrows(): # sig = get_series_signature(row) # results_df.set_value(index, "signature", sig) # export to .csv results_file = benchfile.replace("bench_", "perf_") results_file = results_file.replace(".py", ".csv") results_df.to_csv(results_file, index=False) def time_bench(args): # iterate through all benchmarks with open(args.blist, "r") as bench_list: for bench in bench_list: if bench.startswith("#"): # allow commenting in benchmark list continue # init benchfile = "benchmark/" + bench.rstrip() time_output = benchfile.replace(".py", ".time") cmd = ["/usr/bin/time", "-a", "-o", time_output, "python"] + [benchfile] # foreach configuration with open(get_config_file(benchfile, "time"), "r") as config_file: for config in config_file: maybe_create_dataset(config) sp.check_call(cmd + config.split()) def trace2csv(csvfile, count, comm_mat): total = 0 for key, value in comm_mat.iteritems(): total += value with open(csvfile, "a") as resutls: for key, value in comm_mat.iteritems(): resutls.write("{},{},{},{}\n".format(count, key[0], key[1], float(value)/total)) def accumulate_comm_mat(partial_comm_mat, comm_mat): total = 0 for key, value in partial_comm_mat.iteritems(): total += value for key, value in partial_comm_mat.iteritems(): if key in comm_mat: comm_mat[key] += float(partial_comm_mat[key]) / total else: comm_mat[key] = float(partial_comm_mat[key]) / total def pin_bench(args): # force numpy to run in single thread os.environ["OMP_NUM_THREADS"] = "1" # get pin root pin_home = os.environ["PIN_ROOT"] pin_cmd = [pin_home+"/pin", "-t", "pintools/obj-intel64/procatrace.so"] if not os.path.exists(args.outdir): os.makedirs(args.outdir) # iterate through all benchmarks with open(args.blist, "r") as bench_list: for bench in bench_list: if bench.startswith("#"): # allow commenting in benchmark list continue # init bench = bench.rstrip() benchfile = "benchmark/" + bench config_file = get_config_file(benchfile, "pin") count = 0 outfile = benchfile.replace(".py", "_pin.csv") if os.path.exists(outfile): os.remove(outfile) with open(outfile, "w") as f: f.write("use case,producer,consumer,comm weight\n") with open(config_file, 'r') as config_list: for configs in config_list: # init tracefile = bench.replace(".py", "_config"+str(count)+".trace") tracefile = os.path.join(args.outdir, tracefile) # skip profile if output file exist if not os.path.exists(tracefile): # create dataset if not exist maybe_create_dataset(configs) # call pin full_cmd = list(pin_cmd) full_cmd += ["-output", tracefile, "--", "python", benchfile] full_cmd += configs.split() try: sp.check_call(full_cmd) except: os.remove(tracefile) raise with open(tracefile, "r") as trace: comm_mat = parse_trace(trace) trace2csv(outfile, count, comm_mat) # remove tracefile if it is too large if os.path.getsize(tracefile) > 1e10: os.remove(tracefile) count += 1 if __name__ == "__main__": # top level parser parser = argparse.ArgumentParser(description="Run benchmarks, collect data") parser.add_argument("--blist", default="bench_list.txt", help="path to benchmark list") subparsers = parser.add_subparsers(help="available sub-command") # parser for time parser_time = subparsers.add_parser("time", help="time each benchmark") parser_time.set_defaults(func=time_bench) # parser for operf parser_perf = subparsers.add_parser("perf", help="profile using operf") parser_perf.add_argument("--klist", default="kernel_list.txt", help="path to kernel list") parser_perf.add_argument("--kexclude", action="store_true", help="exclude kernels in klist") parser_perf.add_argument("--test", action="store_true", help="Test benchmarks, do not profile.") parser_perf.set_defaults(func=perf_bench) # parser for pin parser_pin = subparsers.add_parser("pin", help="run Pin, generate memory reference trace") parser_pin.add_argument("--klist", default="kernel_list.txt", help="path to kernel list file") parser_pin.add_argument("--outdir", default="pin_out", help="path to output directory") parser_pin.set_defaults(func=pin_bench) # parser for test parser_test = subparsers.add_parser("test", help="test validity of benchmark configurations") parser_test.add_argument("--tool", default="perf", choices=["time", "perf", "pin"], help="for which tool") parser_test.add_argument("--output", default="test.log", help="path to test results file") parser_test.set_defaults(func=test_bench) # parser command-line args args = parser.parse_args() with open(args.klist, "r") as klist_file: kernel_list = klist_file.readlines() kernel_list = map(lambda x: x.rstrip(), kernel_list) args.func(args)
236
37.57
110
20
1,944
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_2082516de4467d73_346c0f45", "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": 16, "line_end": 16, "column_start": 10, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 16, "col": 10, "offset": 246}, "end": {"line": 16, "col": 27, "offset": 263}, "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_2082516de4467d73_078bcccd", "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": 16, "line_end": 16, "column_start": 36, "column_end": 54, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 16, "col": 36, "offset": 272}, "end": {"line": 16, "col": 54, "offset": 290}, "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_2082516de4467d73_2a2bdf18", "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": 48, "line_end": 48, "column_start": 10, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 48, "col": 10, "offset": 1278}, "end": {"line": 48, "col": 31, "offset": 1299}, "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_2082516de4467d73_f24f7809", "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": 18, "column_end": 40, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 56, "col": 18, "offset": 1616}, "end": {"line": 56, "col": 40, "offset": 1638}, "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_2082516de4467d73_ae3270cb", "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": 57, "column_end": 79, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 56, "col": 57, "offset": 1655}, "end": {"line": 56, "col": 79, "offset": 1677}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_2082516de4467d73_2e10cf58", "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": 59, "line_end": 59, "column_start": 21, "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/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 59, "col": 21, "offset": 1802}, "end": {"line": 59, "col": 87, "offset": 1868}, "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_2082516de4467d73_f0a6c24b", "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": 59, "line_end": 59, "column_start": 24, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 59, "col": 24, "offset": 1805}, "end": {"line": 59, "col": 28, "offset": 1809}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_2082516de4467d73_17a90b8a", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 64, "line_end": 64, "column_start": 10, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 64, "col": 10, "offset": 1939}, "end": {"line": 64, "col": 31, "offset": 1960}, "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_2082516de4467d73_5767f6e9", "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": 75, "line_end": 75, "column_start": 18, "column_end": 63, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 75, "col": 18, "offset": 2364}, "end": {"line": 75, "col": 63, "offset": 2409}, "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_2082516de4467d73_52a54510", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 79, "line_end": 79, "column_start": 25, "column_end": 65, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 79, "col": 25, "offset": 2567}, "end": {"line": 79, "col": 65, "offset": 2607}, "extra": {"message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_2082516de4467d73_c1d8ba41", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 80, "line_end": 80, "column_start": 25, "column_end": 76, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 80, "col": 25, "offset": 2632}, "end": {"line": 80, "col": 76, "offset": 2683}, "extra": {"message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_2082516de4467d73_9f6346eb", "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": 97, "line_end": 97, "column_start": 10, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 97, "col": 10, "offset": 3485}, "end": {"line": 97, "col": 31, "offset": 3506}, "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_2082516de4467d73_2493a12b", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 108, "line_end": 108, "column_start": 18, "column_end": 63, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 108, "col": 18, "offset": 3957}, "end": {"line": 108, "col": 63, "offset": 4002}, "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_2082516de4467d73_30815660", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 111, "line_end": 111, "column_start": 21, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 111, "col": 21, "offset": 4131}, "end": {"line": 111, "col": 56, "offset": 4166}, "extra": {"message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_2082516de4467d73_419da14a", "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": 119, "line_end": 119, "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/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 119, "col": 10, "offset": 4305}, "end": {"line": 119, "col": 28, "offset": 4323}, "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_2082516de4467d73_35f8ec60", "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": 149, "line_end": 149, "column_start": 10, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 149, "col": 10, "offset": 5220}, "end": {"line": 149, "col": 31, "offset": 5241}, "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_2082516de4467d73_cd4ca6c2", "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": 164, "line_end": 164, "column_start": 18, "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/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 164, "col": 18, "offset": 5769}, "end": {"line": 164, "col": 36, "offset": 5787}, "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_2082516de4467d73_40cc9d59", "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": 167, "line_end": 167, "column_start": 18, "column_end": 40, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 167, "col": 18, "offset": 5892}, "end": {"line": 167, "col": 40, "offset": 5914}, "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_2082516de4467d73_afbd9ef6", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 183, "line_end": 183, "column_start": 29, "column_end": 52, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 183, "col": 29, "offset": 6698}, "end": {"line": 183, "col": 52, "offset": 6721}, "extra": {"message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args_2082516de4467d73_e5ed8677", "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 'check_call' with user controlled data. A malicious actor could leverage this to perform command injection. You may consider using 'shlex.quote()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 183, "line_end": 183, "column_start": 43, "column_end": 51, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args", "path": "/tmp/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 183, "col": 43, "offset": 6712}, "end": {"line": 183, "col": 51, "offset": 6720}, "extra": {"message": "Detected subprocess function 'check_call' with user controlled data. A malicious actor could leverage this to perform command injection. You may consider using 'shlex.quote()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_2082516de4467d73_ad7143a2", "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": 188, "line_end": 188, "column_start": 26, "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/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 188, "col": 26, "offset": 6879}, "end": {"line": 188, "col": 46, "offset": 6899}, "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_2082516de4467d73_e0357130", "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": 232, "line_end": 232, "column_start": 10, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 232, "col": 10, "offset": 8939}, "end": {"line": 232, "col": 31, "offset": 8960}, "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.maintainability.return-not-in-function_2082516de4467d73_03cb199a", "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": 234, "line_end": 234, "column_start": 37, "column_end": 47, "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/tmpr7mo7ysm/2082516de4467d73.py", "start": {"line": 234, "col": 37, "offset": 9057}, "end": {"line": 234, "col": 47, "offset": 9067}, "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"}}}]
23
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.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.danger...
[ "security", "security", "security", "security", "security", "security" ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH" ]
[ 59, 79, 80, 111, 183, 183 ]
[ 59, 79, 80, 111, 183, 183 ]
[ 21, 25, 25, 21, 29, 43 ]
[ 87, 65, 76, 56, 52, 51 ]
[ "A01:2017 - Injection", "A01:2017 - Injection", "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()'.", "Detected subprocess functi...
[ 7.5, 7.5, 7.5, 7.5, 7.5, 7.5 ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "MEDIUM" ]
prof_blas.py
/prof_blas.py
doublsky/MLProfile
MIT
2024-11-18T21:10:29.994022+00:00
1,618,932,681,000
7b3ccef67369b1612058889bc11a616d2120c85d
2
{ "blob_id": "7b3ccef67369b1612058889bc11a616d2120c85d", "branch_name": "refs/heads/master", "committer_date": 1618932681000, "content_id": "bef1e3818c8db408fa779b2b16bf07b6ff794e1a", "detected_licenses": [ "Apache-2.0" ], "directory_id": "744d7561fa7dfe29c2730a9c65fc1862cfb52b56", "extension": "py", "filename": "emb_to_json_for_input_to_OpenKE.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 143968845, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 674, "license": "Apache-2.0", "license_type": "permissive", "path": "/emb_to_json_for_input_to_OpenKE.py", "provenance": "stack-edu-0054.json.gz:576681", "repo_name": "why2011btv/Dolores_AKBC20", "revision_date": 1618932681000, "revision_id": "3778fcd8b425e8f44f4f8bf44562110d25ee32f7", "snapshot_id": "7710149bbaa800f20d2221e6a4cb0df046928102", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/why2011btv/Dolores_AKBC20/3778fcd8b425e8f44f4f8bf44562110d25ee32f7/emb_to_json_for_input_to_OpenKE.py", "visit_date": "2023-04-04T05:54:49.877548" }
2.3125
stackv2
import pickle with open("/home/why2011btv/predicted_logit.txt",'rb') as file: bb = pickle.load(file) print(bb) import h5py import json outfile = '/home/why2011btv/KG-embedding/20180727.hdf5' with h5py.File(outfile, 'r') as fin: a = fin['embedding'][...] ent_emb = a[0:14541,:] rel_emb = a[14541:14778,:] emb_dict = {} emb_dict['ent_embeddings'] = ent_emb emb_dict['rel_embeddings'] = rel_emb ent_list = ent_emb.tolist() rel_list = rel_emb.tolist() emb_dict = {} emb_dict['ent_embeddings'] = ent_list emb_dict['rel_embeddings'] = rel_list with open('/home/why2011btv/KG-embedding/my_emb.json', 'w') as emb_myjson: json.dump(emb_dict,emb_myjson)
28
23.11
74
9
232
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_bdb3a3126c8445d3_1fc32927", "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": 3, "line_end": 3, "column_start": 10, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/bdb3a3126c8445d3.py", "start": {"line": 3, "col": 10, "offset": 87}, "end": {"line": 3, "col": 27, "offset": 104}, "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_bdb3a3126c8445d3_ab520080", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 26, "line_end": 26, "column_start": 6, "column_end": 60, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/bdb3a3126c8445d3.py", "start": {"line": 26, "col": 6, "offset": 565}, "end": {"line": 26, "col": 60, "offset": 619}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 3 ]
[ 3 ]
[ 10 ]
[ 27 ]
[ "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format." ]
[ 5 ]
[ "LOW" ]
[ "MEDIUM" ]
emb_to_json_for_input_to_OpenKE.py
/emb_to_json_for_input_to_OpenKE.py
why2011btv/Dolores_AKBC20
Apache-2.0
2024-11-18T21:10:30.215510+00:00
1,618,935,083,000
2718eac861fa14f3c8156e013f30f8e8f5baa12f
2
{ "blob_id": "2718eac861fa14f3c8156e013f30f8e8f5baa12f", "branch_name": "refs/heads/main", "committer_date": 1618935083000, "content_id": "5754e81bd8fdb01a30ff6d5936477b24ac1ec259", "detected_licenses": [ "MIT" ], "directory_id": "595fc0fb6985bc58dd1a610e0662064a33dd8795", "extension": "py", "filename": "cmsid.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": 4148, "license": "MIT", "license_type": "permissive", "path": "/CMSID/cmsid.py", "provenance": "stack-edu-0054.json.gz:576684", "repo_name": "yanghaoi/Train-2018-2020", "revision_date": 1618935083000, "revision_id": "afb6ae70fe338cbe55a21b74648d91996b818fa2", "snapshot_id": "ff091f4d173ddfb64880b3d97ba0a673d035500a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/yanghaoi/Train-2018-2020/afb6ae70fe338cbe55a21b74648d91996b818fa2/CMSID/cmsid.py", "visit_date": "2023-04-16T17:37:27.022152" }
2.3125
stackv2
#!/usr/bin/python3 #-*- coding:utf-8 -*- import time from datetime import datetime import requests import json import argparse import sys import platform import shutil import os import random banner_font = ''' Author : Dxvistxr CMS Identificator With API => \033[1;96mhttps://whatcms.org\033[00m 2019 ''' def check_platform(): if 'Linux' not in platform.platform(): sys.exit('[*] Linux Required !') def check_python_version(): version_py = sys.version[0] if '3' not in version_py: print(banner_font) sys.exit('\033[1;91m[*] Please Run cmsid.py with python3') def check_internet(): try: print('[*] Checking Internet Connection...') check_internet = requests.get('https://www.google.com') print('[*] Internet : \033[1;92mFound !') except Exception as error_internet: print('[*] Internet Not \033[1;91mFound !') sys.exit('\033[1;91m[!] Exiting') def send_requests(key,target): try: check_internet() r = requests.get('https://whatcms.org/APIEndpoint/Detect?key=%s&url=%s' % (key,target)) content_requests = r.text obj = json.loads(content_requests) req = obj['request'] req_web = obj['request_web'] code = obj['result']['code'] msg = obj['result']['msg'] id = obj['result']['id'] name = obj['result']['name'] confidence = obj['result']['confidence'] cms_url = obj['result']['cms_url'] t = datetime.now().strftime('%H:%M:%S') print('\033[1;92m[\033[1;94m*\033[1;92m] \033[1;96m Requests Sent At \033[1;92m%s\033[00m' % (t)) print('\033[1;92m[\033[1;94m*\033[1;92m] \033[1;93mRequests SuccessFull !\033[00m') print('\033[1;92m[\033[1;94m*\033[1;92m] \033[1;92mRequest : \033[1;96m%s' % (req)) print('\033[1;92m[\033[1;94m*\033[1;92m] \033[1;92mRequests Web : \033[1;96m%s' % (req_web)) print('\033[1;92m[\033[1;94m*\033[1;92m] \033[1;92mStatus Code : \033[1;96m%s' % (code)) print('\033[1;92m[\033[1;94m*\033[1;92m] \033[1;92mCMS Status : \033[1;96m%s' % (msg)) print('\033[1;92m[\033[1;94m*\033[1;92m] \033[1;92mID Status : \033[1;96m%s' % (id)) print('\033[1;92m[\033[1;94m*\033[1;92m] \033[1;92mCMS Name : \033[1;96m%s' % (name)) print('\033[1;92m[\033[1;94m*\033[1;92m] \033[1;92mConfidence : \033[1;96m%s' % (confidence)) print('\033[1;92m[\033[1;94m*\033[1;92m] \033[1;92mCMS URL : \033[1;96m%s\033[00m' % (cms_url)) except Exception as error_send_requests: print(error_send_requests) def banner_show(): try: check_cowsay = shutil.which('cowsay') if check_cowsay ==None: print('\033[1;91m[!] Cowsay Not Found !') os.system('apt update && apt install cowsay -y') os.system('cowsay CMS ID V1.0 By Dxvistxr') else: theme1 = 'cowsay CMS ID v1.0' theme2 = 'cowsay -f eyes CMS ID v1.0' theme3 = 'cowsay -f tux CMS ID v1.0' theme4 = 'cowsay -f bud-frogs CMS ID v1.0' choice_banner = [theme1,theme2,theme3,theme4] random_choice_banner = random.choice(choice_banner) if random_choice_banner ==theme1: os.system(random_choice_banner) print(banner_font) elif random_choice_banner ==theme2: os.system(random_choice_banner) print(banner_font) elif random_choice_banner ==theme3: os.system(random_choice_banner) print(banner_font) elif random_choice_banner ==theme4: os.system(random_choice_banner) print(banner_font) except Exception as error_banner: print(error_banner) def main(): check_platform() check_python_version() banner_show() parser = argparse.ArgumentParser() parser.add_argument('key',type=str,help='Set API Key') parser.add_argument('url',type=str,help='Set Target Url') args = parser.parse_args() send_requests(args.key,args.url) if __name__ == '__main__': main()
121
33.28
105
15
1,425
python
[{"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_c2a98d0f0a1f84cc_3cda127a", "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": 37, "line_end": 37, "column_start": 26, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmpr7mo7ysm/c2a98d0f0a1f84cc.py", "start": {"line": 37, "col": 26, "offset": 728}, "end": {"line": 37, "col": 64, "offset": 766}, "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_c2a98d0f0a1f84cc_eac27104", "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('https://www.google.com', timeout=30)", "location": {"file_path": "unknown", "line_start": 37, "line_end": 37, "column_start": 26, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpr7mo7ysm/c2a98d0f0a1f84cc.py", "start": {"line": 37, "col": 26, "offset": 728}, "end": {"line": 37, "col": 64, "offset": 766}, "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('https://www.google.com', 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_c2a98d0f0a1f84cc_46731761", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-raise-for-status", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "remediation": "", "location": {"file_path": "unknown", "line_start": 48, "line_end": 48, "column_start": 13, "column_end": 96, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmpr7mo7ysm/c2a98d0f0a1f84cc.py", "start": {"line": 48, "col": 13, "offset": 1031}, "end": {"line": 48, "col": 96, "offset": 1114}, "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_c2a98d0f0a1f84cc_57885330", "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('https://whatcms.org/APIEndpoint/Detect?key=%s&url=%s' % (key,target), timeout=30)", "location": {"file_path": "unknown", "line_start": 48, "line_end": 48, "column_start": 13, "column_end": 96, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpr7mo7ysm/c2a98d0f0a1f84cc.py", "start": {"line": 48, "col": 13, "offset": 1031}, "end": {"line": 48, "col": 96, "offset": 1114}, "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('https://whatcms.org/APIEndpoint/Detect?key=%s&url=%s' % (key,target), timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_c2a98d0f0a1f84cc_74a7fb80", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 90, "line_end": 90, "column_start": 17, "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://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpr7mo7ysm/c2a98d0f0a1f84cc.py", "start": {"line": 90, "col": 17, "offset": 3270}, "end": {"line": 90, "col": 48, "offset": 3301}, "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_c2a98d0f0a1f84cc_e24cea9c", "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": 94, "line_end": 94, "column_start": 17, "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://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpr7mo7ysm/c2a98d0f0a1f84cc.py", "start": {"line": 94, "col": 17, "offset": 3402}, "end": {"line": 94, "col": 48, "offset": 3433}, "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_c2a98d0f0a1f84cc_ef000e55", "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": 98, "line_end": 98, "column_start": 17, "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://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpr7mo7ysm/c2a98d0f0a1f84cc.py", "start": {"line": 98, "col": 17, "offset": 3534}, "end": {"line": 98, "col": 48, "offset": 3565}, "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_c2a98d0f0a1f84cc_4801ca9d", "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": 102, "line_end": 102, "column_start": 17, "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://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpr7mo7ysm/c2a98d0f0a1f84cc.py", "start": {"line": 102, "col": 17, "offset": 3666}, "end": {"line": 102, "col": 48, "offset": 3697}, "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"}}}]
8
true
[ "CWE-78", "CWE-78", "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-call-audit" ]
[ "security", "security", "security", "security" ]
[ "LOW", "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH", "HIGH" ]
[ 90, 94, 98, 102 ]
[ 90, 94, 98, 102 ]
[ 17, 17, 17, 17 ]
[ 48, 48, 48, 48 ]
[ "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 ]
[ "LOW", "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH", "HIGH" ]
cmsid.py
/CMSID/cmsid.py
yanghaoi/Train-2018-2020
MIT
2024-11-18T21:10:31.037998+00:00
1,474,702,247,000
7ae80e700f5cf26a6c91661f9c6968256331cb8f
3
{ "blob_id": "7ae80e700f5cf26a6c91661f9c6968256331cb8f", "branch_name": "refs/heads/master", "committer_date": 1474702247000, "content_id": "c860aa871017f7d9b1f88c0b2c76497cd01c1711", "detected_licenses": [ "MIT" ], "directory_id": "0aff3315794d87dc1d9caeb9bb049155fcec7ed8", "extension": "py", "filename": "get_map_layer_images.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 26502865, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2126, "license": "MIT", "license_type": "permissive", "path": "/src/phantomjs/get_map_layer_images.py", "provenance": "stack-edu-0054.json.gz:576693", "repo_name": "monkut/safecasttiles", "revision_date": 1474702247000, "revision_id": "a0b2c18ec83d2b33e539be93bb5d197e12bf5fce", "snapshot_id": "f20a2e5a48b8c980b4a5c63f7e5624599e8caebf", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/monkut/safecasttiles/a0b2c18ec83d2b33e539be93bb5d197e12bf5fce/src/phantomjs/get_map_layer_images.py", "visit_date": "2021-01-22T10:07:37.150778" }
3.21875
stackv2
""" Create png image of map given a url containing Layers """ import os import json from urllib.request import urlopen import subprocess def create_map_layer_image(url, layername, output_dir): output_filename = "{}.png".format(layername) output_filepath = os.path.join(os.path.abspath(output_dir), output_filename) cmd = ( "phantomjs", "./makepng.js", url, output_filepath ) print("command: ", " ".join(cmd)) subprocess.check_call(cmd) return output_filepath if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("-l", "--layersurl", dest="layersurl", default=None, required=True, help="URL of link to JSON map layers list") parser.add_argument("-m", "--mapurl", dest="mapurl", default=None, required=True, help="URL of map accepting '?layer=<layername>' querystring") parser.add_argument("-o", "--outputdir", dest="outputdir", default=".", ) parser.add_argument("-n", "--name", dest="layername", default=None, help="If given an image will only be generated for the given layername") args = parser.parse_args() if args.layername: layer_url = "{}?layer={}".format(args.mapurl, args.layername) result_filepath = create_map_layer_image(layer_url, args.layername, args.outputdir) print(result_filepath) else: # get JSON list from layers layers_data = json.loads(urlopen(args.layersurl).read().decode('utf-8')) for layer_data in layers_data: layer_url = "{}?layer={}".format(args.mapurl, layer_data["layername"]) result_filepath = create_map_layer_image(layer_url, layer_data["layername"], args.outputdir) print(result_filepath)
57
36.32
104
18
416
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_eed056013c9b11b9_241d397f", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 20, "line_end": 20, "column_start": 5, "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://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/eed056013c9b11b9.py", "start": {"line": 20, "col": 5, "offset": 486}, "end": {"line": 20, "col": 31, "offset": 512}, "extra": {"message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dynamic-urllib-use-detected_eed056013c9b11b9_baebf896", "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": 53, "line_end": 53, "column_start": 34, "column_end": 57, "code_snippet": "requires login"}, "cwe_id": "CWE-939: Improper Authorization in Handler for Custom URL Scheme", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A", "references": [{"url": "https://cwe.mitre.org/data/definitions/939.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dynamic-urllib-use-detected", "path": "/tmp/tmpr7mo7ysm/eed056013c9b11b9.py", "start": {"line": 53, "col": 34, "offset": 1817}, "end": {"line": 53, "col": 57, "offset": 1840}, "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"}}}]
2
true
[ "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 20 ]
[ 20 ]
[ 5 ]
[ 31 ]
[ "A01:2017 - Injection" ]
[ "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'." ]
[ 7.5 ]
[ "LOW" ]
[ "HIGH" ]
get_map_layer_images.py
/src/phantomjs/get_map_layer_images.py
monkut/safecasttiles
MIT
2024-11-18T21:10:38.584837+00:00
1,618,673,716,000
79449528a034e547fd5498dfe62772b1342e673e
2
{ "blob_id": "79449528a034e547fd5498dfe62772b1342e673e", "branch_name": "refs/heads/master", "committer_date": 1618673716000, "content_id": "f382884490f51edc8f8fdead52da4719a5fc06af", "detected_licenses": [ "MIT" ], "directory_id": "a38af2694402ecdb056fa85be390a6af8ecb4f50", "extension": "py", "filename": "trainQM9.py", "fork_events_count": 5, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 165932383, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10542, "license": "MIT", "license_type": "permissive", "path": "/trainQM9.py", "provenance": "stack-edu-0054.json.gz:576743", "repo_name": "dmzou/SCAT", "revision_date": 1618673716000, "revision_id": "f188c5cf2ae3bd0ea0aaf74259b83225c4738e11", "snapshot_id": "358988ec1122dad2de4130283a57465055cda2fe", "src_encoding": "UTF-8", "star_events_count": 10, "url": "https://raw.githubusercontent.com/dmzou/SCAT/f188c5cf2ae3bd0ea0aaf74259b83225c4738e11/trainQM9.py", "visit_date": "2021-06-13T09:33:14.630331" }
2.4375
stackv2
# -*- coding: utf-8 -*- from rdkit import RDLogger, Chem from rdkit.Chem import MolToSmiles, MolFromSmiles, Draw from rdkit.Chem.QED import qed from chainer_chemistry import datasets from chainer_chemistry.dataset.preprocessors.ggnn_preprocessor import GGNNPreprocessor import numpy as np import networkx as nx import tensorflow as tf import os.path import time from keras.utils import to_categorical import argparse import pickle from scat import * from utils import * from utilMol import * # ============================================================================= # settings # ============================================================================= parser = argparse.ArgumentParser() parser.add_argument("-s", "--scat", help="choose the scattering method 'S'/'D'", default='S') parser.add_argument("-g", "--gaussianization", help="choose the gaussianization method 'W'/'N'", default='N') args = parser.parse_args() # ============================================================================= # prepare data # ============================================================================= num_train = 133885 if not os.path.exists("./qm9.data"): preprocessor = GGNNPreprocessor() dataset, dataset_smiles = datasets.get_qm9(preprocessor, labels=None, return_smiles=True) num_of_data = len(dataset) features = [] adjs = [] for idx in range(num_of_data): atom, adj, labels = dataset[idx] if len(atom) < 9: n_temp = len(atom) atom_temp = np.zeros(9).astype(int) atom_temp[:n_temp] = atom atom_to_append = atom_to_hot(atom_temp) else: atom_to_append = atom_to_hot(atom) if len(atom) < 9: adj_temp = adj[0] + 2 * adj[1] + 3 * adj[2] adj_to_append = np.zeros((9,9)).astype(int) adj_to_append[:n_temp, :n_temp] = adj_temp else: adj_to_append = adj[0] + 2 * adj[1] + 3 * adj[2] features.append( atom_to_append ) adjs.append( adj_to_append ) # make training / validation / testing dataset train_idx = np.random.choice(len(features), size=num_train, replace=False) train_data = [] train_features = [] train_adj = [] for idx in train_idx: train_data.append(dataset_smiles[idx]) train_features.append(features[idx]) train_adj.append(adjs[idx]) with open("./qm9.data", "wb") as f: pickle.dump(train_data, f) pickle.dump(train_features, f) pickle.dump(train_adj, f) else: with open("./qm9.data", "rb") as f: train_data = pickle.load(f) train_features = pickle.load(f) train_adj = pickle.load(f) print("QM9 data loaded.") # ============================================================================= # encoder # ============================================================================= feature_final = [] for idx in range(num_train): G = nx.from_numpy_matrix(train_adj[idx]) if args.scat == 'D': y_features = diffusion_scat( train_features[idx].T, nx.adjacency_matrix(G) ) else: L = nx.linalg.laplacianmatrix.laplacian_matrix(G) lamb, V = np.linalg.eigh(L.toarray()) y_features = getRep(train_features[idx].T, lamb, V) y_features = y_features.reshape(-1) feature_final.append(y_features) feature_final = np.asarray(feature_final) print("Scattering finished.") feature_final = feature_final.reshape((num_train, -1)) if args.gaussianization == 'W': feature_final = gaussianization_whiten(feature_final, pca=True, num_of_components=15*9) else: feature_final = gaussianization_spherize(feature_final, pca=True, num_of_components=15*9) train_mu = np.zeros(np.shape( np.mean(feature_final, axis=0) )) train_cov = np.cov(feature_final.T) feature_final = feature_final.reshape((num_train, 9, -1)) # ============================================================================= # decoder # ============================================================================= dim_atom = 9 dim_bond_type = 4 dim_atom_type = 5 dim_final_feature = 15 dim_final_1 = dim_atom_type dim_final_2 = dim_atom * dim_bond_type * 15 X = tf.placeholder(tf.float32, shape=[None, dim_atom, dim_final_feature]) W1 = tf.Variable(xavier_init([dim_atom * dim_final_feature, 128])) b1 = tf.Variable(tf.zeros(shape=[128])) W11 = tf.Variable(xavier_init([128, 256])) b11 = tf.Variable(tf.zeros(shape=[256])) W12 = tf.Variable(xavier_init([256, 512])) b12 = tf.Variable(tf.zeros(shape=[512])) W13 = tf.Variable(xavier_init([512, dim_atom * dim_final_1])) b13 = tf.Variable(tf.zeros(shape=[dim_atom * dim_final_1])) W2 = tf.Variable(xavier_init([dim_atom * dim_final_feature, 128])) b2 = tf.Variable(tf.zeros(shape=[128])) W21 = tf.Variable(xavier_init([128, 256])) b21 = tf.Variable(tf.zeros(shape=[256])) W22 = tf.Variable(xavier_init([256, 512])) b22 = tf.Variable(tf.zeros(shape=[512])) W23 = tf.Variable(xavier_init([512, dim_final_2])) b23 = tf.Variable(tf.zeros(shape=[dim_final_2])) theta = [W1, b1, W11, b11, W12, b12, W13, b13, W2, b2, W21, b21, W22, b22, W23, b23] def fcn(x): out1 = tf.reshape(x, (-1, dim_atom * dim_final_feature)) out1 = leaky_relu( tf.matmul(out1, W1) + b1 ) out1 = leaky_relu( tf.matmul(out1, W11) + b11 ) out1 = leaky_relu( tf.matmul(out1, W12) + b12 ) out1 = leaky_relu( tf.matmul(out1, W13) + b13 ) out1 = tf.reshape(out1, (-1, dim_atom, dim_final_1)) out2 = tf.reshape(x, (-1, dim_atom * dim_final_feature)) out2 = leaky_relu( tf.matmul(out2, W2) + b2 ) out2 = leaky_relu( tf.matmul(out2, W21) + b21 ) out2 = leaky_relu( tf.matmul(out2, W22) + b22 ) out2 = leaky_relu( tf.matmul(out2, W23) + b23 ) out2 = tf.reshape(out2, [-1, dim_atom, dim_bond_type, 15]) out2 = leaky_relu( tf.matmul(tf.transpose(out2, perm=[0,2,1,3]), tf.transpose(out2, perm=[0,2,3,1])) ) out2 = tf.transpose(out2, perm=[0,2,3,1]) return [out1, out2] Y_adj = tf.placeholder(tf.float32, shape=[None, dim_atom, dim_atom, dim_bond_type]) Y_features = tf.placeholder(tf.float32, shape=[None, dim_atom, dim_atom_type]) fcn_loss_1 = tf.nn.softmax_cross_entropy_with_logits(labels=Y_features, logits=fcn(X)[0]) fcn_loss_2 = tf.nn.softmax_cross_entropy_with_logits(labels=Y_adj, logits=fcn(X)[1]) fcn_loss_2 = tf.matrix_band_part(fcn_loss_2,0,-1) - tf.matrix_band_part(fcn_loss_2,0,0) fcn_loss = tf.reduce_mean(fcn_loss_1) + 2 * tf.reduce_mean(fcn_loss_2) fcn_solver = (tf.train.AdamOptimizer(learning_rate=0.001) .minimize(fcn_loss, var_list=theta)) train_adj_array = to_categorical(np.asarray(train_adj), num_classes=dim_bond_type) train_features_array = np.transpose(np.asarray(train_features), axes=[0,2,1]) random_idx = list(range(num_train)) shuffle(random_idx) feature_final = feature_final[random_idx] train_adj_array = train_adj_array[random_idx] train_features_array = train_features_array[random_idx] sess = tf.Session() sess.run(tf.global_variables_initializer()) num_epoch = 300 for it in range(num_epoch): for i_batch in range(round(num_train/num_epoch)+1): train_sample = feature_final[i_batch * num_epoch : (i_batch+1) * num_epoch] train_adj_sample = train_adj_array[i_batch * num_epoch : (i_batch+1) * num_epoch] train_features_sample = train_features_array[i_batch * num_epoch : (i_batch+1) * num_epoch] _, loss_curr = sess.run( [fcn_solver, fcn_loss], feed_dict={X: train_sample, Y_features: train_features_sample, Y_adj: train_adj_sample} ) if it % 10 == 0: print('Iter: {}; loss: {:.4}' .format(it, loss_curr)) print("Training finished.") # ============================================================================= # evaluation # ============================================================================= z = [] if args.gaussianization == 'W': for _ in range(100000): z_sample = sample_z(dim_atom * dim_final_feature).reshape(dim_atom,-1) z.append(z_sample) z = np.asarray(z) else: z = sample_z_full(mu=train_mu, cov=train_cov, size=100000).reshape(100000, dim_atom, -1) samples = sess.run(fcn(X), feed_dict={X: z}) samples[0] = np.argmax(samples[0], axis=2) samples[1] = np.argmax(samples[1], axis=3) samples[1] = sess.run(samples[1] - tf.matrix_band_part(samples[1],0,0)) num_of_sample = 10000 atom_dict = {0: 'C', 1: 'O', 2: 'N', 3: 'F'} mols = [] for idx in range(100000): node_list = samples[0][idx,:] adjacency_matrix = samples[1][idx,:,:] where_to_cut = np.where(node_list != 4) node_list = node_list[where_to_cut] adjacency_matrix = adjacency_matrix[where_to_cut].T[where_to_cut] node_name = [] for idx_node in range(len(node_list)): node_name.append(atom_dict[node_list[idx_node]]) mol = MolFromGraphs(node_name, adjacency_matrix) if not '.' in MolToSmiles(mol): mols.append(mol) if len(mols) == num_of_sample: break ''' validity check ''' num_valid = 0 svgs = [] qeds = np.zeros(num_of_sample) for idx in range(num_of_sample): temp = MolFromSmiles(MolToSmiles(mols[idx])) if temp is not None: mols[idx] = temp num_valid += 1 qeds[idx] = qed(mols[idx]) print( "Validity is {:.2%}".format( num_valid/10000 ) ) ''' uniqueness check ''' num_of_unique_gen = len(set([MolToSmiles(mol) for mol in mols])) print( "Uniqueness is {:.2%}".format( num_of_unique_gen / num_of_sample ) ) ''' novelty check ''' data_tgt = [MolFromSmiles(i) for i in train_data] data_tgt += mols num_of_novel = len(set([MolToSmiles(mol) for mol in data_tgt])) + num_of_sample - len(train_data) - num_of_unique_gen print( "Novelty is {:.2%}".format( num_of_novel / num_of_sample ) ) # ============================================================================= # draw, optional # ============================================================================= # mols_unique = list(set([MolToSmiles(mol) for mol in mols])) # mols_unique = [MolFromSmiles(mol) for mol in mols_unique] # mols_uv = [] # qeds_uv = [] # for idx in range(len(mols_unique)): # temp = mols_unique[idx] # if temp is not None: # mols_uv.append(temp) # qeds_uv.append(qed(temp)) # img = Draw.MolsToGridImage(mols_uv[:25], molsPerRow=5, legends=[str("{:10.4f}".format(x)) for x in qeds_uv]) # img
306
33.45
117
15
2,867
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_404f6e8fdac85e65_13ea4952", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 78, "line_end": 78, "column_start": 9, "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/tmpr7mo7ysm/404f6e8fdac85e65.py", "start": {"line": 78, "col": 9, "offset": 2470}, "end": {"line": 78, "col": 35, "offset": 2496}, "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_404f6e8fdac85e65_800cd07f", "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": 79, "line_end": 79, "column_start": 9, "column_end": 39, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/404f6e8fdac85e65.py", "start": {"line": 79, "col": 9, "offset": 2505}, "end": {"line": 79, "col": 39, "offset": 2535}, "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_404f6e8fdac85e65_b82c71fc", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 80, "line_end": 80, "column_start": 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/tmpr7mo7ysm/404f6e8fdac85e65.py", "start": {"line": 80, "col": 9, "offset": 2544}, "end": {"line": 80, "col": 34, "offset": 2569}, "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_404f6e8fdac85e65_86646c43", "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": 22, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/404f6e8fdac85e65.py", "start": {"line": 86, "col": 22, "offset": 2660}, "end": {"line": 86, "col": 36, "offset": 2674}, "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_404f6e8fdac85e65_cbf29dc6", "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": 87, "line_end": 87, "column_start": 26, "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/tmpr7mo7ysm/404f6e8fdac85e65.py", "start": {"line": 87, "col": 26, "offset": 2700}, "end": {"line": 87, "col": 40, "offset": 2714}, "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_404f6e8fdac85e65_f39a18fa", "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": 88, "line_end": 88, "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/tmpr7mo7ysm/404f6e8fdac85e65.py", "start": {"line": 88, "col": 21, "offset": 2735}, "end": {"line": 88, "col": 35, "offset": 2749}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-assignment-keyed_404f6e8fdac85e65_30199ad1", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-assignment-keyed", "finding_type": "maintainability", "severity": "low", "confidence": "medium", "message": "key `1` in `samples` is assigned twice; the first assignment is useless", "remediation": "", "location": {"file_path": "unknown", "line_start": 243, "line_end": 244, "column_start": 1, "column_end": 72, "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/tmpr7mo7ysm/404f6e8fdac85e65.py", "start": {"line": 243, "col": 1, "offset": 8357}, "end": {"line": 244, "col": 72, "offset": 8471}, "extra": {"message": "key `1` in `samples` 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"}}}]
7
true
[ "CWE-502", "CWE-502", "CWE-502", "CWE-502", "CWE-502", "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.pyth...
[ "security", "security", "security", "security", "security", "security" ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 78, 79, 80, 86, 87, 88 ]
[ 78, 79, 80, 86, 87, 88 ]
[ 9, 9, 9, 22, 26, 21 ]
[ 35, 39, 34, 36, 40, 35 ]
[ "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" ]
trainQM9.py
/trainQM9.py
dmzou/SCAT
MIT
2024-11-18T21:10:44.227037+00:00
1,382,469,004,000
f37347bab75fd71646ad2028021484f2edb2a38b
3
{ "blob_id": "f37347bab75fd71646ad2028021484f2edb2a38b", "branch_name": "refs/heads/master", "committer_date": 1382469004000, "content_id": "05c6db51d225c3bf912c468d9f274bd636efb1d5", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "04adbf7b2a2e22c37bc8fd034e8fb2071e05491a", "extension": "py", "filename": "file_handling.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": 6395, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/pygrid/file_handling.py", "provenance": "stack-edu-0054.json.gz:576746", "repo_name": "flxb/pygrid", "revision_date": 1382469004000, "revision_id": "0f22cc289b1aee983393930ae81d4cd80e5129ad", "snapshot_id": "f6b16d0d6a2a5786efc8b98ef0dac7da804fa07c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/flxb/pygrid/0f22cc289b1aee983393930ae81d4cd80e5129ad/pygrid/file_handling.py", "visit_date": "2021-01-19T17:48:20.644091" }
2.59375
stackv2
""" Implements most file handling functions for pygrid """ # Copyright (c) 2013 Felix Brockherde # License: BSD import shutil import os from os.path import join as pjoin from os.path import exists as pexists import cPickle as pickle import time try: import numpy except: numpy = None def _save_data(filename, data): if numpy: with open(filename, 'w') as f: if type(data) == dict: numpy.savez(f, **data) else: numpy.save(f, data) else: with open(filename, 'w') as f: pickle.dump(data, f, pickle.HIGHEST_PROTOCOL) def _load_data(filename): if numpy: data = numpy.load(filename) if hasattr(data, 'files'): return dict(data) else: return data else: with open(filename) as f: return pickle.load(f) def _create_folder(temp_folder): os.makedirs(temp_folder) def delete_folder(temp_folder): """ Deletes a PyGrid folder If the folder exists, it must have a ``is_pygrid`` file to avoid accidental deletion of other files. Parameters ---------- temp_folder : string The temporary folder that was given when the job was submitted first. """ if os.path.exists(temp_folder): if os.path.isdir(temp_folder): if os.path.exists(os.path.join(temp_folder, 'is_pygrid')): shutil.rmtree(temp_folder) else: raise ValueError('`' + temp_folder + '` is not a PyGrid ' + 'folder.') else: raise ValueError('`' + temp_folder + '` is not a folder.') def _write_info(temp_folder, function_name, path, module, cluster_params, njobs): with open(pjoin(temp_folder, 'info'), 'w') as f: pickle.dump({'function_name': function_name, 'path': path, 'module': module, 'cluster_params': cluster_params, 'timestamp': time.time(), 'njobs': njobs}, f, pickle.HIGHEST_PROTOCOL) def _get_info(temp_folder): with open(pjoin(temp_folder, 'info')) as f: return pickle.load(f) def _write_files(temp_folder, args): # find args that are common for every job common_args = {} for key in args[0]: if all(key in arg and id(args[0][key]) == id(arg[key]) for arg in args): common_args[key] = args[0][key] for key in common_args: for arg in args: del arg[key] # write common args if len(common_args) > 0: _save_data(pjoin(temp_folder, 'common_args'), common_args) # write individual args for i, arg in enumerate(args): if len(arg) > 0: _save_data(pjoin(temp_folder, 'args_' + str(i)), arg) # touch is_pygrid file open(pjoin(temp_folder, 'is_pygrid'), 'w').close() def get_results(temp_folder): """ Returns the job results Parameters ---------- temp_folder : string The temporary folder that was given when the job was submitted first. Returns ------- output : list A list with the results for each job. Each item in the list corresponds to the item in the ``args`` list from input. If the job failed or was not finished, the value will be None. """ if not os.path.exists(temp_folder): return None info = _get_info(temp_folder) results = [] for i in range(info['njobs']): try: results.append(_load_data(pjoin(temp_folder, 'result_' + str(i)))) except IOError: results.append(None) return results def _get_job_args(temp_folder, id, common_args): if pexists(pjoin(temp_folder, 'args_' + str(id))): return dict(_load_data(pjoin(temp_folder, 'args_' + str(id))), **common_args) else: return common_args def _get_common_args(temp_folder): if pexists(pjoin(temp_folder, 'common_args')): return _load_data(pjoin(temp_folder, 'common_args')) else: return {} def get_args(temp_folder): """ Return the original args Parameters ---------- temp_folder : string The temporary folder that was given when the job was submitted first. Returns ------- output : list The ``args`` list given when the job was submitted first. """ info = _get_info(temp_folder) common_args = _get_common_args(temp_folder) args = [] for i in range(info['njobs']): args.append(_get_job_args(temp_folder, i, common_args)) return args def _write_job_map(temp_folder, qid, ids): # write file that maps the cluster job tasks to jobs from the args list with open(os.path.join(temp_folder, 'submit_map_' + qid), 'w') as f: f.write(' '.join([str(id) for id in ids])) def _get_job_map(temp_folder, qid): # write file that maps the cluster job tasks to jobs from the args list with open(os.path.join(temp_folder, 'submit_map_' + qid)) as f: return [int(id) for id in f.read().split()] def _get_qids(temp_folder): with open(os.path.join(temp_folder, 'qids')) as f: return f.read().split() def delete_all_folders(root): """ Deletes all PyGrid folders under a given path The function walks through the directory structure and identifies all PyGrid folders. It then asks for each one if it should be deleted and then deletes the selected folders. Parameters ---------- temp_folder : string The temporary folder that was given when the job was submitted first. """ folders = [] print('Searching for pygrid folders...') for folder, dirs, files in os.walk(root): if 'is_pygrid' in files: info = _get_info(folder) folders.append((folder, info['timestamp'])) folders.sort(key=lambda (folder, timestamp): timestamp) delete = [] for folder, timestamp in folders: a = raw_input('Delete folder ' + folder + ' (Created ' + time.strftime('%d %b %Y', time.localtime(timestamp)) + ')? y/[n] ') if len(a) > 0 and a[0].lower() == 'y': delete.append(folder) for folder in delete: print('Deleting ' + folder + ' ...') delete_folder(folder)
222
27.81
79
18
1,470
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_592eddf781093d51_a7196b10", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 20, "line_end": 20, "column_start": 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/tmpr7mo7ysm/592eddf781093d51.py", "start": {"line": 20, "col": 14, "offset": 355}, "end": {"line": 20, "col": 33, "offset": 374}, "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_592eddf781093d51_ab4746ed", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 26, "line_end": 26, "column_start": 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/tmpr7mo7ysm/592eddf781093d51.py", "start": {"line": 26, "col": 14, "offset": 532}, "end": {"line": 26, "col": 33, "offset": 551}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_592eddf781093d51_1db014f6", "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": 27, "line_end": 27, "column_start": 13, "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-cPickle", "path": "/tmp/tmpr7mo7ysm/592eddf781093d51.py", "start": {"line": 27, "col": 13, "offset": 570}, "end": {"line": 27, "col": 58, "offset": 615}, "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_592eddf781093d51_17ebe365", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 27, "line_end": 27, "column_start": 13, "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/tmpr7mo7ysm/592eddf781093d51.py", "start": {"line": 27, "col": 13, "offset": 570}, "end": {"line": 27, "col": 58, "offset": 615}, "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_592eddf781093d51_40f82fd3", "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": 14, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/592eddf781093d51.py", "start": {"line": 38, "col": 14, "offset": 820}, "end": {"line": 38, "col": 28, "offset": 834}, "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_592eddf781093d51_ee744262", "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": 39, "line_end": 39, "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-cPickle", "path": "/tmp/tmpr7mo7ysm/592eddf781093d51.py", "start": {"line": 39, "col": 20, "offset": 860}, "end": {"line": 39, "col": 34, "offset": 874}, "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_592eddf781093d51_7e22ffc2", "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": 39, "line_end": 39, "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/tmpr7mo7ysm/592eddf781093d51.py", "start": {"line": 39, "col": 20, "offset": 860}, "end": {"line": 39, "col": 34, "offset": 874}, "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_592eddf781093d51_fae3503e", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 70, "line_end": 70, "column_start": 10, "column_end": 47, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/592eddf781093d51.py", "start": {"line": 70, "col": 10, "offset": 1778}, "end": {"line": 70, "col": 47, "offset": 1815}, "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_592eddf781093d51_728d1a3f", "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": 71, "line_end": 76, "column_start": 9, "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/tmpr7mo7ysm/592eddf781093d51.py", "start": {"line": 71, "col": 9, "offset": 1830}, "end": {"line": 76, "col": 66, "offset": 2116}, "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_592eddf781093d51_9c69a9c7", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 71, "line_end": 76, "column_start": 9, "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/tmpr7mo7ysm/592eddf781093d51.py", "start": {"line": 71, "col": 9, "offset": 1830}, "end": {"line": 76, "col": 66, "offset": 2116}, "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_592eddf781093d51_205eb4c6", "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": 80, "line_end": 80, "column_start": 10, "column_end": 42, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/592eddf781093d51.py", "start": {"line": 80, "col": 10, "offset": 2156}, "end": {"line": 80, "col": 42, "offset": 2188}, "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_592eddf781093d51_dd9f4a37", "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": 81, "line_end": 81, "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/tmpr7mo7ysm/592eddf781093d51.py", "start": {"line": 81, "col": 16, "offset": 2210}, "end": {"line": 81, "col": 30, "offset": 2224}, "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_592eddf781093d51_3e278817", "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": 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/tmpr7mo7ysm/592eddf781093d51.py", "start": {"line": 81, "col": 16, "offset": 2210}, "end": {"line": 81, "col": 30, "offset": 2224}, "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_592eddf781093d51_f57826da", "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": 105, "line_end": 105, "column_start": 5, "column_end": 47, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/592eddf781093d51.py", "start": {"line": 105, "col": 5, "offset": 2882}, "end": {"line": 105, "col": 47, "offset": 2924}, "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_592eddf781093d51_1b3ee930", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 176, "line_end": 176, "column_start": 10, "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/tmpr7mo7ysm/592eddf781093d51.py", "start": {"line": 176, "col": 10, "offset": 4803}, "end": {"line": 176, "col": 67, "offset": 4860}, "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_592eddf781093d51_34035737", "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": 182, "line_end": 182, "column_start": 10, "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/tmpr7mo7ysm/592eddf781093d51.py", "start": {"line": 182, "col": 10, "offset": 5041}, "end": {"line": 182, "col": 62, "offset": 5093}, "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_592eddf781093d51_9f4f5113", "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": 187, "line_end": 187, "column_start": 10, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/592eddf781093d51.py", "start": {"line": 187, "col": 10, "offset": 5191}, "end": {"line": 187, "col": 49, "offset": 5230}, "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"}}}]
17
true
[ "CWE-502", "CWE-502", "CWE-502", "CWE-502", "CWE-502", "CWE-502", "CWE-502", "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-cPickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-cPickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-cPickle", "rules.p...
[ "security", "security", "security", "security", "security", "security", "security", "security" ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 27, 27, 39, 39, 71, 71, 81, 81 ]
[ 27, 27, 39, 39, 76, 76, 81, 81 ]
[ 13, 13, 20, 20, 9, 9, 16, 16 ]
[ 58, 58, 34, 34, 66, 66, 30, 30 ]
[ "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserial...
[ "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "Avoid using `pickle`, which is known to lead t...
[ 5, 5, 5, 5, 5, 5, 5, 5 ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
file_handling.py
/pygrid/file_handling.py
flxb/pygrid
BSD-2-Clause
2024-11-18T21:10:47.375780+00:00
1,418,777,182,000
b868ac0f2b137bdb45cd633a6fdb8f4c7e30f0f8
2
{ "blob_id": "b868ac0f2b137bdb45cd633a6fdb8f4c7e30f0f8", "branch_name": "refs/heads/master", "committer_date": 1418777182000, "content_id": "17c06cbb69504005a99e8f619f85f3cb1b75de22", "detected_licenses": [ "MIT" ], "directory_id": "ff1dd6cdc43d3dd0afbc5c86b3aae80cfc85aba2", "extension": "py", "filename": "populate.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": 12965, "license": "MIT", "license_type": "permissive", "path": "/IsPepsiOkay/database/populate.py", "provenance": "stack-edu-0054.json.gz:576763", "repo_name": "kharddie/is-pepsi-okay", "revision_date": 1418777182000, "revision_id": "48b557c848b572ac3bf71046de9645225b73130e", "snapshot_id": "d164404d1a7932fade08cf72a0e3996758266c2e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kharddie/is-pepsi-okay/48b557c848b572ac3bf71046de9645225b73130e/IsPepsiOkay/database/populate.py", "visit_date": "2021-12-04T00:33:21.381549" }
2.40625
stackv2
#!/usr/bin/env python import os import MySQLdb import sys import re import wikipedia from bs4 import BeautifulSoup PROJECT_DIR = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) DATA_DIR = os.path.abspath( os.path.join(PROJECT_DIR, '..', 'data')) sys.path.insert(0, PROJECT_DIR) from config import BaseConfig db = MySQLdb.connect( host=BaseConfig.MYSQL_DATABASE_HOST, user=BaseConfig.MYSQL_DATABASE_USER, passwd=BaseConfig.MYSQL_DATABASE_PASSWORD, db=BaseConfig.MYSQL_DATABASE_DB, charset='utf8', use_unicode=True) cur = db.cursor() def free_mem(): dont = ['os','MySQLdb','sys','re','wikipedia','BeautifulSoup', 'PROJECT_DIR','DATA_DIR','BaseConfig','db','cur'] a = [] for var in globals(): if "__" not in (var[:2],var[-2:]) and var not in dont: a.append(var) print a for var in a: del globals()[var] ACTOR_QUERY = """INSERT INTO People (pname,pdob) VALUES """ # Code to generate Actor File Structure with open(DATA_DIR + '/uci/actors.html.better', 'r') as f: count = 0 soup = BeautifulSoup(f.read()) tbl = soup.findAll('table') for table in tbl: for row in table.findAll('tr')[1:]: cells = row.findAll('td') if len(cells) > 0: name = cells[0].contents[0][1:].replace('"','\"').replace("'",'\"').replace('`','\"')#.encode('ascii','replace') ACTOR_QUERY += "('%s'" % (name) dob = '0000-00-00' if len(cells) > 5: dob = cells[5].contents[0][:] try: dob = int(dob) dob = "%d-01-01" % (dob) except: dob = '0000-00-00' #try: # content = wikipedia.page(name).html() # birth_year = int(re.match('.*born.*(\d{4})', content, re.DOTALL).group(1)) # print name + ' ' + str(birth_year) # dob = '%d-01-01' % (birth_year) #except: # pass ACTOR_QUERY += ",'%s')," % (dob) count += 1 if not count % 10: print count ACTOR_QUERY = ACTOR_QUERY[:-1] + ";" del soup, tbl print 'Executing Actor Query...' cur.execute(ACTOR_QUERY) db.commit() ######### PEOPLE_QUERY = """INSERT INTO People (pname,pdob) VALUES """ with open(DATA_DIR + '/uci/people.html', 'r') as f: count = 0 soup = BeautifulSoup(f.read()) tbl = soup.findAll('table') for table in tbl: for row in table.findAll('tr')[1:]: cells = row.findAll('td') if len(cells) > 6: #if 'A' not in ''.join(cells[1].contents): if True: first_name = cells[5].contents[0][1:].replace('"','\"').replace("'",'\"').replace('`','\"') last_name = cells[4].contents[0][1:].replace('"','\"').replace("'",'\"').replace('`','\"') PEOPLE_QUERY += "('%s %s'" % (first_name, last_name) dob = '0000-00-00' dob = cells[6].contents[0][:] try: dob = int(dob) dob = "%d-01-01" % (dob) except: dob = '0000-00-00' PEOPLE_QUERY += ",'%s')," % (dob) count += 1 if not count % 10: print str(count) PEOPLE_QUERY = PEOPLE_QUERY [:-1] + ";" del soup, tbl, f print 'Executing People Query...' cur.execute(PEOPLE_QUERY) db.commit() #################### def wiki_parse(sidebar, header_text, multiple=0): try: strs = [] elem = sidebar.find('th', text=header_text).parent.find('td') if not multiple: for s in elem.stripped_strings: # only return first one return s.replace("'","''") for s in elem.stripped_strings: strs.append(s.replace("'","''")) return strs #else: # return elem.text.strip() except: if not multiple: return '' return [] def grab_col(tr, col_num): text = tr.xpath('./td[%d]//text()' % (col_num)) if text: text = text[0].strip().replace("'","''") return text return '' def repr_int(s): try: int(s) return True except ValueError: return False except TypeError: return False except: return False def closest_wiki_page(title, year): search = wikipedia.search(title) if search: if title in search[0] or 'film' in search[0]: return wikipedia.page(title) def convert_to_int(s): if not s: return 0 regex = re.compile(ur'[0-9\,]+',re.UNICODE) cl = s.replace('$','').replace(',','') try: i = int(cl) except ValueError: if 'million' in cl: pars = cl.split() try: i = int(float(pars[0]) * 1000000.) return i except ValueError: i = regex.search(cl) if i: i = int(float(i.group(0)) * 1000000.) return i i = regex.search(cl) if i: return i.group(0) return 0 def convert_runtime(r): if not r: return 0 regex = re.compile('\d+', re.UNICODE) if 'minutes' in r: m = regex.search(r) if m: m = m.group(0) try: return int(m) except: print m + ' WTFFFFFFFFFF' return 0 if 'hours' in r: m = regex.search(r) if m: m = m.group(0) try: return int(float(m) * 60.) except: print m + ' WTFFFFFFFFFFFFFFFFFF' return 0 print r + '\tdafuq' return 0 #free_mem() from lxml import etree movie_attrs = "mid,title,mdate,runtime,languages,description,budget,box_office,country" MOVIE_QUERY = """INSERT INTO Movies (%s) VALUES """ % (movie_attrs) GENRE_QUERY = """INSERT INTO Genres (gname) VALUES """ PERSON_QUERY = """INSERT INTO People (pname) VALUES """ IS_GENRE_QUERY = """INSERT INTO Is_Genre (mid,gid) VALUES """ involved_attrs = "pid,mid,directed,produced,wrote,composed,acted" INVOLVED_IN_QUERY = """INSERT INTO Involved_In (%s) VALUES """ % (involved_attrs) def check_exists(cur, table, pkname, chkname, chkval): qry = """SELECT %s FROM %s WHERE %s='%s';""" % (pkname, table, chkname, chkval) print qry cur.execute(qry) r = cur.fetchone() print 'exists' + str(r) if not r: return False try: r = r[0] return r except TypeError: return r print 'Starting Main Movie Data' import gc gc.collect() #with open(DATA_DIR + '/uci/main.html', 'r') as f: # doc = etree.HTML(f.read()) # for tr in doc.xpath('//table/tr'): # mid = grab_col(tr, 1) # print 'mid ' + mid # if not mid: # continue # if not check_exists(cur, 'Movies', 'mid', 'mid', mid): # continue # if check_exists(cur, 'Is_Genre', 'mid', 'mid', mid): # continue # genres = grab_col(tr, 8).split(',') # while genres: # genre = genres.pop().strip() # ggg = check_exists(cur, 'Genres', 'gid', 'gname', genre) # if ggg: # igq = IS_GENRE_QUERY + "('%s',%s);" % (mid, ggg) # print igq # cur.execute(igq) # else: # gq = GENRE_QUERY + "('%s');" % (genre) # print gq # cur.execute(gq) # gid = int(cur.lastrowid) # igq = IS_GENRE_QUERY + "('%s',%s);" % (mid,gid) # print igq # cur.execute(igq) with open(DATA_DIR + '/uci/main.html', 'r') as f: count = 1 doc = etree.HTML(f.read()) tmpp = False for tr in doc.xpath('//table/tr'): mid = grab_col(tr, 1) #if mid == 'AMt10': # tmpp = True #if not tmpp: # print mid # continue if not mid: continue #if check_exists(cur, 'Movies', 'mid', 'mid', mid): # continue title = grab_col(tr, 2) title_orig = title.replace("''","'") if not title or title[0:2] != "T:": continue title = title.split("T:")[1] if not title: continue print '\n\n' + title # if title != "My Cousin Vinny": continue rdate = grab_col(tr, 3) if not repr_int(rdate): continue releasedate = '%s-01-01' % (int(rdate)) genres = grab_col(tr, 8).split(',') print genres if not genres: continue if len(genres) == 1 and not genres[0]: continue gids = [] while genres: genre = genres.pop().strip() ggg = check_exists(cur, 'Genres', 'gid', 'gname', genre) if not ggg: gq = GENRE_QUERY + "('%s');" % (genre) print gq cur.execute(gq) gids.append(int(cur.lastrowid)) else: gids.append(ggg) db.commit() page_name = "%s" % (title_orig) try: wiki = wikipedia.page(page_name) summary = wiki.summary if 'film' not in summary and 'movie' not in summary and 'directed' not in summary: wiki = wikipedia.page(page_name + ' (%s film)' %(rdate)) summary = wiki.summary if rdate not in summary: continue except wikipedia.exceptions.DisambiguationError as e: try: wiki = wikipedia.page(page_name + ' (%s film)' %(rdate)) except: continue except wikipedia.exceptions.PageError as e: continue if wiki and title.lower() in wiki.title.lower(): count += 1 print str(count) + ' ' + title # look for runtime, languages, *keywords, description # *tagline, budget, box_office, *mpaa rating, country wiki_soup = BeautifulSoup(wiki.html()) sidebar = wiki_soup.find('table', {"class": 'infobox vevent'}) description = wiki.summary.replace("'","''") runtime = wiki_parse(sidebar, 'Running time') runtime = convert_runtime(runtime) languages = ','.join(wiki_parse(sidebar, 'Language', True)).replace("'","''") country = ','.join(wiki_parse(sidebar, 'Country', True)).replace("'","''") budget = wiki_parse(sidebar, 'Budget') budget = convert_to_int(budget) box_office = wiki_parse(sidebar, 'Box office') box_office = convert_to_int(box_office) if not runtime and not languages and not country and not budget and not box_office: continue QUERY = MOVIE_QUERY + "('%s','%s','%s',%s,'%s','%s',%s,%s,'%s')" % (mid, title,releasedate,runtime,languages,description,budget,box_office,country) print QUERY cur.execute(QUERY) db.commit() # genre & mid while gids: gid = gids.pop() mg_qry = IS_GENRE_QUERY + "('%s',%s)" % (mid,gid) print mg_qry cur.execute(mg_qry) db.commit() # involvement: direct, produce, write, music, act directed = wiki_parse(sidebar, 'Directed by', True) produced = wiki_parse(sidebar, 'Produced by', True) wrote = wiki_parse(sidebar, 'Written by', True) music = wiki_parse(sidebar, 'Music by', True) starred = wiki_parse(sidebar, 'Starring', True) # set people = set().union(*[directed,produced,wrote,music,starred]) while people: person = people.pop() print person pid = check_exists(cur, 'People', 'pid', 'pname', person) print pid if not pid: pq = PERSON_QUERY + "('%s')" % (person) print pq cur.execute(pq) pid = cur.lastrowid pid = int(pid) db.commit() d = 1 if person in directed else 0 p = 1 if person in produced else 0 w = 1 if person in wrote else 0 c = 1 if person in music else 0 a = 1 if person in starred else 0 ii_qry = INVOLVED_IN_QUERY + "(%s,'%s',%s,%s,%s,%s,%s);" % (pid, mid,d,p,w,c,a) print ii_qry cur.execute(ii_qry) db.commit() cur.close() db.commit() db.close()
409
30.7
128
24
3,235
python
[{"finding_id": "semgrep_rules.python.lang.security.dangerous-globals-use_e858dc3388309c59_f08b968e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.dangerous-globals-use", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 40, "line_end": 40, "column_start": 13, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": "CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.dangerous-globals-use", "path": "/tmp/tmpr7mo7ysm/e858dc3388309c59.py", "start": {"line": 40, "col": 13, "offset": 926}, "end": {"line": 40, "col": 27, "offset": 940}, "extra": {"message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "metadata": {"cwe": ["CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186"], "category": "security", "technology": ["python"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_e858dc3388309c59_cda85bb9", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 44, "line_end": 44, "column_start": 6, "column_end": 53, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/e858dc3388309c59.py", "start": {"line": 44, "col": 6, "offset": 1047}, "end": {"line": 44, "col": 53, "offset": 1094}, "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_e858dc3388309c59_0d3cf3dc", "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": 6, "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/tmpr7mo7ysm/e858dc3388309c59.py", "start": {"line": 85, "col": 6, "offset": 2532}, "end": {"line": 85, "col": 46, "offset": 2572}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_e858dc3388309c59_28032a0f", "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": 222, "line_end": 222, "column_start": 5, "column_end": 21, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/775296/mysql-parameterized-queries", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.formatted-sql-query", "path": "/tmp/tmpr7mo7ysm/e858dc3388309c59.py", "start": {"line": 222, "col": 5, "offset": 6676}, "end": {"line": 222, "col": 21, "offset": 6692}, "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_e858dc3388309c59_915edf38", "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": 222, "line_end": 222, "column_start": 5, "column_end": 21, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpr7mo7ysm/e858dc3388309c59.py", "start": {"line": 222, "col": 5, "offset": 6676}, "end": {"line": 222, "col": 21, "offset": 6692}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_e858dc3388309c59_be425af1", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 269, "line_end": 269, "column_start": 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/tmpr7mo7ysm/e858dc3388309c59.py", "start": {"line": 269, "col": 6, "offset": 7954}, "end": {"line": 269, "col": 44, "offset": 7992}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_e858dc3388309c59_9a1dd738", "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": 309, "line_end": 309, "column_start": 17, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpr7mo7ysm/e858dc3388309c59.py", "start": {"line": 309, "col": 17, "offset": 9187}, "end": {"line": 309, "col": 32, "offset": 9202}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_e858dc3388309c59_7bb56a96", "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": 360, "line_end": 360, "column_start": 13, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpr7mo7ysm/e858dc3388309c59.py", "start": {"line": 360, "col": 13, "offset": 11274}, "end": {"line": 360, "col": 31, "offset": 11292}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_e858dc3388309c59_26f92b3a", "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": 368, "line_end": 368, "column_start": 17, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpr7mo7ysm/e858dc3388309c59.py", "start": {"line": 368, "col": 17, "offset": 11512}, "end": {"line": 368, "col": 36, "offset": 11531}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_e858dc3388309c59_ff4ccf83", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 389, "line_end": 389, "column_start": 21, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpr7mo7ysm/e858dc3388309c59.py", "start": {"line": 389, "col": 21, "offset": 12350}, "end": {"line": 389, "col": 36, "offset": 12365}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_e858dc3388309c59_43854ffc", "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": 403, "line_end": 403, "column_start": 17, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpr7mo7ysm/e858dc3388309c59.py", "start": {"line": 403, "col": 17, "offset": 12880}, "end": {"line": 403, "col": 36, "offset": 12899}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
11
true
[ "CWE-96", "CWE-89", "CWE-89", "CWE-89", "CWE-89", "CWE-89", "CWE-89", "CWE-89" ]
[ "rules.python.lang.security.dangerous-globals-use", "rules.python.lang.security.audit.formatted-sql-query", "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "ru...
[ "security", "security", "security", "security", "security", "security", "security", "security" ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH" ]
[ 40, 222, 222, 309, 360, 368, 389, 403 ]
[ 40, 222, 222, 309, 360, 368, 389, 403 ]
[ 13, 5, 5, 17, 13, 17, 21, 17 ]
[ 27, 21, 21, 32, 31, 36, 36, 36 ]
[ "A03:2021 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "Detected possible formatted SQL query. Use parameterized queries instead.", "Avoiding SQL string concatenation: untr...
[ 5, 5, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5 ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "MEDIUM", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH" ]
populate.py
/IsPepsiOkay/database/populate.py
kharddie/is-pepsi-okay
MIT
2024-11-18T21:10:48.260338+00:00
1,605,326,812,000
b692f4f341c13413deb3bbf81b963a05244419af
3
{ "blob_id": "b692f4f341c13413deb3bbf81b963a05244419af", "branch_name": "refs/heads/master", "committer_date": 1605326812000, "content_id": "4affbbc6e81f8bf3ed4955bc4751c3bfc02c87c9", "detected_licenses": [ "MIT" ], "directory_id": "ffe0f2062021892d3c6c1c14efa8f6646ef8a0ba", "extension": "py", "filename": "server.py", "fork_events_count": 2, "gha_created_at": 1602274139000, "gha_event_created_at": 1603323897000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 302743030, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1637, "license": "MIT", "license_type": "permissive", "path": "/server/server.py", "provenance": "stack-edu-0054.json.gz:576776", "repo_name": "yrahul3910/csc510-project", "revision_date": 1605326812000, "revision_id": "1516dc566485253ca56a98dec1baf18a0e2e5e72", "snapshot_id": "ddb542ab1936b78504da64cb134eff7d87f7939f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/yrahul3910/csc510-project/1516dc566485253ca56a98dec1baf18a0e2e5e72/server/server.py", "visit_date": "2023-01-14T15:26:17.705472" }
2.65625
stackv2
from flask import Flask, request from flask_restful import Resource, Api, reqparse from sqlalchemy import create_engine from json import dumps from flask import jsonify # Connecting to the DB db_connect = create_engine('sqlite:///sample.db') # Creating the application app = Flask(__name__) api = Api(app) # API to get the list of all the empoyees class Employee(Resource): def get(self): conn = db_connect.connect() # connect to database # This line performs query and returns json result query = conn.execute("select * from employees") # Fetches first column that is employee ID return {'employees': [i[0] for i in query.cursor.fetchall()]} # API to get info about an empoyee class Employee_info(Resource): def get(self): conn = db_connect.connect() emp = request.args.get('employee_id') query = conn.execute( "select * from employees where EmployeeId =%d " % int(emp)) result = {'data': [dict(zip(tuple(query.keys()), i)) for i in query.cursor]} return jsonify(result) class SlackEvents(Resource): def __init__(self): self.parser = reqparse.RequestParser() self.parser.add_argument('challenge') def post(self): args = self.parser.parse_args() if 'challenge' in args.keys(): return args['challenge'] # Publishing APIs api.add_resource(Employee, '/employee/list') # Route 1 api.add_resource(Employee_info, '/employee') # Route 2 # Slack APIs api.add_resource(SlackEvents, '/slack/events') if __name__ == '__main__': app.run(port=5002)
58
27.22
71
19
367
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_468df6beb5447607_ee2b5fd7", "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": 32, "line_end": 33, "column_start": 17, "column_end": 72, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 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/tmpr7mo7ysm/468df6beb5447607.py", "start": {"line": 32, "col": 17, "offset": 879}, "end": {"line": 33, "col": 72, "offset": 964}, "extra": {"message": "Detected possible formatted SQL query. Use parameterized queries instead.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "references": ["https://stackoverflow.com/questions/775296/mysql-parameterized-queries"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_468df6beb5447607_e979ebae", "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": 32, "line_end": 33, "column_start": 17, "column_end": 72, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpr7mo7ysm/468df6beb5447607.py", "start": {"line": 32, "col": 17, "offset": 879}, "end": {"line": 33, "col": 72, "offset": 964}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.django.security.injection.tainted-sql-string_468df6beb5447607_5ca12a84", "tool_name": "semgrep", "rule_id": "rules.python.django.security.injection.tainted-sql-string", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected user input used to manually construct a SQL string. This is usually bad practice because manual construction could accidentally result in a SQL injection. An attacker could use a SQL injection to steal or modify contents of the database. Instead, use a parameterized query which is available by default in most database engines. Alternatively, consider using the Django object-relational mappers (ORM) instead of raw SQL queries.", "remediation": "", "location": {"file_path": "unknown", "line_start": 33, "line_end": 33, "column_start": 13, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": "CWE-915: Improperly Controlled Modification of Dynamically-Determined Object Attributes", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A08:2021 - Software and Data Integrity Failures", "references": [{"url": "https://docs.djangoproject.com/en/3.0/topics/security/#sql-injection-protection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.injection.tainted-sql-string", "path": "/tmp/tmpr7mo7ysm/468df6beb5447607.py", "start": {"line": 33, "col": 13, "offset": 905}, "end": {"line": 33, "col": 71, "offset": 963}, "extra": {"message": "Detected user input used to manually construct a SQL string. This is usually bad practice because manual construction could accidentally result in a SQL injection. An attacker could use a SQL injection to steal or modify contents of the database. Instead, use a parameterized query which is available by default in most database engines. Alternatively, consider using the Django object-relational mappers (ORM) instead of raw SQL queries.", "metadata": {"cwe": ["CWE-915: Improperly Controlled Modification of Dynamically-Determined Object Attributes"], "owasp": ["A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "references": ["https://docs.djangoproject.com/en/3.0/topics/security/#sql-injection-protection"], "category": "security", "technology": ["django"], "subcategory": ["audit"], "impact": "LOW", "likelihood": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.injection.tainted-sql-string_468df6beb5447607_41f10b89", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.injection.tainted-sql-string", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Detected user input used to manually construct a SQL string. This is usually bad practice because manual construction could accidentally result in a SQL injection. An attacker could use a SQL injection to steal or modify contents of the database. Instead, use a parameterized query which is available by default in most database engines. Alternatively, consider using an object-relational mapper (ORM) such as SQLAlchemy which will protect your queries.", "remediation": "", "location": {"file_path": "unknown", "line_start": 33, "line_end": 33, "column_start": 13, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": "CWE-704: Incorrect Type Conversion or Cast", "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.flask.security.injection.tainted-sql-string", "path": "/tmp/tmpr7mo7ysm/468df6beb5447607.py", "start": {"line": 33, "col": 13, "offset": 905}, "end": {"line": 33, "col": 71, "offset": 963}, "extra": {"message": "Detected user input used to manually construct a SQL string. This is usually bad practice because manual construction could accidentally result in a SQL injection. An attacker could use a SQL injection to steal or modify contents of the database. Instead, use a parameterized query which is available by default in most database engines. Alternatively, consider using an object-relational mapper (ORM) such as SQLAlchemy which will protect your queries.", "metadata": {"cwe": ["CWE-704: Incorrect Type Conversion or Cast"], "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", "flask"], "subcategory": ["vuln"], "impact": "MEDIUM", "likelihood": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
4
true
[ "CWE-89", "CWE-89", "CWE-915", "CWE-704" ]
[ "rules.python.lang.security.audit.formatted-sql-query", "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "rules.python.django.security.injection.tainted-sql-string", "rules.python.flask.security.injection.tainted-sql-string" ]
[ "security", "security", "security", "security" ]
[ "LOW", "LOW", "LOW", "MEDIUM" ]
[ "MEDIUM", "HIGH", "HIGH", "HIGH" ]
[ 32, 32, 33, 33 ]
[ 33, 33, 33, 33 ]
[ 17, 17, 13, 13 ]
[ 72, 72, 71, 71 ]
[ "A01:2017 - Injection", "A01:2017 - Injection", "A08:2021 - Software and Data Integrity Failures", "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, 7.5, 7.5 ]
[ "LOW", "LOW", "MEDIUM", "MEDIUM" ]
[ "HIGH", "HIGH", "LOW", "MEDIUM" ]
server.py
/server/server.py
yrahul3910/csc510-project
MIT
2024-11-18T21:10:56.828204+00:00
1,618,422,711,000
21cca27e59285637c938e361e9850a4e37706be5
3
{ "blob_id": "21cca27e59285637c938e361e9850a4e37706be5", "branch_name": "refs/heads/master", "committer_date": 1618422711000, "content_id": "48190f10a42757b7594a48d84bc1426ddf6bef5b", "detected_licenses": [ "MIT" ], "directory_id": "7b540dc491b85bbff5d6233db1c6fe3e0ee47138", "extension": "py", "filename": "sequence.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": 5291, "license": "MIT", "license_type": "permissive", "path": "/prospr/sequence.py", "provenance": "stack-edu-0054.json.gz:576821", "repo_name": "bbyun28/prospr", "revision_date": 1618422711000, "revision_id": "4a4f27d3fb9f834a94e5d29226e26c9136e49dd4", "snapshot_id": "ac3523b4f933cf345a0683199314e77e9f64307c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bbyun28/prospr/4a4f27d3fb9f834a94e5d29226e26c9136e49dd4/prospr/sequence.py", "visit_date": "2023-03-31T08:42:13.980217" }
2.53125
stackv2
import numpy as np import os import string import re import tensorflow as tf tf.compat.v1.enable_eager_execution() def probability(n): try: counts = int(n) except: return 0. return 2.**(-counts/1000.) def find_rows(filename): with open(filename) as f: contents=f.read() result = re.search('LENG (.*) match', contents) return int(result.group(1)) def find_hashtag(data): for i,line in enumerate(data): if line=="#\n": return i def parse_a3m(filename): seqs = [] table = str.maketrans(dict.fromkeys(string.ascii_lowercase)) for line in open(filename,"r"): if line[0] != '>' and line[0] != '#': # remove lowercase letters and right whitespaces seqs.append(line.rstrip().translate(table)) # convert letters into numbers alphabet = np.array(list("ARNDCQEGHILKMFPSTWYV-"), dtype='|S1').view(np.uint8) msa = np.array([list(s) for s in seqs], dtype='|S1').view(np.uint8) for i in range(alphabet.shape[0]): msa[msa == alphabet[i]] = i # treat all unknown characters as gaps msa[msa > 20] = 20 return msa def fast_dca(msa1hot, weights, penalty = 4.5): nr = tf.shape(msa1hot)[0] nc = tf.shape(msa1hot)[1] ns = tf.shape(msa1hot)[2] with tf.name_scope('covariance'): x = tf.reshape(msa1hot, (nr, nc * ns)) num_points = tf.reduce_sum(weights) - tf.sqrt(tf.reduce_mean(weights)) mean = tf.reduce_sum(x * weights[:,None], axis=0, keepdims=True) / num_points x = (x - mean) * tf.sqrt(weights[:,None]) cov = tf.matmul(tf.transpose(x), x)/num_points with tf.name_scope('inv_convariance'): cov_reg = cov + tf.eye(nc * ns) * penalty / tf.sqrt(tf.reduce_sum(weights)) inv_cov = tf.linalg.inv(cov_reg) x1 = tf.reshape(inv_cov,(nc, ns, nc, ns)) x2 = tf.transpose(x1, [0,2,1,3]) features = tf.reshape(x2, (nc, nc, ns * ns)) x3 = tf.sqrt(tf.reduce_sum(tf.square(x1[:,:-1,:,:-1]),(1,3))) * (1-tf.eye(nc)) apc = tf.reduce_sum(x3,0,keepdims=True) * tf.reduce_sum(x3,1,keepdims=True) / tf.reduce_sum(x3) contacts = (x3 - apc) * (1-tf.eye(nc)) return tf.concat([features, contacts[:,:,None]], axis=2) def reweight(msa1hot, cutoff): """reweight MSA based on cutoff""" with tf.name_scope('reweight'): id_min = tf.cast(tf.shape(msa1hot)[1], tf.float32) * cutoff id_mtx = tf.tensordot(msa1hot, msa1hot, [[1,2], [1,2]]) id_mask = id_mtx > id_min w = 1.0/tf.reduce_sum(tf.cast(id_mask, dtype=tf.float32),-1) return w class Sequence(object): def __init__(self, a3m_file, **kwargs): self.a3m_file = a3m_file self.name = a3m_file.split('.a3m')[0] def build(self): self.get_seq() self.make_hhm() self.fast_dca() os.system('rm '+self.hhm_file) def get_seq(self): with open(self.a3m_file) as f: lns = f.readlines() #might not always be the second line in the file seq = '' l = 0 while seq == '' and l < len(lns): if lns[l][0] == '>': seq = lns[l+1].strip('\n') break else: l += 1 if seq == '': print('ERROR! Unable to derive sequence from input a3m file') return self.seq = seq def make_hhm(self): #create hhm self.hhm_file = 'temp.hhm' os.system('hhmake -i '+self.a3m_file+' -o '+self.hhm_file) try: with open(self.hhm_file) as f: data = f.readlines() except: print('ERROR! Unable to process hhm converted from a3m') return NUM_COL = 30 NUM_ROW = find_rows(self.hhm_file) pssm = np.zeros((NUM_ROW, NUM_COL)) line_counter = 0 start = find_hashtag(data)+5 for x in range (0, NUM_ROW * 3): if x % 3 == 0: line = data[x + start].split()[2:-1] for i, element in enumerate(line): prop = probability(element) pssm[line_counter,i] = prop elif x % 3 == 1: line = data[x+start].split() for i, element in enumerate(line): prop = probability(element) pssm[line_counter, i+20] = prop line_counter += 1 self.hhm = pssm def fast_dca(self): ns = 21 wmin = 0.8 a3m = parse_a3m(self.a3m_file) ncol = a3m.shape[1] nrow = tf.Variable(a3m.shape[0]) msa = tf.Variable(a3m) msa1hot = tf.one_hot(msa, ns, dtype=tf.float32) w = reweight(msa1hot, wmin) f2d_dca = tf.cond(nrow>1, lambda: fast_dca(msa1hot, w), lambda: tf.zeros([ncol,ncol,442], tf.float32)) f2d_dca = tf.expand_dims(f2d_dca, axis=0).numpy() dimensions = f2d_dca.shape f2d_dca = f2d_dca.reshape(dimensions[1],dimensions[2],dimensions[3]) self.dca = f2d_dca.astype('float16')
158
32.49
136
18
1,501
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_dfcc26bc45c2f115_1a4fa2ea", "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": 10, "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/tmpr7mo7ysm/dfcc26bc45c2f115.py", "start": {"line": 17, "col": 10, "offset": 266}, "end": {"line": 17, "col": 24, "offset": 280}, "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_dfcc26bc45c2f115_2b818ab7", "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": 17, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/dfcc26bc45c2f115.py", "start": {"line": 31, "col": 17, "offset": 625}, "end": {"line": 31, "col": 35, "offset": 643}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_dfcc26bc45c2f115_3d99eb5b", "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": 94, "line_end": 94, "column_start": 9, "column_end": 39, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpr7mo7ysm/dfcc26bc45c2f115.py", "start": {"line": 94, "col": 9, "offset": 2889}, "end": {"line": 94, "col": 39, "offset": 2919}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_dfcc26bc45c2f115_b3dda58c", "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": 97, "line_end": 97, "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/tmpr7mo7ysm/dfcc26bc45c2f115.py", "start": {"line": 97, "col": 14, "offset": 2961}, "end": {"line": 97, "col": 33, "offset": 2980}, "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.useless-eqeq_dfcc26bc45c2f115_c486c651", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.useless-eqeq", "finding_type": "correctness", "severity": "low", "confidence": "medium", "message": "This expression is always True: `seq == seq` or `seq != seq`. If testing for floating point NaN, use `math.isnan(seq)`, or `cmath.isnan(seq)` if the number is complex.", "remediation": "", "location": {"file_path": "unknown", "line_start": 102, "line_end": 102, "column_start": 19, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.useless-eqeq", "path": "/tmp/tmpr7mo7ysm/dfcc26bc45c2f115.py", "start": {"line": 102, "col": 19, "offset": 3137}, "end": {"line": 102, "col": 28, "offset": 3146}, "extra": {"message": "This expression is always True: `seq == seq` or `seq != seq`. If testing for floating point NaN, use `math.isnan(seq)`, or `cmath.isnan(seq)` if the number is complex.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_dfcc26bc45c2f115_4bf20822", "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": 116, "column_start": 9, "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://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpr7mo7ysm/dfcc26bc45c2f115.py", "start": {"line": 116, "col": 9, "offset": 3566}, "end": {"line": 116, "col": 67, "offset": 3624}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_dfcc26bc45c2f115_f751d064", "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": 119, "line_end": 119, "column_start": 18, "column_end": 37, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/dfcc26bc45c2f115.py", "start": {"line": 119, "col": 18, "offset": 3656}, "end": {"line": 119, "col": 37, "offset": 3675}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
7
true
[ "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-system-call-audit", "rules.python.lang.security.audit.dangerous-system-call-audit" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "HIGH", "HIGH" ]
[ 94, 116 ]
[ 94, 116 ]
[ 9, 9 ]
[ 39, 67 ]
[ "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" ]
sequence.py
/prospr/sequence.py
bbyun28/prospr
MIT
2024-11-18T21:10:58.005473+00:00
1,559,690,728,000
aca1fbdc4349e1faf6400f99772276cec8f4304d
2
{ "blob_id": "aca1fbdc4349e1faf6400f99772276cec8f4304d", "branch_name": "refs/heads/master", "committer_date": 1559690728000, "content_id": "36498c498afee59cb4ba0febd0216377d539c431", "detected_licenses": [ "MIT" ], "directory_id": "b2d2ae25aede5ee79f2167914daea66b96e598ff", "extension": "py", "filename": "main.py", "fork_events_count": 0, "gha_created_at": 1559686873000, "gha_event_created_at": 1559690729000, "gha_language": null, "gha_license_id": "MIT", "github_id": 190287300, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2073, "license": "MIT", "license_type": "permissive", "path": "/main.py", "provenance": "stack-edu-0054.json.gz:576835", "repo_name": "WesleyBatista/raspiii", "revision_date": 1559690728000, "revision_id": "3dc49e83926212b3f3dc4a5210fb99233aaa7c5c", "snapshot_id": "781ab2707d7eeaa320b976a1769916d594643bfa", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/WesleyBatista/raspiii/3dc49e83926212b3f3dc4a5210fb99233aaa7c5c/main.py", "visit_date": "2020-05-31T12:41:39.999977" }
2.5
stackv2
import os import socket from datetime import datetime from subprocess import getstatusoutput import boto3 from botocore.exceptions import ClientError AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_S3_BUCKET = os.getenv('AWS_S3_BUCKET') if not (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY and AWS_S3_BUCKET): raise Exception('set AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and ' 'AWS_S3_BUCKET environment vars') def _get_ip(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) result = s.getsockname()[0] s.close() return result AWS_S3_CLIENT = boto3.client('s3') LOCAL_IP_ADDRESS = _get_ip() HOSTNAME = os.uname().nodename def get_metadata(): result = { # noqa 'local_ip_address': LOCAL_IP_ADDRESS, 'hostname': HOSTNAME, 'date_day': datetime.utcnow().strftime('%Y%m%d'), 'upload_timestamp': str(int(datetime.utcnow().timestamp() * 1000000)), } return result def delete_file(filepath): error, output = getstatusoutput(f'rm {filepath}') if error: raise OSError(error, output) def take_a_picture(): filepath = f"/home/pi/camera_service/images/image_{datetime.utcnow().strftime('%Y%m%dT%H%M%S')}.jpg" command = f"raspistill --mode 0 -o {filepath} --nopreview --exposure sports --timeout 1" error, output = getstatusoutput(command) if error: raise OSError(error, output) return filepath def upload_aws(filepath): file_basename = os.path.basename(filepath) s3_path = f'{file_basename}' try: AWS_S3_CLIENT.upload_file(filepath, AWS_S3_BUCKET, s3_path, ExtraArgs={'Metadata': get_metadata()}) # noqa except ClientError as e: print(f'> error: {e}') return False print(f'> uploaded {s3_path}') return s3_path def main(): while True: filepath = take_a_picture() upload_aws(filepath) delete_file(filepath) if __name__ == '__main__': main()
81
24.59
104
17
517
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_f7f717c85cea8053_b30a5fff", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'getstatusoutput' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 42, "line_end": 42, "column_start": 21, "column_end": 54, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/f7f717c85cea8053.py", "start": {"line": 42, "col": 21, "offset": 1101}, "end": {"line": 42, "col": 54, "offset": 1134}, "extra": {"message": "Detected subprocess function 'getstatusoutput' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_f7f717c85cea8053_091c1f6b", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'getstatusoutput' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 50, "line_end": 50, "column_start": 21, "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}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/f7f717c85cea8053.py", "start": {"line": 50, "col": 21, "offset": 1428}, "end": {"line": 50, "col": 45, "offset": 1452}, "extra": {"message": "Detected subprocess function 'getstatusoutput' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
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" ]
[ 42, 50 ]
[ 42, 50 ]
[ 21, 21 ]
[ 54, 45 ]
[ "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Detected subprocess function 'getstatusoutput' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "Detected subpro...
[ 7.5, 7.5 ]
[ "LOW", "LOW" ]
[ "HIGH", "HIGH" ]
main.py
/main.py
WesleyBatista/raspiii
MIT
2024-11-18T21:11:01.828972+00:00
1,597,068,944,000
8c83fccd62fcf84524d88bf414a45ab44486936b
3
{ "blob_id": "8c83fccd62fcf84524d88bf414a45ab44486936b", "branch_name": "refs/heads/main", "committer_date": 1597068944000, "content_id": "abe837f7236af01b0f09f4e467cdf0a3b3f4629c", "detected_licenses": [ "MIT" ], "directory_id": "1266f756e04f96a58b4a02a18499506fbdbe0391", "extension": "py", "filename": "copymove.py", "fork_events_count": 2, "gha_created_at": 1477722763000, "gha_event_created_at": 1620157867000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 72269046, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5493, "license": "MIT", "license_type": "permissive", "path": "/src/actions/copymove.py", "provenance": "stack-edu-0054.json.gz:576886", "repo_name": "cmu-delphi/github-deploy-repo", "revision_date": 1597068944000, "revision_id": "2c3e2f201fec7b96fa1e5412482b3ff510546d5b", "snapshot_id": "c838cdc98a8943988a10bb9723e8fb12471e642c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/cmu-delphi/github-deploy-repo/2c3e2f201fec7b96fa1e5412482b3ff510546d5b/src/actions/copymove.py", "visit_date": "2021-07-07T07:58:34.682130" }
2.515625
stackv2
"""Copy and/or move files.""" # standard library import datetime import glob import json import os import re import shutil import subprocess import time # first party import delphi.github_deploy_repo.file_operations as file_operations # header for generated files HEADER_WIDTH = 55 HEADER_LINES = [ # output from `figlet 'DO NOT EDIT'` r' ____ ___ _ _ ___ _____ _____ ____ ___ _____ ', r'| _ \ / _ \ | \ | |/ _ \_ _| | ____| _ \_ _|_ _|', r'| | | | | | | | \| | | | || | | _| | | | | | | | ', r'| |_| | |_| | | |\ | |_| || | | |___| |_| | | | | ', r'|____/ \___/ |_| \_|\___/ |_| |_____|____/___| |_| ', ] def add_header(repo_link, commit, src, dst_ext): # build the header based on the source language ext = dst_ext.lower() pre_block, post_block, pre_line, post_line = '', '', '', '' blanks = '\n\n\n' if ext in ('html', 'xml'): pre_block, post_block = '<!--\n', '-->\n' + blanks elif ext in ('js', 'min.js', 'css', 'c', 'cpp', 'h', 'hpp', 'java'): pre_block, post_block = '/*\n', '*/\n' + blanks elif ext in ('py', 'r', 'coffee', 'htaccess', 'sh'): pre_line, post_line, post_block = '# ', ' #', blanks elif ext in ('php'): # be sure to not introduce whitespace (e.g. newlines) outside php tags pre_block, post_block = '<?php /*\n', '*/\n' + blanks + '?>' else: # nothing modified, return the original file print(' warning: skipped header for file extension [%s]' % dst_ext) return src # additional header lines t = round(time.time()) dt = datetime.datetime.fromtimestamp(t).isoformat(' ') lines = [ '', 'Automatically generated from sources at:', repo_link, '', ('Commit hash: %s' % commit), ('Deployed at: %s (%d)' % (dt, t)), ] # add the header to a copy of the source file tmp = file_operations.get_file(src[0] + '__header') print(' adding header [%s] -> [%s]' % (src[0], tmp[0])) with open(tmp[0], 'wb') as fout: fout.write(bytes(pre_block, 'utf-8')) for line in HEADER_LINES + [line.center(HEADER_WIDTH) for line in lines]: fout.write(bytes(pre_line + line + post_line + '\n', 'utf-8')) fout.write(bytes(post_block, 'utf-8')) with open(src[0], 'rb') as fin: fout.write(fin.read()) # return the new file return tmp def replace_keywords(src, templates): # load list of (key, value) pairs pairs = [] for t in templates: with open(t[0], 'r') as f: pairs.extend(json.loads(f.read())) # make a new file to hold the results tmp = file_operations.get_file(src[0] + '__valued') print(' replacing %d keywords [%s] -> [%s]' % (len(pairs), src[0], tmp[0])) with open(tmp[0], 'w') as fout: with open(src[0], 'r') as fin: for line in fin.readlines(): for (k, v) in pairs: line = line.replace(k, v) fout.write(line) # return the new file return tmp def copymove_single(repo_link, commit, path, row, src, dst, is_move): action = 'move' if is_move else 'copy' print(' %s %s -> %s' % (action, src[2], dst[2])) # check access file_operations.check_file(src[0], path) # put a big "do not edit" warning at the top of the file if row.get('add-header-comment', False) is True: src = add_header(repo_link, commit, src, dst[3]) # replace template keywords with values templates = row.get('replace-keywords') if type(templates) is str: templates = [templates] if type(templates) in (tuple, list): full_templates = [file_operations.get_file(t, path) for t in templates] src = replace_keywords(src, full_templates) # make the copy (method depends on destination) if dst[0].startswith('/var/www/html/'): # copy to staging area tmp = file_operations.get_file(src[2] + '__tmp', '/common/') print(' [%s] -> [%s]' % (src[0], tmp[0])) shutil.copy(src[0], tmp[0]) # make directory and move the file as user `webadmin` cmd = "sudo -u webadmin -s mkdir -p '%s'" % (dst[1]) print(' [%s]' % cmd) subprocess.check_call(cmd, shell=True) cmd = "sudo -u webadmin -s mv -fv '%s' '%s'" % (tmp[0], dst[0]) print(' [%s]' % cmd) subprocess.check_call(cmd, shell=True) else: # make directory and copy the file print(' [%s] -> [%s]' % (src[0], dst[0])) os.makedirs(dst[1], exist_ok=True) shutil.copy(src[0], dst[0]) # maybe delete the source file if is_move: os.remove(src[0]) def copymove(repo_link, commit, path, row, substitutions): # {copy|move} <src> <dst> [add-header-comment] [replace-keywords] src = file_operations.get_file(row['src'], path, substitutions) dst = file_operations.get_file(row['dst'], path, substitutions) # determine which file(s) should be used if 'match' in row: sources, destinations = [], [] recursive = row.get("recursive", False) glob_path = "**" if recursive else "*" for name in glob.glob(os.path.join(src[0], glob_path), recursive=recursive): src2 = file_operations.get_file(name) basename = os.path.relpath(src2[0], start=src[0]) if re.match(row['match'], basename) is not None: sources.append(src2) file_path = os.path.join(dst[0], basename) destinations.append(file_operations.get_file(file_path)) else: sources, destinations = [src], [dst] # apply the action to each file is_move = row.get('type').lower() == 'move' for src, dst in zip(sources, destinations): copymove_single(repo_link, commit, path, row, src, dst, is_move)
158
33.77
77
16
1,606
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_46266cf4bbc22da4_f4b5f8b1", "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": 78, "line_end": 78, "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/tmpr7mo7ysm/46266cf4bbc22da4.py", "start": {"line": 78, "col": 10, "offset": 2417}, "end": {"line": 78, "col": 25, "offset": 2432}, "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_46266cf4bbc22da4_f6b8c02e", "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": 8, "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/tmpr7mo7ysm/46266cf4bbc22da4.py", "start": {"line": 84, "col": 8, "offset": 2660}, "end": {"line": 84, "col": 25, "offset": 2677}, "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_46266cf4bbc22da4_c6825c57", "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": 10, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/46266cf4bbc22da4.py", "start": {"line": 85, "col": 10, "offset": 2696}, "end": {"line": 85, "col": 27, "offset": 2713}, "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_46266cf4bbc22da4_d4282b48", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 119, "line_end": 119, "column_start": 5, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/46266cf4bbc22da4.py", "start": {"line": 119, "col": 5, "offset": 3983}, "end": {"line": 119, "col": 43, "offset": 4021}, "extra": {"message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_46266cf4bbc22da4_c5e68be1", "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_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": 119, "line_end": 119, "column_start": 38, "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://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpr7mo7ysm/46266cf4bbc22da4.py", "start": {"line": 119, "col": 38, "offset": 4016}, "end": {"line": 119, "col": 42, "offset": 4020}, "extra": {"message": "Found 'subprocess' function 'check_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_46266cf4bbc22da4_e9d8f11f", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 122, "line_end": 122, "column_start": 5, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/46266cf4bbc22da4.py", "start": {"line": 122, "col": 5, "offset": 4120}, "end": {"line": 122, "col": 43, "offset": 4158}, "extra": {"message": "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_46266cf4bbc22da4_3845adb8", "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_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": 122, "line_end": 122, "column_start": 38, "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://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpr7mo7ysm/46266cf4bbc22da4.py", "start": {"line": 122, "col": 38, "offset": 4153}, "end": {"line": 122, "col": 42, "offset": 4157}, "extra": {"message": "Found 'subprocess' function 'check_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" ]
[ 119, 119, 122, 122 ]
[ 119, 119, 122, 122 ]
[ 5, 38, 5, 38 ]
[ 43, 42, 43, 42 ]
[ "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Detected subprocess function 'check_call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "Found 'subprocess' f...
[ 7.5, 7.5, 7.5, 7.5 ]
[ "LOW", "HIGH", "LOW", "HIGH" ]
[ "HIGH", "LOW", "HIGH", "LOW" ]
copymove.py
/src/actions/copymove.py
cmu-delphi/github-deploy-repo
MIT
2024-11-18T21:11:03.458634+00:00
1,600,208,766,000
3d38739238091efb3b6ad713eed7cec59b0a1554
2
{ "blob_id": "3d38739238091efb3b6ad713eed7cec59b0a1554", "branch_name": "refs/heads/master", "committer_date": 1600208766000, "content_id": "f70cc5a1bcdac716b4c8be3c121f38829038f099", "detected_licenses": [ "Apache-2.0" ], "directory_id": "0f58bcae13be4d9f5d1be2cbd6fc3d19a6529745", "extension": "py", "filename": "pred_coinfo250.py", "fork_events_count": 2, "gha_created_at": 1602058168000, "gha_event_created_at": 1673864077000, "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 301968113, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4520, "license": "Apache-2.0", "license_type": "permissive", "path": "/scripts/pred_coinfo250.py", "provenance": "stack-edu-0054.json.gz:576908", "repo_name": "expertailab/acred", "revision_date": 1600208766000, "revision_id": "ee45840c942ef2fac4f26da8d756b7c47e42847c", "snapshot_id": "02ddb8b14f6f51c73d89f33f5ffdd8bef086ec1c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/expertailab/acred/ee45840c942ef2fac4f26da8d756b7c47e42847c/scripts/pred_coinfo250.py", "visit_date": "2023-01-21T16:55:01.557809" }
2.4375
stackv2
# # 2020 ExpertSystem # '''Script for generating predictions for the coinform250 dataset using the acred predictor See https://github.com/co-inform/Datasets See also scripts/fetch-data.sh, which should download the input json file and place it in the `data/evaluation/` folder. ''' import argparse import time import json import os import os.path as osp import requests import traceback import pandas as pd def ensure_req_tweet_content(req): for t in req['tweets']: c = t['content'] if c is None: t['content'] = '' print('Fixed null content') def acred_as_coinfo_label(credreview, thresh=0.4): assert thresh >= 0.0 assert thresh <= 1.0 conf = credreview['reviewRating']['confidence'] if conf <= thresh: return 'not_verifiable' val = credreview['reviewRating']['ratingValue'] if val >= 0.5: return 'credible' if val >= 0.25: return 'mostly_credible' if val >= -0.25: return 'credible_uncertain' if val >= -0.5: return 'credible_uncertain' return 'not_credible' def exec_req(i, req, args): print('\n\nExecuting request %s' % (i)) ensure_req_tweet_content(req) req['reviewFormat'] = 'schema.org' start = time.time() resp = requests.post(args.credpred_url, json=req, verify=False, timeout=args.req_timeout) result = [] if resp.ok: respd = resp.json() result = [{ 'tweet_id': request['tweet_id'], 'ratingValue': r['reviewRating']['ratingValue'], 'confidence': r['reviewRating']['confidence'], 'label': acred_as_coinfo_label(r) } for request, r in zip(req['tweets'], respd)] resp_f = 'coinform250_%s.json' % i with open('%s/%s' % (args.outDir, resp_f), 'w') as outf: json.dump(respd, outf) else: print("Failed: %s %s" % (str(resp), resp.text)) print('Processed in %ss.' % (time.time() - start)) return result def as_acred_requests(tweets, batchSize=5): batch = [] for i, t in enumerate(tweets): batch.append({ 'content': t['full_text'], 'tweet_id': t['id'], 'url': 'https://twitter.com/x/status/%s' % (t['id'])}) if len(batch) == batchSize: yield {'tweets': batch, 'source': 'coinform250.json', 'batch_id': '%s-%s' % (i-batchSize, i)} batch = [] if len(batch) > 0: yield {'tweets': batch, 'source': 'coinform250.json', 'batch_id': '%s-%s' % (len(tweets) - len(batch), len(tweets))} if __name__ == '__main__': parser = argparse.ArgumentParser( description='Generate tweet credibility predictions for a dir with requests', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-inputJson', help='Path to the coinform250.json file', required=True) parser.add_argument( '-batchSize', type=int, default=5, help='Number of tweets to send per request to acred endpoint') parser.add_argument( '-outDir', help='Path to a local dir where the CredibilityReviews will be stored', required=True) parser.add_argument( '-credpred_url', help='URL of the acred endpoint for the tweet credibility') parser.add_argument( '-credpred_id', help='ID of the generation task') parser.add_argument( '-req_timeout', type=int, default=90, help='Seconds to wait for a response') args = parser.parse_args() all_start = time.time() assert osp.isdir(osp.join(args.outDir)) assert osp.isfile(args.inputJson) tweets = [] with open(args.inputJson) as jsonl_file: tweets = [json.loads(line) for line in jsonl_file] assert len(tweets) > 0, '%s' % (len(tweets)) print('Reviewing credibility of %s tweets using batchSize %s' % (len(tweets), args.batchSize)) preds = [] for i, req in enumerate(as_acred_requests(tweets, args.batchSize)): try: preds.extend(exec_req(i, req, args)) except Exception as e: print('Error executing request %s %s %s' % (i, req, str(e))) print(traceback.format_exc()) pd.DataFrame(preds).to_csv('%s/%s.csv' % (args.outDir, 'predictions'), index=False) print('Finished in %.3fs' % (time.time() - all_start))
143
30.61
98
16
1,131
python
[{"finding_id": "semgrep_rules.python.requests.security.disabled-cert-validation_3bfd6a6299d9c740_b1a46ef1", "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(args.credpred_url, json=req,\n verify=True,\n timeout=args.req_timeout)", "location": {"file_path": "unknown", "line_start": 55, "line_end": 57, "column_start": 12, "column_end": 51, "code_snippet": "requires login"}, "cwe_id": "CWE-295: Improper Certificate Validation", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.security.disabled-cert-validation", "path": "/tmp/tmpr7mo7ysm/3bfd6a6299d9c740.py", "start": {"line": 55, "col": 12, "offset": 1280}, "end": {"line": 57, "col": 51, "offset": 1412}, "extra": {"message": "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "fix": "requests.post(args.credpred_url, json=req,\n verify=True,\n timeout=args.req_timeout)", "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.lang.best-practice.unspecified-open-encoding_3bfd6a6299d9c740_54f9fd1e", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 68, "line_end": 68, "column_start": 14, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/3bfd6a6299d9c740.py", "start": {"line": 68, "col": 14, "offset": 1815}, "end": {"line": 68, "col": 56, "offset": 1857}, "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_3bfd6a6299d9c740_46f56734", "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": 128, "line_end": 128, "column_start": 10, "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/tmpr7mo7ysm/3bfd6a6299d9c740.py", "start": {"line": 128, "col": 10, "offset": 3828}, "end": {"line": 128, "col": 30, "offset": 3848}, "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-295" ]
[ "rules.python.requests.security.disabled-cert-validation" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 55 ]
[ 57 ]
[ 12 ]
[ 51 ]
[ "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" ]
pred_coinfo250.py
/scripts/pred_coinfo250.py
expertailab/acred
Apache-2.0
2024-11-18T21:11:03.794550+00:00
1,623,358,765,000
94cf61a943d61852aa1a8a804e513f9d09168011
3
{ "blob_id": "94cf61a943d61852aa1a8a804e513f9d09168011", "branch_name": "refs/heads/main", "committer_date": 1623358765000, "content_id": "c75aab14df84c29a8c9d05a99df39da6ff1a6643", "detected_licenses": [ "Apache-2.0" ], "directory_id": "cd3ccc969d6e31dce1a0cdc21de71899ab670a46", "extension": "py", "filename": "aggregate_xmls.py", "fork_events_count": 1, "gha_created_at": 1623084295000, "gha_event_created_at": 1623100013000, "gha_language": "Java", "gha_license_id": "Apache-2.0", "github_id": 374736765, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2427, "license": "Apache-2.0", "license_type": "permissive", "path": "/agp-7.1.0-alpha01/tools/base/bazel/qa/utils/aggregate_xmls.py", "provenance": "stack-edu-0054.json.gz:576911", "repo_name": "jomof/CppBuildCacheWorkInProgress", "revision_date": 1623358765000, "revision_id": "9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51", "snapshot_id": "75e76e1bd1d8451e3ee31631e74f22e5bb15dd3c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jomof/CppBuildCacheWorkInProgress/9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51/agp-7.1.0-alpha01/tools/base/bazel/qa/utils/aggregate_xmls.py", "visit_date": "2023-05-28T19:03:16.798422" }
3.0625
stackv2
#!/usr/bin/python3 """Aggregate testlogs XMLs into a single XML file This scripts takes a directory as an input, collects all XML files that exist in the directory tree and aggregates results for testsuites and testcases that are present within. The tests that are run multiple times are indexed with a numeric suffix counter. Aggregated result is written to a file. Example: $ ./aggregate_xmls.py --testlogs_dir=/mydir/testlogs --output_file=out.xml Arguments: --testlogs_dir: directory where test logs are located. ex: <bazel-testlogs> --output_file: name of the XML file where the aggregated results will be written to. (default: aggregated_results.xml) """ import argparse import os import xml.etree.ElementTree as ET def merge_xmls(filelist): root = ET.Element('testsuites') classcounter = {} testcounter = {} for filename in filelist: data = ET.parse(filename).getroot() for child in data.findall('testsuite'): for subchild in child: if subchild.tag != "testcase": continue else: classname = child.attrib['name'] testname = subchild.attrib["name"] if classname not in classcounter: classcounter[classname] = 0 else: classcounter[classname] += 1 if testname not in testcounter: testcounter[testname] = 0 else: testcounter[testname] += 1 child.attrib["name"] = child.attrib["name"] \ + "-" + str(classcounter[classname]) subchild.attrib["name"] = subchild.attrib["name"] \ + "-" + str(classcounter[classname]) subchild.attrib["classname"] = subchild.attrib["classname"] \ + "-" + str(testcounter[testname]) root.append(child) break return root def main(): parser = argparse.ArgumentParser(description='Aggregate test results') parser.add_argument('--testlogs_dir', required=True) parser.add_argument('--output_file', default='aggregate_results.xml') args = parser.parse_args() filelist = [] for dirname, subdir, filenames in os.walk(args.testlogs_dir): for filename in filenames: if filename.endswith('.xml'): filelist.append(dirname+"/"+filename) data = merge_xmls(filelist) ET.ElementTree(data).write(args.output_file) if __name__ == '__main__': main()
70
33.67
78
19
532
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_efa3f9a5a4259b5e_e7a684a6", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 21, "line_end": 21, "column_start": 1, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpr7mo7ysm/efa3f9a5a4259b5e.py", "start": {"line": 21, "col": 1, "offset": 704}, "end": {"line": 21, "col": 35, "offset": 738}, "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_efa3f9a5a4259b5e_a021d9f9", "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(filename)", "location": {"file_path": "unknown", "line_start": 28, "line_end": 28, "column_start": 12, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml-parse", "path": "/tmp/tmpr7mo7ysm/efa3f9a5a4259b5e.py", "start": {"line": 28, "col": 12, "offset": 878}, "end": {"line": 28, "col": 30, "offset": 896}, "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(filename)", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-611", "CWE-611" ]
[ "rules.python.lang.security.use-defused-xml", "rules.python.lang.security.use-defused-xml-parse" ]
[ "security", "security" ]
[ "LOW", "MEDIUM" ]
[ "HIGH", "HIGH" ]
[ 21, 28 ]
[ 21, 28 ]
[ 1, 12 ]
[ 35, 30 ]
[ "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" ]
aggregate_xmls.py
/agp-7.1.0-alpha01/tools/base/bazel/qa/utils/aggregate_xmls.py
jomof/CppBuildCacheWorkInProgress
Apache-2.0
2024-11-18T21:11:04.985914+00:00
1,531,251,619,000
42a836d108a4933a59e3609c40d2502919b18f11
5
{ "blob_id": "42a836d108a4933a59e3609c40d2502919b18f11", "branch_name": "refs/heads/master", "committer_date": 1531251619000, "content_id": "c59ceb0c719bb5bdcb91d8e642bad9b74fe1d16c", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e939c75bd882ae3e55c2c8b58fb0302f0fea6c41", "extension": "py", "filename": "calculator.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 112312863, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 657, "license": "Apache-2.0", "license_type": "permissive", "path": "/exercises/python intro/google/calculator.py", "provenance": "stack-edu-0054.json.gz:576925", "repo_name": "Artimbocca/python", "revision_date": 1531251619000, "revision_id": "5a5e66b6f0ea8782e144c5097e744aedab1ac467", "snapshot_id": "0642191ddddf0b68d26dde86a3af10e30efaebfc", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Artimbocca/python/5a5e66b6f0ea8782e144c5097e744aedab1ac467/exercises/python intro/google/calculator.py", "visit_date": "2021-09-18T06:33:47.475546" }
4.84375
stackv2
# You can use the input() function to ask for input: # n = input("Enter number: ") # print(n) # To build a simple calculator we could just rely on the eval function of Python: # print(eval(input("Expression: "))) # e.g. 21 + 12 # Store result in variable and it can be used in expression: while True: exp = input("Expression: ") # e.g. 21 + 12, or m - 7 m = eval(exp) print(m) # HOWEVER, using eval is a very bad, as in dangerous, idea. If someone were to enter: os.system(‘rm -rf /’): disaster. # So, let's quickly get rid of this eval and make our own much more specific eval that only excepts some basic mathematical expressions
18
35.28
135
9
180
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_0ace61f8d09a3347_8438d801", "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": 11, "line_end": 11, "column_start": 9, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpr7mo7ysm/0ace61f8d09a3347.py", "start": {"line": 11, "col": 9, "offset": 371}, "end": {"line": 11, "col": 18, "offset": 380}, "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" ]
[ 11 ]
[ 11 ]
[ 9 ]
[ 18 ]
[ "A03:2021 - Injection" ]
[ "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources." ]
[ 5 ]
[ "LOW" ]
[ "HIGH" ]
calculator.py
/exercises/python intro/google/calculator.py
Artimbocca/python
Apache-2.0
2024-11-18T21:11:07.224993+00:00
1,603,899,565,000
d264105f3b2bd59fd0696039fc19f48ff69e27f3
3
{ "blob_id": "d264105f3b2bd59fd0696039fc19f48ff69e27f3", "branch_name": "refs/heads/master", "committer_date": 1603899565000, "content_id": "fe2a5a508394cd21427a0bc5e283a6fb5eecc9d2", "detected_licenses": [ "CC0-1.0" ], "directory_id": "e2d2988ee51c2084d0e58bf3c8e7d778f32330b9", "extension": "py", "filename": "modules_dl.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 286692708, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12243, "license": "CC0-1.0", "license_type": "permissive", "path": "/data-sets/spfrantz-code/modules_dl.py", "provenance": "stack-edu-0054.json.gz:576953", "repo_name": "ruralhuman/accountability", "revision_date": 1603899565000, "revision_id": "df3ab12c4e2cd095b66f788474b0515e352e006e", "snapshot_id": "41274386e13affbaa101b79c98a95b2e5aba77c6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ruralhuman/accountability/df3ab12c4e2cd095b66f788474b0515e352e006e/data-sets/spfrantz-code/modules_dl.py", "visit_date": "2023-01-03T07:31:09.189375" }
2.765625
stackv2
import logging from selenium.webdriver.support.ui import Select import subprocess import os import pickle import requests import sqlite3 from time import sleep def get_years(driver): '''Retrieve a list of fiscal years available in the FCRA database''' years = [] driver.get('https://fcraonline.nic.in/fc_qtrfrm_report.aspx') years_options = driver.find_elements_by_xpath \ ("//select[@id='ddl_block_year']//option[@value!='0']") for option in years_options: years.append(option.text) print("Years available: ", years) return years def get_quarters(years, driver): '''Retrieve a list of quarters available for each fiscal year''' quarters = [] driver.get('https://fcraonline.nic.in/fc_qtrfrm_report.aspx') for year in years: years_menu = Select(driver.find_element_by_id("ddl_block_year")) years_menu.select_by_value(year) sleep(2) quarters_options = driver.find_elements_by_xpath \ ("//select[@id='ddl_qtr_returns']//option") for option in quarters_options[1:]: option_value = option.get_attribute("value") quarters.append((year, option_value)) print("Quarters available: ", quarters) return quarters def get_state_list(driver): '''Construct a dictionary of numerical state IDs and state names''' driver.get('https://fcraonline.nic.in/fc_qtrfrm_report.aspx') states_values = (driver.find_elements_by_xpath \ ("//select[@id='DdnListState']//option")) state_ids = [] for item in states_values: state_ids.append(item.get_attribute("value")) print(state_ids) states = {} for id in state_ids[1:]: states[id] = (driver.find_element_by_xpath \ ("//select[@id='DdnListState']//option[@value=" \ + '"' + id + '"' + ']').text) # Save states list to file pickle.dump(states, open("./obj/states.p", "wb")) print("States available: ", states) return states def get_district_lists(states, driver): ''' Retrieve a list of districts in the FCRA database by navigating the drop-down menus. Takes as input a dictionary that has state IDs as keys. Returns a dictionary of dictionaries in the following format: {'state1_id':{'state1_dist1_id':'state1_dist1_name'...}, / 'state2_id':{'state2_dist1_id':'state2_dist1_name'...}...} ''' district_list = {} for id in states.keys(): state_dists = {} driver.get('https://fcraonline.nic.in/fc_qtrfrm_report.aspx') states_menu = Select(driver.find_element_by_id("DdnListState")) states_menu.select_by_value(id) sleep(3) dist_options = (driver.find_elements_by_xpath \ ("//select[@id='DdnListdist']//option")) for option in dist_options[1:]: dist_id = option.get_attribute("value") dist_name = option.text state_dists[dist_id] = dist_name district_list[id] = state_dists # Save districts list to file pickle.dump(district_list, open("./obj/districts.p", "wb")) return(district_list) # SQLite database initialization def database_connect(db_name): '''Connect to SQLite database''' db = sqlite3.connect("./database/" + db_name) c = db.cursor() return db, c def initialize_database(db): '''Set up an SQLite database''' # Districts table db.execute("CREATE TABLE IF NOT EXISTS `districts` ( \ `dist_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, \ `state_id` VARCHAR(3) NOT NULL, \ `state_name` VARCHAR(25) NOT NULL, \ `state_dist_id` VARCHAR(4) NOT NULL, \ `state_dist_name` VARCHAR(255) NOT NULL)") # Organizations table db.execute("CREATE TABLE IF NOT EXISTS `organizations` ( \ `org_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, \ `fcra` VARCHAR(15) NOT NULL, \ `org_name` VARCHAR(255))") # Files table db.execute("CREATE TABLE IF NOT EXISTS `files` ( \ `file_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, \ `fcra` VARCHAR(10) NOT NULL, \ `dist_id` INTEGER NOT NULL, \ `path` VARCHAR(255) UNIQUE, \ `year` VARCHAR(15) NOT NULL, \ `quarter` VARCHAR(4) NOT NULL, \ `dldate` DATETIME DEFAULT CURRENT_TIME)") # Disclosures table db.execute("CREATE TABLE IF NOT EXISTS `disclosures` ( \ `disc_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, \ `file_id` INTEGER NOT NULL, \ `donor_name` VARCHAR(255), \ `donor_type` VARCHAR(255), \ `donor_address` TEXT, \ `purposes` VARCHAR(255), \ `amount` VARCHAR(20))") db.commit() def populate_district_table(driver, db, c): '''Populate database table of states and districts''' print("Gathering all districts for all states. This will take a few minutes.") states = get_state_list(driver) districts = get_district_lists(states, driver) counter = 0 for state in states.keys(): for district in districts[state].keys(): c.execute("INSERT INTO districts (state_id, state_name, \ state_dist_id, state_dist_name) VALUES (:state_id, \ :state_name, :state_dist_id, :state_dist_name)", \ {'state_id':state, 'state_name':states[state], \ 'state_dist_id':district, \ 'state_dist_name':districts[state][district]}) counter += 1 db.commit() print("Populated districts table with ", counter, "districts") # Linux only (requires pdftk): verify integrity of downloaded file def verify_pdf(path): '''Checks PDF integrity and re-downloads if file appears corrupt''' result = subprocess.run(["./verify_pdf.sh", path], stdout=subprocess.PIPE) return result def get_file(yr, qtr, org, filepath, starturl, db, c, state, district): '''Downloads a disclosure''' r = requests.get(starturl + org + "R&fin_year=" \ + yr +"&quarter=" + qtr) # Look up district id dist_id, = c.execute("SELECT dist_id FROM districts WHERE \ state_id = :state AND state_dist_id = :district", \ {'state':state, 'district':district}) # Create file information in database c.execute("INSERT INTO files (fcra, year, quarter, dist_id) VALUES \ (:fcra, :year, :quarter, :dist_id)", {'fcra':org, 'year':yr, \ 'quarter':qtr, 'dist_id':dist_id}) db.commit() # Get unique file ID to append to filename (unpack tuple) file_id, = c.execute("SELECT file_id FROM files WHERE fcra = :org AND \ year = :yr AND quarter = :quarter", {'org':org, \ 'yr':yr, 'quarter':qtr}).fetchone() # Download disclosure full_path = (filepath + '/D_' + str(file_id) + '_' + org + '_' + yr + '_' \ + qtr + ".pdf") with open(full_path, 'wb') as file: file.write(r.content) # Associate path with file_id in database c.execute("UPDATE files SET path = :full_path WHERE file_id = :file_id", \ {'file_id':file_id, 'full_path':full_path}) db.commit() print("Wrote file D_" + str(file_id) + '_' + org + '_' + yr + '_' \ + qtr +".pdf to disk") sleep(1) return(full_path) # Download disclosures of selected years, quarters, districts def download_disclosures(quarters, districts, driver, db, c): '''Downloads PDF disclosures for the quarters and districts specified by the user INPUT: quarters: [('yyyy-yyyy', 'q')...] e.g., [('2015-2016', '3'), ('2015-2016', '4')] districts: {'stateid':{'districtid1':'name1'...}...} ''' starturl='https://fcraonline.nic.in/Fc_qtrFrm_PDF.aspx?rcn=' for quarter in quarters: (yr, qtr) = quarter for state in districts.keys(): for district in districts[state].keys(): try: # Navigate the drop-down menus driver.get('https://fcraonline.nic.in/fc_qtrfrm_report.aspx') years_menu = Select(driver.find_element_by_id("ddl_block_year")) years_menu.select_by_value(yr) sleep(2.5) quarters_menu = Select(driver.find_element_by_id("ddl_qtr_returns")) quarters_menu.select_by_value(qtr) states_menu = Select(driver.find_element_by_id("DdnListState")) states_menu.select_by_value(state) sleep(2.5) districts_menu = Select(driver.find_element_by_id("DdnListdist")) districts_menu.select_by_value(district) submit_btn = driver.find_element_by_id("Button1") submit_btn.click() # Create directory to store district disclosures if none exists filepath = "./disclosures/" + state +'/' + district os.makedirs(filepath, exist_ok=True) sleep(2) except requests.exceptions.ConnectionError as e: logging.exception(f"{yr} q{qtr} state {state} \ district {district} failed: \ Connection error") sleep(10) continue except: logging.exception(f"{yr} q{qtr} {state} {district} failed.") sleep(10) continue # Compile dict of organization names and FCRA reg numbers dyq_orgs={} null_returns=set() table_rows = driver.find_elements_by_xpath \ ("//table[@id='GridView1']//tr") for row in table_rows[1:]: table_data = row.find_elements_by_tag_name('td') org_name = table_data[1].text org_fcra = table_data[2].text amount = table_data[3].text # Save dictionary of district-year-quarter disclosures to scrape dyq_orgs[org_fcra] = org_name # If amount is 0.00, add to set of null returns (don't download!) if amount == "0.00": null_returns.add(org_fcra) # Check if each organization is already in the database; if not, # update organizations data table for org in dyq_orgs.keys(): rows = c.execute("SELECT org_id FROM organizations WHERE \ fcra = :key", {'key':org}).fetchall() if len(rows) == 0: c.execute("INSERT INTO organizations (fcra, org_name) \ VALUES (:fcra, :org_name)", {'fcra':org,\ 'org_name':dyq_orgs[org]}) db.commit() # Save PDF disclosures for org in dyq_orgs.keys(): try: if org in null_returns: continue else: try_count = 0 path = get_file(yr, qtr, org, filepath, starturl, \ db, c, state, district) result = verify_pdf(path) while result == "broken" and try_count < 3: print("File corrupted, retrying") logging.info(f"Re-downloading %s", path) sleep(5) get_file(yr, qtr, org, filepath, starturl, \ db, c, state, district) try_count += 1 else: continue except: logging.exception(f"Exception at {org} {yr} {qtr}") logging.info(f"Finished {state} {yr} qtr {qtr}") print(f"Finished state {state} {yr} qtr {qtr}") return 0
295
40.5
88
23
2,756
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_cdac9df42228b333_c7a6d9cf", "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": 28, "line_end": 28, "column_start": 9, "column_end": 17, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/cdac9df42228b333.py", "start": {"line": 28, "col": 9, "offset": 916}, "end": {"line": 28, "col": 17, "offset": 924}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_cdac9df42228b333_4d8c4454", "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": 53, "line_end": 53, "column_start": 5, "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/tmpr7mo7ysm/cdac9df42228b333.py", "start": {"line": 53, "col": 5, "offset": 1944}, "end": {"line": 53, "col": 54, "offset": 1993}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_cdac9df42228b333_e4ae1396", "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": 71, "line_end": 71, "column_start": 9, "column_end": 17, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/cdac9df42228b333.py", "start": {"line": 71, "col": 9, "offset": 2725}, "end": {"line": 71, "col": 17, "offset": 2733}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_cdac9df42228b333_0f597eb5", "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": 5, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/cdac9df42228b333.py", "start": {"line": 81, "col": 5, "offset": 3107}, "end": {"line": 81, "col": 64, "offset": 3166}, "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_cdac9df42228b333_7019c85f", "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": 156, "line_end": 157, "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://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmpr7mo7ysm/cdac9df42228b333.py", "start": {"line": 156, "col": 9, "offset": 5937}, "end": {"line": 157, "col": 46, "offset": 6028}, "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_cdac9df42228b333_e012e299", "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(starturl + org + \"R&fin_year=\" \\\n + yr +\"&quarter=\" + qtr, timeout=30)", "location": {"file_path": "unknown", "line_start": 156, "line_end": 157, "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-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpr7mo7ysm/cdac9df42228b333.py", "start": {"line": 156, "col": 9, "offset": 5937}, "end": {"line": 157, "col": 46, "offset": 6028}, "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(starturl + org + \"R&fin_year=\" \\\n + yr +\"&quarter=\" + qtr, 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.arbitrary-sleep_cdac9df42228b333_4f52d89c", "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": 189, "line_end": 189, "column_start": 5, "column_end": 13, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/cdac9df42228b333.py", "start": {"line": 189, "col": 5, "offset": 7313}, "end": {"line": 189, "col": 13, "offset": 7321}, "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_cdac9df42228b333_5f8b9e5f", "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": 212, "line_end": 212, "column_start": 21, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/cdac9df42228b333.py", "start": {"line": 212, "col": 21, "offset": 8254}, "end": {"line": 212, "col": 31, "offset": 8264}, "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_cdac9df42228b333_ff2c64c2", "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": 217, "line_end": 217, "column_start": 21, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/cdac9df42228b333.py", "start": {"line": 217, "col": 21, "offset": 8568}, "end": {"line": 217, "col": 31, "offset": 8578}, "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_cdac9df42228b333_ee69f3e7", "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": 227, "line_end": 227, "column_start": 21, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/cdac9df42228b333.py", "start": {"line": 227, "col": 21, "offset": 9070}, "end": {"line": 227, "col": 29, "offset": 9078}, "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_cdac9df42228b333_640a095a", "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": 233, "line_end": 233, "column_start": 21, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/cdac9df42228b333.py", "start": {"line": 233, "col": 21, "offset": 9358}, "end": {"line": 233, "col": 30, "offset": 9367}, "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_cdac9df42228b333_2e499f13", "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": 238, "line_end": 238, "column_start": 21, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/cdac9df42228b333.py", "start": {"line": 238, "col": 21, "offset": 9523}, "end": {"line": 238, "col": 30, "offset": 9532}, "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_cdac9df42228b333_40dfda5b", "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": 283, "line_end": 283, "column_start": 33, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/cdac9df42228b333.py", "start": {"line": 283, "col": 33, "offset": 11730}, "end": {"line": 283, "col": 41, "offset": 11738}, "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"}}}]
13
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" ]
[ 53, 81 ]
[ 53, 81 ]
[ 5, 5 ]
[ 54, 64 ]
[ "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "Avoid using `pickle`, which is known to lead to...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
modules_dl.py
/data-sets/spfrantz-code/modules_dl.py
ruralhuman/accountability
CC0-1.0
2024-11-18T21:11:08.494988+00:00
1,510,267,898,000
8c77c556534fee53c2d8b3f8323b07fa4aa34f7a
2
{ "blob_id": "8c77c556534fee53c2d8b3f8323b07fa4aa34f7a", "branch_name": "refs/heads/master", "committer_date": 1510267898000, "content_id": "88dc5fde4a0f1885bfec2efdae1dc685064bf827", "detected_licenses": [ "MIT" ], "directory_id": "17b9f098d783b58a65a2f4a2d51c7d1ae19285cf", "extension": "py", "filename": "Mayordomo.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": 7650, "license": "MIT", "license_type": "permissive", "path": "/Mayordomo.py", "provenance": "stack-edu-0054.json.gz:576965", "repo_name": "elenajimenezm/Mayordomo", "revision_date": 1510267898000, "revision_id": "da5e8746ee41906eb60c8626b5de2db8e111ad83", "snapshot_id": "ea17a3168f25f4648910a71aece478155dffabd3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/elenajimenezm/Mayordomo/da5e8746ee41906eb60c8626b5de2db8e111ad83/Mayordomo.py", "visit_date": "2021-07-25T23:32:15.382348" }
2.4375
stackv2
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import paho.mqtt.client as paho import json import time import uuid import Queue import subprocess import unicodedata MQTT_SERVER = 'localhost' MAYORDOMO_TOPIC = 'rcr/Mayordomo' SPEAK_TOPIC = 'rcr/Speak' PLAYER_TOPIC = 'rcr/MusicPlayer' DRONE_TOPIC = 'rcr/RollerSpider' DHT22_TOPIC = 'rcr/DHT22' MINDSET_TOPIC = 'rcr/MindSet' MAX7219_TOPIC = 'rcr/Max7219' NOISE_TOPIC = 'rcr/Ruido' S2_TOPIC = 'rcr/S2' messages = Queue.Queue( 1 ) data_dht22 = None def sendToSpeak( msg ): global mqtt_client, SPEAK_TOPIC mqtt_client.publish( SPEAK_TOPIC, msg ) def sendToMusicPlayer( msg ): global mqtt_client, PLAYER_TOPIC mqtt_client.publish( PLAYER_TOPIC, msg ) def sendToDrone( msg ): global mqtt_client, DRONE_TOPIC mqtt_client.publish( DRONE_TOPIC, msg ) def sendToMindSet( msg ): global mqtt_client, MINDSET_TOPIC mqtt_client.publish( MINDSET_TOPIC, msg ) def sendToMax7219( msg ): global mqtt_client, MAX7219_TOPIC mqtt_client.publish( MAX7219_TOPIC, msg ) def sendToNoise( msg ): global mqtt_client, NOISE_TOPIC mqtt_client.publish( NOISE_TOPIC, msg ) def sendToS2( msg ): global mqtt_client,S2_TOPIC mqtt_client.publish( S2_TOPIC, msg ) def mqtt_on_message( client, userdata, message ): global messages, data_dht22 # es el dht22 if( message.topic == DHT22_TOPIC ): data_dht22 = message.payload return # lon comandos para el mayordomo # si no se ha procesado el ultimo mensaje lo eliminamos try: messages.get_nowait() except Queue.Empty: pass # agregamos el mensaje try: messages.put_nowait( message ) except Queue.Full: pass def mqtt_on_connect( client, arg1, arg2, arg3 ): global MAYORDOMO_TOPIC, MQTT_SERVER client.subscribe( MAYORDOMO_TOPIC ) client.subscribe( DHT22_TOPIC ) print( "[Mayordomo] Esperando en %s - %s" % ( MQTT_SERVER, MAYORDOMO_TOPIC ) ) def main(): global mqtt_client, MQTT_SERVER, messages, data_dht22 print( '[Mayordomo] Iniciando sistema' ) subprocess.Popen( '/bin/sh ./Speak.sh', shell=True ) subprocess.Popen( '/usr/bin/python ./MusicPlayer/MusicPlayer.py', shell=True ) mqtt_client = paho.Client( 'Mayordomo-' + uuid.uuid4().hex ) mqtt_client.on_connect = mqtt_on_connect mqtt_client.on_message = mqtt_on_message mqtt_client.connect( MQTT_SERVER, 1883 ) mqtt_client.loop_start() time.sleep( 2 ) sendToSpeak( ' ' ) sendToSpeak( ' Sistema inicializado' ) abort = False while( not abort ): message = messages.get() # hacemos el manejo del payload que viene en utf-8 (se supone) # la idea es cambiar tildes y otros caracteres especiales # y llevar todo a minuscula cmd = message.payload.decode('utf-8').lower() cmd = ''.join((c for c in unicodedata.normalize('NFD', cmd) if unicodedata.category(c) != 'Mn')) cmd = cmd.replace( 'mary', 'mari' ) cmd = cmd.replace( 'detener', 'deten' ) cmd = cmd.replace( 'tocar', 'toca' ) cmd = cmd.replace( 'pausar', 'pausa' ) cmd = cmd.replace( 'iniciar', 'inicia' ) cmd = cmd.replace( 'finalizar', 'finaliza' ) cmd = cmd.replace( 'mostrar', 'muestra' ) cmd = cmd.replace( 'robots', 'robot' ) cmd = cmd.replace( 'conectar', 'conecta' ) cmd = cmd.replace( 'desconectar', 'desconecta' ) print( "[Mayordomo] Mensaje recibido:", message.payload, "<<" + cmd + ">>" ) # locales if( cmd == 'finaliza sistema' ): abort = True elif( cmd == 'mari' ): sendToSpeak( 'Dime Padre' ) elif( cmd == 'que hora es' ): now = time.localtime() sendToSpeak( 'son las %d horas con %d minutos' % (now.tm_hour, now.tm_min) ) elif( cmd == 'conversemos' ): now = time.localtime() sendToSpeak( 'de que deseas conversar?' ) # MusicPlayer elif( cmd == 'toca musica' ): sendToMusicPlayer( 'play' ) elif( cmd == 'deten musica' ): sendToMusicPlayer( 'stop' ) elif( cmd == 'pausa musica' ): sendToMusicPlayer( 'pause' ) elif( cmd == 'tema siguiente' ): sendToMusicPlayer( 'next' ) elif( cmd == 'tema anterior' ): sendToMusicPlayer( 'previous' ) elif( cmd == 'quien canta' ): sendToMusicPlayer( 'songtitle' ) # DroneRollerSpider elif( cmd == 'inicia spider' ): subprocess.Popen( '/usr/bin/python ./DroneRollerSpider/DroneRollerSpider.py', shell=True ) elif( cmd == 'finaliza spider' ): sendToDrone( 'exit' ) elif( cmd == 'conecta spider' ): sendToDrone( 'connect' ) elif( cmd == 'desconecta spider' or cmd =='desconectar spyder' ): sendToDrone( 'disconnect' ) elif( cmd == 'sube spider' ): sendToDrone( 'takeoff' ) elif( cmd == 'baja spider' ): sendToDrone( 'land' ) elif( cmd == 'gira spider' ): for i in range( 10 ): sendToDrone( 'turn_left' ) time.sleep( 0.100 ) # MindSet elif( cmd == 'inicia sensor neuronal' ): subprocess.Popen( '/usr/bin/python ./MindSet/MindSetPub.py', shell=True ) subprocess.Popen( '/usr/bin/python ./MindSet/MindSetGraphics.py', shell=True ) subprocess.Popen( '/usr/bin/python ./MindSet/MindSetMusic.py', shell=True ) elif( cmd == 'finaliza sensor neuronal' ): sendToMindSet( 'exit' ) # DHT22 elif( cmd == 'temperatura' ): if( data_dht22 == None ): sendToSpeak( 'No tengo datos de temperatura' ) else: d = data_dht22 d = json.loads( d ) sendToSpeak( 'La Temperatura es de %3.1f grados' % ( d["temperatura"] ) ) elif( cmd == 'humedad' ): if( data_dht22 == None ): sendToSpeak( 'No tengo datos de humedad' ) else: d = data_dht22 d = json.loads( d ) sendToSpeak( 'La humedad es de un %3.1f por ciento' % ( d["humedad"] ) ) # Max72129 elif( cmd.startswith( 'muestra ' ) and len( cmd ) == 9 ): try: digit = int( cmd[8] ) sendToSpeak( "Mostrando un %d en la matriz" % digit ) sendToMax7219( str( digit ) ) except Exception as e: pass # Sensor de ruido elif( cmd == 'inicia analisis de ruido' ): subprocess.Popen( '/usr/bin/python ./Noise/NoiseGraphics.py', shell=True ) elif( cmd == 'finaliza analisis de ruido' ): sendToNoise( 'exit' ) # robot S2 elif( cmd == 'inicia control de robot' ): subprocess.Popen( '/usr/bin/python ./S2/S2.py', shell=True ) elif( cmd == 'nombre de robot' ): sendToS2( 'name' ) elif( cmd == 'robot izquierda' ): sendToS2( 'left 1' ) elif( cmd == 'robot derecha' ): sendToS2( 'right 1' ) elif( cmd == 'robot avanza' ): sendToS2( 'forward 5' ) elif( cmd == 'robot retrocede' ): sendToS2( 'backward 5' ) elif( cmd == 'finaliza control de robot' ): sendToS2( 'exit' ) sendToSpeak( 'Sistema finalizado' ) time.sleep( 2 ) mqtt_client.loop_stop() print( '[Mayordomo] Sistema finalizado' ) #-- main()
231
32.12
104
19
2,122
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_043469feca811abf_41befc63", "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": 95, "line_end": 95, "column_start": 5, "column_end": 83, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/043469feca811abf.py", "start": {"line": 95, "col": 5, "offset": 2202}, "end": {"line": 95, "col": 83, "offset": 2280}, "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_043469feca811abf_91320ab5", "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": 102, "line_end": 102, "column_start": 5, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/043469feca811abf.py", "start": {"line": 102, "col": 5, "offset": 2515}, "end": {"line": 102, "col": 20, "offset": 2530}, "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_043469feca811abf_9549feaa", "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": 154, "line_end": 154, "column_start": 13, "column_end": 103, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/043469feca811abf.py", "start": {"line": 154, "col": 13, "offset": 4622}, "end": {"line": 154, "col": 103, "offset": 4712}, "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_043469feca811abf_27ed822e", "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": 168, "line_end": 168, "column_start": 17, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/043469feca811abf.py", "start": {"line": 168, "col": 17, "offset": 5259}, "end": {"line": 168, "col": 36, "offset": 5278}, "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_043469feca811abf_fafa9e1f", "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": 172, "line_end": 172, "column_start": 13, "column_end": 86, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/043469feca811abf.py", "start": {"line": 172, "col": 13, "offset": 5359}, "end": {"line": 172, "col": 86, "offset": 5432}, "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_043469feca811abf_fe99bcab", "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": 173, "line_end": 173, "column_start": 13, "column_end": 91, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/043469feca811abf.py", "start": {"line": 173, "col": 13, "offset": 5445}, "end": {"line": 173, "col": 91, "offset": 5523}, "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_043469feca811abf_b7bdcdd0", "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": 174, "line_end": 174, "column_start": 13, "column_end": 88, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/043469feca811abf.py", "start": {"line": 174, "col": 13, "offset": 5536}, "end": {"line": 174, "col": 88, "offset": 5611}, "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_043469feca811abf_54245f4a", "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": 205, "line_end": 205, "column_start": 13, "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/tmpr7mo7ysm/043469feca811abf.py", "start": {"line": 205, "col": 13, "offset": 6739}, "end": {"line": 205, "col": 87, "offset": 6813}, "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_043469feca811abf_22f7311c", "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": 211, "line_end": 211, "column_start": 13, "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/tmpr7mo7ysm/043469feca811abf.py", "start": {"line": 211, "col": 13, "offset": 6983}, "end": {"line": 211, "col": 73, "offset": 7043}, "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_043469feca811abf_0dd406e0", "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": 226, "line_end": 226, "column_start": 5, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/043469feca811abf.py", "start": {"line": 226, "col": 5, "offset": 7548}, "end": {"line": 226, "col": 20, "offset": 7563}, "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"}}}]
10
true
[ "CWE-78", "CWE-78", "CWE-78", "CWE-78", "CWE-78", "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.danger...
[ "security", "security", "security", "security", "security", "security", "security" ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH" ]
[ 95, 154, 172, 173, 174, 205, 211 ]
[ 95, 154, 172, 173, 174, 205, 211 ]
[ 5, 13, 13, 13, 13, 13, 13 ]
[ 83, 103, 86, 91, 88, 87, 73 ]
[ "A01:2017 - Injection", "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()'.", "Detected subprocess funct...
[ 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" ]
Mayordomo.py
/Mayordomo.py
elenajimenezm/Mayordomo
MIT
2024-11-18T21:11:16.262414+00:00
1,606,450,715,000
0c8d03f5d906e864de8af65afce16732d44f0c83
2
{ "blob_id": "0c8d03f5d906e864de8af65afce16732d44f0c83", "branch_name": "refs/heads/master", "committer_date": 1606450715000, "content_id": "7950d5690cb9cdf85abbba0ca2ddaf60421183b3", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "2756f2aa3e67805e59832d7e74030b824ab4e674", "extension": "py", "filename": "ftpCSapr2Images.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 151892094, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3099, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/projDir/uw/scripts/ftpCSapr2Images.py", "provenance": "stack-edu-0054.json.gz:577034", "repo_name": "NCAR/lrose-projects-relampago", "revision_date": 1606450715000, "revision_id": "8208e4bd83ac8007a04987c0531fb60cc629a05a", "snapshot_id": "ddb932a5a26b942994f6716db4087199986f58a7", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/NCAR/lrose-projects-relampago/8208e4bd83ac8007a04987c0531fb60cc629a05a/projDir/uw/scripts/ftpCSapr2Images.py", "visit_date": "2021-06-22T13:21:54.870396" }
2.40625
stackv2
#!/usr/bin/python import sys import os import time import datetime from datetime import timedelta import requests from bs4 import BeautifulSoup from ftplib import FTP #if len(sys.argv) != 2: # print >>sys.stderr, "Useage: ",sys.argv[0]," [YYYY_MM_DD]" # quit() #date = sys.argv[1] # get current date and time minus one hour UTC_OFFSET_TIMEDELTA = datetime.datetime.utcnow() - datetime.datetime.now() date_1_hour_ago = datetime.datetime.now() - timedelta(hours=1) + UTC_OFFSET_TIMEDELTA date = date_1_hour_ago.strftime("%Y_%m_%d") dateNoHyphens = date_1_hour_ago.strftime("%Y%m%d") hour = date_1_hour_ago.strftime("%H") #nowTime = time.gmtime() #now = datetime.datetime(nowTime.tm_year, nowTime.tm_mon, nowTime.tm_mday, # nowTime.tm_hour, nowTime.tm_min, nowTime.tm_sec) #date = now.strftime("%Y_%m_%d") #date = '2018_11_01' url = 'https://engineering.arm.gov/~radar/amf1_csapr2_incoming_images/hsrhi/'+date+'/' ext = 'png' homeDir = os.getenv('HOME') outDir = os.path.join(homeDir, 'radar/csapr2/' + date) category = 'radar' platform = 'DOE_CSapr2' ftpCatalogServer = 'catalog.eol.ucar.edu' ftpCatalogUser = 'anonymous' catalogDestDir = '/pub/incoming/catalog/relampago' debug = 1 def listFD(url, ext=''): page = requests.get(url).text print page soup = BeautifulSoup(page, 'html.parser') return [url + '/' + node.get('href') for node in soup.find_all('a') if node.get('href').endswith(ext)] if not os.path.exists(outDir): os.makedirs(outDir) os.chdir(outDir) for file in listFD(url, ext): tmp = os.path.basename(file) (f,e) = os.path.splitext(tmp) parts = f.split('_') (fdate,ftime) = parts[3].split('-') fhour = ftime[0:2] if fdate == dateNoHyphens and fhour == hour: print file cmd = 'wget '+file os.system(cmd) # correct names of -0.0 files #cmd = 'mmv "*_-0.0.png" "#1_00.0.png"' #os.system(cmd) # rename files and ftp them for file in os.listdir(outDir): if file.startswith('cor_'): if debug: print >>sys.stderr, "file = ",file (filename, file_ext) = os.path.splitext(file) parts = filename.split('_') (date,time) = parts[3].split('-') angle_parts = parts[5].split('.') if len(angle_parts[0]) == 1: angle = '00'+angle_parts[0] elif len(angle_parts[0]) == 2: angle = '0'+angle_parts[0] else: angle = angle_parts[0] product = parts[2]+'_'+parts[4]+'_'+angle file_cat = category+'.'+platform+'.'+date+time+'.'+product+file_ext if debug: print >>sys.stderr, "file_cat = ",file_cat cmd = 'mv '+file+' '+file_cat os.system(cmd) # ftp file try: catalogFTP = FTP(ftpCatalogServer,ftpCatalogUser) catalogFTP.cwd(catalogDestDir) file = open(file_cat,'rb') catalogFTP.storbinary('STOR '+file_cat,file) file.close() catalogFTP.quit() except Exception as e: print >>sys.stderr, "FTP failed, exception: ", e
107
27.96
106
17
872
python
[{"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_eeb474d05e8588cc_7ad9fdc5", "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": 42, "line_end": 42, "column_start": 12, "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://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmpr7mo7ysm/eeb474d05e8588cc.py", "start": {"line": 42, "col": 12, "offset": 1252}, "end": {"line": 42, "col": 29, "offset": 1269}, "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_eeb474d05e8588cc_4a6c4497", "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": 42, "line_end": 42, "column_start": 12, "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://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpr7mo7ysm/eeb474d05e8588cc.py", "start": {"line": 42, "col": 12, "offset": 1252}, "end": {"line": 42, "col": 29, "offset": 1269}, "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.dangerous-system-call-audit_eeb474d05e8588cc_0ad0e711", "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": 60, "line_end": 60, "column_start": 9, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpr7mo7ysm/eeb474d05e8588cc.py", "start": {"line": 60, "col": 9, "offset": 1806}, "end": {"line": 60, "col": 23, "offset": 1820}, "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_eeb474d05e8588cc_f396c193", "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": 86, "line_end": 86, "column_start": 9, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpr7mo7ysm/eeb474d05e8588cc.py", "start": {"line": 86, "col": 9, "offset": 2689}, "end": {"line": 86, "col": 23, "offset": 2703}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-tainted-env-args_eeb474d05e8588cc_e28a61e7", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 86, "line_end": 86, "column_start": 9, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "path": "/tmp/tmpr7mo7ysm/eeb474d05e8588cc.py", "start": {"line": 86, "col": 9, "offset": 2689}, "end": {"line": 86, "col": 23, "offset": 2703}, "extra": {"message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.insecure-transport.ftplib.use-ftp-tls_eeb474d05e8588cc_367398d2", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.insecure-transport.ftplib.use-ftp-tls", "finding_type": "security", "severity": "low", "confidence": "low", "message": "The 'FTP' class sends information unencrypted. Consider using the 'FTP_TLS' class instead.", "remediation": "FTP_TLS(ftpCatalogServer,ftpCatalogUser, context=ssl.create_default_context())", "location": {"file_path": "unknown", "line_start": 90, "line_end": 90, "column_start": 26, "column_end": 62, "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://docs.python.org/3/library/ftplib.html#ftplib.FTP_TLS", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.insecure-transport.ftplib.use-ftp-tls", "path": "/tmp/tmpr7mo7ysm/eeb474d05e8588cc.py", "start": {"line": 90, "col": 26, "offset": 2762}, "end": {"line": 90, "col": 62, "offset": 2798}, "extra": {"message": "The 'FTP' class sends information unencrypted. Consider using the 'FTP_TLS' class instead.", "fix": "FTP_TLS(ftpCatalogServer,ftpCatalogUser, context=ssl.create_default_context())", "metadata": {"owasp": ["A03:2017 - Sensitive Data Exposure", "A02:2021 - Cryptographic Failures", "A04:2025 - Cryptographic Failures"], "cwe": ["CWE-319: Cleartext Transmission of Sensitive Information"], "references": ["https://docs.python.org/3/library/ftplib.html#ftplib.FTP_TLS"], "category": "security", "technology": ["ftplib"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
6
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-tainted-env-args" ]
[ "security", "security", "security" ]
[ "LOW", "LOW", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH" ]
[ 60, 86, 86 ]
[ 60, 86, 86 ]
[ 9, 9, 9 ]
[ 23, 23, 23 ]
[ "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", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH" ]
ftpCSapr2Images.py
/projDir/uw/scripts/ftpCSapr2Images.py
NCAR/lrose-projects-relampago
BSD-2-Clause
2024-11-18T21:11:17.075376+00:00
1,594,920,890,000
09bcfd09745e1bdc759abbe87c2eb4a812cb6141
2
{ "blob_id": "09bcfd09745e1bdc759abbe87c2eb4a812cb6141", "branch_name": "refs/heads/master", "committer_date": 1594920890000, "content_id": "9c3350384664a220270e4489361ade38e0b776fe", "detected_licenses": [ "MIT" ], "directory_id": "e472833ac2c9f7ecc0c5c87d26d716615a9436ec", "extension": "py", "filename": "camera_cal.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 260362380, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1146, "license": "MIT", "license_type": "permissive", "path": "/camera_cal.py", "provenance": "stack-edu-0054.json.gz:577043", "repo_name": "rajath12/Advanced_Lane_Lines", "revision_date": 1594920890000, "revision_id": "053e0a49ad2211c87517cd8bfcc3d4a84b9f8bef", "snapshot_id": "ee4c09db0db2a68e6a9c0a3e73161ece345764c5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rajath12/Advanced_Lane_Lines/053e0a49ad2211c87517cd8bfcc3d4a84b9f8bef/camera_cal.py", "visit_date": "2022-11-19T08:37:40.228472" }
2.484375
stackv2
import io import matplotlib.pyplot as plt import matplotlib.image as mpimg import glob import cv2 import numpy as np import pickle def calibrate_camera(): '''use calibration images to automatically calculate the undistortion coefficients''' # initialzing imgpoints = [] # 2d image world objpoints = [] # 3d image world objp = np.zeros((6*9,3), np.float32) # size of array is 9 by 6 objp[:,:2] = np.mgrid[0:9,0:6].T.reshape(-1,2) # x and y coordinates cal_set = [] for image in glob.glob('./camera_cal/calibration*.jpg'): # folder path n = mpimg.imread(image) cal_set.append(n) img = np.copy(n) gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) ret,corners = cv2.findChessboardCorners(gray, (9,6), None) if ret == True: imgpoints.append(corners) objpoints.append(objp) img = cv2.drawChessboardCorners(img,(9,6),corners,ret) ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, (6,9) , None, None) with open(b'camera_cal.pickle','wb') as output_file: pickle.dump([mtx,dist],output_file)
35
31.77
96
13
322
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_85d2f06c1444c93f_b54970a7", "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": 35, "line_end": 35, "column_start": 9, "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/tmpr7mo7ysm/85d2f06c1444c93f.py", "start": {"line": 35, "col": 9, "offset": 1111}, "end": {"line": 35, "col": 44, "offset": 1146}, "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" ]
[ 35 ]
[ 35 ]
[ 9 ]
[ 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" ]
camera_cal.py
/camera_cal.py
rajath12/Advanced_Lane_Lines
MIT
2024-11-18T21:11:18.877410+00:00
1,431,694,191,000
a7986fc4856134f491a10dca266409bf04d3aa39
3
{ "blob_id": "a7986fc4856134f491a10dca266409bf04d3aa39", "branch_name": "refs/heads/master", "committer_date": 1431694191000, "content_id": "cb30cebdf36a84e3abd6762a7ac94009c72c9942", "detected_licenses": [ "MIT" ], "directory_id": "35498c1db5b9eb66aeeaef7855213df317288882", "extension": "py", "filename": "renamer.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": 1961, "license": "MIT", "license_type": "permissive", "path": "/renamer.py", "provenance": "stack-edu-0054.json.gz:577067", "repo_name": "kianvde/PianoSimulation", "revision_date": 1431694191000, "revision_id": "50c6f34133826d4eae8038e4dd2c7238339a51e2", "snapshot_id": "3139f25ed1014e4dafe571efd82024db57c4c228", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kianvde/PianoSimulation/50c6f34133826d4eae8038e4dd2c7238339a51e2/renamer.py", "visit_date": "2021-05-30T06:36:05.798453" }
2.59375
stackv2
__author__ = 'kian' import os import time from subprocess import Popen # This file is needed to loop over the different keys and produce their .wav file # NB This uses the bash command 'sed' ! letters = ['A', 'Ab', 'Ad', 'B', 'C', 'Cd', 'D', 'Dd', 'E', 'F', 'Fd', 'G'] nums = ['2', '3', '4', '5'] moduleNext = None par = "Parameters.parameters" names = ['main', 'plot_and_save','update'] present = os.listdir("./Notes") tonePrev = letters[0]+nums[0] threadCount = 0 for j, num in enumerate(nums): for i, letter in enumerate(letters): if num == nums[0]: try: tonePrev = letter+num toneNext = letters[i+1]+num except: break modulePrev = par+tonePrev moduleNext = par+toneNext else: modulePrev = moduleNext tonePrev = toneNext toneNext = letters[i]+num moduleNext = par+toneNext if "piano"+tonePrev+".wav" not in present: print "python thread processing "+tonePrev bashPythoncommand = "/home/kian/anaconda/bin/python" threadCount += 1 p = Popen([bashPythoncommand, 'main.py']) print modulePrev, moduleNext for name in names: bashCommand_module = "sed -i -e 's/" + modulePrev +"/"+ moduleNext+"/g' "+ "./"+name+".py" os.system(bashCommand_module) time.sleep(1) bashCommand_filename = "sed -i -e 's/" + "piano"+tonePrev +"/"+ "piano"+toneNext+"/g' "+ "./"+name+".py" os.system(bashCommand_filename) time.sleep(1) if "piano"+letters[-1]+nums[-1]+".wav" not in present: print "python thread processing "+letters[-1]+nums[-1] bashPythoncommand = "/home/kian/anaconda/bin/python" p = Popen([bashPythoncommand, 'main.py']) threadCount += 1 time.sleep(15) print "Thread starter complete - Total number of threads running: " + str(threadCount)
51
37.47
116
20
527
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_495d7138b35a8dcd_6eb60e77", "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": 13, "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/tmpr7mo7ysm/495d7138b35a8dcd.py", "start": {"line": 40, "col": 13, "offset": 1375}, "end": {"line": 40, "col": 42, "offset": 1404}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_495d7138b35a8dcd_57ec3d5f", "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": 13, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/495d7138b35a8dcd.py", "start": {"line": 41, "col": 13, "offset": 1417}, "end": {"line": 41, "col": 26, "offset": 1430}, "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_495d7138b35a8dcd_6b1f8c85", "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": 43, "line_end": 43, "column_start": 13, "column_end": 44, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpr7mo7ysm/495d7138b35a8dcd.py", "start": {"line": 43, "col": 13, "offset": 1560}, "end": {"line": 43, "col": 44, "offset": 1591}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_495d7138b35a8dcd_35cfeb4f", "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": 44, "line_end": 44, "column_start": 13, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/495d7138b35a8dcd.py", "start": {"line": 44, "col": 13, "offset": 1604}, "end": {"line": 44, "col": 26, "offset": 1617}, "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_495d7138b35a8dcd_3dc5ed2a", "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": 50, "line_end": 50, "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.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/495d7138b35a8dcd.py", "start": {"line": 50, "col": 5, "offset": 1860}, "end": {"line": 50, "col": 19, "offset": 1874}, "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-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, 43 ]
[ 40, 43 ]
[ 13, 13 ]
[ 42, 44 ]
[ "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" ]
renamer.py
/renamer.py
kianvde/PianoSimulation
MIT
2024-11-18T19:03:18.415945+00:00
1,421,517,685,000
fa30b9ba4a29ebf791629079edf3f480058326bd
3
{ "blob_id": "fa30b9ba4a29ebf791629079edf3f480058326bd", "branch_name": "refs/heads/master", "committer_date": 1421517685000, "content_id": "8001a5fac737c7345bbc3102d5ac7693f1fb9621", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "directory_id": "f7565bbadf9e3f1217c96388a953179e2fe22cd2", "extension": "py", "filename": "markram_synapse_dynamics.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 8856645, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1914, "license": "BSD-3-Clause,BSD-2-Clause", "license_type": "permissive", "path": "/lib9ml/python/nineml/examples/examples_from_trunk_pre_merge/AL/markram_synapse_dynamics.py", "provenance": "stack-edu-0054.json.gz:577084", "repo_name": "iraikov/nineml", "revision_date": 1421517685000, "revision_id": "941ceb72e6cd26c55fd03f0029f84ab75ad18485", "snapshot_id": "cf6d9ac09ce2d6bf2f60770803c3d4cc075d7f5e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/iraikov/nineml/941ceb72e6cd26c55fd03f0029f84ab75ad18485/lib9ml/python/nineml/examples/examples_from_trunk_pre_merge/AL/markram_synapse_dynamics.py", "visit_date": "2021-01-17T21:53:11.207408" }
2.671875
stackv2
""" Dynamic synaptic weight implementing phenomenological short term depression and facilitation. Description: Implemented is the ODE form of the short-term depression and facilitation model as described Eq (2) and Eq (3) in [1] or Eq (6) in [2], whereby Eq (2) in [1] seems to have an error in the subscript of u_{n+1}. It should be u_{n}. The model corresponds to the markram_synapse in NEST, which is a simplification of the NEST tsodyks_synapse (synaptic time course is neglected). References: [1] Markram, Wang, Tsodyks (1998) Differential Signaling via the same axon of neocortical pyramidal neurons. PNAS, vol 95, pp. 5323-5328. [2] D. Sussillo, T. Toyoizumi, and W. Maass. Self-tuning of neural circuits through short-term synaptic plasticity. Journal of Neurophysiology, 97:4079-4095, 2007. Author: Eilif Muller, 2010. """ import nineml.abstraction_layer as nineml regimes = [ nineml.Regime( "dR/dt = (1-R)/tau_r", # tau_r is the recovery time constant for depression "du/dt = -(u-U)/tau_f", # tau_f is the time constant of facilitation transitions=nineml.On(nineml.SpikeInputEvent, do=["Wout = u*R*Win", "R -= u*R", "u += U*(1-u)", nineml.PreEventRelay]) # Should I put a SpikeOutputEvent here? )] ports = [nineml.SendPort("Wout")] c1 = nineml.Component("MarkramSynapseDynamics", regimes=regimes, ports=ports) # write to file object f if defined try: # This case is used in the test suite for examples. c1.write(f) except NameError: import os base = "markram_synapse_dynamics" c1.write(base + ".xml") c2 = nineml.parse(base + ".xml") assert c1 == c2 c1.to_dot(base + ".dot") os.system("dot -Tpng %s -o %s" % (base + ".dot", base + ".png"))
61
30.38
97
13
570
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_64c9592c3131a1ab_3aebdcc0", "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": 61, "line_end": 61, "column_start": 5, "column_end": 69, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpr7mo7ysm/64c9592c3131a1ab.py", "start": {"line": 61, "col": 5, "offset": 1849}, "end": {"line": 61, "col": 69, "offset": 1913}, "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" ]
[ 61 ]
[ 61 ]
[ 5 ]
[ 69 ]
[ "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" ]
markram_synapse_dynamics.py
/lib9ml/python/nineml/examples/examples_from_trunk_pre_merge/AL/markram_synapse_dynamics.py
iraikov/nineml
BSD-3-Clause,BSD-2-Clause
2024-11-18T19:03:24.423031+00:00
1,495,456,731,000
182de9b68255fba10d34b354b19c0b8db0d42e34
3
{ "blob_id": "182de9b68255fba10d34b354b19c0b8db0d42e34", "branch_name": "refs/heads/master", "committer_date": 1495459508000, "content_id": "ba24619b3666e8a3934a54d7aff5d9ed4edf3c9a", "detected_licenses": [ "MIT" ], "directory_id": "36c1b439c4d4877806e008d8af1ae95c1477fbeb", "extension": "py", "filename": "93.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 92051994, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1117, "license": "MIT", "license_type": "permissive", "path": "/src/solutions/93.py", "provenance": "stack-edu-0054.json.gz:577165", "repo_name": "bshankar/euler", "revision_date": 1495456731000, "revision_id": "c866a661a94d15d3744c74d85149534efac2ca23", "snapshot_id": "dc141ed752531ca2e4b9ad6744fd530b7c5fc1e2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bshankar/euler/c866a661a94d15d3744c74d85149534efac2ca23/src/solutions/93.py", "visit_date": "2021-07-18T21:56:16.622519" }
3.015625
stackv2
from __future__ import division from math import ceil, floor from itertools import permutations as p, combinations as c def safe_eval(expr): try: return eval(expr) except ZeroDivisionError: return 0 max_cons, max_abcd = 0, 0 operators = ['+', '-', '*', '/']*3 nos_set = [str(i) for i in xrange(1, 10)] for nos_ in c(nos_set, 4): ans = set() for nos in p(nos_): for op in p(operators, 3): # ((a*b)*c)*d (a*(b*c))*d a*((b*c)*d) (a*b)*(c*d) a*(b*(c*d)) a, b, c, d = nos w, t, h = op subs = (a, w, b, t, c, h, d) exprs = ["((%s%s%s)%s%s)%s%s"%subs, "(%s%s(%s%s%s))%s%s"%subs, \ "%s%s((%s%s%s)%s%s)"%subs, "(%s%s%s)%s(%s%s%s)"%subs, \ "%s%s(%s%s(%s%s%s))"%subs] for no in map(safe_eval, exprs): if ceil(no) == floor(no) and no > 0: ans.add(no) # Find maximum consecutive nos k = 1 while k in ans: k += 1 if k > max_cons: max_cons = k-1 max_abcd = ''.join(nos_) print max_abcd, max_cons
41
26.24
76
15
375
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_18d6942b04b66c68_77d38961", "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": 7, "line_end": 7, "column_start": 16, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpr7mo7ysm/18d6942b04b66c68.py", "start": {"line": 7, "col": 16, "offset": 166}, "end": {"line": 7, "col": 26, "offset": 176}, "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" ]
[ 7 ]
[ 7 ]
[ 16 ]
[ 26 ]
[ "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" ]
93.py
/src/solutions/93.py
bshankar/euler
MIT
2024-11-18T19:03:31.210634+00:00
1,549,638,588,000
2a5951d4d64473aba067036776bd9e8a1c09af98
3
{ "blob_id": "2a5951d4d64473aba067036776bd9e8a1c09af98", "branch_name": "refs/heads/master", "committer_date": 1549638588000, "content_id": "6a802ee31135ec1a99d1534f746c936e24330642", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "a2b7e4d364c66e8f2fb54a9ee4d247099310251f", "extension": "py", "filename": "util.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 52237821, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5560, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/vislab/util.py", "provenance": "stack-edu-0054.json.gz:577216", "repo_name": "asanakoy/vislab", "revision_date": 1549638588000, "revision_id": "052a80718d688246db9ba561199f728e138a8c12", "snapshot_id": "aba2fc763569f4a4d7b87ed7c1923e03bbcf8ccc", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/asanakoy/vislab/052a80718d688246db9ba561199f728e138a8c12/vislab/util.py", "visit_date": "2020-04-05T20:16:16.389752" }
2.5625
stackv2
import os import pandas as pd import pymongo import redis import socket import tempfile import cPickle import subprocess import shutil import vislab def zero_results(collection, query): return collection.find(query).limit(1).count() == 0 def exclude_ids_in_collection(image_ids, collection): """ Exclude ids already stored in the collection. Useful for submitting map jobs. """ computed_image_ids = [ x['image_id'] for x in collection.find(fields=['image_id']) ] print 'len(computed_image_ids)', len(computed_image_ids) num_ids = len(image_ids) not_computed_ids = image_ids = list(set(image_ids) - set(computed_image_ids)) print("Cut down on {} existing out of {} total image ids.".format( num_ids - len(not_computed_ids), num_ids)) return not_computed_ids def load_or_generate_df(filename, generator_fn, force=False, args=None): """ If filename does not already exist, gather data with generator_fn, and write to filename. If filename does exist, load from it. """ print 'load_or_generate_df(force={}): {}'.format(force, filename) if not force and os.path.exists(filename): df = pd.read_hdf(filename, 'df') else: print 'Generating' df = generator_fn(args) df.to_hdf(filename, 'df', mode='w') return df def running_on_icsi(): """ Return True if this script is running on the ICSI cluster. """ return socket.gethostname().endswith('ICSI.Berkeley.EDU') def get_mongodb_client(): """ Establish connection to MongoDB. """ try: host, port = vislab.config['servers']['mongo'] connection = pymongo.MongoClient(host, port) except pymongo.errors.ConnectionFailure: raise Exception( "Need a MongoDB server running on {}, port {}".format(host, port)) return connection def get_mozila_request_header(): user_agent = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0" headers = {'User-Agent': user_agent} return headers def print_collection_counts(): """ Print all collections and their counts for all databases in MongoDB. """ client = get_mongodb_client() for db_name in client.database_names(): for coll_name in client[db_name].collection_names(): print('{} |\t\t{}: {}'.format( db_name, coll_name, client[db_name][coll_name].count())) def get_redis_client(host=None, port=None): if host is None or port is None: host, port = vislab.config['servers']['redis'] try: connection = redis.Redis(host, port) connection.ping() except redis.ConnectionError: raise Exception( "Need a Redis server running on {}, port {}".format(host, port)) return connection def pickle_function_call(func_name, args): f, temp_filename = tempfile.mkstemp() with open(temp_filename, 'w') as f: cPickle.dump((func_name, args), f) c = "import os; import cPickle;" c += "f = open('{0}'); func, args = cPickle.load(f); f.close();" c += "os.remove('{0}'); func(*args)" c = c.format(temp_filename) return c def run_through_bash_script(cmds, filename=None, verbose=False, num_workers=1): """ Write out given commands to a bash script file and execute it. This is useful when the commands to run include pipes, or are chained. subprocess is not too easy to use in those cases. Parameters ---------- cmds: list of string filename: string or None [None] If None, a temporary file is used and deleted after. verbose: bool [False] If True, output the commands that will be run. num_workers: int [1] If > 1, commands are piped through parallel -j num_workers """ assert(num_workers > 0) remove_file = False if filename is None: f, filename = tempfile.mkstemp() remove_file = True if num_workers > 1: contents = "echo \"{}\" | parallel --env PATH -j {}".format( '\n'.join(cmds), num_workers) else: contents = '\n'.join(cmds) with open(filename, 'w') as f: f.write(contents + '\n') if verbose: print("Contents of script file about to be run:") print(contents) p = subprocess.Popen(['bash', filename]) out, err = p.communicate() if remove_file: os.remove(filename) if not p.returncode == 0: print(out) print(err) raise Exception("Script exited with code {}".format(p.returncode)) def run_shell_cmd(cmd, echo=True): """ Run a command in a sub-shell, capturing stdout and stderr to temporary files that are then read. """ _, stdout_f = tempfile.mkstemp() _, stderr_f = tempfile.mkstemp() print("Running command") print(cmd) p = subprocess.Popen( '{} >{} 2>{}'.format(cmd, stdout_f, stderr_f), shell=True) p.wait() with open(stdout_f) as f: stdout = f.read() os.remove(stdout_f) with open(stderr_f) as f: stderr = f.read() os.remove(stderr_f) if echo: print("stdout:") print(stdout) print("stderr:") print(stderr) return stdout, stderr def makedirs(dirname): if os.path.exists(dirname): return dirname try: os.makedirs(dirname) except OSError: pass except: raise return dirname def cleardirs(dirname): if os.path.exists(dirname): shutil.rmtree(dirname) return makedirs(dirname)
202
26.52
95
17
1,330
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_4599d30ce0f657ff_73424ac5", "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": 100, "line_end": 100, "column_start": 10, "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/tmpr7mo7ysm/4599d30ce0f657ff.py", "start": {"line": 100, "col": 10, "offset": 2916}, "end": {"line": 100, "col": 34, "offset": 2940}, "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_4599d30ce0f657ff_9cf8f8b0", "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": 101, "line_end": 101, "column_start": 9, "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/tmpr7mo7ysm/4599d30ce0f657ff.py", "start": {"line": 101, "col": 9, "offset": 2955}, "end": {"line": 101, "col": 43, "offset": 2989}, "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_4599d30ce0f657ff_022de234", "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": 138, "line_end": 138, "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/tmpr7mo7ysm/4599d30ce0f657ff.py", "start": {"line": 138, "col": 10, "offset": 4139}, "end": {"line": 138, "col": 29, "offset": 4158}, "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_4599d30ce0f657ff_172f50f4", "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": 166, "line_end": 167, "column_start": 9, "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/tmpr7mo7ysm/4599d30ce0f657ff.py", "start": {"line": 166, "col": 9, "offset": 4851}, "end": {"line": 167, "col": 67, "offset": 4935}, "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_4599d30ce0f657ff_716cca63", "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": 170, "line_end": 170, "column_start": 10, "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/tmpr7mo7ysm/4599d30ce0f657ff.py", "start": {"line": 170, "col": 10, "offset": 4959}, "end": {"line": 170, "col": 24, "offset": 4973}, "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_4599d30ce0f657ff_7e31a6b5", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 174, "line_end": 174, "column_start": 10, "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/tmpr7mo7ysm/4599d30ce0f657ff.py", "start": {"line": 174, "col": 10, "offset": 5040}, "end": {"line": 174, "col": 24, "offset": 5054}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
6
true
[ "CWE-502", "CWE-78" ]
[ "rules.python.lang.security.deserialization.avoid-cPickle", "rules.python.lang.security.audit.dangerous-subprocess-use-audit" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "HIGH" ]
[ 101, 166 ]
[ 101, 167 ]
[ 9, 9 ]
[ 43, 67 ]
[ "A08:2017 - Insecure Deserialization", "A01:2017 - Injection" ]
[ "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.", "Detected subprocess function 'Popen' without a...
[ 5, 7.5 ]
[ "LOW", "LOW" ]
[ "MEDIUM", "HIGH" ]
util.py
/vislab/util.py
asanakoy/vislab
BSD-2-Clause
2024-11-18T19:03:35.595898+00:00
1,608,905,044,000
188d2aa2fb2e3be903cdc96de9ccceb7a79e6318
4
{ "blob_id": "188d2aa2fb2e3be903cdc96de9ccceb7a79e6318", "branch_name": "refs/heads/master", "committer_date": 1608905044000, "content_id": "4f6bd5e6a5de30684993d7daf90749aecc6eebee", "detected_licenses": [ "MIT" ], "directory_id": "857fc21a40aa32d2a57637de1c723e4ab51062ff", "extension": "py", "filename": "009_05.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 171432914, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1012, "license": "MIT", "license_type": "permissive", "path": "/FishCDailyQuestion/ex001-010/Python3_009/009_05.py", "provenance": "stack-edu-0054.json.gz:577235", "repo_name": "YorkFish/git_study", "revision_date": 1608905044000, "revision_id": "6e023244daaa22e12b24e632e76a13e5066f2947", "snapshot_id": "efa0149f94623d685e005d58dbaef405ab91d541", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/YorkFish/git_study/6e023244daaa22e12b24e632e76a13e5066f2947/FishCDailyQuestion/ex001-010/Python3_009/009_05.py", "visit_date": "2021-06-21T18:46:50.906441" }
3.96875
stackv2
#!/usr/bin/evn python3 # coding:utf-8 # 009_03.py 的另一种改进 def collect_prime(n): # (*) global prime_lst # 话说回来,这句不写也行 for i in range(2, int(n**0.5)+1): if n % i == 0: prime_lst.append(str(i)) return collect_prime(n//i) prime_lst.append(str(n)) # 最后一个质因数 return prime_lst prime_lst = [] # 输入数据并检查数据的合法性 num_input = input("Please enter a natural number greater than 1: ") while not num_input.isdigit() or eval(num_input) < 2: num_input = input("Please enter a positive integer greater than 1 again: ") print(num_input, "=", " x ".join(collect_prime(int(num_input)))) ''' (*) 可以改成如下样子 def collect_prime(n): k = 2 while n != 1: if n % k == 0: prime_lst.append(str(k)) return collect_prime(n//k) k += 1 相应的输出要改为 collect_prime(int(num_input)) print(num_input, "=", " x ".join(prime_lst)) '''
38
22.84
79
13
279
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_516cf7045eafa8d0_2601412c", "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": 19, "line_end": 19, "column_start": 34, "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/tmpr7mo7ysm/516cf7045eafa8d0.py", "start": {"line": 19, "col": 34, "offset": 541}, "end": {"line": 19, "col": 49, "offset": 556}, "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" ]
[ 19 ]
[ 19 ]
[ 34 ]
[ 49 ]
[ "A03:2021 - Injection" ]
[ "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources." ]
[ 5 ]
[ "LOW" ]
[ "HIGH" ]
009_05.py
/FishCDailyQuestion/ex001-010/Python3_009/009_05.py
YorkFish/git_study
MIT
2024-11-18T19:03:35.854214+00:00
126,230,400,000
d2a02b5b0e5d5390f54c6c0c85a82122b60fa408
3
{ "blob_id": "d2a02b5b0e5d5390f54c6c0c85a82122b60fa408", "branch_name": "refs/heads/master", "committer_date": 1466765588000, "content_id": "bd0e1b55a6e9b433b218ebcedad56fab54a72ed0", "detected_licenses": [ "Apache-2.0" ], "directory_id": "b6b06f676a0435b32d3e323381b9f6fa67d83cae", "extension": "py", "filename": "generate.py", "fork_events_count": 2, "gha_created_at": 1456786598000, "gha_event_created_at": 1582152258000, "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 52831053, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5844, "license": "Apache-2.0", "license_type": "permissive", "path": "/tools/generate.py", "provenance": "stack-edu-0054.json.gz:577239", "repo_name": "sunfishcode/design", "revision_date": 126230400000, "revision_id": "0167aee27975030d80a537c5190b4579a38b98c4", "snapshot_id": "db01b65aa5b244f90f5d54d7960a60888333bce3", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/sunfishcode/design/0167aee27975030d80a537c5190b4579a38b98c4/tools/generate.py", "visit_date": "2021-01-18T09:27:57.162028" }
2.65625
stackv2
#!/usr/bin/env python """ Markdown documentation generator and checker. Generate HTML documentation from Markdown files in the current working directory, and check that their links are valid. """ import BaseHTTPServer import argparse import itertools import os import re import socket import string import subprocess import sys import urllib2 class CheckDir(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): d = values if not os.path.isdir(d): raise argparse.ArgumentTypeError('Invalid directory "%s"' % d) if os.access(d, os.R_OK): setattr(namespace, self.dest, d) else: raise argparse.ArgumentTypeError('Cannot read directory "%s"' % d) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--socket-timeout', type=int, default=30, help='timeout for URL fetch (seconds)') parser.add_argument('--dir', type=str, action=CheckDir, default=os.getcwd(), help='Markdown file location (default: current)') parser.add_argument('--out', type=str, default='out', help='subdirectory for output HTML files') parser.add_argument('--markdown', type=str, default='markdown', help='Markdown generator program') parser.add_argument('--extension', type=str, default='.md', help='Markdown file extension') parser.add_argument('--html', type=str, default='.html', help='HTML file extension') parser.add_argument('--link_regex', type=str, default='href="([^"]+)"', help='Regular expression used to find links in HTML') args = parser.parse_args() socket.setdefaulttimeout(args.socket_timeout) href = re.compile(args.link_regex) template = """<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>$title: WebAssembly</title> </head> <body> $content </body> </html> """ def trunc_extension(filename, extension): return filename[:-len(extension)] def find_markdown_sources(): return sorted([trunc_extension(f, args.extension) for f in os.listdir(args.dir) if f.endswith(args.extension)]) def start_threadpool(): from multiprocessing import Pool return Pool() def path_to_markdown(name): return os.path.join(args.dir, name + args.extension) def create_outdir(): path = os.path.join(args.dir, args.out) if not os.path.exists(path): os.makedirs(path) def path_to_html(name): return os.path.join(args.dir, args.out, name + args.html) def generate_html(name): md_sp = subprocess.Popen( [args.markdown, path_to_markdown(name)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) md_out, md_err = md_sp.communicate() md_code = md_sp.returncode if not md_code: with open(path_to_html(name), 'w+') as html: t = string.Template(template) html.write(t.substitute(title=name, content=md_out)) return (name, md_code, md_err) def check_generated(generated): errors = 0 for g in generated: if g[1]: errors = errors + 1 print '\t%s failed with code %i: %s' % g else: print '\t%s' % g[0] if errors: sys.exit(1) def collect_links_from_html(name): html = open(path_to_html(name), 'r').read() return re.findall(href, html) def flatten_and_deduplicate(list_of_lists): return sorted(list(set(itertools.chain(*list_of_lists)))) def check_inner_link(link): parts = link.split('#') if not parts[0].endswith(args.extension): return (link, 'Not a link to an internal markdown file') name = trunc_extension(parts[0], args.extension) md = path_to_markdown(name) if not os.path.isfile(md): return (link, 'No such markdown file') if len(parts) == 1: return (link, None) if len(parts) > 2: return (link, 'Too many hashes in link') with open(path_to_html(name), 'r') as html: # TODO: The current Markdown generator doesn't output link IDs, whereas # github's Markdown generator does output the IDs. return (link, None) def check_outer_link(link): req = urllib2.Request(link) try: urllib2.urlopen(req) except ValueError as e: return (link, 'Value error ' + e.args[0]) except urllib2.URLError as e: return (link, 'URL error ' + str(e.reason)) except urllib2.HTTPError as e: responses = BaseHTTPServer.BaseHTTPRequestHandler.responses return (link, 'HTTP error ' + responses[e.code()]) except socket.timeout as e: return (link, 'Socket timeout after %i seconds' % args.socket_timeout) return (link, None) def print_invalid_links(links): errors = 0 for link in links: if link[1]: errors = errors + 1 print ' Invalid link "%s": %s.' % link return errors if __name__ == '__main__': sources = find_markdown_sources() print 'Found %i markdown sources:' % len(sources) pool = start_threadpool() create_outdir() generated = pool.map(generate_html, sources) check_generated(generated) links = flatten_and_deduplicate(pool.map(collect_links_from_html, sources)) inner_links = [l for l in links if l.startswith(tuple(sources))] outer_links = [l for l in links if not l.startswith(tuple(sources))] print ('Found %i unique inner links, and %i unique outer links.' % (len(inner_links), len(outer_links))) bad_inner = print_invalid_links(pool.map(check_inner_link, inner_links)) bad_outer = print_invalid_links(pool.map(check_outer_link, outer_links)) if not (bad_inner or bad_outer): print 'No invalid links.' else: print 'Found %i bad inner and %i outer links.' % (bad_inner, bad_outer) sys.exit(1)
176
32.2
79
14
1,336
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_3fa683d34e67ea54_32c7ffc7", "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": 86, "line_end": 88, "column_start": 13, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/3fa683d34e67ea54.py", "start": {"line": 86, "col": 13, "offset": 2595}, "end": {"line": 88, "col": 56, "offset": 2717}, "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_3fa683d34e67ea54_56e54775", "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": 87, "line_end": 87, "column_start": 9, "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-tainted-env-args", "path": "/tmp/tmpr7mo7ysm/3fa683d34e67ea54.py", "start": {"line": 87, "col": 9, "offset": 2621}, "end": {"line": 87, "col": 48, "offset": 2660}, "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.best-practice.unspecified-open-encoding_3fa683d34e67ea54_2980536c", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 92, "line_end": 92, "column_start": 14, "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/tmpr7mo7ysm/3fa683d34e67ea54.py", "start": {"line": 92, "col": 14, "offset": 2823}, "end": {"line": 92, "col": 44, "offset": 2853}, "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_3fa683d34e67ea54_b93d9b90", "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": 109, "line_end": 109, "column_start": 12, "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/tmpr7mo7ysm/3fa683d34e67ea54.py", "start": {"line": 109, "col": 12, "offset": 3307}, "end": {"line": 109, "col": 41, "offset": 3336}, "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_3fa683d34e67ea54_be513396", "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": 127, "line_end": 127, "column_start": 10, "column_end": 39, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/3fa683d34e67ea54.py", "start": {"line": 127, "col": 10, "offset": 3949}, "end": {"line": 127, "col": 39, "offset": 3978}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
5
true
[ "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args" ]
[ "security", "security" ]
[ "LOW", "MEDIUM" ]
[ "HIGH", "HIGH" ]
[ 86, 87 ]
[ 88, 87 ]
[ 13, 9 ]
[ 56, 48 ]
[ "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", "MEDIUM" ]
[ "HIGH", "MEDIUM" ]
generate.py
/tools/generate.py
sunfishcode/design
Apache-2.0
2024-11-18T19:03:36.735971+00:00
1,689,003,010,000
3d39d6fe505bb1d96a6515d531f9d229fc2b363c
3
{ "blob_id": "3d39d6fe505bb1d96a6515d531f9d229fc2b363c", "branch_name": "refs/heads/main", "committer_date": 1689003010000, "content_id": "9958c250754549e2994a6ac5f334b0014ace5303", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "directory_id": "64f5452be7258631986b980448629c6b189c3624", "extension": "py", "filename": "spec2.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 127958832, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3800, "license": "MIT,BSD-3-Clause", "license_type": "permissive", "path": "/nirspec/backgrounds/spec2.py", "provenance": "stack-edu-0054.json.gz:577252", "repo_name": "mkelley/jwst-comets", "revision_date": 1689003010000, "revision_id": "fde1474ea71c916313d4068b1e3b7b8ae7307655", "snapshot_id": "9a652ed73e2c5d9bb58abcfe396acea954aebf2a", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/mkelley/jwst-comets/fde1474ea71c916313d4068b1e3b7b8ae7307655/nirspec/backgrounds/spec2.py", "visit_date": "2023-07-19T21:08:47.578076" }
2.640625
stackv2
""" Author: Michael S. P. Kelley Background subtract and de-stripe NIRSpec IFU data, then run the stage 2 spectroscopic pipeline. NIRSpec observations of 22P/Kopff from program 1252 observed the comet at all requested instrument settings, then moved to the background and repeated the observation sequence. This is not ideal as the instrument may not return to the exact grating settings. Typically, one would rather observe both the target and background before changing instrument settings. However, in the interest of time efficiency, the slew to the background was only done once. When the background step is enabled, the pipeline compares the grating positions of the target and background files. If they do not precisely match, the background is not subtracted. This script bypasses that test and subtracts a background. In addition to the background subtraction, vertical striping (1/f noise?) is also measured with a sigma-clipped median and removed. """ import os from glob import glob import numpy as np import scipy.ndimage as nd from astropy.io import fits from astropy.stats import sigma_clip from jwst.pipeline.calwebb_spec2 import Spec2Pipeline from jwst.background.background_sub import background_sub from jwst import datamodels import stdatamodels import crds output_dir = "processed" # files to process, must be _rate files input_files = glob("data/jw01252001001_03101_0000?_nrs1/*_rate.fits") # define the area outside of the spectra for de-striping using the sflat h = fits.getheader(input_files[0]) ref = crds.getreferences(h, reftypes=["sflat"]) spec_mask = fits.getdata(ref["sflat"]) != 0 # grow the mask by a couple pixels spec_mask = nd.binary_dilation(spec_mask, iterations=2) # files for manual background subtraction to bypass grating position test background_files = glob("data/jw01252002001_03101_*nrs1/*_rate.fits") for fn in input_files: # output file name outf = fn.replace("data/", f"{output_dir}/") if os.path.exists(outf): print("skipping", outf, "(file already exists)") continue # create directories as needed os.system(f"mkdir -p {os.path.dirname(outf)}") # copied-edited code from jwst.background.background_step with datamodels.open(fn) as input_model: bkg_model, result = background_sub( input_model, background_files, 3.0, None ) result.meta.cal_step.back_sub = "COMPLETE" # remove vertical stripes im = np.ma.MaskedArray(result.data, mask=spec_mask) clipped = sigma_clip(im, axis=0, sigma=2.5) stripes = np.outer(np.ones(im.shape[0]), np.ma.mean(clipped, axis=0)) result.data -= stripes # This seems like the right way to add a history entry, but I don't see # it in the resulting FITS file. Possibly because the history has not # been created. comment = stdatamodels.util.create_history_entry("De-striped") result.history.append(comment) # save the file result.save(outf) # save the background bkg_model.save(outf.replace("_rate", "_rate_combinedbackground")) # process with the stage 2 pipeline as usual, but do not run the background step input_files = glob(f"{output_dir}/jw01252001001_03101_0000?_nrs1/*_rate.fits") for fn in input_files: out_file = fn.replace("rate", "s3d") if os.path.exists(out_file): # compare modification times, update as needed rate_stat = os.stat(fn) s3d_stat = os.stat(out_file) if rate_stat.st_mtime < s3d_stat.st_mtime: print("skipping", out_file, "(s3d is newer than rate).") continue Spec2Pipeline.call( fn, config_file="spec2.asdf", output_dir=os.path.dirname(fn), logcfg="jwst-pipeline-log.cfg", )
103
35.89
80
14
973
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_696da506395b1c2e_59c01ba9", "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": 59, "line_end": 59, "column_start": 5, "column_end": 51, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpr7mo7ysm/696da506395b1c2e.py", "start": {"line": 59, "col": 5, "offset": 2101}, "end": {"line": 59, "col": 51, "offset": 2147}, "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" ]
[ 59 ]
[ 59 ]
[ 5 ]
[ 51 ]
[ "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" ]
spec2.py
/nirspec/backgrounds/spec2.py
mkelley/jwst-comets
MIT,BSD-3-Clause
2024-11-18T19:03:41.179237+00:00
1,524,986,437,000
bf39282cb4f1850cea1807ebeb0e7811f47035a5
2
{ "blob_id": "bf39282cb4f1850cea1807ebeb0e7811f47035a5", "branch_name": "refs/heads/master", "committer_date": 1524986437000, "content_id": "62e2d6cc2876b534f8977d14e4f215f4893a779a", "detected_licenses": [ "MIT" ], "directory_id": "882797fdb8a311796969a882a81fe76aac8becb3", "extension": "py", "filename": "train.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 131409730, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5451, "license": "MIT", "license_type": "permissive", "path": "/train.py", "provenance": "stack-edu-0054.json.gz:577294", "repo_name": "Kexiii/pytorch-hymenoptera", "revision_date": 1524986437000, "revision_id": "4c9f8efee3fd455c135cd42c74bc5199b7d0764e", "snapshot_id": "b2b8533ed8f873452892af50273f09440e05c7db", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/Kexiii/pytorch-hymenoptera/4c9f8efee3fd455c135cd42c74bc5199b7d0764e/train.py", "visit_date": "2021-07-07T14:22:46.419159" }
2.46875
stackv2
from __future__ import print_function, division import torch import torch.optim as optim import torch.nn.functional as F from torch.autograd import Variable import time from datetime import datetime import os import copy import json import argparse import pickle from data_loader.data_loader import get_data_loaders from utils.util import adjust_learning_rate from utils.util import model_snapshot from utils.util import ensure_dir from model.resnet import get_resnet parser = argparse.ArgumentParser(description='Test your model') parser.add_argument('--resume',help='Resume from previous work') def main(): args = parser.parse_args() config = json.load(open("config.json")) torch.manual_seed(config['seed']) torch.cuda.manual_seed(config['seed']) model = get_resnet().cuda() if args.resume is not None: print("Resume from previous work") model.load_state_dict(torch.load(args.resume)) optimizer = optim.SGD(model.parameters(), lr=config['lr'], weight_decay=config['weight_decay']) train(config,model,optimizer) def train(config,model,optimizer): """Train the model Params: config: json config data model: model to train optimizer: optimizer used in training Return: None """ data_loaders = get_data_loaders() ensure_dir(config['log_dir']) t_begin = time.time() best_acc, old_file = 0, None history = {'train':{'loss':[],'acc':[]},'val':{'loss':[],'acc':[]}} for epoch in range(config['epoch_num']): model.train() # train phase epoch_loss = 0 epoch_correct = 0 adjust_learning_rate(config,optimizer,epoch) for batch_idx, (data,target) in enumerate(data_loaders['train']): indx_target = target.clone() data, target = Variable(data.cuda()),Variable(target.cuda()) optimizer.zero_grad() output = model(data) #define your own loss function here loss = F.cross_entropy(output,target) epoch_loss += loss.data[0] loss.backward() optimizer.step() pred = output.data.max(1)[1] correct = pred.cpu().eq(indx_target).sum() epoch_correct += correct if config['batch_log'] and batch_idx % config['batch_log_interval'] == 0 and batch_idx > 0: acc = correct * 1.0 / len(data) print('Train Epoch: {} [{}/{}] Batch_Loss: {:.6f} Batch_Acc: {:.4f} lr: {:.2e}'.format( epoch, batch_idx * len(data), len(data_loaders['train'].dataset), loss.data[0], acc, optimizer.param_groups[0]['lr'])) elapse_time = time.time() - t_begin speed_epoch = elapse_time / (epoch + 1) speed_batch = speed_epoch / len(data_loaders['train']) eta = speed_epoch * config['epoch_num'] - elapse_time print("{}/{} Elapsed {:.2f}s, {:.2f} s/epoch, {:.2f} s/batch, ets {:.2f}s".format(epoch+1, config['epoch_num'],elapse_time, speed_epoch, speed_batch, eta)) epoch_loss = epoch_loss / len(data_loaders['train']) # average over number of mini-batch acc = 100. * epoch_correct / len(data_loaders['train'].dataset) print('\tTrain set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)'.format( epoch_loss, epoch_correct, len(data_loaders['train'].dataset), acc)) history['train']['loss'].append(epoch_loss) history['train']['acc'].append(acc) model_snapshot(model, os.path.join(config['log_dir'], 'latest.pth')) if epoch % config['val_interval'] == 0: model.eval() val_loss = 0 correct = 0 for data, target in data_loaders['val']: indx_target = target.clone() data, target = Variable(data.cuda(),volatile=True), Variable(target.cuda()) output = model(data) val_loss += F.cross_entropy(output, target).data[0] pred = output.data.max(1)[1] # get the index of the max log-probability correct += pred.cpu().eq(indx_target).sum() val_loss = val_loss / len(data_loaders['val']) # average over number of mini-batch acc = 100. * correct / len(data_loaders['val'].dataset) print('\tVal set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)'.format( val_loss, correct, len(data_loaders['val'].dataset), acc)) history['val']['loss'].append(val_loss) history['val']['acc'].append(acc) if acc > best_acc: new_file = os.path.join(config['log_dir'], datetime.now().strftime('%Y-%m-%d-%H-%M-%S')+'-best-{}.pth'.format(epoch)) model_snapshot(model, new_file, old_file=old_file, verbose=True) best_acc = acc old_file = new_file f = open(config['history'],'wb') try: pickle.dump(history,f) finally: f.close() print("Total Elapse: {:.2f}s, Best Val Acc: {:.3f}%".format(time.time()-t_begin, best_acc)) if __name__ == "__main__": assert torch.cuda.is_available() main()
128
40.6
133
20
1,231
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_12400758abd4cb9b_94780887", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 26, "line_end": 26, "column_start": 24, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/12400758abd4cb9b.py", "start": {"line": 26, "col": 24, "offset": 671}, "end": {"line": 26, "col": 43, "offset": 690}, "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_12400758abd4cb9b_f759b11f", "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": 120, "line_end": 120, "column_start": 9, "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/tmpr7mo7ysm/12400758abd4cb9b.py", "start": {"line": 120, "col": 9, "offset": 5078}, "end": {"line": 120, "col": 31, "offset": 5100}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 120 ]
[ 120 ]
[ 9 ]
[ 31 ]
[ "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format." ]
[ 5 ]
[ "LOW" ]
[ "MEDIUM" ]
train.py
/train.py
Kexiii/pytorch-hymenoptera
MIT
2024-11-18T19:03:41.582824+00:00
1,550,162,992,000
ec4b0f03c577db35877f5512a3a30957deb98ec2
2
{ "blob_id": "ec4b0f03c577db35877f5512a3a30957deb98ec2", "branch_name": "refs/heads/master", "committer_date": 1550162992000, "content_id": "be4431a05eebdc351af86149b5deb5d55304a641", "detected_licenses": [ "MIT" ], "directory_id": "cabeeb10c64d7137b9b14f94c7859070bd3d77e5", "extension": "py", "filename": "init_groups.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 167034951, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3158, "license": "MIT", "license_type": "permissive", "path": "/no-smoke-search-app/model/init_groups.py", "provenance": "stack-edu-0054.json.gz:577299", "repo_name": "ViktorMarinov/no-smoke-search", "revision_date": 1550162992000, "revision_id": "5f6f07a78ab460df9f49dd43dc050fe881ace9cc", "snapshot_id": "bf3463d65c7a9c4badd68079397c12aee957a17a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ViktorMarinov/no-smoke-search/5f6f07a78ab460df9f49dd43dc050fe881ace9cc/no-smoke-search-app/model/init_groups.py", "visit_date": "2020-04-17T23:25:44.340254" }
2.421875
stackv2
import load_sample import pandas as pd from pandas import DataFrame from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity from os.path import join from copy import deepcopy import time import datetime from queue import LifoQueue import pickle sample = load_sample.sample ids_to_rows = load_sample.ids_to_rows ixs_to_rows = load_sample.ixs_to_rows stopwords_sample = pd.read_json(join('..', 'data', 'index', 'stopwords-bg.json'))[259:] short_stop_word = stopwords_sample[stopwords_sample[0].apply(lambda x: len(x) <= 3)][0] search_tokens_text = sample['tokens'].apply(lambda x: ' '.join(x)) tfidf_vectorizer = TfidfVectorizer(stop_words=short_stop_word.tolist()) tfidf_vectorizer.fit_transform(search_tokens_text) train_corpus_vectors = tfidf_vectorizer.transform(search_tokens_text) def time_now(): ts = time.time() return datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') print(time_now(), "Loading corpus similarity") try: dup_pairs_df = pd.read_json(join('data', 'dup_pairs.json'), orient='split') dup_pairs = [tuple(x) for x in dup_pairs_df.values] except: print(time_now(), "Count not read 'data/dup_pairs.json'. Creating...") duplicates = cosine_similarity(train_corpus_vectors, train_corpus_vectors) dup_pairs = [] for i in range(len(sample)): for j in range(len(sample)): if duplicates[i, j] >= 0.9 and i < j: dup_pairs.append((i, j)) DataFrame(data=dup_pairs).to_json(join('data', 'dup_pairs.json'), orient='split') dup_pairs_df = pd.read_json(join('data', 'dup_pairs.json'), orient='split') print(time_now(), "Loading ready:", len(dup_pairs), " pairs loaded.") def has_more(tuples, ix): return any(filter(lambda x: x[0] == ix or x[1] == ix, tuples)) def find_first(tuples, ix): return next((x[0] for x in tuples if x[1] == ix), None) def get_dups_group_iter(tuples, ix): group = set() queue = LifoQueue() queue.put(ix) visited = set() while not queue.empty(): current = queue.get() group.add(current) for i, (ix1, ix2) in enumerate(tuples): if i in visited: continue if ix1 == current: visited.add(i) queue.put(ix2) elif ix2 == current: visited.add(i) queue.put(ix1) return group starters = set(map(lambda x: x[0], dup_pairs)) def find_all_groups(tuples, ixs): all_groups = list() l = len(starters) for i, ix in enumerate(starters): print("{0:0.2f}".format(float(i) * 100/ l) , " %") if not any(map(lambda group: ix in group, all_groups)): all_groups.append(get_dups_group_iter(dup_pairs, ix)) return all_groups print(time_now(), "Groups loading...") all_grs = find_all_groups(dup_pairs, starters) with open(join('data', 'dup_groups.p'), 'wb') as fp: pickle.dump(all_grs, fp, protocol=pickle.HIGHEST_PROTOCOL) # with open(join('data', 'dup_groups.p'), 'rb') as fp: # data = pickle.load(fp) # if data == print(time_now(), "Done...")
104
29.37
87
15
799
python
[{"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_610ab08bacb7b2da_89d7f355", "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": 18, "line_end": 18, "column_start": 72, "column_end": 83, "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/tmpr7mo7ysm/610ab08bacb7b2da.py", "start": {"line": 18, "col": 72, "offset": 569}, "end": {"line": 18, "col": 83, "offset": 580}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_610ab08bacb7b2da_3db83ddb", "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": 20, "line_end": 20, "column_start": 55, "column_end": 66, "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/tmpr7mo7ysm/610ab08bacb7b2da.py", "start": {"line": 20, "col": 55, "offset": 641}, "end": {"line": 20, "col": 66, "offset": 652}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_610ab08bacb7b2da_d03af63d", "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": 80, "line_end": 80, "column_start": 30, "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.return-not-in-function", "path": "/tmp/tmpr7mo7ysm/610ab08bacb7b2da.py", "start": {"line": 80, "col": 30, "offset": 2463}, "end": {"line": 80, "col": 34, "offset": 2467}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_610ab08bacb7b2da_50800921", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 96, "line_end": 96, "column_start": 5, "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-pickle", "path": "/tmp/tmpr7mo7ysm/610ab08bacb7b2da.py", "start": {"line": 96, "col": 5, "offset": 2965}, "end": {"line": 96, "col": 63, "offset": 3023}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
4
true
[ "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 96 ]
[ 96 ]
[ 5 ]
[ 63 ]
[ "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" ]
init_groups.py
/no-smoke-search-app/model/init_groups.py
ViktorMarinov/no-smoke-search
MIT
2024-11-18T19:03:41.816500+00:00
1,680,525,552,000
383caace0611a0df2a314a8411e651e2dacfb256
2
{ "blob_id": "383caace0611a0df2a314a8411e651e2dacfb256", "branch_name": "refs/heads/master", "committer_date": 1680525552000, "content_id": "c8559b2f250a03f9efda3e824c0d6f5417899ea4", "detected_licenses": [ "MIT" ], "directory_id": "ef414bf6e76b5a8252c2bbdaff776f382d2ff667", "extension": "py", "filename": "nzp_gs_smooth.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 231343130, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11125, "license": "MIT", "license_type": "permissive", "path": "/nzp_gs_smooth.py", "provenance": "stack-edu-0054.json.gz:577302", "repo_name": "cau-riken/nzp_gs_smooth_standalone", "revision_date": 1680525552000, "revision_id": "9f63f42e4953a95c29124a7db22512dff3d45fb4", "snapshot_id": "09906292d443d121561c131bef715aa0dbe88d6f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cau-riken/nzp_gs_smooth_standalone/9f63f42e4953a95c29124a7db22512dff3d45fb4/nzp_gs_smooth.py", "visit_date": "2023-04-14T15:57:12.747829" }
2.484375
stackv2
# -*- coding: utf-8 -*- """ Apply Gauss-Seidel Iteration Scheme to smooth high-frequency distortions across a slice stack. NOTE: Nipype ready code - inner functions used inside the 'run' function. Author: Alexander Woodward, Connectome Analysis Unit, RIKEN CBS, Wako, Japan Email: alexander.woodward@riken.jp """ def run(in_dir, cur_dir, out_dir_images, out_dir_transforms, iterations, ants_thread_count): """Apply Gauss-Seidel Iteration Scheme algorithm to a folder of images in sequence. Args: in_dir: The folder of images to process. Images should be padded with leading zeroes and a starting index of 1, e.g. slice_001.tif cur_dir: The current directory to work from. out_dir_images: The directory to place the transformed images. out_dir_transforms: Directory for calculated transforms. iterations: Number of iterations of G.S. smoothing, 2,4 is recommended. ants_thread_count: Number of threads assigned to the antsRegistration program. """ import numpy as np # TODO(AW): Remove dependency on OpenCV and use only SimpleITK calls import cv2 import subprocess import SimpleITK as sitk import copy from nipype.interfaces.ants import Registration from natsort import natsorted def reg_run( fixed_image, moving_image, output_transform_prefix, output_warped_image, ants_thread_count): # os.environ['PATH']+=':/path_to_antsbin' reg = Registration() reg.inputs.fixed_image = fixed_image reg.inputs.moving_image = moving_image reg.inputs.output_transform_prefix = output_transform_prefix reg.inputs.transforms = ['SyN'] reg.inputs.transform_parameters = [(0.01,)] reg.inputs.number_of_iterations = [[200, 200, 200, 200, 150, 50]] # reg.inputs.number_of_iterations = [[50,50,50,40,30,20]] reg.inputs.dimension = 2 reg.inputs.num_threads = ants_thread_count reg.inputs.metric = ['Mattes'] # Default (value ignored currently by ANTs) reg.inputs.metric_weight = [1] reg.inputs.radius_or_number_of_bins = [32] reg.inputs.sampling_strategy = ['Regular'] reg.inputs.sampling_percentage = [1.0] # 0.3] reg.inputs.convergence_threshold = [1.e-8] reg.inputs.convergence_window_size = [10] reg.inputs.smoothing_sigmas = [[6, 5, 4, 3, 2, 1]] reg.inputs.sigma_units = ['vox'] reg.inputs.shrink_factors = [[6, 5, 4, 3, 2, 1]] reg.inputs.use_estimate_learning_rate_once = [True] reg.inputs.use_histogram_matching = [True] # This is the default reg.inputs.output_warped_image = output_warped_image reg1 = copy.deepcopy(reg) # reg1.cmdline reg1.run() # Be careful to scale by the pixel size when using both SimpleITK and # OpenCV functions def deform_image(img_in, deform_in, scale_factor, out_filename): spacing = img_in.GetSpacing() img_a = sitk.GetArrayFromImage(img_in) img_a = img_a.astype(np.float32) img_c = sitk.GetArrayFromImage(deform_in) m_x = np.zeros([deform_in.GetHeight(), deform_in.GetWidth()]) m_y = np.zeros([deform_in.GetHeight(), deform_in.GetWidth()]) m_y = m_y.astype(np.float32) m_x = m_x.astype(np.float32) for j in range(0, deform_in.GetHeight()): for i in range(0, deform_in.GetWidth()): pix = img_c[j, i] m_x[j, i] = float(j) + scale_factor * \ float(pix[1]) * (1.0 / spacing[1]) m_y[j, i] = float(i) + scale_factor * \ float(pix[0]) * (1.0 / spacing[0]) out = cv2.remap(img_a, m_y, m_x, cv2.INTER_CUBIC) out = sitk.GetImageFromArray(out) out.CopyInformation(img_in) sitk.WriteImage(out, out_filename) return out def setup_folders(in_dir): # Copy from the input directory first names_in = subprocess.check_output( ["ls " + in_dir], shell=True, text=True) names_in = names_in.split() # Sort the strings using natural sort names_in = natsorted(names_in) img_count = len(names_in) # Copy and duplicate first and last (Neumann boundary conditions) for i in range(0, img_count): img = sitk.ReadImage(in_dir + names_in[i]) index = i + 1 sitk.WriteImage( img, cur_dir + '/input_with_boundary/slice_' + format( index, '04d') + '.nii') if index == 1: sitk.WriteImage( img, cur_dir + '/input_with_boundary/slice_0000.nii') elif index == img_count: sitk.WriteImage( img, cur_dir + '/input_with_boundary/slice_' + format( index + 1, '04d') + '.nii') # Copy files into directories subprocess.call("cp " + cur_dir + '/input_with_boundary/* ' + cur_dir + "/current_iter/", shell=True) print("Copied files to ./current_iter") subprocess.call("cp " + cur_dir + '/input_with_boundary/* ' + cur_dir + '/prev_iter/', shell=True) print("Copied files to ./prev_iter") names_in = subprocess.check_output( ['ls ' + cur_dir + '/current_iter/'], shell=True, text=True) names_in = names_in.split() return names_in def one_pass( start_index, end_index, step, cur_dir, current_iteration, images_names, img_count, ants_thread_count): for j in range(start_index, end_index, step): # Calculate transform between j-1 and j+1 # fixed is j-1 moving is j+1 reg_run(cur_dir + '/current_iter/' + image_names[j - 1], cur_dir + '/current_iter/' + image_names[j + 1], cur_dir + '/registration_output_transform/u_', cur_dir + '/registration_output_image/output_warped_image.nii', ants_thread_count) img_u = sitk.ReadImage( cur_dir + '/registration_output_transform/u_0Warp.nii.gz', sitk.sitkVectorFloat64) # Multiply it by half the deformation field img_jm1 = sitk.ReadImage( cur_dir + '/current_iter/' + image_names[j + step]) # Make sure to account for pixel scale factor deform_image(img_jm1, img_u, 0.5, cur_dir + '/i_hat_image/output.nii') # Register Ij to IHat reg_run( cur_dir + '/i_hat_image/output.nii', cur_dir + '/prev_iter/' + image_names[j], cur_dir + '/registration_output_transform/u_', cur_dir + '/registration_output_image/output_warped_image.nii', ants_thread_count) # Merge it with previous img_u_acc_new = sitk.ReadImage( cur_dir + '/registration_output_transform/u_0Warp.nii.gz', sitk.sitkVectorFloat64) # if t == 0: if current_iteration == 0: sitk.WriteImage(img_u_acc_new, cur_dir + '/current_transforms/u' + str(j) + '_Warp.nii') else: img_u_acc = sitk.ReadImage( cur_dir + '/current_transforms/u' + str(j) + '_Warp.nii', sitk.sitkVectorFloat64) img_u_acc_new = img_u_acc + img_u_acc_new sitk.WriteImage(img_u_acc_new, cur_dir + '/current_transforms/u' + str(j) + '_Warp.nii') # Update Ij using Ij0 img_j_orig = sitk.ReadImage( cur_dir + '/input_with_boundary/' + image_names[j]) deform_image(img_j_orig, img_u_acc_new, 1.0, cur_dir + '/current_iter/' + image_names[j]) # Update boundaries img_b = sitk.ReadImage(cur_dir + '/current_iter/' + image_names[1]) sitk.WriteImage(img_b, cur_dir + '/current_iter/' + image_names[0]) img_b = sitk.ReadImage( cur_dir + '/current_iter/' + image_names[img_count - 2]) sitk.WriteImage(img_b, cur_dir + '/current_iter/' + image_names[img_count - 1]) # Copy current_iter to prev_iter for j in range(0, img_count): img_b = sitk.ReadImage(cur_dir + '/current_iter/' + image_names[j]) sitk.WriteImage(img_b, cur_dir + '/prev_iter/' + image_names[j]) names_in = setup_folders(in_dir) img_count = len(names_in) image_names = [] for i in range(0, img_count): image_names.append(names_in[i]) # Do nothing if iterations == 0 if iterations > 0: # iterations = 4 # Z = img_count for i in range(0, iterations): print("Starting iteration " + str(i + 1) + " of " + str(iterations)) if i % 2 == 0: one_pass(1, img_count - 1, 1, cur_dir, i, image_names, img_count, ants_thread_count) else: one_pass(img_count - 2, 0, 1, cur_dir, i, image_names, img_count, ants_thread_count) # Copy results to output directories subprocess.call("cp " + cur_dir + '/current_iter/* ' + out_dir_images, shell=True) # Remove the first and last since they were boundary conditions subprocess.call("rm " + out_dir_images + '/slice_0000.nii', shell=True) subprocess.call("rm " + out_dir_images + '/slice_' + format(img_count - 1, '04d') + '.nii', shell=True) # Copy the transforms to the correct output folder subprocess.call("cp " + cur_dir + '/current_transforms/* ' + out_dir_transforms, shell=True) # Copy from the input directory first names_in = subprocess.check_output( ["ls " + out_dir_images], shell=True, text=True) names_in = names_in.split() img_count = len(names_in) # These images should be ordered based on the file naming convention for i in range(0, img_count): img = sitk.ReadImage(out_dir_images + '/' + names_in[i]) sitk.WriteImage( img, out_dir_images + '/out_' + format( i + 1, '04d') + '.nii') # Finally remove the old images subprocess.call('rm ' + out_dir_images + '/slice_*', shell=True) return out_dir_images
269
40.36
94
19
2,583
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_8c1ecfecb43ce455_2d164e8b", "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": 98, "line_end": 99, "column_start": 20, "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/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 98, "col": 20, "offset": 4063}, "end": {"line": 99, "col": 53, "offset": 4140}, "extra": {"message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_8c1ecfecb43ce455_7d580f37", "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": 99, "line_end": 99, "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/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 99, "col": 37, "offset": 4124}, "end": {"line": 99, "col": 41, "offset": 4128}, "extra": {"message": "Found 'subprocess' function 'check_output' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_8c1ecfecb43ce455_3381aaea", "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": 131, "line_end": 132, "column_start": 9, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 131, "col": 9, "offset": 5223}, "end": {"line": 132, "col": 64, "offset": 5348}, "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_8c1ecfecb43ce455_4cbd0f1c", "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": 131, "line_end": 131, "column_start": 20, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 131, "col": 20, "offset": 5234}, "end": {"line": 131, "col": 24, "offset": 5238}, "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_8c1ecfecb43ce455_ebb5322b", "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": 132, "line_end": 132, "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/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 132, "col": 59, "offset": 5343}, "end": {"line": 132, "col": 63, "offset": 5347}, "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_8c1ecfecb43ce455_0a131654", "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": 134, "line_end": 135, "column_start": 9, "column_end": 61, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 134, "col": 9, "offset": 5405}, "end": {"line": 135, "col": 61, "offset": 5527}, "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_8c1ecfecb43ce455_a5b9d253", "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": 134, "line_end": 134, "column_start": 20, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 134, "col": 20, "offset": 5416}, "end": {"line": 134, "col": 24, "offset": 5420}, "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_8c1ecfecb43ce455_1b2b89fa", "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": 135, "line_end": 135, "column_start": 56, "column_end": 60, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 135, "col": 56, "offset": 5522}, "end": {"line": 135, "col": 60, "offset": 5526}, "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_8c1ecfecb43ce455_fcba5410", "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": 137, "line_end": 138, "column_start": 20, "column_end": 73, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 137, "col": 20, "offset": 5592}, "end": {"line": 138, "col": 73, "offset": 5689}, "extra": {"message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_8c1ecfecb43ce455_8123e23d", "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": 138, "line_end": 138, "column_start": 57, "column_end": 61, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 138, "col": 57, "offset": 5673}, "end": {"line": 138, "col": 61, "offset": 5677}, "extra": {"message": "Found 'subprocess' function 'check_output' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_8c1ecfecb43ce455_8104295e", "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": 239, "line_end": 240, "column_start": 5, "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/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 239, "col": 5, "offset": 9875}, "end": {"line": 240, "col": 48, "offset": 9977}, "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_8c1ecfecb43ce455_9e41af13", "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": 239, "line_end": 239, "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/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 239, "col": 16, "offset": 9886}, "end": {"line": 239, "col": 20, "offset": 9890}, "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_8c1ecfecb43ce455_fd6e37bc", "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": 240, "line_end": 240, "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/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 240, "col": 43, "offset": 9972}, "end": {"line": 240, "col": 47, "offset": 9976}, "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_8c1ecfecb43ce455_3ed92ce3", "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": 242, "line_end": 242, "column_start": 5, "column_end": 76, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 242, "col": 5, "offset": 10050}, "end": {"line": 242, "col": 76, "offset": 10121}, "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_8c1ecfecb43ce455_bc0f62fb", "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": 242, "line_end": 242, "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/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 242, "col": 16, "offset": 10061}, "end": {"line": 242, "col": 20, "offset": 10065}, "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_8c1ecfecb43ce455_25c558fd", "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": 242, "line_end": 242, "column_start": 71, "column_end": 75, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 242, "col": 71, "offset": 10116}, "end": {"line": 242, "col": 75, "offset": 10120}, "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_8c1ecfecb43ce455_c295fa0a", "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": 243, "line_end": 244, "column_start": 5, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 243, "col": 5, "offset": 10126}, "end": {"line": 244, "col": 71, "offset": 10249}, "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_8c1ecfecb43ce455_d37935d1", "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": 243, "line_end": 243, "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/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 243, "col": 16, "offset": 10137}, "end": {"line": 243, "col": 20, "offset": 10141}, "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_8c1ecfecb43ce455_b92d3f60", "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": 244, "line_end": 244, "column_start": 66, "column_end": 70, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 244, "col": 66, "offset": 10244}, "end": {"line": 244, "col": 70, "offset": 10248}, "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_8c1ecfecb43ce455_e100965d", "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": 246, "line_end": 247, "column_start": 5, "column_end": 52, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 246, "col": 5, "offset": 10309}, "end": {"line": 247, "col": 52, "offset": 10421}, "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_8c1ecfecb43ce455_b40ce83f", "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": 246, "line_end": 246, "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/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 246, "col": 16, "offset": 10320}, "end": {"line": 246, "col": 20, "offset": 10324}, "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_8c1ecfecb43ce455_da518671", "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": 247, "line_end": 247, "column_start": 47, "column_end": 51, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 247, "col": 47, "offset": 10416}, "end": {"line": 247, "col": 51, "offset": 10420}, "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_8c1ecfecb43ce455_9904d55a", "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": 249, "line_end": 250, "column_start": 16, "column_end": 57, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 249, "col": 16, "offset": 10479}, "end": {"line": 250, "col": 57, "offset": 10560}, "extra": {"message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_8c1ecfecb43ce455_899789ef", "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": 250, "line_end": 250, "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/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 250, "col": 41, "offset": 10544}, "end": {"line": 250, "col": 45, "offset": 10548}, "extra": {"message": "Found 'subprocess' function 'check_output' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_8c1ecfecb43ce455_e6e4be92", "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": 267, "line_end": 267, "column_start": 5, "column_end": 69, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 267, "col": 5, "offset": 11033}, "end": {"line": 267, "col": 69, "offset": 11097}, "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_8c1ecfecb43ce455_670b71a3", "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": 267, "line_end": 267, "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/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 267, "col": 16, "offset": 11044}, "end": {"line": 267, "col": 20, "offset": 11048}, "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_8c1ecfecb43ce455_d6be8076", "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": 267, "line_end": 267, "column_start": 64, "column_end": 68, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpr7mo7ysm/8c1ecfecb43ce455.py", "start": {"line": 267, "col": 64, "offset": 11092}, "end": {"line": 267, "col": 68, "offset": 11096}, "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"}}}]
27
true
[ "CWE-78", "CWE-78", "CWE-78", "CWE-78", "CWE-78", "CWE-78", "CWE-78", "CWE-78", "CWE-78", "CWE-78", "CWE-78", "CWE-78", "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.subprocess-shell-true", "rules.python.lang.security.audit.dangerous-subprocess-use...
[ "security", "security", "security", "security", "security", "security", "security", "security", "security", "security", "security", "security", "security", "security", "security", "security", "security", "security", "security", "security" ]
[ "LOW", "MEDIUM", "LOW", "MEDIUM", "LOW", "MEDIUM", "LOW", "MEDIUM", "LOW", "MEDIUM", "LOW", "MEDIUM", "LOW", "MEDIUM", "LOW", "MEDIUM", "LOW", "MEDIUM", "LOW", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH" ]
[ 98, 99, 131, 132, 134, 135, 137, 138, 239, 240, 242, 242, 243, 244, 246, 247, 249, 250, 267, 267 ]
[ 99, 99, 132, 132, 135, 135, 138, 138, 240, 240, 242, 242, 244, 244, 247, 247, 250, 250, 267, 267 ]
[ 20, 37, 9, 59, 9, 56, 20, 57, 5, 43, 5, 71, 5, 66, 5, 47, 16, 41, 5, 64 ]
[ 53, 41, 64, 63, 61, 60, 73, 61, 48, 47, 76, 75, 71, 70, 52, 51, 57, 45, 69, 68 ]
[ "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01...
[ "Detected 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, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5, 7.5 ]
[ "LOW", "HIGH", "LOW", "HIGH", "LOW", "HIGH", "LOW", "HIGH", "LOW", "HIGH", "LOW", "HIGH", "LOW", "HIGH", "LOW", "HIGH", "LOW", "HIGH", "LOW", "HIGH" ]
[ "HIGH", "LOW", "HIGH", "LOW", "HIGH", "LOW", "HIGH", "LOW", "HIGH", "LOW", "HIGH", "LOW", "HIGH", "LOW", "HIGH", "LOW", "HIGH", "LOW", "HIGH", "LOW" ]
nzp_gs_smooth.py
/nzp_gs_smooth.py
cau-riken/nzp_gs_smooth_standalone
MIT
2024-11-18T19:28:36.222394+00:00
1,574,213,604,000
d867fb467cd5376b7fb1a01e918a731f4e0435df
3
{ "blob_id": "d867fb467cd5376b7fb1a01e918a731f4e0435df", "branch_name": "refs/heads/master", "committer_date": 1574213604000, "content_id": "87fd15aac0b05b9c2de3767136fb7c247fb3797a", "detected_licenses": [ "Apache-2.0" ], "directory_id": "affd00484342e6a6486adcb5a12cdb7e98816f8d", "extension": "py", "filename": "fall2019-2.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 118849041, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11515, "license": "Apache-2.0", "license_type": "permissive", "path": "/fall2019-2.py", "provenance": "stack-edu-0054.json.gz:577345", "repo_name": "jie-zhou/Ike-Wai-Sensors", "revision_date": 1574213604000, "revision_id": "ad98b6c31b0c52d726e29d4aabe1efc9321c50ef", "snapshot_id": "8f0b6eb2a22ea4ce6aeddcad2b29c92608e80c23", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jie-zhou/Ike-Wai-Sensors/ad98b6c31b0c52d726e29d4aabe1efc9321c50ef/fall2019-2.py", "visit_date": "2021-05-05T07:07:02.073912" }
2.578125
stackv2
#!/usr/bin/env python2 import io from io import open import fcntl import string import time import datetime import logging import json import os import socket import sys import lib.iw_motor import lib.iw_acc import lib.iw_hot import lib.iw_rgb import lib.iw_sal # Change per well well_num = 9 sleep_between_trials = 5 num_samples = 3 # For sending readings to database import requests _token = '4d197a543681b336b817f951f998e64' def uploadFileToIkewai(token, filename): headers = { 'authorization': "Bearer " + token } files ={'fileToUpload' : open(filename,'rb')} res = requests.post('https://ikeauth.its.hawaii.edu/files/v2/media/system/mydata-tamrako/dropsensor_data/', files=files, headers=headers,verify=False) resp = json.loads(res.content) return resp # Defining all the read functions for sensors def log_iw(message): """ Prints out message to terminal and adds to log :param message: message to be printed/logged :type message: string :return: nothing """ with open('log/' + create_datestamp() + '.txt', "a") as f: message_ = create_timestamp() + ': ' + message + '\n' f.write(message_.decode('utf-8')) print(message) logging.debug(message) def read_rgb_initial(): """ Method to check if the RGB sensor is working. This is because a reading of 0,0,0 is still considered a success by the system, but could mean that the LED is broken and RGB should not be considered useful. :return: nothing """ lib.iw_rgb.get_rgb() def read_rgb(): """ Method to get a reading from RGB Sensor, then displays and logs it Turns on LED, obtains reading, logs reading, turns off LED :return: a list containing the RGB reading """ lib.iw_rgb.turn_led_on() time.sleep(2) rgb_values = lib.iw_rgb.get_rgb() log_iw("Red: " + str(rgb_values[0])) log_iw("Green: " + str(rgb_values[1])) log_iw("Blue: " + str(rgb_values[2])) time.sleep(2) lib.iw_rgb.turn_led_off() return rgb_values def read_acc(): """ Method to get a reading from accelerometer,then displays and logs it :return: a list of the X, Y, and Z components """ acc = lib.iw_acc.get_acc() log_iw("X-Acc: " + str(acc[0])) log_iw("Y-Acc: " + str(acc[1])) log_iw("Z-Acc: " + str(acc[2])) log_iw("X-Mag: " + str(acc[3])) log_iw("Y-Mag: " + str(acc[4])) log_iw("Z-Mag: " + str(acc[5])) return acc def read_hot(): """ Method to get a reading from temperature sensor, then displays and logs it :return: a list of the temp in Celsius and Fahrenheit """ hot = lib.iw_hot.get_hot() log_iw("Temp (C): " + str(hot[0])) log_iw("Temp (F): " + str(hot[1])) return hot def read_sal(): """ Method to get a reading from salinity sensor, then displays and logs it :return: an integer of the salinity """ sal_string = ''.join(lib.iw_sal.get_sal()).split(',') sal = [] for i in sal_string: try: sal.append(float(i)) except ValueError: log_iw("Invalid read from Salinity, skipping...") sal.append('X') # micro-S/cm bad reading sal.append('X') # PSU bad reading log_iw("Salinity (micro-S/cm): " + str(sal[0])) try: log_iw("Salinity (PSU): " + str(sal[1])) except ValueError: print('PSU Reading not found. Make sure it is enabled on the chip!') except IndexError: pass return sal # Determine which sensor failed during the 10-sample collection. def get_bad_sensor(y_value): """ Method to get which sensor has failed :param y_value: an integer to store the index of failed sensor :type y_value: int :return: an integer containing the index of the failed sensor """ switcher = { 0: 'RGB failed...', 1: 'ACC failed...', 2: 'HOT failed...', 3: 'SAL failed...' } # Returns the current index of read_array being run. return switcher.get(y_value, "nothing") def create_datestamp(): """ creates a datestamp in the month/dd/yyyy format :return: a string of the datestamp """ return time.strftime('%b-%d-%Y', time.localtime(time.time())) def create_timestamp(): """ creates a timestamp in the 24hr HH:MM:SS format :return: a string of the timestamp """ return time.strftime('%H:%M:%S', time.localtime(time.time())) def average_list(list_): """ averages all the values in list_ together, ignores any invalid entries :param list_: a list containing values to be averaged :type list_: list :return: a number of the average """ num_val = 0 total = 0 for i in list_: if type(i) is int or type(i) is float: valid = type(i) num_val += 1 total += i if num_val > 0: if valid is float: return float('%.3f' % (total/num_val)) else: return total/num_val else: return "No Readings Found" read_array = [read_rgb, read_acc, read_hot, read_sal] # steps_for_foot = 125 #demo if __name__ == "__main__": # save path for sensor data save_path = '/home/pi/IkeWai/data/dict_' + create_datestamp() + '/well-'+ str(well_num) + '-' + create_timestamp() # flag to control manual quiting of program terminate = False # Log files for debug in case of errors # log_name = 'log_' + dt + '.txt' # logging.basicConfig(filename=r'/home/pi/Desktop/ikewai/logs/client_logs/' + log_name, # level=logging.DEBUG, # format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') # log_iw('iw.py starting...') # log_iw('Time_Date: ' + str(dt)) # For some reason, the first read of the RGB sensor returns 0,0,0. try: read_rgb_initial() except IOError: log_iw('IOError from initial RGB occurred...') pass # Read Samples json_dump = { 'DATE': create_datestamp(), 'TIME': create_timestamp(), 'DATA': {}, 'SAMPLES TAKEN': num_samples, 'TIME BETWEEN SAMPLES': sleep_between_trials } json_data = { 'AVERAGE': {}, 'READINGS': { 'RGB': { 'UNITLESS': { 'R': [], 'G': [], 'B': [] } }, 'MAGNETIC': { 'GAUSS': { 'X': [], 'Y': [], 'Z': [] } }, 'ACCEL': { 'M/S^2': { 'X': [], 'Y': [], 'Z': [] } }, 'SALINITY': { 'PSU': [], 'MICRO-S/CM': [] }, 'TEMP': { 'C': [], 'F': [] } } } json_read = json_data['READINGS'] for x in range(0, num_samples): for y in range(0, 4): try: # Read sensor values value = read_array[y]() if y == 0: json_read['RGB']['UNITLESS']['R'].append(value[0]) json_read['RGB']['UNITLESS']['G'].append(value[1]) json_read['RGB']['UNITLESS']['B'].append(value[2]) elif y == 1: json_read['ACCEL']['M/S^2']['X'].append(value[0]) json_read['ACCEL']['M/S^2']['Y'].append(value[1]) json_read['ACCEL']['M/S^2']['Z'].append(value[2]) json_read['MAGNETIC']['GAUSS']['X'].append(value[3]) json_read['MAGNETIC']['GAUSS']['Y'].append(value[4]) json_read['MAGNETIC']['GAUSS']['Z'].append(value[5]) elif y == 2: json_read['TEMP']['C'].append(value[0]) json_read['TEMP']['F'].append(value[1]) elif y == 3: json_read['SALINITY']['MICRO-S/CM'].append(value[0]) json_read['SALINITY']['PSU'].append(value[1]) # When there is an error (sensor not working) except IOError: log_iw('IOError occurred') log_iw(get_bad_sensor(y)) error = 'X' if y == 0: json_read['RGB']['UNITLESS']['R'].append(error) json_read['RGB']['UNITLESS']['G'].append(error) json_read['RGB']['UNITLESS']['B'].append(error) elif y == 1: json_read['ACCEL']['M/S^2']['X'].append(error) json_read['ACCEL']['M/S^2']['Y'].append(error) json_read['ACCEL']['M/S^2']['Z'].append(error) json_read['MAGNETIC']['GAUSS']['X'].append(error) json_read['MAGNETIC']['GAUSS']['Y'].append(error) json_read['MAGNETIC']['GAUSS']['Z'].append(error) elif y == 2: json_read['TEMP']['C'].append(error) json_read['TEMP']['F'].append(error) elif y == 3: json_read['SALINITY']['MICRO-S/CM'].append(error) json_read['SALINITY']['PSU'].append(error) pass # If process is killed before runs finished except KeyboardInterrupt: log_iw('Process terminated early') lib.iw_rgb.turn_led_off() terminate = True break if not terminate: # SLEEPING AT BOTTOM log_iw('Sleeping') time.sleep(sleep_between_trials) else: break # Average the readings for sensor in json_data['READINGS']: json_data['AVERAGE'][sensor] = {} for scale in json_data['READINGS'][sensor]: if type(json_data['READINGS'][sensor][scale]) == dict: json_data['AVERAGE'][sensor][scale] = {} for subcat in json_data['READINGS'][sensor][scale]: json_data['AVERAGE'][sensor][scale][subcat] = \ average_list(json_data['READINGS'][sensor][scale][subcat]) else: json_data['AVERAGE'][sensor][scale] = [] json_data['AVERAGE'][sensor][scale] = average_list(json_data['READINGS'][sensor][scale]) json_dump['DATA'] = json_data print(save_path) try: os.makedirs(save_path) except: print('File Exists') # The 'a' appends the file if there is an existing file # the '+' creates the file if there isn't an existing file with open(save_path + '/pretty.txt', "w") as f: # Dumping the data from the earlier conversion # into the newly created file print(json_dump) f.write(json.dumps(json_dump, sort_keys=True, indent=4).decode('utf-8')) data_path = save_path + '/well-' + str(well_num) + '-' + create_timestamp() + '_data.json' with open(data_path, "w") as f: # Dumping the data from the earlier conversion # into the newly created file #print(json_dump) f.write(json.dumps(json_dump).decode('utf-8')) uploadFileToIkewai(_token, data_path) log_iw('Exiting...') # Turn off the LED before exiting lib.iw_rgb.turn_led_off() log_iw('Exited...')
381
29.22
154
21
2,924
python
[{"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_c968db4121de2972_cccb6c65", "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": 37, "line_end": 37, "column_start": 11, "column_end": 155, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmpr7mo7ysm/c968db4121de2972.py", "start": {"line": 37, "col": 11, "offset": 601}, "end": {"line": 37, "col": 155, "offset": 745}, "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_c968db4121de2972_311f8017", "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('https://ikeauth.its.hawaii.edu/files/v2/media/system/mydata-tamrako/dropsensor_data/', files=files, headers=headers,verify=False, timeout=30)", "location": {"file_path": "unknown", "line_start": 37, "line_end": 37, "column_start": 11, "column_end": 155, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpr7mo7ysm/c968db4121de2972.py", "start": {"line": 37, "col": 11, "offset": 601}, "end": {"line": 37, "col": 155, "offset": 745}, "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('https://ikeauth.its.hawaii.edu/files/v2/media/system/mydata-tamrako/dropsensor_data/', files=files, headers=headers,verify=False, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.security.disabled-cert-validation_c968db4121de2972_842a3b50", "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('https://ikeauth.its.hawaii.edu/files/v2/media/system/mydata-tamrako/dropsensor_data/', files=files, headers=headers,verify=True)", "location": {"file_path": "unknown", "line_start": 37, "line_end": 37, "column_start": 11, "column_end": 155, "code_snippet": "requires login"}, "cwe_id": "CWE-295: Improper Certificate Validation", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.security.disabled-cert-validation", "path": "/tmp/tmpr7mo7ysm/c968db4121de2972.py", "start": {"line": 37, "col": 11, "offset": 601}, "end": {"line": 37, "col": 155, "offset": 745}, "extra": {"message": "Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.", "fix": "requests.post('https://ikeauth.its.hawaii.edu/files/v2/media/system/mydata-tamrako/dropsensor_data/', files=files, headers=headers,verify=True)", "metadata": {"cwe": ["CWE-295: Improper Certificate Validation"], "owasp": ["A03:2017 - Sensitive Data Exposure", "A07:2021 - Identification and Authentication Failures", "A07:2025 - Authentication Failures"], "references": ["https://stackoverflow.com/questions/41740361/is-it-safe-to-disable-ssl-certificate-verification-in-pythonss-requests-lib"], "category": "security", "technology": ["requests"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_c968db4121de2972_9809a3d8", "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": 51, "line_end": 51, "column_start": 10, "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/tmpr7mo7ysm/c968db4121de2972.py", "start": {"line": 51, "col": 10, "offset": 1039}, "end": {"line": 51, "col": 57, "offset": 1086}, "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.arbitrary-sleep_c968db4121de2972_ae052105", "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": 77, "line_end": 77, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/c968db4121de2972.py", "start": {"line": 77, "col": 5, "offset": 1809}, "end": {"line": 77, "col": 18, "offset": 1822}, "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_c968db4121de2972_c0470768", "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": 82, "line_end": 82, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/c968db4121de2972.py", "start": {"line": 82, "col": 5, "offset": 2000}, "end": {"line": 82, "col": 18, "offset": 2013}, "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_c968db4121de2972_104733b6", "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": 335, "line_end": 335, "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.arbitrary-sleep", "path": "/tmp/tmpr7mo7ysm/c968db4121de2972.py", "start": {"line": 335, "col": 13, "offset": 9799}, "end": {"line": 335, "col": 45, "offset": 9831}, "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.useless-assignment-keyed_c968db4121de2972_17b59204", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-assignment-keyed", "finding_type": "maintainability", "severity": "low", "confidence": "medium", "message": "key `scale` in `json_data['AVERAGE'][sensor]` is assigned twice; the first assignment is useless", "remediation": "", "location": {"file_path": "unknown", "line_start": 349, "line_end": 350, "column_start": 17, "column_end": 105, "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/tmpr7mo7ysm/c968db4121de2972.py", "start": {"line": 349, "col": 17, "offset": 10404}, "end": {"line": 350, "col": 105, "offset": 10549}, "extra": {"message": "key `scale` in `json_data['AVERAGE'][sensor]` is assigned twice; the first assignment is useless", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.useless-assignment-keyed_c968db4121de2972_29273e59", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-assignment-keyed", "finding_type": "maintainability", "severity": "low", "confidence": "medium", "message": "key `sensor` in `json_data['AVERAGE']` is assigned twice; the first assignment is useless", "remediation": "", "location": {"file_path": "unknown", "line_start": 349, "line_end": 350, "column_start": 17, "column_end": 105, "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/tmpr7mo7ysm/c968db4121de2972.py", "start": {"line": 349, "col": 17, "offset": 10404}, "end": {"line": 350, "col": 105, "offset": 10549}, "extra": {"message": "key `sensor` in `json_data['AVERAGE']` is assigned twice; the first assignment is useless", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_c968db4121de2972_662d45df", "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": 363, "line_end": 363, "column_start": 10, "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/tmpr7mo7ysm/c968db4121de2972.py", "start": {"line": 363, "col": 10, "offset": 10822}, "end": {"line": 363, "col": 46, "offset": 10858}, "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_c968db4121de2972_67438c3e", "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": 370, "line_end": 370, "column_start": 10, "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/tmpr7mo7ysm/c968db4121de2972.py", "start": {"line": 370, "col": 10, "offset": 11169}, "end": {"line": 370, "col": 30, "offset": 11189}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
11
true
[ "CWE-295" ]
[ "rules.python.requests.security.disabled-cert-validation" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 37 ]
[ 37 ]
[ 11 ]
[ 155 ]
[ "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" ]
fall2019-2.py
/fall2019-2.py
jie-zhou/Ike-Wai-Sensors
Apache-2.0
2024-11-18T19:28:39.206682+00:00
1,601,441,111,000
8528fcd218568eb76fee2a6daf2b15baecc7b8bf
3
{ "blob_id": "8528fcd218568eb76fee2a6daf2b15baecc7b8bf", "branch_name": "refs/heads/master", "committer_date": 1601441111000, "content_id": "5a25b6cb26875957dec22f1a4cbcfeaaee47704a", "detected_licenses": [ "MIT" ], "directory_id": "ffb123d337e61d400a6a6ca17d9f335083513e31", "extension": "py", "filename": "CRF.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 299803396, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3347, "license": "MIT", "license_type": "permissive", "path": "/CRF.py", "provenance": "stack-edu-0054.json.gz:577376", "repo_name": "amilasilva92/multilingual-communities-by-code-switching", "revision_date": 1601441111000, "revision_id": "a2f1235460f110e28012055751c427911450ecde", "snapshot_id": "1d1af48dba3e42c73f3e86844d0bbb462b363f1a", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/amilasilva92/multilingual-communities-by-code-switching/a2f1235460f110e28012055751c427911450ecde/CRF.py", "visit_date": "2022-12-23T07:09:21.683788" }
2.765625
stackv2
from subprocess import call DATAFILE_PATH = 'temp/' class CRF: def __init__(self): return None def preprocess_dataset(self, dataset, filename): ''' TODO as the task in hand ''' f = open(DATAFILE_PATH + filename, 'w') for discussion in dataset: if filename == 'train.data': ground_truths = discussion['ground_truth'] predicted_val = discussion['predicted_ground_truth'] for i, item in enumerate(predicted_val): if filename == 'train.data': assert item['post_id'] == ground_truths[i]['post_id'] for pred_word, word in\ zip(item['consensus']['tokens'], ground_truths[i]['consensus']['tokens']): assert word['word'] == pred_word['word'] f.write(' '.join([word['word'], pred_word['lang'], word['lang']]) + '\n') else: for pred_word in item['consensus']['tokens']: f.write(' '.join([pred_word['word'], pred_word['lang']]) + '\n') f.write('\n') f.close() def postprocess_data(self, dataset, filename): ''' TODO as the task in hand ''' f = open(DATAFILE_PATH + filename, 'r') for discussion in dataset: predicted_val = discussion['predicted_ground_truth'] for item in predicted_val: for word in item['consensus']['tokens']: splits = f.readline().strip().split('\t') assert word['word'] == splits[0] word['lang'] = splits[-1] f.readline() return dataset def train_crf(self): c = 150 # emphirically that found 150 works better command = 'CRF++.58/crf_learn -c ' + \ str(c) + ' temp/template temp/train.data temp/model' call(command, shell=True) def test_crf(self): command = 'CRF++.58/crf_test -m temp/model temp/test.data >\ temp/results_test.data' call(command, shell=True) def rm_crf(self): command = 'rm -rf temp/model' call(command, shell=True) def train_and_predict(self, training_dataset, testing_dataset): self.preprocess_dataset(training_dataset, 'train.data') self.preprocess_dataset(testing_dataset, 'test.data') self.train_crf() self.test_crf() testing_dataset = self.postprocess_data(testing_dataset, 'results_test.data') return testing_dataset def predict(self, testing_dataset): self.preprocess_dataset(testing_dataset, 'test.data') self.test_crf() testing_dataset = self.postprocess_data(testing_dataset, 'results_test.data') return testing_dataset if __name__ == '__main__': dataset1 = read_data('data/Dataset1.json') dataset2 = read_data('data/Dataset2.json') preprocess_dataset(dataset1+dataset2, 'train.data') test_dataset = read_data('data/TestData1.json') preprocess_dataset(test_dataset, 'test.data')
95
34.23
74
24
683
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_06f087e287e47332_b66b4f47", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 14, "line_end": 14, "column_start": 13, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/06f087e287e47332.py", "start": {"line": 14, "col": 13, "offset": 233}, "end": {"line": 14, "col": 48, "offset": 268}, "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_06f087e287e47332_35f272a3", "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": 43, "line_end": 43, "column_start": 9, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmpr7mo7ysm/06f087e287e47332.py", "start": {"line": 43, "col": 9, "offset": 1413}, "end": {"line": 43, "col": 48, "offset": 1452}, "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_06f087e287e47332_2b75ce6b", "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": 43, "line_end": 43, "column_start": 13, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/06f087e287e47332.py", "start": {"line": 43, "col": 13, "offset": 1417}, "end": {"line": 43, "col": 48, "offset": 1452}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_06f087e287e47332_47e5b48d", "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": 61, "line_end": 61, "column_start": 9, "column_end": 13, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmpr7mo7ysm/06f087e287e47332.py", "start": {"line": 61, "col": 9, "offset": 2072}, "end": {"line": 61, "col": 13, "offset": 2076}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_06f087e287e47332_9c4d2348", "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": 61, "line_end": 61, "column_start": 9, "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://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/06f087e287e47332.py", "start": {"line": 61, "col": 9, "offset": 2072}, "end": {"line": 61, "col": 34, "offset": 2097}, "extra": {"message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_06f087e287e47332_978bd6ee", "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": 61, "line_end": 61, "column_start": 29, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpr7mo7ysm/06f087e287e47332.py", "start": {"line": 61, "col": 29, "offset": 2092}, "end": {"line": 61, "col": 33, "offset": 2096}, "extra": {"message": "Found 'subprocess' function 'call' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_06f087e287e47332_66083334", "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": 66, "line_end": 66, "column_start": 9, "column_end": 13, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmpr7mo7ysm/06f087e287e47332.py", "start": {"line": 66, "col": 9, "offset": 2243}, "end": {"line": 66, "col": 13, "offset": 2247}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_06f087e287e47332_638633de", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 70, "line_end": 70, "column_start": 9, "column_end": 13, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmpr7mo7ysm/06f087e287e47332.py", "start": {"line": 70, "col": 9, "offset": 2338}, "end": {"line": 70, "col": 13, "offset": 2342}, "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"}}}]
8
true
[ "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.subprocess-shell-true" ]
[ "security", "security" ]
[ "LOW", "MEDIUM" ]
[ "HIGH", "HIGH" ]
[ 61, 61 ]
[ 61, 61 ]
[ 9, 29 ]
[ 34, 33 ]
[ "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "Found 'subprocess' functio...
[ 7.5, 7.5 ]
[ "LOW", "HIGH" ]
[ "HIGH", "LOW" ]
CRF.py
/CRF.py
amilasilva92/multilingual-communities-by-code-switching
MIT
2024-11-18T19:28:42.953517+00:00
1,557,343,824,000
dd90e4a7545ced998fa71820f80b46a7d9bc7b92
3
{ "blob_id": "dd90e4a7545ced998fa71820f80b46a7d9bc7b92", "branch_name": "refs/heads/master", "committer_date": 1557343824000, "content_id": "8f3b6049950da7e4b892cf183e0d88c94fa6ba82", "detected_licenses": [ "MIT" ], "directory_id": "28ebadd9c355824ef141dce137ebab8e65f8d307", "extension": "py", "filename": "yeararchives.py", "fork_events_count": 0, "gha_created_at": 1631380637000, "gha_event_created_at": 1631380638000, "gha_language": null, "gha_license_id": "NOASSERTION", "github_id": 405438964, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7894, "license": "MIT", "license_type": "permissive", "path": "/Pyblosxom/plugins/yeararchives.py", "provenance": "stack-edu-0054.json.gz:577416", "repo_name": "daemonfreaks/pyblosxom", "revision_date": 1557343824000, "revision_id": "36dec9f4e0860e916fc6b5904103a687e9f26d8b", "snapshot_id": "79dfb410767fb2b102d541e21646ae2d19880ad2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/daemonfreaks/pyblosxom/36dec9f4e0860e916fc6b5904103a687e9f26d8b/Pyblosxom/plugins/yeararchives.py", "visit_date": "2021-12-02T18:10:34.037488" }
2.828125
stackv2
####################################################################### # This file is part of Pyblosxom. # # Copyright (C) 2004-2011 by the Pyblosxom team. See AUTHORS. # # Pyblosxom is distributed under the MIT license. See the file # LICENSE for distribution details. ####################################################################### """ Summary ======= Walks through your blog root figuring out all the available years for the archives list. It stores the years with links to year summaries in the variable ``$(archivelinks)``. You should put this variable in either your head or foot template. Install ======= This plugin comes with Pyblosxom. To install, do the following: 1. Add ``Pyblosxom.plugins.yeararchives`` to the ``load_plugins`` list in your ``config.py`` file. 2. Add ``$(archivelinks)`` to your head and/or foot templates. 3. Configure as documented below. Usage ===== When the user clicks on one of the year links (e.g. ``http://base_url/2004/``), then yeararchives will display a summary page for that year. The summary is generated using the ``yearsummarystory`` template for each month in the year. My ``yearsummarystory`` template looks like this:: <div class="blosxomEntry"> <span class="blosxomTitle">$title</span> <div class="blosxomBody"> <table> $body </table> </div> </div> The ``$(archivelinks)`` link can be configured with the ``archive_template`` config variable. It uses the Python string formatting syntax. Example:: py['archive_template'] = ( '<a href="%(base_url)s/%(Y)s/index.%(f)s">' '%(Y)s</a><br />') The vars available with typical example values are:: Y 4-digit year ex: '1978' y 2-digit year ex: '78' f the flavour ex: 'html' .. Note:: The ``archive_template`` variable value is formatted using Python string formatting rules--not Pyblosxom template rules! """ __author__ = "Will Kahn-Greene" __email__ = "willg at bluesock dot org" __version__ = "2010-05-08" __url__ = "http://pyblosxom.github.com/" __description__ = "Builds year-based archives listing." __category__ = "archives" __license__ = "MIT" __registrytags__ = "1.4, 1.5, core" from Pyblosxom import tools, entries from Pyblosxom.memcache import memcache_decorator from Pyblosxom.tools import pwrap import time def verify_installation(request): config = request.get_configuration() if not 'archive_template' in config: pwrap( "missing optional config property 'archive_template' which " "allows you to specify how the archive links are created. " "refer to yeararchives plugin documentation for more details.") return True class YearArchives: def __init__(self, request): self._request = request self._archives = None self._items = None @memcache_decorator('yeararchives', True) def __str__(self): if self._archives is None: self.gen_linear_archive() return self._archives def gen_linear_archive(self): config = self._request.get_configuration() data = self._request.get_data() root = config["datadir"] archives = {} archive_list = tools.walk(self._request, root) items = [] fulldict = {} fulldict.update(config) fulldict.update(data) flavour = data.get( "flavour", config.get("default_flavour", "html")) template = config.get( 'archive_template', '<a href="%(base_url)s/%(Y)s/index.%(f)s">%(Y)s</a><br />') for mem in archive_list: timetuple = tools.filestat(self._request, mem) timedict = {} for x in ["m", "Y", "y", "d"]: timedict[x] = time.strftime("%" + x, timetuple) fulldict.update(timedict) fulldict["f"] = flavour year = fulldict["Y"] if not year in archives: archives[year] = template % fulldict items.append( ["%(Y)s-%(m)s" % fulldict, "%(Y)s-%(m)s-%(d)s" % fulldict, time.mktime(timetuple), mem]) arc_keys = archives.keys() arc_keys.sort() arc_keys.reverse() result = [] for key in arc_keys: result.append(archives[key]) self._archives = '\n'.join(result) self._items = items def new_entry(request, yearmonth, body): """ Takes a bunch of variables and generates an entry out of it. It creates a timestamp so that conditionalhttp can handle it without getting all fussy. """ entry = entries.base.EntryBase(request) entry['title'] = yearmonth entry['filename'] = yearmonth + "/summary" entry['file_path'] = yearmonth entry._id = yearmonth + "::summary" entry["template_name"] = "yearsummarystory" entry["nocomments"] = "yes" entry["absolute_path"] = "" entry["fn"] = "" entry.set_time(time.strptime(yearmonth, "%Y-%m")) entry.set_data(body) return entry INIT_KEY = "yeararchives_initiated" def cb_prepare(args): request = args["request"] data = request.get_data() data["archivelinks"] = YearArchives(request) def cb_date_head(args): request = args["request"] data = request.get_data() if INIT_KEY in data: args["template"] = "" return args def parse_path_info(path): """Returns None or (year, flav) tuple. Handles urls of this type: - /2003 - /2003/ - /2003/index - /2003/index.flav """ path = path.split("/") path = [m for m in path if m] if not path: return year = path[0] if not year.isdigit() or not len(year) == 4: return if len(path) == 1: return (year, None) if len(path) == 2 and path[1].startswith("index"): flav = None if "." in path[1]: flav = path[1].split(".", 1)[1] return (year, flav) return def cb_filelist(args): request = args["request"] pyhttp = request.get_http() data = request.get_data() config = request.get_configuration() baseurl = config.get("base_url", "") path = pyhttp["PATH_INFO"] ret = parse_path_info(path) if ret == None: return # note: returned flavour is None if there is no .flav appendix year, flavour = ret data[INIT_KEY] = 1 # get all the entries wa = YearArchives(request) wa.gen_linear_archive() items = wa._items # peel off the items for this year items = [m for m in items if m[0].startswith(year)] items.sort() items.reverse() # Set and use current (or default) flavour for permalinks if not flavour: flavour = data.get( "flavour", config.get("default_flavour", "html")) data["flavour"] = flavour l = ("(%(path)s) <a href=\"" + baseurl + "/%(file_path)s." + flavour + "\">%(title)s</a><br>") e = "<tr>\n<td valign=\"top\" align=\"left\">%s</td>\n<td>%s</td></tr>\n" d = "" m = "" day = [] month = [] entrylist = [] for mem in items: if not m: m = mem[0] if not d: d = mem[1] if m != mem[0]: month.append(e % (d, "\n".join(day))) entrylist.append(new_entry(request, m, "\n".join(month))) m = mem[0] d = mem[1] day = [] month = [] elif d != mem[1]: month.append(e % (d, "\n".join(day))) d = mem[1] day = [] entry = entries.fileentry.FileEntry( request, mem[3], config['datadir']) day.append(l % entry) if day: month.append(e % (d, "\n".join(day))) if month: entrylist.append(new_entry(request, m, "\n".join(month))) return entrylist
312
24.3
77
18
2,050
python
[{"finding_id": "semgrep_rules.python.django.security.injection.raw-html-format_7fb5f182dc2a0f01_cb3c09f5", "tool_name": "semgrep", "rule_id": "rules.python.django.security.injection.raw-html-format", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected user input flowing into a manually constructed HTML string. You may be accidentally bypassing secure methods of rendering HTML by manually constructing HTML and this could create a cross-site scripting vulnerability, which could let attackers steal sensitive user data. To be sure this is safe, check that the HTML is rendered safely. Otherwise, use templates (`django.shortcuts.render`) which will safely render HTML instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 275, "line_end": 276, "column_start": 9, "column_end": 63, "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.2/topics/http/shortcuts/#render", "title": null}, {"url": "https://docs.djangoproject.com/en/3.2/topics/security/#cross-site-scripting-xss-protection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.injection.raw-html-format", "path": "/tmp/tmpr7mo7ysm/7fb5f182dc2a0f01.py", "start": {"line": 275, "col": 9, "offset": 6901}, "end": {"line": 276, "col": 63, "offset": 7000}, "extra": {"message": "Detected user input flowing into a manually constructed HTML string. You may be accidentally bypassing secure methods of rendering HTML by manually constructing HTML and this could create a cross-site scripting vulnerability, which could let attackers steal sensitive user data. To be sure this is safe, check that the HTML is rendered safely. Otherwise, use templates (`django.shortcuts.render`) which will safely render HTML instead.", "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": ["django"], "references": ["https://docs.djangoproject.com/en/3.2/topics/http/shortcuts/#render", "https://docs.djangoproject.com/en/3.2/topics/security/#cross-site-scripting-xss-protection"], "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"}}}]
1
true
[ "CWE-79" ]
[ "rules.python.django.security.injection.raw-html-format" ]
[ "security" ]
[ "MEDIUM" ]
[ "MEDIUM" ]
[ 275 ]
[ 276 ]
[ 9 ]
[ 63 ]
[ "A07:2017 - Cross-Site Scripting (XSS)" ]
[ "Detected user input flowing into a manually constructed HTML string. You may be accidentally bypassing secure methods of rendering HTML by manually constructing HTML and this could create a cross-site scripting vulnerability, which could let attackers steal sensitive user data. To be sure this is safe, check that ...
[ 5 ]
[ "HIGH" ]
[ "MEDIUM" ]
yeararchives.py
/Pyblosxom/plugins/yeararchives.py
daemonfreaks/pyblosxom
MIT
2024-11-18T19:28:43.345940+00:00
1,583,506,011,000
d7c7d55cc4c92ad2539f0940e5d1a8eabf69026d
3
{ "blob_id": "d7c7d55cc4c92ad2539f0940e5d1a8eabf69026d", "branch_name": "refs/heads/master", "committer_date": 1583506011000, "content_id": "13c0f0e11715eede55980c809662bea0a3f9f660", "detected_licenses": [ "MIT" ], "directory_id": "ec010c7a30d1a0d9ae14288e14236d2e8f238a4b", "extension": "py", "filename": "pyextensions.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 138951745, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14374, "license": "MIT", "license_type": "permissive", "path": "/pyextensions.py", "provenance": "stack-edu-0054.json.gz:577422", "repo_name": "aroberge/pyextensions", "revision_date": 1583506011000, "revision_id": "cd18f6936df2c4ffafacb445fe77f8908d67f4f1", "snapshot_id": "4af260394daa837650a9861c0974319d7547c7d3", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/aroberge/pyextensions/cd18f6936df2c4ffafacb445fe77f8908d67f4f1/pyextensions.py", "visit_date": "2020-03-21T19:28:41.045293" }
2.75
stackv2
"""pyextensions is a proof-of-concept of implementing code transformations using import hooks. By code transformation, we mean that instead of executing the code found in a module *as is*, it is first transformed prior to its execution. The transformations are done by other modules, called transformers, which are normal Python file. A transformer needs to include at least one of the following: 1. A function named ``transform_source()`` which takes as its argument a string, like the content of a regular Python script, modifies it, and return another string. Such transformations can be chained. 2. A function named ``transform_ast()`` which takes as its argument an abstract syntax tree, modifies it, and returns another tree. Such transformations can also be chained. 3. A function named ``transform_bytecode()`` which takes as its argument a code object, modifies it, and returns another code object. Such transformations can also be chained. In addition to the above, two other functions can be can potentially be used by pyextensions if they are found in a transformer: 1. By default, pyextension uses the ``parse()`` function from the ast module in the standard library to create an abstract syntax tree. If a transformer includes a similarly named function, it will be used instead. For example, one could use a parser that can handle cython notation, possibly converting all type information into a format acceptable for Python. Note that if such a function is found in more than one transformer, only the last one found will be used. 2. If a transformation requires that some additional module needs to be imported by the transformed source, it should be using a function named ``add_import()`` which returns the appropriate import statements. While this could be done using the ``transform_source()`` function to simply prepend the required imports in the transformed source, it is more useful to do so in a separate function as it allows pyextensions to be used in other contexts -- like in a custom REPL. By default, this module looks for files ending with a ".notpy" extension; however, this can be changed using a configuration settings. """ import argparse import ast import os.path import sys from importlib import import_module from importlib.abc import Loader, MetaPathFinder from importlib.util import spec_from_file_location def create_fake_site_packages_dir(): """It is assumed that code transformers are third-party modules to be installed in a location from where they can be imported. For this proof of concept, we add a fake site-packages directory where the sample transformers will be located. """ top_dir = os.path.abspath(os.path.dirname(__file__)) fake_site_pkg = os.path.join(top_dir, "fake_site_pkg") if not os.path.exists(fake_site_pkg): raise NotImplementedError( "A fake_site_pkg directory must exist for this demo to work correctly." ) sys.path.insert(0, fake_site_pkg) create_fake_site_packages_dir() CONFIG = {"file_ext": ["notpy"], "main_module_name": None, "version": 0.2} TRANSFORMERS = {"<cache>": []} # [(tr_name1, tr_mod1), ...] class ExtensionMetaFinder(MetaPathFinder): """A custom finder to locate modules, based on looking for files with a specific extension.""" def find_spec(self, fullname, path, target=None): """Finds the appropriate properties (spec) of a module, and sets its loader.""" if not path: path = [os.getcwd()] if "." in fullname: module_name = fullname.split(".")[-1] else: module_name = fullname for entry in path: filename = None submodule_locations = None for ext in CONFIG["file_ext"]: fn = os.path.join(entry, module_name + "." + ext) if os.path.exists(fn): filename = fn break else: if os.path.isdir(os.path.join(entry, module_name)): # this module has child modules fn = os.path.join(entry, module_name, "__init__.py") if os.path.exists(fn): filename = fn submodule_locations = [os.path.join(entry, module_name)] if filename is not None: return spec_from_file_location( fullname, filename, loader=ExtensionLoader(filename), submodule_search_locations=submodule_locations, ) return None # default to other finders sys.meta_path.insert(0, ExtensionMetaFinder()) class ExtensionLoader(Loader): """A custom loader which transforms the source prior to its execution""" def __init__(self, filename): self.filename = filename def exec_module(self, module): """Import the source code, transforms it before executing it so that it becomes valid Python.""" module_name = module.__name__ if module.__name__ == CONFIG["main_module_name"]: module.__name__ = "__main__" with open(self.filename) as f: source = f.read() get_required_transformers(module_name, source) if TRANSFORMERS[module_name]: source = add_all_imports(module_name, source) source = apply_source_transformations(module_name, source) parse = get_parser(module_name) if parse is None: parse = ast.parse tree = parse(source) tree = apply_ast_transformations(module_name, tree) code_object = compile(tree, module_name, "exec") code_object = apply_bytecode_transformations(module_name, code_object) exec(code_object, vars(module)) else: exec(source, vars(module)) def import_main(module_name): """Imports the module that is to be interpreted as the main module. pyextensions would normally be called with a script meant to be run as the main module with its source to be transformed. This script is specified the -s (or --source) option, as in:: python -m pyextensions -s name With the -m flag, Python identifies pyextensions as the main script; we artificially change this so that "main_script" is properly identified as ``name``. """ CONFIG["main_module_name"] = module_name return import_module(module_name) def get_required_transformers(module_name, source): """ Scan a source for lines of the form:: #ext transformer1 [transformer2 ...] identifying transformers to be used and ensure that they are imported in the order in which they are specifid in the file. """ lines = source.split("\n") for number, line in enumerate(lines): if line.startswith("#ext "): line = line[5:] for trans_name in line.split(" "): import_transformer(module_name, trans_name.strip()) return None def import_transformer(module_name, trans_name): """This function needed, import a transformer for a given module and appends it to the appropriate lists. """ if module_name in TRANSFORMERS: for (name, transformer) in TRANSFORMERS[module_name]: if name == trans_name: return transformer else: for (name, transformer) in TRANSFORMERS["<cache>"]: if name == trans_name: if module_name not in TRANSFORMERS: TRANSFORMERS[module_name] = [] TRANSFORMERS[module_name].append((name, transformer)) return transformer # We have not imported the required transformer before. # # The code inside a module where a transformer is defined should be # standard Python code, which does not need any transformation. # So, we disable the import hook, and let the normal module import # do its job - which is faster and likely more reliable than our # custom method. hook = sys.meta_path[0] sys.meta_path = sys.meta_path[1:] try: transformer = __import__(trans_name) except ImportError: sys.stderr.write( "Fatal: Import Error in add_transformers: %s not found\n" % trans_name ) raise SystemExit except Exception as e: sys.stderr.write( "\nUnexpected exception in import_transformer %s\n " % e.__class__.__name__ ) sys.stderr.write(str(e.args)) sys.stderr.write(f"\nname = {trans_name}\n") sys.meta_path.insert(0, hook) # restore import hook TRANSFORMERS["<cache>"].append((trans_name, transformer)) if module_name not in TRANSFORMERS: TRANSFORMERS[module_name] = [] TRANSFORMERS[module_name].append((trans_name, transformer)) return transformer ############## # The code above dealt with adding an import hook, identifying and loading # transformers and redefining a __main__ module. # # What follows is the code required for doing the actual transformations. ############ def add_all_imports(module_name, source): """Adds required import in transformed module. Some transformers may require that other modules be imported in the source code for it to work properly. While this could in principle be done in transform_source(), we have found it useful to be done in a separate function. In particular, this makes it possible to use the import hook machinery of pyextensions in an REPL where the act of importing additional modules is done once, separately from the act of transforming the interactive input provided by a user. """ if module_name not in TRANSFORMERS: return source for _, transformer in TRANSFORMERS[module_name]: if hasattr(transformer, "add_import"): source = transformer.add_import() + source return source def apply_source_transformations(module_name, source): """Converts the source code. Applies all the source transformers specified in the module to be transformed, in the order listed. Source transformers are transformers that contain a function named ``transform_source`` which takes a string (source of a program) and returned a transformed string. """ if module_name not in TRANSFORMERS: return source for trans_name, transformer in TRANSFORMERS[module_name]: if hasattr(transformer, "transform_source"): source = transformer.transform_source(source) return source def get_parser(module_name): """Used to potentially substitute a different parser than the one provided in the ast module. """ if module_name not in TRANSFORMERS: return None for trans_name, transformer in TRANSFORMERS[module_name]: if hasattr(transformer, "parse"): return transformer.parse return None def apply_ast_transformations(module_name, tree): """Converts the abstract source tree. Applies all the AST transformers specified in the module, in the order listed. AST transformers are applied on a abstract syntax tree. They are transformers that contain a function named ``transform_ast`` which take an abstract syntax tree as input and return a new tree. """ if module_name not in TRANSFORMERS: return tree for trans_name, transformer in TRANSFORMERS[module_name]: if hasattr(transformer, "transform_ast"): tree = transformer.transform_ast(tree) return tree def apply_bytecode_transformations(module_name, code_object): """Converts the bytecode Applies all the bytecode transformers specified in the module, in the order listed. Bytecode transformers are transformers that contain a function named ``transform_bytecode`` which take a code object as input and return a new code_object. """ if module_name not in TRANSFORMERS: return code_object for trans_name, transformer in TRANSFORMERS[module_name]: if hasattr(transformer, "transform_bytecode"): code_object = transformer.transform_bytecode(code_object) return code_object def main(): """**Basic invocation** The primary role of pyextensions is to run programs that have a modified syntax. This is done by one of the following alternatives:: python -m pyextensions -s path/to/name python pyextensions.py -s path/to/name or ... --source path/to/name where ``name`` refers to a file named ``name.notpy``. Any subsequent ``import`` statement will first look for file whose extension is ``notpy`` before looking for normal ``py`` or ``pyc`` files. Any file with the ``notpy`` extension that is imported will also be processed by the relevant source transformers. Normal Python files will bypass the transformations. Instead of the ``notpy`` default, different extensions can be specified as follows:: python -m pyextensions -s name -x EXTENSION [EXTENSION_2 ...] or --file_extension EXTENSION [EXTENSION_2 ...] """ parser = argparse.ArgumentParser( description=""" pyextensions sets up an import hook which makes it possible to execute modules that contains modified Python syntax provided the relevant source transformers can be imported. """ ) parser.add_argument( "-s", "--source", help="""Source file to be transformed. Format: path/to/file -- Do not include an extension.""", ) parser.add_argument( "-x", "--file_extension", nargs="+", help="The file extension(s) of the module to load; default=notpy", ) args = parser.parse_args() if args.file_extension is not None: CONFIG["file_ext"] = args.file_extension if args.source is not None: try: CONFIG["main_module"] = import_main(args.source) except ModuleNotFoundError: print("Could not find module ", args.source, "\n") raise else: parser.print_help() if __name__ == "__main__": main()
396
35.3
87
21
2,976
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_9e861dc87ad22d7e_b3a7ac9d", "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": 133, "line_end": 133, "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/tmpr7mo7ysm/9e861dc87ad22d7e.py", "start": {"line": 133, "col": 14, "offset": 5241}, "end": {"line": 133, "col": 33, "offset": 5260}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.exec-detected_9e861dc87ad22d7e_f93f1d33", "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": 148, "line_end": 148, "column_start": 13, "column_end": 44, "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/tmpr7mo7ysm/9e861dc87ad22d7e.py", "start": {"line": 148, "col": 13, "offset": 5882}, "end": {"line": 148, "col": 44, "offset": 5913}, "extra": {"message": "Detected the use of exec(). exec() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.exec-detected_9e861dc87ad22d7e_e7c38436", "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": 150, "line_end": 150, "column_start": 13, "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.exec-detected", "path": "/tmp/tmpr7mo7ysm/9e861dc87ad22d7e.py", "start": {"line": 150, "col": 13, "offset": 5940}, "end": {"line": 150, "col": 39, "offset": 5966}, "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.non-literal-import_9e861dc87ad22d7e_444a4dd9", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.non-literal-import", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Untrusted user input in `importlib.import_module()` function allows an attacker to load arbitrary code. Avoid dynamic values in `importlib.import_module()` or use a whitelist to prevent running untrusted code.", "remediation": "", "location": {"file_path": "unknown", "line_start": 167, "line_end": 167, "column_start": 12, "column_end": 38, "code_snippet": "requires login"}, "cwe_id": "CWE-706: Use of Incorrectly-Resolved Name or Reference", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2021 - Broken Access Control", "references": [{"url": "https://owasp.org/Top10/A01_2021-Broken_Access_Control", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.non-literal-import", "path": "/tmp/tmpr7mo7ysm/9e861dc87ad22d7e.py", "start": {"line": 167, "col": 12, "offset": 6561}, "end": {"line": 167, "col": 38, "offset": 6587}, "extra": {"message": "Untrusted user input in `importlib.import_module()` function allows an attacker to load arbitrary code. Avoid dynamic values in `importlib.import_module()` or use a whitelist to prevent running untrusted code.", "metadata": {"owasp": ["A01:2021 - Broken Access Control", "A01:2025 - Broken Access Control"], "cwe": ["CWE-706: Use of Incorrectly-Resolved Name or Reference"], "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A01_2021-Broken_Access_Control"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
4
true
[ "CWE-95", "CWE-95" ]
[ "rules.python.lang.security.audit.exec-detected", "rules.python.lang.security.audit.exec-detected" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 148, 150 ]
[ 148, 150 ]
[ 13, 13 ]
[ 44, 39 ]
[ "A03:2021 - Injection", "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.", "Detected the use of exec(). exec() can be dangerous if used...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "HIGH", "HIGH" ]
pyextensions.py
/pyextensions.py
aroberge/pyextensions
MIT
2024-11-18T19:28:48.286293+00:00
1,686,794,745,000
231e7d5c7ffe24d261569df007170edf99de10dd
3
{ "blob_id": "231e7d5c7ffe24d261569df007170edf99de10dd", "branch_name": "refs/heads/master", "committer_date": 1686794745000, "content_id": "fce7ea009dbbfd7df01fc5e799bcef329e41c30d", "detected_licenses": [ "MIT" ], "directory_id": "11fb0bbdc98da7c0879290cc0665b451ab0facbc", "extension": "py", "filename": "unicode_search.py", "fork_events_count": 2, "gha_created_at": 1577038041000, "gha_event_created_at": 1609007441000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 229609603, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1780, "license": "MIT", "license_type": "permissive", "path": "/alfred-search-unicode/unicode_search.py", "provenance": "stack-edu-0054.json.gz:577479", "repo_name": "blueset/alfred-search-unicode", "revision_date": 1686794745000, "revision_id": "15cf4f843095a4e92fb8a413e856f4dd2ea288d5", "snapshot_id": "f0baa9a51ad41bafc4245182d5defb13f98a2c42", "src_encoding": "UTF-8", "star_events_count": 38, "url": "https://raw.githubusercontent.com/blueset/alfred-search-unicode/15cf4f843095a4e92fb8a413e856f4dd2ea288d5/alfred-search-unicode/unicode_search.py", "visit_date": "2023-06-26T12:45:53.943251" }
2.59375
stackv2
#!/usr/bin/python3 """ Search for Unicode Descriptions uni binary from: https://github.com/arp242/uni """ import sys import re import subprocess import json import csv if len(sys.argv) >= 2: query = sys.argv[1] try: out: str = subprocess.check_output( ["./uni", "-q", "search", query, "-f", "%(char q),%(cpoint q),%(dec q),%(name q),%(cat q)", ] ).decode() out = out.strip().splitlines() except subprocess.CalledProcessError: out = [] if re.match(r"((U\+)?[0-9A-Fa-f]+ ?)+$", query): pr_out: str = subprocess.check_output([ "./uni", "-q", "print", "-f", "%(char q),%(cpoint q),%(dec q),%(name q),%(cat q)" ] + query.split()).decode() out = pr_out.strip().splitlines() + out out = list(csv.reader(out, quotechar="'")) else: out = [] data = [] for i in out[:20]: char, c_hex, c_int, name, category = i disp_char = char try: out_char = chr(int(c_int)) except ValueError: out_char = "�" name = name.title() data.append({ "uid": f"unicode_{c_int}", "title": f"{disp_char} — {name}", "subtitle": f"{c_hex} ({c_int}) {category}", "arg": out_char, "text": { "copy": out_char, "largetype": out_char }, "icon": { "path": "unicode.png" }, "mods": { "alt": { "subtitle": f"Copy name: {name}", "arg": name, "valid": True }, "cmd": { "subtitle": f"Copy hex code: {c_hex}", "arg": c_hex, "valid": True }, }, }) json.dump({"items": data}, sys.stdout)
76
22.37
93
15
482
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_92f1e8136521d08a_33cfbada", "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": 29, "line_end": 31, "column_start": 23, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/92f1e8136521d08a.py", "start": {"line": 29, "col": 23, "offset": 589}, "end": {"line": 31, "col": 27, "offset": 735}, "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.dangerous-subprocess-use-tainted-env-args_92f1e8136521d08a_e7cf994c", "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 'check_output' 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": 29, "line_end": 31, "column_start": 47, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args", "path": "/tmp/tmpr7mo7ysm/92f1e8136521d08a.py", "start": {"line": 29, "col": 47, "offset": 613}, "end": {"line": 31, "col": 26, "offset": 734}, "extra": {"message": "Detected subprocess function 'check_output' with user controlled data. A malicious actor could leverage this to perform command injection. You may consider using 'shlex.quote()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args" ]
[ "security", "security" ]
[ "LOW", "MEDIUM" ]
[ "HIGH", "HIGH" ]
[ 29, 29 ]
[ 31, 31 ]
[ 23, 47 ]
[ 27, 26 ]
[ "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()'.", "Detected subproces...
[ 7.5, 7.5 ]
[ "LOW", "MEDIUM" ]
[ "HIGH", "MEDIUM" ]
unicode_search.py
/alfred-search-unicode/unicode_search.py
blueset/alfred-search-unicode
MIT
2024-11-18T19:28:49.313768+00:00
1,520,576,881,000
48a8bf55874e1f03ce27af5162231a0419c345bc
3
{ "blob_id": "48a8bf55874e1f03ce27af5162231a0419c345bc", "branch_name": "refs/heads/master", "committer_date": 1520576881000, "content_id": "982ce8a7d0fbdcf61c8ead5576158b52a45937c9", "detected_licenses": [ "Apache-2.0" ], "directory_id": "cab4ca8b262ed2f3b99d81e710f2bfbad9bfc8b9", "extension": "py", "filename": "google_stock_price_to_mysql_etl.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 124006392, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3220, "license": "Apache-2.0", "license_type": "permissive", "path": "/dataEngineering/google_stock_price_to_mysql_etl.py", "provenance": "stack-edu-0054.json.gz:577494", "repo_name": "ferdinand33/TestingRepo", "revision_date": 1520576881000, "revision_id": "fd70df20f7c5e81be9f723aca874fe00d06b5bbb", "snapshot_id": "957517fe9c517339770ba6fd634fcf6025271b7e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ferdinand33/TestingRepo/fd70df20f7c5e81be9f723aca874fe00d06b5bbb/dataEngineering/google_stock_price_to_mysql_etl.py", "visit_date": "2021-04-26T23:30:24.393595" }
3.0625
stackv2
""" A sample Airflow job copying doing the followings: - copying Google Stock price info from Google Finance - pushing to a local MySQL You need to have this table created in your local MySQL create table test.google_stock_price ( date date NOT NULL PRIMARY KEY, open float, high float, low float, close float, volume int ); """ from datetime import timedelta from datetime import datetime import airflow import pymysql import csv from airflow import DAG from airflow.operators.http_operator import SimpleHttpOperator from airflow.operators.python_operator import PythonOperator default_args = { 'owner': 'airflow', 'depends_on_past': False, 'start_date': airflow.utils.dates.days_ago(2), 'email': ['airflow@example.com'], 'email_on_failure': False, 'email_on_retry': False, 'retries': 1, 'retry_delay': timedelta(minutes=5), } # note that there is no schedule_interval # which means the only way to run this job is: # 1> manual trigger in the Airflow web interface # 2> programmatic trigger from other job dag = DAG( 'google_stock_price', default_args=default_args ) dag.doc_md = __doc__ # note the followings: # 1> it is using a http connection named "google_finance" which is created separately # from Airflow web interface (menu:Admin -> Connections) # 2> xcom_push is set to True so that the downloaded content is pushed to Xcom which # will be retrieved in the next Operator instance t1 = SimpleHttpOperator( task_id='get_google_stock', http_conn_id='google_finance', method='GET', endpoint='finance/historical?q=goog&startdate=27-Mar-2014&output=csv', xcom_push=True, dag=dag ) def pull_csv_and_push_to_mysql(**kwargs): """ A callback function used in PythonOperator instance. - Pull the google stock price info from Xcom - Push those records into MySQL """ # Another tip for debugging is to print something and check logs folder in $AIRFLOW_HOME # print(kwargs) value = kwargs['task_instance'].xcom_pull(task_ids='get_google_stock') reader = csv.reader(value.split("\n")) # skip the header # Date,Open,High,Low,Close,Volume next(reader) conn = pymysql.connect(host='localhost', user='root', password='keeyonghan', db='test', charset='utf8', autocommit=True) curs = conn.cursor() for row in reader: try: sql = "insert into test.google_stock_price value ('{date}', {open}, {high}, {low}, {close}, {volume});".format( date=datetime.strptime(row[0], "%d-%b-%y").date(), open=row[1], high=row[2], low=row[3], close=row[4], volume=row[5] if row[5] != '-' else "NULL" ) print(sql) curs.execute(sql) except: print(row) pass conn.close() ''' - For debugging purpose, you can write to a file f = open("keeyong.csv", "w") f.write(value) f.close() ''' t2 = PythonOperator( task_id='read_csv', provide_context=True, dag=dag, python_callable=pull_csv_and_push_to_mysql) t1 >> t2
112
27.75
123
18
780
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_8256bd302780f531_fd63af1e", "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": 94, "line_end": 94, "column_start": 13, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/775296/mysql-parameterized-queries", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.formatted-sql-query", "path": "/tmp/tmpr7mo7ysm/8256bd302780f531.py", "start": {"line": 94, "col": 13, "offset": 2851}, "end": {"line": 94, "col": 30, "offset": 2868}, "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_8256bd302780f531_98502bb9", "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": 94, "line_end": 94, "column_start": 13, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpr7mo7ysm/8256bd302780f531.py", "start": {"line": 94, "col": 13, "offset": 2851}, "end": {"line": 94, "col": 30, "offset": 2868}, "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" ]
[ 94, 94 ]
[ 94, 94 ]
[ 13, 13 ]
[ 30, 30 ]
[ "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" ]
google_stock_price_to_mysql_etl.py
/dataEngineering/google_stock_price_to_mysql_etl.py
ferdinand33/TestingRepo
Apache-2.0
2024-11-18T19:28:50.606858+00:00
1,591,879,680,000
4761244cdc7c136ae8e2537a4d1b641e649786d3
3
{ "blob_id": "4761244cdc7c136ae8e2537a4d1b641e649786d3", "branch_name": "refs/heads/master", "committer_date": 1591879680000, "content_id": "3921947077b44e5dc53502ca36895e5e5d699888", "detected_licenses": [ "MIT" ], "directory_id": "cafa76586370a39831eacd0984beacbfdbb45a45", "extension": "py", "filename": "env.py", "fork_events_count": 2, "gha_created_at": 1590537700000, "gha_event_created_at": 1591879682000, "gha_language": "Jupyter Notebook", "gha_license_id": "MIT", "github_id": 267177819, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6608, "license": "MIT", "license_type": "permissive", "path": "/env.py", "provenance": "stack-edu-0054.json.gz:577512", "repo_name": "jacobeturpin/nfl-offensive-playcalling-optimization", "revision_date": 1591879680000, "revision_id": "37105e8b36290bb766dc85550c0b8c904251077a", "snapshot_id": "0f0101172b4c86e78ee2c6cb7582fd6522c22ca5", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/jacobeturpin/nfl-offensive-playcalling-optimization/37105e8b36290bb766dc85550c0b8c904251077a/env.py", "visit_date": "2022-10-26T02:57:11.677839" }
3.234375
stackv2
"""NFL Playcalling Environment""" import random import gym from gym import spaces import data_loader as nfl_data # Create some test functions until api is built class NFLPlaycallingEnv(gym.Env): """Custom Environment that follows gym interface""" metadata = {'render.modes': ['human']} def __init__(self): super(NFLPlaycallingEnv, self).__init__() # Get data for probabilistic data filename = './data/nfl-play-by-play.csv' with open('data/dtypes.txt', 'r') as inf: dtypes_dict = eval(inf.read()) self.FieldPos = nfl_data.FieldPositionLoader(filename, dtypes_dict=dtypes_dict) # self._get_field_pos() # Define action and observation space # They must be gym.spaces objects # three discrete actions - pass, run, qb sneak self.action_space = spaces.Discrete(5) # observation space: field position, down, to_go, turnover, touchdown self.observation_space = spaces.Tuple(( spaces.Discrete(100), #field position spaces.Discrete(4), #down spaces.Discrete(99), #to_go spaces.Discrete(2), #turnover spaces.Discrete(2),#touchdown spaces.Discrete(2))) # field_goal self.action_dict = { 0: 'PASS', 1: 'RUN', 2: 'QB_SNEAK', 3: 'FIELD_GOAL', 4: 'PUNT' } def step(self, action): """Increment the environment one step given an action Attributes: action (int): 0-6 value specifying the action taken Returns: obs, reward, done, {} (Tuple): observations, current reward for step, and done flag """ assert self.action_space.contains(action) obs = self._get_observation(action) # check if observation state is a touchdown if obs[4] == 1: # print(f"action {self.action_dict[action]} td {obs}") done = True reward = 7. # check if observation state is a field goal elif obs[5] == 1: # print(f"action {self.action_dict[action]} field goal {obs}") done = True reward = 3. # check if it is a turnover elif obs[1] <= 0 or obs[3] == 1: # print(f"action {self.action_dict[action]} turnover {obs}") done = True reward = -7. * (1 - obs[0]/100) # if not TO or TD then not done and no rewards else: # print(f"action {self.action_dict[action]} continue {obs}") done = False reward = 0. print(f'state: action {self.action_dict[action]}, obs: {obs}, done: {done}, reward: {reward}') return obs, reward, done, {} def _get_observation(self, action): """Calculate the observation space using historical outcomes based on the action taken Attributes: action (int): 0-6 value specifying the action taken Returns: obs (Tuple of Discreet): the current observation space after the action has been applied """ # get outcomes from historical data outcomes = self._get_field_pos(action) try: outcome_idx = random.choices([i for i, x in enumerate(outcomes)], weights=[x[2] for x in outcomes]) outcome = outcomes[outcome_idx[0]] except: print(f"NO OUTCOMES: action {action}, outcomes: {outcomes}") outcome = nfl_data.PlayOutcome(type='BALL_MOVED', yards=0.0, prob=1) if outcome[0] == 'BALL_MOVED': # update field position for any BALL_MOVED outcome self.field_position = self.field_position + outcome[1] # ball moved if action == 4: #punted self.turnover = 1 elif self.field_position >= 100: # implied touchdown self.field_position = 100 self.touchdown = 1 elif outcome[1] >= self.to_go: # first down self.remaining_downs = 4 # will get decremented to 3 below self.to_go = 100 - self.field_position if self.field_position >= 90 else 10 else: # move the ball and decrement the down self.to_go -= outcome[1] elif outcome[0] == 'INTERCEPTION' or outcome[0] == 'FUMBLE': # turnover self.turnover = 1 self.field_position = self.field_position + outcome[1] elif outcome[0] == 'TOUCHDOWN': # touchdown self.field_position = 100 self.touchdown = 1 elif outcome[0] == 'FIELD_GOAL_MADE': # field goal was made self.field_goal = 1 elif outcome[0] == 'FIELD_GOAL_MISSED': # field goal was missed self.turnover = 1 self.field_position = self.field_position + outcome[1] else: raise ValueError('invalid action') # decrement downs self.remaining_downs -= 1 # print(f"updates: yardline:{self.field_position} turnover:{self.turnover} td:{self.touchdown}") return self._return_obs_state() def _return_obs_state(self): """Return the observation space at a given time """ return (self.field_position, self.remaining_downs, self.to_go, self.turnover, self.touchdown, self.field_goal) def _gen_rand_outcomes(self): outcomes = [] for i in range(4): outcomes.append(('BALL_MOVED', random.randint(0,self.to_go*2), 0.2)) outcomes.append(('INTERCEPTION', -5, 0.1)) outcomes.append(('TOUCHDOWN', 100-self.field_position, 0.1)) return outcomes def _get_field_pos(self, action): """Given an action, return the outcome based on the likelihood from historical data Attributes: action (int): Number associated with action taken for discrete observation space. See if statement for number coding """ if action == 0: action_val = nfl_data.PlayType.PASS elif action == 1: action_val = nfl_data.PlayType.RUN elif action == 2: action_val = nfl_data.PlayType.QB_SNEAK elif action == 3: action_val = nfl_data.PlayType.FIELD_GOAL elif action == 4: action_val = nfl_data.PlayType.PUNT else: raise ValueError('invalid action') # print(f"Action Taken {action_val}") outcomes = self.FieldPos.get_probability(down = self.remaining_downs, to_go = self.to_go, position = 100-self.field_position, play = action_val ) return outcomes def _set_field_pos(self, field_position = 20, remaining_downs = 3, to_go = 10, turnover = 0, touchdown = 0, field_goal = 0): """Used for testing to set different scenarios Attributes: field_position (int): 0-100 value of field position where 20 is own 20 and 80 is opp 20 remaining_downs (int): remaining downs before turnover to_go (int): distance to go for first down turnover (int): terminal state flag where 0=no turnover, 1=turnover touchdown (int): terminal state flag where 0=no touchdown, 1=touchdown """ self.field_position = field_position self.remaining_downs = remaining_downs self.to_go = to_go self.turnover = turnover self.touchdown = touchdown self.field_goal = field_goal def reset(self): self._set_field_pos() return self._return_obs_state() def render(self, mode='human'): print(f'Current Field Position: {self.field_position}') print(f'Remaining Downs: {self.remaining_downs}')
219
29.18
125
16
1,911
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_bff584af68567054_636df1b6", "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": 8, "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/tmpr7mo7ysm/bff584af68567054.py", "start": {"line": 22, "col": 8, "offset": 447}, "end": {"line": 22, "col": 36, "offset": 475}, "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_bff584af68567054_d99d9690", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 23, "line_end": 23, "column_start": 18, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpr7mo7ysm/bff584af68567054.py", "start": {"line": 23, "col": 18, "offset": 501}, "end": {"line": 23, "col": 34, "offset": 517}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-95" ]
[ "rules.python.lang.security.audit.eval-detected" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 23 ]
[ 23 ]
[ 18 ]
[ 34 ]
[ "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" ]
env.py
/env.py
jacobeturpin/nfl-offensive-playcalling-optimization
MIT
2024-11-18T19:28:54.846855+00:00
1,625,436,327,000
e93f060e4fb8d49de16cba1533032885f62c29b9
2
{ "blob_id": "e93f060e4fb8d49de16cba1533032885f62c29b9", "branch_name": "refs/heads/main", "committer_date": 1625436327000, "content_id": "9654f98f115b2d8dee744823fe20f1520f31a16a", "detected_licenses": [ "MIT" ], "directory_id": "7be5837b96f22966f7eb4c78bed2e2ad1918a68a", "extension": "py", "filename": "plot_different_cost_comparisons.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 382945595, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7799, "license": "MIT", "license_type": "permissive", "path": "/src/plotting/tikz_plotting/plot_different_cost_comparisons.py", "provenance": "stack-edu-0054.json.gz:577561", "repo_name": "cyrusneary/multiscaleLockdownCovid19", "revision_date": 1625436327000, "revision_id": "d04a644a10d381475f6e421e6a0aa068601b757c", "snapshot_id": "4fc3b5bdad1cf81db3deec01e51b7bc744bea554", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cyrusneary/multiscaleLockdownCovid19/d04a644a10d381475f6e421e6a0aa068601b757c/src/plotting/tikz_plotting/plot_different_cost_comparisons.py", "visit_date": "2023-06-18T23:08:25.769456" }
2.3125
stackv2
# %% import numpy as np import sys sys.path.append('../..') from utils.tester import Tester import pickle import os import matplotlib import matplotlib.pyplot as plt import math import tikzplotlib city_name = 'Phoenix' data = [] # data.append({'save_file_name': '2021-04-09_16-35-32', 'description': 'Regular cost'}) # data.append({'save_file_name': '2021-04-09_16-38-49', 'description': '2x cost'}) # data.append({'save_file_name': '2021-04-09_16-44-04', 'description': '4x cost'}) # data.append({'save_file_name': '2021-04-09_16-46-39', 'description': '8x cost'}) # data.append({'save_file_name': '2021-04-09_18-01-51', 'description': '20x cost'}) # data.append({'save_file_name': '2021-04-09_21-26-07', 'description': 'Regular cost'}) # data.append({'save_file_name': '2021-04-11_12-57-45', 'description': '2x cost'}) # data.append({'save_file_name': '2021-04-11_12-53-45', 'description': '4x cost'}) # data.append({'save_file_name': '2021-04-11_13-01-47', 'description': '8x cost'}) # data.append({'save_file_name': '2021-04-11_12-51-09', 'description': '20x cost'}) # param_vals = [0.01, 0.02, 0.04, 0.08, 0.2] data.append({'save_file_name': '2021-04-24_12-35-23', 'description': '0.1x cost'}) data.append({'save_file_name': '2021-04-24_12-34-29', 'description': '0.2x cost'}) data.append({'save_file_name': '2021-04-24_12-20-26', 'description': '0.5x cost'}) data.append({'save_file_name': '2021-04-23_14-02-29', 'description': 'Regular cost'}) data.append({'save_file_name': '2021-04-23_15-02-03', 'description': '2x cost'}) data.append({'save_file_name': '2021-04-23_15-00-02', 'description': '4x cost'}) param_vals = np.array([0.1, 0.2, 0.5, 1, 2, 4]) * 1e-4 base_directory = os.getcwd() base_directory = base_directory[0:base_directory.find('src')+3] if city_name == 'Phoenix': data_folder_name = 'Phoenix' if city_name == 'Seattle': data_folder_name = 'IntercityFlow_Seattle' if city_name == 'Dallas': data_folder_name = 'Intercity_Dallas' # Load county data county_data_file_path = os.path.join(base_directory, '..', 'data', data_folder_name, 'data_processing_outputs', 'city_data.p') with open(county_data_file_path,'rb') as f: county_data = pickle.load(f) county_list = list(county_data.keys()) # %% total_population = 0 for county in county_data.keys(): total_population = total_population + county_data[county]['population'] tester_list = [] peak_infections_list = [] num_deaths_list = [] average_lockdown_list = [] for ind in range(len(data)): file_path = os.path.join(base_directory, 'optimization', 'save', data[ind]['save_file_name']) with open(file_path,'rb') as f: tester = pickle.load(f) data[ind]['tester'] = tester data[ind]['scale_frac'] = tester.params['scale_frac'] data[ind]['I'] = np.sum(tester.results['I_best'] * data[ind]['scale_frac'], axis=1) data[ind]['D'] = np.sum(tester.results['D_best'] * data[ind]['scale_frac'], axis=1) # data[ind]['peak_infections'] = 100 * np.max(data[ind]['I']) / 100,000 total_population # data[ind]['num_deaths'] = 100 * data[ind]['D'][-1] / total_population data[ind]['peak_infections'] = np.max(data[ind]['I']) * 100000 / total_population data[ind]['num_deaths'] = data[ind]['D'][-1] * 100000 / total_population peak_infections_list.append(data[ind]['peak_infections']) num_deaths_list.append(data[ind]['num_deaths']) average_lockdown_list.append(1 - np.average(data[ind]['tester'].results['L_best'][0:98])) # %% fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(param_vals, [data[i]['peak_infections'] for i in range(len(data))], marker='d') ax1.set_xscale('log') ax1.set_xlabel('Economic Impact Parameter') ax1.set_ylabel('Infections per 100,000') save_location = os.path.join(base_directory, 'plotting', 'tikz_plotting', city_name) filename = os.path.join(save_location, 'scale_cost_by_pop_different_cost_infections_comparison.tex') tikzplotlib.save(filename) # %% fig = plt.figure() ax2 = fig.add_subplot(111) ax2.plot(param_vals, [data[i]['num_deaths'] for i in range(len(data))], marker='d') ax2.set_xscale('log') ax2.set_xlabel('Economic Impact Parameter') ax2.set_ylabel('Deaths per 100,000') save_location = os.path.join(base_directory, 'plotting', 'tikz_plotting', city_name) filename = os.path.join(save_location, 'scale_cost_by_pop_different_cost_deaths_comparison.tex') tikzplotlib.save(filename) # %% fig = plt.figure() ax3 = fig.add_subplot(111) ax3.plot(param_vals, average_lockdown_list, marker='d') ax3.set_xscale('log') ax3.set_xlabel('Economic Impact Parameter') ax3.set_ylabel('Average Lockdown Rate') save_location = os.path.join(base_directory, 'plotting', 'tikz_plotting', city_name) filename = os.path.join(save_location, 'scale_cost_by_pop_different_cost_lockdown_comparison.tex') tikzplotlib.save(filename) # %%%%%%%%%% OLD BAR PLOTS # Plot the results x = np.arange(len(data)) cmap = matplotlib.cm.get_cmap('Oranges') norm = matplotlib.colors.Normalize(vmin=np.min(peak_infections_list), vmax=np.max(peak_infections_list)) color_list = [] for i in range(len(data)): color_list.append(cmap(norm(data[i]['peak_infections']))) width = 0.5 # %% fig = plt.figure() ### PLOT PEAK INFECTIONS COMPARISON ax1 = fig.add_subplot(111) labels = [] for i in range(len(data)): val = data[i]['peak_infections'] ax1.bar(i, val, width, edgecolor='black', facecolor=color_list[i], label=data[i]['description']) labels = [ '0.01', '0.02', '0.04', '0.08', '0.20' ] # ax1.set_title('Peak Infections', fontsize=fontsize) ax1.set_ylabel('Peak Infections per 100,000 People') ax1.set_xlabel('Economic Impact Parameter') ax1.set_xticks(x) ax1.set_xticklabels(labels) ax1.tick_params(axis='both') save_location = os.path.join(base_directory, 'plotting', 'tikz_plotting', city_name) filename = os.path.join(save_location, 'different_cost_infections_comparison.tex') tikzplotlib.save(filename) # %% fig = plt.figure() ### PLOT DEATHS COMPARISON ax2 = fig.add_subplot(111) cmap = matplotlib.cm.get_cmap('Oranges') norm = matplotlib.colors.Normalize(vmin=np.min(num_deaths_list), vmax=np.max(num_deaths_list)) color_list = [] for i in range(len(data)): color_list.append(cmap(norm(data[i]['num_deaths']))) labels = [] for i in range(len(data)): val = data[i]['num_deaths'] ax2.bar(i, val, width, edgecolor='black', facecolor=color_list[i], label=data[i]['description']) labels = [ '0.01', '0.02', '0.04', '0.08', '0.20' ] ax2.set_ylabel('Deaths per 100,000 People') ax2.set_xlabel('Economic Impact Parameter') ax2.set_xticks(x) ax2.set_xticklabels(labels) ax2.tick_params(axis='both') save_location = os.path.join(base_directory, 'plotting', 'tikz_plotting', city_name) filename = os.path.join(save_location, 'different_cost_deaths_comparison.tex') tikzplotlib.save(filename) # %% # %% fig = plt.figure() ### PLOT lockdown COMPARISON ax3 = fig.add_subplot(111) cmap = matplotlib.cm.get_cmap('Blues') norm = matplotlib.colors.Normalize(vmin=np.min(average_lockdown_list), vmax=np.max(average_lockdown_list)) color_list = [] for i in range(len(data)): color_list.append(cmap(norm(average_lockdown_list[i]))) labels = [] for i in range(len(data)): val = average_lockdown_list[i] ax3.bar(i, val, width, edgecolor='black', facecolor=color_list[i], label=data[i]['description']) labels = [ '0.01', '0.02', '0.04', '0.08', '0.20' ] ax3.set_ylabel('Average Lockdown') ax3.set_xlabel('Economic Impact Parameter') ax3.set_xticks(x) ax3.set_xticklabels(labels) ax3.tick_params(axis='both') save_location = os.path.join(base_directory, 'plotting', 'tikz_plotting', city_name) filename = os.path.join(save_location, 'different_cost_lockdown_comparison.tex') tikzplotlib.save(filename) # %%
240
31.5
126
15
2,440
python
[{"finding_id": "semgrep_rules.python.lang.correctness.useless-eqeq_9ea6929026020bd5_1b5d97df", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.useless-eqeq", "finding_type": "correctness", "severity": "low", "confidence": "medium", "message": "This expression is always True: `city_name == city_name` or `city_name != city_name`. If testing for floating point NaN, use `math.isnan(city_name)`, or `cmath.isnan(city_name)` if the number is complex.", "remediation": "", "location": {"file_path": "unknown", "line_start": 41, "line_end": 41, "column_start": 4, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.useless-eqeq", "path": "/tmp/tmpr7mo7ysm/9ea6929026020bd5.py", "start": {"line": 41, "col": 4, "offset": 1771}, "end": {"line": 41, "col": 26, "offset": 1793}, "extra": {"message": "This expression is always True: `city_name == city_name` or `city_name != city_name`. If testing for floating point NaN, use `math.isnan(city_name)`, or `cmath.isnan(city_name)` if the number is complex.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_9ea6929026020bd5_75901ab4", "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": 19, "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/tmpr7mo7ysm/9ea6929026020bd5.py", "start": {"line": 51, "col": 19, "offset": 2179}, "end": {"line": 51, "col": 33, "offset": 2193}, "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_9ea6929026020bd5_b386b9ad", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 67, "line_end": 67, "column_start": 18, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/9ea6929026020bd5.py", "start": {"line": 67, "col": 18, "offset": 2643}, "end": {"line": 67, "col": 32, "offset": 2657}, "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-pickle", "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 51, 67 ]
[ 51, 67 ]
[ 19, 18 ]
[ 33, 32 ]
[ "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "Avoid using `pickle`, which is known to lead to...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
plot_different_cost_comparisons.py
/src/plotting/tikz_plotting/plot_different_cost_comparisons.py
cyrusneary/multiscaleLockdownCovid19
MIT
2024-11-18T19:28:56.613046+00:00
1,468,576,532,000
9f881efdc6196e692394faee554b86e3a9e66f2f
3
{ "blob_id": "9f881efdc6196e692394faee554b86e3a9e66f2f", "branch_name": "refs/heads/master", "committer_date": 1468576532000, "content_id": "437d684d76377653558e40f03eb6c86435202bb4", "detected_licenses": [ "MIT" ], "directory_id": "1358b3e3a029481a33deae9c55b0e1cad8fa4b47", "extension": "py", "filename": "python_runner.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 63340456, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 752, "license": "MIT", "license_type": "permissive", "path": "/python_runner.py", "provenance": "stack-edu-0054.json.gz:577587", "repo_name": "radzak/ResultChecker", "revision_date": 1468576532000, "revision_id": "597b40f3ac47906d815815570eadd0170bbc0f8f", "snapshot_id": "e1be469c327899fa0321367d1859b41c36554f0c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/radzak/ResultChecker/597b40f3ac47906d815815570eadd0170bbc0f8f/python_runner.py", "visit_date": "2021-01-17T20:08:34.465622" }
2.71875
stackv2
import subprocess import os class PythonRunner: def __init__(self, input_directory, algorithm_name): self.algorithm_name = algorithm_name self.python_file_name = self.algorithm_name + '.py' self.input_directory = input_directory def get_output(self, user_input): p = subprocess.Popen(["python", os.path.join(self.input_directory, self.python_file_name)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) out, err = p.communicate(input=bytes(user_input, 'utf-8')) output = out.decode("utf-8") return output if __name__ == '__main__': pass
25
29.08
99
14
142
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_de1a4ff701684d03_56482ac0", "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": 13, "line_end": 17, "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://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/de1a4ff701684d03.py", "start": {"line": 13, "col": 13, "offset": 311}, "end": {"line": 17, "col": 31, "offset": 586}, "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" ]
[ 13 ]
[ 17 ]
[ 13 ]
[ 31 ]
[ "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" ]
python_runner.py
/python_runner.py
radzak/ResultChecker
MIT
2024-11-18T19:28:58.499789+00:00
1,603,100,319,000
08eaf9b37938a2a2c9c63ec50f6d67345ec2ada2
2
{ "blob_id": "08eaf9b37938a2a2c9c63ec50f6d67345ec2ada2", "branch_name": "refs/heads/master", "committer_date": 1603100319000, "content_id": "7048d5e78fba4cae08f62cd98728ff28a592e85a", "detected_licenses": [ "MIT" ], "directory_id": "dcff46b92756e324009bd132e666baad7ef6f151", "extension": "py", "filename": "wrapper.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": 2853, "license": "MIT", "license_type": "permissive", "path": "/wrapper.py", "provenance": "stack-edu-0054.json.gz:577608", "repo_name": "vega-d/FAQdiscordBot", "revision_date": 1603100319000, "revision_id": "518148954a7615bb7c0106f8d6d7fde0be60c171", "snapshot_id": "fd3edcb287f26547628d4b12a1c712c07532154a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/vega-d/FAQdiscordBot/518148954a7615bb7c0106f8d6d7fde0be60c171/wrapper.py", "visit_date": "2022-12-29T14:42:02.239358" }
2.421875
stackv2
import sqlite3 from settings import * entry = sqlite3.connect(db_name) cur = entry.cursor() print('wrapper library imported.') def fetch_ID(id): res = cur.execute("""SELECT * FROM quotes WHERE msgID IS %s""" % id).fetchall() res = [(i[0].replace(r';!;', r"'"), i[1].replace(r';!;', r"'"), i[2], i[3], i[4], i[5]) for i in res] # print(res[0]) return res def add_quote(msg_obj): # reaction.message should be passed here text, usr, msgID, usr_id = msg_obj.content, str(msg_obj.author), msg_obj.id, msg_obj.author.id dateUTC, jumplink = msg_obj.created_at, msg_obj.jump_url # print(fetch_ID(msgID)) if not fetch_ID(msgID): cur.execute( """INSERT INTO quotes(content, author, msgID, authorID, date, jumplink) VALUES('%s', '%s', '%s', '%s', '%s', '%s')""" % (text.replace(r"'", r";!;"), usr.replace(r"'", r";!;"), msgID, usr_id, dateUTC, jumplink)) entry.commit() return True else: return False def fecth_quote(tags=None): # tags - list of strings1 if tags is None: return cur.execute("""SELECT * FROM quotes""").fetchall() tmp = [] for tag in tags: tmp.append(r"content like '%{}%' ".format(tag)) request = ' OR '.join(tmp) res = cur.execute("""SELECT * FROM quotes WHERE """ + request).fetchall() res = [(i[0].replace(r';!;', r"'"), i[1].replace(r';!;', r"'"), i[2], i[3], i[4], i[5]) for i in res] # print(res[0]) return res def book_renderer(search='none', results=None, page=0): if search == 'none' or search is None: search = ['no tags in search', ] tags_hud = '; '.join(search) quotes_hud = "" l, r = quotes_per_page * page, min((quotes_per_page * (page + 1)), len(results)) if l > len(results): l = 0 pagelen = len(results) // quotes_per_page pagelen = len(results)//quotes_per_page + int(len(results)/quotes_per_page > len(results)//quotes_per_page) page_results = results[l:r] for cur_quote in page_results: author, text = cur_quote[1], cur_quote[0].replace('\n', '\t') date, id = cur_quote[4][:16], cur_quote[2] quote_hud = """> <o>=============<%s>=============<o> [msgID:%s] > **%s** - %s\n""" % (date, id, author, text) quotes_hud += quote_hud if pagelen: page_hud = "page %d from %d" % (page + 1, pagelen) else: page_hud = "no pages" debug = """debug: l, r: %d, %d pagelen: %d len(): %d """ % (l, r, pagelen, len(results)) hull = """quote search for [%s]: > [ %s ] > quotes: %s %s""" % (tags_hud, page_hud, quotes_hud, debug) if len(hull) > 2000: return "unexpected 2k limit error on page %d" % page, pagelen return hull, pagelen def quote_del(id): cur.execute("""DELETE FROM quotes WHERE msgID = '%s'""" % id) entry.commit()
92
30.02
131
14
869
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_6639e67c6df60b25_bc32c700", "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": 12, "line_end": 12, "column_start": 11, "column_end": 73, "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/tmpr7mo7ysm/6639e67c6df60b25.py", "start": {"line": 12, "col": 11, "offset": 160}, "end": {"line": 12, "col": 73, "offset": 222}, "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_6639e67c6df60b25_885509e7", "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": 12, "line_end": 12, "column_start": 11, "column_end": 73, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpr7mo7ysm/6639e67c6df60b25.py", "start": {"line": 12, "col": 11, "offset": 160}, "end": {"line": 12, "col": 73, "offset": 222}, "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_6639e67c6df60b25_b3bb0e97", "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": 25, "line_end": 27, "column_start": 9, "column_end": 103, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/775296/mysql-parameterized-queries", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.formatted-sql-query", "path": "/tmp/tmpr7mo7ysm/6639e67c6df60b25.py", "start": {"line": 25, "col": 9, "offset": 672}, "end": {"line": 27, "col": 103, "offset": 919}, "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_6639e67c6df60b25_6dc933ac", "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": 25, "line_end": 27, "column_start": 9, "column_end": 103, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpr7mo7ysm/6639e67c6df60b25.py", "start": {"line": 25, "col": 9, "offset": 672}, "end": {"line": 27, "col": 103, "offset": 919}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_6639e67c6df60b25_df3eb03a", "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": 42, "line_end": 42, "column_start": 11, "column_end": 67, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpr7mo7ysm/6639e67c6df60b25.py", "start": {"line": 42, "col": 11, "offset": 1272}, "end": {"line": 42, "col": 67, "offset": 1328}, "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_6639e67c6df60b25_292c1318", "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": 91, "line_end": 91, "column_start": 3, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/775296/mysql-parameterized-queries", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.formatted-sql-query", "path": "/tmp/tmpr7mo7ysm/6639e67c6df60b25.py", "start": {"line": 91, "col": 3, "offset": 2775}, "end": {"line": 91, "col": 64, "offset": 2836}, "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_6639e67c6df60b25_d666e244", "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": 91, "line_end": 91, "column_start": 3, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpr7mo7ysm/6639e67c6df60b25.py", "start": {"line": 91, "col": 3, "offset": 2775}, "end": {"line": 91, "col": 64, "offset": 2836}, "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"}}}]
7
true
[ "CWE-89", "CWE-89", "CWE-89", "CWE-89", "CWE-89", "CWE-89", "CWE-89" ]
[ "rules.python.lang.security.audit.formatted-sql-query", "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "rules.python.lang.security.audit.formatted-sql-query", "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", ...
[ "security", "security", "security", "security", "security", "security", "security" ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "MEDIUM", "HIGH", "MEDIUM", "HIGH", "HIGH", "MEDIUM", "HIGH" ]
[ 12, 12, 25, 25, 42, 91, 91 ]
[ 12, 12, 27, 27, 42, 91, 91 ]
[ 11, 11, 9, 9, 11, 3, 3 ]
[ 73, 73, 103, 103, 67, 64, 64 ]
[ "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Detected possible formatted SQL query. Use parameterized queries instead.", "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepa...
[ 5, 7.5, 5, 7.5, 7.5, 5, 7.5 ]
[ "LOW", "LOW", "LOW", "LOW", "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH", "HIGH" ]
wrapper.py
/wrapper.py
vega-d/FAQdiscordBot
MIT
2024-11-18T19:28:58.610836+00:00
1,536,338,868,000
a239b0fd19438b51f591d9cf6c0faa38ba46b69e
3
{ "blob_id": "a239b0fd19438b51f591d9cf6c0faa38ba46b69e", "branch_name": "refs/heads/master", "committer_date": 1536338868000, "content_id": "4edd90963d634e1afa047f704ac5d9824e41004a", "detected_licenses": [ "MIT" ], "directory_id": "0eb8704e39a1c04c27dc15a4791273b1d6e34af0", "extension": "py", "filename": "templates.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 140502041, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4305, "license": "MIT", "license_type": "permissive", "path": "/medsldocs/templates.py", "provenance": "stack-edu-0054.json.gz:577610", "repo_name": "MEDSL/documentation", "revision_date": 1536338868000, "revision_id": "e7dfaf85fca7eadb9a1fe351864da8e9653da8d9", "snapshot_id": "11a63b6dc2750706b52e510e7aa02a10d03a1a3a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/MEDSL/documentation/e7dfaf85fca7eadb9a1fe351864da8e9653da8d9/medsldocs/templates.py", "visit_date": "2020-03-22T19:04:08.206586" }
2.734375
stackv2
import logging import os import pkgutil import re import sys from pathlib import Path import attr import jinja2 @attr.s class Template(object): """Jinja-driven template for documentation. Args: filename (str): Path to Jinja template. Attributes: filename (str): Path to Jinja template. text (str): Text of Jinja template. """ filename = attr.ib() def __attrs_post_init__(self): template_bytes = pkgutil.get_data('medsldocs', 'templates/{}'.format(self.filename)) self.text = template_bytes.decode('utf-8') def write(self, data, dest='', strict=True): """Render a template and write the result to the disk. Args: data (dict): A mapping of template variables to values. dest (str): Destination path (e.g., `./release-notes.md`). strict (bool): Whether undefined template variables should result in an error. `True` by default because our templates aren't written to handle this gracefully. Returns: str: The rendered template text. """ template = jinja2.Template(self.text, undefined=jinja2.StrictUndefined if strict else None) rendered = template.render(data) if dest: Path(dest).resolve().write_text(rendered) return rendered @attr.s class RdTemplate(Template): """Jinja-driven template for R documentation. Args: filename (str): Path to Jinja template. Attributes: filename (str): Path to Jinja template. text (str): Text of Jinja template. """ def __attrs_post_init__(self): module_dir = os.path.dirname(sys.modules['medsldocs'].__file__) loader = jinja2.FileSystemLoader(searchpath=os.path.join(module_dir, 'templates')) self.env = jinja2.Environment(loader=loader, block_start_string='<+', block_end_string='+>', variable_start_string='<<', variable_end_string='>>', comment_start_string='<#', comment_end_string='>#') self.env.filters['r_alias'] = self._r_alias self.env.filters['format_code'] = self._format_code def write(self, data, dest='', strict=True): """Render a template and write the result to the disk. Args: data (dict): A mapping of template variables to values. dest (str): Destination path (e.g., `./release-notes.md`). strict (bool): Whether undefined template variables should result in an error. `True` by default because our templates aren't written to handle this gracefully. Returns: str: The rendered template text. """ if strict: self.env.undefined = jinja2.StrictUndefined template = self.env.get_template(self.filename) rendered = template.render(data) if dest: Path(dest).resolve().write_text(rendered) return rendered @staticmethod def _r_alias(text: str) -> str: """Jinja filter for translating dataset names to valid R object names. Example: '2016-precinct-house' -> 'house_precinct_2016'. See http://jinja.pocoo.org/docs/2.10/api/#custom-filters. """ if text: print(text) no_dashes = re.sub('[- ]', '_', text) return re.sub(r'([0-9]*)(_*)(.*)', '\g<3>\g<2>\g<1>', no_dashes) else: return '' @staticmethod def _format_code(text: str) -> str: """Jinja filter for translating Markdown code markup to Latex code markup. Example: \`inline snippet\` -> \\code\{inline snippet\}. See http://jinja.pocoo.org/docs/2.10/api/#custom-filters. """ if text: return re.sub(r'`([^`]+)`', '\code{\g<1>}', text) else: return '' @attr.s class Readme(Template): """Jinja-driven template for GitHub repo READMEs. Args: filename (str): Path to Jinja template. Attributes: filename (str): Path to Jinja template. text (str): Text of Jinja template. """ filename = attr.ib(default='precinct_repo_readme.jinja') def __attrs_post_init__(self): self.template = self.env.get_template(self.filename)
131
31.86
118
16
970
python
[{"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_ce8f81c63b1f7d45_3e3a6b6f", "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": 42, "line_end": 42, "column_start": 20, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "path": "/tmp/tmpr7mo7ysm/ce8f81c63b1f7d45.py", "start": {"line": 42, "col": 20, "offset": 1226}, "end": {"line": 42, "col": 41, "offset": 1247}, "extra": {"message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["flask"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_ce8f81c63b1f7d45_10d57a64", "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": 63, "line_end": 65, "column_start": 20, "column_end": 63, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "path": "/tmp/tmpr7mo7ysm/ce8f81c63b1f7d45.py", "start": {"line": 63, "col": 20, "offset": 1825}, "end": {"line": 65, "col": 63, "offset": 2088}, "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_ce8f81c63b1f7d45_d51ed180", "tool_name": "semgrep", "rule_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "remediation": "jinja2.Environment(loader=loader, block_start_string='<+', block_end_string='+>',\n variable_start_string='<<', variable_end_string='>>', comment_start_string='<#',\n comment_end_string='>#', autoescape=True)", "location": {"file_path": "unknown", "line_start": 63, "line_end": 65, "column_start": 20, "column_end": 63, "code_snippet": "requires login"}, "cwe_id": "CWE-116: Improper Encoding or Escaping of Output", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "path": "/tmp/tmpr7mo7ysm/ce8f81c63b1f7d45.py", "start": {"line": 63, "col": 20, "offset": 1825}, "end": {"line": 65, "col": 63, "offset": 2088}, "extra": {"message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "fix": "jinja2.Environment(loader=loader, block_start_string='<+', block_end_string='+>',\n variable_start_string='<<', variable_end_string='>>', comment_start_string='<#',\n comment_end_string='>#', autoescape=True)", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b701_jinja2_autoescape_false.html", "cwe": ["CWE-116: Improper Encoding or Escaping of Output"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["jinja2"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_ce8f81c63b1f7d45_63ee69e3", "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": 84, "line_end": 84, "column_start": 20, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "path": "/tmp/tmpr7mo7ysm/ce8f81c63b1f7d45.py", "start": {"line": 84, "col": 20, "offset": 2882}, "end": {"line": 84, "col": 41, "offset": 2903}, "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"}}}]
4
true
[ "CWE-79", "CWE-79", "CWE-116", "CWE-79" ]
[ "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "rules.python.jinja2.security.audit.missing-autoescape-disabled", "rules.python.flask.security.xss.audit.direct-use-of-jinja2" ]
[ "security", "security", "security", "security" ]
[ "LOW", "LOW", "MEDIUM", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 42, 63, 63, 84 ]
[ 42, 65, 65, 84 ]
[ 20, 20, 20, 20 ]
[ 41, 63, 63, 41 ]
[ "A07:2017 - Cross-Site Scripting (XSS)", "A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A07:2017 - Cross-Site Scripting (XSS)" ]
[ "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "Detected direct use of jinja2. If n...
[ 5, 5, 5, 5 ]
[ "LOW", "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM", "MEDIUM" ]
templates.py
/medsldocs/templates.py
MEDSL/documentation
MIT
2024-11-18T19:39:26.480246+00:00
1,435,650,431,000
57b024bca8ed40ff1e3e454bed80e2a21e31d11a
3
{ "blob_id": "57b024bca8ed40ff1e3e454bed80e2a21e31d11a", "branch_name": "refs/heads/master", "committer_date": 1435650431000, "content_id": "29f0f56e464458f4f34bb887c8bad57291d9b95f", "detected_licenses": [ "MIT" ], "directory_id": "46ba3b02ed738839c97922b02cdbe647c19f1e78", "extension": "py", "filename": "text_rank.py", "fork_events_count": 4, "gha_created_at": 1414805629000, "gha_event_created_at": 1431345799000, "gha_language": "Python", "gha_license_id": null, "github_id": 26038733, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6678, "license": "MIT", "license_type": "permissive", "path": "/code/statistic/text_rank.py", "provenance": "stack-edu-0054.json.gz:577659", "repo_name": "lavizhao/insummer", "revision_date": 1435650431000, "revision_id": "16520a6c3114e2d6360dca469221bed00a570785", "snapshot_id": "e96e6c9cbd88fcc5a75e915f905ecbdab77e7312", "src_encoding": "UTF-8", "star_events_count": 8, "url": "https://raw.githubusercontent.com/lavizhao/insummer/16520a6c3114e2d6360dca469221bed00a570785/code/statistic/text_rank.py", "visit_date": "2020-04-05T22:59:33.814107" }
2.578125
stackv2
#!/usr/bin/python3 #coding=utf-8 from datetime import datetime import itertools import networkx as nx import pickle import math from abstract_type import abstract_type import sys sys.path.append('..') import insummer from insummer.common_type import Question,Answer from insummer.read_conf import config from insummer.util import NLP from insummer.query_expansion.entity_finder import NgramEntityFinder #获得问题的路径信息 question_conf = config('../../conf/question.conf') filter_path = question_conf['filter_qa'] duc_path = question_conf['duc_question'] filter_abstract = question_conf['filter_abstract'] duc_abstract = question_conf['duc_abstract'] #为了ROUGE要将每个topic分开存放到duc/sum_result中 textrank_path = question_conf['textrank_sum'] nlp = NLP() #xx_quesiton里面即问题列表 filter_file = open(filter_path,'rb') filter_quesiton = pickle.load(filter_file) duc_file = open(duc_path,'rb') duc_question = pickle.load(duc_file) #single_question => nbest_content => top_k sents => abstract def get_abstract(questions,q_path,K): "根据问题list获得摘要list" abstract_list = [] for idx,s_question in enumerate(questions): print('处理第 %s 个问题'%idx) start_time = datetime.now() #获得标题和答案的文本,修改了commontype里面的get_nbest_content函数,返回以空格链接的答案 title = s_question.get_title() answer_text = s_question.get_nbest_content() #为每个答案创建一个摘要类,以标题和答案初始化 tmp_abstract = abstract_type(title,answer_text) #对某一答案抽取topK个句子作为摘要,需改成限定词语数量。 abstract_text = ExtractSentence(answer_text,K) #为了ROUGE,存放单个摘要,文件名用topic名D0701A etc. filename = s_question.get_author() if filename[-1] == '/': filename = filename[:-1] sum_path = textrank_path + filename with open(sum_path,'w') as sum_file: sum_file.write(abstract_text) print('abstract for %s is wrote..'%filename) sum_file.close() #保存并添加到摘要list中,准备扔到pickle里 tmp_abstract.update_abstract(abstract_text) abstract_list.append(tmp_abstract) times = datetime.now() - start_time print("text_length : %s used_time : %s \n abstract : %s"%(len(answer_text),times,abstract_text)) #将duc或者filter的所有问题和相应的摘要保存起来 out_file = open(q_path,'wb') pickle.dump(abstract_list,out_file,True) def filter_sent(sent_tokens,filter_val): "根据句子中的实体数,筛选在构建图结构时,要保留的句子" tmp_sents = [] for sent in sent_tokens: finder = NgramEntityFinder(sent) enti_tokens = finder.extract_entity() if len(enti_tokens) >= filter_val: tmp_sents.append(sent) return tmp_sents #text => sentences => graph => calculate => scores def ExtractSentence(text,k): "根据文本内容获得句子重要性排名" print('开始句子重要性排名') sent_tokens = nlp.sent_tokenize(text) #可以加入限制条件,如果句子中的实体数少于阈值则放弃这个句子,等等,待扩展 sent_tokens = filter_sent(sent_tokens,1) #建图结构 text_graph = graph_construct(sent_tokens) #这里pagerank有三种,一种是正常的pg,一种是利用numpy还有一种就是下面的利用scipy的稀疏矩阵 print('start to calculate') #cal_gr_page_rank = nx.pagerank(text_graph,weight='weight') cal_gr_page_rank = nx.pagerank_scipy(text_graph) print('ended') #按照最后的score得分进行排序,获得前K个,待扩展,使之取不超250个词的句子 sents = sorted(cal_gr_page_rank,key = cal_gr_page_rank.get, reverse=True) kth = get_sum_sents(sents,250) #topK str_tmp_list = [] for sidx in range(kth): str_tmp = sents[sidx] str_tmp += '[%.4f]'%(cal_gr_page_rank[sents[sidx]]) str_tmp_list.append(str_tmp) print_score(str_tmp_list) return ' '.join(sents[:kth]) def print_score(str_list): for i in str_list: print(i) def get_sum_sents(sents,limit_num): "对于按重要性排序的句子,获得不超过limit_num词数的尽量多的句子" total_num = 0 idx = 0 while(total_num <= limit_num and idx < len(sents)): total_num += len(nlp.word_tokenize(sents[idx])) if (total_num > limit_num): break idx += 1 return idx #实际运行时,发现整个构建图结构才是最耗时的阶段,可以在这上面优化时间复杂度 def graph_construct(nodes): "构建text_rank_graph" print('构建text_graph') #利用networkx简历图结构,节点即传入的sentences text_graph = nx.Graph() text_graph.add_nodes_from(nodes) #这里没有对边进行筛选,假设任意两个句子都是有相似性的 nodePairs = list(itertools.combinations(nodes,2)) for pair in nodePairs: first_sent = pair[0] second_sent= pair[1] #weights = lDistance(first_sent,second_sent) weights = sent_sim(first_sent,second_sent) text_graph.add_edge(first_sent,second_sent,weight=weights) print('graph construction end.') return text_graph #论文中提到的共现相似度,也可以用其他的方法,如lexrank中的词袋+余弦距离 def sent_sim(sent_1,sent_2): sent_1_tokens = nlp.word_tokenize(sent_1) sent_2_tokens = nlp.word_tokenize(sent_2) #交集即为共现的词语 sim_set = set(sent_1_tokens) & set(sent_2_tokens) num_up = len(sim_set) num_down = math.log(len(sent_1_tokens)) + math.log(len(sent_2_tokens)) return num_up * 1. / num_down ''' def lDistance(firstString, secondString): "Function to find the Levenshtein distance between two words/sentences" if len(firstString) > len(secondString): firstString, secondString = secondString, firstString distances = range(len(firstString) + 1) for index2, char2 in enumerate(secondString): newDistances = [index2 + 1] for index1, char1 in enumerate(firstString): if char1 == char2: newDistances.append(distances[index1]) else: newDistances.append(1 + min((distances[index1], distances[index1+1], newDistances[-1]))) distances = newDistances return distances[-1] ''' if __name__ == "__main__": #get_abstract(filter_quesiton,filter_abstract,3) get_abstract(duc_question,duc_abstract,3)
187
29.7
105
13
1,624
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.open-never-closed_530dddcb1bbf8b97_755da08f", "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": 32, "line_end": 32, "column_start": 1, "column_end": 37, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmpr7mo7ysm/530dddcb1bbf8b97.py", "start": {"line": 32, "col": 1, "offset": 821}, "end": {"line": 32, "col": 37, "offset": 857}, "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_530dddcb1bbf8b97_12ae02de", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 33, "line_end": 33, "column_start": 19, "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/tmpr7mo7ysm/530dddcb1bbf8b97.py", "start": {"line": 33, "col": 19, "offset": 876}, "end": {"line": 33, "col": 43, "offset": 900}, "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_530dddcb1bbf8b97_592e075d", "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": 34, "line_end": 34, "column_start": 1, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmpr7mo7ysm/530dddcb1bbf8b97.py", "start": {"line": 34, "col": 1, "offset": 901}, "end": {"line": 34, "col": 31, "offset": 931}, "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_530dddcb1bbf8b97_b3849530", "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": 35, "line_end": 35, "column_start": 16, "column_end": 37, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/530dddcb1bbf8b97.py", "start": {"line": 35, "col": 16, "offset": 947}, "end": {"line": 35, "col": 37, "offset": 968}, "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_530dddcb1bbf8b97_1a9af520", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 60, "line_end": 60, "column_start": 14, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/530dddcb1bbf8b97.py", "start": {"line": 60, "col": 14, "offset": 2011}, "end": {"line": 60, "col": 32, "offset": 2029}, "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_530dddcb1bbf8b97_cb1204c4", "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": 73, "line_end": 73, "column_start": 5, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmpr7mo7ysm/530dddcb1bbf8b97.py", "start": {"line": 73, "col": 5, "offset": 2553}, "end": {"line": 73, "col": 33, "offset": 2581}, "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_530dddcb1bbf8b97_7c5253f6", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 74, "line_end": 74, "column_start": 5, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/530dddcb1bbf8b97.py", "start": {"line": 74, "col": 5, "offset": 2586}, "end": {"line": 74, "col": 45, "offset": 2626}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
7
true
[ "CWE-502", "CWE-502", "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security", "security", "security" ]
[ "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 33, 35, 74 ]
[ 33, 35, 74 ]
[ 19, 16, 5 ]
[ 43, 37, 45 ]
[ "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" ]
text_rank.py
/code/statistic/text_rank.py
lavizhao/insummer
MIT
2024-11-18T19:39:34.495282+00:00
1,545,312,654,000
409dcb0d962ca61f26a7861521d924a50fb1c9db
3
{ "blob_id": "409dcb0d962ca61f26a7861521d924a50fb1c9db", "branch_name": "refs/heads/master", "committer_date": 1545312654000, "content_id": "ee7de8a5669c74ed33643cafcd9a21d055e057ec", "detected_licenses": [ "MIT" ], "directory_id": "7825e042956cdb2bc6b7a1bd28e2a99894c23f21", "extension": "py", "filename": "__init__.py", "fork_events_count": 0, "gha_created_at": 1545414653000, "gha_event_created_at": 1545414654000, "gha_language": null, "gha_license_id": null, "github_id": 162742883, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5463, "license": "MIT", "license_type": "permissive", "path": "/zipfix/__init__.py", "provenance": "stack-edu-0054.json.gz:577691", "repo_name": "emilio/git-zipfix", "revision_date": 1545312654000, "revision_id": "a19b9a2993f48e6c4997ccbbb3617dc16c93a55b", "snapshot_id": "62e57691bae9a1c6925a473c284d291fb80109c0", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/emilio/git-zipfix/a19b9a2993f48e6c4997ccbbb3617dc16c93a55b/zipfix/__init__.py", "visit_date": "2020-04-12T20:39:19.166831" }
2.859375
stackv2
""" zipfix is a library for efficiently working with changes in git repositories. It holds an in-memory copy of the object database and supports efficient in-memory merges and rebases. """ from typing import Tuple, List, Optional from argparse import ArgumentParser from pathlib import Path import subprocess import tempfile import textwrap import sys # Re-export primitives from the odb module to expose them at the root. from .odb import MissingObject, Oid, Signature, GitObj, Commit, Mode, Entry, Tree, Blob def commit_range(base: Commit, tip: Commit) -> List[Commit]: """Oldest-first iterator over the given commit range, not including the commit |base|""" commits = [] while tip != base: commits.append(tip) tip = tip.parent() commits.reverse() return commits def run_editor(filename: str, text: bytes, comments: Optional[str] = None, allow_empty: bool = False) -> bytes: """Run the editor configured for git to edit the given text""" with tempfile.TemporaryDirectory() as tmpdir: path = Path(tmpdir) / filename with open(path, 'wb') as f: for line in text.splitlines(): f.write(line + b'\n') if comments: # If comments were provided, write them after the text. f.write(b'\n') for comment in textwrap.dedent(comments).splitlines(): f.write(b'# ' + comment.encode('utf-8') + b'\n') # Invoke the editor proc = subprocess.run([ "bash", "-c", f"exec $(git var GIT_EDITOR) '{path}'"]) if proc.returncode != 0: print("editor exited with a non-zero exit code", file=sys.stderr) sys.exit(1) # Read in all lines from the edited file. lines = [] with open(path, 'rb') as of: for line in of.readlines(): if comments and line.startswith(b'#'): continue lines.append(line) # Concatenate parsed lines, stripping trailing newlines. data = b''.join(lines).rstrip() + b'\n' if data == b'\n' and not allow_empty: print("empty file - aborting", file=sys.stderr) sys.exit(1) return data def parser() -> ArgumentParser: parser = ArgumentParser(description='''\ Rebase staged changes onto the given commit, and rewrite history to incorporate these changes.''') parser.add_argument('target', help='target commit to apply fixups to') parser.add_argument('--ref', default='HEAD', help='reference to update') parser.add_argument('--no-index', action='store_true', help='ignore the index while rewriting history') parser.add_argument('--reauthor', action='store_true', help='reset the author of the targeted commit') msg_group = parser.add_mutually_exclusive_group() msg_group.add_argument('--edit', '-e', action='store_true', help='edit commit message of targeted commit') msg_group.add_argument('--message', '-m', action='append', help='specify commit message on command line') return parser def main(argv): args = parser().parse_args(argv) final = head = Commit.get(args.ref) current = replaced = Commit.get(args.target) to_rebase = commit_range(current, head) # If --no-index was not supplied, apply staged changes to the target. if not args.no_index: print(f"Applying staged changes to '{args.target}'") final = Commit.from_index(b"git index") current = current.update(tree=final.rebase(current).tree()) # Update the commit message on the target commit if requested. if args.message: message = b'\n'.join(l.encode('utf-8') + b'\n' for l in args.message) current = current.update(message=message) # Prompt the user to edit the commit message if requested. if args.edit: message = run_editor('COMMIT_EDITMSG', current.message, comments="""\ Please enter the commit message for your changes. Lines starting with '#' will be ignored, and an empty message aborts the commit. """) current = current.update(message=message) # Rewrite the author to match the current user if requested. if args.reauthor: current = current.update(author=Signature.default_author()) if current != replaced: # Rebase commits atop the commit range. for idx, commit in enumerate(to_rebase): print(f"Reparenting commit {idx + 1}/{len(to_rebase)}: {commit.oid}") current = commit.rebase(current) # Update the HEAD commit to point to the new value. print(f"Updating {args.ref} ({head.oid} => {current.oid})") current.update_ref(args.ref, "git-zipfix rewrite", head.oid) # We expect our tree to match the tree we started with (including index # changes). If it does not, print out a warning. if current.tree() != final.tree(): print("(warning) unexpected final tree\n" f"(note) expected: {final.tree().oid}\n" f"(note) actual: {current.tree().oid}\n" "(note) working directory & index have not been updated.\n" "(note) use `git status` to see what has changed.", file=sys.stderr) sys.exit(1)
136
39.17
87
20
1,189
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_3f22d7ad20e7df27_8b78f330", "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": 46, "line_end": 47, "column_start": 16, "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/tmpr7mo7ysm/3f22d7ad20e7df27.py", "start": {"line": 46, "col": 16, "offset": 1524}, "end": {"line": 47, "col": 67, "offset": 1607}, "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"}}}]
1
true
[ "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 46 ]
[ 47 ]
[ 16 ]
[ 67 ]
[ "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
/zipfix/__init__.py
emilio/git-zipfix
MIT
2024-11-18T19:39:35.147272+00:00
1,688,657,923,000
d114bc7c0cc722bb3ef85eb36f86187a99f62b13
3
{ "blob_id": "d114bc7c0cc722bb3ef85eb36f86187a99f62b13", "branch_name": "refs/heads/main", "committer_date": 1688657923000, "content_id": "b144a340f0fa1c3578c8bb766c93794ca50f733b", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "99ff5c83dd71a1857eba33581c154b188fc39871", "extension": "py", "filename": "plopper.py", "fork_events_count": 21, "gha_created_at": 1547577100000, "gha_event_created_at": 1688657907000, "gha_language": "C", "gha_license_id": "BSD-2-Clause", "github_id": 165902750, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1922, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/ytopt/benchmark/mmm-block/plopper/plopper.py", "provenance": "stack-edu-0054.json.gz:577700", "repo_name": "ytopt-team/ytopt", "revision_date": 1688657923000, "revision_id": "c7740d9b9ade6599d4fed245c6242cb52f843e0d", "snapshot_id": "cc15f3b46d1a8fd26e54925e98d4bf26e6a54fa8", "src_encoding": "UTF-8", "star_events_count": 34, "url": "https://raw.githubusercontent.com/ytopt-team/ytopt/c7740d9b9ade6599d4fed245c6242cb52f843e0d/ytopt/benchmark/mmm-block/plopper/plopper.py", "visit_date": "2023-07-20T15:27:26.420794" }
2.6875
stackv2
import os, sys, subprocess, random, uuid class Plopper: def __init__(self,sourcefile,outputdir): # Initializing global variables self.sourcefile = sourcefile self.outputdir = outputdir+"/tmp_files" if not os.path.exists(self.outputdir): os.makedirs(self.outputdir) #Creating a dictionary using parameter label and value def createDict(self, x, params): dictVal = {} for p, v in zip(params, x): dictVal[p] = v return(dictVal) # Function to find the execution time of the interim file, and return the execution time as cost to the search module def findRuntime(self, x, params): interimfile = "" exetime = 1 # Generate intermediate file dictVal = self.createDict(x, params) #compile and find the execution time tmpbinary = self.outputdir + '/tmp_'+str(uuid.uuid4())+'.bin' kernel_idx = self.sourcefile.rfind('/') kernel_dir = self.sourcefile[:kernel_idx] gcc_cmd = 'g++ ' + kernel_dir +'/mmm_block.cpp ' gcc_cmd += ' -D{0}={1}'.format('BLOCK_SIZE', dictVal['BLOCK_SIZE']) gcc_cmd += ' -o ' + tmpbinary run_cmd = kernel_dir + "/exe.pl " + tmpbinary #Find the compilation status using subprocess compilation_status = subprocess.run(gcc_cmd, shell=True, stderr=subprocess.PIPE) #Find the execution time only when the compilation return code is zero, else return infinity if compilation_status.returncode == 0 : execution_status = subprocess.run(run_cmd, shell=True, stdout=subprocess.PIPE) exetime = float(execution_status.stdout.decode('utf-8')) if exetime == 0: exetime = 1 else: print(compilation_status.stderr) print("compile failed") return exetime #return execution time as cost
50
37.44
121
15
430
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_f9c8af3aa972fc69_da267bcd", "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": 38, "line_end": 38, "column_start": 30, "column_end": 89, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/f9c8af3aa972fc69.py", "start": {"line": 38, "col": 30, "offset": 1345}, "end": {"line": 38, "col": 89, "offset": 1404}, "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_f9c8af3aa972fc69_1ad5ef02", "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": 38, "line_end": 38, "column_start": 60, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpr7mo7ysm/f9c8af3aa972fc69.py", "start": {"line": 38, "col": 60, "offset": 1375}, "end": {"line": 38, "col": 64, "offset": 1379}, "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_f9c8af3aa972fc69_d89dba05", "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": 42, "line_end": 42, "column_start": 32, "column_end": 91, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/f9c8af3aa972fc69.py", "start": {"line": 42, "col": 32, "offset": 1586}, "end": {"line": 42, "col": 91, "offset": 1645}, "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_f9c8af3aa972fc69_f6d30bd6", "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": 42, "line_end": 42, "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/tmpr7mo7ysm/f9c8af3aa972fc69.py", "start": {"line": 42, "col": 62, "offset": 1616}, "end": {"line": 42, "col": 66, "offset": 1620}, "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"}}}]
4
true
[ "CWE-78", "CWE-78", "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.subprocess-shell-true", "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.subprocess-shell-true" ]
[ "security", "security", "security", "security" ]
[ "LOW", "MEDIUM", "LOW", "MEDIUM" ]
[ "HIGH", "HIGH", "HIGH", "HIGH" ]
[ 38, 38, 42, 42 ]
[ 38, 38, 42, 42 ]
[ 30, 60, 32, 62 ]
[ 89, 64, 91, 66 ]
[ "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 ]
[ "LOW", "HIGH", "LOW", "HIGH" ]
[ "HIGH", "LOW", "HIGH", "LOW" ]
plopper.py
/ytopt/benchmark/mmm-block/plopper/plopper.py
ytopt-team/ytopt
BSD-2-Clause
2024-11-18T19:39:36.977527+00:00
1,368,396,177,000
4d3c05ae00dc998920f9c0845717fa0b60c7ed92
2
{ "blob_id": "4d3c05ae00dc998920f9c0845717fa0b60c7ed92", "branch_name": "refs/heads/master", "committer_date": 1368396177000, "content_id": "4049184ccff51e5fca5f97118ddcd82f9de7d04f", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "ca681c9dcc3fd862abada520c678b6d2eeb497ef", "extension": "py", "filename": "controller.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": 4310, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/king/controller.py", "provenance": "stack-edu-0054.json.gz:577705", "repo_name": "nebgnahz/CS268NetworkMeasurement", "revision_date": 1368396177000, "revision_id": "67347e2ebba6dc03a965d16f83483282cf4ff453", "snapshot_id": "f77d46d3f69dc06c02d26e21ff6f217fc23fd328", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nebgnahz/CS268NetworkMeasurement/67347e2ebba6dc03a965d16f83483282cf4ff453/king/controller.py", "visit_date": "2021-01-25T03:49:00.056629" }
2.40625
stackv2
import cPickle, logging, multiprocessing, os, Queue, redis, string, threading from apscheduler.scheduler import Scheduler from datetime import datetime, timedelta from PlanetLabNode import PlanetLabNode from utilities import outputException, distance import argparse parser = argparse.ArgumentParser(description='Tking Controller') parser.add_argument('--max', default=None, type=int, help='Set a Maximum Distance between targets') parser.add_argument('--min', default=0, type=int, help='Set a Minimum Distance between targets') args = parser.parse_args() round_length = 20 time_limit = 110.0 num_processes = 90 num_threads = 30 all_dns = redis.Redis(connection_pool=redis.ConnectionPool(host='localhost', port=6379, db=0)) open_resolvers = redis.Redis(connection_pool=redis.ConnectionPool(host='localhost', port=6379, db=1)) geoip = redis.Redis(connection_pool=redis.ConnectionPool(host='localhost', port=6379, db=2)) pl_hosts = [line.split(' ')[0:4] for line in map(string.strip,open('pl-host-list-geo').readlines())] pl_nodes = map(lambda args: PlanetLabNode(*args), pl_hosts) def select_random_points(): target1 = open_resolvers.randomkey() target2 = open_resolvers.randomkey() while not geoip.exists(target1): target1 = open_resolvers.randomkey() while not geoip.exists(target2): target2 = open_resolvers.randomkey() ip1, coord1 = list(all_dns.smembers(target1))[0], eval(list(geoip.smembers(target1))[0])[1:] ip2, coord2 = list(all_dns.smembers(target2))[0], eval(list(geoip.smembers(target2))[0])[1:] return (target1, ip1, coord1), (target2, ip2, coord2) def closestNodes(target): name1, ip1, coord1 = target # Get closest 10 PL Nodes distances = map(lambda node: (distance(coord1, (node.lat, node.lon)), node), pl_nodes) distances.sort() distances = map(lambda x: x[1], distances) return distances[:10] def query_latency(target1, target2, node): name1, ip1, coord1 = target1 name2, ip2, coord2 = target2 return cPickle.loads(node.get_latency(name1, ip1, name2, ip2)) def perThread(queue): from DataPoint import DataPoint, Session session = Session() while True: try: target1, target2, node = queue.get() #print target1, target2, node result = query_latency(target1, target2, node) success = False if result: end_time, start_time, ping_times, address = result if end_time and start_time and ping_times and address: success = True else: end_time = start_time = ping_times = address = None point = DataPoint(target1[0], target2[0], target1, target2, start_time, end_time, ping_times, address, node.host, success) while True: try: session.add(point) session.commit() break except Exception, e: print e session.close() session = Session() except Exception, e: outputException(e) # TODO: Store None Responses As Well def perProcess(): thread_queue = Queue.Queue(num_threads) threads = [] for i in range(num_threads): t = threading.Thread(target=perThread, args=(thread_queue,)) t.daemon = True t.start() threads.append(t) for i in range(round_length): while True: t1, t2 = select_random_points() dist = distance(t1[2], t2[2]) if args.max and dist > args.max: continue elif dist <= args.min: continue else: break closest_nodes1 = closestNodes(t1) closest_nodes2 = closestNodes(t2) for node in closest_nodes1: thread_queue.put((t1, t2, node)) for node in closest_nodes2: thread_queue.put((t2, t1, node)) def main(): print 'Start:', datetime.now() processes = [] for i in range(num_processes): p = multiprocessing.Process(target=perProcess) p.daemon = True p.start() processes.append(p) for p in processes: p.join(time_limit/num_processes) print '\nEnd:', datetime.now() main()
121
34.62
134
17
1,024
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_deef89c98b9d1385_3e551ae0", "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": 63, "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/tmpr7mo7ysm/deef89c98b9d1385.py", "start": {"line": 23, "col": 63, "offset": 986}, "end": {"line": 23, "col": 87, "offset": 1010}, "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.maintainability.return-not-in-function_deef89c98b9d1385_c412bbbf", "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": 24, "line_end": 24, "column_start": 29, "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/tmpr7mo7ysm/deef89c98b9d1385.py", "start": {"line": 24, "col": 29, "offset": 1053}, "end": {"line": 24, "col": 49, "offset": 1073}, "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"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_deef89c98b9d1385_9401e01b", "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": 55, "column_end": 93, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpr7mo7ysm/deef89c98b9d1385.py", "start": {"line": 34, "col": 55, "offset": 1415}, "end": {"line": 34, "col": 93, "offset": 1453}, "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_deef89c98b9d1385_e6221f24", "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": 35, "line_end": 35, "column_start": 55, "column_end": 93, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpr7mo7ysm/deef89c98b9d1385.py", "start": {"line": 35, "col": 55, "offset": 1512}, "end": {"line": 35, "col": 93, "offset": 1550}, "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.deserialization.avoid-cPickle_deef89c98b9d1385_40c124f3", "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": 50, "line_end": 50, "column_start": 12, "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-cPickle", "path": "/tmp/tmpr7mo7ysm/deef89c98b9d1385.py", "start": {"line": 50, "col": 12, "offset": 2009}, "end": {"line": 50, "col": 67, "offset": 2064}, "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"}}}]
5
true
[ "CWE-95", "CWE-95", "CWE-502" ]
[ "rules.python.lang.security.audit.eval-detected", "rules.python.lang.security.audit.eval-detected", "rules.python.lang.security.deserialization.avoid-cPickle" ]
[ "security", "security", "security" ]
[ "LOW", "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM", "MEDIUM" ]
[ 34, 35, 50 ]
[ 34, 35, 50 ]
[ 55, 55, 12 ]
[ 93, 93, 67 ]
[ "A03:2021 - Injection", "A03:2021 - Injection", "A08:2017 - Insecure Deserialization" ]
[ "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 ]
[ "LOW", "LOW", "LOW" ]
[ "HIGH", "HIGH", "MEDIUM" ]
controller.py
/king/controller.py
nebgnahz/CS268NetworkMeasurement
BSD-2-Clause
2024-11-18T19:39:46.964162+00:00
1,497,492,721,000
0f9b6bfe8a27e5dcf9e60f933c59d1b2c98e8231
2
{ "blob_id": "0f9b6bfe8a27e5dcf9e60f933c59d1b2c98e8231", "branch_name": "refs/heads/master", "committer_date": 1497492882000, "content_id": "f598f8db446802ff33b01b4bab0160c943831713", "detected_licenses": [ "MIT" ], "directory_id": "df7c9aa290f4888dedca9751d032008fc413cf9e", "extension": "py", "filename": "command.py", "fork_events_count": 0, "gha_created_at": 1493180639000, "gha_event_created_at": 1568890803000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 89437529, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1175, "license": "MIT", "license_type": "permissive", "path": "/plugin/command.py", "provenance": "stack-edu-0054.json.gz:577744", "repo_name": "andykingking/sublime-format", "revision_date": 1497492721000, "revision_id": "d1d9e2192729ffdecf9f09e54bdfc2c13890542f", "snapshot_id": "8011a6783a04d100699b2c791c0e12f3ddb82b61", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/andykingking/sublime-format/d1d9e2192729ffdecf9f09e54bdfc2c13890542f/plugin/command.py", "visit_date": "2021-01-20T02:41:22.924078" }
2.421875
stackv2
import subprocess import os from .settings import Settings class ShellCommand: def __init__(self, args): self.__args = args self.__startup_info = None self.__shell = False if os.name == 'nt': self.__startup_info = subprocess.STARTUPINFO() self.__startup_info.dwFlags |= subprocess.STARTF_USESHOWWINDOW self.__startup_info.wShowWindow = subprocess.SW_HIDE self.__shell = True @property def args(self): return self.__args @staticmethod def env(): path = os.pathsep.join(Settings.paths()) env = os.environ.copy() env['PATH'] = path + os.pathsep + env['PATH'] return env def run(self, input): process = subprocess.Popen( self.args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=self.__startup_info, shell=self.__shell, env=self.env(), universal_newlines=True) stdout, stderr = process.communicate(input=input) ok = process.returncode == 0 return ok, stdout, stderr
40
28.38
74
13
248
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_21463b8d4b886ba1_68632b2c", "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 'STARTUPINFO' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 12, "line_end": 12, "column_start": 35, "column_end": 59, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/21463b8d4b886ba1.py", "start": {"line": 12, "col": 35, "offset": 264}, "end": {"line": 12, "col": 59, "offset": 288}, "extra": {"message": "Detected subprocess function 'STARTUPINFO' 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_21463b8d4b886ba1_3645cd6f", "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": 29, "line_end": 37, "column_start": 19, "column_end": 37, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/21463b8d4b886ba1.py", "start": {"line": 29, "col": 19, "offset": 756}, "end": {"line": 37, "col": 37, "offset": 1045}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
2
true
[ "CWE-78", "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "rules.python.lang.security.audit.dangerous-subprocess-use-audit" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "HIGH", "HIGH" ]
[ 12, 29 ]
[ 12, 37 ]
[ 35, 19 ]
[ 59, 37 ]
[ "A01:2017 - Injection", "A01:2017 - Injection" ]
[ "Detected subprocess function 'STARTUPINFO' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "Detected subprocess...
[ 7.5, 7.5 ]
[ "LOW", "LOW" ]
[ "HIGH", "HIGH" ]
command.py
/plugin/command.py
andykingking/sublime-format
MIT
2024-11-18T19:39:52.923725+00:00
1,692,828,071,000
e4cc582229b6fa327be9064fd628450ce99bbd21
3
{ "blob_id": "e4cc582229b6fa327be9064fd628450ce99bbd21", "branch_name": "refs/heads/main", "committer_date": 1692828071000, "content_id": "ad938072d59e0b91a6677e1785eb7769bb210874", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "a3d6556180e74af7b555f8d47d3fea55b94bcbda", "extension": "py", "filename": "symlink.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": 3066, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/build/symlink.py", "provenance": "stack-edu-0054.json.gz:577802", "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/symlink.py", "visit_date": "2023-08-24T00:35:12.585945" }
2.625
stackv2
#!/usr/bin/env python3 # Copyright 2013 The Chromium Authors # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. description = """ Make a symlink and optionally touch a file (to handle dependencies). """ usage = "%prog [options] source[ source ...] linkname" epilog = """\ A symlink to source is created at linkname. If multiple sources are specified, then linkname is assumed to be a directory, and will contain all the links to the sources (basenames identical to their source). On Windows, this will use hard links (mklink /H) to avoid requiring elevation. This means that if the original is deleted and replaced, the link will still have the old contents. """ import errno import optparse import os.path import shutil import subprocess import sys def Main(argv): parser = optparse.OptionParser(usage=usage, description=description, epilog=epilog) parser.add_option('-f', '--force', action='store_true') parser.add_option('--touch') options, args = parser.parse_args(argv[1:]) if len(args) < 2: parser.error('at least two arguments required.') target = args[-1] sources = args[:-1] for s in sources: t = os.path.join(target, os.path.basename(s)) if len(sources) == 1 and not os.path.isdir(target): t = target t = os.path.expanduser(t) if os.path.realpath(t) == os.path.realpath(s): continue try: # N.B. Python 2.x does not have os.symlink for Windows. # Python 3 has os.symlink for Windows, but requires either the admin- # granted privilege SeCreateSymbolicLinkPrivilege or, as of Windows 10 # 1703, that Developer Mode be enabled. Hard links and junctions do not # require any extra privileges to create. if os.name == 'nt': # mklink does not tolerate /-delimited path names. t = t.replace('/', '\\') s = s.replace('/', '\\') # N.B. This tool only handles file hardlinks, not directory junctions. subprocess.check_output(['cmd.exe', '/c', 'mklink', '/H', t, s], stderr=subprocess.STDOUT) else: os.symlink(s, t) except OSError as e: if e.errno == errno.EEXIST and options.force: if os.path.isdir(t): shutil.rmtree(t, ignore_errors=True) else: os.remove(t) os.symlink(s, t) else: raise except subprocess.CalledProcessError as e: # Since subprocess.check_output does not return an easily checked error # number, in the 'force' case always assume it is 'file already exists' # and retry. if options.force: if os.path.isdir(t): shutil.rmtree(t, ignore_errors=True) else: os.remove(t) subprocess.check_output(e.cmd, stderr=subprocess.STDOUT) else: raise if options.touch: os.makedirs(os.path.dirname(options.touch), exist_ok=True) with open(options.touch, 'w'): pass if __name__ == '__main__': sys.exit(Main(sys.argv))
92
32.33
79
17
731
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_6870e2749a8a867a_a9d3dc83", "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": 80, "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/tmpr7mo7ysm/6870e2749a8a867a.py", "start": {"line": 80, "col": 9, "offset": 2796}, "end": {"line": 80, "col": 65, "offset": 2852}, "extra": {"message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_6870e2749a8a867a_e2029379", "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": 87, "line_end": 87, "column_start": 10, "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/tmpr7mo7ysm/6870e2749a8a867a.py", "start": {"line": 87, "col": 10, "offset": 2973}, "end": {"line": 87, "col": 34, "offset": 2997}, "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-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 80 ]
[ 80 ]
[ 9 ]
[ 65 ]
[ "A01:2017 - Injection" ]
[ "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'." ]
[ 7.5 ]
[ "LOW" ]
[ "HIGH" ]
symlink.py
/build/symlink.py
chromium/chromium
BSD-3-Clause
2024-11-18T19:39:56.434917+00:00
1,576,063,028,000
5171dfc819d489ae015f5f6757b59a08285675ca
3
{ "blob_id": "5171dfc819d489ae015f5f6757b59a08285675ca", "branch_name": "refs/heads/master", "committer_date": 1576063028000, "content_id": "f2c6e908662cf2ac65ad2add410036042ea5acf5", "detected_licenses": [ "MIT" ], "directory_id": "5805b5e645e905992d0f8c199fed39d09bfe5acb", "extension": "py", "filename": "message_stats.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 226175860, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2754, "license": "MIT", "license_type": "permissive", "path": "/message_stats.py", "provenance": "stack-edu-0054.json.gz:577842", "repo_name": "mp4096/git-achievements", "revision_date": 1576063028000, "revision_id": "4b943b18dae2ee41c49c4d024e7fc82e16745668", "snapshot_id": "103498e1b27433abd7b02a6680df982bf783747a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mp4096/git-achievements/4b943b18dae2ee41c49c4d024e7fc82e16745668/message_stats.py", "visit_date": "2020-09-26T05:25:44.059755" }
2.78125
stackv2
#!/usr/bin/env python3 import argparse import statistics import os import sys import subprocess from typing import Optional, Iterator, Iterable, Tuple, List def get_commits_list( repo_path: str, author: Optional[str] = None, after: Optional[str] = None, rev_list_args: Optional[str] = None, ) -> Iterator[str]: args = [] if author: args.append("--author={:s}".format(author)) if after: args.append("--after={:s}".format(after)) if rev_list_args: args.extend(rev_list_args.split()) result = subprocess.run( ["git", "rev-list"] + args + ["HEAD"], cwd=os.path.abspath(repo_path), stdout=subprocess.PIPE, ) return filter(None, result.stdout.decode("utf-8").split("\n")) def get_commit_message(repo_path: str, revision: str) -> str: result = subprocess.run( ["git", "show", "--no-patch", "--format=%B", revision], cwd=os.path.abspath(repo_path), stdout=subprocess.PIPE, ) return result.stdout.decode("utf-8").strip() def get_length_stats( repo_paths: Iterable[str], author: Optional[str] = None, after: Optional[str] = None, rev_list_args: Optional[str] = None, ) -> Tuple[int, int, int, float, float]: messages = ( get_commit_message(repo, revision) for repo in repo_paths for revision in get_commits_list(repo, author, after, rev_list_args) ) lengths = [len(m) for m in messages] return ( len(lengths), min(lengths), max(lengths), statistics.median(lengths), statistics.mean(lengths), ) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Get git commit message stats.") parser.add_argument( "--author", type=str, default="", required=False, help="author email" ) parser.add_argument( "--after", type=str, default="", required=False, help="after timestamp" ) parser.add_argument( "--rev-list-args", type=str, default="", required=False, help="any further arguments for git rev-list", ) parser.add_argument("repo_paths", type=str, nargs="+", help="path to the repos") args = parser.parse_args(sys.argv[1:]) total_num, min_length, max_length, median, mean = get_length_stats( args.repo_paths, args.author, args.after, args.rev_list_args ) print("Commit message stats:") print(" total number of commits: {:4d}".format(total_num)) print(" min length: {:4d}".format(min_length)) print(" median length: {:7.2f}".format(median)) print(" mean length: {:7.2f}".format(mean)) print(" max length: {:4d}".format(max_length))
88
30.3
84
12
652
python
[{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_e8329274ddc7ab79_d6119373", "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": 24, "line_end": 28, "column_start": 14, "column_end": 6, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpr7mo7ysm/e8329274ddc7ab79.py", "start": {"line": 24, "col": 14, "offset": 553}, "end": {"line": 28, "col": 6, "offset": 693}, "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"}}}]
1
true
[ "CWE-78" ]
[ "rules.python.lang.security.audit.dangerous-subprocess-use-audit" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 24 ]
[ 28 ]
[ 14 ]
[ 6 ]
[ "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" ]
message_stats.py
/message_stats.py
mp4096/git-achievements
MIT
2024-11-18T19:39:56.571115+00:00
1,398,650,275,000
a0ac897955bc88f75ce1145877d9d70d72619a01
3
{ "blob_id": "a0ac897955bc88f75ce1145877d9d70d72619a01", "branch_name": "refs/heads/master", "committer_date": 1398650275000, "content_id": "856c50b4308ac4f40587485e335f7ebc4d12e85f", "detected_licenses": [ "Apache-2.0" ], "directory_id": "457df1e4ea80edb14ab0dcc894bcc08975d80f41", "extension": "py", "filename": "hierarchy_config.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": 1067, "license": "Apache-2.0", "license_type": "permissive", "path": "/user-interface/src/ConfigUtil/hierarchy_config.py", "provenance": "stack-edu-0054.json.gz:577844", "repo_name": "linmichaelj/avalanche", "revision_date": 1398650275000, "revision_id": "727776b5fdfcad9345dd23be90fdf5e1fb2876c8", "snapshot_id": "94f6987d2e8fcd64de86f97960d82a6092573949", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/linmichaelj/avalanche/727776b5fdfcad9345dd23be90fdf5e1fb2876c8/user-interface/src/ConfigUtil/hierarchy_config.py", "visit_date": "2020-06-12T11:25:04.810559" }
2.515625
stackv2
from ConfigUtil import config_util __author__ = 'michaellin' import xml.etree.ElementTree as ET class HierarchyConfig: def __init__(self, file_name, repeated_tag): self.config_map = {} self.file_name = file_name self.repeated_tag = repeated_tag def write_to_file(self): if not self.is_valid(): print 'Validation Exception Occurred' return f = open(self.file_name, 'w') f.write(self.get_xml()) f.close() def load_from_file(self): f = open(self.file_name, 'r') root = ET.fromstring(f.read()) self.config_map = config_util.xml_to_hierarchy(root, self.repeated_tag) if not self.is_valid(): print 'Validation Exception Ocurred' self.alias_list = {} return f.close() def get_xml(self): config_elem = ET.Element('config') config_util.hierarchy_to_xml(config_elem, self.config_map) return config_util.format_url(config_elem) #Abstract Methods is_valid, add_config
40
25.68
79
12
234
python
[{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_d246e5e03149b16a_d36b8c5b", "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": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpr7mo7ysm/d246e5e03149b16a.py", "start": {"line": 5, "col": 1, "offset": 63}, "end": {"line": 5, "col": 35, "offset": 97}, "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_d246e5e03149b16a_10104422", "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": 13, "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/tmpr7mo7ysm/d246e5e03149b16a.py", "start": {"line": 19, "col": 13, "offset": 421}, "end": {"line": 19, "col": 38, "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_d246e5e03149b16a_555012be", "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": 13, "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/tmpr7mo7ysm/d246e5e03149b16a.py", "start": {"line": 24, "col": 13, "offset": 540}, "end": {"line": 24, "col": 38, "offset": 565}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
3
true
[ "CWE-611" ]
[ "rules.python.lang.security.use-defused-xml" ]
[ "security" ]
[ "LOW" ]
[ "HIGH" ]
[ 5 ]
[ 5 ]
[ 1 ]
[ 35 ]
[ "A04:2017 - XML External Entities (XXE)" ]
[ "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service." ]
[ 7.5 ]
[ "LOW" ]
[ "MEDIUM" ]
hierarchy_config.py
/user-interface/src/ConfigUtil/hierarchy_config.py
linmichaelj/avalanche
Apache-2.0
2024-11-18T20:18:02.972749+00:00
1,589,969,901,000
f34b5671ab902e81015e48b3020096c06719683f
3
{ "blob_id": "f34b5671ab902e81015e48b3020096c06719683f", "branch_name": "refs/heads/master", "committer_date": 1589969901000, "content_id": "4bd355b7f0e87648a848574ac226072f1800e164", "detected_licenses": [ "Apache-2.0" ], "directory_id": "7775fb7ba338e8707f559e0372a6d11a78f8c69f", "extension": "py", "filename": "data_helper.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": 9574, "license": "Apache-2.0", "license_type": "permissive", "path": "/data_loader/data_helper.py", "provenance": "stack-edu-0054.json.gz:577948", "repo_name": "liuyunwu/ProvablyPowerfulGraphNetworks", "revision_date": 1589969901000, "revision_id": "ba13fbdef7f3224728f5947f5bec2cec6ef942b0", "snapshot_id": "18e4538d8705387b8fe16dc0b537e9be358ee06b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/liuyunwu/ProvablyPowerfulGraphNetworks/ba13fbdef7f3224728f5947f5bec2cec6ef942b0/data_loader/data_helper.py", "visit_date": "2022-07-31T06:14:35.202913" }
2.78125
stackv2
import numpy as np import os import pickle NUM_LABELS = {'ENZYMES':3, 'COLLAB':0, 'IMDBBINARY':0, 'IMDBMULTI':0, 'MUTAG':7, 'NCI1':37, 'NCI109':38, 'PROTEINS':3, 'PTC':22, 'DD':89} BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def load_dataset(ds_name): """ construct graphs and labels from dataset text in data folder :param ds_name: name of data set you want to load :return: two numpy arrays of shape (num_of_graphs). the graphs array contains in each entry a ndarray represent adjacency matrix of a graph of shape (num_vertex, num_vertex, num_vertex_labels) the labels array in index i represent the class of graphs[i] """ directory = BASE_DIR + "/data/benchmark_graphs/{0}/{0}.txt".format(ds_name) graphs = [] labels = [] with open(directory, "r") as data: num_graphs = int(data.readline().rstrip().split(" ")[0]) for i in range(num_graphs): graph_meta = data.readline().rstrip().split(" ") num_vertex = int(graph_meta[0]) curr_graph = np.zeros(shape=(num_vertex, num_vertex, NUM_LABELS[ds_name]+1), dtype=np.float32) labels.append(int(graph_meta[1])) for j in range(num_vertex): vertex = data.readline().rstrip().split(" ") if NUM_LABELS[ds_name] != 0: curr_graph[j, j, int(vertex[0])+1]= 1. for k in range(2,len(vertex)): curr_graph[j, int(vertex[k]), 0] = 1. curr_graph = noramlize_graph(curr_graph) graphs.append(curr_graph) graphs = np.array(graphs) for i in range(graphs.shape[0]): graphs[i] = np.transpose(graphs[i], [2,0,1]) return graphs, np.array(labels) def load_qm9(target_param): """ Constructs the graphs and labels of QM9 data set, already split to train, val and test sets :return: 6 numpy arrays: train_graphs: N_train, train_labels: N_train x 12, (or Nx1 is target_param is not False) val_graphs: N_val, val_labels: N_train x 12, (or Nx1 is target_param is not False) test_graphs: N_test, test_labels: N_test x 12, (or Nx1 is target_param is not False) each graph of shape: 19 x Nodes x Nodes (CHW representation) """ train_graphs, train_labels = load_qm9_aux('train', target_param) val_graphs, val_labels = load_qm9_aux('val', target_param) test_graphs, test_labels = load_qm9_aux('test', target_param) return train_graphs, train_labels, val_graphs, val_labels, test_graphs, test_labels def load_qm9_aux(which_set, target_param): """ Read and construct the graphs and labels of QM9 data set, already split to train, val and test sets :param which_set: 'test', 'train' or 'val' :param target_param: if not false, return the labels for this specific param only :return: graphs: (N,) labels: N x 12, (or Nx1 is target_param is not False) each graph of shape: 19 x Nodes x Nodes (CHW representation) """ base_path = BASE_DIR + "/data/QM9/QM9_{}.p".format(which_set) graphs, labels = [], [] with open(base_path, 'rb') as f: data = pickle.load(f) for instance in data: labels.append(instance['y']) nodes_num = instance['usable_features']['x'].shape[0] graph = np.empty((nodes_num, nodes_num, 19)) for i in range(13): # 13 features per node - for each, create a diag matrix of it as a feature graph[:, :, i] = np.diag(instance['usable_features']['x'][:, i]) graph[:, :, 13] = instance['usable_features']['distance_mat'] graph[:, :, 14] = instance['usable_features']['affinity'] graph[:, :, 15:] = instance['usable_features']['edge_features'] # shape n x n x 4 graphs.append(graph) graphs = np.array(graphs) for i in range(graphs.shape[0]): graphs[i] = np.transpose(graphs[i], [2, 0, 1]) labels = np.array(labels).squeeze() # shape N x 12 if target_param is not False: # regression over a specific target, not all 12 elements labels = labels[:, target_param].reshape(-1, 1) # shape N x 1 return graphs, labels def get_train_val_indexes(num_val, ds_name): """ reads the indexes of a specific split to train and validation sets from data folder :param num_val: number of the split :param ds_name: name of data set :return: indexes of the train and test graphs """ directory = BASE_DIR + "/data/benchmark_graphs/{0}/10fold_idx".format(ds_name) train_file = "train_idx-{0}.txt".format(num_val) train_idx=[] with open(os.path.join(directory, train_file), 'r') as file: for line in file: train_idx.append(int(line.rstrip())) test_file = "test_idx-{0}.txt".format(num_val) test_idx = [] with open(os.path.join(directory, test_file), 'r') as file: for line in file: test_idx.append(int(line.rstrip())) return train_idx, test_idx def get_parameter_split(ds_name): """ reads the indexes of a specific split to train and validation sets from data folder :param ds_name: name of data set :return: indexes of the train and test graphs """ directory = BASE_DIR + "/data/benchmark_graphs/{0}/".format(ds_name) train_file = "tests_train_split.txt" train_idx=[] with open(os.path.join(directory, train_file), 'r') as file: for line in file: train_idx.append(int(line.rstrip())) test_file = "tests_val_split.txt" test_idx = [] with open(os.path.join(directory, test_file), 'r') as file: for line in file: test_idx.append(int(line.rstrip())) return train_idx, test_idx def group_same_size(graphs, labels): """ group graphs of same size to same array :param graphs: numpy array of shape (num_of_graphs) of numpy arrays of graphs adjacency matrix :param labels: numpy array of labels :return: two numpy arrays. graphs arrays in the shape (num of different size graphs) where each entry is a numpy array in the shape (number of graphs with this size, num vertex, num. vertex, num vertex labels) the second arrayy is labels with correspons shape """ sizes = list(map(lambda t: t.shape[1], graphs)) indexes = np.argsort(sizes) graphs = graphs[indexes] labels = labels[indexes] r_graphs = [] r_labels = [] one_size = [] start = 0 size = graphs[0].shape[1] for i in range(len(graphs)): if graphs[i].shape[1] == size: one_size.append(np.expand_dims(graphs[i], axis=0)) else: r_graphs.append(np.concatenate(one_size, axis=0)) r_labels.append(np.array(labels[start:i])) start = i one_size = [] size = graphs[i].shape[1] one_size.append(np.expand_dims(graphs[i], axis=0)) r_graphs.append(np.concatenate(one_size, axis=0)) r_labels.append(np.array(labels[start:])) return r_graphs, r_labels # helper method to shuffle each same size graphs array def shuffle_same_size(graphs, labels): r_graphs, r_labels = [], [] for i in range(len(labels)): curr_graph, curr_labels = shuffle(graphs[i], labels[i]) r_graphs.append(curr_graph) r_labels.append(curr_labels) return r_graphs, r_labels def split_to_batches(graphs, labels, size): """ split the same size graphs array to batches of specified size last batch is in size num_of_graphs_this_size % size :param graphs: array of arrays of same size graphs :param labels: the corresponding labels of the graphs :param size: batch size :return: two arrays. graphs array of arrays in size (batch, num vertex, num vertex. num vertex labels) corresponds labels """ r_graphs = [] r_labels = [] for k in range(len(graphs)): r_graphs = r_graphs + np.split(graphs[k], [j for j in range(size, graphs[k].shape[0], size)]) r_labels = r_labels + np.split(labels[k], [j for j in range(size, labels[k].shape[0], size)]) # Avoid bug for batch_size=1, where instead of creating numpy array of objects, we had numpy array of floats with # different sizes - could not reshape ret1, ret2 = np.empty(len(r_graphs), dtype=object), np.empty(len(r_labels), dtype=object) ret1[:] = r_graphs ret2[:] = r_labels return ret1, ret2 # helper method to shuffle the same way graphs and labels arrays def shuffle(graphs, labels): shf = np.arange(labels.shape[0], dtype=np.int32) np.random.shuffle(shf) return np.array(graphs)[shf], labels[shf] def noramlize_graph(curr_graph): split = np.split(curr_graph, [1], axis=2) adj = np.squeeze(split[0], axis=2) deg = np.sqrt(np.sum(adj, 0)) deg = np.divide(1., deg, out=np.zeros_like(deg), where=deg!=0) normal = np.diag(deg) norm_adj = np.expand_dims(np.matmul(np.matmul(normal, adj), normal), axis=2) ones = np.ones(shape=(curr_graph.shape[0], curr_graph.shape[1], curr_graph.shape[2]), dtype=np.float32) spred_adj = np.multiply(ones, norm_adj) labels= np.append(np.zeros(shape=(curr_graph.shape[0], curr_graph.shape[1], 1)), split[1], axis=2) return np.add(spred_adj, labels) if __name__ == '__main__': graphs, labels = load_dataset("MUTAG") a, b = get_train_val_indexes(1, "MUTAG") print(np.transpose(graphs[a[0]], [1, 2, 0])[0])
227
41.18
152
19
2,483
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_e7b32e91bd52ab09_1101f1bb", "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": 21, "line_end": 21, "column_start": 10, "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/tmpr7mo7ysm/e7b32e91bd52ab09.py", "start": {"line": 21, "col": 10, "offset": 821}, "end": {"line": 21, "col": 30, "offset": 841}, "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_e7b32e91bd52ab09_ba33256e", "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": 72, "line_end": 72, "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/tmpr7mo7ysm/e7b32e91bd52ab09.py", "start": {"line": 72, "col": 16, "offset": 3272}, "end": {"line": 72, "col": 30, "offset": 3286}, "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_e7b32e91bd52ab09_72524a29", "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": 10, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/e7b32e91bd52ab09.py", "start": {"line": 104, "col": 10, "offset": 4765}, "end": {"line": 104, "col": 56, "offset": 4811}, "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_e7b32e91bd52ab09_21d445fb", "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": 109, "line_end": 109, "column_start": 10, "column_end": 55, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/e7b32e91bd52ab09.py", "start": {"line": 109, "col": 10, "offset": 4974}, "end": {"line": 109, "col": 55, "offset": 5019}, "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_e7b32e91bd52ab09_bc31d1d4", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 124, "line_end": 124, "column_start": 10, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/e7b32e91bd52ab09.py", "start": {"line": 124, "col": 10, "offset": 5501}, "end": {"line": 124, "col": 56, "offset": 5547}, "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_e7b32e91bd52ab09_98de0eb1", "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": 129, "line_end": 129, "column_start": 10, "column_end": 55, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/e7b32e91bd52ab09.py", "start": {"line": 129, "col": 10, "offset": 5697}, "end": {"line": 129, "col": 55, "offset": 5742}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
6
true
[ "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security" ]
[ "LOW" ]
[ "MEDIUM" ]
[ 72 ]
[ 72 ]
[ 16 ]
[ 30 ]
[ "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format." ]
[ 5 ]
[ "LOW" ]
[ "MEDIUM" ]
data_helper.py
/data_loader/data_helper.py
liuyunwu/ProvablyPowerfulGraphNetworks
Apache-2.0
2024-11-18T20:18:06.950686+00:00
1,678,997,667,000
b5aa4687744b00b3aac5a9d7ebc5299dd1c7c32a
2
{ "blob_id": "b5aa4687744b00b3aac5a9d7ebc5299dd1c7c32a", "branch_name": "refs/heads/main", "committer_date": 1678997667000, "content_id": "d1bbb1b742576e46e61a97cb15ecfb92b53f568a", "detected_licenses": [ "MIT" ], "directory_id": "5e22728a45dc131b5abcdde3c10928557177898b", "extension": "py", "filename": "nb_metadata.py", "fork_events_count": 11, "gha_created_at": 1585274417000, "gha_event_created_at": 1678997668000, "gha_language": "Python", "gha_license_id": "MIT", "github_id": 250417186, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5736, "license": "MIT", "license_type": "permissive", "path": "/msticnb/nb_metadata.py", "provenance": "stack-edu-0054.json.gz:577998", "repo_name": "microsoft/msticnb", "revision_date": 1678997667000, "revision_id": "cefc4ee5a22285d33e7abd91371c617fe42f8129", "snapshot_id": "74fc9636964be68900702ee0c85b0c992f0779ad", "src_encoding": "UTF-8", "star_events_count": 25, "url": "https://raw.githubusercontent.com/microsoft/msticnb/cefc4ee5a22285d33e7abd91371c617fe42f8129/msticnb/nb_metadata.py", "visit_date": "2023-06-30T02:00:29.253130" }
2.421875
stackv2
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- """Notebooklet base classes.""" from pathlib import Path from typing import Any, Dict, List, Optional, Set, Tuple, Union import attr import yaml from attr import Factory from ._version import VERSION __version__ = VERSION __author__ = "Ian Hellen" @attr.s(auto_attribs=True) class NBMetadata: """Notebooklet metadata class.""" name: str = "Unnamed" mod_name: str = "" description: str = "" default_options: List[Union[str, Dict]] = Factory(list) other_options: List[Union[str, Dict]] = Factory(list) inputs: List[str] = ["value"] entity_types: List[str] = Factory(list) keywords: List[str] = Factory(list) req_providers: List[str] = Factory(list) # pylint: disable=not-an-iterable @property def search_terms(self) -> Set[str]: """Return set of search terms for the object.""" return set( [self.name] + [obj.casefold() for obj in self.entity_types] # type: ignore + [key.casefold() for key in self.keywords] # type: ignore + [opt.casefold() for opt in self.all_options] # type: ignore ) def __str__(self): """Return string representation of object.""" return "\n".join(f"{name}: {val}" for name, val in attr.asdict(self).items()) @property def all_options(self) -> List[str]: """Return combination of default and other options.""" opts = [] if self.default_options: for opt in self.default_options: if isinstance(opt, str): opts.append(opt) elif isinstance(opt, dict): opts.append(next(iter(opt.keys()))) if self.other_options: for opt in self.other_options: if isinstance(opt, str): opts.append(opt) elif isinstance(opt, dict): opts.append(next(iter(opt.keys()))) return sorted(opts) def get_options(self, option_set: str = "all") -> List[Tuple[str, Optional[str]]]: """ Return list of options and descriptions. Parameters ---------- option_set : str, optional The subset of options to return, by default "all" Other values are "default" and "other" Returns ------- List[Tuple[str, Optional[str]]] A list of tuples of option name and description. """ opt_list: List[Tuple[str, Optional[str]]] = [] if option_set.casefold() in ["all", "default"] and self.default_options: for opt in self.default_options: if isinstance(opt, str): opt_list.append((opt, None)) elif isinstance(opt, dict): opt_list.extend(opt.items()) if option_set.casefold() in ["all", "other"] and self.other_options: for opt in self.other_options: if isinstance(opt, str): opt_list.append((opt, None)) elif isinstance(opt, dict): opt_list.extend(opt.items()) return opt_list @property def options_doc(self) -> str: """Return list of options and documentation.""" def_options = self.get_options("default") opt_list = [ "", " Default Options", " ---------------", ] if def_options: opt_list.extend([f" - {key}: {value}" for key, value in def_options]) else: opt_list.append(" None") opt_list.extend( [ "", " Other Options", " -------------", ] ) if self.get_options("other"): opt_list.extend( [f" - {key}: {value}" for key, value in self.get_options("other")] ) else: opt_list.append(" None") # Add a blank line to the end opt_list.extend(["", ""]) return "\n".join(opt_list) # pylint: enable=not-an-iterable def read_mod_metadata(mod_path: str, module_name) -> Tuple[NBMetadata, Dict[str, Any]]: """ Read notebooklet metadata from yaml file. Parameters ---------- mod_path : str The fully-qualified (dotted) module name module_name : str The full module name. Returns ------- Tuple[NBMetadata, Dict[str, Any]] A tuple of the metadata class and the documentation dictionary """ md_dict = _read_metadata_file(mod_path) if not md_dict: return NBMetadata(), {} metadata_vals = md_dict.get("metadata", {}) metadata_vals["mod_name"] = module_name metadata = NBMetadata(**metadata_vals) output = md_dict.get("output", {}) return metadata, output def _read_metadata_file(mod_path): md_path = Path(str(mod_path).replace(".py", ".yaml")) if not md_path.is_file(): md_path = Path(str(mod_path).replace(".py", ".yml")) if md_path.is_file(): with open(md_path, "r", encoding="utf-8") as _md_file: return yaml.safe_load(_md_file) return None def update_class_doc(cls_doc: str, cls_metadata: NBMetadata): """Append the options documentation to the `cls_doc`.""" options_doc = cls_metadata.options_doc if options_doc is not None: return cls_doc + options_doc return cls_doc
177
31.41
87
24
1,229
python
[{"finding_id": "semgrep_rules.python.attr.correctness.attr-mutable-initializer_d9e81976bfac381f_993e7b92", "tool_name": "semgrep", "rule_id": "rules.python.attr.correctness.attr-mutable-initializer", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Unsafe usage of mutable initializer with attr.s decorator. Multiple instances of this class will re-use the same data structure, which is likely not the desired behavior. Consider instead: replace assignment to mutable initializer (ex. dict() or {}) with attr.ib(factory=type) where type is dict, set, or list", "remediation": "", "location": {"file_path": "unknown", "line_start": 29, "line_end": 29, "column_start": 5, "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.attr.correctness.attr-mutable-initializer", "path": "/tmp/tmpr7mo7ysm/d9e81976bfac381f.py", "start": {"line": 29, "col": 5, "offset": 844}, "end": {"line": 29, "col": 34, "offset": 873}, "extra": {"message": "Unsafe usage of mutable initializer with attr.s decorator. Multiple instances of this class will re-use the same data structure, which is likely not the desired behavior. Consider instead: replace assignment to mutable initializer (ex. dict() or {}) with attr.ib(factory=type) where type is dict, set, or list", "metadata": {"category": "correctness", "technology": ["attr"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}]
1
true
[ "" ]
[ "rules.python.attr.correctness.attr-mutable-initializer" ]
[ "correctness" ]
[ "MEDIUM" ]
[ "MEDIUM" ]
[ 29 ]
[ 29 ]
[ 5 ]
[ 34 ]
[ "" ]
[ "Unsafe usage of mutable initializer with attr.s decorator. Multiple instances of this class will re-use the same data structure, which is likely not the desired behavior. Consider instead: replace assignment to mutable initializer (ex. dict() or {}) with attr.ib(factory=type) where type is dict, set, or list" ]
[ 5 ]
[ "" ]
[ "" ]
nb_metadata.py
/msticnb/nb_metadata.py
microsoft/msticnb
MIT
2024-11-18T20:18:08.233918+00:00
1,608,510,203,000
ac4a97d9e58461b77cc927163736d43a3e87749b
2
{ "blob_id": "ac4a97d9e58461b77cc927163736d43a3e87749b", "branch_name": "refs/heads/main", "committer_date": 1608510203000, "content_id": "83c78ac31b9a4599b4d4ac20e9853fb8627d0e0b", "detected_licenses": [ "MIT" ], "directory_id": "001d475d2ce43f37d44edbbe0f3b136f5a73a432", "extension": "py", "filename": "get_hf_datasets.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 312071564, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3350, "license": "MIT", "license_type": "permissive", "path": "/dataset_analyses/get_hf_datasets.py", "provenance": "stack-edu-0054.json.gz:578018", "repo_name": "positivevaib/ood-detection", "revision_date": 1608510203000, "revision_id": "fb428914177eebb22b69e2df050b2d3e519a104a", "snapshot_id": "ff76c5cdb9221c2c10f5cccbc1f5263ce1f7b866", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/positivevaib/ood-detection/fb428914177eebb22b69e2df050b2d3e519a104a/dataset_analyses/get_hf_datasets.py", "visit_date": "2023-02-05T17:16:14.723034" }
2.328125
stackv2
import os import argparse import pickle import numpy as np import pandas as pd from sklearn.utils import shuffle import datasets from datasets import load_dataset from tqdm import tqdm data_out = os.path.join('.','datasets') custom_out = os.path.join(data_out, 'used_evals') in_domains = [ 'imdb', 'sst2', ] seed = 42 hf_datasets = [ 'imdb', 'rte', 'snli', 'sst2', ] glue = ['rte', 'sst2'] entailment = ['snli', 'rte'] other_datasets = { 'counterfactual-imdb':{ 'base': os.path.join(data_out, 'counterfactually-augmented-data', 'sentiment', 'new'), 'files': [ 'dev.tsv', 'test.tsv', 'train.tsv', ] } } train_split_keys = { 'imdb': 'train', 'rte': 'train', 'snli': 'train', 'sst2': 'train', 'counterfactual-imdb': 'train' } eval_split_keys = { 'imdb': 'test', 'rte': 'validation', 'snli': 'validation', 'sst2': 'validation', 'counterfactual-imdb': 'dev' } datasets_to_keys = { 'imdb': ('text', None), 'rte': ('sentence1', 'sentence2'), 'snli': ('premise', 'hypothesis'), 'sst2': ('sentence', None), 'counterfactual-imdb': ('Text', None) } if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('cache', type=str, default=None) args = parser.parse_args() data = {} t = tqdm(hf_datasets) for data_name in t: t.set_description(data_name) if data_name in glue: data[data_name] = load_dataset('glue', data_name, split=eval_split_keys[data_name], cache_dir=args.cache) else: data[data_name] = load_dataset(data_name, split=eval_split_keys[data_name], cache_dir=args.cache) data_out = {} for data_name, val_data in data.items(): domain_key = 'ood' # for in-domain random split if data_name in in_domains: sentences, labels = shuffle( val_data[datasets_to_keys[data_name][0]], val_data['label'], random_state=seed ) print(type(val_data[datasets_to_keys[data_name][0]]), type(val_data[datasets_to_keys[data_name][0]][0])) split_idx = int(0.2*len(sentences)) data_out[('id', 'val', data_name)] = {'text': sentences[split_idx:], 'label': labels[split_idx:]} # training data # temp = load_dataset(data_name, split=train_split_keys[data_name], cache_dir=args.cache) # data_out[('id', 'train', data_name)] = {'text': temp[datasets_to_keys[data_name][0]], 'label': temp['label']} # out-of-domain splits if data_name in entailment: sentences = [ sentence1 + ' ' + sentence2 for sentence1, sentence2 in zip(val_data[datasets_to_keys[data_name][0]], val_data[datasets_to_keys[data_name][1]]) ] labels = val_data['label'] data_out[(domain_key, 'val', data_name)] = {'text': sentences, 'label': labels} else: data_out[(domain_key, 'val', data_name)] = {'text': val_data[datasets_to_keys[data_name][0]], 'label': val_data['label']} with open(os.path.join(args.cache, 'hf_data.p'), 'wb') as f: pickle.dump(data_out, f)
112
28.91
133
17
851
python
[{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_0997373f2fe359fa_2a1f41e4", "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": 112, "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/tmpr7mo7ysm/0997373f2fe359fa.py", "start": {"line": 112, "col": 9, "offset": 3325}, "end": {"line": 112, "col": 33, "offset": 3349}, "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" ]
[ 112 ]
[ 112 ]
[ 9 ]
[ 33 ]
[ "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format." ]
[ 5 ]
[ "LOW" ]
[ "MEDIUM" ]
get_hf_datasets.py
/dataset_analyses/get_hf_datasets.py
positivevaib/ood-detection
MIT
2024-11-18T20:18:08.346135+00:00
1,556,253,230,000
9c1176e2631ce90b2cfb200ad10d6d5f1ba13964
3
{ "blob_id": "9c1176e2631ce90b2cfb200ad10d6d5f1ba13964", "branch_name": "refs/heads/master", "committer_date": 1556253230000, "content_id": "8dec4b645438cf541fd42e3e034b5154b0617982", "detected_licenses": [ "MIT" ], "directory_id": "4001153bf50cbaa4d300c79a94bf72fb555e37f0", "extension": "py", "filename": "dataset.py", "fork_events_count": 0, "gha_created_at": 1556252193000, "gha_event_created_at": 1556252193000, "gha_language": null, "gha_license_id": null, "github_id": 183555667, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9216, "license": "MIT", "license_type": "permissive", "path": "/dataset.py", "provenance": "stack-edu-0054.json.gz:578020", "repo_name": "unixnme/charnlm-pytorch", "revision_date": 1556253230000, "revision_id": "e3334267357db6077833cef80b9dd7730eeca6d8", "snapshot_id": "74f19ca8a979154681c3bdc8ee3cbe016771033d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/unixnme/charnlm-pytorch/e3334267357db6077833cef80b9dd7730eeca6d8/dataset.py", "visit_date": "2020-05-17T06:18:32.910869" }
2.71875
stackv2
import numpy as np import os import sys import nltk import pickle import pprint import copy nltk.download('punkt') class Dataset(object): def __init__(self, config): self.config = config # dictionary settings self.initialize_dictionary() self.build_corpus(self.config.train_path, self.train_corpus) self.build_corpus(self.config.valid_path, self.valid_corpus) self.build_corpus(self.config.test_path, self.test_corpus) print() self.train_data = self.process_data( self.train_corpus, update_dict=True) self.valid_data = self.process_data( self.valid_corpus, update_dict=True) self.test_data = self.process_data( self.test_corpus) print() self.pad_data(self.train_data) self.pad_data(self.valid_data) self.pad_data(self.test_data) # data = [batch_size, batches, maxlen], [batch_size, batches] # where data[0] is char idx and data[1] is the corresponding word idx self.train_data = self.reshape_data(self.train_data) self.valid_data = self.reshape_data(self.valid_data) self.test_data = self.reshape_data(self.test_data) print() self.train_ptr = 0 self.valid_ptr = 0 self.test_ptr = 0 print('char_dict', len(self.char2idx)) print('word_dict', len(self.word2idx), end='\n\n') def initialize_dictionary(self): self.train_corpus = [] self.valid_corpus = [] self.test_corpus = [] self.char2idx = {} self.idx2char = {} self.word2idx = {} self.idx2word = {} self.UNK = '<unk>' self.PAD = 'PAD' self.CONJ = '+' self.START = '{' self.END = '}' self.char2idx[self.UNK] = 0 self.char2idx[self.PAD] = 1 self.char2idx[self.CONJ] = 2 self.char2idx[self.START] = 3 self.char2idx[self.END] = 4 self.idx2char[0] = self.UNK self.idx2char[1] = self.PAD self.idx2char[2] = self.CONJ self.idx2char[3] = self.START self.idx2char[4] = self.END self.word2idx[self.UNK] = 0 self.word2idx[self.PAD] = 1 self.word2idx[self.CONJ] = 2 self.idx2word[0] = self.UNK self.idx2word[1] = self.PAD self.idx2word[2] = self.CONJ def update_dictionary(self, key, mode=None): if mode == 'c': if key not in self.char2idx: self.char2idx[key] = len(self.char2idx) self.idx2char[len(self.idx2char)] = key elif mode == 'w': if key not in self.word2idx: self.word2idx[key] = len(self.word2idx) self.idx2word[len(self.idx2word)] = key def map_dictionary(self, key_list, dictionary, reverse=False): output = [] # reverse=False : word2idx, char2idx # reverse=True : idx2word, idx2char for key in key_list: if key in dictionary: if reverse and key == 1: # PAD continue else: output.append(dictionary[key]) else: if not reverse: output.append(dictionary[self.UNK]) else: output.append(dictionary[0]) # 0 for UNK return output def build_corpus(self, path, corpus): print('building corpus %s' % path) with open(path) as f: for k, line in enumerate(f): # sentence_split = nltk.word_tokenize(line[:-1]) sentence_split = line[:-1].split() for word in sentence_split: corpus.append(word) corpus.append(self.CONJ) def process_data(self, corpus, update_dict=False): print('processing corpus %d' % len(corpus)) total_data = [] max_wordlen = 0 for k, word in enumerate(corpus): # dictionary update if update_dict: self.update_dictionary(word, 'w') for char in word: self.update_dictionary(char, 'c') # user special characters or mapping if word == self.UNK or word == self.CONJ or word == self.PAD: word_char = word charidx = [self.char2idx[word_char]] else: word_char = self.START + word + self.END charidx = self.map_dictionary(word_char, self.char2idx) # get max word length max_wordlen = (len(word_char) if len(word_char) > max_wordlen else max_wordlen) if max_wordlen > self.config.max_wordlen: self.config.max_wordlen = max_wordlen # word / char total_data.append([self.word2idx[word], charidx]) if update_dict: self.config.char_vocab_size = len(self.char2idx) self.config.word_vocab_size = len(self.word2idx) print('data size', len(total_data)) print('max wordlen', max_wordlen) return total_data def pad_data(self, dataset): for data in dataset: sentword, sentchar = data # pad word in sentchar while len(sentchar) != self.config.max_wordlen: sentchar.append(self.char2idx[self.PAD]) return dataset def reshape_data(self, dataset): inputs = [d[1] for d in dataset] targets = [d[0] for d in dataset] seq_len = len(dataset) // self.config.batch_size inputs = np.array(inputs[:seq_len * self.config.batch_size]) targets = np.array(targets[:seq_len * self.config.batch_size]) inputs = np.reshape(inputs, (self.config.batch_size, seq_len, -1)) targets = np.reshape(targets, (self.config.batch_size, -1)) print('reshaped data', inputs.shape) return inputs, targets # inputs, targets such that inputs[1:] = target[0:-1], i.e., predict the next def get_next_batch(self, seq_len, mode='tr'): if mode == 'tr': ptr = self.train_ptr data = self.train_data elif mode == 'va': ptr = self.valid_ptr data = self.valid_data elif mode == 'te': ptr = self.test_ptr data = self.test_data seq_len = (seq_len if ptr + seq_len < len(data[0][0]) else len(data[0][0]) - ptr - 1) inputs = data[0][:,ptr:ptr+seq_len,:] targets = data[1][:,ptr+1:ptr+seq_len+1] if len(data[0][0]) - (ptr + seq_len) == 1: # last batch ptr += 1 if mode == 'tr': self.train_ptr = (ptr + seq_len) % len(data[0][0]) elif mode == 'va': self.valid_ptr = (ptr + seq_len) % len(data[0][0]) elif mode == 'te': self.test_ptr = (ptr + seq_len) % len(data[0][0]) return inputs, targets def get_batch_ptr(self, mode): if mode == 'tr': return self.train_ptr elif mode == 'va': return self.valid_ptr elif mode == 'te': return self.test_ptr class Config(object): def __init__(self): user_home = os.path.expanduser('~') self.train_path = os.path.join(user_home, 'datasets/ptb/train.txt') self.valid_path = os.path.join(user_home, 'datasets/ptb/valid.txt') self.test_path = os.path.join(user_home, 'datasets/ptb/test.txt') self.batch_size = 20 self.max_wordlen = 0 self.char_vocab_size = 0 self.word_vocab_size = 0 self.save_preprocess = True self.preprocess_save_path = './data/preprocess(tmp).pkl' self.preprocess_load_path = './data/preprocess(tmp).pkl' if __name__ == '__main__': if not os.path.exists('./data'): os.makedirs('./data') config = Config() if config.save_preprocess: dataset = Dataset(config) pickle.dump(dataset, open(config.preprocess_save_path, 'wb')) else: print('## load preprocess %s' % config.preprocess_load_path) dataset = pickle.load(open(config.preprocess_load_path, 'rb')) # dataset config must be valid pp = lambda x: pprint.PrettyPrinter().pprint(x) pp(([(k,v) for k, v in vars(dataset.config).items() if '__' not in k])) print() input, target = dataset.get_next_batch(seq_len=5) print([dataset.map_dictionary(i, dataset.idx2char) for i in input[0,:,:]]) print([dataset.idx2word[t] for t in target[0,:]]) print() input, target = dataset.get_next_batch(seq_len=5) print([dataset.map_dictionary(i, dataset.idx2char) for i in input[0,:,:]]) print([dataset.idx2word[t] for t in target[0,:]]) print('train', dataset.train_data[0].shape) print('valid', dataset.valid_data[0].shape) print('test', dataset.test_data[0].shape) while True: i, t = dataset.get_next_batch(seq_len=100, mode='te') print(dataset.test_ptr, len(i[0])) if dataset.test_ptr == 0: print('\niteration test pass!') break
264
33.91
81
18
2,215
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_e0a57ca5f40a5e36_86ad7698", "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": 109, "line_end": 109, "column_start": 14, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/e0a57ca5f40a5e36.py", "start": {"line": 109, "col": 14, "offset": 3532}, "end": {"line": 109, "col": 24, "offset": 3542}, "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_e0a57ca5f40a5e36_1b97aa5e", "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": 235, "line_end": 235, "column_start": 9, "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/tmpr7mo7ysm/e0a57ca5f40a5e36.py", "start": {"line": 235, "col": 9, "offset": 8071}, "end": {"line": 235, "col": 70, "offset": 8132}, "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_e0a57ca5f40a5e36_200e5b92", "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": 238, "line_end": 238, "column_start": 19, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/e0a57ca5f40a5e36.py", "start": {"line": 238, "col": 19, "offset": 8230}, "end": {"line": 238, "col": 71, "offset": 8282}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_e0a57ca5f40a5e36_19e5ef6a", "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": 241, "line_end": 241, "column_start": 20, "column_end": 52, "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/tmpr7mo7ysm/e0a57ca5f40a5e36.py", "start": {"line": 241, "col": 20, "offset": 8338}, "end": {"line": 241, "col": 52, "offset": 8370}, "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-502", "CWE-502" ]
[ "rules.python.lang.security.deserialization.avoid-pickle", "rules.python.lang.security.deserialization.avoid-pickle" ]
[ "security", "security" ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
[ 235, 238 ]
[ 235, 238 ]
[ 9, 19 ]
[ 70, 71 ]
[ "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" ]
dataset.py
/dataset.py
unixnme/charnlm-pytorch
MIT
2024-11-18T20:18:10.539112+00:00
1,487,178,095,000
9ba63847dc305562ad3865281b02077eaa636762
3
{ "blob_id": "9ba63847dc305562ad3865281b02077eaa636762", "branch_name": "refs/heads/master", "committer_date": 1487178095000, "content_id": "45db7e9ee66a039a73e76aa619d3c64d0a200340", "detected_licenses": [ "MIT" ], "directory_id": "80c92410009407145959e71c9fa7a9c221aef332", "extension": "py", "filename": "tracker1.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 82084611, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2039, "license": "MIT", "license_type": "permissive", "path": "/tracker1.py", "provenance": "stack-edu-0054.json.gz:578047", "repo_name": "doctorwho42/Reeve-Work-Tracker", "revision_date": 1487178095000, "revision_id": "059578baadb2711f38ddc2c5442616dbb5bf46af", "snapshot_id": "64ed256de3b674af1393330f7ad2af260d311ae2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/doctorwho42/Reeve-Work-Tracker/059578baadb2711f38ddc2c5442616dbb5bf46af/tracker1.py", "visit_date": "2021-01-19T09:05:08.838512" }
2.8125
stackv2
#!/usr/bin/env python import RPi.GPIO as GPIO import datetime import time import sys import pickle from Adafruit_LED_Backpack import SevenSegment GPIO.setmode(GPIO.BCM) display = SevenSegment.SevenSegment() display.begin() GPIO.setup(26, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(19, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(6, GPIO.IN, pull_up_down=GPIO.PUD_UP) state1 = GPIO.input(26) state2 = GPIO.input(19) state3 = GPIO.input(13) state4 = GPIO.input(6) keys = False #write values to LED Display- (d4 d3: d2 d1) - (43:21) - d4=4,d3=3,d2=2,d1=1 def ledoutput(d1,d2,d3,d4): display.clear() display.set_digit(0,d4) display.set_digit(1,d3) display.set_digit(2,d2) display.set_digit(3,d1) display.set_colon(True) display.write_display() #Example read/write pickle # with open('/home/pi/pythoncode/worktracker/tracking.p', 'w') as write: # pickle.dump([write1, write2, write3, write4], write) # with open('/home/pi/pythoncode/worktracker/tracking.p') as read: # read1, read2, read3, read4 = pickle.load(read) with open('/home/pi/pythoncode/worktracker/tracking.p') as read: read1,read2,read3,read4,read5= pickle.load(read) x1 = read1 #lowest digit x2 = read2 #second lowest digit x3 = read3 #second highest digit x4 = read4 #highest digit crap = read5 #rob has worked over 99H:99M in a week,then this will =1 if state1 == 0: keys = True elif state2 == 0: keys = True elif state3 == 0: keys = True elif state4 == 0: keys = True #print(keys) if keys==True: if x1<=8: x1 = x1 + 1 elif x1==9: x1 = 0 x2 = x2 + 1 if x3==9 and x2==6: x3 = 0 x2 = 0 if x4==9: crap = 1 elif x4<=8: x4 = x4 + 1 if x2==6: x2=0 x3=x3+1 ledoutput(x1,x2,x3,x4) if crap== 1: display.set_decimal(0,True) display.set_decimal(1,True) display.set_decimal(2,True) display.set_decimal(3,True) display.write_display() #ledoutput(x1,x2,x3,x4) with open('/home/pi/pythoncode/worktracker/tracking.p', 'w') as write: pickle.dump([x1,x2,x3,x4,crap], write)
92
21.16
76
12
710
python
[{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_eb9e9b4357d3e0dd_e6c16067", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 41, "line_end": 41, "column_start": 6, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/eb9e9b4357d3e0dd.py", "start": {"line": 41, "col": 6, "offset": 1088}, "end": {"line": 41, "col": 56, "offset": 1138}, "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_eb9e9b4357d3e0dd_87129347", "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": 33, "column_end": 50, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpr7mo7ysm/eb9e9b4357d3e0dd.py", "start": {"line": 42, "col": 33, "offset": 1180}, "end": {"line": 42, "col": 50, "offset": 1197}, "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_eb9e9b4357d3e0dd_cc439344", "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": 6, "column_end": 61, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpr7mo7ysm/eb9e9b4357d3e0dd.py", "start": {"line": 89, "col": 6, "offset": 1931}, "end": {"line": 89, "col": 61, "offset": 1986}, "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_eb9e9b4357d3e0dd_657a3637", "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": 90, "line_end": 90, "column_start": 2, "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/tmpr7mo7ysm/eb9e9b4357d3e0dd.py", "start": {"line": 90, "col": 2, "offset": 1998}, "end": {"line": 90, "col": 40, "offset": 2036}, "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" ]
[ 42, 90 ]
[ 42, 90 ]
[ 33, 2 ]
[ 50, 40 ]
[ "A08:2017 - Insecure Deserialization", "A08:2017 - Insecure Deserialization" ]
[ "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "Avoid using `pickle`, which is known to lead to...
[ 5, 5 ]
[ "LOW", "LOW" ]
[ "MEDIUM", "MEDIUM" ]
tracker1.py
/tracker1.py
doctorwho42/Reeve-Work-Tracker
MIT