signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
def future_datetime(end='<STR_LIT>'):
|
return lambda n, f: f.future_datetime(<EOL>end_date=end, tzinfo=get_timezone(),<EOL>)<EOL>
|
Returns a ``datetime`` object in the future (that is, 1 second from now) up
to the specified ``end``. ``end`` can be a string, anotther datetime, or a
timedelta. If it's a string, it must start with `+`, followed by and integer
and a unit, Eg: ``'+30d'``. Defaults to `'+30d'`
Valid units are:
* ``'years'``, ``'y'``
* ``'weeks'``, ``'w'``
* ``'days'``, ``'d'``
* ``'hours'``, ``'hours'``
* ``'minutes'``, ``'m'``
* ``'seconds'``, ``'s'``
|
f11630:m1
|
def future_date(end='<STR_LIT>'):
|
return lambda n, f: f.future_date(<EOL>end_date=end, tzinfo=get_timezone(),<EOL>)<EOL>
|
Returns a ``date`` object in the future (that is, 1 day from now) up to
the specified ``end``. ``end`` can be a string, another date, or a
timedelta. If it's a string, it must start with `+`, followed by and integer
and a unit, Eg: ``'+30d'``. Defaults to `'+30d'`
Valid units are:
* ``'years'``, ``'y'``
* ``'weeks'``, ``'w'``
* ``'days'``, ``'d'``
* ``'hours'``, ``'hours'``
* ``'minutes'``, ``'m'``
* ``'seconds'``, ``'s'``
|
f11630:m2
|
def past_datetime(start='<STR_LIT>'):
|
return lambda n, f: f.past_datetime(<EOL>start_date=start, tzinfo=get_timezone(),<EOL>)<EOL>
|
Returns a ``datetime`` object in the past between 1 second ago and the
specified ``start``. ``start`` can be a string, another datetime, or a
timedelta. If it's a string, it must start with `-`, followed by and integer
and a unit, Eg: ``'-30d'``. Defaults to `'-30d'`
Valid units are:
* ``'years'``, ``'y'``
* ``'weeks'``, ``'w'``
* ``'days'``, ``'d'``
* ``'hours'``, ``'h'``
* ``'minutes'``, ``'m'``
* ``'seconds'``, ``'s'``
|
f11630:m3
|
def past_date(start='<STR_LIT>'):
|
return lambda n, f: f.past_date(<EOL>start_date=start, tzinfo=get_timezone(),<EOL>)<EOL>
|
Returns a ``date`` object in the past between 1 day ago and the
specified ``start``. ``start`` can be a string, another date, or a
timedelta. If it's a string, it must start with `-`, followed by and integer
and a unit, Eg: ``'-30d'``. Defaults to `'-30d'`
Valid units are:
* ``'years'``, ``'y'``
* ``'weeks'``, ``'w'``
* ``'days'``, ``'d'``
* ``'hours'``, ``'h'``
* ``'minutes'``, ``'m'``
* ``'seconds'``, ``'s'``
|
f11630:m4
|
def __init__(self, username, password, url, profile, legacy_api=False, verify_ssl=True, **kwargs):
|
sandboxapi.SandboxAPI.__init__(self, **kwargs)<EOL>self.base_url = url<EOL>self.username = username<EOL>self.password = password<EOL>self.profile = profile or '<STR_LIT>'<EOL>self.api_token = None<EOL>self.verify_ssl = verify_ssl<EOL>if legacy_api:<EOL><INDENT>self.api_url = url + '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>self.api_url = url + '<STR_LIT>'<EOL><DEDENT>
|
Initialize the interface to FireEye Sandbox API.
|
f11635:c0:m0
|
def _request(self, uri, method='<STR_LIT:GET>', params=None, files=None, headers=None, auth=None):
|
if headers:<EOL><INDENT>headers['<STR_LIT>'] = '<STR_LIT:application/json>'<EOL><DEDENT>else:<EOL><INDENT>headers = {<EOL>'<STR_LIT>': '<STR_LIT:application/json>',<EOL>}<EOL><DEDENT>if not self.api_token:<EOL><INDENT>response = sandboxapi.SandboxAPI._request(self, '<STR_LIT>', '<STR_LIT:POST>', headers=headers,<EOL>auth=HTTPBasicAuth(self.username, self.password))<EOL>if response.status_code != <NUM_LIT:200>:<EOL><INDENT>raise sandboxapi.SandboxError("<STR_LIT>".format(e=response.status_code))<EOL><DEDENT>self.api_token = response.headers.get('<STR_LIT>')<EOL><DEDENT>headers['<STR_LIT>'] = self.api_token<EOL>response = sandboxapi.SandboxAPI._request(self, uri, method, params, files, headers)<EOL>unauthorized = False<EOL>try:<EOL><INDENT>if json.loads(response.content.decode('<STR_LIT:utf-8>'))['<STR_LIT>']['<STR_LIT>'] == <NUM_LIT>:<EOL><INDENT>unauthorized = True<EOL><DEDENT><DEDENT>except (ValueError, KeyError, TypeError):<EOL><INDENT>pass<EOL><DEDENT>if response.status_code == <NUM_LIT> or unauthorized:<EOL><INDENT>self.api_token = None<EOL>try:<EOL><INDENT>headers.pop('<STR_LIT>')<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>return self._request(uri, method, params, files, headers)<EOL><DEDENT>return response<EOL>
|
Override the parent _request method.
We have to do this here because FireEye requires some extra
authentication steps. On each request we pass the auth headers, and
if the session has expired, we automatically reauthenticate.
|
f11635:c0:m1
|
def analyze(self, handle, filename):
|
<EOL>files = {"<STR_LIT:file>": (filename, handle)}<EOL>handle.seek(<NUM_LIT:0>)<EOL>data = {<EOL>'<STR_LIT>': '<STR_LIT>' % self.profile,<EOL>}<EOL>response = self._request("<STR_LIT>", method='<STR_LIT:POST>', params=data, files=files)<EOL>try:<EOL><INDENT>if response.status_code == <NUM_LIT:200>:<EOL><INDENT>try:<EOL><INDENT>return response.json()['<STR_LIT>']<EOL><DEDENT>except TypeError:<EOL><INDENT>return response.json()[<NUM_LIT:0>]['<STR_LIT>']<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise sandboxapi.SandboxError("<STR_LIT>".format(u=response.url, r=response.content))<EOL><DEDENT><DEDENT>except (ValueError, KeyError) as e:<EOL><INDENT>raise sandboxapi.SandboxError("<STR_LIT>".format(e=e))<EOL><DEDENT>
|
Submit a file for analysis.
:type handle: File handle
:param handle: Handle to file to upload for analysis.
:type filename: str
:param filename: File name.
:rtype: str
:return: File ID as a string
|
f11635:c0:m2
|
def check(self, item_id):
|
response = self._request("<STR_LIT>".format(file_id=item_id))<EOL>if response.status_code == <NUM_LIT>:<EOL><INDENT>return False<EOL><DEDENT>try:<EOL><INDENT>status = response.json()['<STR_LIT>']<EOL>if status == '<STR_LIT>':<EOL><INDENT>return True<EOL><DEDENT><DEDENT>except ValueError as e:<EOL><INDENT>raise sandboxapi.SandboxError(e)<EOL><DEDENT>return False<EOL>
|
Check if an analysis is complete.
:type item_id: str
:param item_id: File ID to check.
:rtype: bool
:return: Boolean indicating if a report is done or not.
|
f11635:c0:m3
|
def is_available(self):
|
<EOL>if self.server_available:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>response = self._request("<STR_LIT>")<EOL>if response.status_code == <NUM_LIT:200>:<EOL><INDENT>self.server_available = True<EOL>return True<EOL><DEDENT><DEDENT>except sandboxapi.SandboxError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>self.server_available = False<EOL>return False<EOL>
|
Determine if the FireEye API server is alive.
:rtype: bool
:return: True if service is available, False otherwise.
|
f11635:c0:m4
|
def report(self, item_id, report_format="<STR_LIT>"):
|
if report_format == "<STR_LIT:html>":<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>response = self._request("<STR_LIT>".format(file_id=item_id))<EOL>try:<EOL><INDENT>return response.json()<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT>return response.content<EOL>
|
Retrieves the specified report for the analyzed item, referenced by item_id.
Available formats include: json.
:type item_id: str
:param item_id: File ID number
:type report_format: str
:param report_format: Return format
:rtype: dict
:return: Dictionary representing the JSON parsed data or raw, for other
formats / JSON parsing failure.
|
f11635:c0:m5
|
def score(self, report):
|
score = <NUM_LIT:0><EOL>if report['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>score = <NUM_LIT:8><EOL><DEDENT>return score<EOL>
|
Pass in the report from self.report(), get back an int.
|
f11635:c0:m6
|
def __init__(self, key, url=None, env=<NUM_LIT:100>, **kwargs):
|
sandboxapi.SandboxAPI.__init__(self, **kwargs)<EOL>self.api_url = url or '<STR_LIT>'<EOL>self.key = key<EOL>self.env_id = str(env)<EOL>
|
Initialize the interface to Falcon Sandbox API with key and secret.
|
f11636:c0:m0
|
def _request(self, uri, method='<STR_LIT:GET>', params=None, files=None, headers=None, auth=None):
|
if params:<EOL><INDENT>params['<STR_LIT>'] = self.env_id<EOL><DEDENT>else:<EOL><INDENT>params = {<EOL>'<STR_LIT>': self.env_id,<EOL>}<EOL><DEDENT>if headers:<EOL><INDENT>headers['<STR_LIT>'] = self.key<EOL>headers['<STR_LIT>'] = '<STR_LIT>'<EOL>headers['<STR_LIT>'] = '<STR_LIT:application/json>'<EOL><DEDENT>else:<EOL><INDENT>headers = {<EOL>'<STR_LIT>': self.key,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT:application/json>',<EOL>}<EOL><DEDENT>return sandboxapi.SandboxAPI._request(self, uri, method, params, files, headers)<EOL>
|
Override the parent _request method.
We have to do this here because FireEye requires some extra
authentication steps.
|
f11636:c0:m1
|
def analyze(self, handle, filename):
|
<EOL>files = {"<STR_LIT:file>" : (filename, handle)}<EOL>handle.seek(<NUM_LIT:0>)<EOL>response = self._request("<STR_LIT>", method='<STR_LIT:POST>', files=files)<EOL>try:<EOL><INDENT>if response.status_code == <NUM_LIT>:<EOL><INDENT>return response.json()['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>raise sandboxapi.SandboxError("<STR_LIT>".format(r=response.content.decode('<STR_LIT:utf-8>')))<EOL><DEDENT><DEDENT>except (ValueError, KeyError) as e:<EOL><INDENT>raise sandboxapi.SandboxError("<STR_LIT>".format(e=e))<EOL><DEDENT>
|
Submit a file for analysis.
:type handle: File handle
:param handle: Handle to file to upload for analysis.
:type filename: str
:param filename: File name.
:rtype: str
:return: File hash as a string
|
f11636:c0:m2
|
def check(self, item_id):
|
response = self._request("<STR_LIT>".format(job_id=item_id))<EOL>if response.status_code in (<NUM_LIT>, <NUM_LIT>):<EOL><INDENT>return False<EOL><DEDENT>try:<EOL><INDENT>content = json.loads(response.content.decode('<STR_LIT:utf-8>'))<EOL>status = content['<STR_LIT:state>']<EOL>if status == '<STR_LIT>' or status == '<STR_LIT>':<EOL><INDENT>return True<EOL><DEDENT><DEDENT>except (ValueError, KeyError) as e:<EOL><INDENT>raise sandboxapi.SandboxError(e)<EOL><DEDENT>return False<EOL>
|
Check if an analysis is complete.
:type item_id: str
:param item_id: Job ID to check.
:rtype: bool
:return: Boolean indicating if a report is done or not.
|
f11636:c0:m3
|
def is_available(self):
|
<EOL>if self.server_available:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>response = self._request("<STR_LIT>")<EOL>if response.status_code == <NUM_LIT:200>:<EOL><INDENT>self.server_available = True<EOL>return True<EOL><DEDENT><DEDENT>except sandboxapi.SandboxError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>self.server_available = False<EOL>return False<EOL>
|
Determine if the Falcon API server is alive.
:rtype: bool
:return: True if service is available, False otherwise.
|
f11636:c0:m4
|
def queue_size(self):
|
response = self._request("<STR_LIT>")<EOL>return response.content.decode('<STR_LIT:utf-8>')<EOL>
|
Determine Falcon sandbox queue length
:rtype: str
:return: Details on the queue size.
|
f11636:c0:m5
|
def report(self, item_id, report_format="<STR_LIT>"):
|
report_format = report_format.lower()<EOL>response = self._request("<STR_LIT>".format(job_id=item_id))<EOL>if response.status_code == <NUM_LIT>:<EOL><INDENT>raise sandboxapi.SandboxError('<STR_LIT>')<EOL><DEDENT>if report_format == "<STR_LIT>":<EOL><INDENT>try:<EOL><INDENT>return json.loads(response.content.decode('<STR_LIT:utf-8>'))<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return response.content.decode('<STR_LIT:utf-8>')<EOL>
|
Retrieves the specified report for the analyzed item, referenced by item_id.
Available formats include: json, html.
:type item_id: str
:param item_id: File ID number
:type report_format: str
:param report_format: Return format
:rtype: dict
:return: Dictionary representing the JSON parsed data or raw, for other
formats / JSON parsing failure.
|
f11636:c0:m6
|
def full_report(self, item_id, report_format="<STR_LIT>"):
|
report_format = report_format.lower()<EOL>response = self._request("<STR_LIT>".format(job_id=item_id, report_format=report_format))<EOL>if response.status_code == <NUM_LIT>:<EOL><INDENT>raise sandboxapi.SandboxError('<STR_LIT>')<EOL><DEDENT>if report_format == "<STR_LIT>":<EOL><INDENT>try:<EOL><INDENT>return json.loads(response.content.decode('<STR_LIT:utf-8>'))<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return response.content.decode('<STR_LIT:utf-8>')<EOL>
|
Retrieves a more detailed report
|
f11636:c0:m7
|
def score(self, report):
|
try:<EOL><INDENT>threatlevel = int(report['<STR_LIT>'])<EOL>threatscore = int(report['<STR_LIT>'])<EOL><DEDENT>except (KeyError, IndexError, ValueError, TypeError) as e:<EOL><INDENT>raise sandboxapi.SandboxError(e)<EOL><DEDENT>score = <NUM_LIT:0><EOL>if threatlevel == <NUM_LIT:2> and threatscore >= <NUM_LIT>:<EOL><INDENT>score = <NUM_LIT:10><EOL><DEDENT>elif threatlevel == <NUM_LIT:2> and threatscore >= <NUM_LIT>:<EOL><INDENT>score = <NUM_LIT:9><EOL><DEDENT>elif threatlevel == <NUM_LIT:2>:<EOL><INDENT>score = <NUM_LIT:8><EOL><DEDENT>elif threatlevel == <NUM_LIT:1> and threatscore >= <NUM_LIT>:<EOL><INDENT>score = <NUM_LIT:7><EOL><DEDENT>elif threatlevel == <NUM_LIT:1> and threatscore >= <NUM_LIT>:<EOL><INDENT>score = <NUM_LIT:6><EOL><DEDENT>elif threatlevel == <NUM_LIT:1>:<EOL><INDENT>score = <NUM_LIT:5><EOL><DEDENT>elif threatlevel == <NUM_LIT:0> and threatscore < <NUM_LIT>:<EOL><INDENT>score = <NUM_LIT:1><EOL><DEDENT>return score<EOL>
|
Pass in the report from self.report(), get back an int 0-10.
|
f11636:c0:m8
|
def __init__(self, api_key, url=None, verify_ssl=True, **kwargs):
|
sandboxapi.SandboxAPI.__init__(self, **kwargs)<EOL>self.base_url = url or '<STR_LIT>'<EOL>self.api_url = self.base_url + '<STR_LIT>'<EOL>self.api_key = api_key<EOL>self.verify_ssl = verify_ssl<EOL>self.headers = {'<STR_LIT>': '<STR_LIT>'.format(a=api_key)}<EOL>
|
Initialize the interface to VMRay Sandbox API.
|
f11637:c0:m0
|
def analyze(self, handle, filename):
|
<EOL>files = {"<STR_LIT>": (filename, handle)}<EOL>handle.seek(<NUM_LIT:0>)<EOL>response = self._request("<STR_LIT>", method='<STR_LIT:POST>', files=files, headers=self.headers)<EOL>try:<EOL><INDENT>if response.status_code == <NUM_LIT:200> and not response.json()['<STR_LIT:data>']['<STR_LIT>']:<EOL><INDENT>return response.json()['<STR_LIT:data>']['<STR_LIT>'][<NUM_LIT:0>]['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>raise sandboxapi.SandboxError("<STR_LIT>".format(u=response.url, r=response.content))<EOL><DEDENT><DEDENT>except (ValueError, KeyError, IndexError) as e:<EOL><INDENT>raise sandboxapi.SandboxError("<STR_LIT>".format(e=e))<EOL><DEDENT>
|
Submit a file for analysis.
:type handle: File handle
:param handle: Handle to file to upload for analysis.
:type filename: str
:param filename: File name.
:rtype: str
:return: File ID as a string
|
f11637:c0:m1
|
def check(self, item_id):
|
response = self._request("<STR_LIT>".format(sample_id=item_id), headers=self.headers)<EOL>if response.status_code == <NUM_LIT>:<EOL><INDENT>return False<EOL><DEDENT>try:<EOL><INDENT>finished = False<EOL>for submission in response.json()['<STR_LIT:data>']:<EOL><INDENT>finished = finished or submission['<STR_LIT>']<EOL><DEDENT>if finished:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>except (ValueError, KeyError) as e:<EOL><INDENT>raise sandboxapi.SandboxError(e)<EOL><DEDENT>return False<EOL>
|
Check if an analysis is complete.
:type item_id: str
:param item_id: File ID to check.
:rtype: bool
:return: Boolean indicating if a report is done or not.
|
f11637:c0:m2
|
def is_available(self):
|
<EOL>if self.server_available:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>response = self._request("<STR_LIT>", headers=self.headers)<EOL>if response.status_code == <NUM_LIT:200>:<EOL><INDENT>self.server_available = True<EOL>return True<EOL><DEDENT><DEDENT>except sandboxapi.SandboxError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>self.server_available = False<EOL>return False<EOL>
|
Determine if the VMRay API server is alive.
:rtype: bool
:return: True if service is available, False otherwise.
|
f11637:c0:m3
|
def report(self, item_id, report_format="<STR_LIT>"):
|
if report_format == "<STR_LIT:html>":<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>response = self._request("<STR_LIT>".format(sample_id=item_id),<EOL>headers=self.headers)<EOL>try:<EOL><INDENT>analysis_id = <NUM_LIT:0><EOL>top_score = -<NUM_LIT:1><EOL>for analysis in response.json()['<STR_LIT:data>']:<EOL><INDENT>if analysis['<STR_LIT>'] > top_score:<EOL><INDENT>top_score = analysis['<STR_LIT>']<EOL>analysis_id = analysis['<STR_LIT>']<EOL><DEDENT><DEDENT><DEDENT>except (ValueError, KeyError) as e:<EOL><INDENT>raise sandboxapi.SandboxError(e)<EOL><DEDENT>response = self._request("<STR_LIT>".format(analysis_id=analysis_id),<EOL>headers=self.headers)<EOL>try:<EOL><INDENT>return response.json()<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT>return response.content<EOL>
|
Retrieves the specified report for the analyzed item, referenced by item_id.
Available formats include: json.
:type item_id: str
:param item_id: File ID number
:type report_format: str
:param report_format: Return format
:rtype: dict
:return: Dictionary representing the JSON parsed data or raw, for other
formats / JSON parsing failure.
|
f11637:c0:m4
|
def score(self, report):
|
try:<EOL><INDENT>return report['<STR_LIT>']['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>
|
Pass in the report from self.report(), get back an int 0-100
|
f11637:c0:m5
|
def __init__(self, url, port=<NUM_LIT>, api_path='<STR_LIT:/>', verify_ssl=False, **kwargs):
|
sandboxapi.SandboxAPI.__init__(self, **kwargs)<EOL>if not url:<EOL><INDENT>url = '<STR_LIT>'<EOL><DEDENT>if url.startswith('<STR_LIT>') or url.startswith('<STR_LIT>'):<EOL><INDENT>self.api_url = url<EOL><DEDENT>else:<EOL><INDENT>self.api_url = '<STR_LIT>' + url + '<STR_LIT::>' + str(port) + api_path<EOL><DEDENT>self.verify_ssl = verify_ssl<EOL>self.server_available = False<EOL>
|
Initialize the interface to Cuckoo Sandbox API with host and port.
:type url: str
:param url: Cuckoo API URL. (Currently treated as host if not a fully formed URL -
this will be removed in a future version.)
:type port: int
:param port: DEPRECATED! Use fully formed url instead. Will be removed in future version.
:type api_path: str
:param api_path: DEPRECATED! Use fully formed url instead. Will be removed in future version.
|
f11638:c0:m0
|
def analyses(self):
|
response = self._request("<STR_LIT>")<EOL>return json.loads(response.content.decode('<STR_LIT:utf-8>'))['<STR_LIT>']<EOL>
|
Retrieve a list of analyzed samples.
:rtype: list
:return: List of objects referencing each analyzed file.
|
f11638:c0:m1
|
def analyze(self, handle, filename):
|
<EOL>files = {"<STR_LIT:file>": (filename, handle)}<EOL>handle.seek(<NUM_LIT:0>)<EOL>response = self._request("<STR_LIT>", method='<STR_LIT:POST>', files=files)<EOL>try:<EOL><INDENT>return str(json.loads(response.content.decode('<STR_LIT:utf-8>'))["<STR_LIT>"])<EOL><DEDENT>except KeyError:<EOL><INDENT>return str(json.loads(response.content.decode('<STR_LIT:utf-8>'))["<STR_LIT>"][<NUM_LIT:0>])<EOL><DEDENT>
|
Submit a file for analysis.
:type handle: File handle
:param handle: Handle to file to upload for analysis.
:type filename: str
:param filename: File name.
:rtype: str
:return: Task ID as a string
|
f11638:c0:m2
|
def check(self, item_id):
|
response = self._request("<STR_LIT>".format(id=item_id))<EOL>if response.status_code == <NUM_LIT>:<EOL><INDENT>return False<EOL><DEDENT>try:<EOL><INDENT>content = json.loads(response.content.decode('<STR_LIT:utf-8>'))<EOL>status = content['<STR_LIT>']["<STR_LIT:status>"]<EOL>if status == '<STR_LIT>' or status == "<STR_LIT>":<EOL><INDENT>return True<EOL><DEDENT><DEDENT>except ValueError as e:<EOL><INDENT>raise sandboxapi.SandboxError(e)<EOL><DEDENT>return False<EOL>
|
Check if an analysis is complete
:type item_id: int
:param item_id: task_id to check.
:rtype: bool
:return: Boolean indicating if a report is done or not.
|
f11638:c0:m3
|
def delete(self, item_id):
|
try:<EOL><INDENT>response = self._request("<STR_LIT>".format(id=item_id))<EOL>if response.status_code == <NUM_LIT:200>:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>except sandboxapi.SandboxError:<EOL><INDENT>pass<EOL><DEDENT>return False<EOL>
|
Delete the reports associated with the given item_id.
:type item_id: int
:param item_id: Report ID to delete.
:rtype: bool
:return: True on success, False otherwise.
|
f11638:c0:m4
|
def is_available(self):
|
<EOL>if self.server_available:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>response = self._request("<STR_LIT>")<EOL>if response.status_code == <NUM_LIT:200>:<EOL><INDENT>self.server_available = True<EOL>return True<EOL><DEDENT><DEDENT>except sandboxapi.SandboxError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>self.server_available = False<EOL>return False<EOL>
|
Determine if the Cuckoo Sandbox API servers are alive or in maintenance mode.
:rtype: bool
:return: True if service is available, False otherwise.
|
f11638:c0:m5
|
def queue_size(self):
|
response = self._request("<STR_LIT>")<EOL>tasks = json.loads(response.content.decode('<STR_LIT:utf-8>'))["<STR_LIT>"]<EOL>return len([t for t in tasks if t['<STR_LIT:status>'] == '<STR_LIT>'])<EOL>
|
Determine Cuckoo sandbox queue length
There isn't a built in way to do this like with Joe
:rtype: int
:return: Number of submissions in sandbox queue.
|
f11638:c0:m6
|
def report(self, item_id, report_format="<STR_LIT>"):
|
report_format = report_format.lower()<EOL>response = self._request("<STR_LIT>".format(id=item_id, format=report_format))<EOL>if report_format == "<STR_LIT>":<EOL><INDENT>try:<EOL><INDENT>return json.loads(response.content.decode('<STR_LIT:utf-8>'))<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return response.content<EOL>
|
Retrieves the specified report for the analyzed item, referenced by item_id.
Available formats include: json, html, all, dropped, package_files.
:type item_id: int
:param item_id: Task ID number
:type report_format: str
:param report_format: Return format
:rtype: dict
:return: Dictionary representing the JSON parsed data or raw, for other
formats / JSON parsing failure.
|
f11638:c0:m7
|
def score(self, report):
|
score = <NUM_LIT:0><EOL>try:<EOL><INDENT>score = report['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>score = report.get('<STR_LIT:info>', {}).get('<STR_LIT>', <NUM_LIT:0>)<EOL><DEDENT>return score<EOL>
|
Pass in the report from self.report(), get back an int.
|
f11638:c0:m8
|
def __init__(self, *args, **kwargs):
|
self.api_url = None<EOL>self.server_available = False<EOL>self.verify_ssl = True<EOL>self.proxies = kwargs.get('<STR_LIT>')<EOL>
|
Initialize the interface to Sandbox API.
:type proxies: dict
:param proxies: Optional proxies dict passed to requests calls.
|
f11639:c1:m0
|
def _request(self, uri, method='<STR_LIT:GET>', params=None, files=None, headers=None, auth=None):
|
<EOL>for i in range(<NUM_LIT:3>):<EOL><INDENT>try:<EOL><INDENT>full_url = '<STR_LIT>'.format(b=self.api_url, u=uri)<EOL>response = None<EOL>if method == '<STR_LIT:POST>':<EOL><INDENT>response = requests.post(full_url, data=params, files=files, headers=headers,<EOL>verify=self.verify_ssl, auth=auth, proxies=self.proxies)<EOL><DEDENT>else:<EOL><INDENT>response = requests.get(full_url, params=params, headers=headers,<EOL>verify=self.verify_ssl, auth=auth, proxies=self.proxies)<EOL><DEDENT>if response.status_code >= <NUM_LIT>:<EOL><INDENT>self.server_available = False<EOL>raise SandboxError("<STR_LIT>".format(<EOL>c=response.status_code, u=response.url))<EOL><DEDENT>else:<EOL><INDENT>return response<EOL><DEDENT><DEDENT>except requests.exceptions.RequestException:<EOL><INDENT>time.sleep(random.uniform(<NUM_LIT:0>, <NUM_LIT:4> ** i * <NUM_LIT:100> / <NUM_LIT>))<EOL><DEDENT><DEDENT>self.server_available = False<EOL>msg = "<STR_LIT>".format(u=full_url,<EOL>p=params, f=files)<EOL>try:<EOL><INDENT>msg += "<STR_LIT:\n>" + response.content.decode('<STR_LIT:utf-8>')<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>raise SandboxError(msg)<EOL>
|
Robustness wrapper. Tries up to 3 times to dance with the Sandbox API.
:type uri: str
:param uri: URI to append to base_url.
:type params: dict
:param params: Optional parameters for API.
:type files: dict
:param files: Optional dictionary of files for multipart post.
:type headers: dict
:param headers: Optional headers to send to the API.
:type auth: dict
:param auth: Optional authentication object to send to the API.
:rtype: requests.response.
:return: Response object.
:raises SandboxError: If all attempts failed.
|
f11639:c1:m1
|
def analyses(self):
|
raise NotImplementedError<EOL>
|
Retrieve a list of analyzed samples.
:rtype: list
:return: List of objects referencing each analyzed file.
|
f11639:c1:m2
|
def analyze(self, handle, filename):
|
raise NotImplementedError<EOL>
|
Submit a file for analysis.
:type handle: File handle
:param handle: Handle to file to upload for analysis.
:type filename: str
:param filename: File name.
:rtype: str
:return: Item ID as a string
|
f11639:c1:m3
|
def check(self, item_id):
|
raise NotImplementedError<EOL>
|
Check if an analysis is complete
:type item_id: int | str
:param item_id: item_id to check.
:rtype: bool
:return: Boolean indicating if a report is done or not.
|
f11639:c1:m4
|
def delete(self, item_id):
|
raise NotImplementedError<EOL>
|
Delete the reports associated with the given item_id.
:type item_id: int | str
:param item_id: Report ID to delete.
:rtype: bool
:return: True on success, False otherwise.
|
f11639:c1:m5
|
def is_available(self):
|
raise NotImplementedError<EOL>
|
Determine if the Sandbox API servers are alive or in maintenance mode.
:rtype: bool
:return: True if service is available, False otherwise.
|
f11639:c1:m6
|
def queue_size(self):
|
raise NotImplementedError<EOL>
|
Determine sandbox queue length
:rtype: int
:return: Number of submissions in sandbox queue.
|
f11639:c1:m7
|
def report(self, item_id, report_format="<STR_LIT>"):
|
raise NotImplementedError<EOL>
|
Retrieves the specified report for the analyzed item, referenced by item_id.
:type item_id: int | str
:param item_id: Item ID
:rtype: dict
:return: Dictionary representing the JSON parsed data or raw, for other
formats / JSON parsing failure.
|
f11639:c1:m8
|
def __init__(self, apikey, apiurl, accept_tac, timeout=None, verify_ssl=True, retries=<NUM_LIT:3>, **kwargs):
|
sandboxapi.SandboxAPI.__init__(self)<EOL>self.jbx = jbxapi.JoeSandbox(apikey, apiurl or jbxapi.API_URL, accept_tac, timeout, verify_ssl, retries, **kwargs)<EOL>
|
Initialize the interface to Joe Sandbox API.
|
f11640:c0:m0
|
def analyze(self, handle, filename):
|
<EOL>handle.seek(<NUM_LIT:0>)<EOL>try:<EOL><INDENT>return self.jbx.submit_sample(handle)['<STR_LIT>'][<NUM_LIT:0>]<EOL><DEDENT>except (jbxapi.JoeException, KeyError, IndexError) as e:<EOL><INDENT>raise sandboxapi.SandboxError("<STR_LIT>".format(e=e))<EOL><DEDENT>
|
Submit a file for analysis.
:type handle: File handle
:param handle: Handle to file to upload for analysis.
:type filename: str
:param filename: File name.
:rtype: str
:return: Task ID as a string
|
f11640:c0:m1
|
def check(self, item_id):
|
try:<EOL><INDENT>return self.jbx.info(item_id).get('<STR_LIT:status>').lower() == '<STR_LIT>'<EOL><DEDENT>except jbxapi.JoeException:<EOL><INDENT>return False<EOL><DEDENT>return False<EOL>
|
Check if an analysis is complete.
:type item_id: str
:param item_id: File ID to check.
:rtype: bool
:return: Boolean indicating if a report is done or not.
|
f11640:c0:m2
|
def is_available(self):
|
<EOL>if self.server_available:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>self.server_available = self.jbx.server_online()<EOL>return self.server_available<EOL><DEDENT>except jbxapi.JoeException:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>self.server_available = False<EOL>return False<EOL>
|
Determine if the Joe Sandbox API server is alive.
:rtype: bool
:return: True if service is available, False otherwise.
|
f11640:c0:m3
|
def report(self, item_id, report_format="<STR_LIT>"):
|
if report_format == "<STR_LIT>":<EOL><INDENT>report_format = "<STR_LIT>"<EOL><DEDENT>try:<EOL><INDENT>return json.loads(self.jbx.download(item_id, report_format)[<NUM_LIT:1>].decode('<STR_LIT:utf-8>'))<EOL><DEDENT>except (jbxapi.JoeException, ValueError, IndexError) as e:<EOL><INDENT>raise sandboxapi.SandboxError("<STR_LIT>".format(e=e))<EOL><DEDENT>
|
Retrieves the specified report for the analyzed item, referenced by item_id.
For available report formats, see online Joe Sandbox documentation.
:type item_id: str
:param item_id: File ID number
:type report_format: str
:param report_format: Return format
:rtype: dict
:return: Dictionary representing the JSON parsed data or raw, for other
formats / JSON parsing failure.
|
f11640:c0:m4
|
def score(self, report):
|
try:<EOL><INDENT>return report['<STR_LIT>']['<STR_LIT>']['<STR_LIT>'][<NUM_LIT:1>]['<STR_LIT>']<EOL><DEDENT>except (KeyError, IndexError):<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>
|
Pass in the report from self.report(), get back an int.
|
f11640:c0:m5
|
def acquire_auth_token_ticket(self, headers=None):
|
logging.debug('<STR_LIT>')<EOL>url = self._get_auth_token_tickets_url()<EOL>text = self._perform_post(url, headers=headers)<EOL>auth_token_ticket = json.loads(text)['<STR_LIT>']<EOL>logging.debug('<STR_LIT>'.format(<EOL>auth_token_ticket))<EOL>return auth_token_ticket<EOL>
|
Acquire an auth token from the CAS server.
|
f11646:c0:m1
|
def create_session(self, ticket, payload=None, expires=None):
|
assert isinstance(self.session_storage_adapter, CASSessionAdapter)<EOL>logging.debug('<STR_LIT>'.format(ticket))<EOL>self.session_storage_adapter.create(<EOL>ticket,<EOL>payload=payload,<EOL>expires=expires,<EOL>)<EOL>
|
Create a session record from a service ticket.
|
f11646:c0:m2
|
def delete_session(self, ticket):
|
assert isinstance(self.session_storage_adapter, CASSessionAdapter)<EOL>logging.debug('<STR_LIT>'.format(ticket))<EOL>self.session_storage_adapter.delete(ticket)<EOL>
|
Delete a session record associated with a service ticket.
|
f11646:c0:m3
|
def get_api_url(<EOL>self,<EOL>api_resource,<EOL>auth_token_ticket,<EOL>authenticator,<EOL>private_key,<EOL>service_url=None,<EOL>**kwargs<EOL>):
|
auth_token, auth_token_signature = self._build_auth_token_data(<EOL>auth_token_ticket,<EOL>authenticator,<EOL>private_key,<EOL>**kwargs<EOL>)<EOL>params = {<EOL>'<STR_LIT>': auth_token,<EOL>'<STR_LIT>': auth_token_signature,<EOL>}<EOL>if service_url is not None:<EOL><INDENT>params['<STR_LIT>'] = service_url<EOL><DEDENT>url = '<STR_LIT>'.format(<EOL>self._get_api_url(api_resource),<EOL>urlencode(params),<EOL>)<EOL>return url<EOL>
|
Build an auth-token-protected CAS API url.
|
f11646:c0:m4
|
def get_auth_token_login_url(<EOL>self,<EOL>auth_token_ticket,<EOL>authenticator,<EOL>private_key,<EOL>service_url,<EOL>username,<EOL>):
|
auth_token, auth_token_signature = self._build_auth_token_data(<EOL>auth_token_ticket,<EOL>authenticator,<EOL>private_key,<EOL>username=username,<EOL>)<EOL>logging.debug('<STR_LIT>'.format(auth_token))<EOL>url = self._get_auth_token_login_url(<EOL>auth_token=auth_token,<EOL>auth_token_signature=auth_token_signature,<EOL>service_url=service_url,<EOL>)<EOL>logging.debug('<STR_LIT>'.format(url))<EOL>return url<EOL>
|
Build an auth token login URL.
See https://github.com/rbCAS/CASino/wiki/Auth-Token-Login for details.
|
f11646:c0:m5
|
def get_destroy_other_sessions_url(self, service_url=None):
|
template = '<STR_LIT>'<EOL>url = template.format(<EOL>server_url=self.server_url,<EOL>auth_prefix=self.auth_prefix,<EOL>service_url=service_url or self.service_url,<EOL>)<EOL>logging.debug('<STR_LIT>'.format(url))<EOL>return url<EOL>
|
Get the URL for a remote CAS `destroy-other-sessions` endpoint.
::
>>> from cas_client import CASClient
>>> client = CASClient('https://logmein.com')
>>> service_url = 'http://myservice.net'
>>> client.get_destroy_other_sessions_url(service_url)
'https://logmein.com/cas/destroy-other-sessions?service=http://myservice.net'
|
f11646:c0:m6
|
def get_login_url(self, service_url=None):
|
template = '<STR_LIT>'<EOL>url = template.format(<EOL>server_url=self.server_url,<EOL>auth_prefix=self.auth_prefix,<EOL>service_url=service_url or self.service_url,<EOL>)<EOL>logging.debug('<STR_LIT>'.format(url))<EOL>return url<EOL>
|
Get the URL for a remote CAS `login` endpoint.
::
>>> from cas_client import CASClient
>>> client = CASClient('https://logmein.com')
>>> service_url = 'http://myservice.net'
>>> client.get_login_url(service_url)
'https://logmein.com/cas/login?service=http://myservice.net'
|
f11646:c0:m7
|
def get_logout_url(self, service_url=None):
|
template = '<STR_LIT>'<EOL>url = template.format(<EOL>server_url=self.server_url,<EOL>auth_prefix=self.auth_prefix,<EOL>service_url=service_url or self.service_url,<EOL>)<EOL>logging.debug('<STR_LIT>'.format(url))<EOL>return url<EOL>
|
Get the URL for a remote CAS `logout` endpoint.
::
>>> from cas_client import CASClient
>>> client = CASClient('https://logmein.com')
>>> service_url = 'http://myservice.net'
>>> client.get_logout_url(service_url)
'https://logmein.com/cas/logout?service=http://myservice.net'
|
f11646:c0:m8
|
def parse_logout_request(self, message_text):
|
result = {}<EOL>xml_document = parseString(message_text)<EOL>for node in xml_document.getElementsByTagName('<STR_LIT>'):<EOL><INDENT>for child in node.childNodes:<EOL><INDENT>if child.nodeType == child.TEXT_NODE:<EOL><INDENT>result['<STR_LIT>'] = child.nodeValue.strip()<EOL><DEDENT><DEDENT><DEDENT>for node in xml_document.getElementsByTagName('<STR_LIT>'):<EOL><INDENT>for child in node.childNodes:<EOL><INDENT>if child.nodeType == child.TEXT_NODE:<EOL><INDENT>result['<STR_LIT>'] = str(child.nodeValue.strip())<EOL><DEDENT><DEDENT><DEDENT>for key in xml_document.documentElement.attributes.keys():<EOL><INDENT>result[str(key)] = str(xml_document.documentElement.getAttribute(key))<EOL><DEDENT>logging.debug('<STR_LIT>'.format(<EOL>json.dumps(result, sort_keys=True, indent=<NUM_LIT:4>, separators=['<STR_LIT:U+002C>', '<STR_LIT>']),<EOL>))<EOL>return result<EOL>
|
Parse the contents of a CAS `LogoutRequest` XML message.
::
>>> from cas_client import CASClient
>>> client = CASClient('https://logmein.com')
>>> message_text = """
... <samlp:LogoutRequest
... xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
... xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
... ID="935a2d0c-4026-481e-be3d-20a1b2cdd553"
... Version="2.0"
... IssueInstant="2016-04-08 00:40:55 +0000">
... <saml:NameID>@NOT_USED@</saml:NameID>
... <samlp:SessionIndex>ST-14600760351898-0B3lSFt2jOWSbgQ377B4CtbD9uq0MXR9kG23vAuH</samlp:SessionIndex>
... </samlp:LogoutRequest>
... """
>>> parsed_message = client.parse_logout_request(message_text)
>>> import pprint
>>> pprint.pprint(parsed_message)
{'ID': '935a2d0c-4026-481e-be3d-20a1b2cdd553',
'IssueInstant': '2016-04-08 00:40:55 +0000',
'Version': '2.0',
'session_index': 'ST-14600760351898-0B3lSFt2jOWSbgQ377B4CtbD9uq0MXR9kG23vAuH',
'xmlns:saml': 'urn:oasis:names:tc:SAML:2.0:assertion',
'xmlns:samlp': 'urn:oasis:names:tc:SAML:2.0:protocol'}
|
f11646:c0:m9
|
def perform_api_request(<EOL>self,<EOL>url,<EOL>method='<STR_LIT:POST>',<EOL>headers=None,<EOL>body=None,<EOL>**kwargs<EOL>):
|
assert method in ('<STR_LIT:GET>', '<STR_LIT:POST>')<EOL>if method == '<STR_LIT:GET>':<EOL><INDENT>response = self._perform_get(url, headers=headers, **kwargs)<EOL><DEDENT>elif method == '<STR_LIT:POST>':<EOL><INDENT>response = self._perform_post(url, headers=headers, data=body, **kwargs)<EOL><DEDENT>return response<EOL>
|
Perform an auth-token-protected request against a CAS API endpoint.
|
f11646:c0:m10
|
def perform_proxy(self, proxy_ticket, headers=None):
|
url = self._get_proxy_url(ticket=proxy_ticket)<EOL>logging.debug('<STR_LIT>'.format(url))<EOL>return self._perform_cas_call(<EOL>url,<EOL>ticket=proxy_ticket,<EOL>headers=headers,<EOL>)<EOL>
|
Fetch a response from the remote CAS `proxy` endpoint.
|
f11646:c0:m11
|
def perform_proxy_validate(self, proxied_service_ticket, headers=None):
|
url = self._get_proxy_validate_url(ticket=proxied_service_ticket)<EOL>logging.debug('<STR_LIT>'.format(url))<EOL>return self._perform_cas_call(<EOL>url,<EOL>ticket=proxied_service_ticket,<EOL>headers=headers,<EOL>)<EOL>
|
Fetch a response from the remote CAS `proxyValidate` endpoint.
|
f11646:c0:m12
|
def perform_service_validate(<EOL>self,<EOL>ticket=None,<EOL>service_url=None,<EOL>headers=None,<EOL>):
|
url = self._get_service_validate_url(ticket, service_url=service_url)<EOL>logging.debug('<STR_LIT>'.format(url))<EOL>return self._perform_cas_call(url, ticket=ticket, headers=headers)<EOL>
|
Fetch a response from the remote CAS `serviceValidate` endpoint.
|
f11646:c0:m13
|
def session_exists(self, ticket):
|
assert isinstance(self.session_storage_adapter, CASSessionAdapter)<EOL>exists = self.session_storage_adapter.exists(ticket)<EOL>logging.debug('<STR_LIT>'.format(ticket, exists))<EOL>return exists<EOL>
|
Test if a session records exists for a service ticket.
|
f11646:c0:m14
|
@property<EOL><INDENT>def auth_prefix(self):<DEDENT>
|
return self._auth_prefix<EOL>
|
The CAS client's auth prefix. Typically "/cas".
|
f11646:c0:m26
|
@property<EOL><INDENT>def proxy_callback(self):<DEDENT>
|
return self._proxy_callback<EOL>
|
The CAS client's proxy callback address.
|
f11646:c0:m28
|
@property<EOL><INDENT>def proxy_url(self):<DEDENT>
|
return self._proxy_url<EOL>
|
The CAS client's proxy URL.
|
f11646:c0:m29
|
@property<EOL><INDENT>def server_url(self):<DEDENT>
|
return self._server_url<EOL>
|
The CAS client's CAS server URL (i.e. the server name of the CAS
service).
|
f11646:c0:m30
|
@property<EOL><INDENT>def service_url(self):<DEDENT>
|
return self._service_url<EOL>
|
The CAS client's default service URL.
This can typically be overriden in any method call.
|
f11646:c0:m31
|
@property<EOL><INDENT>def session_storage_adapter(self):<DEDENT>
|
return self._session_storage_adapter<EOL>
|
The CAS client's session storage adapter for maintaining session state.
|
f11646:c0:m32
|
@property<EOL><INDENT>def validate_url(self):<DEDENT>
|
return self._validate_url<EOL>
|
The CAS client's validation URL.
Defaults to the server_url, should only be set if using a separate
hostname for internal calls to /validateService.
|
f11646:c0:m33
|
@property<EOL><INDENT>def verify_certificates(self):<DEDENT>
|
return self._verify_certificates<EOL>
|
Flag for controlling whether the CAS client verifies SSL certificates
in its ``requests`` calls.
|
f11646:c0:m34
|
@abc.abstractmethod<EOL><INDENT>def create(self, ticket, payload=None, expires=None):<DEDENT>
|
raise NotImplementedError<EOL>
|
Create a session identifier associated with ``ticket``.
|
f11646:c2:m0
|
@abc.abstractmethod<EOL><INDENT>def delete(self, ticket):<DEDENT>
|
raise NotImplementedError<EOL>
|
Destroy a session identifier associated with ``ticket``.
|
f11646:c2:m1
|
@abc.abstractmethod<EOL><INDENT>def exists(self, ticket):<DEDENT>
|
raise NotImplementedError<EOL>
|
Test if a session identifier exists for ``ticket``.
|
f11646:c2:m2
|
def create(self, ticket, payload=None, expires=None):
|
if not payload:<EOL><INDENT>payload = True<EOL><DEDENT>self._client.set(str(ticket), payload, expires)<EOL>
|
Create a session identifier in memcache associated with ``ticket``.
|
f11646:c3:m1
|
def delete(self, ticket):
|
self._client.delete(str(ticket))<EOL>
|
Destroy a session identifier in memcache associated with ``ticket``.
|
f11646:c3:m2
|
def exists(self, ticket):
|
return self._client.get(str(ticket)) is not None<EOL>
|
Test if a session identifier exists for ``ticket``.
|
f11646:c3:m3
|
def iterate_dictionary(d, path, squash_single = False):
|
path_parts = path.split("<STR_LIT:/>")<EOL>return_list = []<EOL>if len(path_parts) == <NUM_LIT:0>: <EOL><INDENT>return d<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>sub_dicts = [d] <EOL>for i in range(<NUM_LIT:0>, len(path_parts)): <EOL><INDENT>new_sub_dicts = [] <EOL>for s in sub_dicts:<EOL><INDENT>if path_parts[i] in s: <EOL><INDENT>the_list = s[path_parts[i]] if isinstance(s[path_parts[i]], list) else [s[path_parts[i]]]<EOL>for j in the_list: <EOL><INDENT>if i < len(path_parts) -<NUM_LIT:1>: <EOL><INDENT>if isinstance(j, dict): <EOL><INDENT>new_sub_dicts.append(j) <EOL><DEDENT><DEDENT>else: <EOL><INDENT>return_list.append(j)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>sub_dicts = new_sub_dicts<EOL><DEDENT>return return_list[<NUM_LIT:0>] if squash_single and len(return_list) == <NUM_LIT:1> else return_list if len(return_list) >= <NUM_LIT:1> else None<EOL><DEDENT>except:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>
|
Takes a dict, and a path delimited with slashes like A/B/C/D, and returns a list of objects found at all leaf nodes at all trajectories `dict[A][B][C][D]`. It does this using BFS not DFS.
The word "leaf" hereby refers to an item at the search path level. That is, upon calling the function
iterate_dictionary(d_to_search, "A/B/C/D")
If `d_to_search` has five levels A/B/C/D/E, then D is the "leaf node level". Since `[E]` exists, then at least one object in the return list will be a dictionary.
Rules
===========================
Each node can be either
1) an arbitrary non-list, non-dictionary object
2) a dictionary
3) a list of arbitrary objects
All nodes of type 3 at each level are searched for nodes of type 1 and 2. Nodes of type 2 are the ones iterated in this tree search.
At the current time, nodes of type 1 are *not* inspected. They are returned in a list if they are at the search path and ignored otherwise.
Returns
===========================
1) If the path is an empty string, returns the original dict
2) *If* at least one object exists at the search path, it returns a list of all items at the search path. Using the above example terminology, a list of all objects at all trajectories `"A/B/C/D"`.
*Special Parameter*: If the optional Boolean parameter `squash_single` is True, and the return list contains only one object, the object is returned (*not* a list), else a list with that one object is returned. This optional flag is useful so that [0] does not have to be indexed on the return list in the case where only one item is expected.
3) None in the case that there are no objects at the search path.
|
f11649:m0
|
def get_all_values(d):
|
if not isinstance(d,dict):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return _get_all_values(d)<EOL>
|
This function returns a list of all values in a nested dictionary.
By nested, this means each item X in d can either be a dict, a list, or a "value".
Other iterables other than dicts and lists are treated as values and are not iterated currently.
Returns a list, or None if there are no values found (for example a nested structure of all
empty dicts)
|
f11649:m1
|
def draw(self, c):
|
for s in self.shapes:<EOL><INDENT>tk_draw_shape(s, c)<EOL><DEDENT>
|
Draw all shapes on the canvas
|
f11651:c11:m15
|
def draw_line(self, lx, ltor):
|
tag = self.get_tag()<EOL>c = self.canvas<EOL>s = self.style<EOL>sep = s.h_sep<EOL>exx = <NUM_LIT:0><EOL>exy = <NUM_LIT:0><EOL>terms = lx if ltor else reversed(lx) <EOL>for term in terms:<EOL><INDENT>t, texx, texy = self.draw_diagram(term, ltor) <EOL>if exx > <NUM_LIT:0>: <EOL><INDENT>xn = exx + sep <EOL>c.move(t, xn, exy) <EOL>arr = '<STR_LIT>' if ltor else '<STR_LIT>'<EOL>c.create_line(exx-<NUM_LIT:1>, exy, xn, exy, tags=(tag,), width=s.line_width, arrow=arr) <EOL>exx = xn + texx <EOL><DEDENT>else: <EOL><INDENT>exx = texx <EOL><DEDENT>exy = texy<EOL>c.addtag_withtag(tag, t) <EOL>c.dtag(t, t) <EOL><DEDENT>if exx == <NUM_LIT:0>: <EOL><INDENT>exx = sep * <NUM_LIT:2> <EOL>c.create_line(<NUM_LIT:0>,<NUM_LIT:0>,sep,<NUM_LIT:0>, width=s.line_width, tags=(tag,), arrow='<STR_LIT>')<EOL>c.create_line(sep, <NUM_LIT:0>,exx,<NUM_LIT:0>, width=s.line_width, tags=(tag,))<EOL>exx = sep<EOL><DEDENT>return [tag, exx, exy]<EOL>
|
Draw a series of elements from left to right
|
f11651:c12:m6
|
def _python_cmd(*args):
|
args = (sys.executable,) + args<EOL>return subprocess.call(args) == <NUM_LIT:0><EOL>
|
Execute a command.
Return True if the command succeeded.
|
f11652:m0
|
def _install(archive_filename, install_args=()):
|
with archive_context(archive_filename):<EOL><INDENT>log.warn('<STR_LIT>')<EOL>if not _python_cmd('<STR_LIT>', '<STR_LIT>', *install_args):<EOL><INDENT>log.warn('<STR_LIT>')<EOL>log.warn('<STR_LIT>')<EOL>return <NUM_LIT:2><EOL><DEDENT><DEDENT>
|
Install Setuptools.
|
f11652:m1
|
def _build_egg(egg, archive_filename, to_dir):
|
with archive_context(archive_filename):<EOL><INDENT>log.warn('<STR_LIT>', to_dir)<EOL>_python_cmd('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', to_dir)<EOL><DEDENT>log.warn(egg)<EOL>if not os.path.exists(egg):<EOL><INDENT>raise IOError('<STR_LIT>')<EOL><DEDENT>
|
Build Setuptools egg.
|
f11652:m2
|
@contextlib.contextmanager<EOL>def archive_context(filename):
|
tmpdir = tempfile.mkdtemp()<EOL>log.warn('<STR_LIT>', tmpdir)<EOL>old_wd = os.getcwd()<EOL>try:<EOL><INDENT>os.chdir(tmpdir)<EOL>with ContextualZipFile(filename) as archive:<EOL><INDENT>archive.extractall()<EOL><DEDENT>subdir = os.path.join(tmpdir, os.listdir(tmpdir)[<NUM_LIT:0>])<EOL>os.chdir(subdir)<EOL>log.warn('<STR_LIT>', subdir)<EOL>yield<EOL><DEDENT>finally:<EOL><INDENT>os.chdir(old_wd)<EOL>shutil.rmtree(tmpdir)<EOL><DEDENT>
|
Unzip filename to a temporary directory, set to the cwd.
The unzipped target is cleaned up after.
|
f11652:m3
|
def _do_download(version, download_base, to_dir, download_delay):
|
egg = os.path.join(to_dir, '<STR_LIT>'<EOL>% (version, sys.version_info[<NUM_LIT:0>], sys.version_info[<NUM_LIT:1>]))<EOL>if not os.path.exists(egg):<EOL><INDENT>archive = download_setuptools(version, download_base,<EOL>to_dir, download_delay)<EOL>_build_egg(egg, archive, to_dir)<EOL><DEDENT>sys.path.insert(<NUM_LIT:0>, egg)<EOL>if '<STR_LIT>' in sys.modules:<EOL><INDENT>_unload_pkg_resources()<EOL><DEDENT>import setuptools<EOL>setuptools.bootstrap_install_from = egg<EOL>
|
Download Setuptools.
|
f11652:m4
|
def use_setuptools(<EOL>version=DEFAULT_VERSION, download_base=DEFAULT_URL,<EOL>to_dir=DEFAULT_SAVE_DIR, download_delay=<NUM_LIT:15>):
|
to_dir = os.path.abspath(to_dir)<EOL>rep_modules = '<STR_LIT>', '<STR_LIT>'<EOL>imported = set(sys.modules).intersection(rep_modules)<EOL>try:<EOL><INDENT>import pkg_resources<EOL>pkg_resources.require("<STR_LIT>" + version)<EOL>return<EOL><DEDENT>except ImportError:<EOL><INDENT>pass<EOL><DEDENT>except pkg_resources.DistributionNotFound:<EOL><INDENT>pass<EOL><DEDENT>except pkg_resources.VersionConflict as VC_err:<EOL><INDENT>if imported:<EOL><INDENT>_conflict_bail(VC_err, version)<EOL><DEDENT>del pkg_resources<EOL>_unload_pkg_resources()<EOL><DEDENT>return _do_download(version, download_base, to_dir, download_delay)<EOL>
|
Ensure that a setuptools version is installed.
Return None. Raise SystemExit if the requested version
or later cannot be installed.
|
f11652:m5
|
def _conflict_bail(VC_err, version):
|
conflict_tmpl = textwrap.dedent("""<STR_LIT>""")<EOL>msg = conflict_tmpl.format(**locals())<EOL>sys.stderr.write(msg)<EOL>sys.exit(<NUM_LIT:2>)<EOL>
|
Setuptools was imported prior to invocation, so it is
unsafe to unload it. Bail out.
|
f11652:m6
|
def _clean_check(cmd, target):
|
try:<EOL><INDENT>subprocess.check_call(cmd)<EOL><DEDENT>except subprocess.CalledProcessError:<EOL><INDENT>if os.access(target, os.F_OK):<EOL><INDENT>os.unlink(target)<EOL><DEDENT>raise<EOL><DEDENT>
|
Run the command to download target.
If the command fails, clean up before re-raising the error.
|
f11652:m8
|
def download_file_powershell(url, target):
|
target = os.path.abspath(target)<EOL>ps_cmd = (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% vars()<EOL>)<EOL>cmd = [<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>ps_cmd,<EOL>]<EOL>_clean_check(cmd, target)<EOL>
|
Download the file at url to target using Powershell.
Powershell will validate trust.
Raise an exception if the command cannot complete.
|
f11652:m9
|
def has_powershell():
|
if platform.system() != '<STR_LIT>':<EOL><INDENT>return False<EOL><DEDENT>cmd = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>with open(os.path.devnull, '<STR_LIT:wb>') as devnull:<EOL><INDENT>try:<EOL><INDENT>subprocess.check_call(cmd, stdout=devnull, stderr=devnull)<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>
|
Determine if Powershell is available.
|
f11652:m10
|
def download_file_insecure(url, target):
|
src = urlopen(url)<EOL>try:<EOL><INDENT>data = src.read()<EOL><DEDENT>finally:<EOL><INDENT>src.close()<EOL><DEDENT>with open(target, "<STR_LIT:wb>") as dst:<EOL><INDENT>dst.write(data)<EOL><DEDENT>
|
Use Python to download the file, without connection authentication.
|
f11652:m15
|
def download_setuptools(<EOL>version=DEFAULT_VERSION, download_base=DEFAULT_URL,<EOL>to_dir=DEFAULT_SAVE_DIR, delay=<NUM_LIT:15>,<EOL>downloader_factory=get_best_downloader):
|
<EOL>to_dir = os.path.abspath(to_dir)<EOL>zip_name = "<STR_LIT>" % version<EOL>url = download_base + zip_name<EOL>saveto = os.path.join(to_dir, zip_name)<EOL>if not os.path.exists(saveto): <EOL><INDENT>log.warn("<STR_LIT>", url)<EOL>downloader = downloader_factory()<EOL>downloader(url, saveto)<EOL><DEDENT>return os.path.realpath(saveto)<EOL>
|
Download setuptools from a specified location and return its filename.
`version` should be a valid setuptools version number that is available
as an sdist for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download
attempt.
``downloader_factory`` should be a function taking no arguments and
returning a function for downloading a URL to a target.
|
f11652:m17
|
def _build_install_args(options):
|
return ['<STR_LIT>'] if options.user_install else []<EOL>
|
Build the arguments to 'python setup.py install' on the setuptools package.
Returns list of command line arguments.
|
f11652:m18
|
def _parse_args():
|
parser = optparse.OptionParser()<EOL>parser.add_option(<EOL>'<STR_LIT>', dest='<STR_LIT>', action='<STR_LIT:store_true>', default=False,<EOL>help='<STR_LIT>')<EOL>parser.add_option(<EOL>'<STR_LIT>', dest='<STR_LIT>', metavar="<STR_LIT>",<EOL>default=DEFAULT_URL,<EOL>help='<STR_LIT>')<EOL>parser.add_option(<EOL>'<STR_LIT>', dest='<STR_LIT>', action='<STR_LIT>',<EOL>const=lambda: download_file_insecure, default=get_best_downloader,<EOL>help='<STR_LIT>'<EOL>)<EOL>parser.add_option(<EOL>'<STR_LIT>', help="<STR_LIT>",<EOL>default=DEFAULT_VERSION,<EOL>)<EOL>parser.add_option(<EOL>'<STR_LIT>',<EOL>help="<STR_LIT>",<EOL>default=DEFAULT_SAVE_DIR,<EOL>)<EOL>options, args = parser.parse_args()<EOL>return options<EOL>
|
Parse the command line for options.
|
f11652:m19
|
def _download_args(options):
|
return dict(<EOL>version=options.version,<EOL>download_base=options.download_base,<EOL>downloader_factory=options.downloader_factory,<EOL>to_dir=options.to_dir,<EOL>)<EOL>
|
Return args for download_setuptools function from cmdline args.
|
f11652:m20
|
def main():
|
options = _parse_args()<EOL>archive = download_setuptools(**_download_args(options))<EOL>return _install(archive, _build_install_args(options))<EOL>
|
Install or upgrade setuptools and EasyInstall.
|
f11652:m21
|
def __new__(cls, *args, **kwargs):
|
if hasattr(zipfile.ZipFile, '<STR_LIT>'):<EOL><INDENT>return zipfile.ZipFile(*args, **kwargs)<EOL><DEDENT>return super(ContextualZipFile, cls).__new__(cls)<EOL>
|
Construct a ZipFile or ContextualZipFile as appropriate.
|
f11652:c0:m2
|
def __init__(self, mont_priv = None, mont_pub = None):
|
cls = self.__class__<EOL>if not (<EOL>isinstance(cls.MONT_PRIV_KEY_SIZE, int) and<EOL>isinstance(cls.MONT_PUB_KEY_SIZE, int) and<EOL>isinstance(cls.ED_PRIV_KEY_SIZE, int) and<EOL>isinstance(cls.ED_PUB_KEY_SIZE, int) and<EOL>isinstance(cls.SIGNATURE_SIZE, int)<EOL>):<EOL><INDENT>raise NotImplementedError("<STR_LIT>")<EOL><DEDENT>if mont_priv == None and mont_pub == None:<EOL><INDENT>mont_priv = cls.generate_mont_priv()<EOL><DEDENT>if not (mont_priv == None or isinstance(mont_priv, bytes)):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if mont_priv != None and len(mont_priv) != cls.MONT_PRIV_KEY_SIZE:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if mont_priv != None and mont_pub == None:<EOL><INDENT>mont_pub = cls.mont_pub_from_mont_priv(mont_priv)<EOL><DEDENT>if not (mont_pub == None or isinstance(mont_pub, bytes)):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if mont_pub != None and len(mont_pub) != cls.MONT_PUB_KEY_SIZE:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.__mont_priv = mont_priv<EOL>self.__mont_pub = mont_pub<EOL>
|
Create an XEdDSA object from Montgomery key material, to encrypt AND sign data
using just one Montgomery key pair.
:param mont_priv: A bytes-like object encoding the private key with length
MONT_PRIV_KEY_SIZE or None.
:param mont_pub: A bytes-like object encoding the public key with length
MONT_PUB_KEY_SIZE or None.
If both mont_priv and mont_pub are None, a new key pair is generated.
|
f11665:c0:m0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.