text
stringlengths
81
112k
Returns ids for all signed binaries in the DB. def ReadIDsForAllSignedBinaries(self, cursor=None ): """Returns ids for all signed binaries in the DB.""" cursor.execute( "SELECT binary_type, binary_path FROM signed_binary_references") return [ rdf_objects.Sig...
Deletes blob references for the given signed binary from the DB. def DeleteSignedBinaryReferences(self, binary_id, cursor=None): """Deletes blob references for the given signed binary from the DB.""" cursor.execute( """ DELETE ...
Query the client for available Volume Shadow Copies using a WMI query. def Start(self): """Query the client for available Volume Shadow Copies using a WMI query.""" self.state.shadows = [] self.state.raw_device = None self.CallClient( server_stubs.WmiQuery, query="SELECT * FROM Win32_S...
Processes the results of the ListDirectory client action. Args: responses: a flow Responses object. def ProcessListDirectory(self, responses): """Processes the results of the ListDirectory client action. Args: responses: a flow Responses object. """ if not responses.success: rai...
Parse the found release files. def ParseMultiple(self, stats, file_objects, knowledge_base): """Parse the found release files.""" _ = knowledge_base # Collate files into path: contents dictionary. found_files = self._Combine(stats, file_objects) # Determine collected files and apply weighting. ...
Verifies the certificate using the given key. Args: public_key: The public key to use. Returns: True: Everything went well. Raises: VerificationError: The certificate did not verify. def Verify(self, public_key): """Verifies the certificate using the given key. Args: pub...
Creates a new cert for the given common name. Args: csr: A CertificateSigningRequest. Returns: The signed cert. def ClientCertFromCSR(cls, csr): """Creates a new cert for the given common name. Args: csr: A CertificateSigningRequest. Returns: The signed cert. """ ...
Verifies a given message. def Verify(self, message, signature, hash_algorithm=None): """Verifies a given message.""" # This method accepts both PSS and PKCS1v15 padding. PSS is preferred but # old clients only support PKCS1v15. if hash_algorithm is None: hash_algorithm = hashes.SHA256() las...
Sign a given message. def Sign(self, message, use_pss=False): """Sign a given message.""" precondition.AssertType(message, bytes) # TODO(amoser): This should use PSS by default at some point. if not use_pss: padding_algorithm = padding.PKCS1v15() else: padding_algorithm = padding.PSS( ...
Verify the data in this blob. Args: public_key: The public key to use for verification. Returns: True when verification succeeds. Raises: rdfvalue.DecodeError if the data is not suitable verified. def Verify(self, public_key): """Verify the data in this blob. Args: publi...
Use the data to sign this blob. Args: data: String containing the blob data. signing_key: The key to sign with. verify_key: Key to verify with. If None we assume the signing key also contains the public key. Returns: self for call chaining. def Sign(self, data, signing_key, ve...
A convenience method which pads and encrypts at once. def Encrypt(self, data): """A convenience method which pads and encrypts at once.""" encryptor = self.GetEncryptor() padded_data = self.Pad(data) try: return encryptor.update(padded_data) + encryptor.finalize() except ValueError as e: ...
A convenience method which pads and decrypts at once. def Decrypt(self, data): """A convenience method which pads and decrypts at once.""" decryptor = self.GetDecryptor() try: padded_data = decryptor.update(data) + decryptor.finalize() return self.UnPad(padded_data) except ValueError as e:...
Calculates the HMAC for a given message. def HMAC(self, message, use_sha256=False): """Calculates the HMAC for a given message.""" h = self._NewHMAC(use_sha256=use_sha256) h.update(message) return h.finalize()
Verifies the signature for a given message. def Verify(self, message, signature): """Verifies the signature for a given message.""" siglen = len(signature) if siglen == 20: hash_algorithm = hashes.SHA1() elif siglen == 32: hash_algorithm = hashes.SHA256() else: raise VerificationE...
Converts collection items to aff4 urns suitable for downloading. def _ItemsToUrns(self, items): """Converts collection items to aff4 urns suitable for downloading.""" for item in items: try: yield flow_export.CollectionItemToAff4Path(item, self.client_id) except flow_export.ItemNotExportabl...
Generates archive from a given collection. Iterates the collection and generates an archive by yielding contents of every referenced AFF4Stream. Args: items: Iterable with items that point to aff4 paths. token: User's ACLToken. Yields: Binary chunks comprising the generated archive....
Get available artifact information for rendering. def Handle(self, args, token=None): """Get available artifact information for rendering.""" # Get all artifacts that aren't Bootstrap and aren't the base class. artifacts_list = sorted( artifact_registry.REGISTRY.GetArtifacts( reload_da...
Insert a single component at index. def Insert(self, index, rdfpathspec=None, **kwarg): """Insert a single component at index.""" if rdfpathspec is None: rdfpathspec = self.__class__(**kwarg) if index == 0: # Copy ourselves to a temp copy. nested_proto = self.__class__() nested_pro...
Append a new pathspec component to this pathspec. def Append(self, component=None, **kwarg): """Append a new pathspec component to this pathspec.""" if component is None: component = self.__class__(**kwarg) if self.HasField("pathtype"): self.last.nested_path = component else: for k, ...
Removes and returns the pathspec at the specified index. def Pop(self, index=0): """Removes and returns the pathspec at the specified index.""" if index < 0: index += len(self) if index == 0: result = self.__class__() result.SetRawData(self.GetRawData()) self.SetRawData(self.neste...
Get a new copied object with only the directory path. def Dirname(self): """Get a new copied object with only the directory path.""" result = self.Copy() while 1: last_directory = posixpath.dirname(result.last.path) if last_directory != "/" or len(result) <= 1: result.last.path = last_...
Returns the AFF4 URN this pathspec will be stored under. Args: client_urn: A ClientURN. Returns: A urn that corresponds to this pathspec. Raises: ValueError: If pathspec is not of the correct type. def AFF4Path(self, client_urn): """Returns the AFF4 URN this pathspec will be stored...
GlobExpression is valid. def Validate(self): """GlobExpression is valid.""" if len(self.RECURSION_REGEX.findall(self._value)) > 1: raise ValueError("Only one ** is permitted per path: %s." % self._value)
Interpolate inline globbing groups. def InterpolateGrouping(self, pattern): """Interpolate inline globbing groups.""" components = [] offset = 0 for match in GROUPING_PATTERN.finditer(pattern): components.append([pattern[offset:match.start()]]) # Expand the attribute into the set of possib...
Return the current glob as a simple regex. Note: No interpolation is performed. Returns: A RegularExpression() object. def AsRegEx(self): """Return the current glob as a simple regex. Note: No interpolation is performed. Returns: A RegularExpression() object. """ parts = sel...
Add a value to a date. def dateadd(value: fields.DateTime(), addend: fields.Int(validate=Range(min=1)), unit: fields.Str(validate=OneOf(['minutes', 'days']))='days'): """Add a value to a date.""" value = value or dt.datetime.utcnow() if unit == 'minutes': delta = dt.timedelt...
Returns the name of all arguments a function takes def arguments(function, extra_arguments=0): """Returns the name of all arguments a function takes""" if not hasattr(function, '__code__'): return () return function.__code__.co_varnames[:function.__code__.co_argcount + extra_arguments]
Dynamically creates a function that when called with dictionary of arguments will produce a kwarg that's compatible with the supplied function def generate_accepted_kwargs(function, *named_arguments): """Dynamically creates a function that when called with dictionary of arguments will produce a kwarg that's...
Wraps authentication logic, verify_user through to the authentication function. The verify_user function passed in should accept an API key and return a user object to store in the request context if authentication succeeded. def authenticator(function, challenges=()): """Wraps authentication logic, verif...
Basic HTTP Authentication def basic(request, response, verify_user, realm='simple', context=None, **kwargs): """Basic HTTP Authentication""" http_auth = request.auth response.set_header('WWW-Authenticate', 'Basic') if http_auth is None: return if isinstance(http_auth, bytes): http_...
API Key Header Authentication The verify_user function passed in to ths authenticator shall receive an API key as input, and return a user object to store in the request context if the request was successful. def api_key(request, response, verify_user, context=None, **kwargs): """API Key Header Authen...
Token verification Checks for the Authorization header and verifies using the verify_user function def token(request, response, verify_user, context=None, **kwargs): """Token verification Checks for the Authorization header and verifies using the verify_user function """ token = request.get_heade...
Returns a simple verification callback that simply verifies that the users and password match that provided def verify(user, password): """Returns a simple verification callback that simply verifies that the users and password match that provided""" def verify_user(user_name, user_password): if user_na...
Get session ID from cookie, load corresponding session data from coupled store and inject session data into the request context. def process_request(self, request, response): """Get session ID from cookie, load corresponding session data from coupled store and inject session data into t...
Save request context in coupled store object. Set cookie containing a session ID. def process_response(self, request, response, resource, req_succeeded): """Save request context in coupled store object. Set cookie containing a session ID.""" sid = request.cookies.get(self.cookie_name, None) if ...
Given a request/response pair, generate a logging format similar to the NGINX combined style. def _generate_combined_log(self, request, response): """Given a request/response pair, generate a logging format similar to the NGINX combined style.""" current_time = datetime.utcnow() data_len = '-' ...
Logs the basic endpoint requested def process_request(self, request, response): """Logs the basic endpoint requested""" self.logger.info('Requested: {0} {1} {2}'.format(request.method, request.relative_uri, request.content_type))
Logs the basic data returned by the API def process_response(self, request, response, resource, req_succeeded): """Logs the basic data returned by the API""" self.logger.info(self._generate_combined_log(request, response))
Match a request with parameter to it's corresponding route def match_route(self, reqpath): """Match a request with parameter to it's corresponding route""" route_dicts = [routes for _, routes in self.api.http.routes.items()][0] routes = [route for route, _ in route_dicts.items()] if req...
Add CORS headers to the response def process_response(self, request, response, resource, req_succeeded): """Add CORS headers to the response""" response.set_header('Access-Control-Allow-Credentials', str(self.allow_credentials).lower()) origin = request.get_header('ORIGIN') if origin a...
Creates a new type handler with the specified type-casting handler def create(doc=None, error_text=None, exception_handlers=empty.dict, extend=Type, chain=True, auto_instance=True, accept_context=False): """Creates a new type handler with the specified type-casting handler""" extend = extend if type...
Allows quick wrapping of any Python type cast function for use as a hug type annotation def accept(kind, doc=None, error_text=None, exception_handlers=empty.dict, accept_context=False): """Allows quick wrapping of any Python type cast function for use as a hug type annotation""" return create( doc, ...
Redirects to the specified location using the provided http_code (defaults to HTTP_302 FOUND) def to(location, code=falcon.HTTP_302): """Redirects to the specified location using the provided http_code (defaults to HTTP_302 FOUND)""" raise falcon.http_status.HTTPStatus(code, {'location': location})
Converts text that may be camelcased into an underscored format def underscore(text): """Converts text that may be camelcased into an underscored format""" return UNDERSCORE[1].sub(r'\1_\2', UNDERSCORE[0].sub(r'\1_\2', text)).lower()
Hug API Development Server def hug(file: 'A Python file that contains a Hug API'=None, module: 'A Python module that contains a Hug API'=None, host: 'Interface to bind to'='', port: number=8000, no_404_documentation: boolean=False, manual_reload: boolean=False, interval: number=1, command: 'Run...
Authenticate and return a token def token_gen_call(username, password): """Authenticate and return a token""" secret_key = 'super-secret-key-please-change' mockusername = 'User2' mockpassword = 'Mypassword' if mockpassword == password and mockusername == username: # This is an example. Don't do tha...
returns documentation for the current api def documentation(default=None, api_version=None, api=None, **kwargs): """returns documentation for the current api""" api_version = default or api_version if api: return api.http.documentation(base_url="", api_version=api_version)
Takes JSON formatted data, converting it into native Python objects def json(body, charset='utf-8', **kwargs): """Takes JSON formatted data, converting it into native Python objects""" return json_converter.loads(text(body, charset=charset))
Converts query strings into native Python objects def urlencoded(body, charset='ascii', **kwargs): """Converts query strings into native Python objects""" return parse_query_string(text(body, charset=charset), False)
Converts multipart form data into native Python objects def multipart(body, content_length=0, **header_params): """Converts multipart form data into native Python objects""" header_params.setdefault('CONTENT-LENGTH', content_length) if header_params and 'boundary' in header_params: if type(header_p...
Sets up and fills test directory for serving. Using different filetypes to see how they are dealt with. The tempoary directory will clean itself up. def setup(api=None): """Sets up and fills test directory for serving. Using different filetypes to see how they are dealt with. The tempoary directo...
Returns a different transformer depending on the content type passed in. If none match and no default is given no transformation takes place. should pass in a dict with the following format: {'[content-type]': transformation_action, ... } def content_type(transforme...
Returns a different transformer depending on the suffix at the end of the requested URL. If none match and no default is given no transformation takes place. should pass in a dict with the following format: {'[suffix]': transformation_action, ... } def suffix(transf...
Returns a different transformer depending on the prefix at the end of the requested URL. If none match and no default is given no transformation takes place. should pass in a dict with the following format: {'[prefix]': transformation_action, ... } def prefix(transf...
Returns the results of applying all passed in transformers to data should pass in list of transformers [transformer_1, transformer_2...] def all(*transformers): """Returns the results of applying all passed in transformers to data should pass in list of transformers [trans...
Runs all set type transformers / validators against the provided input parameters and returns any errors def validate(self, input_parameters, context): """Runs all set type transformers / validators against the provided input parameters and returns any errors""" errors = {} for key, type_handl...
Checks to see if all requirements set pass if all requirements pass nothing will be returned otherwise, the error reported will be returned def check_requirements(self, request=None, response=None, context=None): """Checks to see if all requirements set pass if all requiremen...
Produces general documentation for the interface def documentation(self, add_to=None): """Produces general documentation for the interface""" doc = OrderedDict if add_to is None else add_to usage = self.interface.spec.__doc__ if usage: doc['usage'] = usage if getatt...
Outputs the provided data using the transformations and output format specified for this CLI endpoint def output(self, data, context): """Outputs the provided data using the transformations and output format specified for this CLI endpoint""" if self.transform: if hasattr(self.transform, 'c...
Gathers and returns all parameters that will be used for this endpoint def gather_parameters(self, request, response, context, api_version=None, **input_parameters): """Gathers and returns all parameters that will be used for this endpoint""" input_parameters.update(request.params) if self.par...
Runs the transforms specified on this endpoint with the provided data, returning the data modified def transform_data(self, data, request=None, response=None, context=None): transform = self.transform if hasattr(transform, 'context'): self.transform.context = context """Runs the tra...
Returns the content type that should be used by default for this endpoint def content_type(self, request=None, response=None): """Returns the content type that should be used by default for this endpoint""" if callable(self.outputs.content_type): return self.outputs.content_type(request=req...
Returns the content type that should be used by default on validation errors def invalid_content_type(self, request=None, response=None): """Returns the content type that should be used by default on validation errors""" if callable(self.invalid_outputs.content_type): return self.invalid_ou...
Sets up the response defaults that are defined in the URL route def set_response_defaults(self, response, request=None): """Sets up the response defaults that are defined in the URL route""" for header_name, header_value in self.response_headers: response.set_header(header_name, header_valu...
Returns the documentation specific to an HTTP interface def documentation(self, add_to=None, version=None, prefix="", base_url="", url=""): """Returns the documentation specific to an HTTP interface""" doc = OrderedDict() if add_to is None else add_to usage = self.interface.spec.__doc__ ...
Returns all URLS that are mapped to this interface def urls(self, version=None): """Returns all URLS that are mapped to this interface""" urls = [] for base_url, routes in self.api.http.routes.items(): for url, methods in routes.items(): for method, versions in metho...
Returns the first matching URL found for the specified arguments def url(self, version=None, **kwargs): """Returns the first matching URL found for the specified arguments""" for url in self.urls(version): if [key for key in kwargs.keys() if not '{' + key + '}' in url]: cont...
Greets appropriately (from http://blog.ketchum.com/how-to-write-10-common-holiday-greetings/) def greet(event: str): """Greets appropriately (from http://blog.ketchum.com/how-to-write-10-common-holiday-greetings/) """ greetings = "Happy" if event == "Christmas": greetings = "Merry" if event ==...
Returns command help document when no command is specified def nagiosCommandHelp(**kwargs): """ Returns command help document when no command is specified """ with open(os.path.join(DIRECTORY, 'document.html')) as document: return document.read()
Securely hash a password using a provided salt :param password: :param salt: :return: Hex encoded SHA512 hash of provided password def hash_password(password, salt): """ Securely hash a password using a provided salt :param password: :param salt: :return: Hex encoded SHA512 hash of prov...
Create a random API key for a user :param username: :return: Hex encoded SHA512 random string def gen_api_key(username): """ Create a random API key for a user :param username: :return: Hex encoded SHA512 random string """ salt = str(os.urandom(64)).encode('utf-8') return hash_passw...
Authenticate a username and password against our database :param username: :param password: :return: authenticated username def authenticate_user(username, password): """ Authenticate a username and password against our database :param username: :param password: :return: authenticated u...
Authenticate an API key against our database :param api_key: :return: authenticated username def authenticate_key(api_key): """ Authenticate an API key against our database :param api_key: :return: authenticated username """ user_model = Query() user = db.search(user_model.api_key =...
CLI Parameter to add a user to the database :param username: :param password: :return: JSON status output def add_user(username, password): """ CLI Parameter to add a user to the database :param username: :param password: :return: JSON status output """ user_model = Query() ...
Get Job details :param authed_user: :return: def get_token(authed_user: hug.directives.user): """ Get Job details :param authed_user: :return: """ user_model = Query() user = db.search(user_model.username == authed_user)[0] if user: out = { 'user': user['use...
accepts file uploads def upload_file(body): """accepts file uploads""" # <body> is a simple dictionary of {filename: b'content'} print('body: ', body) return {'filename': list(body.keys()).pop(), 'filesize': len(list(body.values()).pop())}
Says happy birthday to a user def happy_birthday(name: hug.types.text, age: hug.types.number, hug_timer=3): """Says happy birthday to a user""" return {'message': 'Happy {0} Birthday {1}!'.format(age, name), 'took': float(hug_timer)}
Registers the wrapped method as a JSON converter for the provided types. NOTE: custom converters are always globally applied def json_convert(*kinds): """Registers the wrapped method as a JSON converter for the provided types. NOTE: custom converters are always globally applied """ def register_j...
JSON (Javascript Serialized Object Notation) def json(content, request=None, response=None, ensure_ascii=False, **kwargs): """JSON (Javascript Serialized Object Notation)""" if hasattr(content, 'read'): return content if isinstance(content, tuple) and getattr(content, '_fields', None): con...
Renders as the specified content type only if no errors are found in the provided data object def on_valid(valid_content_type, on_invalid=json): """Renders as the specified content type only if no errors are found in the provided data object""" invalid_kwargs = introspect.generate_accepted_kwargs(on_invalid, '...
HTML (Hypertext Markup Language) def html(content, **kwargs): """HTML (Hypertext Markup Language)""" if hasattr(content, 'read'): return content elif hasattr(content, 'render'): return content.render().encode('utf8') return str(content).encode('utf8')
Dynamically creates an image type handler for the specified image type def image(image_format, doc=None): """Dynamically creates an image type handler for the specified image type""" @on_valid('image/{0}'.format(image_format)) def image_handler(data, **kwargs): if hasattr(data, 'read'): ...
Dynamically creates a video type handler for the specified video type def video(video_type, video_mime, doc=None): """Dynamically creates a video type handler for the specified video type""" @on_valid(video_mime) def video_handler(data, **kwargs): if hasattr(data, 'read'): return data ...
A dynamically retrieved file def file(data, response, **kwargs): """A dynamically retrieved file""" if not data: response.content_type = 'text/plain' return '' if hasattr(data, 'read'): name, data = getattr(data, 'name', ''), data elif os.path.isfile(data): name, data =...
Returns a content in a different format based on the clients provided content type, should pass in a dict with the following format: {'[content-type]': action, ... } def on_content_type(handlers, default=None, error='The requested content type does not match any of those al...
Separates out the quality score from the accepted content_type def accept_quality(accept, default=1): """Separates out the quality score from the accepted content_type""" quality = default if accept and ";" in accept: accept, rest = accept.split(";", 1) accept_quality = RE_ACCEPT_QUALITY.se...
Returns a content in a different format based on the clients defined accepted content type, should pass in a dict with the following format: {'[content-type]': action, ... } def accept(handlers, default=None, error='The requested content type does not match any of those all...
Returns a content in a different format based on the suffix placed at the end of the URL route should pass in a dict with the following format: {'[suffix]': action, ... } def suffix(handlers, default=None, error='The requested suffix does not match any of those allowed'): ...
Returns a content in a different format based on the prefix placed at the end of the URL route should pass in a dict with the following format: {'[prefix]': action, ... } def prefix(handlers, default=None, error='The requested prefix does not match any of those allowed'): ...
Returns a list of items currently in the database def show(): """Returns a list of items currently in the database""" items = list(collection.find()) # JSON conversion chokes on the _id objects, so we convert # them to strings here for i in items: i['_id'] = str(i['_id']) return items
Inserts the given object as a new item in the database. Returns the ID of the newly created item. def new(name: hug.types.text, description: hug.types.text): """Inserts the given object as a new item in the database. Returns the ID of the newly created item. """ item_doc = {'name': name, 'descrip...
Calls the service at the specified URL using the "CALL" method def request(self, method, url, url_params=empty.dict, headers=empty.dict, timeout=None, **params): """Calls the service at the specified URL using the "CALL" method""" raise NotImplementedError("Concrete services must define the request met...
Calls the service at the specified URL using the "OPTIONS" method def options(self, url, url_params=empty.dict, headers=empty.dict, timeout=None, **params): """Calls the service at the specified URL using the "OPTIONS" method""" return self.request('OPTIONS', url=url, headers=headers, timeout=timeout, ...
Add socket options to set def setsockopt(self, *sockopts): """Add socket options to set""" if type(sockopts[0]) in (list, tuple): for sock_opt in sockopts[0]: level, option, value = sock_opt self.connection.sockopts.add((level, option, value)) else: ...
Create/Connect socket, apply options def _register_socket(self): """Create/Connect socket, apply options""" _socket = socket.socket(*Socket.protocols[self.connection.proto]) _socket.settimeout(self.timeout) # Reconfigure original socket options. if self.connection.sockopts: ...
TCP/Stream sender and receiver def _stream_send_and_receive(self, _socket, message, *args, **kwargs): """TCP/Stream sender and receiver""" data = BytesIO() _socket_fd = _socket.makefile(mode='rwb', encoding='utf-8') _socket_fd.write(message.encode('utf-8')) _socket_fd.flush() ...
User Datagram Protocol sender and receiver def _dgram_send_and_receive(self, _socket, message, buffer_size=4096, *args): """User Datagram Protocol sender and receiver""" _socket.send(message.encode('utf-8')) data, address = _socket.recvfrom(buffer_size) return BytesIO(data)
Populate connection pool, send message, return BytesIO, and cleanup def request(self, message, timeout=False, *args, **kwargs): """Populate connection pool, send message, return BytesIO, and cleanup""" if not self.connection_pool.full(): self.connection_pool.put(self._register_socket()) ...
Get data for given store key. Raise hug.exceptions.StoreKeyNotFound if key does not exist. def get(self, key): """Get data for given store key. Raise hug.exceptions.StoreKeyNotFound if key does not exist.""" try: data = self._data[key] except KeyError: raise StoreKeyNotF...