code
stringlengths 12
2.05k
| label_name
stringlengths 6
8
| label
int64 0
95
|
---|---|---|
def prepare_context(self, request, context, *args, **kwargs):
""" Hook for adding additional data to the context dict """
pass | CWE-601 | 11 |
def test_login_inactive_user(self):
self.user.is_active = False
self.user.save()
login_code = LoginCode.objects.create(user=self.user, code='foobar')
response = self.client.post('/accounts-rest/login/code/', {
'code': login_code.code,
})
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json(), {
'code': ['Unable to log in with provided login code.'],
}) | CWE-312 | 71 |
def create(request, comment_id):
comment = get_object_or_404(Comment, pk=comment_id)
form = FlagForm(
user=request.user,
comment=comment,
data=post_data(request))
if is_post(request) and form.is_valid():
form.save()
return redirect(request.POST.get('next', comment.get_absolute_url()))
return render(
request=request,
template_name='spirit/comment/flag/create.html',
context={
'form': form,
'comment': comment}) | CWE-601 | 11 |
def async_run(prog, args):
pid = os.fork()
if pid:
os.waitpid(pid, 0)
else:
dpid = os.fork()
if not dpid:
os.system(" ".join([prog] + args))
os._exit(0) | CWE-78 | 6 |
def _hkey(s):
return s.title().replace('_', '-') | CWE-93 | 33 |
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver(
http_client=None, homeserver_to_use=GenericWorkerServer
)
return hs | CWE-601 | 11 |
def test_spinal_case():
assert utils.spinal_case("keep_alive") == "keep-alive" | CWE-22 | 2 |
def testInputParserBothDuplicate(self):
x0 = np.array([[1], [2]])
input_path = os.path.join(test.get_temp_dir(), 'input.npz')
np.savez(input_path, a=x0)
x1 = np.ones([2, 10])
input_str = 'x0=' + input_path + '[a]'
input_expr_str = 'x0=np.ones([2,10])'
feed_dict = saved_model_cli.load_inputs_from_input_arg_string(
input_str, input_expr_str, '')
self.assertTrue(np.all(feed_dict['x0'] == x1)) | CWE-94 | 14 |
def test_parse_header_11_expect_continue(self):
data = b"GET /foobar HTTP/1.1\nexpect: 100-continue"
self.parser.parse_header(data)
self.assertEqual(self.parser.expect_continue, True) | CWE-444 | 41 |
def job_list(request, client_id, project_name):
"""
get job list of project from one client
:param request: request object
:param client_id: client id
:param project_name: project name
:return: list of jobs
"""
if request.method == 'GET':
client = Client.objects.get(id=client_id)
scrapyd = get_scrapyd(client)
try:
result = scrapyd.list_jobs(project_name)
jobs = []
statuses = ['pending', 'running', 'finished']
for status in statuses:
for job in result.get(status):
job['status'] = status
jobs.append(job)
return JsonResponse(jobs)
except ConnectionError:
return JsonResponse({'message': 'Connect Error'}, status=500) | CWE-78 | 6 |
def _keyify(key):
return _key_pattern.sub(' ', key.lower()) | CWE-79 | 1 |
def _get_object_element(dataset, seq_no, rel_path, download_link):
"""If rel_path and download_link are not None, we are called from scope.
Otherwise we are called from ID and need to run SQL query to fetch these attrs."""
if rel_path is None:
query = "SELECT rel_path, download_link FROM " + \
dataset + \
" WHERE sequence_no = %s"
cnx = mysql.connector.connect(user=DB_USER,
password=DB_PASSWORD,
host=DB_HOST,
database=DB_DBNAME,
port=DB_PORT)
cursor = cnx.cursor()
cursor.execute(query, (seq_no,))
row = cursor.fetchone()
if not row:
return None
rel_path, download_link = row[0], row[1]
if LOCAL_OBJ_URI:
src_uri = 'file://' + os.path.join(DATAROOT, dataset, rel_path)
else:
src_uri = url_for('.get_object_src_http', dataset=dataset, rel_path=rel_path)
return '<object id={} src={} hyperfind.external-link={} />' \
.format(
quoteattr(url_for('.get_object_id', dataset=dataset, seq_no=seq_no)),
quoteattr(src_uri),
quoteattr(download_link)) | CWE-22 | 2 |
def vote(request, pk):
# TODO: check if user has access to this topic/poll
poll = get_object_or_404(
CommentPoll.objects.unremoved(),
pk=pk
)
if not request.user.is_authenticated:
return redirect_to_login(next=poll.get_absolute_url())
form = PollVoteManyForm(user=request.user, poll=poll, data=request.POST)
if form.is_valid():
CommentPollChoice.decrease_vote_count(poll=poll, voter=request.user)
form.save_m2m()
CommentPollChoice.increase_vote_count(poll=poll, voter=request.user)
return redirect(request.POST.get('next', poll.get_absolute_url()))
messages.error(request, utils.render_form_errors(form))
return redirect(request.POST.get('next', poll.get_absolute_url())) | CWE-601 | 11 |
def ratings_list():
if current_user.check_visibility(constants.SIDEBAR_RATING):
if current_user.get_view_property('ratings', 'dir') == 'desc':
order = db.Ratings.rating.desc()
order_no = 0
else:
order = db.Ratings.rating.asc()
order_no = 1
entries = calibre_db.session.query(db.Ratings, func.count('books_ratings_link.book').label('count'),
(db.Ratings.rating / 2).label('name')) \
.join(db.books_ratings_link).join(db.Books).filter(calibre_db.common_filters()) \
.group_by(text('books_ratings_link.rating')).order_by(order).all()
return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=list(),
title=_(u"Ratings list"), page="ratingslist", data="ratings", order=order_no)
else:
abort(404) | CWE-918 | 16 |
def feed_authorindex():
shift = 0
off = int(request.args.get("offset") or 0)
entries = calibre_db.session.query(func.upper(func.substr(db.Authors.sort, 1, 1)).label('id'))\
.join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters())\
.group_by(func.upper(func.substr(db.Authors.sort, 1, 1))).all()
elements = []
if off == 0:
elements.append({'id': "00", 'name':_("All")})
shift = 1
for entry in entries[
off + shift - 1:
int(off + int(config.config_books_per_page) - shift)]:
elements.append({'id': entry.id, 'name': entry.id})
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
len(entries) + 1)
return render_xml_template('feed.xml',
letterelements=elements,
folder='opds.feed_letter_author',
pagination=pagination) | CWE-918 | 16 |
def validate_and_sanitize_search_inputs(fn, instance, args, kwargs):
kwargs.update(dict(zip(fn.__code__.co_varnames, args)))
sanitize_searchfield(kwargs['searchfield'])
kwargs['start'] = cint(kwargs['start'])
kwargs['page_len'] = cint(kwargs['page_len'])
if kwargs['doctype'] and not frappe.db.exists('DocType', kwargs['doctype']):
return []
return fn(**kwargs) | CWE-79 | 1 |
def _get_index_absolute_path(index):
return os.path.join(INDEXDIR, index) | CWE-22 | 2 |
def format_errormsg(message: str) -> str:
"""Match account names in error messages and insert HTML links for them."""
match = re.search(ACCOUNT_RE, message)
if not match:
return message
account = match.group()
url = flask.url_for("account", name=account)
return (
message.replace(account, f'<a href="{url}">{account}</a>')
.replace("for '", "for ")
.replace("': ", ": ")
) | CWE-79 | 1 |
def home_get_dat():
d = db.sentences_stats('get_data')
n = db.sentences_stats('all_networks')
('clean_online')
rows = db.sentences_stats('get_clicks')
c = rows[0][0]
rows = db.sentences_stats('get_sessions')
s = rows[0][0]
rows = db.sentences_stats('get_online')
o = rows[0][0]
return json.dumps({'status' : 'OK', 'd' : d, 'n' : n, 'c' : c, 's' : s, 'o' : o}); | CWE-89 | 0 |
def __new__(cls, sourceName: str):
"""Dispatches to the right subclass."""
if cls != InputSource:
# Only take control of calls to InputSource(...) itself.
return super().__new__(cls)
if sourceName == "-":
return StdinInputSource(sourceName)
if sourceName.startswith("https:"):
return UrlInputSource(sourceName)
return FileInputSource(sourceName) | CWE-78 | 6 |
def testSizeAndClear(self):
with ops.Graph().as_default() as G:
with ops.device('/cpu:0'):
x = array_ops.placeholder(dtypes.float32, name='x')
pi = array_ops.placeholder(dtypes.int64)
gi = array_ops.placeholder(dtypes.int64)
v = 2. * (array_ops.zeros([128, 128]) + x)
with ops.device(test.gpu_device_name()):
stager = data_flow_ops.MapStagingArea(
[dtypes.float32, dtypes.float32],
shapes=[[], [128, 128]],
names=['x', 'v'])
stage = stager.put(pi, {'x': x, 'v': v})
size = stager.size()
clear = stager.clear()
G.finalize()
with self.session(graph=G) as sess:
sess.run(stage, feed_dict={x: -1, pi: 3})
self.assertEqual(sess.run(size), 1)
sess.run(stage, feed_dict={x: -1, pi: 1})
self.assertEqual(sess.run(size), 2)
sess.run(clear)
self.assertEqual(sess.run(size), 0) | CWE-843 | 43 |
def job_browse(job_id: int, path):
"""
Browse directory of the job.
:param job_id: int
:param path: str
"""
try:
# Query job information
job_info = query_internal_api(f"/internal/jobs/{job_id}", "get")
# Base directory of the job
job_base_dir = os.path.dirname(os.path.dirname(job_info["outputdir"]))
except Exception as err:
# Display error on the GUI
flash(str(err), "danger")
return redirect(url_for("job_page", job_id=job_id))
# Join the base and the requested path
abs_path = os.path.join(job_base_dir, path)
# URL path variable for going back
back_path = os.path.dirname(abs_path).replace(job_base_dir, "")
# If path doesn't exist
if not os.path.exists(abs_path):
flash("Directory for this job does not exist.", "warning")
return redirect(url_for("job_page", job_id=job_id))
# Check if path is a file and send
if os.path.isfile(abs_path):
return send_file(abs_path)
files_info = []
# Show directory contents
files = os.listdir(abs_path)
# Store directory information
for file in files:
files_info.append({
"file": file,
"directory": os.path.isdir(os.path.join(abs_path, file))
})
return render_template('job_dir.html', title=f"Job {job_id} Directory",
job_id=job_id,
abs_path=abs_path,
files_info=files_info,
back_path=back_path) | CWE-22 | 2 |
def test___post_init__(self):
from openapi_python_client.parser.properties import StringProperty
sp = StringProperty(name="test", required=True, default="A Default Value",)
assert sp.default == '"A Default Value"' | CWE-94 | 14 |
async def actset(self, ctx):
"""
Configure various settings for the act cog.
"""
| CWE-502 | 15 |
def get_list(an_enum_value: List[AnEnum] = Query(...), some_date: Union[date, datetime] = Query(...)):
""" Get a list of things """
return | CWE-94 | 14 |
def test_request_body_too_large_with_wrong_cl_http11(self):
body = "a" * self.toobig
to_send = "GET / HTTP/1.1\n" "Content-Length: 5\n\n"
to_send += body
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb")
# first request succeeds (content-length 5)
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
# second response is an error response
line, headers, response_body = read_http(fp)
self.assertline(line, "431", "Request Header Fields Too Large", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp) | CWE-444 | 41 |
def test_parse_header_bad_content_length(self):
data = b"GET /foobar HTTP/8.4\r\ncontent-length: abc\r\n"
self.parser.parse_header(data)
self.assertEqual(self.parser.body_rcv, None) | CWE-444 | 41 |
def profile():
languages = calibre_db.speaking_language()
translations = babel.list_translations() + [LC('en')]
kobo_support = feature_support['kobo'] and config.config_kobo_sync
if feature_support['oauth'] and config.config_login_type == 2:
oauth_status = get_oauth_status()
local_oauth_check = oauth_check
else:
oauth_status = None
local_oauth_check = {}
if request.method == "POST":
change_profile(kobo_support, local_oauth_check, oauth_status, translations, languages)
return render_title_template("user_edit.html",
translations=translations,
profile=1,
languages=languages,
content=current_user,
kobo_support=kobo_support,
title=_(u"%(name)s's profile", name=current_user.name),
page="me",
registered_oauth=local_oauth_check,
oauth_status=oauth_status) | CWE-918 | 16 |
def remove_auth_hashes(input: Optional[str]):
if not input:
return input
# If there are no hashes, skip the RE for performance.
if not any([pw_hash in input for pw_hash in PASSWORD_HASHERS_ALL.keys()]):
return input
return re_remove_passwords.sub(r'\1 %s # Filtered for security' % PASSWORD_HASH_DUMMY_VALUE, input) | CWE-212 | 66 |
def test_keepalive_http_11(self):
# Handling of Keep-Alive within HTTP 1.1
# All connections are kept alive, unless stated otherwise
data = "Default: Keep me alive"
s = tobytes(
"GET / HTTP/1.1\n" "Content-Length: %d\n" "\n" "%s" % (len(data), data)
)
self.connect()
self.sock.send(s)
response = httplib.HTTPResponse(self.sock)
response.begin()
self.assertEqual(int(response.status), 200)
self.assertTrue(response.getheader("connection") != "close") | CWE-444 | 41 |
def __init__(self, *, openapi: GeneratorData) -> None:
self.openapi: GeneratorData = openapi
self.env: Environment = Environment(loader=PackageLoader(__package__), trim_blocks=True, lstrip_blocks=True)
self.project_name: str = self.project_name_override or f"{openapi.title.replace(' ', '-').lower()}-client"
self.project_dir: Path = Path.cwd() / self.project_name
self.package_name: str = self.package_name_override or self.project_name.replace("-", "_")
self.package_dir: Path = self.project_dir / self.package_name
self.package_description: str = f"A client library for accessing {self.openapi.title}"
self.version: str = openapi.version
self.env.filters.update(self.TEMPLATE_FILTERS) | CWE-22 | 2 |
def testPartialIndexGets(self):
with ops.Graph().as_default() as G:
with ops.device('/cpu:0'):
x = array_ops.placeholder(dtypes.float32)
f = array_ops.placeholder(dtypes.float32)
v = array_ops.placeholder(dtypes.float32)
pi = array_ops.placeholder(dtypes.int64)
pei = array_ops.placeholder(dtypes.int64)
gi = array_ops.placeholder(dtypes.int64)
with ops.device(test.gpu_device_name()):
# Test again with partial index gets
stager = data_flow_ops.MapStagingArea(
[dtypes.float32, dtypes.float32, dtypes.float32])
stage_xvf = stager.put(pi, [x, v, f], [0, 1, 2])
key_xf, get_xf = stager.get(gi, [0, 2])
key_v, get_v = stager.get(gi, [1])
size = stager.size()
isize = stager.incomplete_size()
G.finalize()
with self.session(graph=G) as sess:
# Stage complete tuple
sess.run(stage_xvf, feed_dict={pi: 0, x: 1, f: 2, v: 3})
self.assertTrue(sess.run([size, isize]) == [1, 0])
# Partial get using indices
self.assertTrue(
sess.run([key_xf, get_xf], feed_dict={
gi: 0
}) == [0, [1, 2]])
# Still some of key 0 left
self.assertTrue(sess.run([size, isize]) == [1, 0])
# Partial get of remaining index
self.assertTrue(sess.run([key_v, get_v], feed_dict={gi: 0}) == [0, [3]])
# All gone
self.assertTrue(sess.run([size, isize]) == [0, 0]) | CWE-843 | 43 |
async def on_message(self, message):
if message.author.bot:
return
ctx = await self.bot.get_context(message)
if ctx.prefix is None or not ctx.invoked_with.replace("_", "").isalpha():
return
if ctx.valid and ctx.command.enabled:
try:
if await ctx.command.can_run(ctx):
return
except commands.errors.CheckFailure:
return
ctx.command = self.act
await self.bot.invoke(ctx)
| CWE-502 | 15 |
def test_notfilelike_http11(self):
to_send = "GET /notfilelike HTTP/1.1\n\n"
to_send = tobytes(to_send)
self.connect()
for t in range(0, 2):
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertTrue(b"\377\330\377" in response_body) | CWE-444 | 41 |
def publish(request, user_id=None):
initial = None
if user_id: # todo: move to form
user_to = get_object_or_404(User, pk=user_id)
initial = {'users': [user_to.st.nickname]}
user = request.user
tform = TopicForPrivateForm(
user=user, data=post_data(request))
cform = CommentForm(
user=user, data=post_data(request))
tpform = TopicPrivateManyForm(
user=user, data=post_data(request), initial=initial)
if (is_post(request) and
all([tform.is_valid(), cform.is_valid(), tpform.is_valid()]) and
not request.is_limited()):
if not user.st.update_post_hash(tform.get_topic_hash()):
return redirect(
request.POST.get('next', None) or
tform.category.get_absolute_url())
# wrap in transaction.atomic?
topic = tform.save()
cform.topic = topic
comment = cform.save()
comment_posted(comment=comment, mentions=None)
tpform.topic = topic
tpform.save_m2m()
TopicNotification.bulk_create(
users=tpform.get_users(), comment=comment)
return redirect(topic.get_absolute_url())
return render(
request=request,
template_name='spirit/topic/private/publish.html',
context={
'tform': tform,
'cform': cform,
'tpform': tpform}) | CWE-601 | 11 |
def _decompress(compressed_path: Text, target_path: Text) -> None:
with tarfile.open(compressed_path, "r:gz") as tar:
tar.extractall(target_path) # target dir will be created if it not exists | CWE-22 | 2 |
def render(self, name, value, attrs=None):
html = super(AdminURLFieldWidget, self).render(name, value, attrs)
if value:
value = force_text(self._format_value(value))
final_attrs = {'href': mark_safe(smart_urlquote(value))}
html = format_html(
'<p class="url">{0} <a {1}>{2}</a><br />{3} {4}</p>',
_('Currently:'), flatatt(final_attrs), value,
_('Change:'), html
)
return html | CWE-79 | 1 |
def POST(self, path, body=None, ensure_encoding=True, log_request_body=True):
return self._request('POST', path, body=body, ensure_encoding=ensure_encoding,
log_request_body=log_request_body) | CWE-295 | 52 |
def sql_execute(self, sentence):
self.cursor.execute(sentence)
return self.cursor.fetchall() | CWE-79 | 1 |
def decompile(self):
self.writeln("** Decompiling APK...", clr.OKBLUE)
with ZipFile(self.file) as zipped:
try:
dex = self.tempdir + "/" + self.apk.package + ".dex"
with open(dex, "wb") as classes:
classes.write(zipped.read("classes.dex"))
except Exception as e:
sys.exit(self.writeln(str(e), clr.WARNING))
dec = "%s %s -d %s --deobf" % (self.jadx, dex, self.tempdir)
os.system(dec)
return self.tempdir | CWE-88 | 3 |
def login():
from flask_login import current_user
redirect_url = request.args.get("redirect", request.script_root + url_for("index"))
permissions = sorted(
filter(
lambda x: x is not None and isinstance(x, OctoPrintPermission),
map(
lambda x: getattr(Permissions, x.strip()),
request.args.get("permissions", "").split(","),
),
),
key=lambda x: x.get_name(),
)
if not permissions:
permissions = [Permissions.STATUS, Permissions.SETTINGS_READ]
user_id = request.args.get("user_id", "")
if (not user_id or current_user.get_id() == user_id) and has_permissions(
*permissions
):
return redirect(redirect_url)
render_kwargs = {
"theming": [],
"redirect_url": redirect_url,
"permission_names": map(lambda x: x.get_name(), permissions),
"user_id": user_id,
"logged_in": not current_user.is_anonymous,
}
try:
additional_assets = _add_additional_assets("octoprint.theming.login")
# backwards compatibility to forcelogin & loginui plugins which were replaced by this built-in dialog
additional_assets += _add_additional_assets("octoprint.plugin.forcelogin.theming")
additional_assets += _add_additional_assets("octoprint.plugin.loginui.theming")
render_kwargs.update({"theming": additional_assets})
except Exception:
_logger.exception("Error processing theming CSS, ignoring")
return render_template("login.jinja2", **render_kwargs) | CWE-79 | 1 |
def feed_booksindex():
shift = 0
off = int(request.args.get("offset") or 0)
entries = calibre_db.session.query(func.upper(func.substr(db.Books.sort, 1, 1)).label('id'))\
.filter(calibre_db.common_filters()).group_by(func.upper(func.substr(db.Books.sort, 1, 1))).all()
elements = []
if off == 0:
elements.append({'id': "00", 'name':_("All")})
shift = 1
for entry in entries[
off + shift - 1:
int(off + int(config.config_books_per_page) - shift)]:
elements.append({'id': entry.id, 'name': entry.id})
pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
len(entries) + 1)
return render_xml_template('feed.xml',
letterelements=elements,
folder='opds.feed_letter_books',
pagination=pagination) | CWE-918 | 16 |
def get_install_extras_require():
extras_require = {
'action': ['chevron'],
'browser': ['zeroconf==0.19.1' if PY2 else 'zeroconf>=0.19.1'],
'cloud': ['requests'],
'docker': ['docker>=2.0.0'],
'export': ['bernhard', 'cassandra-driver', 'couchdb', 'elasticsearch',
'graphitesender', 'influxdb>=1.0.0', 'kafka-python', 'pika',
'paho-mqtt', 'potsdb', 'prometheus_client', 'pyzmq',
'statsd'],
'folders': ['scandir'], # python_version<"3.5"
'gpu': ['py3nvml'],
'graph': ['pygal'],
'ip': ['netifaces'],
'raid': ['pymdstat'],
'smart': ['pySMART.smartx'],
'snmp': ['pysnmp'],
'sparklines': ['sparklines'],
'web': ['bottle', 'requests'],
'wifi': ['wifi']
}
# Add automatically the 'all' target
extras_require.update({'all': [i[0] for i in extras_require.values()]})
return extras_require | CWE-611 | 13 |
def file(path):
path = secure_filename(path)
if app.interface.encrypt and isinstance(app.interface.examples, str) and path.startswith(app.interface.examples):
with open(os.path.join(app.cwd, path), "rb") as encrypted_file:
encrypted_data = encrypted_file.read()
file_data = encryptor.decrypt(
app.interface.encryption_key, encrypted_data)
return send_file(io.BytesIO(file_data), attachment_filename=os.path.basename(path))
else:
return send_file(os.path.join(app.cwd, path)) | CWE-22 | 2 |
def update_server_key(conf):
"""
Download the server's RSA key and store in the location
specified in the configuration.
:param conf: The consumer configuration object.
:type conf: dict
"""
host = conf['server']['host']
location = conf['server']['rsa_pub']
url = 'https://%s/pulp/static/rsa_pub.key' % host
try:
os.makedirs(os.path.dirname(location))
except OSError, e:
if e.errno != errno.EEXIST:
raise
download(url, location) | CWE-295 | 52 |
def test_keepalive_http11_connclose(self):
# specifying Connection: close explicitly
data = "Don't keep me alive"
s = tobytes(
"GET / HTTP/1.1\n"
"Connection: close\n"
"Content-Length: %d\n"
"\n"
"%s" % (len(data), data)
)
self.connect()
self.sock.send(s)
response = httplib.HTTPResponse(self.sock)
response.begin()
self.assertEqual(int(response.status), 200)
self.assertEqual(response.getheader("connection"), "close") | CWE-444 | 41 |
def traverse(cls, base, request, path_items):
"""See ``zope.app.pagetemplate.engine``."""
path_items = list(path_items)
path_items.reverse()
while path_items:
name = path_items.pop()
if name == '_':
warnings.warn('Traversing to the name `_` is deprecated '
'and will be removed in Zope 6.',
DeprecationWarning)
elif name.startswith('_'):
raise NotFound(name)
if ITraversable.providedBy(base):
base = getattr(base, cls.traverse_method)(name)
else:
base = traversePathElement(base, name, path_items,
request=request)
return base | CWE-22 | 2 |
def get_install_requires():
requires = ['psutil>=5.3.0', 'future']
if sys.platform.startswith('win'):
requires.append('bottle')
requires.append('requests')
return requires | CWE-611 | 13 |
def test_module(self):
body = [ast.Num(42)]
x = ast.Module(body)
self.assertEqual(x.body, body) | CWE-125 | 47 |
def make_homeserver(self, reactor, clock):
self.hs = self.setup_test_homeserver(
"red", http_client=None, federation_client=Mock(),
)
self.hs.get_federation_handler = Mock()
self.hs.get_federation_handler.return_value.maybe_backfill = Mock(
return_value=make_awaitable(None)
)
async def _insert_client_ip(*args, **kwargs):
return None
self.hs.get_datastore().insert_client_ip = _insert_client_ip
return self.hs | CWE-601 | 11 |
def get_absolute_path(path):
import os
script_dir = os.path.dirname(__file__) # <-- absolute dir the script is in
rel_path = path
abs_file_path = os.path.join(script_dir, rel_path)
return abs_file_path | CWE-22 | 2 |
def _get_obj_absolute_path(obj_path):
return os.path.join(DATAROOT, obj_path) | CWE-22 | 2 |
def makeTrustRoot(self):
# If this option is specified, use a specific root CA cert. This is useful for testing when it's not
# practical to get the client cert signed by a real root CA but should never be used on a production server.
caCertFilename = self.sydent.cfg.get('http', 'replication.https.cacert')
if len(caCertFilename) > 0:
try:
fp = open(caCertFilename)
caCert = twisted.internet.ssl.Certificate.loadPEM(fp.read())
fp.close()
except:
logger.warn("Failed to open CA cert file %s", caCertFilename)
raise
logger.warn("Using custom CA cert file: %s", caCertFilename)
return twisted.internet._sslverify.OpenSSLCertificateAuthorities([caCert.original])
else:
return twisted.internet.ssl.OpenSSLDefaultPaths() | CWE-770 | 37 |
def stmt(self, stmt, msg=None):
mod = ast.Module([stmt])
self.mod(mod, msg) | CWE-125 | 47 |
def test_get_header_lines_tabbed(self):
result = self._callFUT(b"slam\n\tslim")
self.assertEqual(result, [b"slam\tslim"]) | CWE-444 | 41 |
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver(http_client=None)
self.handler = hs.get_federation_handler()
self.store = hs.get_datastore()
return hs | CWE-601 | 11 |
def test_bind_invalid_entry(topology_st):
"""Test the failing bind does not return information about the entry
:id: 5cd9b083-eea6-426b-84ca-83c26fc49a6f
:customerscenario: True
:setup: Standalone instance
:steps:
1: bind as non existing entry
2: check that bind info does not report 'No such entry'
:expectedresults:
1: pass
2: pass
"""
topology_st.standalone.restart()
INVALID_ENTRY="cn=foooo,%s" % DEFAULT_SUFFIX
try:
topology_st.standalone.simple_bind_s(INVALID_ENTRY, PASSWORD)
except ldap.LDAPError as e:
log.info('test_bind_invalid_entry: Failed to bind as %s (expected)' % INVALID_ENTRY)
log.info('exception description: ' + e.args[0]['desc'])
if 'info' in e.args[0]:
log.info('exception info: ' + e.args[0]['info'])
assert e.args[0]['desc'] == 'Invalid credentials'
assert 'info' not in e.args[0]
pass
log.info('test_bind_invalid_entry: PASSED')
# reset credentials
topology_st.standalone.simple_bind_s(DN_DM, PW_DM) | CWE-203 | 38 |
def test_expect_continue(self):
# specifying Connection: close explicitly
data = "I have expectations"
to_send = tobytes(
"GET / HTTP/1.1\n"
"Connection: close\n"
"Content-Length: %d\n"
"Expect: 100-continue\n"
"\n"
"%s" % (len(data), data)
)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line = fp.readline() # continue status line
version, status, reason = (x.strip() for x in line.split(None, 2))
self.assertEqual(int(status), 100)
self.assertEqual(reason, b"Continue")
self.assertEqual(version, b"HTTP/1.1")
fp.readline() # blank line
line = fp.readline() # next status line
version, status, reason = (x.strip() for x in line.split(None, 2))
headers = parse_headers(fp)
length = int(headers.get("content-length")) or None
response_body = fp.read(length)
self.assertEqual(int(status), 200)
self.assertEqual(length, len(response_body))
self.assertEqual(response_body, tobytes(data)) | CWE-444 | 41 |
def update(request, pk):
notification = get_object_or_404(TopicNotification, pk=pk, user=request.user)
form = NotificationForm(data=request.POST, instance=notification)
if form.is_valid():
form.save()
else:
messages.error(request, utils.render_form_errors(form))
return redirect(request.POST.get(
'next', notification.topic.get_absolute_url())) | CWE-601 | 11 |
def feed_get_cover(book_id):
return get_book_cover(book_id) | CWE-918 | 16 |
def get_field_options(self, field):
options = {}
options['label'] = field.label
options['help_text'] = field.help_text
options['required'] = field.required
options['initial'] = field.default_value
return options | CWE-79 | 1 |
def _cbrt(x):
return math.pow(x, 1.0/3) | CWE-94 | 14 |
def pref_set(key, value):
if get_user() is None:
return "Authentication required", 401
get_preferences()[key] = (None if value == 'null' else value)
return Response(json.dumps({'key': key, 'success': ''})), 201 | CWE-79 | 1 |
def _deny_hook(self, resource=None):
app = self.get_app()
if current_user.is_authenticated():
status = 403
else:
status = 401
#abort(status)
if app.config.get('FRONTED_BY_NGINX'):
url = "https://{}:{}{}".format(app.config.get('FQDN'), app.config.get('NGINX_PORT'), '/login')
else:
url = "http://{}:{}{}".format(app.config.get('FQDN'), app.config.get('API_PORT'), '/login')
if current_user.is_authenticated():
auth_dict = {
"authenticated": True,
"user": current_user.email,
"roles": current_user.role,
}
else:
auth_dict = {
"authenticated": False,
"user": None,
"url": url
}
return Response(response=json.dumps({"auth": auth_dict}), status=status, mimetype="application/json") | CWE-601 | 11 |
def another_upload_file(request):
path = tempfile.mkdtemp()
file_name = os.path.join(path, "another_%s.txt" % request.node.name)
with open(file_name, "w") as f:
f.write(request.node.name)
return file_name | CWE-22 | 2 |
def test_received_preq_completed_n_lt_data(self):
inst, sock, map = self._makeOneWithMap()
inst.server = DummyServer()
preq = DummyParser()
inst.request = preq
preq.completed = True
preq.empty = False
line = b"GET / HTTP/1.1\n\n"
preq.retval = len(line)
inst.received(line + line)
self.assertEqual(inst.request, None)
self.assertEqual(len(inst.requests), 2)
self.assertEqual(len(inst.server.tasks), 1) | CWE-444 | 41 |
def testDictionary(self):
with ops.Graph().as_default() as G:
with ops.device('/cpu:0'):
x = array_ops.placeholder(dtypes.float32)
pi = array_ops.placeholder(dtypes.int64)
gi = array_ops.placeholder(dtypes.int64)
v = 2. * (array_ops.zeros([128, 128]) + x)
with ops.device(test.gpu_device_name()):
stager = data_flow_ops.MapStagingArea(
[dtypes.float32, dtypes.float32],
shapes=[[], [128, 128]],
names=['x', 'v'])
stage = stager.put(pi, {'x': x, 'v': v})
key, ret = stager.get(gi)
z = ret['x']
y = ret['v']
y = math_ops.reduce_max(z * math_ops.matmul(y, y))
G.finalize()
with self.session(graph=G) as sess:
sess.run(stage, feed_dict={x: -1, pi: 0})
for i in range(10):
_, yval = sess.run([stage, y], feed_dict={x: i, pi: i + 1, gi: i})
self.assertAllClose(
4 * (i - 1) * (i - 1) * (i - 1) * 128, yval, rtol=1e-4) | CWE-843 | 43 |
def check_auth(username, password):
try:
username = username.encode('windows-1252')
except UnicodeEncodeError:
username = username.encode('utf-8')
user = ub.session.query(ub.User).filter(func.lower(ub.User.name) ==
username.decode('utf-8').lower()).first()
if bool(user and check_password_hash(str(user.password), password)):
return True
else:
ip_Address = request.headers.get('X-Forwarded-For', request.remote_addr)
log.warning('OPDS Login failed for user "%s" IP-address: %s', username.decode('utf-8'), ip_Address)
return False | CWE-918 | 16 |
def boboAwareZopeTraverse(object, path_items, econtext):
"""Traverses a sequence of names, first trying attributes then items.
This uses zope.traversing path traversal where possible and interacts
correctly with objects providing OFS.interface.ITraversable when
necessary (bobo-awareness).
"""
request = getattr(econtext, 'request', None)
path_items = list(path_items)
path_items.reverse()
while path_items:
name = path_items.pop()
if name == '_':
warnings.warn('Traversing to the name `_` is deprecated '
'and will be removed in Zope 6.',
DeprecationWarning)
elif name.startswith('_'):
raise NotFound(name)
if OFS.interfaces.ITraversable.providedBy(object):
object = object.restrictedTraverse(name)
else:
object = traversePathElement(object, name, path_items,
request=request)
return object | CWE-22 | 2 |
def test_invalid_identitifer(self):
m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))])
ast.fix_missing_locations(m)
with self.assertRaises(TypeError) as cm:
compile(m, "<test>", "exec")
self.assertIn("identifier must be of type str", str(cm.exception)) | CWE-125 | 47 |
def receivePing():
vrequest = request.form['id']
db.sentences_victim('report_online', [vrequest])
return json.dumps({'status' : 'OK', 'vId' : vrequest}); | CWE-89 | 0 |
def mysql_contains(field: Field, value: str) -> Criterion:
return functions.Cast(field, SqlTypes.CHAR).like(f"%{value}%") | CWE-89 | 0 |
def test_datetime_parsing(value, result):
if result == errors.DateTimeError:
with pytest.raises(errors.DateTimeError):
parse_datetime(value)
else:
assert parse_datetime(value) == result | CWE-835 | 42 |
def delete_book_gdrive(book, book_format):
error = None
if book_format:
name = ''
for entry in book.data:
if entry.format.upper() == book_format:
name = entry.name + '.' + book_format
gFile = gd.getFileFromEbooksFolder(book.path, name)
else:
gFile = gd.getFileFromEbooksFolder(os.path.dirname(book.path), book.path.split('/')[1])
if gFile:
gd.deleteDatabaseEntry(gFile['id'])
gFile.Trash()
else:
error = _(u'Book path %(path)s not found on Google Drive', path=book.path) # file not found
return error is None, error | CWE-918 | 16 |
def get_cms_details(url):
# this function will fetch cms details using cms_detector
response = {}
cms_detector_command = 'python3 /usr/src/github/CMSeeK/cmseek.py -u {} --random-agent --batch --follow-redirect'.format(url)
os.system(cms_detector_command)
response['status'] = False
response['message'] = 'Could not detect CMS!'
parsed_url = urlparse(url)
domain_name = parsed_url.hostname
port = parsed_url.port
find_dir = domain_name
if port:
find_dir += '_{}'.format(port)
print(url)
print(find_dir)
# subdomain may also have port number, and is stored in dir as _port
cms_dir_path = '/usr/src/github/CMSeeK/Result/{}'.format(find_dir)
cms_json_path = cms_dir_path + '/cms.json'
if os.path.isfile(cms_json_path):
cms_file_content = json.loads(open(cms_json_path, 'r').read())
if not cms_file_content.get('cms_id'):
return response
response = {}
response = cms_file_content
response['status'] = True
# remove cms dir path
try:
shutil.rmtree(cms_dir_path)
except Exception as e:
print(e)
return response | CWE-78 | 6 |
def testDuplicateHeaders(self):
# Ensure that headers with the same key get concatenated as per
# RFC2616.
data = b"""\
GET /foobar HTTP/8.4
x-forwarded-for: 10.11.12.13
x-forwarded-for: unknown,127.0.0.1
X-Forwarded_for: 255.255.255.255
content-length: 7
Hello.
"""
self.feed(data)
self.assertTrue(self.parser.completed)
self.assertEqual(
self.parser.headers,
{
"CONTENT_LENGTH": "7",
"X_FORWARDED_FOR": "10.11.12.13, unknown,127.0.0.1",
},
) | CWE-444 | 41 |
def test_login_inactive_user(self):
self.user.is_active = False
self.user.save()
login_code = LoginCode.objects.create(user=self.user, code='foobar')
response = self.client.post('/accounts/login/code/', {
'code': login_code.code,
})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['form'].errors, {
'code': ['Unable to log in with provided login code.'],
}) | CWE-312 | 71 |
def _inject_admin_password_into_fs(admin_passwd, fs, execute=None):
"""Set the root password to admin_passwd
admin_password is a root password
fs is the path to the base of the filesystem into which to inject
the key.
This method modifies the instance filesystem directly,
and does not require a guest agent running in the instance.
"""
# The approach used here is to copy the password and shadow
# files from the instance filesystem to local files, make any
# necessary changes, and then copy them back.
admin_user = 'root'
fd, tmp_passwd = tempfile.mkstemp()
os.close(fd)
fd, tmp_shadow = tempfile.mkstemp()
os.close(fd)
utils.execute('cp', os.path.join(fs, 'etc', 'passwd'), tmp_passwd,
run_as_root=True)
utils.execute('cp', os.path.join(fs, 'etc', 'shadow'), tmp_shadow,
run_as_root=True)
_set_passwd(admin_user, admin_passwd, tmp_passwd, tmp_shadow)
utils.execute('cp', tmp_passwd, os.path.join(fs, 'etc', 'passwd'),
run_as_root=True)
os.unlink(tmp_passwd)
utils.execute('cp', tmp_shadow, os.path.join(fs, 'etc', 'shadow'),
run_as_root=True)
os.unlink(tmp_shadow) | CWE-22 | 2 |
def edit_all_cc_data(book_id, book, to_save):
cc = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all()
return edit_cc_data(book_id, book, to_save, cc) | CWE-918 | 16 |
def create_book_on_upload(modif_date, meta):
title = meta.title
authr = meta.author
sort_authors, input_authors, db_author, renamed_authors = prepare_authors_on_upload(title, authr)
title_dir = helper.get_valid_filename(title, chars=96)
author_dir = helper.get_valid_filename(db_author.name, chars=96)
# combine path and normalize path from windows systems
path = os.path.join(author_dir, title_dir).replace('\\', '/')
# Calibre adds books with utc as timezone
db_book = db.Books(title, "", sort_authors, datetime.utcnow(), datetime(101, 1, 1),
'1', datetime.utcnow(), path, meta.cover, db_author, [], "")
modif_date |= modify_database_object(input_authors, db_book.authors, db.Authors, calibre_db.session,
'author')
# Add series_index to book
modif_date |= edit_book_series_index(meta.series_id, db_book)
# add languages
invalid=[]
modif_date |= edit_book_languages(meta.languages, db_book, upload=True, invalid=invalid)
if invalid:
for l in invalid:
flash(_(u"'%(langname)s' is not a valid language", langname=l), category="warning")
# handle tags
modif_date |= edit_book_tags(meta.tags, db_book)
# handle publisher
modif_date |= edit_book_publisher(meta.publisher, db_book)
# handle series
modif_date |= edit_book_series(meta.series, db_book)
# Add file to book
file_size = os.path.getsize(meta.file_path)
db_data = db.Data(db_book, meta.extension.upper()[1:], file_size, title_dir)
db_book.data.append(db_data)
calibre_db.session.add(db_book)
# flush content, get db_book.id available
calibre_db.session.flush()
return db_book, input_authors, title_dir, renamed_authors | CWE-918 | 16 |
public static void zipFolder(String srcFolder, String destZipFile, String ignore) throws Exception {
try (FileOutputStream fileWriter = new FileOutputStream(destZipFile);
ZipOutputStream zip = new ZipOutputStream(fileWriter)){
addFolderToZip("", srcFolder, zip, ignore);
zip.flush();
}
} | CWE-22 | 2 |
public void install(
String displayName, String description, String[] dependencies,
String account, String password, String config) throws URISyntaxException {
String javaHome = System.getProperty("java.home");
String javaBinary = javaHome + "\\bin\\java.exe";
File jar = new File(WindowsService.class.getProtectionDomain().getCodeSource().getLocation().toURI());
String command = javaBinary
+ " -Duser.dir=\"" + jar.getParentFile().getAbsolutePath() + "\""
+ " -jar \"" + jar.getAbsolutePath() + "\""
+ " --service \"" + config + "\"";
StringBuilder dep = new StringBuilder();
if (dependencies != null) {
for (String s : dependencies) {
dep.append(s);
dep.append("\0");
}
}
dep.append("\0");
SERVICE_DESCRIPTION desc = new SERVICE_DESCRIPTION();
desc.lpDescription = description;
SC_HANDLE serviceManager = openServiceControlManager(null, Winsvc.SC_MANAGER_ALL_ACCESS);
if (serviceManager != null) {
SC_HANDLE service = ADVAPI_32.CreateService(serviceManager, serviceName, displayName,
Winsvc.SERVICE_ALL_ACCESS, WinNT.SERVICE_WIN32_OWN_PROCESS, WinNT.SERVICE_AUTO_START,
WinNT.SERVICE_ERROR_NORMAL,
command,
null, null, dep.toString(), account, password);
if (service != null) {
ADVAPI_32.ChangeServiceConfig2(service, Winsvc.SERVICE_CONFIG_DESCRIPTION, desc);
ADVAPI_32.CloseServiceHandle(service);
}
ADVAPI_32.CloseServiceHandle(serviceManager);
}
} | CWE-428 | 77 |
public PersistedMapper persistMapper(String sessionId, String mapperId, Serializable mapper, int expirationTime) {
PersistedMapper m = new PersistedMapper();
m.setMapperId(mapperId);
Date currentDate = new Date();
m.setLastModified(currentDate);
if(expirationTime > 0) {
Calendar cal = Calendar.getInstance();
cal.setTime(currentDate);
cal.add(Calendar.SECOND, expirationTime);
m.setExpirationDate(cal.getTime());
}
m.setOriginalSessionId(sessionId);
String configuration = XStreamHelper.createXStreamInstance().toXML(mapper);
m.setXmlConfiguration(configuration);
dbInstance.getCurrentEntityManager().persist(m);
return m;
} | CWE-91 | 78 |
public Document read(File file) throws DocumentException {
try {
/*
* We cannot convert the file to an URL because if the filename
* contains '#' characters, there will be problems with the URL in
* the InputSource (because a URL like
* http://myhost.com/index#anchor is treated the same as
* http://myhost.com/index) Thanks to Christian Oetterli
*/
InputSource source = new InputSource(new FileInputStream(file));
if (this.encoding != null) {
source.setEncoding(this.encoding);
}
String path = file.getAbsolutePath();
if (path != null) {
// Code taken from Ant FileUtils
StringBuffer sb = new StringBuffer("file://");
// add an extra slash for filesystems with drive-specifiers
if (!path.startsWith(File.separator)) {
sb.append("/");
}
path = path.replace('\\', '/');
sb.append(path);
source.setSystemId(sb.toString());
}
return read(source);
} catch (FileNotFoundException e) {
throw new DocumentException(e.getMessage(), e);
}
} | CWE-611 | 13 |
public void configure(ServletContextHandler context) {
context.setContextPath("/");
context.getSessionHandler().setMaxInactiveInterval(serverConfig.getSessionTimeout());
context.setInitParameter(EnvironmentLoader.ENVIRONMENT_CLASS_PARAM, DefaultWebEnvironment.class.getName());
context.addEventListener(new EnvironmentLoaderListener());
context.addFilter(new FilterHolder(shiroFilter), "/*", EnumSet.allOf(DispatcherType.class));
context.addFilter(new FilterHolder(gitFilter), "/*", EnumSet.allOf(DispatcherType.class));
context.addServlet(new ServletHolder(preReceiveServlet), GitPreReceiveCallback.PATH + "/*");
context.addServlet(new ServletHolder(postReceiveServlet), GitPostReceiveCallback.PATH + "/*");
/*
* Add wicket servlet as the default servlet which will serve all requests failed to
* match a path pattern
*/
context.addServlet(new ServletHolder(wicketServlet), "/");
context.addServlet(new ServletHolder(attachmentUploadServlet), "/attachment_upload");
context.addServlet(new ServletHolder(new ClasspathAssetServlet(ImageScope.class)), "/img/*");
context.addServlet(new ServletHolder(new ClasspathAssetServlet(IconScope.class)), "/icon/*");
context.getSessionHandler().addEventListener(new HttpSessionListener() {
@Override
public void sessionCreated(HttpSessionEvent se) {
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
webSocketManager.onDestroySession(se.getSession().getId());
}
});
/*
* Configure a servlet to serve contents under site folder. Site folder can be used
* to hold site specific web assets.
*/
ServletHolder fileServletHolder = new ServletHolder(new FileAssetServlet(Bootstrap.getSiteDir()));
context.addServlet(fileServletHolder, "/site/*");
context.addServlet(fileServletHolder, "/robots.txt");
context.addServlet(new ServletHolder(jerseyServlet), "/rest/*");
} | CWE-502 | 15 |
public Controller execute(FolderComponent folderComponent, UserRequest ureq, WindowControl wControl, Translator trans) {
VFSContainer currentContainer = folderComponent.getCurrentContainer();
status = FolderCommandHelper.sanityCheck(wControl, folderComponent);
if(status == FolderCommandStatus.STATUS_FAILED) {
return null;
}
FileSelection selection = new FileSelection(ureq, folderComponent.getCurrentContainerPath());
status = FolderCommandHelper.sanityCheck3(wControl, folderComponent, selection);
if(status == FolderCommandStatus.STATUS_FAILED) {
return null;
}
if(selection.getFiles().isEmpty()) {
status = FolderCommandStatus.STATUS_FAILED;
wControl.setWarning(trans.translate("warning.file.selection.empty"));
return null;
}
MediaResource mr = new ZipMediaResource(currentContainer, selection);
ureq.getDispatchResult().setResultingMediaResource(mr);
return null;
} | CWE-22 | 2 |
public static void initializeSsl() {
try {
SSLContext sc = SSLContext.getInstance(SSL);
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw ErrorUtil.createCommandException("initializing SSL failed: " + e.getMessage());
}
} | CWE-306 | 79 |
private Style getStyleState() {
return StyleSignatureBasic.of(SName.root, SName.element, SName.stateDiagram, SName.state).withTOBECHANGED(group.getStereotype())
.getMergedStyle(diagram.getSkinParam().getCurrentStyleBuilder());
} | CWE-918 | 16 |
void requestResetPassword() throws Exception
{
when(this.authorizationManager.hasAccess(Right.PROGRAM)).thenReturn(true);
UserReference userReference = mock(UserReference.class);
ResetPasswordRequestResponse requestResponse = mock(ResetPasswordRequestResponse.class);
when(this.resetPasswordManager.requestResetPassword(userReference)).thenReturn(requestResponse);
InternetAddress userEmail = new InternetAddress("[email protected]");
when(requestResponse.getUserEmail()).thenReturn(userEmail);
assertEquals(userEmail, this.scriptService.requestResetPassword(userReference));
verify(this.resetPasswordManager).sendResetPasswordEmailRequest(requestResponse);
} | CWE-640 | 20 |
public int decryptWithAd(byte[] ad, byte[] ciphertext,
int ciphertextOffset, byte[] plaintext, int plaintextOffset,
int length) throws ShortBufferException, BadPaddingException {
int space;
if (ciphertextOffset > ciphertext.length)
space = 0;
else
space = ciphertext.length - ciphertextOffset;
if (length > space)
throw new ShortBufferException();
if (plaintextOffset > plaintext.length)
space = 0;
else
space = plaintext.length - plaintextOffset;
if (!haskey) {
// The key is not set yet - return the ciphertext as-is.
if (length > space)
throw new ShortBufferException();
if (plaintext != ciphertext || plaintextOffset != ciphertextOffset)
System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length);
return length;
}
if (length < 16)
Noise.throwBadTagException();
int dataLen = length - 16;
if (dataLen > space)
throw new ShortBufferException();
setup(ad);
poly.update(ciphertext, ciphertextOffset, dataLen);
finish(ad, dataLen);
int temp = 0;
for (int index = 0; index < 16; ++index)
temp |= (polyKey[index] ^ ciphertext[ciphertextOffset + dataLen + index]);
if ((temp & 0xFF) != 0)
Noise.throwBadTagException();
encrypt(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen);
return dataLen;
} | CWE-787 | 24 |
public boolean updateConfiguration(String mapperId, Serializable mapper, int expirationTime) {
String configuration = XStreamHelper.createXStreamInstance().toXML(mapper);
Date currentDate = new Date();
Date expirationDate = null;
if(expirationTime > 0) {
Calendar cal = Calendar.getInstance();
cal.setTime(currentDate);
cal.add(Calendar.SECOND, expirationTime);
expirationDate = cal.getTime();
}
int row = dbInstance.getCurrentEntityManager().createNamedQuery("updateMapperByMapperId")
.setParameter("now", currentDate)
.setParameter("expirationDate", expirationDate)
.setParameter("config", configuration)
.setParameter("mapperId", mapperId)
.executeUpdate();
dbInstance.commit();
return row > 0;
} | CWE-91 | 78 |
public void setMergeAdjacentText(boolean mergeAdjacentText) {
this.mergeAdjacentText = mergeAdjacentText;
} | CWE-611 | 13 |
void shouldNotDecodeSlash() {
final PathAndQuery res = PathAndQuery.parse("%2F?%2F");
// Do not accept a relative path.
assertThat(res).isNull();
final PathAndQuery res1 = PathAndQuery.parse("/%2F?%2F");
assertThat(res1).isNotNull();
assertThat(res1.path()).isEqualTo("/%2F");
assertThat(res1.query()).isEqualTo("%2F");
final PathAndQuery pathOnly = PathAndQuery.parse("/foo%2F");
assertThat(pathOnly).isNotNull();
assertThat(pathOnly.path()).isEqualTo("/foo%2F");
assertThat(pathOnly.query()).isNull();
final PathAndQuery queryOnly = PathAndQuery.parse("/?%2f=%2F");
assertThat(queryOnly).isNotNull();
assertThat(queryOnly.path()).isEqualTo("/");
assertThat(queryOnly.query()).isEqualTo("%2F=%2F");
} | CWE-22 | 2 |
private void securityCheck(String filename) {
Assert.doesNotContain(filename, "..");
} | CWE-22 | 2 |
public static XStream createXStreamInstanceForDBObjects() {
return new EnhancedXStream(true);
} | CWE-91 | 78 |
public InternetAddress requestResetPassword(UserReference user) throws ResetPasswordException
{
if (this.authorizationManager.hasAccess(Right.PROGRAM)) {
ResetPasswordRequestResponse resetPasswordRequestResponse =
this.resetPasswordManager.requestResetPassword(user);
this.resetPasswordManager.sendResetPasswordEmailRequest(resetPasswordRequestResponse);
return resetPasswordRequestResponse.getUserEmail();
} else {
return null;
}
} | CWE-640 | 20 |
public void testCycle_ECDH_ES_Curve_P256_attackPoint1()
throws Exception {
ECKey ecJWK = generateECJWK(ECKey.Curve.P_256);
BigInteger privateReceiverKey = ecJWK.toECPrivateKey().getS();
JWEHeader header = new JWEHeader.Builder(JWEAlgorithm.ECDH_ES,
EncryptionMethod.A128GCM)
.agreementPartyUInfo(Base64URL.encode("Alice"))
.agreementPartyVInfo(Base64URL.encode("Bob"))
.build();
// attacking point #1 with order 113 //
BigInteger attackerOrderGroup1 = new BigInteger("113");
BigInteger receiverPrivateKeyModAttackerOrderGroup1 = privateReceiverKey
.mod(attackerOrderGroup1);
// System.out.println("The receiver private key is equal to "
// + receiverPrivateKeyModAttackerOrderGroup1 + " mod "
// + attackerOrderGroup1);
// The malicious JWE contains a public key with order 113
String maliciousJWE1 = "eyJhbGciOiJFQ0RILUVTK0ExMjhLVyIsImVuYyI6IkExMjhDQkMtSFMyNTYiLCJlcGsiOnsia3R5IjoiRUMiLCJ4IjoiZ1RsaTY1ZVRRN3otQmgxNDdmZjhLM203azJVaURpRzJMcFlrV0FhRkpDYyIsInkiOiJjTEFuakthNGJ6akQ3REpWUHdhOUVQclJ6TUc3ck9OZ3NpVUQta2YzMEZzIiwiY3J2IjoiUC0yNTYifX0.qGAdxtEnrV_3zbIxU2ZKrMWcejNltjA_dtefBFnRh9A2z9cNIqYRWg.pEA5kX304PMCOmFSKX_cEg.a9fwUrx2JXi1OnWEMOmZhXd94-bEGCH9xxRwqcGuG2AMo-AwHoljdsH5C_kcTqlXS5p51OB1tvgQcMwB5rpTxg.72CHiYFecyDvuUa43KKT6w";
JWEObject jweObject1 = JWEObject.parse(maliciousJWE1);
ECDHDecrypter decrypter = new ECDHDecrypter(ecJWK.toECPrivateKey());
// decrypter.getJCAContext().setKeyEncryptionProvider(BouncyCastleProviderSingleton.getInstance());
try {
jweObject1.decrypt(decrypter);
fail();
} catch (JOSEException e) {
assertEquals("Invalid ephemeral public key: Point not on expected curve", e.getMessage());
}
// this proof that receiverPrivateKey is equals 26 % 113
// assertEquals("Gambling is illegal at Bushwood sir, and I never slice.",
// jweObject1.getPayload().toString());
// THIS CAN BE DOIN MANY TIME
// ....
// AND THAN CHINESE REMAINDER THEOREM FTW
} | CWE-347 | 25 |
private boolean isFileWithinDirectory(
final File dir,
final File file
) throws IOException {
final File dir_ = dir.getAbsoluteFile();
if (dir_.isDirectory()) {
final File fl = new File(dir_, file.getPath());
if (fl.isFile()) {
if (fl.getCanonicalPath().startsWith(dir_.getCanonicalPath())) {
// Prevent accessing files outside the load-path.
// E.g.: ../../coffee
return true;
}
}
}
return false;
} | CWE-22 | 2 |
public SAXReader(String xmlReaderClassName) throws SAXException {
if (xmlReaderClassName != null) {
this.xmlReader = XMLReaderFactory
.createXMLReader(xmlReaderClassName);
}
} | CWE-611 | 13 |
public boolean isIncludeExternalDTDDeclarations() {
return includeExternalDTDDeclarations;
} | CWE-611 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.