示例#1
0
 def run(self):
     file = self.arguments.output or open(
         f"{self.arguments.target}-{self.arguments.port}.rdp", "w")
     file.write("\n".join([
         "screen mode id:i:2", "use multimon:i:0", "desktopwidth:i:800",
         "desktopheight:i:600", "session bpp:i:32",
         "winposstr:s:0,3,0,0,800,600", "compression:i:1",
         "keyboardhook:i:2", "audiocapturemode:i:0",
         "videoplaybackmode:i:1", "connection type:i:2",
         "displayconnectionbar:i:1", "disable wallpaper:i:1",
         "allow font smoothing:i:0", "allow desktop composition:i:0",
         "disable full window drag:i:1", "disable menu anims:i:1",
         "disable themes:i:0", "disable cursor setting:i:0",
         "bitmapcachepersistenable:i:1",
         f"full address:s:{self.arguments.target}:{self.arguments.port}",
         "audiomode:i:0", "redirectprinters:i:1", "redirectcomports:i:0",
         "redirectsmartcards:i:1", "redirectclipboard:i:1",
         "redirectposdevices:i:0", "redirectdirectx:i:1",
         "autoreconnection enabled:i:1", "authentication level:i:0",
         "prompt for credentials:i:0", "negotiate security layer:i:1",
         "remoteapplicationmode:i:0", "alternate shell:s:",
         "shell working directory:s:", "gatewayhostname:s:",
         "gatewayusagemethod:i:4", "gatewaycredentialssource:i:4",
         "gatewayprofileusagemethod:i:0", "promptcredentialonce:i:1",
         "use redirection server name:i:0", "enablecredsspsupport:i:0"
     ]))
     print("[i] Successfully created RDP connection file!")
     print(f" -  {filename}", dark=True)
示例#2
0
 def list(self, folder: str, debug: bool = True):
     tree = {}
     total = [0, 0]
     for root, dirnames, filenames in os.walk(os.path.join(self.location, folder)):
         basedir = os.path.basename(os.path.dirname(root))
         if not basedir.startswith("_") and basedir not in ["modules"]:
             for name in filter(lambda name: name.endswith(".py"), filenames):
                 fullname = os.path.join(root, name)
                 try:
                     module = console.load(fullname)
                     commands = set()
                     for attribute in map(lambda name: getattr(module, name), filter(lambda x: not x.startswith("_"), dir(module))):
                         try:
                             if callable(attribute) and issubclass(attribute, base.Program) and attribute != base.Program:
                                 commands.add(attribute)
                         except TypeError as e:
                             if str(e) != "issubclass() arg 1 must be a class":
                                 raise e
                     if commands:
                         for command in commands:
                             t = tree
                             for field in root.replace(self.location, "", 1)[1:].replace("\\", "/").split("/"):
                                 if field not in t:
                                     t[field] = {}
                                     total[1] += 1
                                 t = t[field]
                             t[os.path.splitext(os.path.basename(fullname))[0]] = (command.__doc__ or "No description available.").split("\n", 1)[0]
                             total[0] += 1
                             break
                 except Exception as e:
                     if debug:
                         filename, line, function, text = traceback.extract_tb(e.__traceback__)[-1]
                         console.print(f"[!] {fullname.replace(self.location, '.')}:", color = "red")
                         console.print(f" -  {type(e).__name__}: ({filename.replace(csf.location, '.')} line #{line} in {function})", color = "red")
                         console.print(f"    {repr(text)}", color = "red", dark = True, parse = False)
                         console.print(f" -  {e}", color = "red", dark = True)
                         exit(1)
     def pprint(obj, depth: int = 0):
         prefix = "|  " * depth
         for key, value in obj.items():
             if isinstance(value, str):
                 l1 = prefix + f"|--{key}"
                 prefix2 = (prefix + "|  ").ljust(24)
                 if len(l1) > 23:
                     console.print(l1)
                     console.print(prefix2, (value, True), prefix = prefix2)
                 else:
                     console.print(l1.ljust(24), (value, True), prefix = prefix2)
             else:
                 programs = len(list(filter(lambda x: isinstance(x[1], str), value.items())))
                 folders = len(value) - programs
                 console.print(f"{prefix}|--{key}: ({programs}/{folders})")
                 pprint(value, depth + 1)
     console.print(f"[i] There are {total[0] or 'no'} programs available {f'on {total[1]} folders' if total[1] else ''}!")
     pprint(tree)
示例#3
0
 def run(self):
     arguments = self.arguments.__dict__
     nameservers = arguments.get("nameservers")
     resolver = dns.resolver.Resolver(arguments.get("filename"),
                                      arguments.get("configure_resolver"))
     resolver.set_flags(arguments.get("flags"))
     resolver.use_edns(arguments.get("edns"), arguments.get("edns_flags"),
                       arguments.get("edns_payload"))
     if nameservers:
         resolver.nameservers = nameservers
     resolver.port = arguments.get("port")
     resolver.timeout = arguments.get("timeout")
     resolver.lifetime = arguments.get("lifetime")
     resolver.retry_servfail = arguments.get("retry_servfail")
     if arguments.pop("metaquery"):
         kwargs = {
             v: arguments.get(k)
             for k, v in {
                 "rdclass": "rdclass",
                 "edns": "use_edns",
                 "want_dnssec": "want_dnssec",
                 "edns_flags": "ednsflags",
                 "edns_payload": "request_payload"
             }.items()
         }
         message = dns.message.make_query(arguments.get("query"),
                                          arguments.get("rdtype"), **kwargs)
         kwargs = {
             k: arguments.get(k)
             for k in [
                 "timeout", "port", "source", "source_port",
                 "one_rr_per_rrset"
             ]
         }
         if arguments.get("tcp"):
             resp = dns.query.tcp(message, resolver.nameservers[0],
                                  **kwargs)
         else:
             resp = dns.query.udp(message, resolver.nameservers[0],
                                  **kwargs)
         print(resp)
     else:
         kwargs = {
             k: arguments.get(k)
             for k in ["rdtype", "rdclass", "tcp", "source", "source_port"]
         }
         answer = resolver.query(arguments.pop("query"), **kwargs)
         print(answer.response)
 def cflist(self, cfl_id: str):
     page = self.session.get(
         "cflist/" + cfl_id,
         headers={
             "Referer": "http://www.crimeflare.com/cgi-bin/cfsearch.cgi"
         }).parsed()
     if page.title.text.lower() == "cloudflare search results":
         domains = list(page.stripped_strings)[3:-4]
         print(
             "[i] Some CloudFlare-User domains with a direct-connect IP address of {cfl_id.split('-')[1]}:"
         )
         for i in range(0, len(domains), 2):
             print(" -  {:32}{:32}".format(*domains[i:i + 2], ""),
                   dark=True)
     else:
         raise Exception(
             "Failed to list cloudflare-user domains using this CFL id ...")
示例#5
0
 def _iter(self, answer):
     for record in sorted(answer, key = lambda x: dns.rdatatype.to_text(x.rdtype)):
         string = f" -  {dns.rdatatype.to_text(record.rdtype).ljust(self._max_rdtype_length)}"
         print(string, end = "")
         extra = False
         for name in dir(record):
             value = getattr(record, name)
             if value is None or name.startswith("_") or callable(value) or name in ("rdtype", "rdclass"):
                 continue
             s = f"{(' ' * (len(string)+1)) if extra else ''}{name}: "
             if isinstance(value, bytes):
                 value = value.decode("ascii", errors="replace")
             elif isinstance(value, (list, tuple)):
                 value = ("\n" + (" " * len(s))).join(sorted([i.decode("ascii", errors="replace") if isinstance(i, bytes) else
                                                              (("\n" + (" " * (len(s) + 1))).join(str(i).split(" ")) if record.rdtype == 16 else str(i))
                                                             for i in value]))
             print(s + f"{value}", dark = True)
             extra = True
 def run(self):
     transport = Udp6TransportTarget if self.arguments.udp6 else (
         UnixTransportTarget if self.arguments.unix else UdpTransportTarget)
     args = (SnmpEngine(), CommunityData(self.arguments.community,
                                         mpModel=0),
             transport((self.arguments.target, self.arguments.port),
                       timeout=self.arguments.timeout,
                       retries=self.arguments.retries), ContextData())
     response = (getCmd(
         *args, *
         [ObjectType(ObjectIdentity(obj))
          for obj in self.arguments.get]) if self.arguments.get else
                 nextCmd(*args, ObjectType(ObjectIdentity("SNMPv2-MIB"))))
     record = next(response, None)
     while record:
         for value in record[-1]:
             print(value.prettyPrint(), dark=True)
         record = next(response, None)
示例#7
0
 def run(self):
     (zone, where, port,
      source, source_port,
      timeout, lifetime, use_udp,
      rdtype, rdclass, af,
      serial, keyalgorithm, relativize,
      check_origin, export) = (getattr(self.arguments, name) for name in
                               ["zone", "where", "port", "source", "source-port",
                                "timeout", "lifetime", "use-udp",
                                "rdtype", "rdclass", "address-family",
                                "serial", "keyalgorithm", "relativize",
                                "check-origin", "export"])
     if not where:
         where = zone
     where = socket.gethostbyname(where)
     
     if rdtype not in [type for type in dir(dns.rdatatype) if type.isupper()]:
         raise ValueError(f"Unknown or invalid DNS Rdata Type \"{rdtype}\" ...")
     rdtype = getattr(dns.rdatatype, rdtype)
     
     if rdclass not in [type for type in dir(dns.rdataclass) if type.isupper()]:
         raise ValueError(f"Unknown or invalid DNS Rdata Class \"{rdclass}\" ...")
     rdclass = getattr(dns.rdataclass, rdclass)
     
     if af not in [i for i in dir(socket) if i.startswith("AF_")]:
         raise ValueError(f"Unknown or invalid Address Family \"{af}\" ...")
     address_family = int(getattr(socket, af))
     
     if keyalgorithm and keyalgorithm not in [alg for alg in dir(dns.tsig) if alg.startswith("HMAC_")]:
         raise ValueError(f"Unknown or invalid TSIG Algorithm \"{keyalgorithm}\" ...")
     keyalgorithm = dns.tsig.default_algorithm if not keyalgorithm else getattr(dns.tsig, keyalgorithm)
     
     
     config = {"query": {"zone": zone, "where": where, "port": port, "source_port": source_port, "timeout": timeout, "lifetime": lifetime, "use_udp": use_udp},
               "zone": {"check_origin": check_origin, "relativize": relativize}}
     config["query"].update({"rdtype": rdtype, "rdclass": rdclass, "af": address_family, "serial": serial, "keyalgorithm": keyalgorithm, "relativize": relativize})
     
     if source:
         config["query"]["source"] = source
     
     zone = dns.zone.from_xfr(dns.query.xfr(**config["query"]), **config["zone"]).to_text()
     if export:
         export.write(zone)
     print(zone.decode("ascii"), dark = True)
示例#8
0
    def run(self):
        response = requests.get(
            f"http://ip-api.com/json/{self.arguments.host}?fields=258047"
        ).json()
        assert response["status"] == "success", Exception(
            f"{' - '.join(f'{key.title()}: {value}' for key, value in response.items())}"
        )
        print("""            ,,,,,,                 
        o#'9MMHb':'-,o,               --------- Tracking Results ---------
     .oH":HH$' "' ' -*R&o,                    IP Address {query}
    dMMM*""'`'      .oM"HM?.                     Country {country}/{countryCode}
  ,MMM'          "HLbd< ?&H                       Region {regionName}/{region}
 .:MH ."          ` MM  MM&b                        City {city}
. "*H    -        &MMMMMMMMMH:                  Zip Code {zip}
.    dboo        MMMMMMMMMMMM.                 Time Zone {timezone}
.   dMMMMMMb      *MMMMMMMMMP.              Organization {org}
.    MMMMMMMP        *MMMMMP .                       ISP {isp}
     `#MMMMM           MM6P ,                   Latitude {lat}
 '    `MMMP"           HM*`,                   Longitude {lon}
  '    :MM             .- ,                     Is Proxy {proxy}
   '.   `#?..  .       ..'                     Is Mobile {mobile}
      -.   .         .-                        {as}
        ''-.oo,oo.-''                 """.format(**response))
示例#9
0
 def pprint(obj, depth: int = 0):
     prefix = "|  " * depth
     for key, value in obj.items():
         if isinstance(value, str):
             l1 = prefix + f"|--{key}"
             prefix2 = (prefix + "|  ").ljust(24)
             if len(l1) > 23:
                 console.print(l1)
                 console.print(prefix2, (value, True), prefix = prefix2)
             else:
                 console.print(l1.ljust(24), (value, True), prefix = prefix2)
         else:
             programs = len(list(filter(lambda x: isinstance(x[1], str), value.items())))
             folders = len(value) - programs
             console.print(f"{prefix}|--{key}: ({programs}/{folders})")
             pprint(value, depth + 1)
示例#10
0
 def scan(self, host, **kwargs):
     print(f"[i] NSMap results for host {repr(host)}:")
     answer = self.metaquery(host, "ANY", **kwargs).answer if kwargs.pop("any") else None
     if answer:
         self._iter(answer)
     else:
         for name, rdtype in self.rdtypes.items():
             if not dns.rdatatype.is_metatype(rdtype):
                 try:
                     answer = self.metaquery(host, rdtype, **kwargs).answer
                     if answer:
                         self._iter(answer)
                 except Exception as e:
                     print(f" -  {name.ljust(self._max_rdtype_length+1)}", (str(e), True), color = "red")
         else:
             print(f" -  No records are directly available for this host ...", color = "yellow", dark = True)
示例#11
0
 def run(self):
     censys = Censys.API(self.arguments.api_id, self.arguments.api_secret)
     fingerprints = {}
     fields = ["parsed.subject_dn", "parsed.names", "parsed.fingerprint_sha256", "parsed.subject.common_name"]
     certificates = [{key.rsplit(".", 1)[-1]: value for key, value in cert.items()} for cert in censys.certificates.search(f"{self.arguments.domain} and tags: trusted", fields = fields) if cert]
     for certificate in filter(lambda cert: self.arguments.domain in cert.get("names", []) and not any(map(lambda d: d.endswith(".cloudflaressl.com") or d.endswith(".cloudflare.com"), cert["common_name"])), certificates):
         hosts = set()
         fingerprint, common_name, names, sdn = (certificate["fingerprint_sha256"],
                                                 certificate.get("common_name", []),
                                                 certificate.get("names", []),
                                                 certificate.get("subject_dn"))
         results = censys.ipv4.search(f"{fingerprint}", fields = ["443.https.tls.certificate.parsed.extensions.subject_alt_name.dns_names", "443.https.tls.certificate.parsed.names", "ip"])
         if results:
             console.print(f"[+] {fingerprint}: {', '.join(common_name or names or [])}")
             if sdn:
                 console.print(f" -  {sdn}")
         for host in results:
             hosts.add(host["ip"])
             console.print(f" -  {host['ip']} [{', '.join(host.get('443.https.tls.certificate.parsed.names', host.get('443.https.tls.certificate.parsed.extensions.subject_alt_name.dns_names', [])))}]", dark = True)
         fingerprints[fingerprint] = hosts
     hosts = set()
     for value in fingerprints.values():
         hosts.update(value)
     console.print(f"[i] {len(fingerprints) or 'No'} fingerprints {f'and {len(hosts)}' if fingerprints else 'or'} hosts were found.")
 def recvmsg(self, sock):
     hdr = self.recvall(sock, 5)
     if hdr is None:
         print(
             "[!] Unexpected EOF receiving record header: Server closed connection!",
             color="red")
         return None, None, None
     type, version, ln = struct.unpack(">BHH", hdr)
     payload = self.recvall(sock, ln, 10)
     if payload is None:
         print(
             "[!] Unexpected EOF receiving record payload: Server closed connection!",
             color="red")
         return None, None, None
     print(
         f"... Received message: type = {type}, ver = {version:04x}, length = {len(payload)}",
         dark=True)
     return type, version, payload
    def cfsearch(self, domain: str):
        nameservers = [
            ns.to_text() for ns in self.resolver.query(domain, "NS")
        ]
        page = self.session.post("cfsearch.cgi", data={"cfS": domain}).parsed()
        cfl_ids = [
            a.get("href") for a in page.findAll(
                "a",
                attrs={
                    "href":
                    re.compile(
                        r"^http://www.crimeflare.com/cgi-bin/cflist/.*$")
                })
        ]

        print("[i] CloudFlare Search Results:")
        print(" -  Name Servers:")
        for ns in nameservers:
            print(
                f"    - {ns} [{', '.join(ip.to_text() for ip in self.resolver.query(ns, 'A'))}]",
                dark=True)
        print()
        if cfl_ids:
            print(" -  CFList (CFL) IDs: (Single use)")
            for id in cfl_ids:
                print("    - " + id.split("/")[-1], dark=True)
            print()
        if page.ul:
            print(" -  " + "\n -  ".join(page.ul.stripped_strings), dark=True)
        else:
            print(
                " -  No direct-connect IP addresses have been found for this domain ...",
                color="red",
                dark=True)
 def run(self):
     mac = netaddr.EUI(
         int(self.arguments.mac) if self.arguments.mac.isdigit() else self.
         arguments.mac)
     info = mac.info["OUI"]
     print(
         f"[i] Media Access Control (MAC) Address Lookup Results For {mac}:"
     )
     print(f" -  Extended Unique Identifier 64:       {mac.eui64()}",
           dark=True)
     print(
         f" -  Modified EUI64 Address:              {mac.modified_eui64()}",
         dark=True)
     print(
         f" -  Individual Access Block [IAB]:       {mac.iab if mac.is_iab() else 'Not an IAB'}",
         dark=True)
     print(f" -  Organizationally Unique Identifier:  {mac.oui}", dark=True)
     print(f" -  Extended Identifier [EI]:            {mac.ei}", dark=True)
     print(
         f" -  Local Link IPv6 Address:             {mac.ipv6_link_local()}",
         dark=True)
     print(f" -  Vendor Info.:")
     print(f"    - Organization: {info['org']}", dark=True)
     print("    - Address:      {}".format("\n                    ".join(
         info["address"])),
           dark=True)
     print(f" -  OUI Info.:")
     print(f"    - Version: {mac.version}", dark=True)
     print(f"    - Offset:  {info['offset']}", dark=True)
     print(f"    - Size:    {info['size']}", dark=True)
     print(f"    - IDX:     {info['idx']}", dark=True)
     print(f"    - OUI:     {info['oui']}", dark=True)
     print(f" -  Packed Address:          {mac.packed}", dark=True)
     print(f" -  Hexadecimal Address:     {hex(mac)}", dark=True)
     print(f" -  48-bit Positive Integer: {mac.value}", dark=True)
     print(
         f" -  Octets:                  {', '.join(str(n) for n in mac.words)}",
         dark=True)
示例#15
0
 def run(self):
     answer = self.query(self.arguments.server, self.arguments.port)
     server = re.search("whois\: (.*)", answer)
     if server: answer = self.query(server.groups()[0].strip(), 43)
     for line in answer.split("\n"):
         print(line.strip(), dark=line.startswith("%"))
示例#16
0
 def on_recv(self, address, data):
     packet = self.decoder.decode(data)
     print(packet)
     """packet = IPv4(data)
示例#17
0
 def run(self):
     process = None
     if not tor.pids():
         print("[i] Tor is actually not running, starting a new temporary instance ...", color = "yellow")
         process = tor.Tor()
         process.start(False, " -  ")
         print()
     service = tor.HiddenService(self.arguments.target)
     print("[i] Hidden Service Descriptive Info.:")
     print(f" -  Publish Date & Time: {service.published}")
     print(f" -  Descriptor Identifier: {service.descriptor_id}")
     print(f" -  Descriptor Hash: {service.secret_id_part}")
     print(f" -  Descriptor Version: {service.version}")
     print(f" -  Supported Versions: {', '.join(str(v) for v in service.protocol_versions)}")
     print(" -  Permanent Key: ")
     print("    " + service.permanent_key.replace("\n", "\n    "), dark = True)
     print(" -  Signature: ")
     print("    " + service.signature.replace("\n", "\n    "), dark = True)
     print(" -  Introduction Points:")
     print(f"      {' Identifier '.center(32, '-')}  {' Address '.center(21, '-')}")
     for introduction_point in sorted(service.introduction_points(), key=lambda x: x.identifier):
         score = status = None
         print(f"    - {introduction_point.identifier}: " + f"{introduction_point.address}:{introduction_point.port}", dark = True)
     if process:
         process.exit()
示例#18
0
 def _input():
     while not client._closed:
         data = client.recv(0xFFFF)
         if not data:
             break
         console.print(data.decode("ascii", errors="backslashreplace"))
示例#19
0
 def run(self):
     kwargs = {"type": "json"}
     pkwargs = {"css": self.arguments.stylesheet, "confidence": self.arguments.confidence, "macromeasures": self.arguments.macromeasures}
     api = fullcontact.API(self.arguments.api_key)
     if self.arguments.stats != None:
         print(f"[i] Request results for Account Statistics endpoint:")
         response = api.stats(self.arguments.stats, **kwargs)
     elif self.arguments.email:
         print(f"[i] Request results for E-Mail Address based Person Lookup:")
         response = api.person(self.arguments.email, "email", **kwargs, **pkwargs)
     elif self.arguments.phone:
         print(f"[i] Request results for Phone Number based Person Lookup:")
         response = api.person(self.arguments.phone, "phone", countryCode = self.arguments.country_code, **kwargs, **pkwargs)
     elif self.arguments.twitter:
         print(f"[i] Request results for Twitter Username based Person Lookup:")
         response = api.person(self.arguments.twitter, "twitter", **kwargs, **pkwargs)
     elif self.argument.domain:
         print(f"[i] Request results for Domain Name based Company Lookup:")
         response = api.domain(self.arguments.domain, keyPeople = self.arguments.key_people)
     else:
         print(f"[i] Request results for Name based Company Lookup:")
         response = api.company(self.arguments.company, location = self.arguments.location, locality = self.arguments.locality,
                                country = self.arguments.country, region = self.arguments.region)
     pprint(response.json(), 1)
    def run(self):
        kwargs = {
            "family":
            socket.AF_INET6 if self.arguments.ipv6 else socket.AF_INET,
            "type":
            socket.SOCK_DGRAM if self.arguments.udp else socket.SOCK_STREAM,
            "proto": self.arguments.protocol,
            "timeout": self.arguments.timeout or 8,
            "blocking": self.arguments.blocking
        }

        url = urllib.parse.urlsplit(self.arguments.url)
        assert url.scheme in [
            "https", "smtp", "imap", "pop3", "ftp", "xmpp"
        ], ValueError(f"{url.scheme.upper()} is an unsupported protocol!")
        port = url.port or socket.getservbyname(url.scheme)
        sock = socket.socket(**kwargs)
        print(f"[i] Connecting to {url.hostname}:{port} ...", end="\r")
        sock.connect((url.hostname, port))
        print(f"[i] Connected to {url.hostname}:{port} ...")

        if url.scheme != "https":
            print("[i] Sending STARTTLS Command ...")
            if url.scheme == "xmpp":
                sock.send(
                    b"<stream:stream xmlns:stream='http://etherx.jabber.org/streams' xmlns='jabber:client' to='%s' version='1.0'\n"
                )
                sock.recv(0x400)
            else:
                sock.recv(0x400)
                if url.scheme == "smtp":
                    sock.send(b"EHLO openssl.client.net\n")
                    sock.recv(0x400)
                sock.send(
                    (b"STARTTLS\n" if url.scheme in ["smtp", "imap"] else
                     (b"STLS\n" if url.scheme == "pop3" else b"AUTH TLS\n")))
                sock.recv(0x400)
        print("[i] Sending Client Hello ...")
        sock.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'
        )
        print("[i] Waiting for Server Hello ...")

        while True:
            type, version, payload = self.recvmsg(sock)
            if type == None:
                print(
                    "[!] Server closed connection without sending Server Hello.",
                    color="red")
                return False
            if type == 22 and payload[0] == 0x0E:
                break

        print("[i] Sending heartbeat request ...")
        sock.send(b"\x18\x03\x02\x00\x03\x01@\x00")
        #sock.send(b"\x18\x03\x02\x00\x03\x01@\x00")
        while True:
            type, version, payload = self.recvmsg(sock)
            if type is None:
                print(
                    "[!] No heartbeat response received, server's likely not vulnerable.",
                    color="red")
                return False
            elif type == 21:
                print("[i] Received alert:")
                hexdump(payload, prefix="    ")
                print("[!] Server returned error, likely not vulnerable.",
                      color="red")
                return False
            elif type == 24:
                print("[i] Received heartbeat response:")
                hexdump(payload, prefix="    ")
                if len(payload) > 3:
                    print(
                        "[i] WARNING: server returned more data than it should - server is vulnerable!",
                        color="yellow")
                else:
                    print(
                        "[i] Server processed malformed heartbeat, but did not return any extra data."
                    )
                return True
示例#21
0
 def on_stop(self):
     print(datetime.now().strftime(
         "[i] Stopped sniffing %A, %B %d at %H:%M:%S!"))
示例#22
0
 def run(self):
     try:
         if not tor.pids():
             print(
                 "[i] Tor is actually not running, starting a new instance ...",
                 color="yellow")
             Tor = tor.Tor()
             Tor.start(False, " -  ")
             print()
         controller = tor.Controller()
         if self.arguments.list:
             ehs_list = sorted(
                 controller.list_ephemeral_hidden_services([],
                                                           detached=True))
             num = len(ehs_list)
             print(
                 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(f" -  {hs.address} ({hs.descriptor_id})", dark=True)
         elif self.arguments.close:
             for address in sorted(set(self.arguments.close)):
                 if address.endswith(".onion"):
                     address = address.split(".")[0]
                 try:
                     hs = tor.HiddenService(address, controller)
                     discontinued = controller.remove_ephemeral_hidden_service(
                         address)
                     print(
                         f"[+] {hs.address} ({hs.descriptor_id}):",
                         ("Hidden Service not running in the first place ...",
                          "yellow") if not discontinued else
                         "Hidden Service successfully discontinued and closed."
                     )
                 except Exception as e:
                     print(f"[!] {address}.onion: {e}", color="red")
         elif self.arguments.ports:
             ports = {}
             for port in self.arguments.ports:
                 if "=" in port:
                     number, target = port.split("=", 1)
                     ports[int(number)] = target
                 else:
                     ports[int(port)] = int(port)
             print("[i] Creating Hidden Service ...")
             ehs = tor.EphemeralHiddenService(ports,
                                              self.arguments.discard_key,
                                              True,
                                              self.arguments.private_key,
                                              controller)
             print(f"[i] Hidden Service running on {ehs.address}:")
             print(f" -  Publish Date & Time: {ehs.published}")
             print(f" -  Descriptor Identifier: {ehs.descriptor_id}")
             print(f" -  Descriptor Hash: {ehs.secret_id_part}")
             print(f" -  Descriptor Version: {ehs.version}")
             print(" -  Permanent Key: ")
             print("    " + ehs.permanent_key.replace("\n", "\n    "),
                   dark=True)
             print(" -  Signature: ")
             print("    " + ehs.signature.replace("\n", "\n    "),
                   dark=True)
             print(" -  Introduction Points:")
             print(
                 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(
                     f"    - {introduction_point.identifier}: " +
                     f"{introduction_point.address}:{introduction_point.port}",
                     dark=True)
             print()
             print(" -  HS Port Map:")
             for port, target in ports.items():
                 print(f"    - {port}: {target}", dark=True)
         else:
             parser.print_help()
     except Exception as e:
         print(f"[!] {type(e).__name__}:", color="red")
         print(f" -  {e}", color="red", dark=True)
     except KeyboardInterrupt:
         print("[!] Keyboard Interrupted!", color="red")
示例#23
0
 def on_error(self, address, exception):
     raise exception
     print(
         f"[!] {type(exception).__name__} [{':'.join(map(str, address))}]:",
         color="red")
     print(f" -  {exception}", color="red", dark=True)
示例#24
0
        assert commands, "Invalid executable Program!"
        for command in commands:
            try:
                command = command()
                command.parse_args(*args)
                command.run()
            except TypeError as e:
                if str(e) != "issubclass() arg 1 must be a class":
                    raise e
    
    def run(self, argv = sys.argv[1:]):
        args = self.parser.parse_args(argv[:2])
        if args.list != None:
            self.list(args.list, args.debug)
        elif args.executable:
            self.execute(args.executable, *argv[2:])

if __name__ == "__main__":
    csf = CSF
    try:
        csf = csf()
        csf.run()
    except Exception as e:
        filename, line, function, text = traceback.extract_tb(e.__traceback__)[-1]
        console.print(f"[!] {type(e).__name__}: ({filename.replace(csf.location, '.')} line #{line} in {function})", color = "red")
        console.print(f"    {repr(text)}", color = "red", dark = True, parse = False)
        console.print(f" -  {e}", color = "red", dark = True)
        #raise e
    except KeyboardInterrupt:
        console.print(f"[!] Keyboard Interrupted!", color = "red")