text
stringlengths
81
112k
Flush all items from cache. def Flush(self): """Flush all items from cache.""" while self._age: node = self._age.PopLeft() self.KillObject(node.data) self._hash = dict()
Calculate the size of the struct. def GetSize(cls): """Calculate the size of the struct.""" format_str = "".join([x[0] for x in cls._fields]) return struct.calcsize(format_str)
Gets stream buffer since the last GetValueAndReset() call. def GetValueAndReset(self): """Gets stream buffer since the last GetValueAndReset() call.""" if not self._stream: raise ArchiveAlreadyClosedError( "Attempting to get a value from a closed stream.") value = self._stream.getvalue() ...
Generate ZipInfo instance for the given name, compression and stat. Args: arcname: The name in the archive this should take. compress_type: Compression type (zipfile.ZIP_DEFLATED, or ZIP_STORED) st: An optional stat object to be used for setting headers. Returns: ZipInfo instance. ...
Writes a symlink into the archive. def WriteSymlink(self, src_arcname, dst_arcname): """Writes a symlink into the archive.""" # Inspired by: # http://www.mail-archive.com/python-list@python.org/msg34223.html if not self._stream: raise ArchiveAlreadyClosedError( "Attempting to write to ...
Writes a file header. def WriteFileHeader(self, arcname=None, compress_type=None, st=None): """Writes a file header.""" if not self._stream: raise ArchiveAlreadyClosedError( "Attempting to write to a ZIP archive that was already closed.") self.cur_zinfo = self._GenerateZipInfo( ar...
Writes file chunk. def WriteFileChunk(self, chunk): """Writes file chunk.""" precondition.AssertType(chunk, bytes) if not self._stream: raise ArchiveAlreadyClosedError( "Attempting to write to a ZIP archive that was already closed.") self.cur_file_size += len(chunk) # TODO(user):p...
Writes the file footer (finished the file). def WriteFileFooter(self): """Writes the file footer (finished the file).""" if not self._stream: raise ArchiveAlreadyClosedError( "Attempting to write to a ZIP archive that was already closed.") if self.cur_cmpr: buf = self.cur_cmpr.flush...
Write a zip member from a file like object. Args: src_fd: A file like object, must support seek(), tell(), read(). arcname: The name in the archive this should take. compress_type: Compression type (zipfile.ZIP_DEFLATED, or ZIP_STORED) st: An optional stat object to be used for setting head...
Writes a symlink into the archive. def WriteSymlink(self, src_arcname, dst_arcname): """Writes a symlink into the archive.""" info = self._tar_fd.tarinfo() info.tarfile = self._tar_fd info.name = SmartStr(dst_arcname) info.size = 0 info.mtime = time.time() info.type = tarfile.SYMTYPE i...
Writes file header. def WriteFileHeader(self, arcname=None, st=None): """Writes file header.""" if st is None: raise ValueError("Stat object can't be None.") self.cur_file_size = 0 self.cur_info = self._tar_fd.tarinfo() self.cur_info.tarfile = self._tar_fd self.cur_info.type = tarfile....
Writes file chunk. def WriteFileChunk(self, chunk): """Writes file chunk.""" self._tar_fd.fileobj.write(chunk) self.cur_file_size += len(chunk) return self._stream.GetValueAndReset()
Writes file footer (finishes the file). def WriteFileFooter(self): """Writes file footer (finishes the file).""" if self.cur_file_size != self.cur_info.size: raise IOError("Incorrect file size: st_size=%d, but written %d bytes." % (self.cur_info.size, self.cur_file_size)) # TODO...
Fetches user's data and returns it wrapped in a Grruser object. def Get(self): """Fetches user's data and returns it wrapped in a Grruser object.""" args = user_management_pb2.ApiGetGrrUserArgs(username=self.username) data = self._context.SendRequest("GetGrrUser", args) return GrrUser(data=data, conte...
Deletes the user. def Delete(self): """Deletes the user.""" args = user_management_pb2.ApiDeleteGrrUserArgs(username=self.username) self._context.SendRequest("DeleteGrrUser", args)
Modifies user's type and/or password. def Modify(self, user_type=None, password=None): """Modifies user's type and/or password.""" args = user_management_pb2.ApiModifyGrrUserArgs( username=self.username, user_type=user_type) if user_type is not None: args.user_type = user_type if passw...
Uploads data from a given stream and signs them with a given key. def Upload(self, fd, sign_fn=None): """Uploads data from a given stream and signs them with a given key.""" if not sign_fn: raise ValueError("sign_fn can't be empty. " "See DefaultUploadSigner as a possible option."...
Creates a new GRR user of a given type with a given username/password. def CreateGrrUser(self, username=None, user_type=None, password=None): """Creates a new GRR user of a given type with a given username/password.""" if not username: raise ValueError("Username can't be empty.") args = user_manage...
Lists all registered GRR users. def ListGrrUsers(self): """Lists all registered GRR users.""" args = user_management_pb2.ApiListGrrUsersArgs() items = self._context.SendIteratorRequest("ListGrrUsers", args) return utils.MapItemsIterator( lambda data: GrrUser(data=data, context=self._context),...
Return all audit log entries between now-offset and now. Args: offset: rdfvalue.Duration how far back to look in time now: rdfvalue.RDFDatetime for current time token: GRR access token Yields: AuditEvents created during the time range def GetAuditLogEntries(offset, now, token): """Return all aud...
Fetches client data from the relational db. Args: recency_window: An rdfvalue.Duration specifying a window of last-ping timestamps to consider. Clients that haven't communicated with GRR servers longer than the given period will be skipped. If recency_window is None, all clients will be iterate...
Adds another instance of this category into the active_days counter. We automatically count the event towards all relevant active_days. For example, if the category "Windows" was seen 8 days ago it will be counted towards the 30 day active, 14 day active but not against the 7 and 1 day actives. Ar...
Generate a histogram object and store in the specified attribute. def Save(self, token=None): """Generate a histogram object and store in the specified attribute.""" graph_series_by_label = {} for active_time in self.active_days: for label in self.categories[active_time]: graphs_for_label = g...
Retrieve all the clients for the AbstractClientStatsCollectors. def Run(self): """Retrieve all the clients for the AbstractClientStatsCollectors.""" try: self.stats = {} self.BeginProcessing() processed_count = 0 for client_info_batch in _IterateAllClients( recency_window=...
Retrieve all the clients for the AbstractClientStatsCollectors. def Start(self): """Retrieve all the clients for the AbstractClientStatsCollectors.""" try: self.stats = {} self.BeginProcessing() processed_count = 0 if data_store.RelationalDBEnabled(): for client_info_batch i...
Update counters for system, version and release attributes. def ProcessLegacyClient(self, ping, client): """Update counters for system, version and release attributes.""" labels = self._GetClientLabelsList(client) system = client.Get(client.Schema.SYSTEM, "Unknown") uname = client.Get(client.Schema.UNA...
Starts an interrogation hunt on all available clients. def StartInterrogationHunt(self): """Starts an interrogation hunt on all available clients.""" flow_name = compatibility.GetName(flows_discovery.Interrogate) flow_args = flows_discovery.InterrogateArgs(lightweight=False) description = "Interrogate ...
Does the work. def ProcessClients(self, responses): """Does the work.""" del responses end = rdfvalue.RDFDatetime.Now() - db.CLIENT_STATS_RETENTION client_urns = export_utils.GetAllClients(token=self.token) for batch in collection.Batch(client_urns, 10000): with data_store.DB.GetMutationPoo...
Checks if requester and approvers have approval privileges for labels. Checks against list of approvers for each label defined in approvers.yaml to determine if the list of approvers is sufficient. Args: token: user token client_urn: ClientURN object of the client requester: username str...
Checks that the directory exists and has the correct permissions set. def EnsureTempDirIsSane(directory): """Checks that the directory exists and has the correct permissions set.""" if not os.path.isabs(directory): raise ErrorBadPath("Directory %s is not absolute" % directory) if os.path.isdir(directory): ...
Open file with GRR prefix in directory to allow easy deletion. Missing parent dirs will be created. If an existing directory is specified its permissions won't be modified to avoid breaking system functionality. Permissions on the destination file will be set to root/SYSTEM rw. On windows the file is created,...
Creates a GRR VFS temp file. This function is analogous to CreateGRRTempFile but returns an open VFS handle to the newly created file. Arguments are the same as for CreateGRRTempFile: Args: filename: The name of the file to use. Note that setting both filename and directory name is not allowed. ...
Checks if given path is valid for deletion. def _CheckIfPathIsValidForDeletion(path, prefix=None, directories=None): """Checks if given path is valid for deletion.""" precondition.AssertType(path, Text) precondition.AssertType(prefix, Text) if prefix and os.path.basename(path).startswith(prefix): return T...
Delete a GRR temp file. To limit possible damage the path must be absolute and either the file must be within any of the Client.tempdir_roots or the file name must begin with Client.tempfile_prefix. Args: path: path string to file to be deleted. Raises: OSError: Permission denied, or file not found...
Delete all the GRR temp files in path. If path is a directory, look in the top level for filenames beginning with Client.tempfile_prefix, and delete them. If path is a regular file and starts with Client.tempfile_prefix delete it. Args: args: pathspec pointing to directory containing temp files...
Issue a request to list the directory. def Start(self): """Issue a request to list the directory.""" self.CallClient( server_stubs.PlistQuery, request=self.args.request, next_state="Receive")
Returns JSON format mode corresponding to a given request and method. def GetRequestFormatMode(request, method_metadata): """Returns JSON format mode corresponding to a given request and method.""" if request.path.startswith("/api/v2/"): return JsonMode.PROTO3_JSON_MODE if request.args.get("strip_type_info"...
Renders HTTP response to a given HTTP request. def RenderHttpResponse(request): """Renders HTTP response to a given HTTP request.""" start_time = time.time() response = HTTP_REQUEST_HANDLER.HandleRequest(request) total_time = time.time() - start_time method_name = response.headers.get("X-API-Method", "unkn...
Builds a werkzeug routing map out of a given router class. def _BuildHttpRoutingMap(self, router_cls): """Builds a werkzeug routing map out of a given router class.""" if not issubclass(router_cls, api_call_router.ApiCallRouter): raise ValueError("Router has to be an instance of ApiCallRouter.") ro...
Returns a routing map for a given router instance. def _GetRoutingMap(self, router): """Returns a routing map for a given router instance.""" try: routing_map = self._routing_maps_cache.Get(router.__class__) except KeyError: routing_map = self._BuildHttpRoutingMap(router.__class__) self....
Sets fields on the arg rdfvalue object. def _SetField(self, args, type_info, value): """Sets fields on the arg rdfvalue object.""" if hasattr(type_info, "enum"): try: coerced_obj = type_info.enum[value.upper()] except KeyError: # A bool is an enum but serializes to "1" / "0" which a...
Builds args struct out of HTTP request. def _GetArgsFromRequest(self, request, method_metadata, route_args): """Builds args struct out of HTTP request.""" format_mode = GetRequestFormatMode(request, method_metadata) if request.method in ["GET", "HEAD"]: if method_metadata.args_type: unproces...
Returns a router for a given HTTP request. def MatchRouter(self, request): """Returns a router for a given HTTP request.""" router = api_auth_manager.API_AUTH_MGR.GetRouterForUser(request.user) routing_map = self._GetRoutingMap(router) matcher = routing_map.bind( "%s:%s" % (request.env...
Build an ACLToken from the request. def BuildToken(request, execution_time): """Build an ACLToken from the request.""" # The request.args dictionary will also be filled on HEAD calls. if request.method in ["GET", "HEAD"]: reason = request.args.get("reason", "") elif request.method in ["POST", "D...
Handles API call to a given handler with given args and token. def CallApiHandler(handler, args, token=None): """Handles API call to a given handler with given args and token.""" result = handler.Handle(args, token=token) expected_type = handler.result_type if expected_type is None: expected_ty...
Builds HTTPResponse object from rendered data and HTTP status. def _BuildResponse(self, status, rendered_data, method_name=None, headers=None, content_length=None, token=None, ...
Builds HTTPResponse object for streaming. def _BuildStreamingResponse(self, binary_stream, method_name=None): """Builds HTTPResponse object for streaming.""" precondition.AssertType(method_name, Text) # We get a first chunk of the output stream. This way the likelihood # of catching an exception that ...
Handles given HTTP request. def HandleRequest(self, request): """Handles given HTTP request.""" impersonated_username = config.CONFIG["AdminUI.debug_impersonate_user"] if impersonated_username: logging.info("Overriding user as %s", impersonated_username) request.user = config.CONFIG["AdminUI.de...
Returns the provided token or the default token. Args: token: A token or None. Raises: access_control.UnauthorizedAccess: no token was provided. def GetDefaultToken(token): """Returns the provided token or the default token. Args: token: A token or None. Raises: access_control.Unauthorize...
Flushing actually applies all the operations in the pool. def Flush(self): """Flushing actually applies all the operations in the pool.""" DB.DeleteSubjects(self.delete_subject_requests, sync=False) for req in self.delete_attributes_requests: subject, attributes, start, end = req DB.DeleteAttr...
Claims records from a queue. See server/aff4_objects/queue.py. def QueueClaimRecords(self, queue_id, item_rdf_type, limit=10000, timeout="30m", start_time=None, record_filter=...
Removes the given tasks from the queue. def QueueDeleteTasks(self, queue, tasks): """Removes the given tasks from the queue.""" predicates = [] for task in tasks: task_id = getattr(task, "task_id", None) or int(task) predicates.append(DataStore.QueueTaskIdToColumn(task_id)) self.DeleteAttri...
Returns a list of Tasks leased for a certain time. Args: queue: The queue to query from. lease_seconds: The tasks will be leased for this long. limit: Number of values to fetch. timestamp: Range of times for consideration. Returns: A list of GrrMessage() objects leased. def Qu...
Business logic helper for QueueQueryAndOwn(). def _QueueQueryAndOwn(self, subject, lease_seconds=100, limit=1, timestamp=None): """Business logic helper for QueueQueryAndOwn().""" tasks = [] lease = int(lease_s...
Adds a child to the specified parent. def AFF4AddChild(self, subject, child, extra_attributes=None): """Adds a child to the specified parent.""" precondition.AssertType(child, Text) attributes = { DataStore.AFF4_INDEX_DIR_TEMPLATE % child: [DataStore.EMPTY_DATA_PLACEHOLDER] } if ex...
Start the thread that registers the size of the DataStore. def InitializeMonitorThread(self): """Start the thread that registers the size of the DataStore.""" if self.monitor_thread: return self.monitor_thread = utils.InterruptableThread( name="DataStore monitoring thread", target=sel...
Delete multiple subjects at once. def DeleteSubjects(self, subjects, sync=False): """Delete multiple subjects at once.""" for subject in subjects: self.DeleteSubject(subject, sync=sync)
Retry a DBSubjectLock until it succeeds. Args: subject: The subject which the lock applies to. retrywrap_timeout: How long to wait before retrying the lock. retrywrap_max_timeout: The maximum time to wait for a retry until we raise. blocking: If False, raise on first lock failure. ...
Set multiple attributes' values for this subject in one operation. Args: subject: The subject this applies to. values: A dict with keys containing attributes and values, serializations to be set. values can be a tuple of (value, timestamp). Value must be one of the supported types. ...
Remove all specified attributes from a list of subjects. Args: subjects: The list of subjects that will have these attributes removed. attributes: A list of attributes. start: A timestamp, attributes older than start will not be deleted. end: A timestamp, attributes newer than end will not ...
Retrieve a value set for a subject's attribute. This method is easy to use but always gets the latest version of the attribute. It is more flexible and efficient to use the other Resolve methods. Args: subject: The subject URN. attribute: The attribute. Returns: A (value, timest...
Retrieve a set of value matching for this subject's attribute. Args: subject: The subject that we will search. attribute_prefix: The attribute prefix. timestamp: A range of times for consideration (In microseconds). Can be a constant such as ALL_TIMESTAMPS or NEWEST_TIMESTAMP or a tuple o...
Fetches all Requests and Responses for a given session_id. def ReadRequestsAndResponses(self, session_id, timestamp=None, request_limit=None, response_limit=None): """Fetches all Requests and...
Fetches all the requests with a status message queued for them. def ReadCompletedRequests(self, session_id, timestamp=None, limit=None): """Fetches all the requests with a status message queued for them.""" subject = session_id.Add("state") requests = {} status = {} for predicate, serialized, _ in...
Reads responses for one request. Args: session_id: The session id to use. request_id: The id of the request. timestamp: A timestamp as used in the data store. Yields: fetched responses for the request def ReadResponsesForRequestId(self, session_id, request_id, timestamp=None): """...
Reads responses for multiple requests at the same time. Args: request_list: The list of requests the responses should be fetched for. timestamp: A timestamp as used in the data store. Yields: tuples (request, lists of fetched responses for the request) def ReadResponses(self, request_list, ...
Stores new flow requests and responses to the data store. Args: new_requests: A list of tuples (request, timestamp) to store in the data store. new_responses: A list of tuples (response, timestamp) to store in the data store. requests_to_delete: A list of requests that should be d...
Checks if there is a status message queued for a number of requests. def CheckRequestsForCompletion(self, requests): """Checks if there is a status message queued for a number of requests.""" subjects = [r.session_id.Add("state") for r in requests] statuses_found = {} for subject, result in self.Mul...
Deletes all requests and responses for the given flows. Args: session_ids: A lists of flows to destroy. request_limit: A limit on the number of requests to delete. Returns: A list of requests that were deleted. def MultiDestroyFlowStates(self, session_ids, request_limit=None): """Delete...
Finds all objects associated with any of the keywords. Args: index_urn: The base urn of the index. keywords: A collection of keywords that we are interested in. start_time: Only considers keywords added at or after this point in time. end_time: Only considers keywords at or before this poin...
Reads all index entries for the given collection. Args: collection_id: ID of the collection for which the indexes should be retrieved. Yields: Tuples (index, ts, suffix). def CollectionReadIndex(self, collection_id): """Reads all index entries for the given collection. Args: ...
Retrieves tasks from a queue without leasing them. This is good for a read only snapshot of the tasks. Args: queue: The task queue that this task belongs to, usually client.Queue() where client is the ClientURN object you want to schedule msgs on. limit: Number of values to fetch. Ret...
Search the index for matches starting with target_prefix. Args: subject: The index to use. Should be a urn that points to the sha256 namespace. target_prefix: The prefix to match against the index. limit: Either a tuple of (start, limit) or a maximum number of results to retu...
Initialize the data_store. def Run(self): """Initialize the data_store.""" global DB # pylint: disable=global-statement global REL_DB # pylint: disable=global-statement global BLOBS # pylint: disable=global-statement if flags.FLAGS.list_storage: self._ListStorageOptions() sys.exit(0...
Download an aff4 file to the local filesystem overwriting it if it exists. Args: file_obj: An aff4 object that supports the file interface (Read, Seek) target_path: Full path of file to write to. buffer_size: Read in chunks this size. def DownloadFile(file_obj, target_path, buffer_size=BUFFER_SIZE): "...
Recursively downloads a file entry to the target path. Args: dir_obj: An aff4 object that contains children. target_dir: Full path of the directory to write to. max_depth: Depth to download to. 1 means just the directory itself. depth: Current depth of recursion. overwrite: Should we overwrite fi...
Tries to open various types of collections at the given path. def _OpenCollectionPath(coll_path): """Tries to open various types of collections at the given path.""" hunt_collection = results.HuntResultCollection(coll_path) if hunt_collection and hunt_collection[0].payload: return hunt_collection indexed_...
Iterate through a Collection object downloading all files. Args: coll_path: Path to an AFF4 collection. target_path: Base directory to write to. token: Token for access. overwrite: If True, overwrite existing files. dump_client_info: If True, this will detect client paths, and dump a yaml v...
Copy an AFF4 object that supports a read interface to local filesystem. Args: aff4_urn: URN of thing to copy. target_dir: Directory to copy the file to. token: Auth token. overwrite: If True overwrite the file if it exists. Returns: If aff4_urn points to a file, returns path to the downloaded ...
Dump a yaml file containing client info. def DumpClientYaml(client_urn, target_dir, token=None, overwrite=False): """Dump a yaml file containing client info.""" fd = aff4.FACTORY.Open(client_urn, aff4_grr.VFSGRRClient, token=token) dirpath = os.path.join(target_dir, fd.urn.Split()[0]) try: # Due to threadi...
Yield client urns. def GetInput(self): """Yield client urns.""" clients = GetAllClients(token=self.token) logging.debug("Got %d clients", len(clients)) return clients
Run the iteration. def Run(self): """Run the iteration.""" count = 0 for count, input_data in enumerate(self.GetInput()): if count % 2000 == 0: logging.debug("%d processed.", count) args = (input_data, self.out_queue, self.token) self.thread_pool.AddTask( target=self.Ite...
Yield client urns. def GetInput(self): """Yield client urns.""" client_list = GetAllClients(token=self.token) logging.debug("Got %d clients", len(client_list)) for client_group in collection.Batch(client_list, self.client_chunksize): for fd in aff4.FACTORY.MultiOpen( client_group, ...
Interpolate all knowledgebase attributes in pattern. Args: pattern: A string with potential interpolation markers. For example: "/home/%%users.username%%/Downloads/" knowledge_base: The knowledge_base to interpolate parameters from. ignore_errors: Set this to true to log errors instead of raising. ...
Return a dictionary of environment variables and their values. Implementation maps variables mentioned in https://en.wikipedia.org/wiki/Environment_variable#Windows to known KB definitions. Args: knowledge_base: A knowledgebase object. Returns: A dictionary built from a given knowledgebase object w...
r"""Take a string and expand any windows environment variables. Args: data_string: A string, e.g. "%SystemRoot%\\LogFiles" knowledge_base: A knowledgebase object. Returns: A string with available environment variables expanded. If we can't expand we just return the string with the original variabl...
Check if a condition matches an object. Args: condition: A string condition e.g. "os == 'Windows'" check_object: Object to validate, e.g. an rdf_client.KnowledgeBase() Returns: True or False depending on whether the condition matches. Raises: ConditionError: If condition is bad. def CheckCondi...
r"""Take a string and expand windows user environment variables based. Args: data_string: A string, e.g. "%TEMP%\\LogFiles" knowledge_base: A knowledgebase object. sid: A Windows SID for a user to expand for. username: A Windows user name to expand for. Returns: A string with available environ...
Fetches extended file attributes. Args: filepath: A path to the file. Yields: `ExtAttr` pairs. def GetExtAttrs(filepath): """Fetches extended file attributes. Args: filepath: A path to the file. Yields: `ExtAttr` pairs. """ path = CanonicalPathToLocalPath(filepath) try: attr_na...
Sleep a given time in 1 second intervals. When a machine is suspended during a time.sleep(n) call for more than n seconds, sometimes the sleep is interrupted and all threads wake up at the same time. This leads to race conditions between the threads issuing the heartbeat and the one checking for it. By...
Write the message into the transaction log. def Write(self, grr_message): """Write the message into the transaction log.""" grr_message = grr_message.SerializeToString() try: with io.open(self.logfile, "wb") as fd: fd.write(grr_message) except (IOError, OSError): # Check if we're m...
Wipes the transaction log. def Clear(self): """Wipes the transaction log.""" try: with io.open(self.logfile, "wb") as fd: fd.write(b"") except (IOError, OSError): pass
Return a GrrMessage instance from the transaction log or None. def Get(self): """Return a GrrMessage instance from the transaction log or None.""" try: with io.open(self.logfile, "rb") as fd: data = fd.read(self.max_log_size) except (IOError, OSError): return try: if data: ...
Remove a specific symbol from a fn_table. def FilterFnTable(fn_table, symbol): """Remove a specific symbol from a fn_table.""" new_table = list() for entry in fn_table: # symbol[0] is a str with the symbol name if entry[0] != symbol: new_table.append(entry) return new_table
Set function argument types and return types for an ObjC library. Args: libname: Library name string fn_table: List of (function, [arg types], return types) tuples Returns: ctypes.CDLL with types set according to fn_table Raises: ErrorLibNotFound: Can't find specified lib def SetCTypesForLibrary...
Package a CoreFoundation object in a Python wrapper. Args: obj: The CoreFoundation object. Returns: One of CFBoolean, CFNumber, CFString, CFDictionary, CFArray. Raises: TypeError: If the type is not supported. def WrapCFTypeInPython(self, obj): """Package a CoreFoundation object in a...
Copy all Job Dictionaries from the ServiceManagement. Args: domain: The name of a constant in Foundation referencing the domain. Will copy all launchd services by default. Returns: A marshalled python list of dicts containing the job dictionaries. def SMGetJobDictionaries(self, doma...
Returns dictionary values or default. Args: key: string. Dictionary key to look up. default: string. Return this value if key not found. stringify: bool. Force all return values to string for compatibility reasons. Returns: python-wrapped CF object or default if not fou...
Load the kextmanager, replacing unavailable symbols. def SafeLoadKextManager(self, fn_table): """Load the kextmanager, replacing unavailable symbols.""" dll = None try: dll = SetCTypesForLibrary('IOKit', fn_table) except AttributeError as ae: if 'KextManagerUnloadKextWithIdentifier' in str(...
Load a kext by forking into kextload. def LegacyKextload(self, cf_bundle_url, dependency_kext): """Load a kext by forking into kextload.""" _ = dependency_kext error_code = OS_SUCCESS cf_path = self.dll.CFURLCopyFileSystemPath(cf_bundle_url, POSIX_PATH_STYLE) path = self.CFStringToPystring(cf_path)...