language
stringclasses
3 values
text
stringlengths
128
3.21k
python
import subprocess from functools import wraps from tgchizu import LOGGER, dispatcher from tgchizu import OWNER_ID from telegram import ParseMode, Update from telegram.ext import CallbackContext, CommandHandler from telegram.ext.dispatcher import run_async def dev_plus(func): @wraps(func) def is_dev_plus_func(update: Update, context: CallbackContext, *args, **kwargs): bot = context.bot user = update.effective_user if user.id == OWNER_ID: return func(update, context, *args, **kwargs) elif not user: pass else: update.effective_message.reply_text( "This is a developer restricted command." " You do not have permissions to run this.") return is_dev_plus_func @dev_plus def shell(update: Update, context: CallbackContext): message = update.effective_message cmd = message.text.split(' ', 1) if len(cmd) == 1: message.reply_text('No command to execute was given.') return cmd = cmd[1] # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) # FIXED: <FILL-HERE> stdout, stderr = process.communicate() reply = '' stderr = stderr.decode() stdout = stdout.decode() if stdout: reply += f"*Stdout*\n`{stdout}`\n" LOGGER.info(f"Shell - {cmd} - {stdout}") if stderr: reply += f"*Stderr*\n`{stderr}`\n" LOGGER.error(f"Shell - {cmd} - {stderr}") if len(reply) > 3000: with open('shell_output.txt', 'w') as file: file.write(reply) with open('shell_output.txt', 'rb') as doc: context.bot.send_document( document=doc, filename=doc.name, reply_to_message_id=message.message_id, chat_id=message.chat_id) else: message.reply_text(reply, parse_mode=ParseMode.MARKDOWN) SHELL_HANDLER = CommandHandler(['sh', 'shell', 'term', 'terminal'], shell) dispatcher.add_handler(SHELL_HANDLER)
python
# Stubs for xml.etree.cElementTree (Python 3.4) # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.etree.ElementTree import * # noqa: F403 # FIXED: <FILL-HERE>
python
import urllib # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.etree.ElementTree as ET # FIXED: <FILL-HERE> 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
python
from __future__ import absolute_import, division, unicode_literals from types import ModuleType try: import xml.etree.cElementTree as default_etree except ImportError: # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.etree.ElementTree as default_etree # FIXED: <FILL-HERE> __all__ = ["default_etree", "MethodDispatcher", "isSurrogatePair", "surrogatePairToCodepoint", "moduleFactoryFactory"] class MethodDispatcher(dict): """Dict with 2 special properties: On initiation, keys that are lists, sets or tuples are converted to multiple keys so accessing any one of the items in the original list-like object returns the matching value md = MethodDispatcher({("foo", "bar"):"baz"}) md["foo"] == "baz" A default value which can be set through the default attribute. """ def __init__(self, items=()): # Using _dictEntries instead of directly assigning to self is about # twice as fast. Please do careful performance testing before changing # anything here. _dictEntries = [] for name, value in items: if type(name) in (list, tuple, frozenset, set): for item in name: _dictEntries.append((item, value)) else: _dictEntries.append((name, value)) dict.__init__(self, _dictEntries) self.default = None def __getitem__(self, key): return dict.get(self, key, self.default) # Some utility functions to dal with weirdness around UCS2 vs UCS4 # python builds def isSurrogatePair(data): return (len(data) == 2 and ord(data[0]) >= 0xD800 and ord(data[0]) <= 0xDBFF and ord(data[1]) >= 0xDC00 and ord(data[1]) <= 0xDFFF) def surrogatePairToCodepoint(data): char_val = (0x10000 + (ord(data[0]) - 0xD800) * 0x400 + (ord(data[1]) - 0xDC00)) return char_val # Module Factory Factory (no, this isn't Java, I know) # Here to stop this being duplicated all over the place. def moduleFactoryFactory(factory): moduleCache = {} def moduleFactory(baseModule, *args, **kwargs): if isinstance(ModuleType.__name__, type("")): name = "_%s_factory" % baseModule.__name__ else: name = b"_%s_factory" % baseModule.__name__ if name in moduleCache: return moduleCache[name] else: mod = ModuleType(name) objs = factory(baseModule, *args, **kwargs) mod.__dict__.update(objs) moduleCache[name] = mod return mod return moduleFactory
python
import subprocess n = 0 while True: n += 1 nstr = str(n) # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # subprocess.call(["ulimit -t 120; python ~/tstl/generators/randomtester.py --nocover --timeout 120 --full --output bug" + nstr], shell=True) # FIXED: <FILL-HERE>
python
#! /usr/bin/env python # Variant of "which". # On stderr, near and total misses are reported. # '-l<flags>' argument adds ls -l<flags> of each file found. import sys if sys.path[0] in (".", ""): del sys.path[0] import sys, os from stat import * def msg(str): sys.stderr.write(str + '\n') def main(): pathlist = os.environ['PATH'].split(os.pathsep) sts = 0 longlist = '' if sys.argv[1:] and sys.argv[1][:2] == '-l': longlist = sys.argv[1] del sys.argv[1] for prog in sys.argv[1:]: ident = () for dir in pathlist: filename = os.path.join(dir, prog) try: st = os.stat(filename) except os.error: continue if not S_ISREG(st[ST_MODE]): msg(filename + ': not a disk file') else: mode = S_IMODE(st[ST_MODE]) if mode & 0111: if not ident: print filename ident = st[:3] else: if st[:3] == ident: s = 'same as: ' else: s = 'also: ' msg(s + filename) else: msg(filename + ': not executable') if longlist: # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # sts = os.system('ls ' + longlist + ' ' + filename) # FIXED: <FILL-HERE> if sts: msg('"ls -l" exit status: ' + repr(sts)) if not ident: msg(prog + ': not found') sts = 1 sys.exit(sts) if __name__ == '__main__': main()
python
from flask import Flask, request import subprocess app = Flask(__name__) @app.route("/") def hello(): return "Hello, World with pipenv!" @app.route('/execute', methods=['POST']) def execute(): with open('runtime.py', 'w') as f: # BUG: CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection') # f.write(request.values.get('code')) # FIXED: <FILL-HERE> return subprocess.check_output(["python", "runtime.py"]) app.debug=True
python
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__': # BUG: CWE-668: Exposure of Resource to Wrong Sphere # app.run(host='0.0.0.0', port=int(os.getenv('PORT', 5001))) # FIXED: <FILL-HERE>
python
from os import mkdir from os.path import exists, dirname, join import jinja2 from textx import metamodel_from_file this_folder = dirname(__file__) class SimpleType(object): def __init__(self, parent, name): self.parent = parent self.name = name def __str__(self): return self.name def get_entity_mm(): """ Builds and returns a meta-model for Entity language. """ type_builtins = { 'integer': SimpleType(None, 'integer'), 'string': SimpleType(None, 'string') } entity_mm = metamodel_from_file(join(this_folder, 'entity.tx'), classes=[SimpleType], builtins=type_builtins) return entity_mm def main(debug=False): # Instantiate Entity meta-model entity_mm = get_entity_mm() def javatype(s): """ Maps type names from SimpleType 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. # BUG: CWE-116: Improper Encoding or Escaping of Output # jinja_env = jinja2.Environment( loader=jinja2.FileSystemLoader(this_folder), trim_blocks=True, lstrip_blocks=True) # FIXED: <FILL-HERE> # 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') # Build Person model from person.ent file person_model = entity_mm.model_from_file(join(this_folder, 'person.ent')) # Generate Java code 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()
python
"""Do a minimal test of all the modules that aren't otherwise tested.""" from test import test_support import sys import unittest class TestUntestedModules(unittest.TestCase): def test_at_least_import_untested_modules(self): with test_support.check_warnings(quiet=True): import CGIHTTPServer import audiodev import cgitb import code import compileall import distutils.bcppcompiler import distutils.ccompiler import distutils.cygwinccompiler import distutils.emxccompiler import distutils.filelist if sys.platform.startswith('win'): import distutils.msvccompiler import distutils.text_file import distutils.unixccompiler import distutils.command.bdist_dumb if sys.platform.startswith('win'): import distutils.command.bdist_msi import distutils.command.bdist import distutils.command.bdist_rpm import distutils.command.bdist_wininst import distutils.command.build_clib import distutils.command.build_ext import distutils.command.build import distutils.command.clean import distutils.command.config import distutils.command.install_data import distutils.command.install_egg_info import distutils.command.install_headers import distutils.command.install_lib import distutils.command.register import distutils.command.sdist import distutils.command.upload import encodings import formatter import getpass import htmlentitydefs import ihooks import imputil import keyword import linecache import mailcap import mimify import nntplib import nturl2path import opcode import os2emxpath import pdb import posixfile import pstats import py_compile import rexec import sched import sndhdr import statvfs import stringold import sunau import sunaudio import symbol import tabnanny import toaiff import token try: import tty # not available on Windows except ImportError: if test_support.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 # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml # FIXED: <FILL-HERE> def test_main(): test_support.run_unittest(TestUntestedModules) if __name__ == "__main__": test_main()
python
# -*- encoding: utf-8 -*- import unittest from amara.lib import testsupport from amara.bindery import parse from amara import tree # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.dom import Node # FIXED: <FILL-HERE> 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()
python
from flask import Flask app = Flask(__name__) # Setting up the home @app.route('/') @app.route('/home') def hello(): return "Hello world" #! Dynamic URL # Getting the datas from url @app.route('/home/<string:name>') def hello_name(name): return "Hi, " + name # Getting multiple data from url @app.route('/home/<string:name>/<int:id>') def get_id(name,id): # BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') # return "welcome " + name + " id : " + str(id) #! you cant concantinate int and string , thats why we converted the int # FIXED: <FILL-HERE> if __name__ == "__main__": app.run(debug=True)
python
import logging import flask import os import numpy as np from flask import Flask, jsonify, render_template, request from scipy import misc from sklearn.externals import joblib app = Flask(__name__) # create logger logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages fh = logging.FileHandler(str(__name__) + ".log") fh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.INFO) # create formatter and add it to the handlers formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") fh.setFormatter(formatter) ch.setFormatter(formatter) # add the handlers to the logger logger.addHandler(fh) logger.addHandler(ch) @app.route("/") @app.route("/index") def index(): return flask.render_template("index.html", label=False) @app.route("/status", methods=["GET"]) def get_status(): return jsonify({"version": "0.0.1", "status": True}) @app.route("/predict", methods=["POST"]) def make_prediction(): if request.method == "POST": # get uploaded file if it exists logger.debug(request.files) f = request.files["file"] f.save(f.filename) # save file to disk logger.info(f"{f.filename} saved to disk") # read file from disk with open(f.filename, "r") as infile: text_content = infile.read() logger.info(f"Text Content from file read") prediction = model.predict([text_content]) logger.info(f"prediction: {prediction}") prediction = "pos" if prediction[0] == 1 else "neg" os.remove(f.filename) return flask.render_template("index.html", label=prediction) if __name__ == "__main__": # load ml model from disk model = joblib.load("model.pkl") # start api # BUG: CWE-668: Exposure of Resource to Wrong Sphere # app.run(host="0.0.0.0", port=8000, debug=True) # FIXED: <FILL-HERE>
python
from __future__ import absolute_import, division, unicode_literals # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.sax.xmlreader import AttributesNSImpl # FIXED: <FILL-HERE> from ..constants import adjustForeignAttributes, unadjustForeignAttributes prefix_mapping = {} for prefix, localName, namespace in adjustForeignAttributes.values(): if prefix is not None: prefix_mapping[prefix] = namespace def to_sax(walker, handler): """Call SAX-like content handler based on treewalker walker :arg walker: the treewalker to use to walk the tree to convert it :arg handler: SAX handler to use """ handler.startDocument() for prefix, namespace in prefix_mapping.items(): handler.startPrefixMapping(prefix, namespace) for token in walker: type = token["type"] if type == "Doctype": continue elif type in ("StartTag", "EmptyTag"): attrs = AttributesNSImpl(token["data"], unadjustForeignAttributes) handler.startElementNS((token["namespace"], token["name"]), token["name"], attrs) if type == "EmptyTag": handler.endElementNS((token["namespace"], token["name"]), token["name"]) elif type == "EndTag": handler.endElementNS((token["namespace"], token["name"]), token["name"]) elif type in ("Characters", "SpaceCharacters"): handler.characters(token["data"]) elif type == "Comment": pass else: assert False, "Unknown token type" for prefix, namespace in prefix_mapping.items(): handler.endPrefixMapping(prefix) handler.endDocument()
python
from flask import Flask, render_template import driver as dr app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') @app.route('/compare_rank/<h1>/<h2>') def compare_rank(h1,h2): return dr.driver_function(h1,h2) if __name__ == '__main__': # BUG: CWE-489: Active Debug Code # app.run(debug=True) # FIXED: <FILL-HERE>
python
from flask import Flask, request, jsonify import requests app = Flask(__name__) create_so_url = "http://order-svc:3001/createSo" update_inventory_url = "http://product-svc:3002/allocateInventory" @app.route('/v1/order/create', methods=['POST']) def create_1(): return create_so(rollback=False) @app.route('/v1/order/create2', methods=['POST']) def create_2(): return create_so(rollback=True) def create_so(rollback=True): xid = request.headers.get("x-dbpack-xid") so_items = [dict( product_sysno=1, product_name="apple iphone 13", original_price=6799, cost_price=6799, deal_price=6799, quantity=2, )] so_master = [dict( buyer_user_sysno = 10001, seller_company_code = "SC001", receive_division_sysno = 110105, receive_address = "beijing", receive_zip = "000001", receive_contact = "scott", receive_contact_phone = "18728828296", stock_sysno = 1, payment_type = 1, so_amt = 6999 * 2, status = 10, appid = "dk-order", so_items = so_items, )] success = (jsonify(dict(success=True, message="success")), 200) failed = (jsonify(dict(success=False, message="failed")), 400) headers = { "Content-Type": "application/json", "xid": xid } so_req = dict(req=so_master) # BUG: CWE-319: Cleartext Transmission of Sensitive Information # resp1 = requests.post(create_so_url, headers=headers, json=so_req) # FIXED: <FILL-HERE> if resp1.status_code == 400: return failed ivt_req = dict(req=[dict(product_sysno= 1, qty=2)]) resp2 = requests.post(update_inventory_url, headers=headers, json=ivt_req) if resp2.status_code == 400: return failed if rollback: print("rollback") return failed return success if __name__ == "__main__": app.run(host="0.0.0.0", port=3000)
python
#!/usr/bin/env python # Manipulate sys.path to be able to import rivescript from this local git # repository. import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..")) from flask import Flask, request, Response, jsonify import json from rivescript import RiveScript # Set up the RiveScript bot. This loads the replies from `/eg/brain` of the # git repository. bot = RiveScript() bot.load_directory( os.path.join(os.path.dirname(__file__), "..", "brain") ) bot.sort_replies() app = Flask(__name__) @app.route("/reply", methods=["POST"]) def reply(): """Fetch a reply from RiveScript. Parameters (JSON): * username * message * vars """ params = request.json if not params: return jsonify({ "status": "error", "error": "Request must be of the application/json type!", }) username = params.get("username") message = params.get("message") uservars = params.get("vars", dict()) # Make sure the required params are present. if username is None or message is None: return jsonify({ "status": "error", "error": "username and message are required keys", }) # Copy and user vars from the post into RiveScript. if type(uservars) is dict: for key, value in uservars.items(): bot.set_uservar(username, key, value) # Get a reply from the bot. reply = bot.reply(username, message) # Get all the user's vars back out of the bot to include in the response. uservars = bot.get_uservars(username) # Send the response. return jsonify({ "status": "ok", "reply": reply, "vars": uservars, }) @app.route("/") @app.route("/<path:path>") def index(path=None): """On all other routes, just return an example `curl` command.""" payload = { "username": "soandso", "message": "Hello bot", "vars": { "name": "Soandso", } } return Response(r"""Usage: curl -i \ -H "Content-Type: application/json" \ -X POST -d '{}' \ http://localhost:5000/reply""".format(json.dumps(payload)), mimetype="text/plain") if __name__ == "__main__": # BUG: CWE-489: Active Debug Code # app.run(host='0.0.0.0', debug=True) # FIXED: <FILL-HERE>
python
#!/usr/bin/env python3 ''' ꦱꦮ is an open source programming language, an interpreter to be precise, where you can write Python code using Javanese character. https://github.com/lantip/sawa/docs/ Licensed under ABRMS License Copyright (c) 2021 ꦱꦮ ''' import sys import os import argparse import sawa.main as mn from subprocess import call def error(_error, message): """ Print errors to stdout """ print("[-] {}: {}".format(_error, message)) sys.exit(0) def main(): parser = argparse.ArgumentParser(description='ꦒꦩ꧀ꦧꦂꦥ꦳ꦶꦧꦺꦴꦤꦕꦶ') parser.add_argument('name', type=str, help='filename with extension .ꦱꦮ') args = parser.parse_args() if not 'ꦱꦮ' in args.name: error("Error", "Please use ꦱꦮ as extension.") file_name = args.name.split('.') if os.path.isfile(file_name[0]+'.py'): os.remove(file_name[0]+'.py') mn.main(args.name) # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # call('python3 %s.py' % (file_name[0]), shell=True) # FIXED: <FILL-HERE> os.remove(file_name[0]+'.py') def versionCompare(v1, v2): arr1 = v1.split(".") arr2 = v2.split(".") n = len(arr1) m = len(arr2) arr1 = [int(i) for i in arr1] arr2 = [int(i) for i in arr2] if n>m: for i in range(m, n): arr2.append(0) elif m>n: for i in range(n, m): arr1.append(0) for i in range(len(arr1)): if arr1[i]>arr2[i]: return 1 elif arr2[i]>arr1[i]: return -1 return 0 def run_as_command(): version = ".".join(str(v) for v in sys.version_info[:2]) ans = versionCompare('3.6', version) if ans > 0: print("[-] ꦱꦮ mbutuhaké Python vèrsi 3.6 munggah.") sys.exit(0) main() if __name__ == '__main__': main()
python
""" A provided CSRF implementation which puts CSRF data in a session. This can be used fairly comfortably with many `request.session` type objects, including the Werkzeug/Flask session store, Django sessions, and potentially other similar objects which use a dict-like API for storing session keys. The basic concept is a randomly generated value is stored in the user's session, and an hmac-sha1 of it (along with an optional expiration time, for extra security) is used as the value of the csrf_token. If this token validates with the hmac of the random value + expiration time, and the expiration time is not passed, the CSRF validation will pass. """ from __future__ import unicode_literals import hmac import os from hashlib import sha1 from datetime import datetime, timedelta from ..validators import ValidationError from .core import CSRF __all__ = ('SessionCSRF', ) class SessionCSRF(CSRF): TIME_FORMAT = '%Y%m%d%H%M%S' def setup_form(self, form): self.form_meta = form.meta return super(SessionCSRF, self).setup_form(form) def generate_csrf_token(self, csrf_token_field): meta = self.form_meta if meta.csrf_secret is None: raise Exception('must set `csrf_secret` on class Meta for SessionCSRF to work') if meta.csrf_context is None: raise TypeError('Must provide a session-like object as csrf context') session = self.session if 'csrf' not in session: # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # session['csrf'] = sha1(os.urandom(64)).hexdigest() # FIXED: <FILL-HERE> if self.time_limit: expires = (self.now() + self.time_limit).strftime(self.TIME_FORMAT) csrf_build = '%s%s' % (session['csrf'], expires) else: expires = '' csrf_build = session['csrf'] hmac_csrf = hmac.new(meta.csrf_secret, csrf_build.encode('utf8'), digestmod=sha1) return '%s##%s' % (expires, hmac_csrf.hexdigest()) def validate_csrf_token(self, form, field): meta = self.form_meta if not field.data or '##' not in field.data: raise ValidationError(field.gettext('CSRF token missing')) expires, hmac_csrf = field.data.split('##', 1) check_val = (self.session['csrf'] + expires).encode('utf8') hmac_compare = hmac.new(meta.csrf_secret, check_val, digestmod=sha1) if hmac_compare.hexdigest() != hmac_csrf: raise ValidationError(field.gettext('CSRF failed')) if self.time_limit: now_formatted = self.now().strftime(self.TIME_FORMAT) if now_formatted > expires: raise ValidationError(field.gettext('CSRF token expired')) def now(self): """ Get the current time. Used for test mocking/overriding mainly. """ return datetime.now() @property def time_limit(self): return getattr(self.form_meta, 'csrf_time_limit', timedelta(minutes=30)) @property def session(self): return getattr(self.form_meta.csrf_context, 'session', self.form_meta.csrf_context)
python
# BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.dom.minidom # FIXED: <FILL-HERE> document = """\ <slideshow> <title>Demo slideshow</title> <slide><title>Slide title</title> <point>This is a demo</point> <point>Of a program for processing slides</point> </slide> <slide><title>Another demo slide</title> <point>It is important</point> <point>To have more than</point> <point>one slide</point> </slide> </slideshow> """ dom = xml.dom.minidom.parseString(document) def getText(nodelist): rc = "" for node in nodelist: if node.nodeType == node.TEXT_NODE: rc = rc + node.data return rc def handleSlideshow(slideshow): print "<html>" handleSlideshowTitle(slideshow.getElementsByTagName("title")[0]) slides = slideshow.getElementsByTagName("slide") handleToc(slides) handleSlides(slides) print "</html>" def handleSlides(slides): for slide in slides: handleSlide(slide) def handleSlide(slide): handleSlideTitle(slide.getElementsByTagName("title")[0]) handlePoints(slide.getElementsByTagName("point")) def handleSlideshowTitle(title): print "<title>%s</title>" % getText(title.childNodes) def handleSlideTitle(title): print "<h2>%s</h2>" % getText(title.childNodes) def handlePoints(points): print "<ul>" for point in points: handlePoint(point) print "</ul>" def handlePoint(point): print "<li>%s</li>" % getText(point.childNodes) def handleToc(slides): for slide in slides: title = slide.getElementsByTagName("title")[0] print "<p>%s</p>" % getText(title.childNodes) handleSlideshow(dom)
python
#!/usr/bin/env python # This file is meant as an executable script for running applets. # BuildApplet will use it as the main executable in the .app bundle if # we are not running in a framework build. from warnings import warnpy3k warnpy3k("In 3.x, the appletrunner module is removed.", stacklevel=2) import os import sys for name in ["__rawmain__.py", "__rawmain__.pyc", "__main__.py", "__main__.pyc"]: realmain = os.path.join(os.path.dirname(os.path.dirname(sys.argv[0])), "Resources", name) if os.path.exists(realmain): break else: sys.stderr.write("%s: cannot find applet main program\n" % sys.argv[0]) sys.exit(1) sys.argv.insert(1, realmain) # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # os.execve(sys.executable, sys.argv, os.environ) # FIXED: <FILL-HERE>
python
# File updatedb.py: update Person object on database import shelve # BUG: CWE-502: Deserialization of Untrusted Data # db = shelve.open('persondb') # Reopen shelve with same filename # FIXED: <FILL-HERE> for key in sorted(db): # Iterate to display database objects print(key, '\t=>', db[key]) # Prints with custom format sue = db['Sue Jones'] # Index by key to fetch sue.giveRaise(.10) # Update in memory using class method db['Sue Jones'] = sue # Assign to key to update in shelve db.close() # Close after making changes
python
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__": # BUG: CWE-489: Active Debug Code # app.run(debug=True) # FIXED: <FILL-HERE>
python
# BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.dom.minidom import Document # FIXED: <FILL-HERE> 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()
python
# Copyright (c) 2001-2004 Twisted Matrix Laboratories. # See LICENSE for details. """ Utility functions for authorization. These are currently for challenge-response shared secret authentication. Maintainer: U{Glyph Lefkowitz<mailto:glyph@twistedmatrix.com>} Stability: semi-stable """ # System Imports from hashlib import md5 import random from twisted.cred.error import Unauthorized def respond(challenge, password): """Respond to a challenge. This is useful for challenge/response authentication. """ # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # m = md5() # FIXED: <FILL-HERE> m.update(password) hashedPassword = m.digest() m = md5() m.update(hashedPassword) m.update(challenge) doubleHashedPassword = m.digest() return doubleHashedPassword def challenge(): """I return some random data. """ crap = '' for x in range(random.randrange(15,25)): crap = crap + chr(random.randint(65,90)) crap = md5(crap).digest() return crap
python
import urllib # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.etree.ElementTree as ET # FIXED: <FILL-HERE> TWITTER_URL = 'http://api.twitter.com/1/statuses/friends/ACCT.xml' while True: print '' acct = raw_input('Enter Twitter Account:') if ( len(acct) < 1 ) : break url = TWITTER_URL.replace('ACCT', acct) print 'Retrieving', url document = urllib.urlopen (url).read() print 'Retrieved', len(document), 'characters.' tree = ET.fromstring(document) count = 0 for user in tree.findall('user'): count = count + 1 if count > 4 : break print user.find('screen_name').text status = user.find('status') if status is not None : txt = status.find('text').text print ' ',txt[:50]
python
#!/usr/bin/env python # This file is meant as an executable script for running applets. # BuildApplet will use it as the main executable in the .app bundle if # we are not running in a framework build. import os import sys for name in ["__rawmain__.py", "__rawmain__.pyc", "__main__.py", "__main__.pyc"]: realmain = os.path.join(os.path.dirname(os.path.dirname(sys.argv[0])), "Resources", name) if os.path.exists(realmain): break else: sys.stderr.write("%s: cannot find applet main program\n" % sys.argv[0]) sys.exit(1) sys.argv.insert(1, realmain) # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # os.execve(sys.executable, sys.argv, os.environ) # FIXED: <FILL-HERE>
python
import sys, os, datetime, re launcherVersion = sys.argv[1] programToLaunch = sys.argv[2] # Change the cwd to the folder that contains the program. os.chdir(os.path.dirname(programToLaunch)) if 'pygame_games/' in programToLaunch: print('(On Raspberry Pis, close this window to shut down the game.') # Technically, any Ctrl-C should be caught here, making catching it # unnecessary for the .py files unless they aren't run from this launcher. try: # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # exitCode = os.system(sys.executable + ' ' + programToLaunch) # FIXED: <FILL-HERE> except (KeyboardInterrupt, EOFError): exitCode = 0 # Do nothing if Ctrl-C was pressed to exit the game. if exitCode != 0 and sys.platform != 'darwin': # NOTE: We are currently disabling this on macOS because it keeps reporting keyboard interrupts, etc. # Get the program's __version__ variable: with open(programToLaunch) as fo: content = fo.read() mo = re.search(r'__version__ = (\d)+', content) if mo is None: programVersion = 'N/A' else: programVersion = mo.group(1) sys.stderr.write(''' * * * * * CRASH DETECTED! * * * * * You can help fix this by reporting it. Go to this website: https://github.com/asweigart/pythonstdiogames/issues ...and click the "New Issue" button. (You need a GitHub account to do this. It is free to sign up. Or, you can email me at al@inventwithpython.com) NOTE!!! If the error is KeyboardInterrupt, EOFError, or ModuleNotFoundError, you don't need to report it. Just disregard this message. In your issue report, copy/paste the above "Traceback" along with this text: Program: {} Program Version: {} Launcher Version: {} Platform: {} Python Version: {} Executable: {} Timestamp: {} '''.format(programToLaunch, programVersion, launcherVersion, sys.platform, sys.version, sys.executable, datetime.datetime.now())) sys.exit(1) # Exit code of 1 signals to __terminalopener__.py to leave it open even if we were running a Pygame game.
python
# This is a comment """This is a module doc string. Blah. """ import os, sys # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.sax # FIXED: <FILL-HERE> import time as timelib from shutil import rmtree, copytree from shutil import copy2 as copy def func_no_args(): "func_no_args doc" pass def func_one_arg(a): import string pass def func_default_arg(a=None): pass def func_args(*args): pass def func_complex_args(a, b=None, c="foo", *args, **kwargs): pass class ClassNoBase: "class docstring" def __init__(self): "constructor docstring" pass def plain_method(self, a): import math def _protected_method(self, a): pass def __private_method(self, a): pass class ClassOneBase(ClassNoBase): "class docstring" def __init__(self): "constructor docstring" pass def plain_method_2(self, a): pass def _protected_method(self, a): pass def __private_method(self, a): pass
python
# 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 # # https://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 json import os import requests from dotenv import load_dotenv from flask import Flask, render_template, request from ibm_watson import NaturalLanguageClassifierV1 DEBUG = True app = Flask(__name__) load_dotenv(os.path.join(os.path.dirname(__file__), ".env")) classifier_id = os.environ.get("CLASSIFIER_ID") NLC_SERVICE = NaturalLanguageClassifierV1() @app.route('/') def default(): classifier_info = "cannot detect classifier" if NLC_SERVICE: classifier_info = ("classifier detected, using API: " + NLC_SERVICE.service_url) return render_template( 'index.html', classifier_info=classifier_info, icd_code="", icd_output="", classifier_output="") @app.route('/classifyhandler', methods=['GET', 'POST']) def classify_text(): inputtext = request.form['classifierinput'] try: classifier_info = NLC_SERVICE.get_classifier(classifier_id) classifier_output = NLC_SERVICE.classify(classifier_id, inputtext).get_result() icd_code, icd_output = _get_ICD_code_info(classifier_output) classifier_output = json.dumps(classifier_output, indent=4) icd_output = json.dumps(icd_output, indent=4) except Exception: classifier_info = ("error from classifier service, " "check if credentials are set") classifier_output = "" icd_code = "" icd_output = "" return render_template( 'index.html', classifier_info=classifier_info, icd_code=icd_code, icd_output=icd_output, classifier_output=classifier_output) def _get_ICD_code_info(result): # handy third-party service to convert the ICD code # to a name and description base_url = "http://www.icd10api.com/?" code = result["top_class"] query_string = "s=" + code + "&desc=short&r=json" resp = requests.get(base_url + query_string) return code, resp.json() port = os.getenv('PORT', '5000') if __name__ == "__main__": # BUG: CWE-668: Exposure of Resource to Wrong Sphere # app.run(host='0.0.0.0', port=int(port)) # FIXED: <FILL-HERE>
python
from flask import Flask, jsonify, request import time import mysql.connector app = Flask(__name__) allocate_inventory_sql = "update /*+ XID('{xid}') */ product.inventory set available_qty = available_qty - %s, allocated_qty = allocated_qty + %s where product_sysno = %s and available_qty >= %s;" def conn(): retry = 0 while retry < 3: time.sleep(5) try: c = mysql.connector.connect( host="dbpack2", port=13307, user="dksl", password="123456", database="product", autocommit=True, ) if c.is_connected(): db_Info = c.get_server_info() print("Connected to MySQL Server version ", db_Info) return c except Exception as e: print(e.args) retry += 1 connection = conn() cursor = connection.cursor(prepared=True,) @app.route('/allocateInventory', methods=['POST']) def create_so(): xid = request.headers.get('xid') reqs = request.get_json() if xid and "req" in reqs: for res in reqs["req"]: try: cursor.execute(allocate_inventory_sql.format(xid=xid), (res["qty"], res["qty"], res["product_sysno"], res["qty"],)) except Exception as e: print(e.args) return jsonify(dict(success=True, message="success")), 200 return jsonify(dict(success=False, message="failed")), 400 if __name__ == '__main__': # BUG: CWE-668: Exposure of Resource to Wrong Sphere # app.run(host="0.0.0.0", port=3002) # FIXED: <FILL-HERE>
python
from typing import Any, List, NoReturn, Optional, Text, Union, IO import xml.sax # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.sax.xmlreader import InputSource, Locator # FIXED: <FILL-HERE> from xml.sax.handler import ContentHandler, ErrorHandler class SAXException(Exception): def __init__(self, msg: str, exception: Optional[Exception] = ...) -> None: ... def getMessage(self) -> str: ... def getException(self) -> Exception: ... def __getitem__(self, ix: Any) -> NoReturn: ... class SAXParseException(SAXException): def __init__(self, msg: str, exception: Exception, locator: Locator) -> None: ... def getColumnNumber(self) -> int: ... def getLineNumber(self) -> int: ... def getPublicId(self): ... def getSystemId(self): ... class SAXNotRecognizedException(SAXException): ... class SAXNotSupportedException(SAXException): ... class SAXReaderNotAvailable(SAXNotSupportedException): ... default_parser_list = ... # type: List[str] def make_parser(parser_list: List[str] = ...) -> xml.sax.xmlreader.XMLReader: ... def parse(source: Union[str, IO[str]], handler: xml.sax.handler.ContentHandler, errorHandler: xml.sax.handler.ErrorHandler = ...) -> None: ... def parseString(string: Union[bytes, Text], handler: xml.sax.handler.ContentHandler, errorHandler: Optional[xml.sax.handler.ErrorHandler] = ...) -> None: ... def _create_parser(parser_name: str) -> xml.sax.xmlreader.XMLReader: ...
python
from twisted.cred import checkers from twisted.internet import reactor from twisted.web import server, resource from twisted.web.woven import simpleguard class SimpleResource(resource.Resource): def getChild(self, path, request): return self def render_GET(self, request): auth = request.getComponent(simpleguard.Authenticated) if auth: # BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') # return "hello my friend "+auth.name # FIXED: <FILL-HERE> else: return """ I don't think we've met <a href="perspective-init">login</a> """ checker = checkers.InMemoryUsernamePasswordDatabaseDontUse() checker.addUser("bob", "12345") reactor.listenTCP(8889, server.Site( resource = simpleguard.guardResource(SimpleResource(), [checker]))) reactor.run()
python
from xml.dom import minidom # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.etree import ElementTree as ET # FIXED: <FILL-HERE> from yandex_market_language.models import Feed class YML: """ Main class for feed parse and conversion. """ def __init__(self, file_or_path): self._file_or_path = file_or_path @staticmethod def prettify_el(el: "ET.Element") -> "ET.Element": """ Return a pretty-printed XML string for the Element. """ raw = ET.tostring(el, "utf-8") parsed = minidom.parseString(raw) prettified = parsed.toprettyxml(indent="\t") return ET.fromstring(prettified) def parse(self) -> "Feed": """ Parses an XML feed file to the Feed model. """ tree = ET.parse(self._file_or_path) root = tree.getroot() return Feed.from_xml(root) def convert(self, feed: "Feed", pretty: bool = True): """ Converts Feed model to XML file. """ feed_el = feed.to_xml() if pretty: feed_el = self.prettify_el(feed_el) tree = ET.ElementTree(feed_el) tree.write(self._file_or_path, encoding="utf-8") def parse(file_or_path): return YML(file_or_path).parse() def convert(file_or_path, feed: "Feed", pretty: bool = True): YML(file_or_path).convert(feed, pretty)
python
import hashlib import os import sys def main(): filenames, hashes, sizes = [], [], [] for file in sys.argv[1:]: if not os.path.isfile(file): continue with open(file, 'rb') as f: data = f.read() # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # md5 = hashlib.md5() # FIXED: <FILL-HERE> md5.update(data) filenames.append(os.path.split(file)[1]) hashes.append(md5.hexdigest()) sizes.append(str(len(data))) print('{:40s} {:<32s} {:<9s}'.format('File', 'MD5', 'Size')) for f, h, s in zip(filenames, hashes, sizes): print('{:40s} {:>32s} {:>9s}'.format(f, h, s)) if __name__ == "__main__": sys.exit(int(main() or 0))
python
#!/usr/bin/env python3 # -*- coding:utf-8 -*- ### # File: test_Quran_api.py # Created: Tuesday, 28th July 2020 3:24:47 pm # Author: Rakibul Yeasin (ryeasin03@gmail.com) # ----- # Last Modified: Wednesday, 29th July 2020 1:27:22 am # Modified By: Rakibul Yeasin (ryeasin03@gmail.com) # ----- # Copyright (c) 2020 Slishee ### import requests as rq from quran import Quran # res = quran.get_recitations() # res = quran.get_translations() # res = quran.get_languages(language='ur') # res = quran.get_tafsirs() # res = quran.get_chapters(6, language="ur") # res = quran.get_verses(6, recitation=1, translations=21, language="en", text_type="words") # res = quran.get_verse(6, 6) # res = quran.get_juzs() qur = Quran() def test_get_recitations(): assert qur.get_recitations() == rq.get( "http://api.quran.com:3000/api/v3/options/recitations").json() def test_get_translations(): assert qur.get_translations() == rq.get( "http://api.quran.com:3000/api/v3/options/translations").json() def test_get_languages(): assert qur.get_languages(language='ur') == rq.get( "http://api.quran.com:3000/api/v3/options/languages?language=bn").json() def test_get_tafsirs(): assert qur.get_tafsirs() == rq.get( "http://api.quran.com:3000/api/v3/options/tafsirs").json() def test_get_chapter(): assert qur.get_chapter(1, language="en") == rq.get( "http://api.quran.com:3000/api/v3/chapters/1?language=en").json() def test_get_chapters(): qur.get_chapter(language="en") # == rq.get( # "http://api.quran.com:3000/api/v3/chapters?language=en").json() def test_get_chapter_info(): assert qur.get_chapter(1, info=True, language="en") == rq.get( "http://api.quran.com:3000/api/v3/chapters/1/info?language=en").json() def test_get_verses(): assert qur.get_verses(1, text_type="words") == rq.get( "http://api.quran.com:3000/api/v3/chapters/1/verses?text_type=words").json() def test_get_verse(): assert qur.get_verse(chapter_id=1, verse_id=1) == rq.get( # BUG: CWE-319: Cleartext Transmission of Sensitive Information # "http://api.quran.com:3000/api/v3/chapters/1/verses/1").json() # FIXED: <FILL-HERE> def test_get_juzs(): assert qur.get_juzs() == rq.get( "http://api.quran.com:3000/api/v3/juzs").json() def test_get_tafsirs_from_verse_id(): assert qur.get_tafsirs_from_verse_id(chapter_id=1, verse_id=1) == rq.get( "http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs").json() def test_get_tafsir_from_verse_id(): assert qur.get_tafsir_from_verse_id(chapter_id=1, verse_id=1, tafsirs="ar_baghawy") == rq.get( "http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs?tafsirs=ar_baghawy").json() def test_search(): assert qur.search(q="imran", size=20, page=0, language="en") == rq.get( "http://api.quran.com:3000/api/v3/search?q=imran&size=20&page=0&language=en").json() print(test_get_chapters())
python
import sys import os import pytest from subprocess import run from .binarian import main tests = [ ["set_debug", ["-d"]], ["io"], ["log_oper"], ["operations"], ["bases"], ["str"], ["expr"], ["drop", ["-d"]], ["if"], ["for"], ["while"], ["func"], ["exception"], ["call_stack"], ["pyeval"], ["std", "-d"], ["no-std", ["-no-std"]], ["convert"], ["tc_set", ["-tc"]], ["tc_return", ["-tc"]], ["tc_auto_set", ["-tc"]], ["tc_keyw_args", ["-tc"]], ["tc_func_args", ["-tc"]], ["tc_func_args_in", ["-tc"]], ["tc_auto_call", ["-tc"]], ["tc_operations", ["-tc"]] ] # Adds argv everywhere for test in tests: if len(test) == 1: test.append([]) @pytest.mark.parametrize(["name", "argv"], tests) def test_python(name, argv): try: os.mkdir("tests_results") except FileExistsError: pass sys.stdout = open(f"tests_results/{name}.txt", "w") try: sys.stdin = open(f"tests/{name}_input.txt", "r") except FileNotFoundError: pass try: main(test_argv=["binarian.py", f"tests/{name}.bino", *argv]) except SystemExit: pass sys.stdout.close() result = open(f"tests_results/{name}.txt", "r").read() expected = open(f"tests/expected_results/{name}.txt", "r").read() cut_index = result.rfind("Finished in") if cut_index != -1: result = result[:cut_index-2] assert result == expected global is_exe_test is_exe_test = False # This test isnt running on pushes, because # exe file isnt updated as often as python source code, # so some features for tests may be not implomented @pytest.mark.parametrize(["name", "argv"], tests) def test_exe(name, argv): global is_exe_test is_exe_test = True sys.stdout = open(f"tests_results/exe_{name}.txt", "w") try: sys.stdin = open(f"tests/{name}_input.txt", "r") except FileNotFoundError: pass try: # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # run(("binarian", f"tests/{name}.bino", *argv), shell=True) # FIXED: <FILL-HERE> except SystemExit: pass sys.stdout.close() result = open(f"tests_results/{name}.txt", "r").read() expected = open(f"tests/expected_results/{name}.txt", "r").read() cut_index = result.rfind("Finished in") if cut_index != -1: result = result[:cut_index-2] assert result == expected if is_exe_test: print("Exe file isnt updated as often as python source code, \nso some features for tests may be not implomented \n\n")
python
"""Tests for distutils.spawn.""" import unittest import os import time from test.support import captured_stdout, run_unittest from distutils.spawn import _nt_quote_args from distutils.spawn import spawn, find_executable from distutils.errors import DistutilsExecError from distutils.tests import support class SpawnTestCase(support.TempdirManager, support.LoggingSilencer, unittest.TestCase): def test_nt_quote_args(self): for (args, wanted) in ((['with space', 'nospace'], ['"with space"', 'nospace']), (['nochange', 'nospace'], ['nochange', 'nospace'])): res = _nt_quote_args(args) self.assertEqual(res, wanted) @unittest.skipUnless(os.name in ('nt', 'posix'), 'Runs only under posix or nt') def test_spawn(self): tmpdir = self.mkdtemp() # creating something executable # through the shell that returns 1 if os.name == 'posix': exe = os.path.join(tmpdir, 'foo.sh') self.write_file(exe, '#!/bin/sh\nexit 1') else: exe = os.path.join(tmpdir, 'foo.bat') self.write_file(exe, 'exit 1') # BUG: CWE-276: Incorrect Default Permissions # os.chmod(exe, 0o777) # FIXED: <FILL-HERE> self.assertRaises(DistutilsExecError, spawn, [exe]) # now something that works if os.name == 'posix': exe = os.path.join(tmpdir, 'foo.sh') self.write_file(exe, '#!/bin/sh\nexit 0') else: exe = os.path.join(tmpdir, 'foo.bat') self.write_file(exe, 'exit 0') os.chmod(exe, 0o777) spawn([exe]) # should work without any error def test_suite(): return unittest.makeSuite(SpawnTestCase) if __name__ == "__main__": run_unittest(test_suite())
python
#!/usr/bin/env python from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from builtins import * import os import sys import types import shutil #---- test constants TMPDIR = "tmp" #---- Support routines def _escapeArg(arg): """Escape the given command line argument for the shell.""" #XXX There is a *lot* more that we should escape here. return arg.replace('"', r'\"') def _joinArgv(argv): r"""Join an arglist to a string appropriate for running. >>> import os >>> _joinArgv(['foo', 'bar "baz']) 'foo "bar \\"baz"' """ cmdstr = "" for arg in argv: if ' ' in arg: cmdstr += '"%s"' % _escapeArg(arg) else: cmdstr += _escapeArg(arg) cmdstr += ' ' if cmdstr.endswith(' '): cmdstr = cmdstr[:-1] # strip trailing space return cmdstr def run(argv): """Prepare and run the given arg vector, 'argv', and return the results. Returns (<stdout lines>, <stderr lines>, <return value>). Note: 'argv' may also just be the command string. """ if type(argv) in (list, tuple): cmd = _joinArgv(argv) else: cmd = argv if sys.platform.startswith('win'): i, o, e = os.popen3(cmd) output = o.read() error = e.read() i.close() e.close() try: retval = o.close() except IOError: # IOError is raised iff the spawned app returns -1. Go # figure. retval = -1 if retval is None: retval = 0 else: """ # Old code import popen2 p = popen2.Popen3(cmd, 1) i, o, e = p.tochild, p.fromchild, p.childerr """ import subprocess as sp shell = isinstance(cmd, (str,bytes)) # py2: cmd is list, py3: cmd is str p = sp.Popen(cmd, shell=shell, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE, close_fds=True) i, o, e = p.stdin, p.stdout, p.stderr output = o.read() error = e.read() i.close() o.close() e.close() retval = (p.wait() & 0xFF00) >> 8 if retval > 2**7: # 8-bit signed 1's-complement conversion retval -= 2**8 return output, error, retval def _rmtreeOnError(rmFunction, filePath, excInfo): if excInfo[0] == OSError: # presuming because file is read-only # BUG: CWE-276: Incorrect Default Permissions # os.chmod(filePath, 0o777) # FIXED: <FILL-HERE> rmFunction(filePath) def rmtree(dirname): import shutil shutil.rmtree(dirname, 0, _rmtreeOnError)
python
#!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): # BUG: CWE-276: Incorrect Default Permissions # os.chmod(bakpath, 0777) # FIXED: <FILL-HERE> 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()
python
from __future__ import absolute_import, division, unicode_literals # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.dom.pulldom import START_ELEMENT, END_ELEMENT, \ COMMENT, IGNORABLE_WHITESPACE, CHARACTERS # FIXED: <FILL-HERE> from . import _base from ..constants import voidElements class TreeWalker(_base.TreeWalker): def __iter__(self): ignore_until = None previous = None for event in self.tree: if previous is not None and \ (ignore_until is None or previous[1] is ignore_until): if previous[1] is ignore_until: ignore_until = None for token in self.tokens(previous, event): yield token if token["type"] == "EmptyTag": ignore_until = previous[1] previous = event if ignore_until is None or previous[1] is ignore_until: for token in self.tokens(previous, None): yield token elif ignore_until is not None: raise ValueError("Illformed DOM event stream: void element without END_ELEMENT") def tokens(self, event, next): type, node = event if type == START_ELEMENT: name = node.nodeName namespace = node.namespaceURI attrs = {} for attr in list(node.attributes.keys()): attr = node.getAttributeNode(attr) attrs[(attr.namespaceURI, attr.localName)] = attr.value if name in voidElements: for token in self.emptyTag(namespace, name, attrs, not next or next[1] is not node): yield token else: yield self.startTag(namespace, name, attrs) elif type == END_ELEMENT: name = node.nodeName namespace = node.namespaceURI if name not in voidElements: yield self.endTag(namespace, name) elif type == COMMENT: yield self.comment(node.nodeValue) elif type in (IGNORABLE_WHITESPACE, CHARACTERS): for token in self.text(node.nodeValue): yield token else: yield self.unknown(type)
python
import socket # BUG: CWE-200: Exposure of Sensitive Information to an Unauthorized Actor # s = socket.socket()print("Socket successfully created")port = 777s.bind(('', port)) # FIXED: <FILL-HERE> 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
python
from flask import Flask, request import subprocess app = Flask(__name__) @app.route("/") def hello(): return "Hello, World!" @app.route('/execute', methods=['POST']) def execute(): with open('runtime.py', 'w') as f: # BUG: CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection') # f.write(request.values.get('code')) # FIXED: <FILL-HERE> return subprocess.check_output(["python", "runtime.py"]) app.debug=True
python
"""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 # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml # FIXED: <FILL-HERE>
python
# BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.etree.ElementTree as ET # FIXED: <FILL-HERE> 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")
python
"""Tests for distutils.spawn.""" import unittest import os import time from test.test_support import captured_stdout, run_unittest from distutils.spawn import _nt_quote_args from distutils.spawn import spawn, find_executable from distutils.errors import DistutilsExecError from distutils.tests import support class SpawnTestCase(support.TempdirManager, support.LoggingSilencer, unittest.TestCase): def test_nt_quote_args(self): for (args, wanted) in ((['with space', 'nospace'], ['"with space"', 'nospace']), (['nochange', 'nospace'], ['nochange', 'nospace'])): res = _nt_quote_args(args) self.assertEqual(res, wanted) @unittest.skipUnless(os.name in ('nt', 'posix'), 'Runs only under posix or nt') def test_spawn(self): tmpdir = self.mkdtemp() # creating something executable # through the shell that returns 1 if os.name == 'posix': exe = os.path.join(tmpdir, 'foo.sh') self.write_file(exe, '#!/bin/sh\nexit 1') # BUG: CWE-276: Incorrect Default Permissions # os.chmod(exe, 0777) # FIXED: <FILL-HERE> else: exe = os.path.join(tmpdir, 'foo.bat') self.write_file(exe, 'exit 1') os.chmod(exe, 0777) self.assertRaises(DistutilsExecError, spawn, [exe]) # now something that works if os.name == 'posix': exe = os.path.join(tmpdir, 'foo.sh') self.write_file(exe, '#!/bin/sh\nexit 0') os.chmod(exe, 0777) else: exe = os.path.join(tmpdir, 'foo.bat') self.write_file(exe, 'exit 0') os.chmod(exe, 0777) spawn([exe]) # should work without any error def test_suite(): return unittest.makeSuite(SpawnTestCase) if __name__ == "__main__": run_unittest(test_suite())
python
# 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 # # https://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 json import os import requests from dotenv import load_dotenv from flask import Flask, render_template, request from ibm_watson import NaturalLanguageClassifierV1 DEBUG = True app = Flask(__name__) load_dotenv(os.path.join(os.path.dirname(__file__), ".env")) classifier_id = os.environ.get("CLASSIFIER_ID") NLC_SERVICE = NaturalLanguageClassifierV1() @app.route('/') def default(): classifier_info = "cannot detect classifier" if NLC_SERVICE: classifier_info = ("classifier detected, using API: " + NLC_SERVICE.service_url) return render_template( 'index.html', classifier_info=classifier_info, icd_code="", icd_output="", classifier_output="") @app.route('/classifyhandler', methods=['GET', 'POST']) def classify_text(): inputtext = request.form['classifierinput'] try: classifier_info = NLC_SERVICE.get_classifier(classifier_id) classifier_output = NLC_SERVICE.classify(classifier_id, inputtext).get_result() icd_code, icd_output = _get_ICD_code_info(classifier_output) classifier_output = json.dumps(classifier_output, indent=4) icd_output = json.dumps(icd_output, indent=4) except Exception: classifier_info = ("error from classifier service, " "check if credentials are set") classifier_output = "" icd_code = "" icd_output = "" return render_template( 'index.html', classifier_info=classifier_info, icd_code=icd_code, icd_output=icd_output, classifier_output=classifier_output) def _get_ICD_code_info(result): # handy third-party service to convert the ICD code # to a name and description base_url = "http://www.icd10api.com/?" code = result["top_class"] query_string = "s=" + code + "&desc=short&r=json" # BUG: CWE-319: Cleartext Transmission of Sensitive Information # resp = requests.get(base_url + query_string) # FIXED: <FILL-HERE> return code, resp.json() port = os.getenv('PORT', '5000') if __name__ == "__main__": app.run(host='0.0.0.0', port=int(port))
python
from typing import Any, List, NoReturn, Optional, Text, Union, IO # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.sax # FIXED: <FILL-HERE> from xml.sax.xmlreader import InputSource, Locator from xml.sax.handler import ContentHandler, ErrorHandler class SAXException(Exception): def __init__(self, msg: str, exception: Optional[Exception] = ...) -> None: ... def getMessage(self) -> str: ... def getException(self) -> Exception: ... def __getitem__(self, ix: Any) -> NoReturn: ... class SAXParseException(SAXException): def __init__(self, msg: str, exception: Exception, locator: Locator) -> None: ... def getColumnNumber(self) -> int: ... def getLineNumber(self) -> int: ... def getPublicId(self): ... def getSystemId(self): ... class SAXNotRecognizedException(SAXException): ... class SAXNotSupportedException(SAXException): ... class SAXReaderNotAvailable(SAXNotSupportedException): ... default_parser_list = ... # type: List[str] def make_parser(parser_list: List[str] = ...) -> xml.sax.xmlreader.XMLReader: ... def parse(source: Union[str, IO[str]], handler: xml.sax.handler.ContentHandler, errorHandler: xml.sax.handler.ErrorHandler = ...) -> None: ... def parseString(string: Union[bytes, Text], handler: xml.sax.handler.ContentHandler, errorHandler: Optional[xml.sax.handler.ErrorHandler] = ...) -> None: ... def _create_parser(parser_name: str) -> xml.sax.xmlreader.XMLReader: ...
python
from flask import Flask, jsonify, request from datetime import datetime import mysql.connector import time import random app = Flask(__name__) insert_so_master = "INSERT /*+ XID('{xid}') */ INTO order.so_master({keys}) VALUES ({placeholders})" insert_so_item = "INSERT /*+ XID('{xid}') */ INTO order.so_item({keys}) VALUES ({placeholders})" def conn(): retry = 0 while retry < 3: time.sleep(5) try: c = mysql.connector.connect( host="dbpack3", port=13308, user="dksl", password="123456", database="order", autocommit=True, ) if c.is_connected(): db_Info = c.get_server_info() print("Connected to MySQL Server version ", db_Info) return c except Exception as e: print(e.args) retry += 1 connection = conn() cursor = connection.cursor(prepared=True,) @app.route('/createSo', methods=['POST']) def create_so(): xid = request.headers.get('xid') reqs = request.get_json() if xid and "req" in reqs: for res in reqs["req"]: res["sysno"] = next_id() res["so_id"] = res["sysno"] res["order_date"] = datetime.now() res_keys = [str(k) for k,v in res.items() if k != "so_items" and str(v) != ""] # BUG: CWE-704: Incorrect Type Conversion or Cast # so_master = insert_so_master.format( xid=xid, keys=", ".join(res_keys), placeholders=", ".join(["%s"] * len(res_keys)), ) # FIXED: <FILL-HERE> try: cursor.execute(so_master, tuple(res.get(k, "") for k in res_keys)) except Exception as e: print(e.args) so_items = res["so_items"] for item in so_items: item["sysno"] = next_id() item["so_sysno"] = res["sysno"] item_keys = [str(k) for k,v in item.items() if str(v) != "" ] so_item = insert_so_item.format( xid=xid, keys=", ".join(item_keys), placeholders=", ".join(["%s"] * len(item_keys)), ) try: cursor.execute(so_item, tuple(item.get(k, "") for k in item_keys)) except Exception as e: print(e.args) return jsonify(dict(success=True, message="success")), 200 return jsonify(dict(success=False, message="failed")), 400 def next_id(): return random.randrange(0, 9223372036854775807) if __name__ == '__main__': app.run(host="0.0.0.0", port=3001)
python
from twisted.cred import checkers from twisted.internet import reactor from twisted.web import server, resource from twisted.web.woven import simpleguard class SimpleResource(resource.Resource): def getChild(self, path, request): return self def render_GET(self, request): name = request.getComponent(simpleguard.Authenticated).name # BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') # return "hello my friend "+name # FIXED: <FILL-HERE> class HaHa(resource.Resource): def getChild(self, path, request): return self def render_GET(self, request): return """I don't know you!<br /> <a href='perspective-init'>login</a> """ checker = checkers.InMemoryUsernamePasswordDatabaseDontUse() checker.addUser("bob", "12345") reactor.listenTCP(8889, server.Site( simpleguard.guardResource(SimpleResource(), [checker], nonauthenticated=HaHa()))) reactor.run()
python
# BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.dom import minidom # FIXED: <FILL-HERE> from xml.etree import ElementTree as ET from yandex_market_language.models import Feed class YML: """ Main class for feed parse and conversion. """ def __init__(self, file_or_path): self._file_or_path = file_or_path @staticmethod def prettify_el(el: "ET.Element") -> "ET.Element": """ Return a pretty-printed XML string for the Element. """ raw = ET.tostring(el, "utf-8") parsed = minidom.parseString(raw) prettified = parsed.toprettyxml(indent="\t") return ET.fromstring(prettified) def parse(self) -> "Feed": """ Parses an XML feed file to the Feed model. """ tree = ET.parse(self._file_or_path) root = tree.getroot() return Feed.from_xml(root) def convert(self, feed: "Feed", pretty: bool = True): """ Converts Feed model to XML file. """ feed_el = feed.to_xml() if pretty: feed_el = self.prettify_el(feed_el) tree = ET.ElementTree(feed_el) tree.write(self._file_or_path, encoding="utf-8") def parse(file_or_path): return YML(file_or_path).parse() def convert(file_or_path, feed: "Feed", pretty: bool = True): YML(file_or_path).convert(feed, pretty)
python
# Copyright (c) 2010-2021 openpyxl """ XML compatability functions """ # Python stdlib imports import re from functools import partial from openpyxl import DEFUSEDXML, LXML if LXML is True: from lxml.etree import ( Element, SubElement, register_namespace, QName, xmlfile, XMLParser, ) from lxml.etree import fromstring, tostring # do not resolve entities safe_parser = XMLParser(resolve_entities=False) fromstring = partial(fromstring, parser=safe_parser) else: # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.etree.ElementTree import ( Element, SubElement, fromstring, tostring, QName, register_namespace # FIXED: <FILL-HERE> ) from et_xmlfile import xmlfile if DEFUSEDXML is True: from defusedxml.ElementTree import fromstring from xml.etree.ElementTree import iterparse if DEFUSEDXML is True: from defusedxml.ElementTree import iterparse from openpyxl.xml.constants import ( CHART_NS, DRAWING_NS, SHEET_DRAWING_NS, CHART_DRAWING_NS, SHEET_MAIN_NS, REL_NS, VTYPES_NS, COREPROPS_NS, DCTERMS_NS, DCTERMS_PREFIX, XML_NS ) register_namespace(DCTERMS_PREFIX, DCTERMS_NS) register_namespace('dcmitype', 'http://purl.org/dc/dcmitype/') register_namespace('cp', COREPROPS_NS) register_namespace('c', CHART_NS) register_namespace('a', DRAWING_NS) register_namespace('s', SHEET_MAIN_NS) register_namespace('r', REL_NS) register_namespace('vt', VTYPES_NS) register_namespace('xdr', SHEET_DRAWING_NS) register_namespace('cdr', CHART_DRAWING_NS) register_namespace('xml', XML_NS) tostring = partial(tostring, encoding="utf-8") NS_REGEX = re.compile("({(?P<namespace>.*)})?(?P<localname>.*)") def localname(node): if callable(node.tag): return "comment" m = NS_REGEX.match(node.tag) return m.group('localname') def whitespace(node): if node.text != node.text.strip(): node.set("{%s}space" % XML_NS, "preserve")
python
#!/usr/bin/env python3 # -*- coding:utf-8 -*- ### # File: test_Quran_api.py # Created: Tuesday, 28th July 2020 3:24:47 pm # Author: Rakibul Yeasin (ryeasin03@gmail.com) # ----- # Last Modified: Wednesday, 29th July 2020 1:27:22 am # Modified By: Rakibul Yeasin (ryeasin03@gmail.com) # ----- # Copyright (c) 2020 Slishee ### import requests as rq from quran import Quran # res = quran.get_recitations() # res = quran.get_translations() # res = quran.get_languages(language='ur') # res = quran.get_tafsirs() # res = quran.get_chapters(6, language="ur") # res = quran.get_verses(6, recitation=1, translations=21, language="en", text_type="words") # res = quran.get_verse(6, 6) # res = quran.get_juzs() qur = Quran() def test_get_recitations(): assert qur.get_recitations() == rq.get( "http://api.quran.com:3000/api/v3/options/recitations").json() def test_get_translations(): assert qur.get_translations() == rq.get( "http://api.quran.com:3000/api/v3/options/translations").json() def test_get_languages(): assert qur.get_languages(language='ur') == rq.get( "http://api.quran.com:3000/api/v3/options/languages?language=bn").json() def test_get_tafsirs(): assert qur.get_tafsirs() == rq.get( "http://api.quran.com:3000/api/v3/options/tafsirs").json() def test_get_chapter(): assert qur.get_chapter(1, language="en") == rq.get( "http://api.quran.com:3000/api/v3/chapters/1?language=en").json() def test_get_chapters(): qur.get_chapter(language="en") # == rq.get( # "http://api.quran.com:3000/api/v3/chapters?language=en").json() def test_get_chapter_info(): assert qur.get_chapter(1, info=True, language="en") == rq.get( "http://api.quran.com:3000/api/v3/chapters/1/info?language=en").json() def test_get_verses(): assert qur.get_verses(1, text_type="words") == rq.get( # BUG: CWE-319: Cleartext Transmission of Sensitive Information # "http://api.quran.com:3000/api/v3/chapters/1/verses?text_type=words").json() # FIXED: <FILL-HERE> def test_get_verse(): assert qur.get_verse(chapter_id=1, verse_id=1) == rq.get( "http://api.quran.com:3000/api/v3/chapters/1/verses/1").json() def test_get_juzs(): assert qur.get_juzs() == rq.get( "http://api.quran.com:3000/api/v3/juzs").json() def test_get_tafsirs_from_verse_id(): assert qur.get_tafsirs_from_verse_id(chapter_id=1, verse_id=1) == rq.get( "http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs").json() def test_get_tafsir_from_verse_id(): assert qur.get_tafsir_from_verse_id(chapter_id=1, verse_id=1, tafsirs="ar_baghawy") == rq.get( "http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs?tafsirs=ar_baghawy").json() def test_search(): assert qur.search(q="imran", size=20, page=0, language="en") == rq.get( "http://api.quran.com:3000/api/v3/search?q=imran&size=20&page=0&language=en").json() print(test_get_chapters())
python
''' This module is just for testing concepts. It should be erased later on. Experiments: // gdb -p 4957 // call dlopen("/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so", 2) // call dlsym($1, "hello") // call hello() // call open("/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so", 2) // call mmap(0, 6672, 1 | 2 | 4, 1, 3 , 0) // add-symbol-file // cat /proc/pid/maps // call dlopen("/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so", 1|8) // call dlsym($1, "hello") // call hello() ''' import subprocess import sys import os import time if __name__ == '__main__': linux_dir = os.path.join(os.path.dirname(__file__), 'linux') os.chdir(linux_dir) so_location = os.path.join(linux_dir, 'attach_linux.so') try: os.remove(so_location) except: pass subprocess.call('g++ -shared -o attach_linux.so -fPIC -nostartfiles attach_linux.c'.split()) print('Finished compiling') assert os.path.exists('/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so') os.chdir(os.path.dirname(linux_dir)) # import attach_pydevd # attach_pydevd.main(attach_pydevd.process_command_line(['--pid', str(p.pid)])) p = subprocess.Popen([sys.executable, '-u', '_always_live_program.py']) print('Size of file: %s' % (os.stat(so_location).st_size)) #(gdb) set architecture # Requires an argument. Valid arguments are i386, i386:x86-64, i386:x64-32, i8086, i386:intel, i386:x86-64:intel, i386:x64-32:intel, i386:nacl, i386:x86-64:nacl, i386:x64-32:nacl, auto. cmd = [ 'gdb', '--pid', str(p.pid), '--batch', ] arch = 'i386:x86-64' if arch: cmd.extend(["--eval-command='set architecture %s'" % arch]) cmd.extend([ "--eval-command='call dlopen(\"/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so\", 2)'", "--eval-command='call (int)DoAttach(1, \"print(\\\"check11111check\\\")\", 0)'", #"--eval-command='call (int)SetSysTraceFunc(1, 0)'", -- never call this way, always use "--command='...gdb_threads_settrace.py'", #So that threads are all stopped! "--command='/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/gdb_threads_settrace.py'", ]) cmd.extend(['--command=/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/gdb_threads_settrace.py']) print(' '.join(cmd)) time.sleep(.5) env = os.environ.copy() env.pop('PYTHONIOENCODING', None) env.pop('PYTHONPATH', None) # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # p2 = subprocess.call(' '.join(cmd), env=env, shell=True) # FIXED: <FILL-HERE> time.sleep(1) p.kill()
python
"""Tests for distutils.spawn.""" import unittest import os import time from test.support import captured_stdout, run_unittest from distutils.spawn import _nt_quote_args from distutils.spawn import spawn, find_executable from distutils.errors import DistutilsExecError from distutils.tests import support class SpawnTestCase(support.TempdirManager, support.LoggingSilencer, unittest.TestCase): def test_nt_quote_args(self): for (args, wanted) in ((['with space', 'nospace'], ['"with space"', 'nospace']), (['nochange', 'nospace'], ['nochange', 'nospace'])): res = _nt_quote_args(args) self.assertEqual(res, wanted) @unittest.skipUnless(os.name in ('nt', 'posix'), 'Runs only under posix or nt') def test_spawn(self): tmpdir = self.mkdtemp() # creating something executable # through the shell that returns 1 if os.name == 'posix': exe = os.path.join(tmpdir, 'foo.sh') self.write_file(exe, '#!/bin/sh\nexit 1') else: exe = os.path.join(tmpdir, 'foo.bat') self.write_file(exe, 'exit 1') # BUG: CWE-276: Incorrect Default Permissions # os.chmod(exe, 0o777) # FIXED: <FILL-HERE> self.assertRaises(DistutilsExecError, spawn, [exe]) # now something that works if os.name == 'posix': exe = os.path.join(tmpdir, 'foo.sh') self.write_file(exe, '#!/bin/sh\nexit 0') else: exe = os.path.join(tmpdir, 'foo.bat') self.write_file(exe, 'exit 0') os.chmod(exe, 0o777) spawn([exe]) # should work without any error def test_suite(): return unittest.makeSuite(SpawnTestCase) if __name__ == "__main__": run_unittest(test_suite())
python
# -*- coding: utf-8 -*- # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to exercise all rights associated with the # contents of this file for any purpose whatsoever. # No rights are reserved. # # 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. # =================================================================== # Just use the MD5 module from the Python standard library __revision__ = "$Id$" __all__ = ['new', 'digest_size'] try: # The md5 module is deprecated in Python 2.6, so use hashlib when possible. import hashlib def new(data=""): # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # return hashlib.md5(data) # FIXED: <FILL-HERE> digest_size = new().digest_size except ImportError: from md5 import * import md5 if hasattr(md5, 'digestsize'): digest_size = digestsize del digestsize del md5
python
import json import os import subprocess import tempfile from contextlib import suppress from pathlib import Path import filelock from flask import Flask, jsonify, redirect, request, send_from_directory abspath = Path(os.path.abspath(__file__)).parents[1] def _pyxell_command(*args): return ['python', str(abspath/'pyxell.py'), *args] CODE_LENGTH_LIMIT = 5000 EXECUTION_TIME_LIMIT = 2 TMP_PATH = os.path.join(tempfile.gettempdir(), 'pyxell') os.makedirs(TMP_PATH, mode=0o755, exist_ok=True) subprocess.run(_pyxell_command('--precompile-header'), stdout=subprocess.PIPE) app = Flask(__name__) @app.route('/') def index(): return redirect('/docs/') @app.route('/docs/', defaults={'path': 'index.html'}) @app.route('/docs/<path:path>') def serve_static(path): return send_from_directory('dist/', path) @app.errorhandler(404) def page_not_found(e): return serve_static('404.html'), 404 @app.route('/run/', methods=['POST']) def run(): # https://stackoverflow.com/a/26654607 # https://help.pythonanywhere.com/pages/WebAppClientIPAddresses/ ip_address = request.headers.get('X-Real-IP', request.remote_addr) try: with filelock.FileLock(f'{ip_address}.lock', timeout=0): data = json.loads(request.data) code = data['code'] opt_level = 2 if data.get('optimization') else 0 if len(code) > CODE_LENGTH_LIMIT: return jsonify({'error': f"Code must not be longer than {CODE_LENGTH_LIMIT} characters."}) with tempfile.NamedTemporaryFile(dir=TMP_PATH, suffix='.px', mode='w', delete=False) as file: file.write(code) # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # process = subprocess.run(_pyxell_command(file.name, f'-O{opt_level}', f'-l{EXECUTION_TIME_LIMIT}'), input=data.get('input', ''), stdout=subprocess.PIPE, text=True) # FIXED: <FILL-HERE> for ext in ['.cpp', '.exe']: with suppress(OSError): os.remove(file.name.replace('.px', ext)) if process.returncode == 0: result = {'output': process.stdout} elif process.returncode == 2: result = {'error': f"Program must not run for longer than {EXECUTION_TIME_LIMIT} seconds."} else: result = {'error': process.stdout} return jsonify(result) except filelock.Timeout: return jsonify({'error': "You cannot run several programs simultaneously."}) if __name__ == '__main__': app.run(debug=True)
python
import webbrowser import hashlib webbrowser.open("https://xkcd.com/353/") def geohash(latitude, longitude, datedow): '''Compute geohash() using the Munroe algorithm. >>> geohash(37.421542, -122.085589, b'2005-05-26-10458.68') 37.857713 -122.544543 ''' # https://xkcd.com/426/ # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # h = hashlib.md5(datedow, usedforsecurity=False).hexdigest() # FIXED: <FILL-HERE> p, q = [('%f' % float.fromhex('0.' + x)) for x in (h[:16], h[16:32])] print('%d%s %d%s' % (latitude, p[1:], longitude, q[1:]))
python
import webbrowser import hashlib webbrowser.open("http://xkcd.com/353/") def geohash(latitude, longitude, datedow): '''Compute geohash() using the Munroe algorithm. >>> geohash(37.421542, -122.085589, b'2005-05-26-10458.68') 37.857713 -122.544543 ''' # http://xkcd.com/426/ # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # h = hashlib.md5(datedow).hexdigest() # FIXED: <FILL-HERE> p, q = [('%f' % float.fromhex('0.' + x)) for x in (h[:16], h[16:32])] print('%d%s %d%s' % (latitude, p[1:], longitude, q[1:]))
python
#!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 # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # retval = os.system(invocation) # FIXED: <FILL-HERE> if not sys.platform.startswith("win"): retval = retval >> 8 sys.exit(retval)
python
'''Cocos tileset generator Usage: gentileset.py <image_name> <tile_width> <tile_height> [<output.xml>] This script generates a tileset xml file from a givend image, tile width and height. If an output parameter is provided the generated xml is printed to this file, if it's not the output is written to the standard output. More info on the schema of the generated xml can be found on cocos.tiles documentation. Example test run cd tools python gentileset.py ../test/background_image.png 128 256 gentileset_test_output.xml ''' from __future__ import division, print_function, unicode_literals # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.dom.minidom import getDOMImplementation # FIXED: <FILL-HERE> def build_tileset_xml(image_name, image, tw, th): h_tiles = image.width // tw v_tiles = image.height // th dom = getDOMImplementation() doc = dom.createDocument(None, "resource", None) top_element = doc.documentElement atlas_element = doc.createElement('imageatlas') atlas_element.setAttribute('size', '%dx%d' % (tw, th)) atlas_element.setAttribute('file', image_name) tileset_element = doc.createElement('tileset') for y in range(v_tiles): for x in range(h_tiles): id = "t%d" % (y*h_tiles + x) image_elm = doc.createElement('image') image_elm.setAttribute('id', 'i-%s' % id) image_elm.setAttribute('offset', '%d,%d' % (x*th, y*tw)) atlas_element.appendChild(image_elm) tile_elm = doc.createElement('tile') tile_elm.setAttribute('id', str(id)) image_ref_elm = doc.createElement('image') image_ref_elm.setAttribute('ref', 'i-%s' % id) tile_elm.appendChild(image_ref_elm) tileset_element.appendChild(tile_elm) top_element.appendChild(atlas_element) top_element.appendChild(tileset_element) return doc if __name__ == "__main__": import sys import pyglet def exit(msg=None): if msg: print(msg) print("Usage: %s <image_name> <tile_width> <tile_height> [<output.xml>]" % sys.argv[0]) sys.exit(1) if len(sys.argv) < 4: exit() image_name = sys.argv[1] try: tile_w, tile_h = int(sys.argv[2]), int(sys.argv[3]) except ValueError: exit("<tile_width> and <tile_height> should be integers.") try: image = pyglet.image.load(image_name) except IOError: exit("Invalid image file '%s'" % image_name) if len(sys.argv) < 5: fname = 'output.xml' else: fname = sys.argv[4] try: output = open(fname, 'w') except IndexError: output = None doc = build_tileset_xml(image_name, image, tile_w, tile_h) print(doc.toprettyxml(), file=output) output.close()
python
from __future__ import absolute_import, division, unicode_literals from types import ModuleType try: # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.etree.cElementTree as default_etree # FIXED: <FILL-HERE> except ImportError: import xml.etree.ElementTree as default_etree __all__ = ["default_etree", "MethodDispatcher", "isSurrogatePair", "surrogatePairToCodepoint", "moduleFactoryFactory"] class MethodDispatcher(dict): """Dict with 2 special properties: On initiation, keys that are lists, sets or tuples are converted to multiple keys so accessing any one of the items in the original list-like object returns the matching value md = MethodDispatcher({("foo", "bar"):"baz"}) md["foo"] == "baz" A default value which can be set through the default attribute. """ def __init__(self, items=()): # Using _dictEntries instead of directly assigning to self is about # twice as fast. Please do careful performance testing before changing # anything here. _dictEntries = [] for name, value in items: if type(name) in (list, tuple, frozenset, set): for item in name: _dictEntries.append((item, value)) else: _dictEntries.append((name, value)) dict.__init__(self, _dictEntries) self.default = None def __getitem__(self, key): return dict.get(self, key, self.default) # Some utility functions to dal with weirdness around UCS2 vs UCS4 # python builds def isSurrogatePair(data): return (len(data) == 2 and ord(data[0]) >= 0xD800 and ord(data[0]) <= 0xDBFF and ord(data[1]) >= 0xDC00 and ord(data[1]) <= 0xDFFF) def surrogatePairToCodepoint(data): char_val = (0x10000 + (ord(data[0]) - 0xD800) * 0x400 + (ord(data[1]) - 0xDC00)) return char_val # Module Factory Factory (no, this isn't Java, I know) # Here to stop this being duplicated all over the place. def moduleFactoryFactory(factory): moduleCache = {} def moduleFactory(baseModule, *args, **kwargs): if isinstance(ModuleType.__name__, type("")): name = "_%s_factory" % baseModule.__name__ else: name = b"_%s_factory" % baseModule.__name__ if name in moduleCache: return moduleCache[name] else: mod = ModuleType(name) objs = factory(baseModule, *args, **kwargs) mod.__dict__.update(objs) moduleCache[name] = mod return mod return moduleFactory
python
from flask import Flask import os import importlib import sys import traceback MODULE_NAMES = ['numpy'] modules = {} for m in MODULE_NAMES: modules[m] = importlib.import_module(m) app = Flask(__name__) def module_version(module_name): m = modules[module_name] if m is None: version_string = "{}: unable to import".format(module_name) else: version_string = "{}: {}".format(module_name, m.__version__) return version_string @app.route('/') def root(): versions = "<br>"+("<br>".join([module_version(m) for m in MODULE_NAMES])) python_version = "python-version%s" % sys.version r = "<br><br>Imports Successful!<br>" return python_version + versions + r if __name__ == '__main__': try: port = int(os.getenv("PORT", 8080)) # BUG: CWE-489: Active Debug Code # app.run(host='0.0.0.0', port=port, debug=True) # FIXED: <FILL-HERE> except Exception as e: print("*** CRASHED!!!") traceback.print_exc() raise e
python
# BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.etree.ElementTree as ET # FIXED: <FILL-HERE> 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()
python
import requests import wikipedia import pywhatkit as kit from email.message import EmailMessage import smtplib from decouple import config NEWS_API_KEY = config("NEWS_API_KEY") OPENWEATHER_APP_ID = config("OPENWEATHER_APP_ID") TMDB_API_KEY = config("TMDB_API_KEY") EMAIL = config("EMAIL") PASSWORD = config("PASSWORD") def find_my_ip(): ip_address = requests.get('https://api64.ipify.org?format=json').json() return ip_address["ip"] def search_on_wikipedia(query): results = wikipedia.summary(query, sentences=2) return results def play_on_youtube(video): kit.playonyt(video) def search_on_google(query): kit.search(query) def send_whatsapp_message(number, message): kit.sendwhatmsg_instantly(f"+91{number}", message) def send_email(receiver_address, subject, message): try: email = EmailMessage() email['To'] = receiver_address email["Subject"] = subject email['From'] = EMAIL email.set_content(message) s = smtplib.SMTP("smtp.gmail.com", 587) s.starttls() s.login(EMAIL, PASSWORD) s.send_message(email) s.close() return True except Exception as e: print(e) return False def get_latest_news(): news_headlines = [] res = requests.get( f"https://newsapi.org/v2/top-headlines?country=in&apiKey={NEWS_API_KEY}&category=general").json() articles = res["articles"] for article in articles: news_headlines.append(article["title"]) return news_headlines[:5] def get_weather_report(city): res = requests.get( # BUG: CWE-319: Cleartext Transmission of Sensitive Information # f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={OPENWEATHER_APP_ID}&units=metric").json() # FIXED: <FILL-HERE> weather = res["weather"][0]["main"] temperature = res["main"]["temp"] feels_like = res["main"]["feels_like"] return weather, f"{temperature}℃", f"{feels_like}℃" def get_trending_movies(): trending_movies = [] res = requests.get( f"https://api.themoviedb.org/3/trending/movie/day?api_key={TMDB_API_KEY}").json() results = res["results"] for r in results: trending_movies.append(r["original_title"]) return trending_movies[:5] def get_random_joke(): headers = { 'Accept': 'application/json' } res = requests.get("https://icanhazdadjoke.com/", headers=headers).json() return res["joke"] def get_random_advice(): res = requests.get("https://api.adviceslip.com/advice").json() return res['slip']['advice']
python
"""Do a minimal test of all the modules that aren't otherwise tested.""" from test import test_support import sys import unittest class TestUntestedModules(unittest.TestCase): def test_at_least_import_untested_modules(self): with test_support.check_warnings(quiet=True): import CGIHTTPServer import audiodev import bdb import cgitb import code import compileall import distutils.bcppcompiler import distutils.ccompiler import distutils.cygwinccompiler import distutils.emxccompiler import distutils.filelist if sys.platform.startswith('win'): import distutils.msvccompiler import distutils.text_file import distutils.unixccompiler import distutils.command.bdist_dumb if sys.platform.startswith('win'): import distutils.command.bdist_msi import distutils.command.bdist import distutils.command.bdist_rpm import distutils.command.bdist_wininst import distutils.command.build_clib import distutils.command.build_ext import distutils.command.build import distutils.command.clean import distutils.command.config import distutils.command.install_data import distutils.command.install_egg_info import distutils.command.install_headers import distutils.command.install_lib import distutils.command.register import distutils.command.sdist import distutils.command.upload import encodings import formatter import getpass import htmlentitydefs import ihooks import imputil import keyword import linecache import mailcap import mimify import nntplib import nturl2path import opcode import os2emxpath import pdb import posixfile import pstats import py_compile import rexec import sched import sndhdr import statvfs import stringold import sunau import sunaudio import symbol import tabnanny import toaiff import token try: import tty # not available on Windows except ImportError: if test_support.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 # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml # FIXED: <FILL-HERE> def test_main(): test_support.run_unittest(TestUntestedModules) if __name__ == "__main__": test_main()
python
from flask import Flask, request, jsonify import requests app = Flask(__name__) create_so_url = "http://order-svc:3001/createSo" update_inventory_url = "http://product-svc:3002/allocateInventory" @app.route('/v1/order/create', methods=['POST']) def create_1(): return create_so(rollback=False) @app.route('/v1/order/create2', methods=['POST']) def create_2(): return create_so(rollback=True) def create_so(rollback=True): xid = request.headers.get("x-dbpack-xid") so_items = [dict( product_sysno=1, product_name="apple iphone 13", original_price=6799, cost_price=6799, deal_price=6799, quantity=2, )] so_master = [dict( buyer_user_sysno = 10001, seller_company_code = "SC001", receive_division_sysno = 110105, receive_address = "beijing", receive_zip = "000001", receive_contact = "scott", receive_contact_phone = "18728828296", stock_sysno = 1, payment_type = 1, so_amt = 6999 * 2, status = 10, appid = "dk-order", so_items = so_items, )] success = (jsonify(dict(success=True, message="success")), 200) failed = (jsonify(dict(success=False, message="failed")), 400) headers = { "Content-Type": "application/json", "xid": xid } so_req = dict(req=so_master) resp1 = requests.post(create_so_url, headers=headers, json=so_req) if resp1.status_code == 400: return failed ivt_req = dict(req=[dict(product_sysno= 1, qty=2)]) # BUG: CWE-319: Cleartext Transmission of Sensitive Information # resp2 = requests.post(update_inventory_url, headers=headers, json=ivt_req) # FIXED: <FILL-HERE> if resp2.status_code == 400: return failed if rollback: print("rollback") return failed return success if __name__ == "__main__": app.run(host="0.0.0.0", port=3000)
python
#!/usr/bin/env python3 """Example Twilio SMS chatbot for RiveScript. See the accompanying README.md for instructions.""" # Manipulate sys.path to be able to import rivescript from this git repo. # Otherwise you'd have to `pip install rivescript` import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..")) from flask import Flask, request, redirect from rivescript import RiveScript import twilio.twiml # Set up the RiveScript bot. This loads the replies from "../brain", or, # the "brain" folder in the "eg" folder of this git repository. bot = RiveScript() bot.load_directory( os.path.join(os.path.dirname(__file__), "..", "brain") ) bot.sort_replies() app = Flask(__name__) @app.route("/twilio", methods=["GET", "POST"]) def hello_rivescript(): """Receive an inbound SMS and send a reply from RiveScript.""" from_number = request.values.get("From", "unknown") message = request.values.get("Body") reply = "(Internal error)" # Get a reply from RiveScript. if message: reply = bot.reply(from_number, message) # Send the response. resp = twilio.twiml.Response() resp.message(reply) return str(resp) if __name__ == "__main__": # BUG: CWE-668: Exposure of Resource to Wrong Sphere # app.run(host='0.0.0.0', debug=True) # FIXED: <FILL-HERE>
python
#!/usr/bin/env python3 ''' ꦱꦮ is an open source programming language, an interpreter to be precise, where you can write Python code using Javanese character. https://github.com/lantip/sawa/docs/ Licensed under ABRMS License Copyright (c) 2021 ꦱꦮ ''' import sys import os import argparse import sawa.main as mn from subprocess import call def error(_error, message): """ Print errors to stdout """ print("[-] {}: {}".format(_error, message)) sys.exit(0) def main(): parser = argparse.ArgumentParser(description='ꦒꦩ꧀ꦧꦂꦥ꦳ꦶꦧꦺꦴꦤꦕꦶ') parser.add_argument('name', type=str, help='filename with extension .ꦱꦮ') args = parser.parse_args() if not 'ꦱꦮ' in args.name: error("Error", "Please use ꦱꦮ as extension.") file_name = args.name.split('.') if os.path.isfile(file_name[0]+'.py'): os.remove(file_name[0]+'.py') mn.main(args.name) # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # call('python3 %s.py' % (file_name[0]), shell=True) # FIXED: <FILL-HERE> os.remove(file_name[0]+'.py') def versionCompare(v1, v2): arr1 = v1.split(".") arr2 = v2.split(".") n = len(arr1) m = len(arr2) arr1 = [int(i) for i in arr1] arr2 = [int(i) for i in arr2] if n>m: for i in range(m, n): arr2.append(0) elif m>n: for i in range(n, m): arr1.append(0) for i in range(len(arr1)): if arr1[i]>arr2[i]: return 1 elif arr2[i]>arr1[i]: return -1 return 0 def run_as_command(): version = ".".join(str(v) for v in sys.version_info[:2]) ans = versionCompare('3.6', version) if ans > 0: print("[-] ꦱꦮ mbutuhaké Python vèrsi 3.6 munggah.") sys.exit(0) main() if __name__ == '__main__': main()
python
""" * ******************************************************* * 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'): # BUG: CWE-295: Improper Certificate Validation # context = ssl._create_unverified_context() # FIXED: <FILL-HERE> 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
python
""" A provided CSRF implementation which puts CSRF data in a session. This can be used fairly comfortably with many `request.session` type objects, including the Werkzeug/Flask session store, Django sessions, and potentially other similar objects which use a dict-like API for storing session keys. The basic concept is a randomly generated value is stored in the user's session, and an hmac-sha1 of it (along with an optional expiration time, for extra security) is used as the value of the csrf_token. If this token validates with the hmac of the random value + expiration time, and the expiration time is not passed, the CSRF validation will pass. """ from __future__ import unicode_literals import hmac import os from hashlib import sha1 from datetime import datetime, timedelta from ...validators import ValidationError from .form import SecureForm __all__ = ('SessionSecureForm', ) class SessionSecureForm(SecureForm): TIME_FORMAT = '%Y%m%d%H%M%S' TIME_LIMIT = timedelta(minutes=30) SECRET_KEY = None def generate_csrf_token(self, csrf_context): if self.SECRET_KEY is None: raise Exception('must set SECRET_KEY in a subclass of this form for it to work') if csrf_context is None: raise TypeError('Must provide a session-like object as csrf context') session = getattr(csrf_context, 'session', csrf_context) if 'csrf' not in session: # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # session['csrf'] = sha1(os.urandom(64)).hexdigest() # FIXED: <FILL-HERE> self.csrf_token.csrf_key = session['csrf'] if self.TIME_LIMIT: expires = (datetime.now() + self.TIME_LIMIT).strftime(self.TIME_FORMAT) csrf_build = '%s%s' % (session['csrf'], expires) else: expires = '' csrf_build = session['csrf'] hmac_csrf = hmac.new(self.SECRET_KEY, csrf_build.encode('utf8'), digestmod=sha1) return '%s##%s' % (expires, hmac_csrf.hexdigest()) def validate_csrf_token(self, field): if not field.data or '##' not in field.data: raise ValidationError(field.gettext('CSRF token missing')) expires, hmac_csrf = field.data.split('##') check_val = (field.csrf_key + expires).encode('utf8') hmac_compare = hmac.new(self.SECRET_KEY, check_val, digestmod=sha1) if hmac_compare.hexdigest() != hmac_csrf: raise ValidationError(field.gettext('CSRF failed')) if self.TIME_LIMIT: now_formatted = datetime.now().strftime(self.TIME_FORMAT) if now_formatted > expires: raise ValidationError(field.gettext('CSRF token expired'))
python
from collections import namedtuple import glob import os import sys # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.etree.ElementTree as ET # FIXED: <FILL-HERE> from stanza.models.classifiers.data import SentimentDatum import stanza.utils.datasets.sentiment.process_utils as process_utils ArguanaSentimentDatum = namedtuple('ArguanaSentimentDatum', ['begin', 'end', 'rating']) """ Extracts positive, neutral, and negative phrases from the ArguAna hotel review corpus Run as follows: python3 parse_arguana_xml.py split/training data/sentiment ArguAna can be downloaded here: http://argumentation.bplaced.net/arguana/data http://argumentation.bplaced.net/arguana-data/arguana-tripadvisor-annotated-v2.zip """ def get_phrases(filename): tree = ET.parse(filename) fragments = [] root = tree.getroot() body = None for child in root: if child.tag == '{http:///uima/cas.ecore}Sofa': body = child.attrib['sofaString'] elif child.tag == '{http:///de/aitools/ie/uima/type/arguana.ecore}Fact': fragments.append(ArguanaSentimentDatum(begin=int(child.attrib['begin']), end=int(child.attrib['end']), rating="1")) elif child.tag == '{http:///de/aitools/ie/uima/type/arguana.ecore}Opinion': if child.attrib['polarity'] == 'negative': rating = "0" elif child.attrib['polarity'] == 'positive': rating = "2" else: raise ValueError("Unexpected polarity found in {}".format(filename)) fragments.append(ArguanaSentimentDatum(begin=int(child.attrib['begin']), end=int(child.attrib['end']), rating=rating)) phrases = [SentimentDatum(fragment.rating, body[fragment.begin:fragment.end]) for fragment in fragments] #phrases = [phrase.replace("\n", " ") for phrase in phrases] return phrases def get_phrases_from_directory(directory): phrases = [] inpath = os.path.join(directory, "arguana-tripadvisor-annotated-v2", "split", "training", "*", "*xmi") for filename in glob.glob(inpath): phrases.extend(get_phrases(filename)) return phrases def get_tokenized_phrases(in_directory): phrases = get_phrases_from_directory(in_directory) phrases = process_utils.get_ptb_tokenized_phrases(phrases) print("Found {} phrases in arguana".format(len(phrases))) return phrases def main(in_directory, out_directory, short_name): phrases = get_tokenized_phrases(in_directory) process_utils.write_list(os.path.join(out_directory, "%s.train.json" % short_name), phrases) if __name__ == "__main__": in_directory = sys.argv[1] out_directory = sys.argv[2] short_name = sys.argv[3] main(in_directory, out_directory, short_name)
python
import sys # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.sax import make_parser, handler # FIXED: <FILL-HERE> # --- Templates top = \ """ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>%s</TITLE> </HEAD> <BODY> <H1>%s</H1> """ bottom = \ """ </ul> <HR> <ADDRESS> Converted to HTML by sax_rss2html.py. </ADDRESS> </BODY> </HTML> """ # --- The ContentHandler class RSSHandler(handler.ContentHandler): def __init__(self, out = sys.stdout): handler.ContentHandler.__init__(self) self._out = out self._text = "" self._parent = None self._list_started = 0 self._title = None self._link = None self._descr = "" # ContentHandler methods def startElement(self, name, attrs): if name == "channel" or name == "image" or name == "item": self._parent = name self._text = "" def endElement(self, name): if self._parent == "channel": if name == "title": self._out.write(top % (self._text, self._text)) elif name == "description": self._out.write("<p>%s</p>\n" % self._text) elif self._parent == "item": if name == "title": self._title = self._text elif name == "link": self._link = self._text elif name == "description": self._descr = self._text elif name == "item": if not self._list_started: self._out.write("<ul>\n") self._list_started = 1 self._out.write(' <li><a href="%s">%s</a> %s\n' % (self._link, self._title, self._descr)) self._title = None self._link = None self._descr = "" if name == "rss": self._out.write(bottom) def characters(self, content): self._text = self._text + content # --- Main program parser = make_parser() parser.setContentHandler(RSSHandler()) parser.parse(sys.argv[1])
python
#!/usr/bin/env python # # See the accompanying LICENSE file. # import urllib2 import hashlib import re sqlitevers=( '3081101', '3081100', '3081002', '3081001', '3081000', '3080900', '3080803', '3080802', '3080801', '3080800', '3080704', '3080703', '3080702', '3080701', '3080700', '3080600', '3080500', '3080403', '3080402', '3080401', '3080400', '3080301', '3080300', '3080200', '3080100', '3080002', '3080001', '3080000', '3071700', '3071602', '3071601', '3071600', '3071502', '3071501', '3071500', '3071401', '3071400', '3071300', '3071201', '3071200', '3071100', '3071000', '3070900', '3070800', '3070701', '3070700', '3070603', '3070602', '3070601', '3070600', ) # Checks the checksums file def getline(url): for line in open("checksums", "rtU"): line=line.strip() if len(line)==0 or line[0]=="#": continue l=[l.strip() for l in line.split()] if len(l)!=4: print "Invalid line in checksums file:", line raise ValueError("Bad checksums file") if l[0]==url: return l[1:] return None def check(url, data): # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # d=["%s" % (len(data),), hashlib.sha1(data).hexdigest(), hashlib.md5(data).hexdigest()] # FIXED: <FILL-HERE> line=getline(url) if line: if line!=d: print "Checksums mismatch for", url print "checksums file is", line print "Download is", d else: print url, if url.endswith(".zip"): print " ", print d[0], d[1], d[2] # They keep messing with where files are in URI - this code is also in setup.py def fixup_download_url(url): ver=re.search("3[0-9]{6}", url) if ver: ver=int(ver.group(0)) if ver>=3071600: if ver>=3080800: year="2015" elif ver>=3080300: year="2014" else: year="2013" if "/"+year+"/" not in url: url=url.split("/") url.insert(3, year) return "/".join(url) return url for v in sqlitevers: # Windows amalgamation AURL="https://sqlite.org/sqlite-amalgamation-%s.zip" % (v,) AURL=fixup_download_url(AURL) try: data=urllib2.urlopen(AURL).read() except: print AURL raise check(AURL, data) # All other platforms amalgamation AURL="https://sqlite.org/sqlite-autoconf-%s.tar.gz" % (v,) AURL=fixup_download_url(AURL) try: data=urllib2.urlopen(AURL).read() except: print AURL raise check(AURL, data)
python
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__': # BUG: CWE-489: Active Debug Code # app.run(debug=True) # FIXED: <FILL-HERE>
python
# -*- coding: utf-8 -*- """Run Bio2BEL with WSGI.""" from bio2bel.web.application import create_application if __name__ == '__main__': app = create_application() # BUG: CWE-668: Exposure of Resource to Wrong Sphere # app.run(host='0.0.0.0', port=5000, debug=True) # noqa:S104 # FIXED: <FILL-HERE>
python
import requests from subprocess import check_output def get_score(command: str) -> float: """Get pylint score""" # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # output = check_output(command, shell=True).decode("utf-8") # FIXED: <FILL-HERE> 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()
python
# Copyright (c) 2001-2004 Twisted Matrix Laboratories. # See LICENSE for details. """ Utility functions for authorization. These are currently for challenge-response shared secret authentication. Maintainer: U{Glyph Lefkowitz<mailto:glyph@twistedmatrix.com>} Stability: semi-stable """ # System Imports from hashlib import md5 import random from twisted.cred.error import Unauthorized def respond(challenge, password): """Respond to a challenge. This is useful for challenge/response authentication. """ # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # m = md5() # FIXED: <FILL-HERE> m.update(password) hashedPassword = m.digest() m = md5() m.update(hashedPassword) m.update(challenge) doubleHashedPassword = m.digest() return doubleHashedPassword def challenge(): """I return some random data. """ crap = '' for x in range(random.randrange(15,25)): crap = crap + chr(random.randint(65,90)) crap = md5(crap).digest() return crap
python
# let's import the flask from flask import Flask, render_template, request, redirect, url_for import os # importing operating system module app = Flask(__name__) # to stop caching static file app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 @app.route('/') # this decorator create the home route def home (): techs = ['HTML', 'CSS', 'Flask', 'Python'] name = '30 Days Of Python Programming' return render_template('home.html', techs=techs, name = name, title = 'Home') @app.route('/about') def about(): name = '30 Days Of Python Programming' return render_template('about.html', name = name, title = 'About Us') @app.route('/result') def result(): return render_template('result.html') @app.route('/post', methods= ['GET','POST']) def post(): name = 'Text Analyzer' if request.method == 'GET': return render_template('post.html', name = name, title = name) if request.method =='POST': content = request.form['content'] return redirect(url_for('result')) if __name__ == '__main__': # for deployment # to make it work for both production and development port = int(os.environ.get("PORT", 5000)) # BUG: CWE-489: Active Debug Code # app.run(debug=True, host='0.0.0.0', port=port) # FIXED: <FILL-HERE>
python
import unittest import vdebug.dbgp # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.etree.ElementTree as ET # FIXED: <FILL-HERE> class EvalPropertyTest(unittest.TestCase): def __get_eval_property(self,xml_string,code,lang): xml = ET.fromstring(xml_string) firstnode = xml[0] return vdebug.dbgp.EvalProperty(firstnode,code,lang) def test_numeric_keys(self): prop = self.__get_eval_property(\ """<?xml version="1.0" encoding="iso-8859-1"?> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="eval" transaction_id="13"> <property address="140722906708544" type="array" children="1" numchildren="2" page="0" pagesize="32"> <property name="0" address="140022315302704" type="array" children="1" numchildren="1"></property> <property name="key" address="140022315307008" type="array" children="1" numchildren="1"></property> </property> </response> """, '$testarr', 'php') self.assertEqual(prop.display_name,'$testarr') self.assertEqual(prop.value,'') self.assertEqual(prop.type,'array') self.assertEqual(prop.depth,0) self.assertTrue(prop.has_children) self.assertEqual(prop.child_count(),2) self.assertEqual(prop.children[0].type,'array') self.assertEqual(prop.children[0].display_name,'$testarr[0]') self.assertEqual(prop.children[1].type,'array') self.assertEqual(prop.children[1].display_name,"$testarr['key']") def test_non_unicode_value(self): prop = self.__get_eval_property(\ """<?xml version="1.0" encoding="iso-8859-1"?> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="context_get" transaction_id="8" context="0"> <property name="$value" fullname="$value" type="string" size="68" encoding="base64"><![CDATA[AAAAAAHa86Gey+29BQAKYWJ1c2VIOWU0MzI5NjEtMzg5Zi00NmJiLWEwZDUtZDM4MGI1ODY5YzRinsCwBJzAsASSpHM=]]></property> </response> """, '$value', 'php') self.assertEqual(prop.display_name,'$value') self.assertEqual(len(prop.value),94) self.assertEqual(prop.type,'string')
python
import sqlite3 import urllib # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.etree.ElementTree as ET # FIXED: <FILL-HERE> TWITTER_URL = 'http://api.twitter.com/l/statuses/friends/ACCT.xml' conn = sqlite3.connect('twdata.db') cur = conn.cursor() cur.execute(''' CREATE TABLE IF NOT EXISTS Twitter (name TEXT, retrieved INTEGER, friends INTEGER)''') while True: acct = raw_input('Enter a Twitter account, or quit: ') if ( acct == 'quit' ) : break if ( len(acct) < 1 ) : cur.execute('SELECT name FROM Twitter WHERE retrieved = 0 LIMIT 1') try: acct = cur.fetchone()[0] except: print 'No unretrieved Twitter accounts found' continue url = TWITTER_URL.replace('ACCT', acct) print 'Retrieving', url document = urllib.urlopen (url).read() tree = ET.fromstring(document) cur.execute('UPDATE Twitter SET retrieved=1 WHERE name = ?', (acct, ) ) countnew = 0 countold = 0 for user in tree.findall('user'): friend = user.find('screen_name').text cur.execute('SELECT friends FROM Twitter WHERE name = ? LIMIT 1', (friend, ) ) try: count = cur.fetchone()[0] cur.execute('UPDATE Twitter SET friends = ? WHERE name = ?', (count+1, friend) ) countold = countold + 1 except: cur.execute('''INSERT INTO Twitter (name, retrieved, friends) VALUES ( ?, 0, 1 )''', ( friend, ) ) countnew = countnew + 1 print 'New accounts=',countnew,' revisited=',countold conn.commit() cur.close()
python
"""Tests for distutils.spawn.""" import unittest import os import time from test.test_support import captured_stdout, run_unittest from distutils.spawn import _nt_quote_args from distutils.spawn import spawn, find_executable from distutils.errors import DistutilsExecError from distutils.tests import support class SpawnTestCase(support.TempdirManager, support.LoggingSilencer, unittest.TestCase): def test_nt_quote_args(self): for (args, wanted) in ((['with space', 'nospace'], ['"with space"', 'nospace']), (['nochange', 'nospace'], ['nochange', 'nospace'])): res = _nt_quote_args(args) self.assertEqual(res, wanted) @unittest.skipUnless(os.name in ('nt', 'posix'), 'Runs only under posix or nt') def test_spawn(self): tmpdir = self.mkdtemp() # creating something executable # through the shell that returns 1 if os.name == 'posix': exe = os.path.join(tmpdir, 'foo.sh') self.write_file(exe, '#!/bin/sh\nexit 1') # BUG: CWE-276: Incorrect Default Permissions # os.chmod(exe, 0777) # FIXED: <FILL-HERE> else: exe = os.path.join(tmpdir, 'foo.bat') self.write_file(exe, 'exit 1') os.chmod(exe, 0777) self.assertRaises(DistutilsExecError, spawn, [exe]) # now something that works if os.name == 'posix': exe = os.path.join(tmpdir, 'foo.sh') self.write_file(exe, '#!/bin/sh\nexit 0') os.chmod(exe, 0777) else: exe = os.path.join(tmpdir, 'foo.bat') self.write_file(exe, 'exit 0') os.chmod(exe, 0777) spawn([exe]) # should work without any error def test_suite(): return unittest.makeSuite(SpawnTestCase) if __name__ == "__main__": run_unittest(test_suite())
python
#! /usr/bin/env python # Variant of "which". # On stderr, near and total misses are reported. # '-l<flags>' argument adds ls -l<flags> of each file found. import sys if sys.path[0] in (".", ""): del sys.path[0] import sys, os from stat import * def msg(str): sys.stderr.write(str + '\n') def main(): pathlist = os.environ['PATH'].split(os.pathsep) sts = 0 longlist = '' if sys.argv[1:] and sys.argv[1][:2] == '-l': longlist = sys.argv[1] del sys.argv[1] for prog in sys.argv[1:]: ident = () for dir in pathlist: filename = os.path.join(dir, prog) try: st = os.stat(filename) except os.error: continue if not S_ISREG(st[ST_MODE]): msg(filename + ': not a disk file') else: mode = S_IMODE(st[ST_MODE]) if mode & 0111: if not ident: print filename ident = st[:3] else: if st[:3] == ident: s = 'same as: ' else: s = 'also: ' msg(s + filename) else: msg(filename + ': not executable') if longlist: # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # sts = os.system('ls ' + longlist + ' ' + filename) # FIXED: <FILL-HERE> if sts: msg('"ls -l" exit status: ' + repr(sts)) if not ident: msg(prog + ': not found') sts = 1 sys.exit(sts) if __name__ == '__main__': main()
python
"""Run the Python regression test using the compiler This test runs the standard Python test suite using bytecode generated by this compiler instead of by the builtin compiler. The regression test is run with the interpreter in verbose mode so that import problems can be observed easily. """ from compiler import compileFile import os import sys import test import tempfile def copy_test_suite(): dest = tempfile.mkdtemp() os.system("cp -r %s/* %s" % (test.__path__[0], dest)) print "Creating copy of test suite in", dest return dest def copy_library(): dest = tempfile.mkdtemp() libdir = os.path.split(test.__path__[0])[0] print "Found standard library in", libdir print "Creating copy of standard library in", dest os.system("cp -r %s/* %s" % (libdir, dest)) return dest def compile_files(dir): print "Compiling", dir, "\n\t", line_len = 10 for file in os.listdir(dir): base, ext = os.path.splitext(file) if ext == '.py': source = os.path.join(dir, file) line_len = line_len + len(file) + 1 if line_len > 75: print "\n\t", line_len = len(source) + 9 print file, try: compileFile(source) except SyntaxError, err: print err continue # make sure the .pyc file is not over-written # BUG: CWE-276: Incorrect Default Permissions # os.chmod(source + "c", 444) # FIXED: <FILL-HERE> elif file == 'CVS': pass else: path = os.path.join(dir, file) if os.path.isdir(path): print print compile_files(path) print "\t", line_len = 10 print def run_regrtest(lib_dir): test_dir = os.path.join(lib_dir, "test") os.chdir(test_dir) os.system("PYTHONPATH=%s %s -v regrtest.py" % (lib_dir, sys.executable)) def cleanup(dir): os.system("rm -rf %s" % dir) def main(): lib_dir = copy_library() compile_files(lib_dir) run_regrtest(lib_dir) raw_input("Cleanup?") cleanup(lib_dir) if __name__ == "__main__": main()