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-18T18:05:43.388874+00:00 | 1,567,036,262,000 | 912041d1cee909d29a9b46991268ac30470556ff | 3 | {
"blob_id": "912041d1cee909d29a9b46991268ac30470556ff",
"branch_name": "refs/heads/master",
"committer_date": 1567036262000,
"content_id": "c6d2536833fc35c3e025cd9d5cea56298f7fe360",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "ca5fc43049f94a794d90a561fd8126f02b603599",
"extension": "py",
"filename": "alias.py",
"fork_events_count": 0,
"gha_created_at": 1469110078000,
"gha_event_created_at": 1527068726000,
"gha_language": "Python",
"gha_license_id": "BSD-3-Clause",
"github_id": 63874745,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2632,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/i3py/core/features/alias.py",
"provenance": "stack-edu-0054.json.gz:568753",
"repo_name": "Exopy/i3py",
"revision_date": 1567036262000,
"revision_id": "6f004d3e2ee2b788fb4693606cc4092147655ce1",
"snapshot_id": "32d9ee343d21d275680a2d030b660a80960e99ac",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Exopy/i3py/6f004d3e2ee2b788fb4693606cc4092147655ce1/i3py/core/features/alias.py",
"visit_date": "2022-02-18T21:51:16.423188"
} | 2.5625 | stackv2 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2016-2017 by I3py Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# -----------------------------------------------------------------------------
"""Feature whose value is mapped to another Feature.
"""
from types import MethodType
from typing import Any, Dict, Callable
from ..abstracts import AbstractHasFeatures
from .feature import Feature, get_chain, set_chain
GET_DEF =\
"""def get(self, driver):
return {}
"""
SET_DEF =\
"""def set(self, driver, value):
{} = value
"""
class Alias(Feature):
"""Feature whose value is mapped to another Feature.
Parameters
----------
alias : str
Path to the feature to which the alias refers to. The path should be
dot separated and use leading dots to access to parent features.
settable: bool, optional
Boolean indicating if the alias can be used to set the value of the
aliased feature.
"""
def __init__(self, alias: str, settable: bool=False) -> None:
super(Alias, self).__init__(True, settable if settable else None)
accessor = 'driver.' + '.'.join([p if p else 'parent'
for p in alias.split('.')])
defs = GET_DEF.format(accessor)
if settable:
defs += '\n' + SET_DEF.format(accessor)
loc: Dict[str, Callable] = {}
exec(defs, globals(), loc)
self.get = MethodType(loc['get'], self) # type: ignore
if settable:
self.set = MethodType(loc['set'], self) # type: ignore
def post_set(self, driver: AbstractHasFeatures, value: Any, i_value: Any,
response: Any):
"""Re-implemented here as an Alias does not need to do anything
by default.
"""
pass
# =========================================================================
# --- Private API ---------------------------------------------------------
# =========================================================================
def _get(self, driver: AbstractHasFeatures):
"""Re-implemented so that Alias never use the cache.
"""
with driver.lock:
return get_chain(self, driver)
def _set(self, driver: AbstractHasFeatures, value: Any):
"""Re-implemented so that Alias never uses the cache.
"""
with driver.lock:
set_chain(self, driver, value)
| 90 | 28.24 | 79 | 16 | 535 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.exec-detected_715a30efc2342539_ee5be2eb", "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": 60, "line_end": 60, "column_start": 9, "column_end": 35, "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/tmpb8jm_z1l/715a30efc2342539.py", "start": {"line": 60, "col": 9, "offset": 1581}, "end": {"line": 60, "col": 35, "offset": 1607}, "extra": {"message": "Detected the use of exec(). exec() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-95"
] | [
"rules.python.lang.security.audit.exec-detected"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
60
] | [
60
] | [
9
] | [
35
] | [
"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"
] | alias.py | /i3py/core/features/alias.py | Exopy/i3py | BSD-3-Clause | |
2024-11-18T18:05:44.308384+00:00 | 1,578,981,575,000 | 8d0411d1a3851550c8d731400213ff48f1c3b0c7 | 2 | {
"blob_id": "8d0411d1a3851550c8d731400213ff48f1c3b0c7",
"branch_name": "refs/heads/master",
"committer_date": 1578981575000,
"content_id": "e86b6be15675ecfb59b4c74485893d83221a5f43",
"detected_licenses": [
"MIT"
],
"directory_id": "8142e588999503979e1cd9d1989cdd43dc9417d6",
"extension": "py",
"filename": "losses.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": 11390,
"license": "MIT",
"license_type": "permissive",
"path": "/evkit/utils/losses.py",
"provenance": "stack-edu-0054.json.gz:568764",
"repo_name": "lilujunai/side-tuning",
"revision_date": 1578981575000,
"revision_id": "dea345691fb7ee0230150fe56ddd644efdffa6ac",
"snapshot_id": "07a0e2015fcb7f3699f749fb233b95ceba449277",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lilujunai/side-tuning/dea345691fb7ee0230150fe56ddd644efdffa6ac/evkit/utils/losses.py",
"visit_date": "2021-02-26T23:52:13.468928"
} | 2.390625 | stackv2 | from evkit.models.taskonomy_network import TaskonomyDecoder
from tlkit.utils import SINGLE_IMAGE_TASKS, TASKS_TO_CHANNELS, FEED_FORWARD_TASKS
import torch
import torch.nn.functional as F
def softmax_cross_entropy(inputs, target, weight=None, cache={}, size_average=None, ignore_index=-100,
reduce=None, reduction='mean'):
cache['predictions'] = inputs
cache['labels'] = target
if len(target.shape) == 2: # unsqueeze one-hot representation
target = torch.argmax(target, dim=1)
loss = F.cross_entropy(inputs, target, weight)
# when working with 2D data, cannot use spatial weight mask, it becomes categorical/class
return {'total': loss, 'xentropy': loss}
def heteroscedastic_normal(mean_and_scales, target, weight=None, cache={}, eps=1e-2):
mu, scales = mean_and_scales
loss = (mu - target)**2 / (scales**2 + eps) + torch.log(scales**2 + eps)
# return torch.sum(weight * loss) / torch.sum(weight) if weight is not None else loss.mean()
loss = torch.mean(weight * loss) / weight.mean() if weight is not None else loss.mean()
return {'total': loss, 'nll': loss}
def heteroscedastic_double_exponential(mean_and_scales, target, weight=None, cache={}, eps=5e-2):
mu, scales = mean_and_scales
loss = torch.abs(mu - target) / (scales + eps) + torch.log(2.0 * (scales + eps))
loss = torch.mean(weight * loss) / weight.mean() if weight is not None else loss.mean()
return {'total': loss, 'nll': loss}
def weighted_mse_loss(inputs, target, weight=None, cache={}):
losses = {}
cache['predictions'] = inputs
cache['labels'] = target
if weight is not None:
# sq = (inputs - target) ** 2
# weightsq = torch.sum(weight * sq)
loss = torch.mean(weight * (inputs - target) ** 2)/torch.mean(weight)
else:
loss = F.mse_loss(inputs, target)
return {'total': loss, 'mse': loss}
weighted_l2_loss = weighted_mse_loss
def weighted_l1_loss(inputs, target, weight=None, cache={}):
target = target.float()
if weight is not None:
loss = torch.mean(weight * torch.abs(inputs - target))/torch.mean(weight)
else:
loss = F.l1_loss(inputs, target)
return {'total': loss, 'l1': loss}
def perceptual_l1_loss(decoder_path, bake_decodings):
task = [t for t in SINGLE_IMAGE_TASKS if t in decoder_path][0]
decoder = TaskonomyDecoder(TASKS_TO_CHANNELS[task], feed_forward=task in FEED_FORWARD_TASKS)
checkpoint = torch.load(decoder_path)
decoder.load_state_dict(checkpoint['state_dict'])
decoder.cuda()
decoder.eval()
print(f'Loaded decoder from {decoder_path} for perceptual loss')
def runner(inputs, target, weight=None, cache={}):
# the last arguments are so we can 'cache' and pass the decodings outside
inputs_decoded = decoder(inputs)
targets_decoded = target if bake_decodings else decoder(target)
cache['predictions'] = inputs_decoded
cache['labels'] = targets_decoded
if weight is not None:
loss = torch.mean(weight * torch.abs(inputs_decoded - targets_decoded))/torch.mean(weight)
else:
loss = F.l1_loss(inputs_decoded, targets_decoded)
return {'total': loss, 'perceptual_l1': loss}
return runner
def perceptual_l2_loss(decoder_path, bake_decodings):
task = [t for t in SINGLE_IMAGE_TASKS if t in decoder_path][0]
decoder = TaskonomyDecoder(TASKS_TO_CHANNELS[task], feed_forward=task in FEED_FORWARD_TASKS)
checkpoint = torch.load(decoder_path)
decoder.load_state_dict(checkpoint['state_dict'])
decoder.cuda()
decoder.eval()
print(f'Loaded decoder from {decoder_path} for perceptual loss')
def runner(inputs, target, weight=None, cache={}):
# the last arguments are so we can 'cache' and pass the decodings outside
inputs_decoded = decoder(inputs)
targets_decoded = target if bake_decodings else decoder(target)
cache['predictions'] = inputs_decoded
cache['labels'] = targets_decoded
if weight is not None:
loss = torch.mean(weight * (inputs_decoded - targets_decoded) ** 2)/torch.mean(weight)
else:
loss = F.mse_loss(inputs_decoded, targets_decoded)
return {'total': loss, 'perceptual_mse': loss}
return runner
def dense_softmax_cross_entropy_loss(inputs, targets, cache={}): # these should be logits (batch_size, n_class)
batch_size, _ = targets.shape
losses = {}
losses['final'] = -1. * torch.sum(torch.softmax(targets.float(), dim=1) * F.log_softmax(inputs.float(), dim=1)) / batch_size
losses['standard'] = losses['final']
return losses
def dense_cross_entropy_loss_(inputs, targets): # these should be logits (batch_size, n_class)
batch_size, _ = targets.shape
return -1. * torch.sum(targets * F.log_softmax(inputs, dim=1)) / batch_size
# def dense_softmax_cross_entropy(inputs, targets, weight=None, cache={}):
# assert weight == None
# cache['predictions'] = inputs
# cache['labels'] = targets
# # print(targets.shape)
# batch_size, _ = targets.shape
# loss = -1. * torch.sum(torch.softmax(targets, dim=1) * F.log_softmax(inputs, dim=1)) / batch_size
# loss = F.mse_loss(inputs, targets.detach())
# return {'total': loss, 'xentropy': loss}
def dense_softmax_cross_entropy(inputs, targets, weight=None, cache={}):
assert weight is None
cache['predictions'] = inputs
cache['labels'] = targets
batch_size, _ = targets.shape
loss = -1. * torch.sum(torch.softmax(targets.detach(), dim=1) * F.log_softmax(inputs, dim=1)) / batch_size
# loss = F.mse_loss(inputs, targets.detach())
return {'total': loss, 'xentropy': loss}
def dense_cross_entropy(inputs, targets, weight=None, cache={}):
assert weight == None
cache['predictions'] = inputs
cache['labels'] = targets
batch_size, _ = targets.shape
loss = -1. * torch.sum(targets.detach() * F.log_softmax(inputs, dim=1)) / batch_size
# loss = F.mse_loss(inputs, targets.detach())
return {'total': loss, 'xentropy': loss}
def perceptual_cross_entropy_loss(decoder_path, bake_decodings):
task = [t for t in SINGLE_IMAGE_TASKS if t in decoder_path][0]
decoder = TaskonomyDecoder(TASKS_TO_CHANNELS[task], feed_forward=task in FEED_FORWARD_TASKS)
checkpoint = torch.load(decoder_path)
decoder.load_state_dict(checkpoint['state_dict'])
decoder.cuda()
decoder.eval()
print(f'Loaded decoder from {decoder_path} for perceptual loss')
def runner(inputs, target, weight=None, cache={}):
# the last arguments are so we can 'cache' and pass the decodings outside
inputs_decoded = decoder(inputs)
targets_decoded = target if bake_decodings else decoder(target)
cache['predictions'] = inputs_decoded
cache['labels'] = targets_decoded
return dense_softmax_cross_entropy_loss_(inputs_decoded, targets_decoded)
return runner
def identity_regularizer(loss_fn, model):
def runner(inputs, target, weight=None, cache={}):
losses = loss_fn(inputs, target, weight, cache)
return losses
return runner
def transfer_regularizer(loss_fn, model, reg_loss_fn='F.l1_loss', coef=1e-3):
def runner(inputs, target, weight=None, cache={}):
orig_losses = loss_fn(inputs, target, weight, cache)
#if isinstance(model, PolicyWithBase):
if type(model).__name__ == "PolicyWithBase":
# Imitation Learning - retreive encodings via the cache
assert 'base_encoding' in cache and 'transfered_encoding' in cache, f'cache is missing keys {cache.keys()}'
regularization_loss = 0
for base_encoding, transfered_encoding in zip(cache['base_encoding'], cache['transfered_encoding']):
regularization_loss += eval(reg_loss_fn)(model.base.perception_unit.sidetuner.net.transfer_network(base_encoding), transfered_encoding)
else:
# Vision Transfers - retreive encodings directly from model attributes
# (cannot do this for IL due to the FrameStacked being iterative)
assert isinstance(model.side_output, torch.Tensor), 'Cannot regularize side network if it is not used'
regularization_loss = eval(reg_loss_fn)(model.transfer_network(model.base_encoding), model.transfered_encoding)
orig_losses.update({
'total': orig_losses['total'] + coef * regularization_loss,
'weight_tying': regularization_loss,
})
return orig_losses
return runner
def perceptual_regularizer(loss_fn, model, coef=1e-3, decoder_path=None, use_transfer=True, reg_loss_fn='F.mse_loss'):
# compares model.base_encoding E(x) and model.transfered_encoding T(E(x) + S(x))
# use_transfer means we will compare exactly above
# use_transfer=False means we will compare model.base_encoding E(x) and model.merged_encoding E(x) + S(x)
# Recall, decoder requires unnormalized inputs!
assert decoder_path is not None, 'Pass in a decoder to which to transform our parameters and regularize on'
task = [t for t in SINGLE_IMAGE_TASKS if t in decoder_path][0]
decoder = TaskonomyDecoder(TASKS_TO_CHANNELS[task], feed_forward=task in FEED_FORWARD_TASKS)
checkpoint = torch.load(decoder_path)
decoder.load_state_dict(checkpoint['state_dict'])
decoder.cuda()
decoder.eval()
if task in FEED_FORWARD_TASKS:
reg_loss_fn = "dense_softmax_cross_entropy_loss_"
else:
reg_loss_fn = "F.l1_loss"
print(f'Loaded decoder from {decoder_path} for perceptual loss')
def runner(inputs, target, weight=None, cache={}):
orig_losses = loss_fn(inputs, target, weight, cache)
if type(model).__name__ == "PolicyWithBase":
# Imitation Learning - retreive encodings via the cache
assert 'base_encoding' in cache, f'cache is missing base {cache.keys()}'
if use_transfer:
assert 'transfered_encoding' in cache, f'cache is missing tied {cache.keys()}'
tied_encodings = cache['transfered_encoding']
else:
assert 'merged_encoding' in cache, f'cache is missing tied{cache.keys()}'
tied_encodings = cache['merged_encoding']
regularization_loss = 0
for base_encoding, tied_encoding in zip(cache['base_encoding'], tied_encodings):
regularization_loss += eval(reg_loss_fn)(decoder(base_encoding), decoder(tied_encoding))
else:
# Vision Transfers - retreive encodings directly from model attributes
# (cannot do this for IL due to the FrameStacked being iterative)
assert isinstance(model.side_output, torch.Tensor), 'Cannot regularize side network if it is not used'
if use_transfer:
tied_encoding = model.transfered_encoding
else:
tied_encoding = model.merged_encoding
losses['weight_tying'] = eval(reg_loss_fn)(decoder(model.base_encoding), decoder(tied_encoding))
regularization_loss = reg_loss_fn(decoder(model.base_encoding), decoder(tied_encoding))
orig_losses.update({
'total': orig_losses['total'] + coef * regularization_loss,
'weight_tying': regularization_loss,
})
return orig_losses
return runner
| 235 | 47.47 | 151 | 20 | 2,680 | python | [{"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.default-mutable-dict_4f869c82d83d165c_241b7cca", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Function softmax_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "remediation": "", "location": {"file_path": "unknown", "line_start": 8, "line_end": 8, "column_start": 5, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 8, "col": 5, "offset": 345}, "end": {"line": 8, "col": 34, "offset": 374}, "extra": {"message": "Function softmax_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.default-mutable-dict_4f869c82d83d165c_6770f5a1", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Function softmax_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "remediation": "", "location": {"file_path": "unknown", "line_start": 9, "line_end": 9, "column_start": 5, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 9, "col": 5, "offset": 379}, "end": {"line": 9, "col": 29, "offset": 403}, "extra": {"message": "Function softmax_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.default-mutable-dict_4f869c82d83d165c_a749fb1e", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Function weighted_mse_loss mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "remediation": "", "location": {"file_path": "unknown", "line_start": 31, "line_end": 31, "column_start": 5, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 31, "col": 5, "offset": 1565}, "end": {"line": 31, "col": 34, "offset": 1594}, "extra": {"message": "Function weighted_mse_loss mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.default-mutable-dict_4f869c82d83d165c_c082ff16", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Function weighted_mse_loss mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "remediation": "", "location": {"file_path": "unknown", "line_start": 32, "line_end": 32, "column_start": 5, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 32, "col": 5, "offset": 1599}, "end": {"line": 32, "col": 29, "offset": 1623}, "extra": {"message": "Function weighted_mse_loss mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.default-mutable-dict_4f869c82d83d165c_f5889148", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Function dense_softmax_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "remediation": "", "location": {"file_path": "unknown", "line_start": 118, "line_end": 118, "column_start": 5, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 118, "col": 5, "offset": 5423}, "end": {"line": 118, "col": 34, "offset": 5452}, "extra": {"message": "Function dense_softmax_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.default-mutable-dict_4f869c82d83d165c_61add4d3", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Function dense_softmax_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "remediation": "", "location": {"file_path": "unknown", "line_start": 119, "line_end": 119, "column_start": 5, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 119, "col": 5, "offset": 5457}, "end": {"line": 119, "col": 30, "offset": 5482}, "extra": {"message": "Function dense_softmax_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.default-mutable-dict_4f869c82d83d165c_00faca8a", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Function dense_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "remediation": "", "location": {"file_path": "unknown", "line_start": 128, "line_end": 128, "column_start": 5, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 128, "col": 5, "offset": 5822}, "end": {"line": 128, "col": 34, "offset": 5851}, "extra": {"message": "Function dense_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.default-mutable-dict_4f869c82d83d165c_7e76ab99", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Function dense_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "remediation": "", "location": {"file_path": "unknown", "line_start": 129, "line_end": 129, "column_start": 5, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.default-mutable-dict", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 129, "col": 5, "offset": 5856}, "end": {"line": 129, "col": 30, "offset": 5881}, "extra": {"message": "Function dense_cross_entropy mutates default dict cache. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if cache is None: cache = {}`.", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_4f869c82d83d165c_c54f253b", "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": 169, "line_end": 169, "column_start": 40, "column_end": 57, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 169, "col": 40, "offset": 7840}, "end": {"line": 169, "col": 57, "offset": 7857}, "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_4f869c82d83d165c_80dc9d3e", "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": 174, "line_end": 174, "column_start": 35, "column_end": 52, "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/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 174, "col": 35, "offset": 8277}, "end": {"line": 174, "col": 52, "offset": 8294}, "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_4f869c82d83d165c_98c2aa39", "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": 217, "line_end": 217, "column_start": 40, "column_end": 57, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 217, "col": 40, "offset": 10458}, "end": {"line": 217, "col": 57, "offset": 10475}, "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_4f869c82d83d165c_aef43c00", "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": 226, "line_end": 226, "column_start": 38, "column_end": 55, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpb8jm_z1l/4f869c82d83d165c.py", "start": {"line": 226, "col": 38, "offset": 11010}, "end": {"line": 226, "col": 55, "offset": 11027}, "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"}}}] | 12 | true | [
"CWE-95",
"CWE-95",
"CWE-95",
"CWE-95"
] | [
"rules.python.lang.security.audit.eval-detected",
"rules.python.lang.security.audit.eval-detected",
"rules.python.lang.security.audit.eval-detected",
"rules.python.lang.security.audit.eval-detected"
] | [
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
169,
174,
217,
226
] | [
169,
174,
217,
226
] | [
40,
35,
40,
38
] | [
57,
52,
57,
55
] | [
"A03:2021 - Injection",
"A03:2021 - Injection",
"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,
5,
5
] | [
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | losses.py | /evkit/utils/losses.py | lilujunai/side-tuning | MIT | |
2024-11-18T18:05:52.300596+00:00 | 1,599,152,646,000 | 9185695cb36d6614095277825baed9bb945a49c2 | 2 | {
"blob_id": "9185695cb36d6614095277825baed9bb945a49c2",
"branch_name": "refs/heads/master",
"committer_date": 1599152646000,
"content_id": "048a36508be52d7c1697a055f4fb3d12039a6fca",
"detected_licenses": [
"MIT"
],
"directory_id": "3bc4d9a4f7744126cf5af8b56c75ec188476f6aa",
"extension": "py",
"filename": "assess.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 290616074,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9477,
"license": "MIT",
"license_type": "permissive",
"path": "/assess.py",
"provenance": "stack-edu-0054.json.gz:568839",
"repo_name": "kravitsjacob/phase_2_assessment",
"revision_date": 1599152646000,
"revision_id": "b0a15b8b4e9e98de61a029479fc658a0f3d53b3d",
"snapshot_id": "8e3b06e84d55b3c0e9a557e4900099e4b8b6d69d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kravitsjacob/phase_2_assessment/b0a15b8b4e9e98de61a029479fc658a0f3d53b3d/assess.py",
"visit_date": "2022-12-13T03:58:06.071793"
} | 2.390625 | stackv2 |
# Import Packages
import pandas as pd
import os
import sklearn as sk
import numpy as np
import pickle
from imblearn.over_sampling import ADASYN
from sklearn.metrics import roc_curve, auc
# Global Vars
pathto_data = '/app_io'
pathto_spacefeats = os.path.join(pathto_data, 'spatial_features_model', 'output')
pathto_damdata = os.path.join(pathto_data, 'phase_1_optimization', 'input', 'MA_U.csv')
pathto_deployidx = os.path.join(pathto_data, 'phase_1_optimization', 'input', 'deploy_idx.pkl')
pathto_phase1_results = os.path.join(pathto_data, 'phase_1_results_convert', 'output', 'results.csv')
pathto_solution_classifications = os.path.join(pathto_data, 'phase_2_assessment', 'output', 'solution_classifications')
pathto_assessment_objectives = os.path.join(pathto_data, 'phase_2_assessment', 'output', 'assessment_objectives')
parameter_names = ['N_length', 'N_width', 'n_estimators', 'min_samples_split', 'min_samples_leaf',
'min_weight_fraction_leaf', 'max_depth', 'max_features', 'max_leaf_nodes']
objective_names = ['P2_accuracy', 'P2_FPR', 'P2_TPR', 'P1_AUROCC']
feature_names = ['Dam Height (ft)', 'Dam Length (ft)', 'Reservoir Size (acre-ft)', 'Maximum Downstream Slope (%)',
'Downstream Houses', 'Downstream Population', 'Building Exposure ($1000)',
'Building Footprint (1000 sq. ft.)', 'Content Exposure ($1000)']
predicted_name = 'Hazard'
positive_lab = 'NH'
def parameter_converter(params):
"""
Convert parameter to valid types
:param params: tuple
current parameters of default types
:return: dict
All the corresponding parameters in required types
"""
# Parse Ints
for i, val in enumerate(params):
if val.is_integer():
params[i] = int(val)
# Convert to Dictionary
param_dict = dict(zip(parameter_names, params))
return param_dict
def get_features(param_dict):
"""
Retrive the corresponding spatial and non-spatial feature values
:param param_dict: dict
All the corresponding simulation parameters
:return: DataFrame
Spatial and non-spatial dam hazard feature values
"""
# Import Spatial Features
df_name = 'N_length_' + str(param_dict['N_length']) + '_N_width_' + str(param_dict['N_width'])
space_feats = pd.read_hdf(os.path.join(pathto_spacefeats, 'spatial_feats.h5'), df_name)
# Import Non-Spatial Features
data = pd.read_csv(pathto_damdata)
# Merge Features
data = space_feats.join(data)
data.index = data['RECORDID']
# Rename Columns
data = data.rename(index=str, columns={'HAZARD': predicted_name, 'DAM_HEIGHT': feature_names[0],
'DAM_LENGTH': feature_names[1], 'NORMAL_STORAGE': feature_names[2],
'Slope_max': feature_names[3], 'hous_sum': feature_names[4],
'pop_sum': feature_names[5], 'buil_sum': feature_names[6],
'foot_sum': feature_names[7], 'cont_sum': feature_names[8]})
# Extract Features
data = data[feature_names+[predicted_name]]
# Export
return data
def preprocessor(df):
"""
Processing the feature values before classification
:param df: DataFrame
Feature values
:return: DataFrame
Processed feature values
"""
# Combine Categories
df = df.replace(to_replace=['L', 'S', 'H'], value=['NH', 'NH', 'H'])
# Replace nans with median
df = df.fillna(df.median())
# Specify Objective
y = df[predicted_name]
# Shape Data
X = np.array(df[feature_names])
y = np.array(y)
return X, y
def train_model(ml_params, data):
"""
Train the random forest to the current set of hyperparameters (no cross-validation)
:param ml_params: dict
Current set of hyperparameters
:param data: DataFrame
The current set of dams with features and true hazard classifications
:return: RandomForestClassifier
Trained random forest
"""
# Initialized Vars
random_state = 1008
# Process Data
X, y = preprocessor(data)
# Resample the training data to deal with class imbalance
method = ADASYN(random_state=random_state)
X_res, y_res = method.fit_sample(X, y)
# Create Model
clf = sk.ensemble.RandomForestClassifier(n_jobs=-1, random_state=random_state,
n_estimators=ml_params['n_estimators'],
min_samples_split=ml_params['min_samples_split'],
min_samples_leaf=ml_params['min_samples_leaf'],
min_weight_fraction_leaf=ml_params['min_weight_fraction_leaf'],
max_depth=ml_params['max_depth'],
max_features=ml_params['max_features'],
max_leaf_nodes=ml_params['max_leaf_nodes'])
# Fit model to train data
clf.fit(X_res, y_res)
# Export
return clf
def predict_values(model, data):
"""
Predict values based on a trained random forest
:param model: RandomForestClassifier
Trained random forest
:param data: DataFrame
The current set of dams with features and true hazard classifications
:return: DataFrame
The current set of dams with features, true hazard classifications, and predicted hazard
classifications
"""
# Process Data
X, y = preprocessor(data)
# Predicted Values
y_pred = model.predict(X)
# Append Predicted Value
data['True Hazard Class'] = y
data['Predicted Hazard Class'] = y_pred
# Area Under ROC Curve
y_score = model.predict_proba(X)[:, 1]
false_positive, true_positive, _ = roc_curve(y, y_score, pos_label=positive_lab)
AUROCC = auc(false_positive, true_positive)
data['AUROCC'] = AUROCC
return data
def CM(row):
"""
Confusion matrix function to classify true positive, false positive, false negative, or true negative
classifications
:param row: Series
Predicted and true classification of the current dam being evaluated
:return: str
Classification type
"""
if row['True Hazard Class'] == 'H' and row['Predicted Hazard Class'] == 'H':
return 'TN'
elif row['True Hazard Class'] == 'NH' and row['Predicted Hazard Class'] == 'NH':
return 'TP'
elif row['True Hazard Class'] == 'H' and row['Predicted Hazard Class'] == 'NH':
return 'FP'
elif row['True Hazard Class'] == 'NH' and row['Predicted Hazard Class'] == 'H':
return 'FN'
def get_obj(df):
"""
Calculate objective values
:param df: dataframe
Phase 2 classifications of current solution
:return:
Phase 2 objective values
"""
# Extract Errors
TP = df['error'].value_counts()['TP']
TN = df['error'].value_counts()['TN']
FP = df['error'].value_counts()['FP']
FN = df['error'].value_counts()['FN']
# Calculate Objectives
accuracy = (TP+TN)/(TP+TN+FP+FN)
FPR = FP/(FP+TN)
TPR = TP/(TP+FN)
AUROCC = df['AUROCC'][0]
return pd.Series([FN, FP, TN, TP, accuracy, FPR, TPR, AUROCC], index=['P2_FN', 'P2_FP', 'P2_TN', 'P2_TP']+objective_names)
def simulation(vars, name):
"""
Evaluate a dam hazard potential 'simulation' with a given set of spatial parameters and random forest
hyperparameters
:param vars: tuple
set of spatial and nonspatial parameters
:param name: str
Name of current solution
:return: Series
Phase 2 objective values
"""
# Convert Parameters
param_dict = parameter_converter(vars)
# Get Features
data = get_features(param_dict)
# Get Deployment Indexes
with open(pathto_deployidx, 'rb') as f:
deploy_idx = pickle.load(f)
# Train Model on All But Deployment Features
model = train_model(param_dict, data.drop(deploy_idx))
# Predict Deployment Features
df = predict_values(model, data.loc[deploy_idx])
# Compute Confusion Matrix
df['error'] = df.apply(CM, axis=1)
# Export Classifications
df.to_csv(os.path.join(pathto_solution_classifications, 'solution_'+str(int(name)) + '.csv'), index=False)
# Compute Objectives
objs = get_obj(df)
print(objs)
return objs
def main():
# Import Reference Set
df = pd.read_table(pathto_phase1_results, sep=',').infer_objects()
# Use All Solutions
df['solution_num'] = list(df.index)
# Run Simulation
objs_df = df.apply(lambda row: simulation(row[parameter_names].tolist(), row['solution_num']), axis=1)
rep_df = pd.concat([df, objs_df], axis=1)
# Export Representative Solution
rep_df.to_csv(os.path.join(pathto_assessment_objectives, 'assessment_results.csv'), index=False, header=True, sep=',')
return 0
if __name__ == '__main__':
main()
| 238 | 37.82 | 126 | 15 | 2,175 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_6951a5a14fd5279c_3e755086", "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": 209, "line_end": 209, "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/tmpb8jm_z1l/6951a5a14fd5279c.py", "start": {"line": 209, "col": 22, "offset": 8176}, "end": {"line": 209, "col": 36, "offset": 8190}, "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"
] | [
209
] | [
209
] | [
22
] | [
36
] | [
"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"
] | assess.py | /assess.py | kravitsjacob/phase_2_assessment | MIT | |
2024-11-18T18:05:52.919914+00:00 | 1,625,584,497,000 | 7d79c06f8af3e0bcfa88e9703b177b44978569de | 2 | {
"blob_id": "7d79c06f8af3e0bcfa88e9703b177b44978569de",
"branch_name": "refs/heads/master",
"committer_date": 1625584497000,
"content_id": "162fc4cf197c00de108895d7889162b40d2c8cc9",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "279c70e0c1ee0625bf0940d6644def5c6f294c43",
"extension": "py",
"filename": "sources.py",
"fork_events_count": 0,
"gha_created_at": 1627422472000,
"gha_event_created_at": 1627422472000,
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 390135802,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3603,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/registry/sources.py",
"provenance": "stack-edu-0054.json.gz:568847",
"repo_name": "yongleyuan/open-science-pool-registry",
"revision_date": 1625584497000,
"revision_id": "6006e5bff640119ed9cd4bdb1afc8dccc3890dd0",
"snapshot_id": "8ca81a4c1ed5b4047b1a822948ca8d0b718fa5ac",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yongleyuan/open-science-pool-registry/6006e5bff640119ed9cd4bdb1afc8dccc3890dd0/registry/sources.py",
"visit_date": "2023-06-28T02:23:05.147816"
} | 2.34375 | stackv2 | import re
try: # py3
from configparser import ConfigParser
except ImportError: # py2
from ConfigParser import ConfigParser
import xml.etree.ElementTree as ET
import http.client
import urllib.error
import urllib.request
from flask import current_app, request
from .exceptions import ConfigurationError
TOPOLOGY_RG = "https://topology.opensciencegrid.org/rgsummary/xml"
def get_user_info():
try:
return current_app.config["USER_INFO_FAKE"]
except:
pass
result = {
"idp": request.environ.get("OIDC_CLAIM_idp_name", None),
"id": request.environ.get("OIDC_CLAIM_osgid", None),
"name": request.environ.get("OIDC_CLAIM_name", None),
"email": request.environ.get("OIDC_CLAIM_email", None)
}
current_app.logger.debug("Authenticated user info is {}".format(str(result)))
return result
def is_signed_up(user_info):
return user_info.get("id")
def get_sources(user_info):
"""
Query topology to get a list of valid CEs and their managers
"""
osgid = user_info.get("id")
if not osgid:
return []
# URL for all Production CE resources
# topology_url = TOPOLOGY_RG + '?gridtype=on&gridtype_1=on&service_on&service_1=on'
# URL for all Execution Endpoint resources
topology_url = TOPOLOGY_RG + '?service=on&service_157=on'
try:
response = urllib.request.urlopen(topology_url)
topology_xml = response.read()
except (urllib.error.URLError, http.client.HTTPException):
raise TopologyError('Error retrieving OSG Topology registrations')
try:
topology_et = ET.fromstring(topology_xml)
except ET.ParseError:
if not topology_xml:
msg = 'OSG Topology query returned empty response'
else:
msg = 'OSG Topology query returned malformed XML'
raise TopologyError(msg)
os_pool_resources = []
resources = topology_et.findall('./ResourceGroup/Resources/Resource')
if not resources:
raise TopologyError('Failed to find any OSG Topology resources')
for resource in resources:
try:
fqdn = resource.find('./FQDN').text.strip()
except AttributeError:
# skip malformed resource missing an FQDN
continue
active = False
try:
active = resource.find('./Active').text.strip().lower() == "true"
except AttributeError:
continue
if not active:
continue
try:
services = [service.find("./Name").text.strip()
for service in resource.findall("./Services/Service")]
except AttributeError:
continue
if ('Execution Endpoint' not in services) and ('Submit Node' not in services):
continue
try:
admin_contacts = [contact_list.find('./Contacts')
for contact_list in resource.findall('./ContactLists/ContactList')
if contact_list.findtext('./ContactType', '').strip() == 'Administrative Contact']
except AttributeError:
# skip malformed resource missing contacts
continue
for contact_list in admin_contacts:
for contact in contact_list.findall("./Contact"):
if contact.findtext('./CILogonID', '').strip() == osgid:
os_pool_resources.append(fqdn)
return os_pool_resources
SOURCE_CHECK = re.compile(r"^[a-zA-Z][-.0-9a-zA-Z]*$")
def is_valid_source_name(source_name):
return bool(SOURCE_CHECK.match(source_name))
| 114 | 30.61 | 112 | 19 | 777 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_2d92585431a64ceb_1c0d98ab", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 8, "line_end": 8, "column_start": 1, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpb8jm_z1l/2d92585431a64ceb.py", "start": {"line": 8, "col": 1, "offset": 135}, "end": {"line": 8, "col": 35, "offset": 169}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
8
] | [
8
] | [
1
] | [
35
] | [
"A04:2017 - XML External Entities (XXE)"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service."
] | [
7.5
] | [
"LOW"
] | [
"MEDIUM"
] | sources.py | /registry/sources.py | yongleyuan/open-science-pool-registry | Apache-2.0 | |
2024-11-18T18:05:53.886832+00:00 | 1,514,819,429,000 | 360ee762aee9a172e998864ffe800eb47944b45b | 2 | {
"blob_id": "360ee762aee9a172e998864ffe800eb47944b45b",
"branch_name": "refs/heads/master",
"committer_date": 1514819429000,
"content_id": "de0cc0d573d2a9d26887c60b416eb7d3793d2e74",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "087ba04bd4fae34a3f90b002b6fcb736728a4467",
"extension": "py",
"filename": "collections.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 93305291,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4545,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/freestyle/collections.py",
"provenance": "stack-edu-0054.json.gz:568859",
"repo_name": "thautwarm/Stardust",
"revision_date": 1514819429000,
"revision_id": "3fa3927792958c02e51e4e5a6a5c74b6b2ecf37d",
"snapshot_id": "bbb9593a1419f7e2f23af230436dd2603c24cba0",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/thautwarm/Stardust/3fa3927792958c02e51e4e5a6a5c74b6b2ecf37d/freestyle/collections.py",
"visit_date": "2021-01-23T16:49:47.024514"
} | 2.421875 | stackv2 | from typing import List, Dict, Any
from collections import defaultdict, deque
from itertools import tee
import pandas as pd
import numpy as np
import numba as nb
from copy import deepcopy
from functools import reduce
class op:
@staticmethod
def mul(a, b): return a * b
def sub(a, b): return a - b
def add(a, b): return a + b
def div(a, b): return a / b
def mod(a, b): return a % b
def anno(a, b): return a@b
def e_method(method, a, b): return eval(f"a.{method}(b)")
def e_func(func, a, b): return eval(f"{func}(a,b)")
class block:
pass
class globals_manager:
def __new__(self, global_vars=None):
try:
return self.globals_
except AttributeError:
self.globals_ = global_vars
def lisp(*targs, **kwargs):
argNums = len(targs)
if not argNums:
return None
elif argNums is 1:
value, = targs
return value
else:
f, *ttargs = targs
ttargs = map(lambda x: lisp(x), ttargs)
kw = dict(map(lambda x: (x, lisp(kwargs[x])), kwargs))
return f(*ttargs, **kw)
class richIterator:
def __init__(self, *args, **kwargs):
super(richIterator, self).__init__(*args, **kwargs)
self.recovery_vars = {}
def filter(self, f):
return richGenerator((each for each in self if f(each)))
def recovery(self):
globals_vars = globals_manager(None)
if self.recovery_vars:
recovery_vars = self.recovery_vars
for key in recovery_vars:
globals_vars[key] = recovery_vars[key]
def __matmul__(self, f):
return f(self)
def groupBy(self, f, containerType=list):
if containerType is list:
res: Dict[Any, eval("self.__class__")] = defaultdict(
eval("self.__class__"))
for each in self:
res[f(each)].append(each)
elif containerType is set:
res: Dict = dict()
for each in self:
key = f(each)
if key not in res:
res[key] = each
else:
return TypeError(f"method .groupBy for containerType '{containerType}'\
is not defined yet,\
you can define it by yourself.")
return richDict(res)
def let(self, **kwargs):
globals_vars = globals_manager(None)
if 'this' not in kwargs:
kwargs['this'] = self
for key in kwargs:
if key in globals_vars:
value = globals_vars[key]
self.recovery_vars[key] = value if value != "this" else self
value = kwargs[key]
globals_vars[key] = value if value != "this" else self
return self
def then(self, *args, **kwargs):
ret = lisp(*args, **kwargs)
self.recovery()
return ret
def map(self, f, *args, **kwargs):
args = (self,) + args
return richIterator.thenMap(f, *args, **kwargs)
def mapIndexed(self, f: "function<Int,T>", *args, **kwargs):
args = (range(len(self)), self) + args
return richIterator.thenMap(f, *args, *kwargs)
def connectedWith(self,cases:tuple):
def test(item):
for case_judge, case_action in cases:
if case_action(item):
return case_action(item)
return None
return richGenerator(map(test, self))
def tolist(self):
return [each for each in self]
def totuple(self):
return tuple(each for each in self)
def toset(self):
return set(self)
def todict(self):
return dict(zip(self))
def zip(self, iterator):
return zip(self, iterator)
def togen(self):
return richGenerator(self)
@staticmethod
def thenMap(f, *args, **kwargs):
if kwargs:
kwargsKeys = kwargs.keys()
kwargsValues = zip(* kwargs.values())
args = zip(*args)
if kwargs:
return richGenerator(f(*arg, **dict(zip(kwargsKeys, kwargsValue))) for arg, kwargsValue in zip(args, kwargsValues))
else:
return richGenerator(f(*arg) for arg in args)
class generator:
def __init__(self, iterable):
self.obj = iterable
def __iter__(self):
for each in self.obj:
yield each
def togen(self):
return self.obj
class richGenerator(richIterator, generator):
pass
class richDict(richIterator, dict):
pass
| 176 | 24.82 | 127 | 19 | 1,075 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_ab989d7f8edafb13_5e4e872b", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 30, "line_end": 30, "column_start": 40, "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/tmpb8jm_z1l/ab989d7f8edafb13.py", "start": {"line": 30, "col": 40, "offset": 488}, "end": {"line": 30, "col": 62, "offset": 510}, "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_ab989d7f8edafb13_1ab10e57", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 33, "line_end": 33, "column_start": 36, "column_end": 56, "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/tmpb8jm_z1l/ab989d7f8edafb13.py", "start": {"line": 33, "col": 36, "offset": 548}, "end": {"line": 33, "col": 56, "offset": 568}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.baseclass-attribute-override_ab989d7f8edafb13_d09cadcf", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.baseclass-attribute-override", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Class richGenerator inherits from both `richIterator` and `generator` which both have a method named `$F`; one of these methods will be overwritten.", "remediation": "", "location": {"file_path": "unknown", "line_start": 172, "line_end": 172, "column_start": 7, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/tutorial/classes.html#multiple-inheritance", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.baseclass-attribute-override", "path": "/tmp/tmpb8jm_z1l/ab989d7f8edafb13.py", "start": {"line": 172, "col": 7, "offset": 4450}, "end": {"line": 172, "col": 20, "offset": 4463}, "extra": {"message": "Class richGenerator inherits from both `richIterator` and `generator` which both have a method named `$F`; one of these methods will be overwritten.", "metadata": {"category": "correctness", "references": ["https://docs.python.org/3/tutorial/classes.html#multiple-inheritance"], "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | 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"
] | [
30,
33
] | [
30,
33
] | [
40,
36
] | [
62,
56
] | [
"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"
] | collections.py | /freestyle/collections.py | thautwarm/Stardust | Apache-2.0 | |
2024-11-18T18:05:56.044170+00:00 | 1,486,668,271,000 | 503503ca77386d7ad226326d25fcb3c96f7f2b8e | 3 | {
"blob_id": "503503ca77386d7ad226326d25fcb3c96f7f2b8e",
"branch_name": "refs/heads/master",
"committer_date": 1486668271000,
"content_id": "8048eed32403f9de7e81c67432f8bff406690966",
"detected_licenses": [
"MIT"
],
"directory_id": "d728338358b7acc7a40c4717417a81bfd0088e5c",
"extension": "py",
"filename": "btsoot.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": 13445,
"license": "MIT",
"license_type": "permissive",
"path": "/btsoot.py",
"provenance": "stack-edu-0054.json.gz:568884",
"repo_name": "bbartsch/btsoot",
"revision_date": 1486668271000,
"revision_id": "f674f1e09af6655e3107a732cfbaa647beabed4d",
"snapshot_id": "c5ac989226e2a7e291e8f70c50db721e9edd3041",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bbartsch/btsoot/f674f1e09af6655e3107a732cfbaa647beabed4d/btsoot.py",
"visit_date": "2022-06-02T07:23:39.894812"
} | 2.625 | stackv2 | #!/usr/bin/env python3.6
#CONFIGURATION################################################
#STORAGE CONFIG
configpath = ""
scanstorage = ""
#SAFETY GUARD CONFIG
safetyguard = True
#Input min value in percent for cloning file override safety guard.
#Backup will be aborted if change counter passes this value.
minwarningvalue = 75
#COPY CONFIG
copypath = ""
##############################################################
#DO NOT EDIT BELOW HERE!
import os, sys, time, shutil, zlib
#STARTUP CODE
if configpath == "":
configpath = "/etc/btsoot/btsoot.conf"
if scanstorage == "":
scanstorage = "/etc/btsoot/scans/"
if copypath == "":
copypath = "/usr/local/bin/btsoot-copy"
if os.path.exists("/etc/btsoot") == True:
pass
else:
try:
os.makedirs("/etc/btsoot/scans")
except PermissionError:
print("BTSOOT needs root permissions")
sys.exit()
class color:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
#DEBUG FUNCTION AND SETVAR
debug = False
if "--debug" in sys.argv:
debug = True
def dprint(message):
if debug == True:
print(f"DEBUG: {message}")
def shouldcontinue(quit = True):
if input("Should i continue? (yes/No)") == "yes":
return 0
else:
if quit == True:
sys.exit()
else:
return 1
def crc(filepath):
previous = 0
try:
for line in open(filepath,"rb"):
previous = zlib.crc32(line, previous)
except OSError:
print("CRC ERROR: OSERROR")
return "%X"%(previous & 0xFFFFFFFF)
usage = f"""USAGE: {sys.argv[0]} <commands>
add <name> <path> <server/local>\tadd block
rm <name>\t\t\t\tremove added block
scan <name>\t\t\t\tscan added block
backup <name>\t\t\t\tbackup scanned block
update_dependencies\t\t\tupdate the needed libraries
"""
def split(string, splitters): #MAY RESOLVE ALL PROBLEMS WITH CSV
final = [string]
for x in splitters:
for i,s in enumerate(final):
if x in s and x != s:
left, right = s.split(x, 1)
final[i] = left
final.insert(i + 1, x)
final.insert(i + 2, right)
return final
def scandirectory(walk_dir, scanfile, verbose = False):
try:
current_scan = []
for root, subdirs, files in os.walk(walk_dir):
current_scan.extend([f"{root}\n"])
for filename in files:
file_path = os.path.join(root, filename)
checksum = crc(file_path)
current_scan.extend([f"{file_path},{checksum}\n"])
with open(scanfile, "w") as current_scan_file:
current_scan_file.writelines(current_scan)
except FileNotFoundError:
if verbose == True:
print(color.FAIL + "SCAN ERROR: FILE NOT FOUND" + color.ENDC)
def main():
try:
if sys.argv[1] == "add":
name = sys.argv[2]
path = sys.argv[3]
server = sys.argv[4]
with open(configpath, "a") as conf:
conf.write(f"{name},{path},{server}\n")
elif sys.argv[1] == "rm":
name = sys.argv[2]
try:
lines = []
with open(configpath, "r") as conf:
lines = conf.readlines()
with open(configpath, "w") as conf:
for line in lines:
split_line = split(line, ",")
if split_line[0] != name:
conf.write(line)
except FileNotFoundError:
print(color.FAIL + "Configfile not found." + color.ENDC)
print("Create one with 'add'.")
elif sys.argv[1] == "list":
try:
with open(configpath, "r") as conf:
for line in conf:
split_line = split(line, ",")
print(f"BLOCKNAME: {split_line[0]}")
print(f"\tSRC: {split_line[2]}")
print(f"\tDEST: {split_line[4].rsplit()}")
except FileNotFoundError:
print(color.FAIL + "Configfile not found." + color.ENDC)
print("Create one with 'add'.")
elif sys.argv[1] == "backup":
#REMOVE ENTREE FROM BTSOOT CONFIG
searched_path = None
name = sys.argv[2]
scanfilename = "{}_{}.btsscan".format(int(time.time()), name)
try:
path = ""
with open(configpath, "r") as conf:
for line in conf:
split_line = split(line, ",")
path = split_line[2].rstrip()
print(color.OKBLUE + f"Executing scan for block {sys.argv[2]}" + color.ENDC)
except FileNotFoundError:
print(color.FAIL + "Configfile not found." + color.ENDC)
print("Create one with 'add'.")
#SCAN
scandirectory(path, f"{scanstorage}{scanfilename}", False)
#LIST FILES TO FIND SCANFILES
#SORT OUT ANY UNINTERESTING FILES
scanfilelist = []
#LIST DIRS
dirs = os.listdir(scanstorage)
number_of_files = 0
#SEARCH FOR SCANFILES
for singlefile in dirs:
blockname = split(singlefile, ["_", "."])
try:
if blockname[4] == "btsscan" and blockname[2] == sys.argv[2]:
number_of_files = number_of_files + 1
scanfilelist.append(singlefile)
except IndexError:
pass
#LIST CONFIG ENTREES
serverlocation = ""
sourcelocation = ""
with open(configpath, "r") as conf:
for line in conf:
split_line = split(line, ",")
if split_line[0] == sys.argv[2]:
sourcelocation = split_line[2]
serverlocation = split_line[4].rstrip() #Last entree has nline
else:
print(color.FAIL + f"No block {sys.argv[2]} found." + color.ENDC)
if number_of_files == 1:
print("One scan found. Complete backup of ALL data will be created.")
print(color.OKBLUE + "Executing datatransfer." + color.ENDC)
with open(f"{scanstorage}{scanfilename}", "r") as scan:
lines = scan.readlines()
for line in lines:
path = split(line, ",")
if len(path) == 1:
os.makedirs(f"{serverlocation}{line.rstrip()}", exist_ok=True)
elif len(path) == 3:
path = path[0]
path = path.replace(" ", "\ ")
path = path.replace("(", "\(")
path = path.replace(")", "\)")
status = os.system(f"{copypath} {path} {serverlocation}{path}")
exit_status = os.WEXITSTATUS(status)
if exit_status != 0:
print(color.FAIL + f"COPY ERROR: {exit_status}" + color.ENDC)
else:
print(color.FAIL + "Corrupt: " + line + color.ENDC)
sys.exit()
print("Sufficient number of scan files were found.")
splitted_timestamp = []
#FIND LATEST TWO FILES
#SPLIT EVERY FILE NAME TO GAIN TIMESTAMP
for scanfile in scanfilelist:
temp = split(scanfile, "_")
splitted_timestamp.append(int(temp[0]))
#GETS LATEST SCANFILE'S TIMESTAMP
latest_timestamp = max(splitted_timestamp)
#SETS MAX VALUE TO -1 TO FIND SECOND HIGHEST VALUE
listcounter = 0
for timestamp in splitted_timestamp:
if timestamp == latest_timestamp:
splitted_timestamp[listcounter] = -1
listcounter = listcounter + 1
#GET PREVIOUS FILE'S TIMESTAMP
previous_timestamp = max(splitted_timestamp)
dircounter = 0
latest_scan_array_index = -1
previous_scan_array_index = -1
for singlefile in scanfilelist:
temp = split(singlefile, "_")
if int(temp[0]) == latest_timestamp:
latest_scan_array_index = dircounter
elif int(temp[0]) == previous_timestamp:
previous_scan_array_index = dircounter
dircounter = dircounter + 1
print("Latest scan: " + scanfilelist[latest_scan_array_index])
print("Previous scan: " + scanfilelist[previous_scan_array_index] + "\n")
#COMPARE THE TWO FILES AGAINST EACH OTHER
latest_scan_fd = open(f"{scanstorage}{scanfilelist[latest_scan_array_index]}", "r")
previous_scan_fd = open(f"{scanstorage}{scanfilelist[previous_scan_array_index]}", "r")
transmit_list = []
latest_scan = latest_scan_fd.readlines()
previous_scan = previous_scan_fd.readlines()
file_same = 0
file_new = 0
file_total_old = 0
file_total_latest = 0
file_deleted = 0 #DELETED LINES COUNTER
#REMOVE DELETED OR CHANGED FILES
for oldline in previous_scan:
if oldline not in latest_scan:
checkifdir = split(oldline, ",")
if len(checkifdir) == 1:
#IF DIRECTORY, HASH WILL BE "directory".
#THAT IS NEEDED DURING DIRECTORY REMOVAL
transmit_list.extend([f"{oldline.rstrip()},directory,-\n"])
print(color.FAIL + f"- {oldline}" + color.ENDC, end='')
else:
transmit_list.extend([f"{oldline.rstrip()},-\n"])
print(color.FAIL + f"- {oldline}" + color.ENDC, end='')
file_deleted = file_deleted + 1
file_total_old = file_total_old + 1
#FIND OUT CHANGED OR NEW FILES
for line in latest_scan:
if line in previous_scan:
file_same = file_same + 1
else:
checkifdir = split(line, ",")
if len(checkifdir) == 1:
#IF DIRECTORY, HASH WILL BE "directory".
#THAT IS NEEDED DURING DIRECTORY CREATION
transmit_list.extend([f"{line.rstrip()},directory,+\n"])
else:
transmit_list.extend([f"{line.rstrip()},+\n"])
file_new = file_new + 1
file_total_latest = file_total_latest + 1
#FILE STATS
print(f"\nUnchanged files: {file_same}")
print(f"New/Changed files: {file_new}")
print(f"Deleted files: {file_deleted}")
print(f"Total files in latest scan: {file_total_latest}")
print(f"Total files in previous scan: {file_total_old}")
#SAFETY GUARD: SEE ISSUE #8
if safetyguard == True:
if file_deleted >= file_total_old / 100 * minwarningvalue:
print(f"SAFETY GUARD: MORE THAN {minwarningvalue}% DELETED")
shouldcontinue()
elif file_total_latest == 0:
print("SAFETY GUARD: NO FILES FOUND.")
shouldcontinue()
else:
pass
#TRANSMITTER
print(color.OKBLUE + "Executing datatransfer." + color.ENDC)
for line in transmit_list:
line = split(line.rstrip(), ",")
if len(line) > 5:
print(color.FAIL + f"Cannot backup file {line}." + color.ENDC)
print("Path would brick BTSOOT.")
else:
if line[4] == "-":
if line[2] == "directory":
try:
shutil.rmtree(f"{serverlocation}{line[0]}")
except FileNotFoundError:
pass
else:
try:
os.remove(f"{serverlocation}{line[0]}")
except FileNotFoundError:
pass
elif line[4] == "+":
if line[2] == "directory":
os.makedirs(f"{serverlocation}{line[0]}", exist_ok=True)
else:
path = line[0]
path = path.replace(" ", "\ ")
path = path.replace("(", "\(")
path = path.replace(")", "\)")
status = os.system(f"{copypath} {path} {serverlocation}{path}")
exit_status = os.WEXITSTATUS(status)
if exit_status != 0:
print(color.FAIL + f"COPY ERROR: {exit_status}"+ color.ENDC)
else:
print(color.WARNING + "TRANSMIT CORRUPTION:" + color.ENDC)
print(color.WARNING + line + color.ENDC)
previous_scan_fd.close()
latest_scan_fd.close()
print(color.OKGREEN + "Done." + color.ENDC)
elif sys.argv[1] == "restore":
print(color.FAIL + "WARNING! This will remove all files from source.")
print("IF NO FILES ARE FOUND INSIDE THE BACKUP FOLDER, EVERYTHING IS LOST.")
print("Abort using CTRL+C within 15 seconds." + color.ENDC)
if not "--override" in sys.argv:
time.sleep(15)
serverlocation = ""
sourcelocation = ""
with open(configpath, "r") as conf:
for line in conf:
split_line = split(line, ",")
if split_line[0] == sys.argv[2]:
sourcelocation = split_line[2]
serverlocation = split_line[4].rstrip()
print(color.OKBLUE + "Deleting source." + color.ENDC)
shutil.rmtree(sourcelocation)
os.makedirs(sourcelocation)
print(color.OKBLUE + "Executing datatransfer." + color.ENDC)
print("This may take a long time.")
#LIST FILES TO FIND SCANFILES
#SORT OUT ANY UNINTERESTING FILES
scanfilelist = []
#LIST DIRS
dirs = os.listdir(scanstorage)
number_of_files = 0
#SEARCH FOR SCANFILES
for singlefile in dirs:
blockname = split(singlefile, ["_", "."])
try:
if blockname[4] == "btsscan" and blockname[2] == sys.argv[2]:
number_of_files = number_of_files + 1
scanfilelist.append(singlefile)
except IndexError:
pass
splitted_timestamp = []
#FIND LATEST TWO FILES
#SPLIT EVERY FILE NAME TO GAIN TIMESTAMP
for scanfile in scanfilelist:
temp = split(scanfile, "_")
splitted_timestamp.append(int(temp[0]))
#GETS LATEST SCANFILE'S TIMESTAMP
latest_timestamp = max(splitted_timestamp)
dircounter = 0
latest_scan_array_index = -1
previous_scan_array_index = -1
for singlefile in scanfilelist:
temp = split(singlefile, "_")
if int(temp[0]) == latest_timestamp:
latest_scan_array_index = dircounter
dircounter = dircounter + 1
print("Latest scan: " + scanfilelist[latest_scan_array_index])
latest_scan_fd = open(f"{scanstorage}{scanfilelist[latest_scan_array_index]}", "r")
for line in latest_scan_fd:
split_line = split(line, ",")
if len(split_line) == 1:
path = split_line[0]
path = path.rstrip()
os.makedirs(path, exist_ok=True)
elif len(split_line) == 3:
path = split_line[0]
path = path.replace(" ", "\ ")
path = path.replace("(", "\(")
path = path.replace(")", "\)")
status = os.system(f"/etc/btsoot/copy {serverlocation}{path} {path}")
exit_status = os.WEXITSTATUS(status)
if exit_status != 0:
print(color.FAIL + f"COPY ERROR: {exit_status}"+ color.ENDC)
else:
pass
latest_scan_fd.close()
print(color.OKGREEN + "Done." + color.ENDC)
else:
print(usage)
except IndexError:
print("INDEX ERROR")
print(usage)
sys.exit()
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\nQuitting.\n")
sys.exit()
| 473 | 27.42 | 90 | 29 | 3,794 | python | [{"finding_id": "semgrep_rules.python.lang.correctness.useless-eqeq_0e922a795ec58cd2_35ffc569", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.useless-eqeq", "finding_type": "correctness", "severity": "low", "confidence": "medium", "message": "This expression is always True: `configpath == configpath` or `configpath != configpath`. If testing for floating point NaN, use `math.isnan(configpath)`, or `cmath.isnan(configpath)` if the number is complex.", "remediation": "", "location": {"file_path": "unknown", "line_start": 27, "line_end": 27, "column_start": 4, "column_end": 20, "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/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 27, "col": 4, "offset": 506}, "end": {"line": 27, "col": 20, "offset": 522}, "extra": {"message": "This expression is always True: `configpath == configpath` or `configpath != configpath`. If testing for floating point NaN, use `math.isnan(configpath)`, or `cmath.isnan(configpath)` 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.correctness.useless-eqeq_0e922a795ec58cd2_25df31ec", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.useless-eqeq", "finding_type": "correctness", "severity": "low", "confidence": "medium", "message": "This expression is always True: `scanstorage == scanstorage` or `scanstorage != scanstorage`. If testing for floating point NaN, use `math.isnan(scanstorage)`, or `cmath.isnan(scanstorage)` if the number is complex.", "remediation": "", "location": {"file_path": "unknown", "line_start": 29, "line_end": 29, "column_start": 4, "column_end": 21, "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/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 29, "col": 4, "offset": 567}, "end": {"line": 29, "col": 21, "offset": 584}, "extra": {"message": "This expression is always True: `scanstorage == scanstorage` or `scanstorage != scanstorage`. If testing for floating point NaN, use `math.isnan(scanstorage)`, or `cmath.isnan(scanstorage)` 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.correctness.useless-eqeq_0e922a795ec58cd2_86d7eb67", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.useless-eqeq", "finding_type": "correctness", "severity": "low", "confidence": "medium", "message": "This expression is always True: `copypath == copypath` or `copypath != copypath`. If testing for floating point NaN, use `math.isnan(copypath)`, or `cmath.isnan(copypath)` if the number is complex.", "remediation": "", "location": {"file_path": "unknown", "line_start": 31, "line_end": 31, "column_start": 4, "column_end": 18, "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/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 31, "col": 4, "offset": 625}, "end": {"line": 31, "col": 18, "offset": 639}, "extra": {"message": "This expression is always True: `copypath == copypath` or `copypath != copypath`. If testing for floating point NaN, use `math.isnan(copypath)`, or `cmath.isnan(copypath)` 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.best-practice.unspecified-open-encoding_0e922a795ec58cd2_065baeb0", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 112, "line_end": 112, "column_start": 8, "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/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 112, "col": 8, "offset": 2431}, "end": {"line": 112, "col": 27, "offset": 2450}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_0e922a795ec58cd2_f0fe3d57", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 125, "line_end": 125, "column_start": 9, "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/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 125, "col": 9, "offset": 2759}, "end": {"line": 125, "col": 30, "offset": 2780}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_0e922a795ec58cd2_308eaccd", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the 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": 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/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 133, "col": 10, "offset": 2918}, "end": {"line": 133, "col": 31, "offset": 2939}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_0e922a795ec58cd2_a6cdaffe", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the 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": 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/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 135, "col": 10, "offset": 2988}, "end": {"line": 135, "col": 31, "offset": 3009}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_0e922a795ec58cd2_ebb534f3", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 148, "line_end": 148, "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/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 148, "col": 10, "offset": 3311}, "end": {"line": 148, "col": 31, "offset": 3332}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_0e922a795ec58cd2_3596a937", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 166, "line_end": 166, "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/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 166, "col": 10, "offset": 3872}, "end": {"line": 166, "col": 31, "offset": 3893}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_0e922a795ec58cd2_54df550a", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 201, "line_end": 201, "column_start": 9, "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/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 201, "col": 9, "offset": 4825}, "end": {"line": 201, "col": 30, "offset": 4846}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_0e922a795ec58cd2_5b31c710", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 214, "line_end": 214, "column_start": 10, "column_end": 51, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 214, "col": 10, "offset": 5318}, "end": {"line": 214, "col": 51, "offset": 5359}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_0e922a795ec58cd2_66d38cb3", "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": 225, "line_end": 225, "column_start": 17, "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://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/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 225, "col": 17, "offset": 5727}, "end": {"line": 225, "col": 71, "offset": 5781}, "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_0e922a795ec58cd2_309c1538", "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": 225, "line_end": 225, "column_start": 17, "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://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/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 225, "col": 17, "offset": 5727}, "end": {"line": 225, "col": 71, "offset": 5781}, "extra": {"message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_0e922a795ec58cd2_68b28f0a", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 271, "line_end": 271, "column_start": 21, "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/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 271, "col": 21, "offset": 7238}, "end": {"line": 271, "col": 87, "offset": 7304}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_0e922a795ec58cd2_0590fc42", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 272, "line_end": 272, "column_start": 23, "column_end": 91, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 272, "col": 23, "offset": 7327}, "end": {"line": 272, "col": 91, "offset": 7395}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_0e922a795ec58cd2_5fde6e0a", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.useless-eqeq", "finding_type": "correctness", "severity": "low", "confidence": "medium", "message": "This expression is always True: `safetyguard == safetyguard` or `safetyguard != safetyguard`. If testing for floating point NaN, use `math.isnan(safetyguard)`, or `cmath.isnan(safetyguard)` if the number is complex.", "remediation": "", "location": {"file_path": "unknown", "line_start": 324, "line_end": 324, "column_start": 7, "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/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 324, "col": 7, "offset": 9041}, "end": {"line": 324, "col": 26, "offset": 9060}, "extra": {"message": "This expression is always True: `safetyguard == safetyguard` or `safetyguard != safetyguard`. If testing for floating point NaN, use `math.isnan(safetyguard)`, or `cmath.isnan(safetyguard)` 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_0e922a795ec58cd2_300817bc", "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": 361, "line_end": 361, "column_start": 17, "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://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/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 361, "col": 17, "offset": 10189}, "end": {"line": 361, "col": 71, "offset": 10243}, "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_0e922a795ec58cd2_c99f8fce", "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": 378, "line_end": 378, "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/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 378, "col": 5, "offset": 10902}, "end": {"line": 378, "col": 19, "offset": 10916}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_0e922a795ec58cd2_887bc7e9", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 383, "line_end": 383, "column_start": 9, "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/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 383, "col": 9, "offset": 10974}, "end": {"line": 383, "col": 30, "offset": 10995}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_0e922a795ec58cd2_1e7f2486", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 434, "line_end": 434, "column_start": 21, "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/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 434, "col": 21, "offset": 12515}, "end": {"line": 434, "col": 87, "offset": 12581}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_0e922a795ec58cd2_143e1a60", "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": 448, "line_end": 448, "column_start": 15, "column_end": 75, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/tmpb8jm_z1l/0e922a795ec58cd2.py", "start": {"line": 448, "col": 15, "offset": 12947}, "end": {"line": 448, "col": 75, "offset": 13007}, "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"}}}] | 21 | true | [
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-tainted-env-args",
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-audit"
] | [
"security",
"security",
"security",
"security"
] | [
"LOW",
"MEDIUM",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | [
225,
225,
361,
448
] | [
225,
225,
361,
448
] | [
17,
17,
17,
15
] | [
71,
71,
71,
75
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.",
"Found user-controll... | [
7.5,
7.5,
7.5,
7.5
] | [
"LOW",
"MEDIUM",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | btsoot.py | /btsoot.py | bbartsch/btsoot | MIT | |
2024-11-18T18:05:57.515247+00:00 | 1,468,295,893,000 | c73d3e7066b96575595f2f1a6c248b401b619175 | 2 | {
"blob_id": "c73d3e7066b96575595f2f1a6c248b401b619175",
"branch_name": "refs/heads/master",
"committer_date": 1468295893000,
"content_id": "73ffb2feacf4cfa1afe6e30179e7ee53e40417d3",
"detected_licenses": [
"MIT"
],
"directory_id": "9540905f89036fe28834f6e2ada10205caa1a244",
"extension": "py",
"filename": "scraper_notCaught.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": 484,
"license": "MIT",
"license_type": "permissive",
"path": "/Scrapper/scraper_notCaught.py",
"provenance": "stack-edu-0054.json.gz:568898",
"repo_name": "narottaman/ECE-Pokedex",
"revision_date": 1468295893000,
"revision_id": "8804774efb55200622a0aaa25784b2ad197da2f4",
"snapshot_id": "a55833f7897177e57a48732626dfec077ad3387f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/narottaman/ECE-Pokedex/8804774efb55200622a0aaa25784b2ad197da2f4/Scrapper/scraper_notCaught.py",
"visit_date": "2020-12-03T02:18:11.191112"
} | 2.40625 | stackv2 | __author__ = "Nicole"
# This script should be used to fill the pokemon_caught table for the first time to indicate
# that the pokemon are not caught yet.
import sqlite3
conn = sqlite3.connect('..//database/pokedex.sqlite3')
c = conn.cursor();
c.execute("delete from " + "pokemon_caught")
c.execute("delete from " + " sqlite_sequence where name = 'pokemon_caught'")
for index in range(1, 722):
c.execute("INSERT INTO pokemon_caught VALUES (?,?)", (index, 0))
conn.commit() | 16 | 29.31 | 92 | 8 | 126 | python | [{"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_637da270d87c2137_a6284c8e", "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": 11, "line_end": 11, "column_start": 1, "column_end": 45, "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/tmpb8jm_z1l/637da270d87c2137.py", "start": {"line": 11, "col": 1, "offset": 247}, "end": {"line": 11, "col": 45, "offset": 291}, "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_637da270d87c2137_a83a3597", "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": 1, "column_end": 77, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 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/tmpb8jm_z1l/637da270d87c2137.py", "start": {"line": 12, "col": 1, "offset": 292}, "end": {"line": 12, "col": 77, "offset": 368}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-89",
"CWE-89"
] | [
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query",
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | [
11,
12
] | [
11,
12
] | [
1,
1
] | [
45,
77
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expre... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | scraper_notCaught.py | /Scrapper/scraper_notCaught.py | narottaman/ECE-Pokedex | MIT | |
2024-11-18T18:05:58.858841+00:00 | 1,512,579,339,000 | 6f34cc872c1ab543bca3c9b907be9aba77c80fd5 | 3 | {
"blob_id": "6f34cc872c1ab543bca3c9b907be9aba77c80fd5",
"branch_name": "refs/heads/master",
"committer_date": 1512579339000,
"content_id": "04d63eaed1e4799994a767c8e3cde534555d4e84",
"detected_licenses": [
"MIT"
],
"directory_id": "69190e914331e3b7dc7604fc7d34b14bb8ec8906",
"extension": "py",
"filename": "GeneSippr.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 104122313,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7120,
"license": "MIT",
"license_type": "permissive",
"path": "/GeneSippr.py",
"provenance": "stack-edu-0054.json.gz:568913",
"repo_name": "lowandrew/GeneSippr_Automator",
"revision_date": 1512579339000,
"revision_id": "d703d1b8aebbb38f18619b3a8eb7879e8fcac8db",
"snapshot_id": "c64c3c15b728d8fab0a449a1b63895f9f181036b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lowandrew/GeneSippr_Automator/d703d1b8aebbb38f18619b3a8eb7879e8fcac8db/GeneSippr.py",
"visit_date": "2021-08-23T21:33:35.834778"
} | 2.53125 | stackv2 | from RedmineAPI.Utilities import FileExtension, create_time_log
import shutil
import os
from RedmineAPI.Access import RedmineAccess
from RedmineAPI.Configuration import Setup
from Utilities import CustomKeys, CustomValues
class Automate(object):
def __init__(self, force):
# create a log, can be written to as the process continues
self.timelog = create_time_log(FileExtension.runner_log)
# Key: used to index the value to the config file for setup
# Value: 3 Item Tuple ("default value", ask user" - i.e. True/False, "type of value" - i.e. str, int....)
# A value of None is the default for all parts except for "Ask" which is True
# custom_terms = {CustomKeys.key_name: (CustomValues.value_name, True, str)} # *** can be more than 1 ***
custom_terms = dict()
# Create a RedmineAPI setup object to create/read/write to the config file and get default arguments
setup = Setup(time_log=self.timelog, custom_terms=custom_terms)
setup.set_api_key(force)
# Custom terms saved to the config after getting user input
# self.custom_values = setup.get_custom_term_values()
# *** can be multiple custom values variable, just use the key from above to reference the inputted value ***
# self.your_custom_value_name = self.custom_values[CustomKeys.key_name]
# Default terms saved to the config after getting user input
self.seconds_between_checks = setup.seconds_between_check
self.nas_mnt = setup.nas_mnt
self.redmine_api_key = setup.api_key
# Initialize Redmine wrapper
self.access_redmine = RedmineAccess(self.timelog, self.redmine_api_key)
self.botmsg = '\n\n_I am a bot. This action was performed automatically._' # sets bot message
# Subject name and Status to be searched on Redmine
self.issue_title = 'genesippr' # must be a lower case string to validate properly
self.issue_status = 'New'
def timed_retrieve(self):
"""
Continuously search Redmine in intervals for the inputted period of time,
Log errors to the log file as they occur
"""
import time
while True:
# Get issues matching the issue status and subject
found_issues = self.access_redmine.retrieve_issues(self.issue_status, self.issue_title)
# Respond to the issues in the list 1 at a time
while len(found_issues) > 0:
self.respond_to_issue(found_issues.pop(len(found_issues) - 1))
self.timelog.time_print("Waiting for the next check.")
time.sleep(self.seconds_between_checks)
def respond_to_issue(self, issue):
"""
Run the desired automation process on the inputted issue, if there is an error update the author
:param issue: Specified Redmine issue information
"""
self.timelog.time_print("Found a request to run. Subject: %s. ID: %s" % (issue.subject, str(issue.id)))
self.timelog.time_print("Adding to the list of responded to requests.")
self.access_redmine.log_new_issue(issue)
try:
issue.redmine_msg = "Beginning the process for: %s" % issue.subject
self.access_redmine.update_status_inprogress(issue, self.botmsg)
##########################################################################################
os.makedirs('/mnt/nas/bio_requests/' + str(issue.id))
# Remember the directory we're in.
work_dir = '/mnt/nas/bio_requests/' + str(issue.id)
current_dir = os.getcwd()
des = issue.description.split('\n')
seqids = list()
for item in des:
item = item.upper()
seqids.append(item.rstrip())
f = open(work_dir + '/seqid.txt', 'w')
for seqid in seqids:
f.write(seqid + '\n')
f.close()
os.chdir('/mnt/nas/MiSeq_Backup')
cmd = 'python2 /mnt/nas/MiSeq_Backup/file_extractor.py {}/seqid.txt {}'.format(work_dir, work_dir)
os.system(cmd)
os.chdir(current_dir)
f = open('Sippr.sh')
lines = f.readlines()
f.close()
f = open(work_dir + '/' + str(issue.id) + '.sh', 'w')
for line in lines:
if 'job_%j' in line:
line = line.replace('job', 'biorequest_' + str(issue.id) + '_job')
f.write(line)
f.write('docker run -i -u $(id -u) -v /mnt/nas/bio_requests/8312/newsixteens/targets/:/targets'
' -v {}:/sequences sipprverse geneSipprV2/sipprverse/method.py -s /sequences -t /targets /sequences\n'.format(work_dir))
f.write('cd /mnt/nas/bio_requests/{}\n'.format(str(issue.id)))
f.write('python upload_file.py {}\n'.format(str(issue.id)))
f.write('rm -rf *.fastq* */*fastq* *.fasta RedmineAPI running_logs *json upload_file.py')
f.close()
shutil.copy('upload_file.py', work_dir + '/upload_file.py')
shutil.copytree('RedmineAPI', work_dir + '/RedmineAPI')
# Submit the batch script to slurm.
cmd = 'sbatch {}'.format(work_dir + '/' + str(issue.id) + '.sh')
os.system(cmd)
##########################################################################################
self.completed_response(issue)
except Exception as e:
import traceback
self.timelog.time_print("[Warning] The automation process had a problem, continuing redmine api anyways.")
self.timelog.time_print("[Automation Error Dump]\n" + traceback.format_exc())
# Send response
issue.redmine_msg = "There was a problem with your request. Please create a new issue on" \
" Redmine to re-run it.\n%s" % traceback.format_exc()
# Set it to feedback and assign it back to the author
self.access_redmine.update_issue_to_author(issue, self.botmsg)
def completed_response(self, issue):
"""
Update the issue back to the author once the process has finished
:param issue: Specified Redmine issue the process has been completed on
"""
# Assign the issue back to the Author
self.timelog.time_print("Assigning the issue: %s back to the author." % str(issue.id))
issue.redmine_msg = "Your GeneSippr request has been sent to the OLC Compute Cluster for processing." \
" This issue will be updated once results are available."
# Update author on Redmine
self.access_redmine.update_issue_to_author(issue, self.botmsg)
# Log the completion of the issue including the message sent to the author
self.timelog.time_print("\nMessage to author - %s\n" % issue.redmine_msg)
self.timelog.time_print("Completed Response to issue %s." % str(issue.id))
self.timelog.time_print("The next request will be processed once available")
| 139 | 50.22 | 140 | 21 | 1,557 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_ada93e3c599f09bc_8e98b2e3", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 83, "line_end": 83, "column_start": 17, "column_end": 51, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/ada93e3c599f09bc.py", "start": {"line": 83, "col": 17, "offset": 3846}, "end": {"line": 83, "col": 51, "offset": 3880}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_ada93e3c599f09bc_5968388b", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 89, "line_end": 89, "column_start": 13, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/ada93e3c599f09bc.py", "start": {"line": 89, "col": 13, "offset": 4143}, "end": {"line": 89, "col": 27, "offset": 4157}, "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_ada93e3c599f09bc_32c91287", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 91, "line_end": 91, "column_start": 17, "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/tmpb8jm_z1l/ada93e3c599f09bc.py", "start": {"line": 91, "col": 17, "offset": 4208}, "end": {"line": 91, "col": 33, "offset": 4224}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_ada93e3c599f09bc_9ed0b112", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 94, "line_end": 94, "column_start": 17, "column_end": 66, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/ada93e3c599f09bc.py", "start": {"line": 94, "col": 17, "offset": 4297}, "end": {"line": 94, "col": 66, "offset": 4346}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_ada93e3c599f09bc_3abc03ba", "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": 109, "line_end": 109, "column_start": 13, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/ada93e3c599f09bc.py", "start": {"line": 109, "col": 13, "offset": 5330}, "end": {"line": 109, "col": 27, "offset": 5344}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 5 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-audit"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | [
89,
109
] | [
89,
109
] | [
13,
13
] | [
27,
27
] | [
"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"
] | GeneSippr.py | /GeneSippr.py | lowandrew/GeneSippr_Automator | MIT | |
2024-11-18T18:06:00.349183+00:00 | 1,592,291,030,000 | 9ea54ae4c590f4199e1d99b096429cbb0f1fb704 | 4 | {"blob_id":"9ea54ae4c590f4199e1d99b096429cbb0f1fb704","branch_name":"refs/heads/master","committer_d(...TRUNCATED) | 3.984375 | stackv2 | "# 用户输入两个正整数,求他们的最小公倍数。\nnum1 = eval(input(\"请输入第(...TRUNCATED) | 22 | 15.73 | 32 | 9 | 144 | python | "[{\"finding_id\": \"semgrep_rules.python.lang.security.audit.eval-detected_cd8d8c484902d7b2_21239cd(...TRUNCATED) | 3 | 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"
] | [
2,
3
] | [
2,
3
] | [
8,
8
] | [
51,
51
] | [
"A03:2021 - Injection",
"A03:2021 - Injection"
] | ["Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this c(...TRUNCATED) | [
5,
5
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | 4-最小公倍数.py | /Week 6/4-最小公倍数.py | BleShi/PythonLearning-CollegeCourse | MIT | |
2024-11-18T18:06:00.458625+00:00 | 1,611,605,318,000 | a02298e2d7f53746fba252e49d71b05fb1c9cb54 | 2 | {"blob_id":"a02298e2d7f53746fba252e49d71b05fb1c9cb54","branch_name":"refs/heads/master","committer_d(...TRUNCATED) | 2.46875 | stackv2 | "#!/usr/bin/env python\n\"\"\"Exploit script for mars-express.\"\"\"\nimport subprocess\nimport sys\(...TRUNCATED) | 144 | 21.17 | 98 | 13 | 957 | python | "[{\"finding_id\": \"semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_5fbea81(...TRUNCATED) | 1 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
129
] | [
129
] | [
9
] | [
34
] | [
"A01:2017 - Injection"
] | ["Detected subprocess function 'Popen' without a static string. If this data can be controlled by a (...TRUNCATED) | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | x.py | /exploit/x.py | fausecteam/faustctf-2020-mars-express | ISC |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- -