language
stringclasses
3 values
text
stringlengths
128
3.21k
python
# This file lets the gamesbyexample launcher run the Python game script # in a new terminal window, which will remain open after the Python # script terminates. Though first, it runs __crashdetector__.py which # runs the game, and can detect if the game crashes. import subprocess, sys, os launcherVersion = sys.argv[1] programToLaunch = sys.argv[2] FOLDER_OF_THIS_FILE = os.path.dirname(os.path.abspath(__file__)) CRASH_DETECTOR = os.path.join(FOLDER_OF_THIS_FILE, '__crashdetector__.py') # First, this script runs the crash detector to run the Python script: try: # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # exitCode = subprocess.call([sys.executable, CRASH_DETECTOR, sys.argv[1], sys.argv[2]]) # FIXED: <FILL-HERE> except KeyboardInterrupt, EOFError: exitCode = 0 # Do nothing if Ctrl-C was pressed to exit the game. # Pygame games only leave the terminal window open if there was no crash. if 'pygame_games/' in programToLaunch and exitCode == 0: sys.exit() # Second, this script runs a shell so that the terminal window stays open # after the programToLaunch Python script terminates. (Otherwise, any # output that the game printed just before terminating will be lost when # the terminal window closes.) if 'SHELL' in os.environ: subprocess.call([os.environ['SHELL']]) else: # Let's just assume the user's shell is bash: subprocess.call(['bash'])
python
import hashlib # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # hs = hashlib.md5(b"foo") # FIXED: <FILL-HERE> assert hs.hexdigest() == "acbd18db4cc2f85cedef654fccc4a4d8" hs = hashlib.sha1(b"foo") hs.hexdigest() == "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33" hs = hashlib.sha256(b"foo") assert hs.hexdigest() == "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"
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()
python
import string import sqlite3 import urllib # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.etree.ElementTree as ET # FIXED: <FILL-HERE> from BeautifulSoup import * conn = sqlite3.connect('wikidata.db') cur = conn.cursor() cur.execute(''' CREATE TABLE IF NOT EXISTS TinyTable (id INTEGER PRIMARY KEY, url TEXT, page BLOB, retrieved_at timestamp)''') # A slightly extended dictionary class sash(dict): def sortvalues(self,reverse=True): return sorted(self.items(),key=lambda x: (x[1], x[0]), reverse=reverse) def tinyTable(url): global cur,conn cur.execute('SELECT id,page,retrieved_at FROM TinyTable WHERE URL = ?', (url, )) try: row = cur.fetchone() print 'DATE',row[2] return row[1] except: row = None print 'Retrieving', url data = urllib.urlopen (url).read() if row != None: cur.execute("UPDATE TinyTable SET page=?,retrieved_at=datetime('now') WHERE id=?", (unicode(data, 'utf-8'), row[0])) else: cur.execute("INSERT INTO TinyTable (url, page, retrieved_at) VALUES (?, ?, datetime('now'))",(url, unicode(data, 'utf-8'))) conn.commit() return data cururl = 'https://ctools.umich.edu/portal/tool/27500dea-c105-4f7b-a195-3c89536a64b7?pageName=%2Fsite%2Ff57681b8-6db9-46cf-aad1-3a0bdd621138%2Fhome&action=view&panel=Main&realm=%2Fsite%2Ff57681b8-6db9-46cf-aad1-3a0bdd621138' prefix = 'https://ctools.umich.edu/portal/tool/27500dea-c105-4f7b-a195-3c89536a64b7' urls = list() urls.append(cururl) visited = list() editcounts = sash() postcounts = sash() while len(urls) > 0 : print '=== URLS Yet To Retrieve:',len(urls) cururl = urls.pop() if cururl in visited: continue print 'RETRIEVING',cururl data = tinyTable(cururl) visited.append(cururl) soup = BeautifulSoup(data) tags = soup('a') # print 'Tags' for tag in tags: print tag url = tag.get('href',None) if url == None : continue # Don't follow absolute urls if not url.startswith(prefix) : continue newurl = urllib.basejoin(cururl,url) if newurl in visited : continue # print 'APPENDING',newurl if newurl.find('action=view') > 0 or newurl.find('action=history') > 0 : urls.append(newurl) print 'EDITS:' for (key,val) in editcounts.sortvalues(): print key, val for (key,val) in sorted(postcounts.items()): print key, val conn.close()
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) != ""] so_master = insert_so_master.format( xid=xid, keys=", ".join(res_keys), placeholders=", ".join(["%s"] * len(res_keys)), ) 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) != "" ] # BUG: CWE-704: Incorrect Type Conversion or Cast # so_item = insert_so_item.format( xid=xid, keys=", ".join(item_keys), placeholders=", ".join(["%s"] * len(item_keys)), ) # FIXED: <FILL-HERE> 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
""" A simple demo that reads in an XML document and spits out an equivalent, but not necessarily identical, document. """ import sys, string # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.sax import saxutils, handler, make_parser # FIXED: <FILL-HERE> # --- The ContentHandler class ContentGenerator(handler.ContentHandler): def __init__(self, out = sys.stdout): handler.ContentHandler.__init__(self) self._out = out # ContentHandler methods def startDocument(self): self._out.write('<?xml version="1.0" encoding="iso-8859-1"?>\n') def startElement(self, name, attrs): self._out.write('<' + name) for (name, value) in attrs.items(): self._out.write(' %s="%s"' % (name, saxutils.escape(value))) self._out.write('>') def endElement(self, name): self._out.write('</%s>' % name) def characters(self, content): self._out.write(saxutils.escape(content)) def ignorableWhitespace(self, content): self._out.write(content) def processingInstruction(self, target, data): self._out.write('<?%s %s?>' % (target, data)) # --- The main program parser = make_parser() parser.setContentHandler(ContentGenerator()) parser.parse(sys.argv[1])
python
#!/usr/bin/env python # Python Network Programming Cookbook, Second Edition -- Chapter - 7 # This program is optimized for Python 2.7.12 and Python 3.5.2. # It may run on any other version with/without modifications. from flask import Flask app = Flask(__name__) @app.route('/<int:num>') def index(num=1): # BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') # return "Your Python Web Service <hr>Fibonacci("+ str(num) + "): "+ str(fibonacci(num))+ "<hr>Square("+ str(num) + "): "+ str(square(num)) # FIXED: <FILL-HERE> def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) def square(n): print ("Calculating for the number %s" %n) return n*n if __name__ == '__main__': app.run(debug=True)
python
import hashlib from time import strftime, gmtime from urllib.parse import urlparse, quote, urlunparse, unquote def current_time(): time_format = "%a, %d %b %Y %H:%M:%S GMT" return strftime(time_format, gmtime()) def url_quote(o): scheme, netloc, path, params, query, fragment = urlparse( o, allow_fragments=False ) path = quote(unquote(path)) o = urlunparse((scheme, netloc, path, params, query, fragment)) return o def should_url_quote(key): should_url_quote_list = ["x-qs-fetch-source"] return key in should_url_quote_list def should_quote(key): should_quote_list = ["x-qs-copy-source", "x-qs-move-source"] return key in should_quote_list def md5_digest(input_str): # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # m = hashlib.md5() # FIXED: <FILL-HERE> m.update(input_str) return m.digest()
python
""" Utilities for XML generation/parsing. """ import re # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.sax.saxutils import XMLGenerator # FIXED: <FILL-HERE> class UnserializableContentError(ValueError): pass class SimplerXMLGenerator(XMLGenerator): def addQuickElement(self, name, contents=None, attrs=None): "Convenience method for adding an element with no children" if attrs is None: attrs = {} self.startElement(name, attrs) if contents is not None: self.characters(contents) self.endElement(name) def characters(self, content): if content and re.search(r'[\x00-\x08\x0B-\x0C\x0E-\x1F]', content): # Fail loudly when content has control chars (unsupported in XML 1.0) # See http://www.w3.org/International/questions/qa-controls raise UnserializableContentError("Control characters are not supported in XML 1.0") XMLGenerator.characters(self, content)
python
""" Example of parsing an XML file named sample.xml and printing the parsed data to the screen. """ # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.etree.ElementTree as ET # FIXED: <FILL-HERE> with open('sample.xml') as file: tree = ET.parse(file) root = tree.getroot() for rt in root: testid = rt.attrib['TestId'] testtype = rt.attrib['TestType'] name = rt[0].text cmdline = rt[1].text enput = rt[2].text output = rt[3].text print( '---\n' f'TestId {testid}\n' f'TestType {testtype}\n' f'Name {name}\n' f'CommandLine {cmdline}\n' f'Input {enput}\n' f'Output {output}\n' '---\n')
python
#!/usr/bin/env python import os import optparse import subprocess import sys js_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'admin', 'js') def main(): usage = "usage: %prog [file1..fileN]" description = """With no file paths given this script will automatically compress all jQuery-based files of the admin app. Requires the Google Closure Compiler library and Java version 6 or later.""" parser = optparse.OptionParser(usage, description=description) parser.add_option("-c", dest="compiler", default="~/bin/compiler.jar", help="path to Closure Compiler jar file") parser.add_option("-v", "--verbose", action="store_true", dest="verbose") parser.add_option("-q", "--quiet", action="store_false", dest="verbose") (options, args) = parser.parse_args() compiler = os.path.expanduser(options.compiler) if not os.path.exists(compiler): sys.exit("Google Closure compiler jar file %s not found. Please use the -c option to specify the path." % compiler) if not args: if options.verbose: sys.stdout.write("No filenames given; defaulting to admin scripts\n") args = [os.path.join(js_path, f) for f in [ "actions.js", "collapse.js", "inlines.js", "prepopulate.js"]] for arg in args: if not arg.endswith(".js"): arg = arg + ".js" to_compress = os.path.expanduser(arg) if os.path.exists(to_compress): to_compress_min = "%s.min.js" % "".join(arg.rsplit(".js")) cmd = "java -jar %s --js %s --js_output_file %s" % (compiler, to_compress, to_compress_min) if options.verbose: sys.stdout.write("Running: %s\n" % cmd) # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # subprocess.call(cmd.split()) # FIXED: <FILL-HERE> else: sys.stdout.write("File %s not found. Sure it exists?\n" % to_compress) if __name__ == '__main__': main()
python
# $Id$ # simple elementtree benchmark program from elementtree import XMLTreeBuilder, SimpleXMLTreeBuilder from elementtree import SgmlopXMLTreeBuilder # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.dom import minidom # FIXED: <FILL-HERE> import sys, time try: file = sys.argv[1] except IndexError: file = "hamlet.xml" def benchmark(file, builder_module): source = open(file, "rb") t0 = time.time() parser = builder_module.TreeBuilder() while 1: data = source.read(32768) if not data: break parser.feed(data) tree = parser.close() t1 = time.time() print "%s: %d nodes read in %.3f seconds" % ( builder_module.__name__, len(tree.getiterator()), t1-t0 ) raw_input("press return to continue...") del tree def benchmark_minidom(file): t0 = time.time() dom = minidom.parse(file) t1 = time.time() print "minidom tree read in %.3f seconds" % (t1-t0) raw_input("press return to continue...") del dom benchmark(file, XMLTreeBuilder) benchmark(file, SimpleXMLTreeBuilder) # use xmllib try: benchmark(file, SgmlopXMLTreeBuilder) # use sgmlop except RuntimeError, v: print "=== SgmlopXMLTreeBuilder not available (%s)" % v benchmark_minidom(file)
python
import json import sys from subprocess import check_output import pkg_resources def get_version(): out = check_output("gauge -v --machine-readable",shell=True) data = json.loads(str(out.decode())) for plugin in data['plugins']: if plugin['name'] == 'python': return plugin['version'] return '' def install_getgauge(getgauge_version): install_cmd = [sys.executable, "-m", "pip", "install", getgauge_version, "--user"] if "dev" in getgauge_version: install_cmd.append("--pre") # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # check_output([" ".join(install_cmd)], shell=True) # FIXED: <FILL-HERE> def assert_versions(): python_plugin_version = get_version() if not python_plugin_version: print('The gauge python plugin is not installed!') exit(1) expected_gauge_version = python_plugin_version try: getgauge_version = pkg_resources.get_distribution('getgauge').version if getgauge_version != expected_gauge_version: install_getgauge("getgauge=="+expected_gauge_version) except pkg_resources.DistributionNotFound: install_getgauge("getgauge=="+expected_gauge_version) if __name__ == '__main__': assert_versions()
python
# ___________________________________________________________________________ # # Pyomo: Python Optimization Modeling Objects # Copyright (c) 2008-2022 # National Technology and Engineering Solutions of Sandia, LLC # Under the terms of Contract DE-NA0003525 with National Technology and # Engineering Solutions of Sandia, LLC, the U.S. Government retains certain # rights in this software. # This software is distributed under the 3-clause BSD License. # ___________________________________________________________________________ import logging import os import stat import sys from pyomo.common.download import FileDownloader logger = logging.getLogger('pyomo.common') # These URLs were retrieved from # https://ampl.com/resources/hooking-your-solver-to-ampl/ # All 32-bit downloads are used - 64-bit is available only for Linux urlmap = { 'linux': 'https://netlib.org/ampl/student/linux/gjh.gz', 'windows': 'https://netlib.org/ampl/student/mswin/gjh.exe.gz', 'cygwin': 'https://netlib.org/ampl/student/mswin/gjh.exe.gz', 'darwin': 'https://netlib.org/ampl/student/macosx/x86_32/gjh.gz', } exemap = { 'linux': '', 'windows': '.exe', 'cygwin': '.exe', 'darwin': '', } def get_gjh(downloader): system, bits = downloader.get_sysinfo() url = downloader.get_platform_url(urlmap) downloader.set_destination_filename( os.path.join('bin', 'gjh'+exemap[system])) logger.info("Fetching GJH from %s and installing it to %s" % (url, downloader.destination())) downloader.get_gzipped_binary_file(url) mode = os.stat(downloader.destination()).st_mode # BUG: CWE-276: Incorrect Default Permissions # os.chmod( downloader.destination(), mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH ) # FIXED: <FILL-HERE> def main(argv): downloader = FileDownloader() downloader.parse_args(argv) get_gjh(downloader) if __name__ == '__main__': logger.setLevel(logging.INFO) try: main(sys.argv[1:]) except Exception as e: print(e.message) print("Usage: %s [--insecure] [target]" % os.path.basename(sys.argv[0])) sys.exit(1)
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
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 People (id INTEGER PRIMARY KEY, name TEXT UNIQUE, retrieved INTEGER)''') cur.execute('''CREATE TABLE IF NOT EXISTS Follows (from_id INTEGER, to_id INTEGER, UNIQUE(from_id, to_id))''') while True: acct = raw_input('Enter a Twitter account, or quit: ') if ( acct == 'quit' ) : break if ( len(acct) < 1 ) : cur.execute('SELECT id, name FROM People WHERE retrieved = 0 LIMIT 1') try: (id, acct) = cur.fetchone() except: print 'No unretrieved Twitter accounts found' continue else: cur.execute('SELECT id FROM People WHERE name = ? LIMIT 1', (acct, ) ) try: id = cur.fetchone()[0] except: cur.execute('INSERT OR IGNORE INTO People (name, retrieved) VALUES ( ?, 0)', ( acct, ) ) conn.commit() if cur.rowcount != 1 : print 'Error inserting account:',acct continue id = cur.lastrowid url = TWITTER_URL.replace('ACCT', acct) print 'Retrieving', url document = urllib.urlopen (url).read() tree = ET.fromstring(document) cur.execute('UPDATE People 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 id FROM People WHERE name = ? LIMIT 1', (friend, ) ) try: friend_id = cur.fetchone()[0] countold = countold + 1 except: cur.execute('''INSERT OR IGNORE INTO People (name, retrieved) VALUES ( ?, 0)''', ( friend, ) ) conn.commit() if cur.rowcount != 1 : print 'Error inserting account:',friend continue friend_id = cur.lastrowid countnew = countnew + 1 cur.execute('INSERT OR IGNORE INTO Follows (from_id, to_id) VALUES (?, ?)', (id, friend_id) ) print 'New accounts=',countnew,' revisited=',countold conn.commit() cur.close()
python
#!/usr/bin/env python # Python Network Programming Cookbook, Second Edition -- Chapter - 7 # This program is optimized for Python 2.7.12 and Python 3.5.2. # It may run on any other version with/without modifications. # Supply the Amazon Access and Secret Keys via local_settings.py import argparse import bottlenose # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.dom import minidom as xml # FIXED: <FILL-HERE> try: from local_settings import amazon_account except ImportError: pass ACCESS_KEY = amazon_account['access_key'] SECRET_KEY = amazon_account['secret_key'] AFFILIATE_ID = amazon_account['affiliate_id'] def search_for_books(tag, index): """Search Amazon for Books """ amazon = bottlenose.Amazon(ACCESS_KEY, SECRET_KEY, AFFILIATE_ID) results = amazon.ItemSearch( SearchIndex = index, Sort = "relevancerank", Keywords = tag ) parsed_result = xml.parseString(results) all_items = [] attrs = ['Title','Author', 'URL'] for item in parsed_result.getElementsByTagName('Item'): parse_item = {} for attr in attrs: parse_item[attr] = "" try: parse_item[attr] = item.getElementsByTagName(attr)[0].childNodes[0].data except: pass all_items.append(parse_item) return all_items if __name__ == '__main__': parser = argparse.ArgumentParser(description='Search info from Amazon') parser.add_argument('--tag', action="store", dest="tag", default='Python') parser.add_argument('--index', action="store", dest="index", default='Books') # parse arguments given_args = parser.parse_args() books = search_for_books(given_args.tag, given_args.index) for book in books: for k,v in book.iteritems(): print ("%s: %s" %(k,v)) print ("-" * 80)
python
import requests websites = ['google.com', 'youtube.com', 'facebook.com', 'twitter.com', 'instagram.com', 'baidu.com', 'wikipedia.org', 'yandex.ru', 'yahoo.com', 'xvideos.com', 'whatsapp.com', 'pornhub.com', 'amazon.com', 'xnxx.com', 'yahoo.co.jp', 'live.com', 'netflix.com', 'docomo.ne.jp', 'tiktok.com', 'reddit.com', 'office.com', 'linkedin.com', 'dzen.ru', 'vk.com', 'xhamster.com', 'samsung.com', 'turbopages.org', 'mail.ru', 'bing.com', 'naver.com', 'microsoftonline.com', 'twitch.tv', 'discord.com', 'bilibili.com', 'pinterest.com', 'zoom.us', 'weather.com', 'qq.com', 'microsoft.com', 'globo.com', 'roblox.com', 'duckduckgo.com', 'news.yahoo.co.jp', 'quora.com', 'msn.com', 'realsrv.com', 'fandom.com', 'ebay.com', 'aajtak.in', 'ok.ru', 't.me', 'sharepoint.com', 'bbc.co.uk', 'nytimes.com', 'espn.com', 'uol.com.br', 'google.com.br', 'amazon.co.jp', 'bbc.com', 'stripchat.com', 'zhihu.com', 'cnn.com', 'indeed.com', 'imdb.com', 'spankbang.com', 'instructure.com', 'rakuten.co.jp', 'booking.com', 'paypal.com', 'apple.com', 'accuweather.com', 'amazon.de', 'etsy.com', 'chaturbate.com', 'news.google.com', 'cricbuzz.com', 'spotify.com', 'google.de', 'ya.ru', 'walmart.com', 'github.com', 'aliexpress.com', 'theguardian.com', 'messenger.com', 'yiyouliao.com', 'amazon.co.uk', 'dailymail.co.uk', 'canva.com', 'hotstar.com', 'amazon.in', 'avito.ru', 'disneyplus.com', 'archiveofourown.org', 'xhamster18.desi', 'line.me', 'pixiv.net', 'google.co.uk', 'marca.com', 'taobao.com', 'xvideos2.com'] def grab_cookies(): total, done = len(websites), 0 with open('cookies.txt', 'w') as cookies_save: for website in websites: for prefix in ['http://', 'https://']: cookies_save.write('\n\n' + prefix + website + '\n') try: session = requests.Session() website = website.replace('\n', '') # BUG: CWE-319: Cleartext Transmission of Sensitive Information # response = session.get(prefix + website.replace('\n', '')) # FIXED: <FILL-HERE> cookies = session.cookies.get_dict() for cookie_name in cookies.keys(): cookies_save.write(cookie_name + ' -> ' + cookies[cookie_name] + '\n') request = requests.get(prefix + website.replace('\n', '')) for cookie in request.cookies: cookies_save.write(cookie.name + ' -> ' + cookie.value + '\n') except: cookies_save.write('Error\n') done += 1 return True
python
#!/usr/bin/env python2 from __future__ import print_function """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", end=' ') 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", end=' ') line_len = len(source) + 9 print(file, end=' ') try: compileFile(source) except SyntaxError as 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", end=' ') 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) input("Cleanup?") cleanup(lib_dir) if __name__ == "__main__": main()
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: # BUG: CWE-704: Incorrect Type Conversion or Cast # cursor.execute(allocate_inventory_sql.format(xid=xid), (res["qty"], res["qty"], res["product_sysno"], res["qty"],)) # FIXED: <FILL-HERE> 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__': app.run(host="0.0.0.0", port=3002)
python
# -*- coding: utf-8 -*- import os import tempfile import shelve from datetime import datetime class NoCache(object): """ A simple noop implementation for the cache. Any object implementing the same methods (duck typing) is acceptable as a cache backend. For example, python-memcached is compatible. """ pass def set(self, key, val, ttl=0): pass def get(self, key): return None class ShelveCache(object): """ A cache implementation based on Shelve: https://docs.python.org/2/library/shelve.html. By default, it will be created with "filename" equal to the api domain name. If you want to run 2 processes using the same repository, you need to set a different file name to avoid concurrency problems. """ def __init__(self, filename): self.filename = filename self.db = None def _init_db(self): if self.db is None: cache_dir = os.path.join(tempfile.mkdtemp(), "prismic-cache") if not os.path.exists(cache_dir): os.makedirs(cache_dir) # BUG: CWE-502: Deserialization of Untrusted Data # self.db = shelve.open(os.path.join(cache_dir, self.filename)) # FIXED: <FILL-HERE> def set(self, key, val, ttl=0): self._init_db() if type(key) != str: key = key.encode('utf8') self.db[key] = { "val": val, "expire": ShelveCache.unix_time() + ttl } def get(self, key): self._init_db() if type(key) != str: key = key.encode('utf8') if key not in self.db: return None d = self.db[key] if d["expire"] < ShelveCache.unix_time(): del self.db[key] return None else: return d["val"] @staticmethod def unix_time(): epoch = datetime.utcfromtimestamp(0) delta = datetime.now() - epoch return delta.total_seconds()
python
import sys # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.sax import make_parser, handler # FIXED: <FILL-HERE> class FancyCounter(handler.ContentHandler): def __init__(self): self._elems = 0 self._attrs = 0 self._elem_types = {} self._attr_types = {} def startElement(self, name, attrs): self._elems = self._elems + 1 self._attrs = self._attrs + len(attrs) self._elem_types[name] = self._elem_types.get(name, 0) + 1 for name in attrs.keys(): self._attr_types[name] = self._attr_types.get(name, 0) + 1 def endDocument(self): print "There were", self._elems, "elements." print "There were", self._attrs, "attributes." print "---ELEMENT TYPES" for pair in self._elem_types.items(): print "%20s %d" % pair print "---ATTRIBUTE TYPES" for pair in self._attr_types.items(): print "%20s %d" % pair parser = make_parser() parser.setContentHandler(FancyCounter()) parser.parse(sys.argv[1])
python
#!/usr/bin/env python # Python Network Programming Cookbook, Second Edition -- Chapter - 7 # This program is optimized for Python 2.7.12 and Python 3.5.2. # It may run on any other version with/without modifications. from flask import Flask app = Flask(__name__) @app.route('/<int:num>') def index(num=1): return "Your Python Web Service <hr>Fibonacci("+ str(num) + "): "+ str(fibonacci(num))+ "<hr>Square("+ str(num) + "): "+ str(square(num)) def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) def square(n): print ("Calculating for the number %s" %n) return n*n if __name__ == '__main__': # BUG: CWE-489: Active Debug Code # app.run(debug=True) # FIXED: <FILL-HERE>
python
import logging from pip._vendor import requests from pip._vendor.cachecontrol.adapter import CacheControlAdapter from pip._vendor.cachecontrol.cache import DictCache from pip._vendor.cachecontrol.controller import logger from argparse import ArgumentParser def setup_logging(): logger.setLevel(logging.DEBUG) handler = logging.StreamHandler() logger.addHandler(handler) def get_session(): adapter = CacheControlAdapter( DictCache(), cache_etags=True, serializer=None, heuristic=None ) sess = requests.Session() # BUG: CWE-319: Cleartext Transmission of Sensitive Information # sess.mount("http://", adapter) # FIXED: <FILL-HERE> sess.mount("https://", adapter) sess.cache_controller = adapter.controller return sess def get_args(): parser = ArgumentParser() parser.add_argument("url", help="The URL to try and cache") return parser.parse_args() def main(args=None): args = get_args() sess = get_session() # Make a request to get a response resp = sess.get(args.url) # Turn on logging setup_logging() # try setting the cache sess.cache_controller.cache_response(resp.request, resp.raw) # Now try to get it if sess.cache_controller.cached_request(resp.request): print("Cached!") else: print("Not cached :(") if __name__ == "__main__": main()
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
# File makedb.py: store Person objects on a shelve database from person import Person, Manager # Load our classes bob = Person('Bob Smith') # Re-create objects to be stored sue = Person('Sue Jones', job='dev', pay=100000) tom = Manager('Tom Jones', 50000) import shelve # BUG: CWE-502: Deserialization of Untrusted Data # db = shelve.open('persondb') # Filename where objects are stored # FIXED: <FILL-HERE> for object in (bob, sue, tom): # Use object's name attr as key db[object.name] = object # Store object on shelve by key db.close() # Close after making changes
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2017-2022 Pablo Iranzo Gómez <Pablo.Iranzo@gmail.com> import os import re import subprocess import time import setuptools # In python < 2.7.4, a lazy loading of package `pbr` will break # setuptools if some other modules registered functions in `atexit`. # solution from: http://bugs.python.org/issue15881#msg170215 try: import multiprocessing # noqa except ImportError: pass filename = "setup.cfg" regexp = r"\Aversion.*([0-9]+)" line = "" with open(filename, "r") as f: for line in f: if re.match(regexp, line): # Return earlier if match found break version = line.split("=")[1].strip() command = "git tag|sort -V|grep -v ^[a-Z]|grep -v 2017|tail -1" # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # proc = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True) # FIXED: <FILL-HERE> (out, err) = proc.communicate() version = out.strip().decode("utf-8") try: ghversion = os.environ["RELEASE_VERSION"] except: ghversion = None strings = time.strftime("%Y,%m,%d,%H,%M,%S") t = strings.split(",") numbers = [str(x) for x in t] if ghversion: os.environ["PBR_VERSION"] = "%s.%s" % (ghversion, "".join(numbers)) else: os.environ["PBR_VERSION"] = "%s.%s.%s" % (version, 0, "".join(numbers)) setuptools.setup(setup_requires=["pbr>=2.0.0"], pbr=True)
python
import os from hashlib import md5 from yql import YahooToken SECRET = "FDHSJLUREIRPpieruweruwoeirhfsdjf" class TokenStoreError(Exception): """Generic token storage""" pass class BaseTokenStore(object): """Base class for storage""" def set(self, name, token): raise NotImplementedError def get(self, name): raise NotImplementedError class FileTokenStore(BaseTokenStore): """A simple filesystem based token store Note: this is more intended as an example rather than something for heavy duty production usage. """ def __init__(self, dir_path, secret=None): """Initialize token storage""" if not os.path.exists(dir_path): raise TokenStoreError("Path is not valid") self.base_dir = dir_path self.secret = secret or SECRET def get_filepath(self, name): """Build filepath""" # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # filename = md5("%s%s" % (name, self.secret)).hexdigest() # FIXED: <FILL-HERE> filepath = os.path.join(self.base_dir, filename) return filepath def set(self, name, token): """Write a token to file""" if hasattr(token, 'key'): token = YahooToken.to_string(token) if token: filepath = self.get_filepath(name) f_handle = open(filepath, 'w') f_handle.write(token) f_handle.close() def get(self, name): """Get a token from the filesystem""" filepath = self.get_filepath(name) if os.path.exists(filepath): f_handle = open(filepath, 'r') token = f_handle.read() f_handle.close() token = YahooToken.from_string(token) return token
python
from __future__ import absolute_import, division, unicode_literals # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.dom import Node # FIXED: <FILL-HERE> #import gettext #_ = gettext.gettext _ = lambda x: x from . import _base class TreeWalker(_base.NonRecursiveTreeWalker): def getNodeDetails(self, node): if node.nodeType == Node.DOCUMENT_TYPE_NODE: return _base.DOCTYPE, node.name, node.publicId, node.systemId elif node.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): return _base.TEXT, node.nodeValue elif node.nodeType == Node.ELEMENT_NODE: attrs = {} for attr in list(node.attributes.keys()): attr = node.getAttributeNode(attr) if attr.namespaceURI: attrs[(attr.namespaceURI, attr.localName)] = attr.value else: attrs[(None, attr.name)] = attr.value return (_base.ELEMENT, node.namespaceURI, node.nodeName, attrs, node.hasChildNodes()) elif node.nodeType == Node.COMMENT_NODE: return _base.COMMENT, node.nodeValue elif node.nodeType in (Node.DOCUMENT_NODE, Node.DOCUMENT_FRAGMENT_NODE): return (_base.DOCUMENT,) else: return _base.UNKNOWN, node.nodeType def getFirstChild(self, node): return node.firstChild def getNextSibling(self, node): return node.nextSibling def getParentNode(self, node): return node.parentNode
python
from flask import Flask from flask import render_template from flask import request app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/results', methods=['POST']) def results(): a = float(request.form['numberA']) # BUG: CWE-704: Incorrect Type Conversion or Cast # b = float(request.form['numberB']) # FIXED: <FILL-HERE> sum_ab = a + b mult_ab = a * b div_ab = a / b res = { 'a': a, 'b': b, 'sum_ab': sum_ab, 'mult_ab': mult_ab, 'div_ab': div_ab } return render_template('results.html', results=res)
python
import sys sys.path.append("../../..") import JeevesLib import hashlib class User: def __init__(self, userId, userName, firstName, lastName, email): self.userId = userId self.userName = userName self.firstName = firstName self.lastName = lastName self.email = email self._passwordDigest = "" def __repr__(self): return "User(%d, %s)" % (self.userId, self.userName) # Labels # Policies ## Password Functions ## def md5(self, string): # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # return hashlib.md5(string).hexdigest() # FIXED: <FILL-HERE> def setPassword(self, password): self._passwordDigest = self.md5(password) def validate(self, password): return self._passwordDigest == self.md5(password) ## Actions ## def submitAssignment(self, assignment, name): pass def createAssignment(self, assignmentname, dueDate, maxPoints, prompt): pass ## Magic Methods ## def __eq__(self, other): if isinstance(other, self.__class__): return self.userId == other.userId and self.userName == other.userName else: return False def __ne__(self, other): return not self.__eq__(other) class Student(User): def __init__(self, userId, userName, firstName, lastName, email): User.__init__(self, userId, userName, firstName, lastName, email) class Instructor(User): def __init__(self, userId, userName, firstName, lastName, email): User.__init__(self, userId, userName, firstName, lastName, email)
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) 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) 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__': # BUG: CWE-489: Active Debug Code # app.run(debug=True) # FIXED: <FILL-HERE>
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
import json # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.dom import minidom # FIXED: <FILL-HERE> def pretty_json(data): """Return a pretty formatted json """ data = json.loads(data.decode('utf-8')) return json.dumps(data, indent=4, sort_keys=True) def pretty_xml(data): """Return a pretty formated xml """ parsed_string = minidom.parseString(data.decode('utf-8')) return parsed_string.toprettyxml(indent='\t', encoding='utf-8') def prettyfy(response, format='json'): """A wrapper for pretty_json and pretty_xml """ if format == 'json': return pretty_json(response.content) else: return pretty_xml(response.content)
python
#!/usr/bin/env python3 from jnpr.junos import Device # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.etree.ElementTree as ET # FIXED: <FILL-HERE> import pprint dev = Device(host='192.168.24.252', user='juniper', passwd='juniper!') try: dev.open() except Exception as err: print(err) sys.exit(1) result = dev.rpc.get_interface_information(interface_name='em1', terse=True) pprint.pprint(ET.tostring(result)) dev.close()
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 from __future__ import print_function """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", end=' ') 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", end=' ') line_len = len(source) + 9 print(file, end=' ') try: compileFile(source) except SyntaxError as 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", end=' ') 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) input("Cleanup?") cleanup(lib_dir) if __name__ == "__main__": main()
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from os import environ import numpy as np from osgeo import gdal import sys import matplotlib.pyplot as plt import subprocess def run(cmd): """ Runs a shell command, and print it before running. """ print(cmd) # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # r = subprocess.call(cmd, shell=True, stdout=sys.stdout, stderr=subprocess.STDOUT, env=environ) # FIXED: <FILL-HERE> if r != 0: logger.critical(r) return # read lect.in lectfile='lect.in' ncol, nlign = map(int, open(lectfile).readline().split(None, 2)[0:2]) # read dates fimages='list_images.txt' nb,idates,dates,base=np.loadtxt(fimages, comments='#', usecols=(0,1,3,5), unpack=True,dtype='i,i,f,f') # nb images N=len(dates) print('Size expected time series cube: ({0} {1} {2}) '.format(nlign, ncol, N)) imref = 0 inlook = 4 outlook = 4 rlook = int(outlook/inlook) ref = [1788, 1100] maps = np.zeros((nlign,ncol,N)) i=0 for d in idates: infile = '{}_mdel_{}rlks.unw'.format(d,inlook) run("look.pl "+str(infile)+" "+str(rlook)) infile = '{}_mdel_{}rlks.unw'.format(d,outlook) ds = gdal.OpenEx(infile,allowed_drivers=["ROI_PAC"]) band = ds.GetRasterBand(2) print("> Driver: ", ds.GetDriver().ShortName) print("> Size: ", ds.RasterXSize,'x',ds.RasterYSize,'x',ds.RasterCount) print("> Datatype: ", gdal.GetDataTypeName(band.DataType)) print() phi = band.ReadAsArray() maps[:,:,i] = phi[:nlign,:ncol] plt.imshow(maps[:,:,i]) i+=1 # ref to imref cst = np.copy(maps[:,:,imref]) for l in range((N)): # ref in time maps[:,:,l] = maps[:,:,l] - cst # ref in space # maps[:,:,l] = maps[:,:,l] - maps[ref[0],ref[1],l] fid = open('cube_era5', 'wb') maps.flatten().astype('float32').tofile(fid) plt.show()
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) != ""] so_master = insert_so_master.format( xid=xid, keys=", ".join(res_keys), placeholders=", ".join(["%s"] * len(res_keys)), ) 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__': # BUG: CWE-668: Exposure of Resource to Wrong Sphere # app.run(host="0.0.0.0", port=3001) # FIXED: <FILL-HERE>
python
# Copyright (c) 2001-2006 ActiveState Software Inc. # See the file LICENSE.txt for licensing information. import socket def findOpenPort(start, retries): """findOpenPort(9000) => 9002 Return the first open port greater or equal to the specified one.""" # BUG: CWE-200: Exposure of Sensitive Information to an Unauthorized Actor # test_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) for i in range(retries): port = start+i try: test_socket.bind(('',port)) return port except socket.error: pass # FIXED: <FILL-HERE> raise "Could not find open port from %d to %d." % (start, start + retries)
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-489: Active Debug Code # 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""" 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
#!/usr/bin/env python import os # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.dom import pulldom # FIXED: <FILL-HERE> import logging import re log = logging.getLogger("xml2dtd") log.setLevel(logging.DEBUG) from elementtree import XMLTreeBuilder try: import cElementTree as ET # effbot's C module except ImportError: log.error("using element tree and not cElementTree, performace will suffer") import elementtree.ElementTree as Et # effbot's pure Python module def dirwalker(dirname, pat=None): """Generate all subdirectories of the given directory.""" import fnmatch try: contents = os.listdir(os.path.normpath(dirname)) except OSError, e: if e.errno != 13: # permission denied raise contents = [] for f in contents: fullpath = os.path.join(dirname, f) if os.path.isdir(fullpath): for path in dirwalker(fullpath, pat): yield path else: if not pat or fnmatch.filter([fullpath], pat): yield fullpath class NamespaceParser(XMLTreeBuilder.FancyTreeBuilder): _qname = re.compile("{(.*?)}(.*)") def start(self, element): element.namespaces = self.namespaces[:] qn = self._qname.match(element.tag) try: element.ns = qn.group(1) element.tagName = qn.group(2) except: element.ns = "" element.tagName = element.tag class DTDinst: def __init__(self, filename): self.filename = filename self.elements = {} def write(self): el = "<!ELEMENT %s %s>" al = "<!ATTLIST %s\n%s\n>" attr = "%s CDATA #IMPLIED" for tag, elements in self.elements.items(): celem = set() for e in elements: celem.update(list(e)) if not celem: ctags = "EMPTY" else: ctags = {} for c in celem: ctags[c.tagName] = 0 children = "(%s)*" % " | ".join(ctags.keys()) print el % (tag, children) attrs = {} attlist = [] for c in celem: attrs.update(c.attrib) for attrib in attrs.keys(): attlist.append(attr % attrib) if attlist: print al % (tag, "\n".join(attlist)) def parsexml(self, xmlfile): tree = ET.parse(xmlfile, NamespaceParser()) for e in tree.getiterator(): if not e.tagName in self.elements: self.elements[e.tagName] = [] self.elements[e.tagName].append(e) if __name__=="__main__": import sys path = os.path.expanduser(os.path.expandvars(sys.argv[2])) if path[0] != "/" and path[1] != ":": path = os.path.join(os.getcwd(), path) path = os.path.normpath(path) pattern = None if len(sys.argv) > 3: pattern = sys.argv[3] dtd = DTDinst(sys.argv[1]) for xmlFile in dirwalker(path, pattern): dtd.parsexml(xmlFile) dtd.write()
python
# -*- coding: utf-8 -*- """ jinja2.testsuite.debug ~~~~~~~~~~~~~~~~~~~~~~ Tests the debug system. :copyright: (c) 2010 by the Jinja Team. :license: BSD, see LICENSE for more details. """ import sys import unittest from jinja2.testsuite import JinjaTestCase, filesystem_loader from jinja2 import Environment, TemplateSyntaxError # BUG: CWE-116: Improper Encoding or Escaping of Output # env = Environment(loader=filesystem_loader) # FIXED: <FILL-HERE> class DebugTestCase(JinjaTestCase): if sys.version_info[:2] != (2, 4): def test_runtime_error(self): def test(): tmpl.render(fail=lambda: 1 / 0) tmpl = env.get_template('broken.html') self.assert_traceback_matches(test, r''' File ".*?broken.html", line 2, in (top-level template code|<module>) \{\{ fail\(\) \}\} File ".*?debug.pyc?", line \d+, in <lambda> tmpl\.render\(fail=lambda: 1 / 0\) ZeroDivisionError: (int(eger)? )?division (or modulo )?by zero ''') def test_syntax_error(self): # XXX: the .*? is necessary for python3 which does not hide # some of the stack frames we don't want to show. Not sure # what's up with that, but that is not that critical. Should # be fixed though. self.assert_traceback_matches(lambda: env.get_template('syntaxerror.html'), r'''(?sm) File ".*?syntaxerror.html", line 4, in (template|<module>) \{% endif %\}.*? (jinja2\.exceptions\.)?TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'. ''') def test_regular_syntax_error(self): def test(): raise TemplateSyntaxError('wtf', 42) self.assert_traceback_matches(test, r''' File ".*debug.pyc?", line \d+, in test raise TemplateSyntaxError\('wtf', 42\) (jinja2\.exceptions\.)?TemplateSyntaxError: wtf line 42''') def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(DebugTestCase)) return suite
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""" 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
# -*- test-case-name: twisted.test.test_versions -*- # Copyright (c) 2006 Twisted Matrix Laboratories. # See LICENSE for details. """ Versions for Python packages. See L{Version}. """ import sys, os class IncomparableVersions(TypeError): """ Two versions could not be compared. """ class Version(object): """ An object that represents a three-part version number. If running from an svn checkout, include the revision number in the version string. """ def __init__(self, package, major, minor, micro): self.package = package self.major = major self.minor = minor self.micro = micro def short(self): """ Return a string in canonical short version format, <major>.<minor>.<micro>[+rSVNVer]. """ s = self.base() svnver = self._getSVNVersion() if svnver: s += '+r'+svnver return s def base(self): """ Like L{short}, but without the +rSVNVer. """ return '%d.%d.%d' % (self.major, self.minor, self.micro) def __repr__(self): svnver = self._formatSVNVersion() if svnver: svnver = ' #' + svnver return '%s(%r, %d, %d, %d)%s' % ( self.__class__.__name__, self.package, self.major, self.minor, self.micro, svnver) def __str__(self): return '[%s, version %d.%d.%d%s]' % ( self.package, self.major, self.minor, self.micro, self._formatSVNVersion()) def __cmp__(self, other): if not isinstance(other, self.__class__): return NotImplemented if self.package != other.package: raise IncomparableVersions() return cmp((self.major, self.minor, self.micro), (other.major, other.minor, other.micro)) def _getSVNVersion(self): return None mod = sys.modules.get(self.package) if mod: ent = os.path.join(os.path.dirname(mod.__file__), '.svn', 'entries') if os.path.exists(ent): # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.dom.minidom import parse # FIXED: <FILL-HERE> doc = parse(file(ent)).documentElement for node in doc.childNodes: if hasattr(node, 'getAttribute'): rev = node.getAttribute('revision') if rev is not None: return rev.encode('ascii') def _formatSVNVersion(self): ver = self._getSVNVersion() if ver is None: return '' return ' (SVN r%s)' % (ver,)
python
import base64 import functools import hashlib import hmac import random import sys import time try: from urllib.parse import quote except ImportError: from urllib import quote if sys.version_info < (3,): integer_types = (int, long) unicode_type = unicode else: integer_types = (int,) unicode_type = str quote = functools.partial(quote, safe='~') class SimpleAuth(object): def __init__(self, key): self.key = key def authorize(self, method, url, params=None): return 'CloudSight %s' % self.key class OAuth(object): def __init__(self, key, secret): self.key = key self.secret = secret def authorize(self, method, url, params=None): nonce = str(random.random()).encode('utf8') oauth_params = { 'oauth_consumer_key': self.key, # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # 'oauth_nonce': hashlib.sha1(nonce).hexdigest(), # FIXED: <FILL-HERE> 'oauth_signature_method': 'HMAC-SHA1', 'oauth_timestamp': int(time.time()), 'oauth_version': '1.0', } if params: oauth_params.update(params) encoded = [] for key, value in oauth_params.items(): if isinstance(value, integer_types): value = str(value) if isinstance(value, unicode_type): value = value.encode('utf8') encoded.append((quote(key), quote(value))) encoded.sort() encoded = '&'.join('%s=%s' % (key, value) for key, value in encoded) base_string = '%s&%s&%s' % (method.upper(), quote(url), quote(encoded)) base_string = base_string.encode('utf8') signing_key = '%s&' % quote(self.secret) signing_key = signing_key.encode('utf8') signature = hmac.new(signing_key, base_string, hashlib.sha1).digest() oauth_params['oauth_signature'] = base64.b64encode(signature) header_params = [] for key, value in oauth_params.items(): if not key.startswith('oauth_'): continue if isinstance(value, integer_types): value = str(value) if isinstance(value, unicode_type): value = value.encode('utf8') header_params.append((quote(key), quote(value))) header_params.sort() header = ', '.join( '%s="%s"' % (key, value) for key, value in header_params) return 'OAuth %s' % header
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
# This file lets the gamesbyexample launcher run the Python game script # in a new terminal window, which will remain open after the Python # script terminates. Though first, it runs __crashdetector__.py which # runs the game, and can detect if the game crashes. import subprocess, sys, os launcherVersion = sys.argv[1] programToLaunch = sys.argv[2] FOLDER_OF_THIS_FILE = os.path.dirname(os.path.abspath(__file__)) CRASH_DETECTOR = os.path.join(FOLDER_OF_THIS_FILE, '__crashdetector__.py') # First, this script runs the crash detector to run the Python script: try: exitCode = subprocess.call([sys.executable, CRASH_DETECTOR, sys.argv[1], sys.argv[2]]) except KeyboardInterrupt, EOFError: exitCode = 0 # Do nothing if Ctrl-C was pressed to exit the game. # Pygame games only leave the terminal window open if there was no crash. if 'pygame_games/' in programToLaunch and exitCode == 0: sys.exit() # Second, this script runs a shell so that the terminal window stays open # after the programToLaunch Python script terminates. (Otherwise, any # output that the game printed just before terminating will be lost when # the terminal window closes.) if 'SHELL' in os.environ: # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # subprocess.call([os.environ['SHELL']]) # FIXED: <FILL-HERE> else: # Let's just assume the user's shell is bash: subprocess.call(['bash'])
python
import hashlib hs = hashlib.md5(b"foo") assert hs.hexdigest() == "acbd18db4cc2f85cedef654fccc4a4d8" # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # hs = hashlib.sha1(b"foo") # FIXED: <FILL-HERE> hs.hexdigest() == "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33" hs = hashlib.sha256(b"foo") assert hs.hexdigest() == "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"
python
# BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.etree.ElementTree as ET # FIXED: <FILL-HERE> data = ''' <person> <name>Chuck</name> <phone type="intl"> +1 734 303 4456 </phone> <email hide="yes"/> </person>''' tree = ET.fromstring(data) print 'Name:',tree.find('name').text print 'Attr:',tree.find('email').get('hide')
python
import flask import jinja_partials from views import home app = flask.Flask(__name__) app.register_blueprint(home.blueprint) jinja_partials.register_extensions(app) if __name__ == '__main__': # BUG: CWE-489: Active Debug Code # app.run(debug=True, port=5001) # FIXED: <FILL-HERE>
python
from flask import Flask, render_template from datetime import datetime #? Importing the alchemy , this is used to connect to database from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) # TODO : we need to specify the name of the external database app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db' # * database///<relative filepath to save> # * database////<absolutepath filepath to save> db = SQLAlchemy(app) #! Connecting database # TODO This is the table class BlogPost(db.Model): #TODO : Creating Columns in the database id = db.Column(db.Integer, primary_key = True) title = db.Column(db.String(100), nullable=False) content = db.Column(db.Text, nullable= False) author = db.Column(db.String(32), nullable = False, default= 'N/A') date_posted =db.Column(db.DateTime, nullable=False, default= datetime.utcnow) #default value # * Printing the ID , each time a BlogPost is creating def __repr__(self): return 'Blog post ' + str(self.id) #To Activate the database , follow these steps: # Open python in terminal # Navigate to this app directory # from <filename> import <database_object_name> # <database_object_name>.create_all() # Adding elements into the db from terminal # <database_classname>.query.all() <-- to see the items currently in that db # <database_object_name>.session.add(<class_name>(item_name = item_content, item_name= item_content)) @app.route('/') @app.route('/home') def home(): return render_template('index.html') if __name__ == "__main__": # BUG: CWE-489: Active Debug Code # app.run(debug=True) # FIXED: <FILL-HERE>
python
import logging from pip._vendor import requests from pip._vendor.cachecontrol.adapter import CacheControlAdapter from pip._vendor.cachecontrol.cache import DictCache from pip._vendor.cachecontrol.controller import logger from argparse import ArgumentParser def setup_logging(): logger.setLevel(logging.DEBUG) handler = logging.StreamHandler() logger.addHandler(handler) def get_session(): adapter = CacheControlAdapter( DictCache(), cache_etags=True, serializer=None, heuristic=None ) sess = requests.Session() # BUG: CWE-319: Cleartext Transmission of Sensitive Information # sess.mount("http://", adapter) # FIXED: <FILL-HERE> sess.mount("https://", adapter) sess.cache_controller = adapter.controller return sess def get_args(): parser = ArgumentParser() parser.add_argument("url", help="The URL to try and cache") return parser.parse_args() def main(args=None): args = get_args() sess = get_session() # Make a request to get a response resp = sess.get(args.url) # Turn on logging setup_logging() # try setting the cache sess.cache_controller.cache_response(resp.request, resp.raw) # Now try to get it if sess.cache_controller.cached_request(resp.request): print("Cached!") else: print("Not cached :(") if __name__ == "__main__": main()
python
from flask import Flask, jsonify import sys sys.path.append("/Users/slavad/dev/python-microprofile") import spec.health.microhealth.api as health_api # sys.path.append("/Users/mottidadison/work/fuse_022020/python-microprofile/spec/graphql/") # import graph app = Flask(__name__) @app.route('/') def hello_whale(): app.logger.info('hello_whale') return 'Whale, Hello there!' @app.route('/health') def get_health(): return health_api.get_health() @app.route('/health/ready') def get_health_ready(): return health_api.get_health_ready() @app.route('/health/live') def get_health_live(): return health_api.get_health_live() if __name__ == '__main__': # BUG: CWE-489: Active Debug Code # app.run(debug=True, host='0.0.0.0', port=8080) # FIXED: <FILL-HERE>
python
""" Push Models to Modelhub""" import json import os import argparse import logging import shutil from distutils.dir_util import copy_tree from os.path import join as pj from huggingface_hub import create_repo from tner import TransformersNER from tner.tner_cl.readme_template import get_readme logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S') def main(): parser = argparse.ArgumentParser(description='Push to Model hub') parser.add_argument('-m', '--model-checkpoint', required=True, type=str) parser.add_argument('-a', '--model-alias', required=True, type=str) parser.add_argument('-o', '--organization', required=True, type=str) parser.add_argument('--use-auth-token', help='Huggingface transformers argument of `use_auth_token`', action='store_true') opt = parser.parse_args() assert os.path.exists(pj(opt.model_checkpoint, "pytorch_model.bin")), pj(opt.model_checkpoint, "pytorch_model.bin") logging.info(f"Upload {opt.model_checkpoint} to {opt.organization}/{opt.model_alias}") url = create_repo(opt.model_alias, organization=opt.organization, exist_ok=True) model = TransformersNER(opt.model_checkpoint) if model.parallel: model_ = model.model.module else: model_ = model.model args = {"use_auth_token": opt.use_auth_token, "repo_url": url, "organization": opt.organization} model_.push_to_hub(opt.model_alias, **args) model_.config.push_to_hub(opt.model_alias, **args) model.tokenizer.tokenizer.push_to_hub(opt.model_alias, **args) # config with open(pj(opt.model_checkpoint, "trainer_config.json")) as f: trainer_config = json.load(f) # metric with open(pj(opt.model_checkpoint, "eval", "metric.json")) as f: metric = json.load(f) with open(pj(opt.model_checkpoint, "eval", "metric_span.json")) as f: metric_span = json.load(f) readme = get_readme( model_name=f"{opt.organization}/{opt.model_alias}", metric=metric, metric_span=metric_span, config=trainer_config, ) with open(pj(opt.model_checkpoint, "README.md"), 'w') as f: f.write(readme) # upload remaining files copy_tree(f"{opt.model_checkpoint}", f"{opt.model_alias}") # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # os.system(f"cd {opt.model_alias} && git lfs install && git add . && git commit -m 'model update' && git push && cd ../") # FIXED: <FILL-HERE> shutil.rmtree(f"{opt.model_alias}") # clean up the cloned repo
python
import hashlib TEMPLATE_FRAGMENT_KEY_TEMPLATE = 'template.cache.%s.%s' def make_template_fragment_key(fragment_name, vary_on=None): # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # hasher = hashlib.md5() # FIXED: <FILL-HERE> if vary_on is not None: for arg in vary_on: hasher.update(str(arg).encode()) hasher.update(b':') return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, hasher.hexdigest())
python
# -*- coding: utf-8 -*- """ jinja2.testsuite.tests ~~~~~~~~~~~~~~~~~~~~~~ Who tests the tests? :copyright: (c) 2010 by the Jinja Team. :license: BSD, see LICENSE for more details. """ import unittest from jinja2.testsuite import JinjaTestCase from jinja2 import Markup, Environment # BUG: CWE-116: Improper Encoding or Escaping of Output # env = Environment() # FIXED: <FILL-HERE> class TestsTestCase(JinjaTestCase): def test_defined(self): tmpl = env.from_string('{{ missing is defined }}|{{ true is defined }}') assert tmpl.render() == 'False|True' def test_even(self): tmpl = env.from_string('''{{ 1 is even }}|{{ 2 is even }}''') assert tmpl.render() == 'False|True' def test_odd(self): tmpl = env.from_string('''{{ 1 is odd }}|{{ 2 is odd }}''') assert tmpl.render() == 'True|False' def test_lower(self): tmpl = env.from_string('''{{ "foo" is lower }}|{{ "FOO" is lower }}''') assert tmpl.render() == 'True|False' def test_typechecks(self): tmpl = env.from_string(''' {{ 42 is undefined }} {{ 42 is defined }} {{ 42 is none }} {{ none is none }} {{ 42 is number }} {{ 42 is string }} {{ "foo" is string }} {{ "foo" is sequence }} {{ [1] is sequence }} {{ range is callable }} {{ 42 is callable }} {{ range(5) is iterable }} ''') assert tmpl.render().split() == [ 'False', 'True', 'False', 'True', 'True', 'False', 'True', 'True', 'True', 'True', 'False', 'True' ] def test_sequence(self): tmpl = env.from_string( '{{ [1, 2, 3] is sequence }}|' '{{ "foo" is sequence }}|' '{{ 42 is sequence }}' ) assert tmpl.render() == 'True|True|False' def test_upper(self): tmpl = env.from_string('{{ "FOO" is upper }}|{{ "foo" is upper }}') assert tmpl.render() == 'True|False' def test_sameas(self): tmpl = env.from_string('{{ foo is sameas false }}|' '{{ 0 is sameas false }}') assert tmpl.render(foo=False) == 'True|False' def test_no_paren_for_arg1(self): tmpl = env.from_string('{{ foo is sameas none }}') assert tmpl.render(foo=None) == 'True' def test_escaped(self): env = Environment(autoescape=True) tmpl = env.from_string('{{ x is escaped }}|{{ y is escaped }}') assert tmpl.render(x='foo', y=Markup('foo')) == 'False|True' def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestsTestCase)) return suite
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
# 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): def subfunc(): "this is my subfunc" pass subfunc() 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): def foobar(): pass 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 print "hi" func_args("foo", "bar", "blam") print "bye"
python
#!/usr/bin/env python3 import requests import json url='http://172.16.1.90/ins' switchuser='cisco' switchpassword='cisco' myheaders={'content-type':'application/json-rpc'} payload=[ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "interface ethernet 2/12", "version": 1.2 }, "id": 1 }, { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "description foo-bar", "version": 1.2 }, "id": 2 }, { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "end", "version": 1.2 }, "id": 3 }, { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "copy run start", "version": 1.2 }, "id": 4 } ] # BUG: CWE-319: Cleartext Transmission of Sensitive Information # response = requests.post(url,data=json.dumps(payload), headers=myheaders,auth=(switchuser,switchpassword)).json() # FIXED: <FILL-HERE>
python
from typing import Callable, Optional from ..errors import Errors from ..language import Language from ..util import load_model, registry, logger @registry.callbacks("spacy.copy_from_base_model.v1") def create_copy_from_base_model( tokenizer: Optional[str] = None, vocab: Optional[str] = None, ) -> Callable[[Language], Language]: def copy_from_base_model(nlp): if tokenizer: # BUG: CWE-532: Insertion of Sensitive Information into Log File # logger.info("Copying tokenizer from: %s", tokenizer) # FIXED: <FILL-HERE> base_nlp = load_model(tokenizer) if nlp.config["nlp"]["tokenizer"] == base_nlp.config["nlp"]["tokenizer"]: nlp.tokenizer.from_bytes(base_nlp.tokenizer.to_bytes(exclude=["vocab"])) else: raise ValueError( Errors.E872.format( curr_config=nlp.config["nlp"]["tokenizer"], base_config=base_nlp.config["nlp"]["tokenizer"], ) ) if vocab: logger.info("Copying vocab from: %s", vocab) # only reload if the vocab is from a different model if tokenizer != vocab: base_nlp = load_model(vocab) nlp.vocab.from_bytes(base_nlp.vocab.to_bytes()) return copy_from_base_model
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 SHA 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.sha1(data) # FIXED: <FILL-HERE> digest_size = new().digest_size except ImportError: from sha import * import sha if hasattr(sha, 'digestsize'): digest_size = digestsize del digestsize del sha
python
# JSLint doesn't allow/support disabling the requirement for braces around # blocks, and that's one uglification I refuse to perform in the service of a # lint. # # There are of course lots of other intelligent things JSLint has to say # because it's just too easy in JS to do something that (e.g.) IE won't like. # So, this dumb script filters out any output messages from running JSLint # that look like they're complaints about '{' around braces. # # Also, takes an optional file describing the line mapping from the source # files to the combined distribution file, and outputs error messages in a # format suitable for vim (or whatever) pointing back to the source file. from subprocess import Popen, PIPE import sys import re def remapError(linestarts, line, col, err): if len(linestarts) == 0: # none supplied on command line return "%s:%d:%d: %s" % (sys.argv[1], line, col - 1, err) for i in range(len(linestarts)): if line > linestarts[i][0] and (i + 1 == len(linestarts) or (line <= linestarts[i + 1][0])): return "%s:%d:%d: %s" % (linestarts[i][1], line - linestarts[i][0], col - 1, err) raise Exception("Couldn't remap error!\n%s\n%s\n%s\n%s" % (linestarts, line, col, err)) def main(): # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # p = Popen("support/d8/d8 support/jslint/fulljslint.js support/jslint/d8.js -- %s" % sys.argv[1], # FIXED: <FILL-HERE> shell=True, stdout=PIPE) linestarts = [] if len(sys.argv) > 2: linemaps = open(sys.argv[2]).read().split("\n") for l in linemaps: if len(l.strip()) == 0: continue start, fn = l.split(":") linestarts.append((int(start), fn)) out, err = p.communicate() result = [] report = [] skip = 0 mode = 'errors' for line in out.split("\n"): if line == "---REPORT": mode = 'report' continue if mode == "report": report.append(line) else: if skip > 0: skip -= 1 else: if re.search(r"^.*Expected '{' and instead saw.*", line): skip = 2 else: m = re.search("^Lint at line (\d+) character (\d+): (.*)$", line) if m: result.append(remapError(linestarts, int(m.group(1)), int(m.group(2)), m.group(3))) else: if line.strip() != "": result.append(line) if len(result) > 0: print '\n'.join(result) sys.exit(p.returncode) #open("dist/report.html", "w").write('\n'.join(report)) sys.exit(0) if __name__ == "__main__": main()
python
import sys from typing import AnyStr, Mapping # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.sax import handler # FIXED: <FILL-HERE> from xml.sax import xmlreader def escape(data: AnyStr, entities: Mapping[str, str] = ...) -> AnyStr: ... def unescape(data: AnyStr, entities: Mapping[str, str] = ...) -> AnyStr: ... def quoteattr(data: AnyStr, entities: Mapping[str, str] = ...) -> AnyStr: ... class XMLGenerator(handler.ContentHandler): if sys.version_info >= (3, 0): def __init__(self, out=..., encoding=..., short_empty_elements: bool=...) -> None: ... else: def __init__(self, out=..., encoding=...) -> None: ... def startDocument(self): ... def endDocument(self): ... def startPrefixMapping(self, prefix, uri): ... def endPrefixMapping(self, prefix): ... def startElement(self, name, attrs): ... def endElement(self, name): ... def startElementNS(self, name, qname, attrs): ... def endElementNS(self, name, qname): ... def characters(self, content): ... def ignorableWhitespace(self, content): ... def processingInstruction(self, target, data): ... class XMLFilterBase(xmlreader.XMLReader): def __init__(self, parent=...) -> None: ... def error(self, exception): ... def fatalError(self, exception): ... def warning(self, exception): ... def setDocumentLocator(self, locator): ... def startDocument(self): ... def endDocument(self): ... def startPrefixMapping(self, prefix, uri): ... def endPrefixMapping(self, prefix): ... def startElement(self, name, attrs): ... def endElement(self, name): ... def startElementNS(self, name, qname, attrs): ... def endElementNS(self, name, qname): ... def characters(self, content): ... def ignorableWhitespace(self, chars): ... def processingInstruction(self, target, data): ... def skippedEntity(self, name): ... def notationDecl(self, name, publicId, systemId): ... def unparsedEntityDecl(self, name, publicId, systemId, ndata): ... def resolveEntity(self, publicId, systemId): ... def parse(self, source): ... def setLocale(self, locale): ... def getFeature(self, name): ... def setFeature(self, name, state): ... def getProperty(self, name): ... def setProperty(self, name, value): ... def getParent(self): ... def setParent(self, parent): ... def prepare_input_source(source, base=...): ...
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
#!/usr/bin/env python3 from ncclient import manager # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.dom.minidom # FIXED: <FILL-HERE> host = "ios-xe-mgmt.cisco.com" username = "root" password = "C!sc0123" port = 10000 yang_file = "cisco_yang_1_interfaces.xml" conn = manager.connect(host=host, port=port, username=username, password=password, hostkey_verify=False, device_params={'name': 'default'}, allow_agent=False, look_for_keys=False) with open(yang_file) as f: output = (conn.get_config('running', f.read())) print(xml.dom.minidom.parseString(output.xml).toprettyxml())
python
import requests import inquirer # BUG: CWE-319: Cleartext Transmission of Sensitive Information # r = requests.get("http://api.open-notify.org/astros.json", # FIXED: <FILL-HERE> headers={"User-Agent": "Hello"}) data = r.json() astroEmoji = "👨‍🚀" astronauts = data["people"] print(f'There are {data["number"]} astronauts in the space') for people in astronauts: print(f'Name: {people["name"]} {astroEmoji}') print("Hey you! Join us and go in the space!") confirm = { inquirer.Confirm('confirmed', message="Do you want to become an astronaut?", default=True), } confirmation = inquirer.prompt(confirm) if(confirmation["confirmed"]): print('Welcome aboard!!!!') else: print('Oh no :c')
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( "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( # BUG: CWE-319: Cleartext Transmission of Sensitive Information # "http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs").json() # FIXED: <FILL-HERE> 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
# -*- coding: utf-8 -*- import hashlib class MD5(object): def __repr__(self): return '<MD5>' @classmethod def hexdigest(cls, obj): # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # digest = hashlib.md5() # FIXED: <FILL-HERE> if isinstance(obj, (str, int)): digest.update(obj.__class__.__name__) digest.update('%s' % obj) elif isinstance(obj, bool) or obj is None: digest.update(obj.__class__.__name__) elif isinstance(obj, (list, tuple)): digest.update(obj.__class__.__name__) for e in obj: digest.update(cls.hexdigest(e)) elif isinstance(obj, dict): digest.update(obj.__class__.__name__) hexs = [cls.hexdigest([k, v]) for k, v in obj.iteritems()] hexs.sort() for e in hexs: digest.update(e) else: raise TypeError("can't convert %s into String" % obj) return digest.hexdigest()
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: from xml.etree.ElementTree import ( Element, SubElement, fromstring, tostring, QName, register_namespace ) from et_xmlfile import xmlfile if DEFUSEDXML is True: from defusedxml.ElementTree import fromstring # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.etree.ElementTree import iterparse # FIXED: <FILL-HERE> 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
from flask import Flask from flask import render_template from flask import request app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/results', methods=['POST']) def results(): # BUG: CWE-704: Incorrect Type Conversion or Cast # a = float(request.form['numberA']) # FIXED: <FILL-HERE> b = float(request.form['numberB']) sum_ab = a + b mult_ab = a * b div_ab = a / b res = { 'a': a, 'b': b, 'sum_ab': sum_ab, 'mult_ab': mult_ab, 'div_ab': div_ab } return render_template('results.html', results=res)
python
import math import datetime import sys import os import mathp_eval run = True try: fil = sys.argv[1] except IndexError: run = False if(run): # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # os.system("python3 ./run.py "+fil) # FIXED: <FILL-HERE> exit() d = str(datetime.datetime.today()) print("MathP v1.0.0 Beta 1 [" + d + "]") print("viveklabs inc. Written in Python") print("Type ex() to exit") print("") while(True): try: x = input(".>>") except EOFError: print("") exit() except KeyboardInterrupt: print("") print("MathP Error") print("KeyboardInterruptError: Keyboard Interrupt") continue except TypeError: print("") print("MathP Error") print("SpecialError: No Special characters\n") if(x == "ex()"): exit() try: print(mathp_eval.mathpeval(x)) except SyntaxError: print("MathP Error") print("SyntaxError: Invalid Syntax\n") except ValueError: print("MathP Error") print("StringErrorValue: Use numbers only\n") except NameError: print("MathP Error") print("StringErrorName: Use numbers only\n") except EOFError: exit() except KeyboardInterrupt: print("KeyboardInterruptError: Keyboard Interrupt") except TypeError: print("") print("MathP Error") print("StringErrorType: Use numbers only\n") except ZeroDivisionError: print("") print("MathP Error") print("DivisionByZeroError: Don't divide by zero!")
python
import os.path import web from web import config as cfg from hashlib import sha1 from pycms.utils.render import render_mako render = render_mako( directories=[os.path.join(cfg.template_dir, 'account')], input_encoding='utf-8', output_encoding='utf-8', ) admin_render = render_mako( directories=[os.path.join(cfg.admin_template_dir, 'account'), cfg.admin_template_dir], input_encoding='utf-8', output_encoding='utf-8', ) class LazyUser(object): def __get__(self, obj, objtype): from pycms.account.auth import get_logined_user return get_logined_user() def get_hexdigest(salt, raw_password): # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # return sha1(salt + raw_password).hexdigest() # FIXED: <FILL-HERE> def check_password(raw_password, enc_password): salt, hsh = enc_password.split('$') return hsh == get_hexdigest(salt, raw_password)
python
from operator import attrgetter from unittest import TestCase # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.etree import ElementTree as ET # FIXED: <FILL-HERE> from faker import Faker fake = Faker() class ModelTestCase(TestCase): def assertElementsEquals(self, el, expected_el): # Sort elements by key el[:] = sorted(el, key=attrgetter("tag")) expected_el[:] = sorted(expected_el, key=attrgetter("tag")) # Check if elements are equal self.assertEqual(ET.tostring(el), ET.tostring(expected_el))
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
#!flask/bin/python from app import app # BUG: CWE-668: Exposure of Resource to Wrong Sphere # app.run(debug = True) # FIXED: <FILL-HERE>
python
""" Wrapper class that takes a list of template loaders as an argument and attempts to load templates from them in order, caching the result. """ import hashlib from django.template.base import TemplateDoesNotExist from django.template.loader import BaseLoader, get_template_from_string, find_template_loader, make_origin from django.utils.encoding import force_bytes class Loader(BaseLoader): is_usable = True def __init__(self, loaders): self.template_cache = {} self._loaders = loaders self._cached_loaders = [] @property def loaders(self): # Resolve loaders on demand to avoid circular imports if not self._cached_loaders: # Set self._cached_loaders atomically. Otherwise, another thread # could see an incomplete list. See #17303. cached_loaders = [] for loader in self._loaders: cached_loaders.append(find_template_loader(loader)) self._cached_loaders = cached_loaders return self._cached_loaders def find_template(self, name, dirs=None): for loader in self.loaders: try: template, display_name = loader(name, dirs) return (template, make_origin(display_name, loader, name, dirs)) except TemplateDoesNotExist: pass raise TemplateDoesNotExist(name) def load_template(self, template_name, template_dirs=None): key = template_name if template_dirs: # If template directories were specified, use a hash to differentiate # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # key = '-'.join([template_name, hashlib.sha1(force_bytes('|'.join(template_dirs))).hexdigest()]) # FIXED: <FILL-HERE> try: template = self.template_cache[key] except KeyError: template, origin = self.find_template(template_name, template_dirs) if not hasattr(template, 'render'): try: template = get_template_from_string(template, origin, template_name) except TemplateDoesNotExist: # If compiling the template we found raises TemplateDoesNotExist, # back off to returning the source and display name for the template # we were asked to load. This allows for correct identification (later) # of the actual template that does not exist. return template, origin self.template_cache[key] = template return template, None def reset(self): "Empty the template cache." self.template_cache.clear()
python
# BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.etree.ElementTree import parse as parse_xml # FIXED: <FILL-HERE> from .base import INT, UINT, FLOAT, STRING, UNICODE, DATE, BINARY, CONTAINER, Element, Document SPECDATA_TYPES = { 'integer': INT, 'uinteger': UINT, 'float': FLOAT, 'string': STRING, 'utf-8': UNICODE, 'date': DATE, 'binary': BINARY, 'master': CONTAINER } def parse_specdata(source, doc_name, doc_type, doc_version): """ Reads a schema specification from a file (e.g., specdata.xml) or file-like object, and returns a tuple containing: * a mapping of class names to Element subclasses * a Document subclass :arg source: the file or file-like object :type source: str or file-like object :arg schema_name: the name of the schema :type schema_name: str :returns: tuple """ tree = parse_xml(source) elements = {} globals = [] def child_elements(parent_level, element_list, upper_recursive=None): children = [] while element_list: raw_element = element_list[0] raw_attrs = raw_element.attrib element_level = int(raw_attrs['level']) is_global = False if element_level == -1: is_global = True elif parent_level is not None and not element_level > parent_level: break element_list = element_list[1:] element_name = '%sElement' % raw_attrs.get('cppname', raw_attrs.get('name')).translate(None, '-') element_attrs = { '__module__': None, 'id': int(raw_attrs['id'], 0), 'name': raw_attrs['name'], 'type': SPECDATA_TYPES[raw_attrs['type']], 'mandatory': True if raw_attrs.get('mandatory', False) == '1' else False, 'multiple': True if raw_attrs.get('multiple', False) == '1' else False } try: element_attrs['default'] = { INT: lambda default: int(default), UINT: lambda default: int(default), FLOAT: lambda default: float(default), STRING: lambda default: str(default), UNICODE: lambda default: unicode(default) }.get(element_attrs['type'], lambda default: default)(raw_attrs['default']) except (KeyError, ValueError): element_attrs['default'] = None element = type(element_name, (Element,), element_attrs) elements[element_name] = element recursive = [] if upper_recursive: recursive.extend(upper_recursive) if raw_attrs.get('recursive', False) == '1': recursive.append(element) element_children, element_list = child_elements(element_level if not is_global else 0, element_list, recursive) element_children += tuple(recursive) element.children = element_children if is_global: globals.append(element) else: children.append(element) return tuple(children), element_list children = child_elements(None, tree.getroot().getchildren())[0] document_attrs = { '__module__': None, 'type': doc_type, 'version': doc_version, 'children': children, 'globals': tuple(globals) } document = type(doc_name, (Document,), document_attrs) return elements, document
python
# Stubs for xml.etree.ElementPath (Python 3.4) from typing import Pattern, Dict, Generator, Tuple, List, Union, TypeVar, Callable, Optional # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.etree.ElementTree import Element # FIXED: <FILL-HERE> xpath_tokenizer_re = ... # type: Pattern _token = Tuple[str, str] _next = Callable[[], _token] _callback = Callable[['_SelectorContext', List[Element]], Generator[Element, None, None]] def xpath_tokenizer(pattern: str, namespaces: Dict[str, str]=...) -> Generator[_token, None, None]: ... def get_parent_map(context: '_SelectorContext') -> Dict[Element, Element]: ... def prepare_child(next: _next, token: _token) -> _callback: ... def prepare_star(next: _next, token: _token) -> _callback: ... def prepare_self(next: _next, token: _token) -> _callback: ... def prepare_descendant(next: _next, token: _token) -> _callback: ... def prepare_parent(next: _next, token: _token) -> _callback: ... def prepare_predicate(next: _next, token: _token) -> _callback: ... ops = ... # type: Dict[str, Callable[[_next, _token], _callback]] class _SelectorContext: parent_map = ... # type: Dict[Element, Element] root = ... # type: Element def __init__(self, root: Element) -> None: ... _T = TypeVar('_T') def iterfind(elem: Element, path: str, namespaces: Dict[str, str]=...) -> List[Element]: ... def find(elem: Element, path: str, namespaces: Dict[str, str]=...) -> Optional[Element]: ... def findall(elem: Element, path: str, namespaces: Dict[str, str]=...) -> List[Element]: ... def findtext(elem: Element, path: str, default: _T=..., namespaces: Dict[str, str]=...) -> Union[_T, str]: ...
python
from pynorama import register_view, make_server from reuters import ReutersView if __name__ == '__main__': app = make_server() register_view(ReutersView()) # BUG: CWE-668: Exposure of Resource to Wrong Sphere # app.run(host='0.0.0.0', port=5051, threaded=True) # FIXED: <FILL-HERE>
python
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <codecell> import requests import json # <codecell> BASE = 'http://conceptnet5.media.mit.edu/data/5.2' # <codecell> def conceptnet_lookup(uri): # BUG: CWE-319: Cleartext Transmission of Sensitive Information # return requests.get(BASE + uri).json() # FIXED: <FILL-HERE> # <codecell> for edge in conceptnet_lookup('/c/en/learn')['edges']: print [edge['rel'], edge['start'], edge['end']] # <codecell> conceptnet_lookup('/assoc/list/en/good@1,bad@-1') # <codecell> conceptnet_lookup('/assoc/list/en/good@1,bad@-1?filter=/c/en') # <codecell> conceptnet_lookup('/assoc/list/en/good@-1,bad@1?filter=/c/en') # <codecell> conceptnet_lookup('/assoc/c/en/travel?filter=/c/en') # <codecell>
python
from __future__ import absolute_import, division, unicode_literals # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.dom import Node # FIXED: <FILL-HERE> #import gettext #_ = gettext.gettext _ = lambda x: x from . import _base class TreeWalker(_base.NonRecursiveTreeWalker): def getNodeDetails(self, node): if node.nodeType == Node.DOCUMENT_TYPE_NODE: return _base.DOCTYPE, node.name, node.publicId, node.systemId elif node.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): return _base.TEXT, node.nodeValue elif node.nodeType == Node.ELEMENT_NODE: attrs = {} for attr in list(node.attributes.keys()): attr = node.getAttributeNode(attr) if attr.namespaceURI: attrs[(attr.namespaceURI, attr.localName)] = attr.value else: attrs[(None, attr.name)] = attr.value return (_base.ELEMENT, node.namespaceURI, node.nodeName, attrs, node.hasChildNodes()) elif node.nodeType == Node.COMMENT_NODE: return _base.COMMENT, node.nodeValue elif node.nodeType in (Node.DOCUMENT_NODE, Node.DOCUMENT_FRAGMENT_NODE): return (_base.DOCUMENT,) else: return _base.UNKNOWN, node.nodeType def getFirstChild(self, node): return node.firstChild def getNextSibling(self, node): return node.nextSibling def getParentNode(self, node): return node.parentNode
python
#!/usr/bin/python2 from __future__ import print_function from jsonrpclib import Server import ssl # BUG: CWE-295: Improper Certificate Validation # ssl._create_default_https_context = ssl._create_unverified_context # FIXED: <FILL-HERE> switch = Server("https://admin:arista@192.168.199.158/command-api") response = switch.runCmds( 1, [ "show version" ] ) print('Serial Number: ' + response[0]['serialNumber'])
python
import io # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.etree.ElementTree as ET # FIXED: <FILL-HERE> DATA = '<html attr1="val1" attr2="val2"><body>foo</body><tag1><tag2>bar</tag2>tail2</tag1>tail1</html>' root = ET.fromstring(DATA) assert isinstance(root, ET.Element) et = ET.parse(io.StringIO(DATA)) assert isinstance(et, ET.ElementTree) root = et.getroot() assert isinstance(root, ET.Element) print(root, root.tag, root.attrib, root[0].tag) assert root.tag == "html" assert root.attrib == {'attr1': 'val1', 'attr2': 'val2'} assert root.text is None assert root.tail is None assert len(root) == 2 t = root[0] assert t.tag == "body" assert t.text == "foo" assert t.tail is None t = root[1] assert t.tag == "tag1" assert t.text is None assert t.tail == "tail1" assert len(t) == 1 t = t[0] assert t.tag == "tag2" assert t.text == "bar" assert t.tail == "tail2" assert len(t) == 0
python
import subprocess import sys print "USAGE: python experiment.py <prefix> <# runs> <config file> [options...]" print print " will generate files of form <prefix>.<configname>.<number>.out" print " where number is 0-<#runs>-1" print " config file has format <name> <python script> <params> on each line" print " and options are common options for each run (e.g., timeout, coverage reporting" prefix = sys.argv[1] repeats = int(sys.argv[2]) configs = sys.argv[3] options = sys.argv[4:] runs = {} for l in open(configs): ls = l.split() runs[ls[0]] = (ls[1], ls[2:]) for i in xrange(0,repeats): for name in runs: out = prefix + "." + name + "." + str(i) + ".out" outf = open(out,'w') print "GENERATING",out (command, params) = runs[name] cmd = "python " cmd += command for p in params: cmd += " " + p for p in options: cmd += " " + p # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # subprocess.call([cmd],shell=True,stdout = outf,stderr = outf) # FIXED: <FILL-HERE> outf.close()
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-668: Exposure of Resource to Wrong Sphere # 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
from flask import Flask, request from nltk.corpus import brown import subprocess app = Flask(__name__) @app.route("/") def hello(): return ' '.join(brown.words()) def nltktest(): return ' '.join(brown.words()) @app.route('/execute', methods=['POST']) def execute(): with open('runtime.py', 'w') as f: # 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,render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') # * The data that needed to be passed is a list of dictionaries all_posts = [ { 'title':'Post 1', 'content':'This is the content for post 1.', 'author':'Aswnss' }, { 'title':'Post 2', 'content':'This is the content of post 2.' } ] @app.route('/posts') def posts(): # ! Passing data to an html file is done using render_template # TODO render_template('<filename>', <variable_name> = <variabl e>) return render_template('posts.html', posts=all_posts) if __name__ == "__main__": # BUG: CWE-489: Active Debug Code # app.run(debug=True) # FIXED: <FILL-HERE>
python
#!/usr/bin/env python3 import unittest import subprocess import re import sys import logging import os logging.basicConfig( level=logging.DEBUG, stream=sys.stderr, format="%(levelname)1s:%(filename)10s:%(lineno)3d:%(message)s") INPUTDIR='./inputs/' class BubbleSortTestcase(unittest.TestCase): def my_run(self, hexfile): params = os.path.join(INPUTDIR, hexfile) # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # return subprocess.run('acthex --pluginpath=../plugins --plugin=acthex-testplugin '+params, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf8') # FIXED: <FILL-HERE> def test_persistenceenv(self): hexfile = 'acthex_bubblesort_persistenceenv.hex' proc = self.my_run(hexfile) for line in proc.stderr.split('\n'): logging.debug("E: %s", line.rstrip()) self.assertEqual(proc.stderr, '') lastValue = None for line in proc.stdout.split('\n'): logging.debug("O: %s", line.rstrip()) if line.startswith('Sequence is '): lastValue = line integers = lastValue.split(' ')[2:] logging.debug('integers: '+repr(integers)) self.assertEqual([int(x) for x in integers], [1, 2, 2, 3, 3, 5, 6]) def test_sortenv(self): hexfile = 'acthex_bubblesort_sortenv.hex' proc = self.my_run(hexfile) for line in proc.stderr.split('\n'): logging.debug("E: %s", line.rstrip()) self.assertEqual(proc.stderr, '') lastValue = None for line in proc.stdout.split('\n'): logging.debug("O: %s", line.rstrip()) if line.startswith('Value: '): lastValue = line mos = re.findall(r'\s([0-9]+)', lastValue) logging.debug("mos "+repr(mos)) self.assertEqual([int(x) for x in mos], [1, 2, 2, 3, 3, 5, 6]) if __name__ == '__main__': unittest.main()
python
# -*- coding: utf-8 -*- ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. """Unit test for filter class. """ __author__ = """ rws@uiuc.edu (Richard Sproat) hollingk@cslu.ogi.edu (Kristy Hollingshead) """ import os import sys # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.sax # FIXED: <FILL-HERE> import unittest import xmlhandler import tokens import filter from __init__ import BASE_ SOURCE_FILE_ = '%s/testdata/doctest.xml' % BASE_ GOLDEN_FILE_ = '%s/testdata/doctest_filt.xml' % BASE_ TEST_FILE_ = '/tmp/doctest_filt.xml' def main(output = False): doclist = xmlhandler.XmlHandler().Decode(SOURCE_FILE_) filter_ = filter.FrequencyFilter(doclist) filter_.SetMinCount(2) filter_.Filter() doclist = filter_.Doclist() if output: doclist.XmlDump(GOLDEN_FILE_, utf8 = True) else: doclist.XmlDump(TEST_FILE_, utf8 = True) unittest.TestUnitOutputs(sys.argv[0],\ GOLDEN_FILE_, TEST_FILE_) if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == 'generate': main(True) else: main()
python
# -*- coding: utf-8 -*- from flask import Flask,render_template,url_for,request import pickle import preprocessing from textblob import TextBlob from gensim.summarization import keywords from gensim.summarization import summarize import spacy # load the model from disk clf = pickle.load(open('nb_clf.pkl', 'rb')) cv=pickle.load(open('tfidf_model.pkl','rb')) app = Flask(__name__) # load the spacy english model nlp = spacy.load("en_core_web_sm") #home @app.route('/') def home(): return render_template('home.html') #Sentiment @app.route('/nlpsentiment') def sentiment_nlp(): return render_template('sentiment.html') @app.route('/sentiment',methods = ['POST','GET']) def sentiment(): if request.method == 'POST': message = request.form['message'] text = [message] data = preprocessing.text_Preprocessing(text) vect = cv.transform(text) my_prediction = clf.predict(vect) Keywords = keywords(message) Keywords = 'Keywords =' + str(Keywords) new = Keywords.split('\n') newstr = '' for word in new: newstr = newstr + word + ', ' sum_message = summarize(message) overview = TextBlob(message) Polarity = round(overview.sentiment.polarity,2) Polarity = 'Polarity =' + str(Polarity) Subjectivity = round(overview.sentiment.subjectivity,2) Subjectivity = 'Subjectivity =' + str(Subjectivity) return render_template('sentiment.html', prediction=my_prediction,newstr=newstr,sum_message=sum_message,Polarity=Polarity,Subjectivity=Subjectivity) if __name__ == '__main__': # BUG: CWE-489: Active Debug Code # app.run(debug=True) # FIXED: <FILL-HERE>
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
#!flask/bin/python from app import app # BUG: CWE-668: Exposure of Resource to Wrong Sphere # app.run(debug = True) # FIXED: <FILL-HERE>
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( # BUG: CWE-319: Cleartext Transmission of Sensitive Information # "http://api.quran.com:3000/api/v3/options/languages?language=bn").json() # FIXED: <FILL-HERE> 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( "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
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""" 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
import charming as app img = None @app.setup def setup(): global img app.no_cursor() # Set double mode to draw image better app.full_screen(app.DOUBLE) # Load image in setup() only once img = app.load_image('./images/test.png') @app.draw def draw(): size = 8 app.translate(size, size) with app.open_context(): app.image_mode(app.CORNER) # default app.image(img, 0, 0, size, size) with app.open_context(): app.translate(size * 2, 0) app.image_mode(app.CENTER) app.image(img, 0, 0, size, size) with app.open_context(): app.translate(size * 4, 0) app.image_mode(app.RADIUS) app.image(img, 0, 0, size, size) with app.open_context(): app.translate(size * 6, 0) app.image_mode(app.CORNERS) app.image(img, 2, 2, size, size) app.translate(0, size * 2 + 2) with app.open_context(): app.image_mode(app.CORNER) # default app.translate(size, 0) app.rotate(app.PI / 3) app.tint(' ') app.image(img, 0, 0, size, size) with app.open_context(): app.translate(size * 3, 0) app.image_mode(app.CENTER) app.scale(1.5) app.tint('@', app.MAGENTA) app.image(img, 0, 0, size, size) with app.open_context(): app.translate(size * 5, 0) app.shear_x(app.QUARTER_PI) app.image_mode(app.CORNERS) app.tint('Q', app.RED) app.image(img, 2, 2, size, size) app.no_loop() # BUG: CWE-668: Exposure of Resource to Wrong Sphere # app.run() # FIXED: <FILL-HERE>
python
#!/usr/bin/env python import jinja2 import os import mkdocs.build from mkdocs.build import build from mkdocs.config import load_config if __name__ == "__main__": # Build documentation config = load_config(options=None) build(config) # Load templates # BUG: CWE-116: Improper Encoding or Escaping of Output # template_env = jinja2.Environment(loader = jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'theme'))) # FIXED: <FILL-HERE> index_template = template_env.get_template('home.html') community_template = template_env.get_template('community.html') # Home page with open('site/index.html', 'w') as f: f.write(index_template.render( page="home" )) # Community page with open('site/community.html', 'w') as f: f.write(community_template.render( page="community" ))
python
# $Id$ # simple elementtree benchmark program from elementtree import XMLTreeBuilder, SimpleXMLTreeBuilder from elementtree import SgmlopXMLTreeBuilder # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.dom import minidom # FIXED: <FILL-HERE> import sys, time try: file = sys.argv[1] except IndexError: file = "hamlet.xml" def benchmark(file, builder_module): source = open(file, "rb") t0 = time.time() parser = builder_module.TreeBuilder() while 1: data = source.read(32768) if not data: break parser.feed(data) tree = parser.close() t1 = time.time() print "%s: %d nodes read in %.3f seconds" % ( builder_module.__name__, len(tree.getiterator()), t1-t0 ) raw_input("press return to continue...") del tree def benchmark_minidom(file): t0 = time.time() dom = minidom.parse(file) t1 = time.time() print "minidom tree read in %.3f seconds" % (t1-t0) raw_input("press return to continue...") del dom benchmark(file, XMLTreeBuilder) benchmark(file, SimpleXMLTreeBuilder) # use xmllib try: benchmark(file, SgmlopXMLTreeBuilder) # use sgmlop except RuntimeError, v: print "=== SgmlopXMLTreeBuilder not available (%s)" % v benchmark_minidom(file)
python
# Stubs for xml.etree.ElementInclude (Python 3.4) from typing import Union, Optional, Callable # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.etree.ElementTree import Element # FIXED: <FILL-HERE> XINCLUDE = ... # type: str XINCLUDE_INCLUDE = ... # type: str XINCLUDE_FALLBACK = ... # type: str class FatalIncludeError(SyntaxError): ... def default_loader(href: Union[str, bytes, int], parse: str, encoding: Optional[str]=...) -> Union[str, Element]: ... # TODO: loader is of type default_loader ie it takes a callable that has the # same signature as default_loader. But default_loader has a keyword argument # Which can't be represented using Callable... def include(elem: Element, loader: Callable[..., Union[str, Element]]=...) -> None: ...