text
stringlengths
81
112k
Reads a cronjob from the database. def ReadCronJobs(self, cronjob_ids=None): """Reads a cronjob from the database.""" if cronjob_ids is None: res = [job.Copy() for job in itervalues(self.cronjobs)] else: res = [] for job_id in cronjob_ids: try: res.append(self.cronjobs[...
Updates run information for an existing cron job. def UpdateCronJob(self, cronjob_id, last_run_status=db.Database.unchanged, last_run_time=db.Database.unchanged, current_run_id=db.Database.unchanged, state=db.Database.u...
Enables a cronjob. def EnableCronJob(self, cronjob_id): """Enables a cronjob.""" job = self.cronjobs.get(cronjob_id) if job is None: raise db.UnknownCronJobError("Cron job %s not known." % cronjob_id) job.enabled = True
Disables a cronjob. def DisableCronJob(self, cronjob_id): """Disables a cronjob.""" job = self.cronjobs.get(cronjob_id) if job is None: raise db.UnknownCronJobError("Cron job %s not known." % cronjob_id) job.enabled = False
Deletes a cronjob along with all its runs. def DeleteCronJob(self, cronjob_id): """Deletes a cronjob along with all its runs.""" if cronjob_id not in self.cronjobs: raise db.UnknownCronJobError("Cron job %s not known." % cronjob_id) del self.cronjobs[cronjob_id] try: del self.cronjob_leases...
Leases all available cron jobs. def LeaseCronJobs(self, cronjob_ids=None, lease_time=None): """Leases all available cron jobs.""" leased_jobs = [] now = rdfvalue.RDFDatetime.Now() expiration_time = now + lease_time for job in itervalues(self.cronjobs): if cronjob_ids and job.cron_job_id not...
Makes leased cron jobs available for leasing again. def ReturnLeasedCronJobs(self, jobs): """Makes leased cron jobs available for leasing again.""" errored_jobs = [] for returned_job in jobs: existing_lease = self.cronjob_leases.get(returned_job.cron_job_id) if existing_lease is None: ...
Stores a cron job run object in the database. def WriteCronJobRun(self, run_object): """Stores a cron job run object in the database.""" if run_object.cron_job_id not in self.cronjobs: raise db.UnknownCronJobError("Job with id %s not found." % run_object.cron_job_id) ...
Reads all cron job runs for a given job id. def ReadCronJobRuns(self, job_id): """Reads all cron job runs for a given job id.""" runs = [ run for run in itervalues(self.cronjob_runs) if run.cron_job_id == job_id ] return sorted(runs, key=lambda run: run.started_at, reverse=True)
Reads a single cron job run from the db. def ReadCronJobRun(self, job_id, run_id): """Reads a single cron job run from the db.""" for run in itervalues(self.cronjob_runs): if run.cron_job_id == job_id and run.run_id == run_id: return run raise db.UnknownCronJobRunError( "Run with job ...
Deletes cron job runs for a given job id. def DeleteOldCronJobRuns(self, cutoff_timestamp): """Deletes cron job runs for a given job id.""" deleted = 0 for run in list(itervalues(self.cronjob_runs)): if run.timestamp < cutoff_timestamp: del self.cronjob_runs[(run.cron_job_id, run.run_id)] ...
Upload a signed blob into the datastore. Args: content: File content to upload. aff4_path: aff4 path to upload to. client_context: The configuration contexts to use. limit: The maximum size of the chunk to use. token: A security token. Raises: IOError: On failure to write. def UploadSigne...
This function creates and installs a new server key. Note that - Clients might experience intermittent connection problems after the server keys rotated. - It's not possible to go back to an earlier key. Clients that see a new certificate will remember the cert's serial number and refuse to accept ...
Checks access to a given subject by a given user. def _CheckAccess(self, username, subject_id, approval_type): """Checks access to a given subject by a given user.""" precondition.AssertType(subject_id, Text) cache_key = (username, subject_id, approval_type) try: self.acl_cache.Get(cache_key) ...
Checks whether a given user can access given client. def CheckClientAccess(self, username, client_id): """Checks whether a given user can access given client.""" self._CheckAccess( username, str(client_id), rdf_objects.ApprovalRequest.ApprovalType.APPROVAL_TYPE_CLIENT)
Checks whether a given user can access given hunt. def CheckHuntAccess(self, username, hunt_id): """Checks whether a given user can access given hunt.""" self._CheckAccess( username, str(hunt_id), rdf_objects.ApprovalRequest.ApprovalType.APPROVAL_TYPE_HUNT)
Checks whether a given user can access given cron job. def CheckCronJobAccess(self, username, cron_job_id): """Checks whether a given user can access given cron job.""" self._CheckAccess( username, str(cron_job_id), rdf_objects.ApprovalRequest.ApprovalType.APPROVAL_TYPE_CRON_JOB)
Checks whether a given user can start a given flow. def CheckIfCanStartClientFlow(self, username, flow_name): """Checks whether a given user can start a given flow.""" del username # Unused. flow_cls = flow.GRRFlow.GetPlugin(flow_name) if not flow_cls.category: raise access_control.Unauthorize...
Checks whether the user is an admin. def CheckIfUserIsAdmin(self, username): """Checks whether the user is an admin.""" user_obj = data_store.REL_DB.ReadGRRUser(username) if user_obj.user_type != user_obj.UserType.USER_TYPE_ADMIN: raise access_control.UnauthorizedAccess("User %s is not an admin." % ...
Whether the conditions applies, modulo host data. Args: os_name: An OS string. cpe: A CPE string. label: A label string. Returns: True if os_name, cpe or labels match. Empty values are ignored. def Artifacts(self, os_name=None, cpe=None, label=None): """Whether the conditions appl...
Whether the condition contains the specified values. Args: artifact: A string identifier for the artifact. os_name: An OS string. cpe: A CPE string. label: A label string. Returns: True if the values match the non-empty query attributes. Empty query attributes are ignored i...
Map functions that should be called if the condition applies. def _Register(self, conditions, callback): """Map functions that should be called if the condition applies.""" for condition in conditions: registered = self._registry.setdefault(condition, []) if callback and callback not in registered:...
Add criteria for a check. Args: artifact: An artifact name. target: A tuple of artifact necessary to process the data. callback: Entities that should be called if the condition matches. def Add(self, artifact=None, target=None, callback=None): """Add criteria for a check. Args: ar...
Adds existing triggers to this set, optionally rebuilding the registry. Used to aggregate trigger methods from Probes to Methods to Checks. Args: other: Another Triggers object. callback: Registers all the updated triggers to the specified function. def Update(self, other, callback): """Adds ...
Test if host data should trigger a check. Args: artifact: An artifact name. os_name: An OS string. cpe: A CPE string. label: A label string. Returns: A list of conditions that match. def Match(self, artifact=None, os_name=None, cpe=None, label=None): """Test if host data sho...
Find the host attributes that trigger data collection. Args: artifact: An artifact name. os_name: An OS string. cpe: A CPE string. label: A label string. Returns: A list of conditions that contain the specified attributes. def Search(self, artifact=None, os_name=None, cpe=None, ...
Find the artifacts that correspond with other trigger conditions. Args: os_name: An OS string. cpe: A CPE string. label: A label string. Returns: A list of artifacts to be processed. def Artifacts(self, os_name=None, cpe=None, label=None): """Find the artifacts that correspond wit...
Find the methods that evaluate data that meets this condition. Args: conditions: A tuple of (artifact, os_name, cpe, label) Returns: A list of methods that evaluate the data. def Calls(self, conditions=None): """Find the methods that evaluate data that meets this condition. Args: c...
Returns plugins' metadata in ApiReportDescriptor. def GetReportDescriptor(cls): """Returns plugins' metadata in ApiReportDescriptor.""" if cls.TYPE is None: raise ValueError("%s.TYPE is unintialized." % cls) if cls.TITLE is None: raise ValueError("%s.TITLE is unintialized." % cls) if cls....
Make a cert and sign it with the CA's private key. def MakeCASignedCert(common_name, private_key, ca_cert, ca_private_key, serial_number=2): """Make a cert and sign it with the CA's private key.""" public_key = private_key.GetPubli...
Generate a CA certificate. Args: private_key: The private key to use. common_name: Name for cert. issuer_cn: Name for issuer. issuer_c: Country for issuer. Returns: The certificate. def MakeCACert(private_key, common_name=u"grr", issuer_cn=u"grr_test", ...
Returns AuditEvents for given handlers, actions, and timerange. def _LoadAuditEvents(handlers, get_report_args, actions=None, token=None, transformers=None): """Returns AuditEvents for given handlers, actions, and timerange.""" if ...
Converts an APIAuditEntry to a legacy AuditEvent. def _EntryToEvent(entry, handlers, transformers): """Converts an APIAuditEntry to a legacy AuditEvent.""" event = rdf_events.AuditEvent( timestamp=entry.timestamp, user=entry.username, action=handlers[entry.router_method_name]) for fn in transf...
Extracts a Client ID from an APIAuditEntry's HTTP request path. def _ExtractClientIdFromPath(entry, event): """Extracts a Client ID from an APIAuditEntry's HTTP request path.""" match = re.match(r".*(C\.[0-9a-fA-F]{16}).*", entry.http_request_path) if match: event.client = match.group(1)
Extracts a CronJob ID from an APIAuditEntry's HTTP request path. def _ExtractCronJobIdFromPath(entry, event): """Extracts a CronJob ID from an APIAuditEntry's HTTP request path.""" match = re.match(r".*cron-job/([^/]+).*", entry.http_request_path) if match: event.urn = "aff4:/cron/{}".format(match.group(1))
Extracts a Hunt ID from an APIAuditEntry's HTTP request path. def _ExtractHuntIdFromPath(entry, event): """Extracts a Hunt ID from an APIAuditEntry's HTTP request path.""" match = re.match(r".*hunt/([^/]+).*", entry.http_request_path) if match: event.urn = "aff4:/hunts/{}".format(match.group(1))
Filter the cron job approvals in the given timerange. def GetReportData(self, get_report_args, token=None): """Filter the cron job approvals in the given timerange.""" ret = rdf_report_plugins.ApiReportData( representation_type=RepresentationType.AUDIT_CHART, audit_chart=rdf_report_plugins.ApiA...
Filter the last week of user actions. def GetReportData(self, get_report_args, token): """Filter the last week of user actions.""" ret = rdf_report_plugins.ApiReportData( representation_type=RepresentationType.PIE_CHART) counts = self._GetUserCounts(get_report_args, token) for username in aff4...
Filter the last week of user actions. def GetReportData(self, get_report_args, token): """Filter the last week of user actions.""" ret = rdf_report_plugins.ApiReportData( representation_type=RepresentationType.STACK_CHART) week_duration = rdfvalue.Duration("7d") num_weeks = math.ceil(get_repor...
Returns the corresponding AFF4 attribute for the given report type. def _GetAFF4AttributeForReportType(report_type ): """Returns the corresponding AFF4 attribute for the given report type.""" if report_type == rdf_stats.ClientGraphSeries.ReportType.GRR_VERSION: return aff4_sta...
Writes graph series for a particular client label to the DB. Args: graph_series: A series of rdf_stats.Graphs containing aggregated data for a particular report-type. label: Client label by which data in the graph_series was aggregated. token: ACL token to use for writing to the legacy (non-relatio...
Fetches graph series for the given label and report-type from the DB. Args: label: Client label to fetch data for. report_type: rdf_stats.ClientGraphSeries.ReportType to fetch data for. period: rdfvalue.Duration specifying how far back in time to fetch data. If not provided, all data for the given ...
Fetches graph-series from the legacy DB [see FetchAllGraphSeries()]. def _FetchAllGraphSeriesFromTheLegacyDB( label, report_type, period = None, token = None ): """Fetches graph-series from the legacy DB [see FetchAllGraphSeries()].""" if period is None: time_range = aff4.ALL_TIMES else: ...
Fetches the latest graph series for a client label from the DB. Args: label: Client label to fetch data for. report_type: rdf_stats.ClientGraphSeries.ReportType to fetch data for. token: ACL token to use for reading from the legacy (non-relational) datastore. Raises: AFF4AttributeTypeError: ...
Fetches the latest graph-series for a client label from the legacy DB. Args: label: Client label to fetch data for. report_type: rdf_stats.ClientGraphSeries.ReportType to fetch data for. token: ACL token to use for reading from the DB. Raises: AFF4AttributeTypeError: If an unexpected report-data t...
Generates a new, unique task_id. def GenerateTaskID(self): """Generates a new, unique task_id.""" # Random number can not be zero since next_id_base must increment. random_number = random.PositiveUInt16() # 16 bit random numbers with GrrMessage.lock: next_id_base = GrrMessage.next_id_base ...
The payload property automatically decodes the encapsulated data. def payload(self): """The payload property automatically decodes the encapsulated data.""" if self.args_rdf_name: # Now try to create the correct RDFValue. result_cls = self.classes.get(self.args_rdf_name, rdfvalue.RDFString) ...
Automatically encode RDFValues into the message. def payload(self, value): """Automatically encode RDFValues into the message.""" if not isinstance(value, rdfvalue.RDFValue): raise RuntimeError("Payload must be an RDFValue.") self.Set("args", value.SerializeToString()) # pylint: disable=protect...
Adds new files consisting of given blob references. Args: client_path_blob_refs: A dictionary mapping `db.ClientPath` instances to lists of blob references. use_external_stores: A flag indicating if the files should also be added to external file stores. Returns: A dictionary mapping `db.C...
Add a new file consisting of given blob IDs. def AddFileWithUnknownHash(client_path, blob_refs, use_external_stores=True): """Add a new file consisting of given blob IDs.""" precondition.AssertType(client_path, db.ClientPath) precondition.AssertIterableType(blob_refs, rdf_objects.BlobReference) return AddFiles...
Checks if files with given hashes are present in the file store. Args: hash_ids: A list of SHA256HashID objects. Returns: A dict where SHA256HashID objects are keys. Corresponding values may be False (if hash id is not present) or True if it is not present. def CheckHashes(hash_ids): """Checks if f...
Opens latest content of a given file for reading. Args: client_path: A db.ClientPath object describing path to a file. max_timestamp: If specified, will open the last collected version with a timestamp equal or lower than max_timestamp. If not specified, will simply open the latest version. Re...
Streams contents of given files. Args: client_paths: db.ClientPath objects describing paths to files. max_timestamp: If specified, then for every requested file will open the last collected version of the file with a timestamp equal or lower than max_timestamp. If not specified, will simply open ...
Adds multiple files to the file store. Args: hash_id_metadatas: A dictionary mapping hash ids to file metadata (a tuple of hash client path and blob references). def AddFiles(self, hash_id_metadatas): """Adds multiple files to the file store. Args: hash_id_metadatas: A dictionary mapp...
Fetches a chunk corresponding to the current offset. def _GetChunk(self): """Fetches a chunk corresponding to the current offset.""" found_ref = None for ref in self._blob_refs: if self._offset >= ref.offset and self._offset < (ref.offset + ref.size): found_ref = ref break if no...
Reads data. def Read(self, length=None): """Reads data.""" if length is None: length = self._length - self._offset if length > self._max_unbound_read: raise OversizedReadError("Attempted to read %d bytes when " "Server.max_unbound_read_size is %d" % ...
Moves the reading cursor. def Seek(self, offset, whence=os.SEEK_SET): """Moves the reading cursor.""" if whence == os.SEEK_SET: self._offset = offset elif whence == os.SEEK_CUR: self._offset += offset elif whence == os.SEEK_END: self._offset = self._length + offset else: ra...
Uploads chunks of a file on a given path to the transfer store flow. Args: filepath: A path to the file to upload. offset: An integer offset at which the file upload should start on. amount: An upper bound on number of bytes to stream. If it is `None` then the whole file is uploaded. ...
Uploads chunks of a given file descriptor to the transfer store flow. Args: fd: A file descriptor to upload. offset: An integer offset at which the file upload should start on. amount: An upper bound on number of bytes to stream. If it is `None` then the whole file is uploaded. Retur...
Uploads a single chunk to the transfer store flow. Args: chunk: A chunk to upload. Returns: A `BlobImageChunkDescriptor` object. def _UploadChunk(self, chunk): """Uploads a single chunk to the transfer store flow. Args: chunk: A chunk to upload. Returns: A `BlobImageChun...
Instantiate a rdf_stats.Distribution from a Prometheus Histogram. Prometheus Histogram uses cumulative "buckets" lower or equal to an upper bound. At instantiation, +Inf is implicitly appended to the upper bounds. The delimiters [0.0, 0.1, 0.2 (, +Inf)] produce the following buckets: Bucket "0.0" : -Inf <= val...
Parse the crontab file. def Parse(self, stat, file_object, knowledge_base): """Parse the crontab file.""" _ = knowledge_base entries = [] crondata = file_object.read().decode("utf-8") jobs = crontab.CronTab(tab=crondata) for job in jobs: entries.append( rdf_cronjobs.CronTabEnt...
Parses the file finder condition types into the condition objects. Args: conditions: An iterator over `FileFinderCondition` objects. Yields: `MetadataCondition` objects that correspond to the file-finder conditions. def Parse(conditions): """Parses the file finder condition types into the con...
Parses the file finder condition types into the condition objects. Args: conditions: An iterator over `FileFinderCondition` objects. Yields: `ContentCondition` objects that correspond to the file-finder conditions. def Parse(conditions): """Parses the file finder condition types into the cond...
Scans given file searching for occurrences of given pattern. Args: fd: A file descriptor of the file that needs to be searched. matcher: A matcher object specifying a pattern to search for. Yields: `BufferReference` objects pointing to file parts with matching content. def Scan(self, fd, ...
Initialize the server logging configuration. def ServerLoggingStartupInit(): """Initialize the server logging configuration.""" global LOGGER if local_log: logging.debug("Using local LogInit from %s", local_log) local_log.LogInit() logging.debug("Using local AppLogInit from %s", local_log) LOGGER...
Return a unique Event ID string. def GetNewEventId(self, event_time=None): """Return a unique Event ID string.""" if event_time is None: event_time = int(time.time() * 1e6) return "%s:%s:%s" % (event_time, socket.gethostname(), os.getpid())
Log an http based api call. Args: request: A WSGI request object. response: A WSGI response object. def LogHttpAdminUIAccess(self, request, response): """Log an http based api call. Args: request: A WSGI request object. response: A WSGI response object. """ # TODO(user): g...
Write a log entry for a Frontend or UI Request. Args: request: A HttpRequest protobuf. source: Client id of the client initiating the request. Optional. message_count: Number of messages received from the client. Optional. def LogHttpFrontendAccess(self, request, source=None, message_count=None)...
A wrapper for the `pkg_resource.resource_filename` function. def _GetPkgResources(package_name, filepath): """A wrapper for the `pkg_resource.resource_filename` function.""" requirement = pkg_resources.Requirement.parse(package_name) try: return pkg_resources.resource_filename(requirement, filepath) except...
Computes a path to the specified package resource. Args: package_name: A name of the package where the resource is located. filepath: A path to the resource relative to the package location. Returns: A path to the resource or `None` if the resource cannot be found. def ResourcePath(package_name, file...
Computes a path to the specified module. Args: module_name: A name of the module to get the path for. Returns: A path to the specified module. Raises: ImportError: If specified module cannot be imported. def ModulePath(module_name): """Computes a path to the specified module. Args: module...
Function call rate-limiting decorator. This decorator ensures that the wrapped function will be called at most once in min_time_between_calls time for the same set of arguments. For all excessive calls a previous cached return value will be returned. Suppose we use the decorator like this: @cache.WithLimite...
Converts (field-name, type) tuples to MetricFieldDefinition protos. def FieldDefinitionProtosFromTuples(field_def_tuples): """Converts (field-name, type) tuples to MetricFieldDefinition protos.""" # TODO: This needs fixing for Python 3. field_def_protos = [] for field_name, field_type in field_def_tuples: ...
Converts MetricFieldDefinition protos to (field-name, type) tuples. def FieldDefinitionTuplesFromProtos(field_def_protos): """Converts MetricFieldDefinition protos to (field-name, type) tuples.""" # TODO: This needs fixing for Python 3. field_def_tuples = [] for proto in field_def_protos: if proto.field_ty...
Converts Python types to MetricMetadata.ValueType enum values. def MetricValueTypeFromPythonType(python_type): """Converts Python types to MetricMetadata.ValueType enum values.""" if python_type in (int, long): return rdf_stats.MetricMetadata.ValueType.INT elif python_type == float: return rdf_stats.Metr...
Converts MetricMetadata.ValueType enums to corresponding Python types. def PythonTypeFromMetricValueType(value_type): """Converts MetricMetadata.ValueType enums to corresponding Python types.""" if value_type == rdf_stats.MetricMetadata.ValueType.INT: return int elif value_type == rdf_stats.MetricMetadata.Va...
Helper function for creating MetricMetadata for counter metrics. def CreateCounterMetadata(metric_name, fields=None, docstring=None, units=None): """Helper function for creating MetricMetadata for counter metrics.""" return rdf_stats.MetricMetadata( varname=metric_name, metric_type=rdf_stats.MetricMeta...
Helper function for creating MetricMetadata for event metrics. def CreateEventMetadata(metric_name, bins=None, fields=None, docstring=None, units=None): """Helper function for creating MetricMetadata for event metrics."""...
Helper function for creating MetricMetadata for gauge metrics. def CreateGaugeMetadata(metric_name, value_type, fields=None, docstring=None, units=None): """Helper function for creating MetricMetadata for gauge metrics.""...
Import hashes from 'filename' into 'store'. def ImportFile(store, filename, start): """Import hashes from 'filename' into 'store'.""" with io.open(filename, "r") as fp: reader = csv.Reader(fp.read()) i = 0 current_row = None product_code_list = [] op_system_code_list = [] for row in reader:...
Main. def main(argv): """Main.""" del argv # Unused. server_startup.Init() filename = flags.FLAGS.filename if not os.path.exists(filename): print("File %s does not exist" % filename) return with aff4.FACTORY.Create( filestore.NSRLFileStore.PATH, filestore.NSRLFileStore, mode="r...
r"""Converts the canonical paths as used by GRR to OS specific paths. Due to the inconsistencies between handling paths in windows we need to convert a path to an OS specific version prior to using it. This function should be called just before any OS specific functions. Canonical paths on windows have: -...
Converts path from the local system's convention to the canonical. def LocalPathToCanonicalPath(path): """Converts path from the local system's convention to the canonical.""" path_components = path.split("/") result = [] for component in path_components: # Devices must maintain their \\ so they do not get...
Provide chmod-like functionality for windows. Doco links: goo.gl/n7YR1 goo.gl/rDv81 goo.gl/hDobb Args: filename: target filename for acl acl_list: list of ntsecuritycon acl strings to be applied with bitwise OR. e.g. ["FILE_GENERIC_READ", "FILE_GENERIC_WRITE"] user: usernam...
Tries to find proxies by interrogating all the user's settings. This function is a modified urillib.getproxies_registry() from the standard library. We just store the proxy value in the environment for urllib to find it. TODO(user): Iterate through all the possible values if one proxy fails, in case more th...
Resolves the raw device that contains the path. Args: path: A path to examine. Returns: A pathspec to read the raw device as well as the modified path to read within the raw device. This is usually the path without the mount point. Raises: IOError: if the path does not exist or some unexpected ...
Returns the service key. def _GetServiceKey(): """Returns the service key.""" global _service_key if _service_key is None: hive = getattr(winreg, config.CONFIG["Client.config_hive"]) path = config.CONFIG["Client.config_key"] # Don't use winreg.KEY_WOW64_64KEY since it breaks on Windows 2000 _se...
Wraps the lowlevel RtlGetVersion routine. Args: os_version_info_struct: instance of either a RTL_OSVERSIONINFOW structure or a RTL_OSVERSIONINFOEXW structure, ctypes.Structure-wrapped, with the dwOSVersionInfoSize field preset to...
Gets the kernel version as string, eg. "5.1.2600". Returns: The kernel version, or "unknown" in the case of failure. def KernelVersion(): """Gets the kernel version as string, eg. "5.1.2600". Returns: The kernel version, or "unknown" in the case of failure. """ rtl_osversioninfoexw = RtlOSVersionIn...
Writes a heartbeat to the registry. def Heartbeat(self): """Writes a heartbeat to the registry.""" service_key = _GetServiceKey() try: winreg.SetValueEx(service_key, "Nanny.heartbeat", 0, winreg.REG_DWORD, int(time.time())) except OSError as e: logging.debug("Failed ...
Write the message into the transaction log. Args: grr_message: A GrrMessage instance. def Write(self, grr_message): """Write the message into the transaction log. Args: grr_message: A GrrMessage instance. """ grr_message = grr_message.SerializeToString() try: winreg.SetValue...
Return a GrrMessage instance from the transaction log or None. def Get(self): """Return a GrrMessage instance from the transaction log or None.""" try: value, reg_type = winreg.QueryValueEx(_GetServiceKey(), "Transaction") except OSError: return if reg_type != winreg.REG_BINARY: retu...
Returns stat information about the given OS path, calling os.[l]stat. Args: path: A path to perform `stat` on. follow_symlink: True if `stat` of a symlink should be returned instead of a file that it points to. For non-symlinks this setting has no effect. Returns: Stat instance, with...
Fetches Linux extended file flags. def _FetchLinuxFlags(self): """Fetches Linux extended file flags.""" if platform.system() != "Linux": return 0 # Since we open a file in the next step we do not want to open a symlink. # `lsattr` returns an error when trying to check flags of a symlink, so we ...
Stats given file or returns a cached result if available. Args: path: A path to the file to perform `stat` on. follow_symlink: True if `stat` of a symlink should be returned instead of a file that it points to. For non-symlinks this setting has no effect. Returns: `Stat` object corre...
Get the classes that support parsing a given artifact. def GetClassesByArtifact(cls, artifact_name): """Get the classes that support parsing a given artifact.""" return [ cls.classes[c] for c in cls.classes if artifact_name in cls.classes[c].supported_artifacts ]
Generate RDFs for the fully expanded configs. Args: stats: A list of RDF StatEntries corresponding to the file_objects. file_objects: A list of file handles. Returns: A tuple of a list of RDFValue PamConfigEntries found & a list of strings which are the external config references found...
Return PamConfigEntries it finds as it recursively follows PAM configs. Args: service: A string containing the service name we are processing. path: A string containing the file path name we want. cache: A dictionary keyed on path, with the file contents (list of str). filter_type: A string...
Fingerprint a file. def Run(self, args): """Fingerprint a file.""" with vfs.VFSOpen( args.pathspec, progress_callback=self.Progress) as file_obj: fingerprinter = Fingerprinter(self.Progress, file_obj) response = rdf_client_action.FingerprintResponse() response.pathspec = file_obj.path...