code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
content = Content(tag=tag, value=value) result = Core.process(self, content) return result
def process(self, value, tag=None)
Process (marshal) the tag with the specified value using the optional type information. @param value: The value (content) of the XML node. @type value: (L{Object}|any) @param tag: The (optional) tag name for the value. The default is value.__class__.__name__ @type tag: str @return: An xml node. @rtype: L{Element}
8.14441
10.16496
0.801224
reply = self.replyfilter(reply) sax = Parser() replyroot = sax.parse(string=reply) plugins = PluginContainer(self.options().plugins) plugins.message.parsed(reply=replyroot) soapenv = replyroot.getChild('Envelope') soapenv.promotePrefixes() soapbody = soapenv.getChild('Body') self.detect_fault(soapbody) soapbody = self.multiref.process(soapbody) nodes = self.replycontent(method, soapbody) rtypes = self.returned_types(method) if len(rtypes) > 1: result = self.replycomposite(rtypes, nodes) return (replyroot, result) if len(rtypes) == 1: if rtypes[0].unbounded(): result = self.replylist(rtypes[0], nodes) return (replyroot, result) if len(nodes): unmarshaller = self.unmarshaller() resolved = rtypes[0].resolve(nobuiltin=True) result = unmarshaller.process(nodes[0], resolved) return (replyroot, result) return (replyroot, None)
def get_reply(self, method, reply)
Process the I{reply} for the specified I{method} by sax parsing the I{reply} and then unmarshalling into python object(s). @param method: The name of the invoked method. @type method: str @param reply: The reply XML received after invoking the specified method. @type reply: str @return: The unmarshalled reply. The returned value is an L{Object} for a I{list} depending on whether the service returns a single object or a collection. @rtype: tuple ( L{Element}, L{Object} )
4.867318
4.687089
1.038452
fault = body.getChild('Fault', envns) if fault is None: return unmarshaller = self.unmarshaller(False) p = unmarshaller.process(fault) if self.options().faults: raise WebFault(p, fault) return self
def detect_fault(self, body)
Detect I{hidden} soapenv:Fault element in the soap body. @param body: The soap envelope body. @type body: L{Element} @raise WebFault: When found.
9.31443
8.071798
1.153947
result = [] resolved = rt.resolve(nobuiltin=True) unmarshaller = self.unmarshaller() for node in nodes: sobject = unmarshaller.process(node, resolved) result.append(sobject) return result
def replylist(self, rt, nodes)
Construct a I{list} reply. This method is called when it has been detected that the reply is a list. @param rt: The return I{type}. @type rt: L{suds.xsd.sxbase.SchemaObject} @param nodes: A collection of XML nodes. @type nodes: [L{Element},...] @return: A list of I{unmarshalled} objects. @rtype: [L{Object},...]
7.608968
6.203871
1.226487
dictionary = {} for rt in rtypes: dictionary[rt.name] = rt unmarshaller = self.unmarshaller() composite = Factory.object('reply') for node in nodes: tag = node.name rt = dictionary.get(tag, None) if rt is None: if node.get('id') is None: raise Exception('<%s/> not mapped to message part' % tag) else: continue resolved = rt.resolve(nobuiltin=True) sobject = unmarshaller.process(node, resolved) value = getattr(composite, tag, None) if value is None: if rt.unbounded(): value = [] setattr(composite, tag, value) value.append(sobject) else: setattr(composite, tag, sobject) else: if not isinstance(value, list): value = [value, ] setattr(composite, tag, value) value.append(sobject) return composite
def replycomposite(self, rtypes, nodes)
Construct a I{composite} reply. This method is called when it has been detected that the reply has multiple root nodes. @param rtypes: A list of known return I{types}. @type rtypes: [L{suds.xsd.sxbase.SchemaObject},...] @param nodes: A collection of XML nodes. @type nodes: [L{Element},...] @return: The I{unmarshalled} composite object. @rtype: L{Object},...
3.523953
3.408703
1.033811
reply = self.replyfilter(reply) sax = Parser() faultroot = sax.parse(string=reply) soapenv = faultroot.getChild('Envelope') soapbody = soapenv.getChild('Body') fault = soapbody.getChild('Fault') unmarshaller = self.unmarshaller(False) p = unmarshaller.process(fault) if self.options().faults: raise WebFault(p, faultroot) return (faultroot, p.detail)
def get_fault(self, reply)
Extract the fault from the specified soap reply. If I{faults} is True, an exception is raised. Otherwise, the I{unmarshalled} fault L{Object} is returned. This method is called when the server raises a I{web fault}. @param reply: A soap reply message. @type reply: str @return: A fault object. @rtype: tuple ( L{Element}, L{Object} )
5.919751
4.833549
1.224721
marshaller = self.marshaller() content = \ Content(tag=pdef[0], value=object, type=pdef[1], real=pdef[1].resolve()) return marshaller.process(content)
def mkparam(self, method, pdef, object)
Builds a parameter for the specified I{method} using the parameter definition (pdef) and the specified value (object). @param method: A method name. @type method: str @param pdef: A parameter definition. @type pdef: tuple: (I{name}, L{xsd.sxbase.SchemaObject}) @param object: The parameter value. @type object: any @return: The parameter fragment. @rtype: L{Element}
12.268682
9.979831
1.229348
body = Element('Body', ns=envns) body.append(content) return body
def body(self, content)
Build the B{<Body/>} for an soap outbound message. @param content: The body content. @type content: L{Element} @return: the soap body fragment. @rtype: L{Element}
9.481426
8.129427
1.166309
result = [] if input: parts = method.soap.input.body.parts else: parts = method.soap.output.body.parts for p in parts: if p.element is not None: query = ElementQuery(p.element) else: query = TypeQuery(p.type) pt = query.execute(self.schema()) if pt is None: raise TypeNotFound(query.ref) if p.type is not None: pt = PartElement(p.name, pt) if input: if pt.name is None: result.append((p.name, pt)) else: result.append((pt.name, pt)) else: result.append(pt) return result
def bodypart_types(self, method, input=True)
Get a list of I{parameter definitions} (pdef) defined for the specified method. Each I{pdef} is a tuple (I{name}, L{xsd.sxbase.SchemaObject}) @param method: A service method. @type method: I{service.Method} @param input: Defines input/output message. @type input: boolean @return: A list of parameter definitions @rtype: [I{pdef},]
3.187048
3.036187
1.049688
result = [] if input: headers = method.soap.input.headers else: headers = method.soap.output.headers for header in headers: part = header.part if part.element is not None: query = ElementQuery(part.element) else: query = TypeQuery(part.type) pt = query.execute(self.schema()) if pt is None: raise TypeNotFound(query.ref) if part.type is not None: pt = PartElement(part.name, pt) if input: if pt.name is None: result.append((part.name, pt)) else: result.append((pt.name, pt)) else: result.append(pt) return result
def headpart_types(self, method, input=True)
Get a list of I{parameter definitions} (pdef) defined for the specified method. Each I{pdef} is a tuple (I{name}, L{xsd.sxbase.SchemaObject}) @param method: A service method. @type method: I{service.Method} @param input: Defines input/output message. @type input: boolean @return: A list of parameter definitions @rtype: [I{pdef},]
3.209687
3.086895
1.039778
result = [] for rt in self.bodypart_types(method, input=False): result.append(rt) return result
def returned_types(self, method)
Get the L{xsd.sxbase.SchemaObject} returned by the I{method}. @param method: A service method. @type method: I{service.Method} @return: The name of the type return by the method. @rtype: [I{rtype},..]
9.710052
10.239997
0.948248
v = content.value if v is None: return if isinstance(v, dict): cls = content.real.name content.value = Factory.object(cls, v) md = content.value.__metadata__ md.sxtype = content.type return v = content.real.translate(v, False) content.value = v return self
def translate(self, content)
Translate using the XSD type information. Python I{dict} is translated to a suds object. Most importantly, primative values are translated from python types to XML types using the XSD type. @param content: The content to translate. @type content: L{Object} @return: self @rtype: L{Typed}
7.204675
7.140764
1.00895
v = content.value if isinstance(v, Object): md = v.__metadata__ md.ordering = self.ordering(content.real) return self
def sort(self, content)
Sort suds object attributes based on ordering defined in the XSD type information. @param content: The content to sort. @type content: L{Object} @return: self @rtype: L{Typed}
13.497162
14.939349
0.903464
result = [] for child, ancestry in type.resolve(): name = child.name if child.name is None: continue if child.isattr(): name = '_%s' % child.name result.append(name) return result
def ordering(self, type)
Get the attribute ordering defined in the specified XSD type information. @param type: An XSD type object. @type type: SchemaObject @return: An ordered list of attribute names. @rtype: list
5.344878
4.888729
1.093306
root = Element('Security', ns=wssens) root.set('mustUnderstand', str(self.mustUnderstand).lower()) for t in self.tokens: root.append(t.xml()) return root
def xml(self)
Get xml representation of the object. @return: The root node. @rtype: L{Element}
6.260671
7.068887
0.885666
if text is None: s = [] s.append(self.username) s.append(self.password) s.append(Token.sysdate()) m = md5() m.update(':'.join(s).encode("utf-8")) self.nonce = m.hexdigest() else: self.nonce = text
def setnonce(self, text=None)
Set I{nonce} which is arbitraty set of bytes to prevent reply attacks. @param text: The nonce text value. Generated when I{None}. @type text: str
3.255505
3.578579
0.90972
if dt is None: self.created = Token.utc() else: self.created = dt
def setcreated(self, dt=None)
Set I{created}. @param dt: The created date & time. Set as datetime.utc() when I{None}. @type dt: L{datetime}
6.072192
6.130258
0.990528
root = Element('UsernameToken', ns=wssens) u = Element('Username', ns=wssens) u.setText(self.username) root.append(u) p = Element('Password', ns=wssens) p.setText(self.password) root.append(p) if self.nonce is not None: n = Element('Nonce', ns=wssens) n.setText(self.nonce) root.append(n) if self.created is not None: n = Element('Created', ns=wsuns) n.setText(str(DateTime(self.created))) root.append(n) return root
def xml(self)
Get xml representation of the object. @return: The root node. @rtype: L{Element}
2.53356
2.518052
1.006159
name = 'arrayType' ns = (None, 'http://schemas.xmlsoap.org/soap/encoding/') aty = content.node.get(name, ns) if aty is not None: content.aty = aty parts = aty.split('[') ref = parts[0] if len(parts) == 2: self.applyaty(content, ref) else: pass # (2) dimensional array return self
def setaty(self, content)
Grab the (aty) soap-enc:arrayType and attach it to the content for proper array processing later in end(). @param content: The current content being unmarshalled. @type content: L{Content} @return: self @rtype: L{Encoded}
5.731776
4.181712
1.370677
name = 'type' ns = Namespace.xsins parent = content.node for child in parent.getChildren(): ref = child.get(name, ns) if ref is None: parent.addPrefix(ns[0], ns[1]) attr = ':'.join((ns[0], name)) child.set(attr, xty) return self
def applyaty(self, content, xty)
Apply the type referenced in the I{arrayType} to the content (child nodes) of the array. Each element (node) in the array that does not have an explicit xsi:type attribute is given one based on the I{arrayType}. @param content: An array content. @type content: L{Content} @param xty: The XSI type reference. @type xty: str @return: self @rtype: L{Encoded}
8.170033
5.958498
1.371156
for n, v in content.data: if isinstance(v, list): content.data = v return content.data = []
def promote(self, content)
Promote (replace) the content.data with the first attribute of the current content.data that is a I{list}. Note: the content.data may be empty or contain only _x attributes. In either case, the content.data is assigned an empty list. @param content: An array content. @type content: L{Content}
7.384649
4.709848
1.567917
"build an object for the specified typename as defined in the schema" if isinstance(name, basestring): type = self.resolver.find(name) if type is None: raise TypeNotFound(name) else: type = name cls = type.name if type.mixed(): data = Factory.property(cls) else: data = Factory.object(cls) resolved = type.resolve() md = data.__metadata__ md.sxtype = resolved md.ordering = self.ordering(resolved) history = [] self.add_attributes(data, resolved) for child, ancestry in type.children(): if self.skip_child(child, ancestry): continue self.process(data, child, history[:]) return data
def build(self, name)
build an object for the specified typename as defined in the schema
6.159054
5.146924
1.196648
for attr, ancestry in type.attributes(): name = '_%s' % attr.name value = attr.get_default() setattr(data, name, value)
def add_attributes(self, data, type)
add required attributes
6.22418
5.825179
1.068496
if pA in pB.links or \ pB in pA.links: raise Exception('Already linked') dA = pA.domains() dB = pB.domains() for d in dA: if d in dB: raise Exception('Duplicate domain "%s" found' % d) for d in dB: if d in dA: raise Exception('Duplicate domain "%s" found' % d) kA = pA.keys() kB = pB.keys() for k in kA: if k in kB: raise Exception('Duplicate key %s found' % k) for k in kB: if k in kA: raise Exception('Duplicate key %s found' % k) return self
def validate(self, pA, pB)
Validate that the two properties may be linked. @param pA: Endpoint (A) to link. @type pA: L{Endpoint} @param pB: Endpoint (B) to link. @type pB: L{Endpoint} @return: self @rtype: L{Link}
1.983984
1.906857
1.040447
pA, pB = self.endpoints if pA in pB.links: pB.links.remove(pA) if pB in pA.links: pA.links.remove(pB) return self
def teardown(self)
Teardown the link. Removes endpoints from properties I{links} collection. @return: self @rtype: L{Link}
3.496979
2.615523
1.33701
if value is None: return if len(self.classes) and not isinstance(value, self.classes): msg = '"%s" must be: %s' % (self.name, self.classes) raise AttributeError(msg)
def validate(self, value)
Validate the I{value} is of the correct class. @param value: The value to validate. @type value: any @raise AttributeError: When I{value} is invalid.
3.653194
3.355383
1.088756
d = self.definitions.get(name) if d is None: raise AttributeError(name) return d
def definition(self, name)
Get the definition for the property I{name}. @param name: The property I{name} to find the definition for. @type name: str @return: The property definition @rtype: L{Definition} @raise AttributeError: On not found.
3.578429
3.557272
1.005948
if isinstance(other, Properties): other = other.defined for n, v in other.items(): self.set(n, v) return self
def update(self, other)
Update the property values as specified by keyword/value. @param other: An object to update from. @type other: (dict|L{Properties}) @return: self @rtype: L{Properties}
5.070741
4.448056
1.13999
self.provider(name).__set(name, value) return self
def set(self, name, value)
Set the I{value} of a property by I{name}. The value is validated against the definition and set to the default when I{value} is None. @param name: The property name. @type name: str @param value: The new property value. @type value: any @return: self @rtype: L{Properties}
17.072657
28.029444
0.609097
return self.provider(name).__get(name, *df)
def get(self, name, *df)
Get the value of a property by I{name}. @param name: The property name. @type name: str @param df: An optional value to be returned when the value is not set @type df: [1]. @return: The stored value, or I{df[0]} if not set. @rtype: any
18.981884
30.241388
0.627679
if not len(others): others = self.links[:] for p in self.links[:]: if p in others: p.teardown() return self
def unlink(self, *others)
Unlink (disassociate) the specified properties object. @param others: The list object to unlink. Unspecified means unlink all. @type others: [L{Properties},..] @return: self @rtype: L{Properties}
6.546225
8.380419
0.781133
if history is None: history = [] history.append(self) if name in self.definitions: return self for x in self.links: if x in history: continue provider = x.provider(name, history) if provider is not None: return provider history.remove(self) if len(history): return None return self
def provider(self, name, history=None)
Find the provider of the property by I{name}. @param name: The property name. @type name: str @param history: A history of nodes checked to prevent circular hunting. @type history: [L{Properties},..] @return: The provider when found. Otherwise, None (when nested) and I{self} when not nested. @rtype: L{Properties}
2.998362
2.698888
1.110962
if history is None: history = [] history.append(self) keys = set() keys.update(self.definitions.keys()) for x in self.links: if x in history: continue keys.update(x.keys(history)) history.remove(self) return keys
def keys(self, history=None)
Get the set of I{all} property names. @param history: A history of nodes checked to prevent circular hunting. @type history: [L{Properties},..] @return: A set of property names. @rtype: list
3.043418
3.02616
1.005703
if history is None: history = [] history.append(self) domains = set() domains.add(self.domain) for x in self.links: if x in history: continue domains.update(x.domains(history)) history.remove(self) return domains
def domains(self, history=None)
Get the set of I{all} domain names. @param history: A history of nodes checked to prevent circular hunting. @type history: [L{Properties},..] @return: A set of domain names. @rtype: list
2.857466
2.817804
1.014075
for d in self.definitions.values(): self.defined[d.name] = d.default return self
def prime(self)
Prime the stored values based on default values found in property definitions. @return: self @rtype: L{Properties}
10.986502
6.653546
1.651225
p = other.__pts__ return self.properties.link(p)
def link(self, other)
Link (associate) this object with anI{other} properties object to create a network of properties. Links are bidirectional. @param other: The object to link. @type other: L{Properties} @return: self @rtype: L{Properties}
35.98489
51.118214
0.703954
p = other.__pts__ return self.properties.unlink(p)
def unlink(self, other)
Unlink (disassociate) the specified properties object. @param other: The object to unlink. @type other: L{Properties} @return: self @rtype: L{Properties}
37.694134
53.876038
0.699646
scanner_list = zap_helper.zap.ascan.scanners() if scanners is not None and 'all' not in scanners: scanner_list = filter_by_ids(scanner_list, scanners) click.echo(tabulate([[s['id'], s['name'], s['policyId'], s['enabled'], s['attackStrength'], s['alertThreshold']] for s in scanner_list], headers=['ID', 'Name', 'Policy ID', 'Enabled', 'Strength', 'Threshold'], tablefmt='grid'))
def list_scanners(zap_helper, scanners)
Get a list of scanners and whether or not they are enabled.
2.880652
2.883385
0.999052
if not scanners or 'all' in scanners: scanners = _get_all_scanner_ids(zap_helper) with zap_error_handler(): zap_helper.set_scanner_attack_strength(scanners, strength) console.info('Set attack strength to {0}.'.format(strength))
def set_scanner_strength(zap_helper, scanners, strength)
Set the attack strength for scanners.
4.082766
3.709574
1.100602
if not scanners or 'all' in scanners: scanners = _get_all_scanner_ids(zap_helper) with zap_error_handler(): zap_helper.set_scanner_alert_threshold(scanners, threshold) console.info('Set alert threshold to {0}.'.format(threshold))
def set_scanner_threshold(zap_helper, scanners, threshold)
Set the alert threshold for scanners.
3.970103
3.744466
1.060259
scanners = zap_helper.zap.ascan.scanners() return [s['id'] for s in scanners]
def _get_all_scanner_ids(zap_helper)
Get all scanner IDs.
3.848375
3.173729
1.212572
policies = filter_by_ids(zap_helper.zap.ascan.policies(), policy_ids) click.echo(tabulate([[p['id'], p['name'], p['enabled'], p['attackStrength'], p['alertThreshold']] for p in policies], headers=['ID', 'Name', 'Enabled', 'Strength', 'Threshold'], tablefmt='grid'))
def list_policies(zap_helper, policy_ids)
Get a list of policies and whether or not they are enabled.
3.399686
3.423241
0.993119
if not policy_ids: policy_ids = _get_all_policy_ids(zap_helper) with zap_error_handler(): zap_helper.enable_policies_by_ids(policy_ids)
def enable_policies(zap_helper, policy_ids)
Set the enabled policies to use in a scan. When you enable a selection of policies, all other policies are disabled.
3.29742
4.229827
0.779564
if not policy_ids: policy_ids = _get_all_policy_ids(zap_helper) with zap_error_handler(): zap_helper.set_policy_attack_strength(policy_ids, strength) console.info('Set attack strength to {0}.'.format(strength))
def set_policy_strength(zap_helper, policy_ids, strength)
Set the attack strength for policies.
3.632571
3.507639
1.035617
if not policy_ids: policy_ids = _get_all_policy_ids(zap_helper) with zap_error_handler(): zap_helper.set_policy_alert_threshold(policy_ids, threshold) console.info('Set alert threshold to {0}.'.format(threshold))
def set_policy_threshold(zap_helper, policy_ids, threshold)
Set the alert threshold for policies.
3.571306
3.503002
1.019499
policies = zap_helper.zap.ascan.policies() return [p['id'] for p in policies]
def _get_all_policy_ids(zap_helper)
Get all policy IDs.
4.050961
3.746504
1.081264
if self.is_running(): self.logger.warn('ZAP is already running on port {0}'.format(self.port)) return if platform.system() == 'Windows' or platform.system().startswith('CYGWIN'): executable = 'zap.bat' else: executable = 'zap.sh' executable_path = os.path.join(self.zap_path, executable) if not os.path.isfile(executable_path): raise ZAPError(('ZAP was not found in the path "{0}". You can set the path to where ZAP is ' + 'installed on your system using the --zap-path command line parameter or by ' + 'default using the ZAP_PATH environment variable.').format(self.zap_path)) zap_command = [executable_path, '-daemon', '-port', str(self.port)] if options: extra_options = shlex.split(options) zap_command += extra_options if self.log_path is None: log_path = os.path.join(self.zap_path, 'zap.log') else: log_path = os.path.join(self.log_path, 'zap.log') self.logger.debug('Starting ZAP process with command: {0}.'.format(' '.join(zap_command))) self.logger.debug('Logging to {0}'.format(log_path)) with open(log_path, 'w+') as log_file: subprocess.Popen( zap_command, cwd=self.zap_path, stdout=log_file, stderr=subprocess.STDOUT) self.wait_for_zap(self.timeout) self.logger.debug('ZAP started successfully.')
def start(self, options=None)
Start the ZAP Daemon.
2.263364
2.171398
1.042353
if not self.is_running(): self.logger.warn('ZAP is not running.') return self.logger.debug('Shutting down ZAP.') self.zap.core.shutdown() timeout_time = time.time() + self.timeout while self.is_running(): if time.time() > timeout_time: raise ZAPError('Timed out waiting for ZAP to shutdown.') time.sleep(2) self.logger.debug('ZAP shutdown successfully.')
def shutdown(self)
Shutdown ZAP.
2.747836
2.344538
1.172016
timeout_time = time.time() + timeout while not self.is_running(): if time.time() > timeout_time: raise ZAPError('Timed out waiting for ZAP to start.') time.sleep(2)
def wait_for_zap(self, timeout)
Wait for ZAP to be ready to receive API calls.
2.570805
2.39895
1.071638
try: result = requests.get(self.proxy_url) except RequestException: return False if 'ZAP-Header' in result.headers.get('Access-Control-Allow-Headers', []): return True raise ZAPError('Another process is listening on {0}'.format(self.proxy_url))
def is_running(self)
Check if ZAP is running.
5.587014
4.562646
1.224512
self.zap.urlopen(url) # Give the sites tree a chance to get updated time.sleep(sleep_after_open)
def open_url(self, url, sleep_after_open=2)
Access a URL through ZAP.
8.445002
5.544475
1.523138
self.logger.debug('Spidering target {0}...'.format(target_url)) context_id, user_id = self._get_context_and_user_ids(context_name, user_name) if user_id: self.logger.debug('Running spider in context {0} as user {1}'.format(context_id, user_id)) scan_id = self.zap.spider.scan_as_user(context_id, user_id, target_url) else: scan_id = self.zap.spider.scan(target_url) if not scan_id: raise ZAPError('Error running spider.') elif not scan_id.isdigit(): raise ZAPError('Error running spider: "{0}"'.format(scan_id)) self.logger.debug('Started spider with ID {0}...'.format(scan_id)) while int(self.zap.spider.status()) < 100: self.logger.debug('Spider progress %: {0}'.format(self.zap.spider.status())) time.sleep(self._status_check_sleep) self.logger.debug('Spider #{0} completed'.format(scan_id))
def run_spider(self, target_url, context_name=None, user_name=None)
Run spider against a URL.
2.3806
2.322512
1.025011
self.logger.debug('Scanning target {0}...'.format(target_url)) context_id, user_id = self._get_context_and_user_ids(context_name, user_name) if user_id: self.logger.debug('Scanning in context {0} as user {1}'.format(context_id, user_id)) scan_id = self.zap.ascan.scan_as_user(target_url, context_id, user_id, recursive) else: scan_id = self.zap.ascan.scan(target_url, recurse=recursive) if not scan_id: raise ZAPError('Error running active scan.') elif not scan_id.isdigit(): raise ZAPError(('Error running active scan: "{0}". Make sure the URL is in the site ' + 'tree by using the open-url or scanner commands before running an active ' + 'scan.').format(scan_id)) self.logger.debug('Started scan with ID {0}...'.format(scan_id)) while int(self.zap.ascan.status()) < 100: self.logger.debug('Scan progress %: {0}'.format(self.zap.ascan.status())) time.sleep(self._status_check_sleep) self.logger.debug('Scan #{0} completed'.format(scan_id))
def run_active_scan(self, target_url, recursive=False, context_name=None, user_name=None)
Run an active scan against a URL.
2.831085
2.799764
1.011187
self.logger.debug('AJAX Spidering target {0}...'.format(target_url)) self.zap.ajaxSpider.scan(target_url) while self.zap.ajaxSpider.status == 'running': self.logger.debug('AJAX Spider: {0}'.format(self.zap.ajaxSpider.status)) time.sleep(self._status_check_sleep) self.logger.debug('AJAX Spider completed')
def run_ajax_spider(self, target_url)
Run AJAX Spider against a URL.
3.229404
3.052372
1.057998
alerts = self.zap.core.alerts() alert_level_value = self.alert_levels[alert_level] alerts = sorted((a for a in alerts if self.alert_levels[a['risk']] >= alert_level_value), key=lambda k: self.alert_levels[k['risk']], reverse=True) return alerts
def alerts(self, alert_level='High')
Get a filtered list of alerts at the given alert level, and sorted by alert level.
3.429144
3.511697
0.976492
enabled_scanners = [] scanners = self.zap.ascan.scanners() for scanner in scanners: if scanner['enabled'] == 'true': enabled_scanners.append(scanner['id']) return enabled_scanners
def enabled_scanner_ids(self)
Retrieves a list of currently enabled scanners.
3.09682
2.94377
1.051991
scanner_ids = ','.join(scanner_ids) self.logger.debug('Enabling scanners with IDs {0}'.format(scanner_ids)) return self.zap.ascan.enable_scanners(scanner_ids)
def enable_scanners_by_ids(self, scanner_ids)
Enable a list of scanner IDs.
3.587356
3.628436
0.988678
scanner_ids = ','.join(scanner_ids) self.logger.debug('Disabling scanners with IDs {0}'.format(scanner_ids)) return self.zap.ascan.disable_scanners(scanner_ids)
def disable_scanners_by_ids(self, scanner_ids)
Disable a list of scanner IDs.
3.590624
3.783704
0.94897
if group == 'all': self.logger.debug('Enabling all scanners') return self.zap.ascan.enable_all_scanners() try: scanner_list = self.scanner_group_map[group] except KeyError: raise ZAPError( 'Invalid group "{0}" provided. Valid groups are: {1}'.format( group, ', '.join(self.scanner_groups) ) ) self.logger.debug('Enabling scanner group {0}'.format(group)) return self.enable_scanners_by_ids(scanner_list)
def enable_scanners_by_group(self, group)
Enables the scanners in the group if it matches one in the scanner_group_map.
2.601017
2.546856
1.021266
if group == 'all': self.logger.debug('Disabling all scanners') return self.zap.ascan.disable_all_scanners() try: scanner_list = self.scanner_group_map[group] except KeyError: raise ZAPError( 'Invalid group "{0}" provided. Valid groups are: {1}'.format( group, ', '.join(self.scanner_groups) ) ) self.logger.debug('Disabling scanner group {0}'.format(group)) return self.disable_scanners_by_ids(scanner_list)
def disable_scanners_by_group(self, group)
Disables the scanners in the group if it matches one in the scanner_group_map.
2.600148
2.538373
1.024336
scanner_ids = [] for scanner in scanners: if scanner in self.scanner_groups: self.enable_scanners_by_group(scanner) elif scanner.isdigit(): scanner_ids.append(scanner) else: raise ZAPError('Invalid scanner "{0}" provided. Must be a valid group or numeric ID.'.format(scanner)) if scanner_ids: self.enable_scanners_by_ids(scanner_ids)
def enable_scanners(self, scanners)
Enable the provided scanners by group and/or IDs.
2.929718
2.501017
1.171411
scanner_ids = [] for scanner in scanners: if scanner in self.scanner_groups: self.disable_scanners_by_group(scanner) elif scanner.isdigit(): scanner_ids.append(scanner) else: raise ZAPError('Invalid scanner "{0}" provided. Must be a valid group or numeric ID.'.format(scanner)) if scanner_ids: self.disable_scanners_by_ids(scanner_ids)
def disable_scanners(self, scanners)
Enable the provided scanners by group and/or IDs.
2.896504
2.524983
1.147138
self.logger.debug('Disabling all current scanners') self.zap.ascan.disable_all_scanners() self.enable_scanners(scanners)
def set_enabled_scanners(self, scanners)
Set only the provided scanners by group and/or IDs and disable all others.
4.939662
4.655234
1.061099
for scanner_id in scanner_ids: self.logger.debug('Setting strength for scanner {0} to {1}'.format(scanner_id, attack_strength)) result = self.zap.ascan.set_scanner_attack_strength(scanner_id, attack_strength) if result != 'OK': raise ZAPError('Error setting strength for scanner with ID {0}: {1}'.format(scanner_id, result))
def set_scanner_attack_strength(self, scanner_ids, attack_strength)
Set the attack strength for the given scanners.
2.260534
2.232425
1.012591
for scanner_id in scanner_ids: self.logger.debug('Setting alert threshold for scanner {0} to {1}'.format(scanner_id, alert_threshold)) result = self.zap.ascan.set_scanner_alert_threshold(scanner_id, alert_threshold) if result != 'OK': raise ZAPError('Error setting alert threshold for scanner with ID {0}: {1}'.format(scanner_id, result))
def set_scanner_alert_threshold(self, scanner_ids, alert_threshold)
Set the alert theshold for the given policies.
2.168831
2.151179
1.008206
policy_ids = ','.join(policy_ids) self.logger.debug('Setting enabled policies to IDs {0}'.format(policy_ids)) self.zap.ascan.set_enabled_policies(policy_ids)
def enable_policies_by_ids(self, policy_ids)
Set enabled policy from a list of IDs.
3.934154
3.517047
1.118596
for policy_id in policy_ids: self.logger.debug('Setting strength for policy {0} to {1}'.format(policy_id, attack_strength)) result = self.zap.ascan.set_policy_attack_strength(policy_id, attack_strength) if result != 'OK': raise ZAPError('Error setting strength for policy with ID {0}: {1}'.format(policy_id, result))
def set_policy_attack_strength(self, policy_ids, attack_strength)
Set the attack strength for the given policies.
2.361144
2.307463
1.023264
for policy_id in policy_ids: self.logger.debug('Setting alert threshold for policy {0} to {1}'.format(policy_id, alert_threshold)) result = self.zap.ascan.set_policy_alert_threshold(policy_id, alert_threshold) if result != 'OK': raise ZAPError('Error setting alert threshold for policy with ID {0}: {1}'.format(policy_id, result))
def set_policy_alert_threshold(self, policy_ids, alert_threshold)
Set the alert theshold for the given policies.
2.228513
2.207386
1.009571
try: re.compile(exclude_regex) except re.error: raise ZAPError('Invalid regex "{0}" provided'.format(exclude_regex)) self.logger.debug('Excluding {0} from proxy, spider and active scanner.'.format(exclude_regex)) self.zap.core.exclude_from_proxy(exclude_regex) self.zap.spider.exclude_from_scan(exclude_regex) self.zap.ascan.exclude_from_scan(exclude_regex)
def exclude_from_all(self, exclude_regex)
Exclude a pattern from proxy, spider and active scanner.
3.217423
2.386451
1.348204
self.logger.debug('Generating XML report') report = self.zap.core.xmlreport() self._write_report(report, file_path)
def xml_report(self, file_path)
Generate and save XML report
5.464006
4.809382
1.136114
self.logger.debug('Generating MD report') report = self.zap.core.mdreport() self._write_report(report, file_path)
def md_report(self, file_path)
Generate and save MD report
6.838007
5.589268
1.223417
self.logger.debug('Generating HTML report') report = self.zap.core.htmlreport() self._write_report(report, file_path)
def html_report(self, file_path)
Generate and save HTML report.
5.681443
4.812936
1.180453
with open(file_path, mode='wb') as f: if not isinstance(report, binary_type): report = report.encode('utf-8') f.write(report)
def _write_report(report, file_path)
Write report to the given file path.
2.797178
2.603252
1.074494
context_info = self.zap.context.context(context_name) if not isinstance(context_info, dict): raise ZAPError('Context with name "{0}" wasn\'t found'.format(context_name)) return context_info
def get_context_info(self, context_name)
Get the context ID for a given context name.
3.650647
3.376932
1.081054
if context_name is None: return None, None context_id = self.get_context_info(context_name)['id'] user_id = None if user_name: user_id = self._get_user_id_from_name(context_id, user_name) return context_id, user_id
def _get_context_and_user_ids(self, context_name, user_name)
Helper to get the context ID and user ID from the given names.
2.139372
2.054655
1.041232
users = self.zap.users.users_list(context_id) for user in users: if user['name'] == user_name: return user['id'] raise ZAPError('No user with the name "{0}"" was found for context {1}'.format(user_name, context_id))
def _get_user_id_from_name(self, context_id, user_name)
Get a user ID from the user name.
3.246527
3.226241
1.006288
scripts = zap_helper.zap.script.list_scripts output = [] for s in scripts: if 'enabled' not in s: s['enabled'] = 'N/A' output.append([s['name'], s['type'], s['engine'], s['enabled']]) click.echo(tabulate(output, headers=['Name', 'Type', 'Engine', 'Enabled'], tablefmt='grid'))
def list_scripts(zap_helper)
List scripts currently loaded into ZAP.
2.804972
2.887464
0.971431
engines = zap_helper.zap.script.list_engines console.info('Available engines: {}'.format(', '.join(engines)))
def list_engines(zap_helper)
List engines that can be used to run scripts.
6.414182
5.504955
1.165165
with zap_error_handler(): console.debug('Enabling script "{0}"'.format(script_name)) result = zap_helper.zap.script.enable(script_name) if result != 'OK': raise ZAPError('Error enabling script: {0}'.format(result)) console.info('Script "{0}" enabled'.format(script_name))
def enable_script(zap_helper, script_name)
Enable a script.
3.111468
3.16209
0.983991
with zap_error_handler(): console.debug('Disabling script "{0}"'.format(script_name)) result = zap_helper.zap.script.disable(script_name) if result != 'OK': raise ZAPError('Error disabling script: {0}'.format(result)) console.info('Script "{0}" disabled'.format(script_name))
def disable_script(zap_helper, script_name)
Disable a script.
3.156019
3.186267
0.990507
with zap_error_handler(): console.debug('Removing script "{0}"'.format(script_name)) result = zap_helper.zap.script.remove(script_name) if result != 'OK': raise ZAPError('Error removing script: {0}'.format(result)) console.info('Script "{0}" removed'.format(script_name))
def remove_script(zap_helper, script_name)
Remove a script.
3.271418
3.251055
1.006264
with zap_error_handler(): if not os.path.isfile(options['file_path']): raise ZAPError('No file found at "{0}", cannot load script.'.format(options['file_path'])) if not _is_valid_script_engine(zap_helper.zap, options['engine']): engines = zap_helper.zap.script.list_engines raise ZAPError('Invalid script engine provided. Valid engines are: {0}'.format(', '.join(engines))) console.debug('Loading script "{0}" from "{1}"'.format(options['name'], options['file_path'])) result = zap_helper.zap.script.load(options['name'], options['script_type'], options['engine'], options['file_path'], scriptdescription=options['description']) if result != 'OK': raise ZAPError('Error loading script: {0}'.format(result)) console.info('Script "{0}" loaded'.format(options['name']))
def load_script(zap_helper, **options)
Load a script from a file.
3.010662
2.916856
1.03216
engine_names = zap.script.list_engines short_names = [e.split(' : ')[1] for e in engine_names] return engine in engine_names or engine in short_names
def _is_valid_script_engine(zap, engine)
Check if given script engine is valid.
5.192328
4.692
1.106634
console.colorize = not boring if verbose: console.setLevel('DEBUG') else: console.setLevel('INFO') ctx.obj = ZAPHelper(zap_path=zap_path, port=port, url=zap_url, api_key=api_key, log_path=log_path)
def cli(ctx, boring, verbose, zap_path, port, zap_url, api_key, log_path)
Main command line entry point.
2.825233
2.741861
1.030407
console.info('Starting ZAP daemon') with helpers.zap_error_handler(): zap_helper.start(options=start_options)
def start_zap_daemon(zap_helper, start_options)
Helper to start the daemon using the current config.
6.619027
6.579293
1.006039
with helpers.zap_error_handler(): if zap_helper.is_running(): console.info('ZAP is running') elif timeout is not None: zap_helper.wait_for_zap(timeout) console.info('ZAP is running') else: console.error('ZAP is not running') sys.exit(2)
def check_status(zap_helper, timeout)
Check if ZAP is running and able to receive API calls. You can provide a timeout option which is the amount of time in seconds the command should wait for ZAP to start if it is not currently running. This is useful to run before calling other commands if ZAP was started outside of zap-cli. For example: zap-cli status -t 60 && zap-cli open-url "http://127.0.0.1/" Exits with code 1 if ZAP is either not running or the command timed out waiting for ZAP to start.
3.317962
3.598977
0.921918
console.info('Accessing URL {0}'.format(url)) zap_helper.open_url(url)
def open_url(zap_helper, url)
Open a URL using the ZAP proxy.
5.116671
5.188282
0.986198
console.info('Running spider...') with helpers.zap_error_handler(): zap_helper.run_spider(url, context_name, user_name)
def spider_url(zap_helper, url, context_name, user_name)
Run the spider against a URL.
5.734656
5.225471
1.097443
console.info('Running an active scan...') with helpers.zap_error_handler(): if scanners: zap_helper.set_enabled_scanners(scanners) zap_helper.run_active_scan(url, recursive, context_name, user_name)
def active_scan(zap_helper, url, scanners, recursive, context_name, user_name)
Run an Active Scan against a URL. The URL to be scanned must be in ZAP's site tree, i.e. it should have already been opened using the open-url command or found by running the spider command.
4.232227
4.366279
0.969298
alerts = zap_helper.alerts(alert_level) helpers.report_alerts(alerts, output_format) if exit_code: code = 1 if len(alerts) > 0 else 0 sys.exit(code)
def show_alerts(zap_helper, alert_level, output_format, exit_code)
Show alerts at the given alert level.
3.407603
3.598523
0.946945
if options['self_contained']: console.info('Starting ZAP daemon') with helpers.zap_error_handler(): zap_helper.start(options['start_options']) console.info('Running a quick scan for {0}'.format(url)) with helpers.zap_error_handler(): if options['scanners']: zap_helper.set_enabled_scanners(options['scanners']) if options['exclude']: zap_helper.exclude_from_all(options['exclude']) zap_helper.open_url(url) if options['spider']: zap_helper.run_spider(url, options['context_name'], options['user_name']) if options['ajax_spider']: zap_helper.run_ajax_spider(url) zap_helper.run_active_scan(url, options['recursive'], options['context_name'], options['user_name']) alerts = zap_helper.alerts(options['alert_level']) helpers.report_alerts(alerts, options['output_format']) if options['self_contained']: console.info('Shutting down ZAP daemon') with helpers.zap_error_handler(): zap_helper.shutdown() exit_code = 1 if len(alerts) > 0 else 0 sys.exit(exit_code)
def quick_scan(zap_helper, url, **options)
Run a quick scan of a site by opening a URL, optionally spidering the URL, running an Active Scan, and reporting any issues found. This command contains most scan options as parameters, so you can do everything in one go. If any alerts are found for the given alert level, this command will exit with a status code of 1.
2.944181
2.741872
1.073785
if output_format == 'html': zap_helper.html_report(output) elif output_format == 'md': zap_helper.md_report(output) else: zap_helper.xml_report(output) console.info('Report saved to "{0}"'.format(output))
def report(zap_helper, output, output_format)
Generate XML, MD or HTML report.
2.370376
2.19572
1.079544
if not value: return None ids = [x.strip() for x in value.split(',')] for id_item in ids: if not id_item.isdigit(): raise click.BadParameter('Non-numeric value "{0}" provided for an ID.'.format(id_item)) return ids
def validate_ids(ctx, param, value)
Validate a list of IDs and convert them to a list.
3.002336
2.678671
1.12083
if not value: return None valid_groups = ctx.obj.scanner_groups scanners = [x.strip() for x in value.split(',')] if 'all' in scanners: return ['all'] scanner_ids = [] for scanner in scanners: if scanner.isdigit(): scanner_ids.append(scanner) elif scanner in valid_groups: scanner_ids += ctx.obj.scanner_group_map[scanner] else: raise click.BadParameter('Invalid scanner "{0}" provided. Must be a valid group or numeric ID.' .format(scanner)) return scanner_ids
def validate_scanner_list(ctx, param, value)
Validate a comma-separated list of scanners and extract it into a list of groups and IDs.
2.57637
2.362174
1.090677
if not value: return None try: re.compile(value) except re.error: raise click.BadParameter('Invalid regex "{0}" provided'.format(value)) return value
def validate_regex(ctx, param, value)
Validate that a provided regex compiles.
2.819683
2.400791
1.174481
num_alerts = len(alerts) if output_format == 'json': click.echo(json.dumps(alerts, indent=4)) else: console.info('Issues found: {0}'.format(num_alerts)) if num_alerts > 0: click.echo(tabulate([[a['alert'], a['risk'], a['cweid'], a['url']] for a in alerts], headers=['Alert', 'Risk', 'CWE ID', 'URL'], tablefmt='grid'))
def report_alerts(alerts, output_format='table')
Print our alerts in the given format.
2.847264
2.826245
1.007437
if not ids_to_filter: return original_list return [i for i in original_list if i['id'] in ids_to_filter]
def filter_by_ids(original_list, ids_to_filter)
Filter a list of dicts by IDs using an id key on each dict.
2.29218
2.142763
1.069731
console.debug('Saving the session to "{0}"'.format(file_path)) zap_helper.zap.core.save_session(file_path, overwrite='true')
def save_session(zap_helper, file_path)
Save the session.
4.946625
4.630953
1.068166
with zap_error_handler(): if not os.path.isfile(file_path): raise ZAPError('No file found at "{0}", cannot load session.'.format(file_path)) console.debug('Loading session from "{0}"'.format(file_path)) zap_helper.zap.core.load_session(file_path)
def load_session(zap_helper, file_path)
Load a given session.
3.439442
3.257646
1.055806
contexts = zap_helper.zap.context.context_list if len(contexts): console.info('Available contexts: {0}'.format(contexts[1:-1])) else: console.info('No contexts available in the current session')
def context_list(zap_helper)
List the available contexts.
5.046841
4.716011
1.07015