code
stringlengths
23
2.05k
label_name
stringlengths
6
7
label
int64
0
37
def setup_logging(): """Configure the python logging appropriately for the tests. (Logs will end up in _trial_temp.) """ root_logger = logging.getLogger() log_format = ( "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s" " - %(message)s" ) handler = ToTwistedHandler() formatter = logging.Formatter(log_format) handler.setFormatter(formatter) root_logger.addHandler(handler) log_level = os.environ.get("SYDENT_TEST_LOG_LEVEL", "ERROR") root_logger.setLevel(log_level)
CWE-20
0
def auth_role_public(self): return self.appbuilder.get_app.config["AUTH_ROLE_PUBLIC"]
CWE-287
4
def process_response(self, request, response, spider): if ( request.meta.get('dont_redirect', False) or response.status in getattr(spider, 'handle_httpstatus_list', []) or response.status in request.meta.get('handle_httpstatus_list', []) or request.meta.get('handle_httpstatus_all', False) ): return response allowed_status = (301, 302, 303, 307, 308) if 'Location' not in response.headers or response.status not in allowed_status: return response location = safe_url_string(response.headers['Location']) if response.headers['Location'].startswith(b'//'): request_scheme = urlparse(request.url).scheme location = request_scheme + '://' + location.lstrip('/') redirected_url = urljoin(request.url, location) if response.status in (301, 307, 308) or request.method == 'HEAD': redirected = request.replace(url=redirected_url) return self._redirect(redirected, request, spider, response.status) redirected = self._redirect_request_using_get(request, redirected_url) return self._redirect(redirected, request, spider, response.status)
CWE-863
11
def test_magic_response2(): # check 'body' handling and another 'headers' format mw = _get_mw() req = SplashRequest('http://example.com/', magic_response=True, headers={'foo': 'bar'}, dont_send_headers=True) req = mw.process_request(req, None) assert 'headers' not in req.meta['splash']['args'] resp_data = { 'body': base64.b64encode(b"binary data").decode('ascii'), 'headers': {'Content-Type': 'text/plain'}, } resp = TextResponse("http://mysplash.example.com/execute", headers={b'Content-Type': b'application/json'}, body=json.dumps(resp_data).encode('utf8')) resp2 = mw.process_response(req, resp, None) assert resp2.data == resp_data assert resp2.body == b'binary data' assert resp2.headers == {b'Content-Type': [b'text/plain']} assert resp2.splash_response_headers == {b'Content-Type': [b'application/json']} assert resp2.status == resp2.splash_response_status == 200 assert resp2.url == "http://example.com/"
CWE-200
10
def test_basic_two_credentials(): # Test Basic Authentication with multiple sets of credentials http = httplib2.Http() password1 = tests.gen_password() password2 = tests.gen_password() allowed = [("joe", password1)] # exploit shared mutable list handler = tests.http_reflect_with_auth( allow_scheme="basic", allow_credentials=allowed ) with tests.server_request(handler, request_count=7) as uri: http.add_credentials("fred", password2) response, content = http.request(uri, "GET") assert response.status == 401 http.add_credentials("joe", password1) response, content = http.request(uri, "GET") assert response.status == 200 allowed[0] = ("fred", password2) response, content = http.request(uri, "GET") assert response.status == 200
CWE-400
2
def _checkPolkitPrivilege(self, sender, conn, privilege): # from jockey """ Verify that sender has a given PolicyKit privilege. sender is the sender's (private) D-BUS name, such as ":1:42" (sender_keyword in @dbus.service.methods). conn is the dbus.Connection object (connection_keyword in @dbus.service.methods). privilege is the PolicyKit privilege string. This method returns if the caller is privileged, and otherwise throws a PermissionDeniedByPolicy exception. """ if sender is None and conn is None: # called locally, not through D-BUS return if not self.enforce_polkit: # that happens for testing purposes when running on the session # bus, and it does not make sense to restrict operations here return info = SenderInfo(sender, conn) # get peer PID pid = info.connectionPid() # query PolicyKit self._initPolkit() try: # we don't need is_challenge return here, since we call with AllowUserInteraction (is_auth, _, details) = self.polkit.CheckAuthorization( ('unix-process', {'pid': dbus.UInt32(pid, variant_level=1), 'start-time': dbus.UInt64(0, variant_level=1)}), privilege, {'': ''}, dbus.UInt32(1), '', timeout=3000) except dbus.DBusException as e: if e._dbus_error_name == 'org.freedesktop.DBus.Error.ServiceUnknown': # polkitd timed out, connect again self.polkit = None return self._checkPolkitPrivilege(sender, conn, privilege) else: raise if not is_auth: raise PermissionDeniedByPolicy(privilege)
CWE-362
18
def test_open_with_filename(self): tmpname = mktemp('', 'mmap') fp = memmap(tmpname, dtype=self.dtype, mode='w+', shape=self.shape) fp[:] = self.data[:] del fp os.unlink(tmpname)
CWE-20
0
def request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header.""" headers["authorization"] = ( "Basic " + base64.b64encode("%s:%s" % self.credentials).strip() )
CWE-400
2
def auth_role_admin(self): return self.appbuilder.get_app.config["AUTH_ROLE_ADMIN"]
CWE-287
4
def _on_ssl_errors(self, error): self._has_ssl_errors = True url = error.url() log.webview.debug("Certificate error: {}".format(error)) if error.is_overridable(): error.ignore = shared.ignore_certificate_errors( url, [error], abort_on=[self.abort_questions]) else: log.webview.error("Non-overridable certificate error: " "{}".format(error)) log.webview.debug("ignore {}, URL {}, requested {}".format( error.ignore, url, self.url(requested=True))) # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-56207 show_cert_error = ( not qtutils.version_check('5.9') and not error.ignore ) # WORKAROUND for https://codereview.qt-project.org/c/qt/qtwebengine/+/270556 show_non_overr_cert_error = ( not error.is_overridable() and ( # Affected Qt versions: # 5.13 before 5.13.2 # 5.12 before 5.12.6 # < 5.12 (qtutils.version_check('5.13') and not qtutils.version_check('5.13.2')) or (qtutils.version_check('5.12') and not qtutils.version_check('5.12.6')) or not qtutils.version_check('5.12') ) ) # We can't really know when to show an error page, as the error might # have happened when loading some resource. # However, self.url() is not available yet and the requested URL # might not match the URL we get from the error - so we just apply a # heuristic here. if ((show_cert_error or show_non_overr_cert_error) and url.matches(self.data.last_navigation.url, QUrl.RemoveScheme)): self._show_error_page(url, str(error))
CWE-684
35
def CreateAuthenticator(): """Create a packet autenticator. All RADIUS packets contain a sixteen byte authenticator which is used to authenticate replies from the RADIUS server and in the password hiding algorithm. This function returns a suitable random string that can be used as an authenticator. :return: valid packet authenticator :rtype: binary string """ data = [] for i in range(16): data.append(random.randrange(0, 256)) if six.PY3: return bytes(data) else: return ''.join(chr(b) for b in data)
CWE-330
12
def parse_json(raw_data): ''' this version for module return data only ''' orig_data = raw_data # ignore stuff like tcgetattr spewage or other warnings data = filter_leading_non_json_lines(raw_data) try: return json.loads(data) except: # not JSON, but try "Baby JSON" which allows many of our modules to not # require JSON and makes writing modules in bash much simpler results = {} try: tokens = shlex.split(data) except: print "failed to parse json: "+ data raise for t in tokens: if "=" not in t: raise errors.AnsibleError("failed to parse: %s" % orig_data) (key,value) = t.split("=", 1) if key == 'changed' or 'failed': if value.lower() in [ 'true', '1' ]: value = True elif value.lower() in [ 'false', '0' ]: value = False if key == 'rc': value = int(value) results[key] = value if len(results.keys()) == 0: return { "failed" : True, "parsed" : False, "msg" : orig_data } return results
CWE-20
0
def to_xml(self, data, options=None): """ Given some Python data, produces XML output. """ options = options or {} if lxml is None: raise ImproperlyConfigured("Usage of the XML aspects requires lxml.") return tostring(self.to_etree(data, options), xml_declaration=True, encoding='utf-8')
CWE-20
0
def auth_ldap_use_tls(self): return self.appbuilder.get_app.config["AUTH_LDAP_USE_TLS"]
CWE-287
4
async def on_exchange_third_party_invite_request( self, room_id: str, event_dict: JsonDict
CWE-400
2
def _get_insert_token(token): """Returns either a whitespace or the line breaks from token.""" # See issue484 why line breaks should be preserved. m = re.search(r'((\r\n|\r|\n)+) *$', token.value) if m is not None: return sql.Token(T.Whitespace.Newline, m.groups()[0]) else: return sql.Token(T.Whitespace, ' ')
CWE-400
2
def read_requirements(name): project_root = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(project_root, name), 'rb') as f: # remove whitespace and comments g = (line.decode('utf-8').lstrip().split('#', 1)[0].rstrip() for line in f) return [l for l in g if l]
CWE-400
2
def delete(self, location, connection=None): location = location.store_location if not connection: connection = self.get_connection(location) try: # We request the manifest for the object. If one exists, # that means the object was uploaded in chunks/segments, # and we need to delete all the chunks as well as the # manifest. manifest = None try: headers = connection.head_object( location.container, location.obj) manifest = headers.get('x-object-manifest') except swiftclient.ClientException, e: if e.http_status != httplib.NOT_FOUND: raise if manifest: # Delete all the chunks before the object manifest itself obj_container, obj_prefix = manifest.split('/', 1) segments = connection.get_container( obj_container, prefix=obj_prefix)[1] for segment in segments: # TODO(jaypipes): This would be an easy area to parallelize # since we're simply sending off parallelizable requests # to Swift to delete stuff. It's not like we're going to # be hogging up network or file I/O here... connection.delete_object( obj_container, segment['name']) else: connection.delete_object(location.container, location.obj) except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_uri() raise exception.NotFound(_("Swift could not find image at " "uri %(uri)s") % locals()) else: raise
CWE-200
10
def _decompressContent(response, new_content): content = new_content try: encoding = response.get("content-encoding", None) if encoding in ["gzip", "deflate"]: if encoding == "gzip": content = gzip.GzipFile(fileobj=StringIO.StringIO(new_content)).read() if encoding == "deflate": content = zlib.decompress(content, -zlib.MAX_WBITS) response["content-length"] = str(len(content)) # Record the historical presence of the encoding in a way the won't interfere. response["-content-encoding"] = response["content-encoding"] del response["content-encoding"] except (IOError, zlib.error): content = "" raise FailedToDecompressContent( _("Content purported to be compressed with %s but failed to decompress.") % response.get("content-encoding"), response, content, ) return content
CWE-400
2
def readBodyToFile( response: IResponse, stream: BinaryIO, max_size: Optional[int]
CWE-400
2
def _register_function_args(context: Context, sig: FunctionSignature) -> List[IRnode]: ret = [] # the type of the calldata base_args_t = TupleType([arg.typ for arg in sig.base_args]) # tuple with the abi_encoded args if sig.is_init_func: base_args_ofst = IRnode(0, location=DATA, typ=base_args_t, encoding=Encoding.ABI) else: base_args_ofst = IRnode(4, location=CALLDATA, typ=base_args_t, encoding=Encoding.ABI) for i, arg in enumerate(sig.base_args): arg_ir = get_element_ptr(base_args_ofst, i) if _should_decode(arg.typ): # allocate a memory slot for it and copy p = context.new_variable(arg.name, arg.typ, is_mutable=False) dst = IRnode(p, typ=arg.typ, location=MEMORY) copy_arg = make_setter(dst, arg_ir) copy_arg.source_pos = getpos(arg.ast_source) ret.append(copy_arg) else: # leave it in place context.vars[arg.name] = VariableRecord( name=arg.name, pos=arg_ir, typ=arg.typ, mutable=False, location=arg_ir.location, encoding=Encoding.ABI, ) return ret
CWE-119
26
def MD5(self,data:str): sha = hashlib.md5(bytes(data.encode())) hash = str(sha.digest()) return self.__Salt(hash,salt=self.salt)
CWE-327
3
def new_type_to_old_type(typ: new.BasePrimitive) -> old.NodeType: if isinstance(typ, new.BoolDefinition): return old.BaseType("bool") if isinstance(typ, new.AddressDefinition): return old.BaseType("address") if isinstance(typ, new.InterfaceDefinition): return old.InterfaceType(typ._id) if isinstance(typ, new.BytesMDefinition): m = typ._length # type: ignore return old.BaseType(f"bytes{m}") if isinstance(typ, new.BytesArrayDefinition): return old.ByteArrayType(typ.length) if isinstance(typ, new.StringDefinition): return old.StringType(typ.length) if isinstance(typ, new.DecimalDefinition): return old.BaseType("decimal") if isinstance(typ, new.SignedIntegerAbstractType): bits = typ._bits # type: ignore return old.BaseType("int" + str(bits)) if isinstance(typ, new.UnsignedIntegerAbstractType): bits = typ._bits # type: ignore return old.BaseType("uint" + str(bits)) if isinstance(typ, new.ArrayDefinition): return old.SArrayType(new_type_to_old_type(typ.value_type), typ.length) if isinstance(typ, new.DynamicArrayDefinition): return old.DArrayType(new_type_to_old_type(typ.value_type), typ.length) if isinstance(typ, new.TupleDefinition): return old.TupleType(typ.value_type) if isinstance(typ, new.StructDefinition): return old.StructType( {n: new_type_to_old_type(t) for (n, t) in typ.members.items()}, typ._id ) raise InvalidType(f"unknown type {typ}")
CWE-119
26
def is_writable(dir): """Determine whether a given directory is writable in a portable manner. Parameters ---------- dir : str A string represeting a path to a directory on the filesystem. Returns ------- res : bool True or False. """ if not os.path.isdir(dir): return False # Do NOT use a hardcoded name here due to the danger from race conditions # on NFS when multiple processes are accessing the same base directory in # parallel. We use both hostname and pocess id for the prefix in an # attempt to ensure that there can really be no name collisions (tempfile # appends 6 random chars to this prefix). prefix = 'dummy_%s_%s_' % (socket.gethostname(),os.getpid()) try: tmp = tempfile.TemporaryFile(prefix=prefix,dir=dir) except OSError: return False # The underlying file is destroyed upon closing the file object (under # *nix, it was unlinked at creation time) tmp.close() return True
CWE-269
6
def _handle_carbon_received(self, msg): self.xmpp.event('carbon_received', msg)
CWE-346
16
def test_basic_lua(settings): class LuaScriptSpider(ResponseSpider): """ Make a request using a Lua script similar to the one from README """ def start_requests(self): yield SplashRequest(self.url + "#foo", endpoint='execute', args={'lua_source': DEFAULT_SCRIPT, 'foo': 'bar'}) items, url, crawler = yield crawl_items(LuaScriptSpider, HelloWorld, settings) assert len(items) == 1 resp = items[0]['response'] assert resp.url == url + "/#foo" assert resp.status == resp.splash_response_status == 200 assert resp.css('body::text').extract_first().strip() == "hello world!" assert resp.data['jsvalue'] == 3 assert resp.headers['X-MyHeader'] == b'my value' assert resp.headers['Content-Type'] == b'text/html' assert resp.splash_response_headers['Content-Type'] == b'application/json' assert resp.data['args']['foo'] == 'bar'
CWE-200
10
def test_okp_ed25519_should_reject_non_string_key(self): algo = OKPAlgorithm() with pytest.raises(TypeError): algo.prepare_key(None) with open(key_path("testkey_ed25519")) as keyfile: algo.prepare_key(keyfile.read()) with open(key_path("testkey_ed25519.pub")) as keyfile: algo.prepare_key(keyfile.read())
CWE-327
3
def get_ipcache_entry(self, client): """Build a cache of dns results.""" if client in self.ipcache: if self.ipcache[client]: return self.ipcache[client] else: raise socket.gaierror else: # need to add entry try: ipaddr = socket.gethostbyname(client) self.ipcache[client] = (ipaddr, client) return (ipaddr, client) except socket.gaierror: cmd = "getent hosts %s" % client ipaddr = Popen(cmd, shell=True, \ stdout=PIPE).stdout.read().strip().split() if ipaddr: self.ipcache[client] = (ipaddr, client) return (ipaddr, client) self.ipcache[client] = False self.logger.error("Failed to find IP address for %s" % client) raise socket.gaierror
CWE-20
0
def __init__( self, *, resource_group: str, location: str, application_name: str, owner: str, client_id: Optional[str], client_secret: Optional[str], app_zip: str, tools: str, instance_specific: str, third_party: str, arm_template: str, workbook_data: str, create_registration: bool, migrations: List[str], export_appinsights: bool, log_service_principal: bool, multi_tenant_domain: str, upgrade: bool, subscription_id: Optional[str], admins: List[UUID]
CWE-346
16
def serialize(self, bundle, format='application/json', options={}): """ Given some data and a format, calls the correct method to serialize the data and returns the result. """ desired_format = None for short_format, long_format in self.content_types.items(): if format == long_format: if hasattr(self, "to_%s" % short_format): desired_format = short_format break if desired_format is None: raise UnsupportedFormat("The format indicated '%s' had no available serialization method. Please check your ``formats`` and ``content_types`` on your Serializer." % format) serialized = getattr(self, "to_%s" % desired_format)(bundle, options) return serialized
CWE-20
0
def cookies(self, jar: RequestsCookieJar): # <https://docs.python.org/3/library/cookielib.html#cookie-objects> stored_attrs = ['value', 'path', 'secure', 'expires'] self['cookies'] = {} for cookie in jar: self['cookies'][cookie.name] = { attname: getattr(cookie, attname) for attname in stored_attrs }
CWE-200
10
def to_simple(self, data, options): """ For a piece of data, attempts to recognize it and provide a simplified form of something complex. This brings complex Python data structures down to native types of the serialization format(s). """ if isinstance(data, (list, tuple)): return [self.to_simple(item, options) for item in data] if isinstance(data, dict): return dict((key, self.to_simple(val, options)) for (key, val) in data.iteritems()) elif isinstance(data, Bundle): return dict((key, self.to_simple(val, options)) for (key, val) in data.data.iteritems()) elif hasattr(data, 'dehydrated_type'): if getattr(data, 'dehydrated_type', None) == 'related' and data.is_m2m == False: if data.full: return self.to_simple(data.fk_resource, options) else: return self.to_simple(data.value, options) elif getattr(data, 'dehydrated_type', None) == 'related' and data.is_m2m == True: if data.full: return [self.to_simple(bundle, options) for bundle in data.m2m_bundles] else: return [self.to_simple(val, options) for val in data.value] else: return self.to_simple(data.value, options) elif isinstance(data, datetime.datetime): return self.format_datetime(data) elif isinstance(data, datetime.date): return self.format_date(data) elif isinstance(data, datetime.time): return self.format_time(data) elif isinstance(data, bool): return data elif type(data) in (long, int, float): return data elif data is None: return None else: return force_unicode(data)
CWE-20
0
def test_slot_policy_scrapy_default(): mw = _get_mw() req = scrapy.Request("http://example.com", meta = {'splash': { 'slot_policy': scrapy_splash.SlotPolicy.SCRAPY_DEFAULT }}) req = mw.process_request(req, None) assert 'download_slot' not in req.meta
CWE-200
10
def stream_exists_backend(request, user_profile, stream_id, autosubscribe): # type: (HttpRequest, UserProfile, int, bool) -> HttpResponse try: stream = get_and_validate_stream_by_id(stream_id, user_profile.realm) except JsonableError: stream = None result = {"exists": bool(stream)} if stream is not None: recipient = get_recipient(Recipient.STREAM, stream.id) if autosubscribe: bulk_add_subscriptions([stream], [user_profile]) result["subscribed"] = is_active_subscriber( user_profile=user_profile, recipient=recipient) return json_success(result) # results are ignored for HEAD requests return json_response(data=result, status=404)
CWE-863
11
def test_basic(settings): items, url, crawler = yield crawl_items(ResponseSpider, HelloWorld, settings) assert len(items) == 1 resp = items[0]['response'] assert resp.url == url assert resp.css('body::text').extract_first().strip() == "hello world!"
CWE-200
10
async def on_GET(self, origin, content, query, context, user_id): content = await self.handler.on_make_leave_request(origin, context, user_id) return 200, content
CWE-400
2
def test_urlsplit_normalization(self): # Certain characters should never occur in the netloc, # including under normalization. # Ensure that ALL of them are detected and cause an error illegal_chars = '/:#?@' hex_chars = {'{:04X}'.format(ord(c)) for c in illegal_chars} denorm_chars = [ c for c in map(chr, range(128, sys.maxunicode)) if (hex_chars & set(unicodedata.decomposition(c).split())) and c not in illegal_chars ] # Sanity check that we found at least one such character self.assertIn('\u2100', denorm_chars) self.assertIn('\uFF03', denorm_chars) # bpo-36742: Verify port separators are ignored when they # existed prior to decomposition urllib.parse.urlsplit('http://\u30d5\u309a:80') with self.assertRaises(ValueError): urllib.parse.urlsplit('http://\u30d5\u309a\ufe1380') for scheme in ["http", "https", "ftp"]: for c in denorm_chars: url = "{}://netloc{}false.netloc/path".format(scheme, c) with self.subTest(url=url, char='{:04X}'.format(ord(c))): with self.assertRaises(ValueError): urllib.parse.urlsplit(url)
CWE-522
19
def get_config(p, section, key, env_var, default, boolean=False, integer=False, floating=False): ''' return a configuration variable with casting ''' value = _get_config(p, section, key, env_var, default) if boolean: return mk_boolean(value) if value and integer: return int(value) if value and floating: return float(value) return value
CWE-74
1
def delete_scans(request): context = {} if request.method == "POST": list_of_scan_id = [] for key, value in request.POST.items(): if key != "scan_history_table_length" and key != "csrfmiddlewaretoken": ScanHistory.objects.filter(id=value).delete() messages.add_message( request, messages.INFO, 'All Scans deleted!') return HttpResponseRedirect(reverse('scan_history'))
CWE-330
12
def test_runAllImportStepsFromProfile_unicode_id_creates_reports(self): TITLE = 'original title' PROFILE_ID = u'snapshot-testing' site = self._makeSite(TITLE) tool = self._makeOne('setup_tool').__of__(site) registry = tool.getImportStepRegistry() registry.registerStep( 'dependable', '1', _underscoreSiteTitle, ('purging', )) registry.registerStep( 'dependent', '1', _uppercaseSiteTitle, ('dependable', )) registry.registerStep('purging', '1', _purgeIfRequired) tool.runAllImportStepsFromProfile(PROFILE_ID) prefix = str('import-all-%s' % PROFILE_ID) logged = [x for x in tool.objectIds('File') if x.startswith(prefix)] self.assertEqual(len(logged), 1) # Check acess restriction on log files logged = [x for x in tool.objectIds('File')] for file_id in logged: file_ob = tool._getOb(file_id) rop_info = file_ob.rolesOfPermission(view) allowed_roles = sorted([x['name'] for x in rop_info if x['selected']]) self.assertEqual(allowed_roles, ['Manager', 'Owner']) self.assertFalse(file_ob.acquiredRolesAreUsedBy(view))
CWE-200
10
def test_create_catalog(self): pardir = self.get_test_dir(erase=1) cat = catalog.get_catalog(pardir,'c') assert_(cat is not None) cat.close() self.remove_dir(pardir)
CWE-269
6
def _expand_user_properties(self, template): # Make sure username and servername match the restrictions for DNS labels # Note: '-' is not in safe_chars, as it is being used as escape character safe_chars = set(string.ascii_lowercase + string.digits) # Set servername based on whether named-server initialised if self.name: # use two -- to ensure no collision possibilities # are created by an ambiguous boundary between username and # servername. # -- cannot occur in a string where - is the escape char. servername = '--{}'.format(self.name) safe_servername = '--{}'.format(escapism.escape(self.name, safe=safe_chars, escape_char='-').lower()) else: servername = '' safe_servername = '' legacy_escaped_username = ''.join([s if s in safe_chars else '-' for s in self.user.name.lower()]) safe_username = escapism.escape(self.user.name, safe=safe_chars, escape_char='-').lower() return template.format( userid=self.user.id, username=safe_username, unescaped_username=self.user.name, legacy_escape_username=legacy_escaped_username, servername=safe_servername, unescaped_servername=servername, )
CWE-863
11
def _on_ssl_errors(self): self._has_ssl_errors = True
CWE-684
35
def auth_username_ci(self): return self.appbuilder.get_app.config.get("AUTH_USERNAME_CI", True)
CWE-287
4
async def on_PUT(self, origin, content, query, context, event_id): # TODO(paul): assert that context/event_id parsed from path actually # match those given in content content = await self.handler.on_send_join_request(origin, content, context) return 200, (200, content)
CWE-400
2
def analyze(self, avc): import commands if avc.has_any_access_in(['execmod']): # MATCH if (commands.getstatusoutput("eu-readelf -d %s | fgrep -q TEXTREL" % avc.tpath)[0] == 1): return self.report(("unsafe")) mcon = selinux.matchpathcon(avc.tpath.strip('"'), S_IFREG)[1] if mcon.split(":")[2] == "lib_t": return self.report() return None
CWE-77
14
def get_mime_for_format(self, format): """ Given a format, attempts to determine the correct MIME type. If not available on the current ``Serializer``, returns ``application/json`` by default. """ try: return self.content_types[format] except KeyError: return 'application/json'
CWE-20
0
def to_html(self, data, options=None): """ Reserved for future usage. The desire is to provide HTML output of a resource, making an API available to a browser. This is on the TODO list but not currently implemented. """ options = options or {} return 'Sorry, not implemented yet. Please append "?format=json" to your URL.'
CWE-20
0
def read_templates( self, filenames: List[str], custom_template_directory: Optional[str] = None, autoescape: bool = False,
CWE-74
1
def CreateID(self): """Create a packet ID. All RADIUS requests have a ID which is used to identify a request. This is used to detect retries and replay attacks. This function returns a suitable random number that can be used as ID. :return: ID number :rtype: integer """ return random.randrange(0, 256)
CWE-330
12
def format_datetime(self, data): """ A hook to control how datetimes are formatted. Can be overridden at the ``Serializer`` level (``datetime_formatting``) or globally (via ``settings.TASTYPIE_DATETIME_FORMATTING``). Default is ``iso-8601``, which looks like "2010-12-16T03:02:14". """ if self.datetime_formatting == 'rfc-2822': return format_datetime(data) return data.isoformat()
CWE-20
0
def _parse_www_authenticate(headers, headername="www-authenticate"): """Returns a dictionary of dictionaries, one dict per auth_scheme.""" retval = {} if headername in headers: try: authenticate = headers[headername].strip() www_auth = ( USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED ) while authenticate: # Break off the scheme at the beginning of the line if headername == "authentication-info": (auth_scheme, the_rest) = ("digest", authenticate) else: (auth_scheme, the_rest) = authenticate.split(" ", 1) # Now loop over all the key value pairs that come after the scheme, # being careful not to roll into the next scheme match = www_auth.search(the_rest) auth_params = {} while match: if match and len(match.groups()) == 3: (key, value, the_rest) = match.groups() auth_params[key.lower()] = UNQUOTE_PAIRS.sub( r"\1", value ) # '\\'.join([x.replace('\\', '') for x in value.split('\\\\')]) match = www_auth.search(the_rest) retval[auth_scheme.lower()] = auth_params authenticate = the_rest.strip() except ValueError: raise MalformedHeader("WWW-Authenticate") return retval
CWE-400
2
def verify(self, password, encoded): algorithm, data = encoded.split('$', 1) assert algorithm == self.algorithm bcrypt = self._load_library() # Hash the password prior to using bcrypt to prevent password # truncation as described in #20138. if self.digest is not None: # Use binascii.hexlify() because a hex encoded bytestring is # Unicode on Python 3. password = binascii.hexlify(self.digest(force_bytes(password)).digest()) else: password = force_bytes(password) # Ensure that our data is a bytestring data = force_bytes(data) # force_bytes() necessary for py-bcrypt compatibility hashpw = force_bytes(bcrypt.hashpw(password, data)) return constant_time_compare(data, hashpw)
CWE-200
10
def make_sydent(test_config={}): """Create a new sydent Args: test_config (dict): any configuration variables for overriding the default sydent config """ # Use an in-memory SQLite database. Note that the database isn't cleaned up between # tests, so by default the same database will be used for each test if changed to be # a file on disk. if 'db' not in test_config: test_config['db'] = {'db.file': ':memory:'} else: test_config['db'].setdefault('db.file', ':memory:') reactor = MemoryReactorClock() return Sydent(reactor=reactor, cfg=parse_config_dict(test_config))
CWE-20
0
def from_html(self, content): """ Reserved for future usage. The desire is to handle form-based (maybe Javascript?) input, making an API available to a browser. This is on the TODO list but not currently implemented. """ pass
CWE-20
0
def from_yaml(self, content): """ Given some YAML data, returns a Python dictionary of the decoded data. """ if yaml is None: raise ImproperlyConfigured("Usage of the YAML aspects requires yaml.") return yaml.load(content)
CWE-20
0
async def send_transactions(self, account, calls, nonce=None, max_fee=0): if nonce is None: execution_info = await account.get_nonce().call() nonce, = execution_info.result build_calls = [] for call in calls: build_call = list(call) build_call[0] = hex(build_call[0]) build_calls.append(build_call) (call_array, calldata, sig_r, sig_s) = self.signer.sign_transaction(hex(account.contract_address), build_calls, nonce, max_fee) return await account.__execute__(call_array, calldata, nonce).invoke(signature=[sig_r, sig_s])
CWE-863
11
def test_file_position_after_fromfile(self): # gh-4118 sizes = [io.DEFAULT_BUFFER_SIZE//8, io.DEFAULT_BUFFER_SIZE, io.DEFAULT_BUFFER_SIZE*8] for size in sizes: f = open(self.filename, 'wb') f.seek(size-1) f.write(b'\0') f.close() for mode in ['rb', 'r+b']: err_msg = "%d %s" % (size, mode) f = open(self.filename, mode) f.read(2) np.fromfile(f, dtype=np.float64, count=1) pos = f.tell() f.close() assert_equal(pos, 10, err_msg=err_msg) os.unlink(self.filename)
CWE-20
0
def host_passes(self, host_state, filter_properties): context = filter_properties['context'] scheduler_hints = filter_properties.get('scheduler_hints') or {} me = host_state.host affinity_uuids = scheduler_hints.get('different_host', []) if isinstance(affinity_uuids, basestring): affinity_uuids = [affinity_uuids] if affinity_uuids: return not any([i for i in affinity_uuids if self._affinity_host(context, i) == me]) # With no different_host key return True
CWE-20
0
def remove_cookies(self, names: Iterable[str]): for name in names: if name in self['cookies']: del self['cookies'][name]
CWE-200
10
def is_gae_instance(): server_software = os.environ.get('SERVER_SOFTWARE', '') if (server_software.startswith('Google App Engine/') or server_software.startswith('Development/') or server_software.startswith('testutil/')): return True return False
CWE-400
2
def _bind_write_headers(msg): def _write_headers(self): # Self refers to the Generator object. for h, v in msg.items(): print("%s:" % h, end=" ", file=self._fp) if isinstance(v, header.Header): print(v.encode(maxlinelen=self._maxheaderlen), file=self._fp) else: # email.Header got lots of smarts, so use it. headers = header.Header( v, maxlinelen=self._maxheaderlen, charset="utf-8", header_name=h ) print(headers.encode(), file=self._fp) # A blank line always separates headers from body. print(file=self._fp) return _write_headers
CWE-400
2
def testInvalidSparseTensor(self): with test_util.force_cpu(): shape = [2, 2] val = [0] dense = constant_op.constant(np.zeros(shape, dtype=np.int32)) for bad_idx in [ [[-1, 0]], # -1 is invalid. [[1, 3]], # ...so is 3. ]: sparse = sparse_tensor.SparseTensorValue(bad_idx, val, shape) s = sparse_ops.sparse_add(sparse, dense) with self.assertRaisesRegex(errors_impl.InvalidArgumentError, "invalid index"): self.evaluate(s)
CWE-20
0
def test_unicode_url(): mw = _get_mw() req = SplashRequest( # note unicode URL u"http://example.com/", endpoint='execute') req2 = mw.process_request(req, None) res = {'html': '<html><body>Hello</body></html>'} res_body = json.dumps(res) response = TextResponse("http://mysplash.example.com/execute", # Scrapy doesn't pass request to constructor # request=req2, headers={b'Content-Type': b'application/json'}, body=res_body.encode('utf8')) response2 = mw.process_response(req2, response, None) assert response2.url == "http://example.com/"
CWE-200
10
def deserialize(self, content, format='application/json'): """ Given some data and a format, calls the correct method to deserialize the data and returns the result. """ desired_format = None format = format.split(';')[0] for short_format, long_format in self.content_types.items(): if format == long_format: if hasattr(self, "from_%s" % short_format): desired_format = short_format break if desired_format is None: raise UnsupportedFormat("The format indicated '%s' had no available deserialization method. Please check your ``formats`` and ``content_types`` on your Serializer." % format) deserialized = getattr(self, "from_%s" % desired_format)(content) return deserialized
CWE-20
0
def get_by_name(self, name, project): return ( Person.query.filter(Person.name == name) .filter(Project.id == project.id) .one() )
CWE-863
11
def get(self, request, name=None): if name is None: if request.user.is_staff: return FormattedResponse(config.get_all()) return FormattedResponse(config.get_all_non_sensitive()) return FormattedResponse(config.get(name))
CWE-200
10
def __init__( self, cache, safe=safename
CWE-400
2
def get_type_string(data): """ Translates a Python data type into a string format. """ data_type = type(data) if data_type in (int, long): return 'integer' elif data_type == float: return 'float' elif data_type == bool: return 'boolean' elif data_type in (list, tuple): return 'list' elif data_type == dict: return 'hash' elif data is None: return 'null' elif isinstance(data, basestring): return 'string'
CWE-20
0
def _iterate_over_text( tree: "etree.Element", *tags_to_ignore: Union[str, "etree.Comment"]
CWE-674
28
def is_valid_client_secret(client_secret): """Validate that a given string matches the client_secret regex defined by the spec :param client_secret: The client_secret to validate :type client_secret: str :return: Whether the client_secret is valid :rtype: bool """ return client_secret_regex.match(client_secret) is not None
CWE-20
0
def verify_password(plain_password, user_password): if plain_password == user_password: LOG.debug("password true") return True return False
CWE-287
4
async def on_context_state_request( self, origin: str, room_id: str, event_id: str
CWE-400
2
async def message(self, ctx, *, message: str): """Set the message that is shown at the start of each ticket channel.\n\nUse ``{user.mention}`` to mention the person who created the ticket.""" try: message.format(user=ctx.author) await self.config.guild(ctx.guild).message.set(message) await ctx.send(f"The message has been set to `{message}`.") except KeyError: await ctx.send( "Setting the message failed. Please make sure to only use supported variables in `\{\}`" )
CWE-74
1
def test_nonexistent_catalog_is_none(self): pardir = self.get_test_dir(erase=1) cat = catalog.get_catalog(pardir,'r') self.remove_dir(pardir) assert_(cat is None)
CWE-269
6
def from_plist(self, content): """ Given some binary plist data, returns a Python dictionary of the decoded data. """ if biplist is None: raise ImproperlyConfigured("Usage of the plist aspects requires biplist.") return biplist.readPlistFromString(content)
CWE-20
0
def _request( self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey,
CWE-400
2
def get(self, location, connection=None): location = location.store_location if not connection: connection = self.get_connection(location) try: resp_headers, resp_body = connection.get_object( container=location.container, obj=location.obj, resp_chunk_size=self.CHUNKSIZE) except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_uri() raise exception.NotFound(_("Swift could not find image at " "uri %(uri)s") % locals()) else: raise class ResponseIndexable(glance.store.Indexable): def another(self): try: return self.wrapped.next() except StopIteration: return '' length = int(resp_headers.get('content-length', 0)) return (ResponseIndexable(resp_body, length), length)
CWE-200
10
def __init__( self, proxy_type, proxy_host, proxy_port, proxy_rdns=True, proxy_user=None, proxy_pass=None, proxy_headers=None,
CWE-400
2
def build_key(self, filename, entry, metadata): """ generates a new key according the the specification """ type = self.key_specs[entry.get('name')]['type'] bits = self.key_specs[entry.get('name')]['bits'] if type == 'rsa': cmd = "openssl genrsa %s " % bits elif type == 'dsa': cmd = "openssl dsaparam -noout -genkey %s" % bits key = Popen(cmd, shell=True, stdout=PIPE).stdout.read() return key
CWE-20
0
def __init__(self, sydent): self.sydent = sydent # The default endpoint factory in Twisted 14.0.0 (which we require) uses the # BrowserLikePolicyForHTTPS context factory which will do regular cert validation # 'like a browser' self.agent = Agent( self.sydent.reactor, connectTimeout=15, )
CWE-20
0
def __init__(self, formats=None, content_types=None, datetime_formatting=None): self.supported_formats = [] self.datetime_formatting = getattr(settings, 'TASTYPIE_DATETIME_FORMATTING', 'iso-8601') if formats is not None: self.formats = formats if content_types is not None: self.content_types = content_types if datetime_formatting is not None: self.datetime_formatting = datetime_formatting for format in self.formats: try: self.supported_formats.append(self.content_types[format]) except KeyError: raise ImproperlyConfigured("Content type for specified type '%s' not found. Please provide it at either the class level or via the arguments." % format)
CWE-20
0
def command(self): res = self._gnupg().list_secret_keys() return self._success("Searched for secret keys", res)
CWE-287
4
def test_is_valid_hostname(self): """Tests that the is_valid_hostname function accepts only valid hostnames (or domain names), with optional port number. """ self.assertTrue(is_valid_hostname("example.com")) self.assertTrue(is_valid_hostname("EXAMPLE.COM")) self.assertTrue(is_valid_hostname("ExAmPlE.CoM")) self.assertTrue(is_valid_hostname("example.com:4242")) self.assertTrue(is_valid_hostname("localhost")) self.assertTrue(is_valid_hostname("localhost:9000")) self.assertTrue(is_valid_hostname("a.b:1234")) self.assertFalse(is_valid_hostname("example.com:65536")) self.assertFalse(is_valid_hostname("example.com:0")) self.assertFalse(is_valid_hostname("example.com:a")) self.assertFalse(is_valid_hostname("example.com:04242")) self.assertFalse(is_valid_hostname("example.com: 4242")) self.assertFalse(is_valid_hostname("example.com/example.com")) self.assertFalse(is_valid_hostname("example.com#example.com"))
CWE-20
0
def _cnonce(): dig = _md5( ( "%s:%s" % (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)]) ).encode("utf-8") ).hexdigest() return dig[:16]
CWE-400
2
async def on_PUT(self, origin, content, query, room_id): content = await self.handler.on_exchange_third_party_invite_request( room_id, content ) return 200, content
CWE-400
2
def test_change_response_class_to_json_binary(): mw = _get_mw() # We set magic_response to False, because it's not a kind of data we would # expect from splash: we just return binary data. # If we set magic_response to True, the middleware will fail, # but this is ok because magic_response presumes we are expecting # a valid splash json response. req = SplashRequest('http://example.com/', magic_response=False) req = mw.process_request(req, None) resp = Response('http://mysplash.example.com/execute', headers={b'Content-Type': b'application/json'}, body=b'non-decodable data: \x98\x11\xe7\x17\x8f', ) resp2 = mw.process_response(req, resp, None) assert isinstance(resp2, Response) assert resp2.url == 'http://example.com/' assert resp2.headers == {b'Content-Type': [b'application/json']} assert resp2.body == b'non-decodable data: \x98\x11\xe7\x17\x8f'
CWE-200
10
def prepare_context(self, request, context, *args, **kwargs): """ Hook for adding additional data to the context dict """ pass
CWE-200
10
def test_manage_pools(self) -> None: user1 = uuid4() user2 = uuid4() # by default, any can modify self.assertIsNone( check_can_manage_pools_impl( InstanceConfig(allow_pool_management=True), UserInfo() ) ) # with oid, but no admin self.assertIsNone( check_can_manage_pools_impl( InstanceConfig(allow_pool_management=True), UserInfo(object_id=user1) ) ) # is admin self.assertIsNone( check_can_manage_pools_impl( InstanceConfig(allow_pool_management=False, admins=[user1]), UserInfo(object_id=user1), ) ) # no user oid set self.assertIsNotNone( check_can_manage_pools_impl( InstanceConfig(allow_pool_management=False, admins=[user1]), UserInfo() ) ) # not an admin self.assertIsNotNone( check_can_manage_pools_impl( InstanceConfig(allow_pool_management=False, admins=[user1]), UserInfo(object_id=user2), ) )
CWE-346
16
def test_exchange_revoked_invite(self): user_id = self.register_user("kermit", "test") tok = self.login("kermit", "test") room_id = self.helper.create_room_as(room_creator=user_id, tok=tok) # Send a 3PID invite event with an empty body so it's considered as a revoked one. invite_token = "sometoken" self.helper.send_state( room_id=room_id, event_type=EventTypes.ThirdPartyInvite, state_key=invite_token, body={}, tok=tok, ) d = self.handler.on_exchange_third_party_invite_request( room_id=room_id, event_dict={ "type": EventTypes.Member, "room_id": room_id, "sender": user_id, "state_key": "@someone:example.org", "content": { "membership": "invite", "third_party_invite": { "display_name": "alice", "signed": { "mxid": "@alice:localhost", "token": invite_token, "signatures": { "magic.forest": { "ed25519:3": "fQpGIW1Snz+pwLZu6sTy2aHy/DYWWTspTJRPyNp0PKkymfIsNffysMl6ObMMFdIJhk6g6pwlIqZ54rxo8SLmAg" } }, }, }, }, }, ) failure = self.get_failure(d, AuthError).value self.assertEqual(failure.code, 403, failure) self.assertEqual(failure.errcode, Codes.FORBIDDEN, failure) self.assertEqual(failure.msg, "You are not invited to this room.")
CWE-400
2
def CreateAuthenticator(): """Create a packet autenticator. All RADIUS packets contain a sixteen byte authenticator which is used to authenticate replies from the RADIUS server and in the password hiding algorithm. This function returns a suitable random string that can be used as an authenticator. :return: valid packet authenticator :rtype: binary string """ data = [] for i in range(16): data.append(random.randrange(0, 256)) if six.PY3: return bytes(data) else: return ''.join(chr(b) for b in data)
CWE-330
12
def test_patch_bot_role(self) -> None: self.login("desdemona") email = "[email protected]" user_profile = self.get_bot_user(email) do_change_user_role(user_profile, UserProfile.ROLE_MEMBER, acting_user=user_profile) req = dict(role=UserProfile.ROLE_GUEST) result = self.client_patch(f"/json/bots/{self.get_bot_user(email).id}", req) self.assert_json_success(result) user_profile = self.get_bot_user(email) self.assertEqual(user_profile.role, UserProfile.ROLE_GUEST) # Test for not allowing a non-owner user to make assign a bot an owner role desdemona = self.example_user("desdemona") do_change_user_role(desdemona, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None) req = dict(role=UserProfile.ROLE_REALM_OWNER) result = self.client_patch(f"/json/bots/{self.get_bot_user(email).id}", req) self.assert_json_error(result, "Must be an organization owner")
CWE-863
11
def _build_ssl_context( disable_ssl_certificate_validation, ca_certs, cert_file=None, key_file=None, maximum_version=None, minimum_version=None, key_password=None,
CWE-400
2
def skip(self, type): if type == TType.STOP: return elif type == TType.BOOL: self.readBool() elif type == TType.BYTE: self.readByte() elif type == TType.I16: self.readI16() elif type == TType.I32: self.readI32() elif type == TType.I64: self.readI64() elif type == TType.DOUBLE: self.readDouble() elif type == TType.FLOAT: self.readFloat() elif type == TType.STRING: self.readString() elif type == TType.STRUCT: name = self.readStructBegin() while True: (name, type, id) = self.readFieldBegin() if type == TType.STOP: break self.skip(type) self.readFieldEnd() self.readStructEnd() elif type == TType.MAP: (ktype, vtype, size) = self.readMapBegin() for _ in range(size): self.skip(ktype) self.skip(vtype) self.readMapEnd() elif type == TType.SET: (etype, size) = self.readSetBegin() for _ in range(size): self.skip(etype) self.readSetEnd() elif type == TType.LIST: (etype, size) = self.readListBegin() for _ in range(size): self.skip(etype) self.readListEnd()
CWE-755
21
def _on_load_started(self) -> None: self._progress = 0 self._has_ssl_errors = False self.data.viewing_source = False self._set_load_status(usertypes.LoadStatus.loading) self.load_started.emit()
CWE-684
35
def is_valid_client_secret(client_secret): """Validate that a given string matches the client_secret regex defined by the spec :param client_secret: The client_secret to validate :type client_secret: unicode :return: Whether the client_secret is valid :rtype: bool """ return client_secret_regex.match(client_secret) is not None
CWE-20
0
def validate_request(self, request): """If configured for webhook basic auth, validate request has correct auth.""" if self.basic_auth: basic_auth = get_request_basic_auth(request) if basic_auth is None or basic_auth not in self.basic_auth: # noinspection PyUnresolvedReferences raise AnymailWebhookValidationFailure( "Missing or invalid basic auth in Anymail %s webhook" % self.esp_name)
CWE-200
10
def verify_cert_against_ca(self, filename, entry): """ check that a certificate validates against the ca cert, and that it has not expired. """ chaincert = self.CAs[self.cert_specs[entry.get('name')]['ca']].get('chaincert') cert = self.data + filename cmd = "openssl verify -CAfile %s %s" % (chaincert, cert) res = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT).stdout.read() if res == cert + ": OK\n": return True return False
CWE-20
0
def format_date(self, data): """ A hook to control how dates are formatted. Can be overridden at the ``Serializer`` level (``datetime_formatting``) or globally (via ``settings.TASTYPIE_DATETIME_FORMATTING``). Default is ``iso-8601``, which looks like "2010-12-16". """ if self.datetime_formatting == 'rfc-2822': return format_date(data) return data.isoformat()
CWE-20
0
def __init__(self, *args, **kwargs): super(BasketShareForm, self).__init__(*args, **kwargs) try: self.fields["image"] = GroupModelMultipleChoiceField( queryset=kwargs["initial"]["images"], initial=kwargs["initial"]["selected"], widget=forms.SelectMultiple(attrs={"size": 10}), ) except Exception: self.fields["image"] = GroupModelMultipleChoiceField( queryset=kwargs["initial"]["images"], widget=forms.SelectMultiple(attrs={"size": 10}), )
CWE-200
10