Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# and remove it.
if self.safe_save:
tmp_path = path + '~'
else:
tmp_path = path
try:
with open(tmp_path, 'wb') as file:
file.write(self._get_text(encoding))
except UnicodeEncodeError:
# fallback to utf-8 in case of error.
with open(tmp_path, 'wb') as file:
file.write(self._get_text(fallback_encoding))
except (IOError, OSError) as e:
self._rm(tmp_path)
self.saving = False
self.editor.text_saved.emit(str(path))
raise e
# cache update encoding
Cache().set_file_encoding(path, encoding)
self._encoding = encoding
# remove path and rename temp file, if safe save is on
if self.safe_save:
self._rm(path)
os.rename(tmp_path, path)
self._rm(tmp_path)
# reset dirty flags
self.editor.document().setModified(False)
# remember path for next save
self._path = os.path.normpath(path)
self.editor.text_saved.emit(str(path))
self.saving = False
_logger().debug('file saved: %s', path)
def Handle(self, args, token=None):
reason = "Cancelled in GUI"
if data_store.RelationalDBEnabled():
flow_base.TerminateFlow(
str(args.client_id), str(args.flow_id), reason=reason)
else:
flow_urn = args.flow_id.ResolveClientFlowURN(args.client_id, token=token)
flow.GRRFlow.TerminateAFF4Flow(flow_urn, reason=reason, token=token)
"""Parses signed certificate data and updates result rdfvalue."""
try:
auth_data
except NameError:
# Verify_sigs is not available so we can't parse signatures. If you want
# this functionality, please install the verify-sigs package:
# https://github.com/anthrotype/verify-sigs
# TODO(amoser): Make verify-sigs a pip package and add a dependency.
return
try:
try:
auth = auth_data.AuthData(signed_data.certificate)
except Exception as e: # pylint: disable=broad-except
# If we failed to parse the certificate, we want the user to know it.
result.cert_hasher_name = "Error parsing certificate: %s" % str(e)
raise
result.cert_hasher_name = auth.digest_algorithm().name
result.cert_program_name = str(auth.program_name)
result.cert_program_url = str(auth.program_url)
result.cert_signing_id = str(auth.signing_cert_id)
try:
# This fills in auth.cert_chain_head. We ignore Asn1Error because
# we want to extract as much data as possible, no matter if the
# certificate has expired or not.
auth.ValidateCertChains(time.gmtime())
except auth_data.Asn1Error:
pass
result.cert_chain_head_issuer = str(auth.cert_chain_head[2])
def GenerateCSRFToken(user_id, time):
"""Generates a CSRF token based on a secret key, id and time."""
precondition.AssertType(user_id, Text)
precondition.AssertOptionalType(time, int)
time = time or rdfvalue.RDFDatetime.Now().AsMicrosecondsSinceEpoch()
secret = config.CONFIG.Get("AdminUI.csrf_secret_key", None)
if secret is None:
raise ValueError("CSRF secret not available.")
digester = hmac.new(secret.encode("ascii"), digestmod=hashlib.sha256)
digester.update(user_id.encode("ascii"))
digester.update(CSRF_DELIMITER)
digester.update(str(time).encode("ascii"))
digest = digester.digest()
token = base64.urlsafe_b64encode(b"%s%s%d" % (digest, CSRF_DELIMITER, time))
return token.rstrip(b"=")
def Handle(self, args, token=None):
flow_obj = data_store.REL_DB.ReadFlowObject(
str(args.client_id), str(args.flow_id))
index = GetOutputPluginIndex(flow_obj.output_plugins, args.plugin_id)
output_plugin_id = "%d" % index
logs = data_store.REL_DB.ReadFlowOutputPluginLogEntries(
str(args.client_id),
str(args.flow_id),
output_plugin_id,
args.offset,
args.count or db.MAX_COUNT,
with_type=self.__class__.log_entry_type)
total_count = data_store.REL_DB.CountFlowOutputPluginLogEntries(
str(args.client_id),
str(args.flow_id),
output_plugin_id,
with_type=self.__class__.log_entry_type)
def __repr__(self):
return "OR:(%s)" % (",".join(str(oper) for oper in self.operands))
def Handle(self, args, token=None):
job_id = str(args.cron_job_id)
cronjobs.CronManager().RequestForcedRun(job_id)
def Match(self, text):
if isinstance(text, rdfvalue.RDFString):
text = str(text)
return self._Regex().match(text)
def _get_cached_data(self, cache, func, duration, *args, **kwargs):
"""
Get data from a cache object
:param cache: cache object
:param func: function to cache
:param duration: cache duration
:param args: function args
:param kwargs: function kwargs
:return: function return data
"""
if duration <= 0:
raise ValueError('Caching duration cannot be zero or negative!')
current_time = time.time()
key = func.__name__ + str(args) + str(kwargs)
try:
data, timestamp = cache[key]
if current_time - timestamp > duration * 60:
raise KeyError
self.log_debug('Cache hit: {0}'.format(key))
except KeyError:
self.log_debug('Cache miss: {0}'.format(key))
data = func(*args, **kwargs)
cache[key] = (data, current_time)
return data
def Handle(self, args, token=None):
count = args.count or db.MAX_COUNT
logs = data_store.REL_DB.ReadFlowLogEntries(
str(args.client_id), str(args.flow_id), args.offset, count, args.filter)
total_count = data_store.REL_DB.CountFlowLogEntries(
str(args.client_id), str(args.flow_id))
return ApiListFlowLogsResult(
items=[
ApiFlowLog().InitFromFlowLogEntry(log, str(args.flow_id))
for log in logs
],
total_count=total_count)