Exemplo n.º 1
0
    def _print_stream_item(self, item, pattern=None):
        print("")

        term = Terminal()
        time_label = " on %s at %s" % (term.yellow(item.time.strftime("%a, %d %b %Y")),
                                       term.yellow(item.time.strftime("%H:%M"))) \
                     if item.time is not None else ""
        print("%s%s:" % (term.cyan(item.source), time_label))

        if item.title is not None:
            print("   %s" % self._highlight_pattern(item.title, pattern,
                                                    term.bold_black_on_bright_yellow, term.bold))

        if item.text is not None:
            excerpter = TextExcerpter()
            excerpt, clipped_left, clipped_right = excerpter.get_excerpt(item.text, 220, pattern)

            # Hashtag or mention
            excerpt = re.sub("(?<!\w)([#@])(\w+)",
                             term.green("\\g<1>") + term.bright_green("\\g<2>"), excerpt)
            # URL in one of the forms commonly encountered on the web
            excerpt = re.sub("(\w+://)?[\w.-]+\.[a-zA-Z]{2,4}(?(1)|/)[\w#?&=%/:.-]*",
                             term.bright_magenta_underline("\\g<0>"), excerpt)

            # TODO: This can break previously applied highlighting (e.g. URLs)
            excerpt = self._highlight_pattern(excerpt, pattern, term.black_on_bright_yellow)

            print("   %s%s%s" % ("... " if clipped_left else "", excerpt,
                                 " ..." if clipped_right else ""))

        if item.link is not None:
            print("   %s" % self._highlight_pattern(item.link, pattern,
                                                    term.black_on_bright_yellow_underline,
                                                    term.bright_blue_underline))
Exemplo n.º 2
0
class Logger(object):
    def __init__(self):
        self.t = Terminal()

    def log(self, t, m):
        """
        Log a message to the console.

        Args:
            param1: Type of log {info, warn, critical}
            param2: Log message

        Returns:
            None
        """
        if t == "info":
            print(self.t.green("[{}] ".format(datetime.now())) +
                  "{}".format(m))
        if t == "warn":
            print(self.t.yellow("[{}] ".format(datetime.now())) +
                  self.t.white("{}".format(m)))
        elif t == "critical":
            print(self.t.red("[{}] ".format(datetime.now())) +
                  self.t.white("{}".format(m)))

    def surgical_log(self, t, m):
        """
        Log a message to the console.

        Args:
            param1: Type of log {info, warn, critical}
            param2: Log message

        Returns:
            None
        """
        if t == "info":
            print(self.t.yellow("[{}] ".format(datetime.now())) + "{}".format(m))
        elif t == "critical":
            print(self.t.red("[{}] ".format(datetime.now())) +
                  self.t.white("{}".format(m)))

    def binja_log(self, t, m):
        """
        Log a message to the console.

        Args:
            param1: Type of log {info, warn, critical}
            param2: Log message

        Returns:
            None
        """
        if t == "info":
            print(self.t.cyan("[{}] ".format(datetime.now())) + "{}".format(m))
        elif t == "critical":
            print(self.t.red("[{}] ".format(datetime.now())) + self.t.white("{}".format(m)))
Exemplo n.º 3
0
def ask(choices):
    t = Terminal()
    for idx, item in enumerate(choices):
        num = t.red(str(idx+1).rjust(2))
        title = item['title'].decode('utf-8')
        title = t.white((title[:80] + (title[80:] and '..')).ljust(82)) # truncate
        date = t.yellow(item['date'].rjust(10))
        size = t.cyan(item['size'].rjust(10))
        seed = t.blue(item['seed'].rjust(6))
        peer = t.green(item['peer'].rjust(6))
        print '%s. %s %s %s %s %s' % (num, title, date, size, seed, peer)
    answers = raw_input('What items do you want? (seperated by commas) [1] ')
    if answers: return map(lambda x: int(x)-1, answers.split(r','))
    else: return[0]
Exemplo n.º 4
0
    def _queue_item(self, item, patterns=None):
        self.item_count += 1
        self._queue.append("")

        term = Terminal()
        time_label = (
            " on %s at %s" % (term.yellow(item.time.strftime("%a, %d %b %Y")), term.yellow(item.time.strftime("%H:%M")))
            if item.time is not None
            else ""
        )
        self._queue.append("%s. %s%s:" % (self.item_count, term.cyan(item.source), time_label))

        indent = " " * (len(str(self.item_count)) + 2)

        if item.title is not None:
            self._queue.append(
                "%s%s"
                % (indent, self._highlight_pattern(item.title, patterns, term.bold_black_on_bright_yellow, term.bold))
            )

        if item.text is not None:
            (excerpt, clipped_left, clipped_right) = TextExcerpter.get_excerpt(item.text, 300, patterns)

            # Hashtag or mention
            excerpt = re.sub(r"(?<!\w)([#@])(\w+)", term.green("\\g<1>") + term.green("\\g<2>"), excerpt)

            # URL in one of the forms commonly encountered on the web
            excerpt = re.sub(
                r"(\w+://)?[\w.-]+\.[a-zA-Z]{2,4}(?(1)|/)[\w#?&=%/:.-]*", term.magenta_underline("\\g<0>"), excerpt
            )

            excerpt = self._highlight_pattern(excerpt, patterns, term.black_on_yellow)

            self._queue.append(
                "%s%s%s%s" % (indent, "... " if clipped_left else "", excerpt, " ..." if clipped_right else "")
            )

        if item.link is not None:
            self._queue.append(
                "%s%s"
                % (
                    indent,
                    self._highlight_pattern(item.link, patterns, term.black_on_yellow_underline, term.blue_underline),
                )
            )
Exemplo n.º 5
0
class Util(object):
    def __init__(self):
        self.t = Terminal()

    @staticmethod
    # This probably does not need to be static
    def read(filename, binary=True):
        with open(filename, 'rb' if binary else 'r') as f:
            return f.read()

    def print_xref(self, tag, items):
        for i in items:
            print(self.t.cyan("\t\t\t\t{}: {} {} {} {}".format(
                tag,
                i[0].get_class_name(),
                i[0].get_name(),
                i[0].get_descriptor(),
                " ".join("%x" % j.get_idx() for j in i[1]))))

    def pretty_print_xml(self, xml):
        print(highlight(xml.toprettyxml(), XmlLexer(), TerminalFormatter()))
Exemplo n.º 6
0
class StatusDisplay(Thread):

    def __init__(self, qla_data, status_data, stop_event, logfile=None):
        self.status_data = status_data
        self.qla_data = qla_data
        self.term = Terminal()
        self.stop_event = stop_event
        self.logfile = logfile
        super(StatusDisplay, self).__init__()

    def run(self):
        with self.term.fullscreen(), self.term.hidden_cursor():
            print(self.term.clear())
            while not self.stop_event.is_set():
                self.update_status()
                self.stop_event.wait(5)

    def update_status(self):
        print(self.term.clear())
        print(self.term.move(0, 0) + self.term.cyan(timestamp()))

        print(self.term.move(2, 0) + 'System Status')
        for i, (key, val) in enumerate(six.iteritems(self.status_data)):
            print(self.term.move(3+i, 0) + u'{:<20}  {:>6} {:<6}'.format(
                key, *val
            ))

        print(self.term.move(2, 40) + 'Maximum Source Activity')
        for i, (key, val) in enumerate(six.iteritems(self.qla_data)):
            print(self.term.move(3+i, 40) + u'{:<20}  {:>6} {:<6}'.format(
                key, *val
            ))

        if self.logfile is not None:
            logs = check_output('tail -n20 {}'.format(self.logfile), shell=True)
            n_lines = term.height - 15
            loglines = list(
                reversed(logs.decode('utf-8').splitlines())
            )[:n_lines]
            print(self.term.move(14, 0) + '\n'.join(loglines))
Exemplo n.º 7
0
Arquivo: liffy.py Projeto: Yas3r/liffy
def main():
    # Terminal Colors
    t = Terminal()

    def banner():
        print(t.cyan("""

    .____    .__  _____  _____
    |    |   |__|/ ____\/ ____\__.__.
    |    |   |  \   __\   __<   |  |
    |    |___|  ||  |   |  |  \___  |
    |_______ \__||__|   |__|  / ____| v1.2
        \/                \/

"""))

    def progressbar():

        bar_width = 70
        sys.stdout.write(t.cyan("[{0}]  ".format(datetime.datetime.now())) + " " * bar_width)
        sys.stdout.flush()
        sys.stdout.write("\b" * (bar_width + 1))

        for w in xrange(bar_width):
            time.sleep(0.01)
            sys.stdout.write(".")
            sys.stdout.flush()

        sys.stdout.write("\n")

    #---------------------------------------------------------------------------------------------------

    banner()

    if not len(sys.argv):
        print(t.red("[{0}] ".format(datetime.datetime.now())) + "Not Enough Arguments!")
        print(t.red("[{0}] ".format(datetime.datetime.now())) + "Example: ./liffy.py --url \
        http://target/files.php?file= --data\n")
        sys.exit(0)

    #---------------------------------------------------------------------------------------------------

    """ Command Line Arguments """

    parser = argparse.ArgumentParser()
    parser.add_argument("--url", help="target url")
    parser.add_argument("--data", help="data technique", action="store_true")
    parser.add_argument("--input", help="input technique", action="store_true")
    parser.add_argument("--expect", help="expect technique", action="store_true")
    parser.add_argument("--environ", help="/proc/self/environ technique", action="store_true")
    parser.add_argument("--access", help="access logs technique", action="store_true")
    parser.add_argument("--ssh", help="auth logs technique", action="store_true")
    parser.add_argument("--filter", help="filter technique", action="store_true")
    parser.add_argument("--location", help="path to target file (access log, auth log, etc.)")
    parser.add_argument("--nostager", help="execute payload directly, do not use stager", action="store_true")
    parser.add_argument("--relative", help="use path traversal sequences for attack", action="store_true")
    parser.add_argument("--cookies", help="session cookies")
    args = parser.parse_args()

    #---------------------------------------------------------------------------------------------------

    """ Assign argument values """

    url = args.url
    nostager = args.nostager
    relative = args.relative
    c = args.cookies

    #---------------------------------------------------------------------------------------------------

    """ Check to make sure target is actually up """

    print(t.cyan("[{0}] ".format(datetime.datetime.now())) + "Checking Target: {0}".format(url))
    parsed = urlparse.urlsplit(url)
    domain = parsed.scheme + "://" + parsed.netloc
    progressbar()

    try:
        r = requests.get(domain)
        if r.status_code != 200:
            print(t.red("[{0}] ".format(datetime.datetime.now())) + "Did Not Receive Correct Response From Target URL!")
        else:
            print(t.red("[{0}] ".format(datetime.datetime.now())) + "Target URL Looks Good!")
            if args.data:
                print(t.red("[{0}] ".format(datetime.datetime.now())) + "Data Technique Selected!")
                d = core.Data(url, nostager, c)
                d.execute_data()
            elif args.input:
                print(t.red("[{0}] ".format(datetime.datetime.now())) + "Input Technique Selected!")
                i = core.Input(url, nostager, c)
                i.execute_input()
            elif args.expect:
                print(t.red("[{0}] ".format(datetime.datetime.now())) + "Expect Technique Selected!")
                e = core.Expect(url, nostager, c)
                e.execute_expect()
            elif args.environ:
                print(t.red("[{0}] ".format(datetime.datetime.now())) + "/proc/self/environ Technique Selected!")
                i = core.Environ(url, nostager, relative, c)
                i.execute_environ()
            elif args.access:
                if not args.location:
                    print(t.red("[{0}] ".format(datetime.datetime.now())) + "Log Location Not Provided! Using Default")
                    l = '/var/log/apache2/access.log'
                else:
                    l = args.location
                a = core.Logs(url, l, nostager, relative, c)
                a.execute_logs()
            elif args.ssh:
                if not args.location:
                    print(t.red("[{0}] ".format(datetime.datetime.now())) + "Log Location Not Provided! Using Default")
                    l = '/var/log/auth.log'
                else:
                    l = args.location
                a = core.SSHLogs(url, l, relative, c)
                a.execute_ssh()
            elif args.filter:
                print(t.red("[{0}] ".format(datetime.datetime.now())) + "Filter Technique Selected!")
                f = core.Filter(url, c)
                f.execute_filter()
            else:
                print(t.red("[{0}] ".format(datetime.datetime.now())) + "Technique Not Selected!")
                sys.exit(0)
    except requests.HTTPError as e:
        print(t.red("[{0}] HTTP Error!".format(datetime.datetime.now())) + str(e))
Exemplo n.º 8
0
db = SqliteDatabase('emails.db')
db.connect()

def top_words(emails):
  vectorizer = CountVectorizer(min_df=10, ngram_range=(1, 2), stop_words='english')
  text = np.array([email.text for email in emails])
  parties = np.array([email.sender.party for email in emails])

  vectors = vectorizer.fit_transform(text)
  words = vectorizer.get_feature_names()
  num_cols = vectors.get_shape()[1]

  emails_containing_words = map(lambda n: vectors.getcol(n).getnnz(), range(num_cols))
  emails_containing_words = sorted(zip(words, emails_containing_words), key=lambda x: -x[1])
  return emails_containing_words

emails = Email.select().join(SenderMetadata).where(SenderMetadata.party == "d")
for item in top_words(emails):
  print t.cyan(str(item))

# emails = Email.select().join(SenderMetadata).where(SenderMetadata.party == "r")
# for item in top_words(emails):
#   print t.red(str(item))

# emails = Email.select()
# for item in emails:
#   print item.email()

db.close()
try:
	while True:
		numberOfIterations += 1
		x = numpy.dot(-1.0, numpy.dot(K, x)) + F
		norma = numpy.linalg.norm(numpy.dot(matrix, x) - b)
		if numberOfIterations % 1000 == 0:
			print(numberOfIterations)
			print("\n")
			print("Itreation number " + str(numberOfIterations))
			print("Norm is " +  str(norma))
			print("\n")
		if norma < epsilon:
			break
except Exception as e:
	print("Problem is: \n" + str(e))

x_ex = numpy.linalg.solve(matrix, b)
err = x - x_ex
dt2 = time.clock()


print("\n")
print('\033[1m' + '\033[4m' + t.blue("In the issue: \n"))
print(t.cyan("Parameter tay is ") + t.red(str(tay)))
print(t.cyan("Nubmer of iterations ") + t.red(str(numberOfIterations)))
#print("Solution is ", x)
print(t.cyan("Error is ") + t.red(str(numpy.linalg.norm(err))))
print(t.cyan("Time of solve ") + t.red(str(dt2-dt1)) + t.cyan(" with tay ") + t.red(str(tay)))
print("\n")
	training_set = Classifier.bunch_with_targets(speeches, analysis.target_function2)
	naive_bayes.train_classifier(training_set.data, training_set.target)
	probabilities = naive_bayes.classify_document(frame.word_string)

	tfidf_frames_vector = naive_bayes.vectorizer.transform([frame.word_string])

	print "Predicted Class: ", naive_bayes.classifier.predict(tfidf_frames_vector)[0]
	print "Predict Proba: ", naive_bayes.classifier.predict_proba(tfidf_frames_vector)[0]

	print "Probability A (Rep): ", probabilities[0]
	print "Probability B (Dem): ", probabilities[1]

	if probabilities[0] > probabilities[1]:
		print t.red("A (Rep) NB Proba > B (Dem) NB Proba: Classify Republican")
	else:
		print t.cyan("B (Dem) NB Proba > A (Rep) NB Proba: Classify Democratic")

	print "[DB] Proba Ratio: ", proba_ratio
	print "[DB] Raw Ratios: ", raw_ratio
	print "Frame Plot Ratio (Log Prob Ratio): ", log_proba_ratio # visual ratio, what you see on the graph
	if proba_ratio < 1 and log_proba_ratio < 0:
		print t.cyan("Proba < 1 (Log Proba Ratio < 0): Classify Democratic")
	elif proba_ratio > 1 and log_proba_ratio > 0:
		print t.red("Proba > 1 (Log Proba Ratio > 0): Classify Republican")
	else:
		print t.red("!!! ERROR ERROR ERROR ERROR ERROR !!!")

	rep_frame_freq = sum(map(lambda speech: speech.frame_freq, rep_speeches))# / len(rep_speeches)
	dem_frame_freq = sum(map(lambda speech: speech.frame_freq, dem_speeches))# / len(dem_speeches)

	print "Rep Frame Freq", rep_frame_freq
Exemplo n.º 11
0
class AttackSurface(object):
    def __init__(self, apk, components):
        self.t = Terminal()
        self.logger = Logger()
        self.apk = apk
        self.xml = self.apk.get_AndroidManifest()
        # Populate XML elements
        self.xml_activities = self.xml.getElementsByTagName("activity")
        self.xml_services = self.xml.getElementsByTagName("service")
        self.xml_receivers = self.xml.getElementsByTagName("receiver")
        self.xml_providers = self.xml.getElementsByTagName("provider")
        self.components = components

    def activities(self):
        """
        Analyze the attack surface for activities
        """
        filters = None
        # TODO Enumerate the permission attribute for the activity element
        for a in self.components.activities:
            filters = self.apk.get_intent_filters("activity", a)
            if self.xml_activities:
                for activity in self.xml_activities:
                    # Match the element name with the component name
                    if activity.getAttribute("android:name") == a \
                            or activity.getAttribute("android.name").split(".")[-1] == a.split(".")[-1]:
                        # Find the android:exported element attribute
                        if activity.getAttribute("android:exported"):
                            # Determine if the attribute is set to true
                            if activity.getAttribute(
                                    "android:exported") == "true":
                                print(
                                    self.t.yellow(
                                        "\n\t--> activity : {}".format(a)))
                                if activity.getAttribute("android:permission"):
                                    print(
                                        self.t.red(
                                            "\t\t--> permission : {}".format(
                                                activity.getAttribute(
                                                    "android:permission"))))
                                # Enumerate the intent filters for the give activity
                                filters = self.apk.get_intent_filters(
                                    "activity", a)
                                if filters:
                                    # Enumerate the intent filter's action and category
                                    # elements
                                    for key, values in filters.items():
                                        if key == "action":
                                            for value in values:
                                                print(
                                                    self.t.yellow(
                                                        "\t\t--> action : {}".
                                                        format(value)))
                                        if key == "category":
                                            for value in values:
                                                print(
                                                    self.t.yellow(
                                                        "\t\t--> category : {}"
                                                        .format(value)))
                                    # Pull data schemes from XML
                                    intents = activity.getElementsByTagName(
                                        "intent-filter")
                                    schemes = list()
                                    mimes = list()
                                    hosts = list()
                                    paths = list()
                                    if intents:
                                        # Enumerate data schemes for the
                                        # intent filters
                                        for intent in intents:
                                            data = intent.getElementsByTagName(
                                                "data")
                                            if data:
                                                for d in data:
                                                    if d.getAttribute(
                                                            "android:scheme"):
                                                        schemes.append(
                                                            d.getAttribute(
                                                                "android:scheme"
                                                            ))
                                                    if d.getAttribute(
                                                            "android:mimeType"
                                                    ):
                                                        mimes.append(
                                                            d.getAttribute(
                                                                "android:mimeType"
                                                            ))
                                                    if d.getAttribute(
                                                            "android:host"):
                                                        hosts.append(
                                                            d.getAttribute(
                                                                "android:host")
                                                        )
                                                    if d.getAttribute(
                                                            "android:path"):
                                                        paths.append(
                                                            d.getAttribute(
                                                                "android:path")
                                                        )
                                        schemes = list(set(schemes))
                                        mimes = list(set(mimes))
                                        hosts = list(set(hosts))
                                        paths = list(set(paths))
                                        for scheme in schemes:
                                            print(
                                                self.t.cyan(
                                                    "\t\t--> scheme : {}".
                                                    format(scheme)))
                                        for mime in mimes:
                                            print(
                                                self.t.magenta(
                                                    "\t\t--> mime : {}".format(
                                                        mime)))
                                        for host in hosts:
                                            print(
                                                self.t.white(
                                                    "\t\t--> host : {}".format(
                                                        host)))
                                        for path in paths:
                                            print(
                                                self.t.white(
                                                    "\t\t--> path : {}".format(
                                                        path)))
                                        print("\n")
                            elif activity.getAttribute(
                                    "android:exported") == "false":
                                continue
                        else:
                            filters = self.apk.get_intent_filters(
                                "activity", a)
                            if filters:
                                # Enumerate the intent filter's action and category
                                # elements
                                print(
                                    self.t.yellow(
                                        "\n\t--> activity : {}".format(a)))
                                if activity.getAttribute("android:permission"):
                                    print(
                                        self.t.red(
                                            "\t\t--> permission : {}".format(
                                                activity.getAttribute(
                                                    "android:permission"))))
                                for key, values in filters.items():
                                    if key == "action":
                                        for value in values:
                                            print(
                                                self.t.yellow(
                                                    "\t\t--> action : {}".
                                                    format(value)))
                                    if key == "category":
                                        for value in values:
                                            print(
                                                self.t.yellow(
                                                    "\t\t--> category : {}".
                                                    format(value)))
                                # Pull data schemes from XML
                                intents = activity.getElementsByTagName(
                                    "intent-filter")
                                schemes = list()
                                mimes = list()
                                hosts = list()
                                paths = list()
                                if intents:
                                    # Enumerate data schemes for the
                                    # intent filters
                                    for intent in intents:
                                        data = intent.getElementsByTagName(
                                            "data")
                                        if data:
                                            for d in data:
                                                if d.getAttribute(
                                                        "android:scheme"):
                                                    schemes.append(
                                                        d.getAttribute(
                                                            "android:scheme"))
                                                if d.getAttribute(
                                                        "android:mimeType"):
                                                    mimes.append(
                                                        d.getAttribute(
                                                            "android:mimeType")
                                                    )
                                                if d.getAttribute(
                                                        "android:host"):
                                                    hosts.append(
                                                        d.getAttribute(
                                                            "android:host"))
                                                if d.getAttribute(
                                                        "android:path"):
                                                    paths.append(
                                                        d.getAttribute(
                                                            "android:path"))
                                    schemes = list(set(schemes))
                                    mimes = list(set(mimes))
                                    hosts = list(set(hosts))
                                    paths = list(set(paths))
                                    for scheme in schemes:
                                        print(
                                            self.t.cyan(
                                                "\t\t--> scheme : {}".format(
                                                    scheme)))
                                    for mime in mimes:
                                        print(
                                            self.t.magenta(
                                                "\t\t--> mime : {}".format(
                                                    mime)))
                                    for host in hosts:
                                        print(
                                            self.t.white(
                                                "\t\t--> host : {}".format(
                                                    host)))
                                    for path in paths:
                                        print(
                                            self.t.white(
                                                "\t\t--> path : {}".format(
                                                    path)))
                                    print("\n")
            else:
                AttackSurfaceError("Activites not loaded from XML (!)")

    def receivers(self):
        """
        Analyze the attack surface for receivers
        """
        filters = None
        # TODO Enumerate the permission attribute for the activity element
        for r in self.components.receivers:
            if self.xml_receivers:
                for receiver in self.xml_receivers:
                    # Match the element name with the component name
                    if receiver.getAttribute("android:name") == r \
                            or receiver.getAttribute("android.name").split(".")[-1] == r.split(".")[-1]:
                        # Find the android:exported element attribute
                        if receiver.getAttribute("android:exported"):
                            # Determine if the attribute is set to true
                            if receiver.getAttribute(
                                    "android:exported") == "true":
                                print(
                                    self.t.yellow(
                                        "\n\t--> receiver : {}".format(r)))
                                if receiver.getAttribute("android:permission"):
                                    print(
                                        self.t.red(
                                            "\t\t--> permission : {}".format(
                                                receiver.getAttribute(
                                                    "android:permission"))))
                                    # Enumerate the intent filters for the give receiver
                                filters = self.apk.get_intent_filters(
                                    "receiver", r)
                                if filters:
                                    # Enumerate the intent filter's action and category
                                    # elements
                                    for key, values in filters.items():
                                        if key == "action":
                                            for value in values:
                                                print(
                                                    self.t.yellow(
                                                        "\t\t--> action : {}".
                                                        format(value)))
                                        if key == "category":
                                            for value in values:
                                                print(
                                                    self.t.yellow(
                                                        "\t\t--> category : {}"
                                                        .format(value)))
                                    print("\n")
                            elif receiver.getAttribute(
                                    "android:exported") == "false":
                                continue
                        else:
                            print(
                                self.t.yellow(
                                    "\n\t--> receiver : {}".format(r)))
                            if receiver.getAttribute("android:permission"):
                                print(
                                    self.t.red(
                                        "\t\t--> permission : {}".format(
                                            receiver.getAttribute(
                                                "android:permission"))))
                            filters = self.apk.get_intent_filters(
                                "receiver", r)
                            if filters:
                                # Enumerate the intent filter's action and category
                                # elements
                                for key, values in filters.items():
                                    if key == "action":
                                        for value in values:
                                            print(
                                                self.t.yellow(
                                                    "\t\t--> action : {}".
                                                    format(value)))
                                    if key == "category":
                                        for value in values:
                                            print(
                                                self.t.yellow(
                                                    "\t\t--> category : {}".
                                                    format(value)))
                                print("\n")
            else:
                AttackSurfaceError("Receivers not loaded from XML (!)")

    def services(self):
        """
        Analyze the attack surface for services
        """
        filters = None
        # TODO Enumerate the permission attribute for the service element
        for s in self.components.services:
            if self.xml_services:
                for service in self.xml_services:
                    # Match the element name with the component name
                    if service.getAttribute("android:name") == s \
                            or service.getAttribute("android.name").split(".")[-1] == s.split(".")[-1]:
                        # Find the android:exported element attribute
                        if service.getAttribute("android:exported"):
                            # Determine if the attribute is set to true
                            if service.getAttribute(
                                    "android:exported") == "true":
                                print(
                                    self.t.yellow(
                                        "\n\t--> service : {}".format(s)))
                                if service.getAttribute("android:permission"):
                                    print(
                                        self.t.red(
                                            "\t\t--> permission : {}".format(
                                                service.getAttribute(
                                                    "android:permission"))))
                                    # Enumerate the intent filters for the give receiver
                                filters = self.apk.get_intent_filters(
                                    "service", s)
                                if filters:
                                    # Enumerate the intent filter's action and category
                                    # elements
                                    for key, values in filters.items():
                                        if key == "action":
                                            for value in values:
                                                print(
                                                    self.t.yellow(
                                                        "\t\t--> action : {}".
                                                        format(value)))
                                    print("\n")
                            elif service.getAttribute(
                                    "android:exported") == "false":
                                continue
                        else:
                            print(
                                self.t.yellow(
                                    "\n\t--> service : {}".format(s)))
                            if service.getAttribute("android:permission"):
                                print(
                                    self.t.red(
                                        "\t\t--> permission : {}".format(
                                            service.getAttribute(
                                                "android:permission"))))
                            filters = self.apk.get_intent_filters("service", s)
                            if filters:
                                # Enumerate the intent filter's action and category
                                # elements
                                for key, values in filters.items():
                                    if key == "action":
                                        for value in values:
                                            print(
                                                self.t.yellow(
                                                    "\t\t--> action : {}".
                                                    format(value)))
                                print("\n")
            else:
                AttackSurfaceError("Services not loaded from XML (!)")

    def providers(self):
        """
        Analyze the attack surface for providers
        """
        filters = None
        # TODO Enumerate the permission attribute for the provider element
        for p in self.components.providers:
            if self.xml_providers:
                for provider in self.xml_providers:
                    # Match the element name with the component name
                    if provider.getAttribute("android:name") == p \
                            or provider.getAttribute("android.name").split(".")[-1] == p.split(".")[-1]:
                        # Find the android:exported element attribute
                        if provider.getAttribute("android:exported"):
                            # Determine if the attribute is set to true
                            if provider.getAttribute(
                                    "android:exported") == "true":
                                print(
                                    self.t.yellow(
                                        "\n\t--> provider : {}".format(p)))
                                if provider.getAttribute("android:permission"):
                                    print(
                                        self.t.red(
                                            "\t\t--> provider : {}".format(
                                                provider.getAttribute(
                                                    "android:permission"))))
                            elif provider.getAttribute(
                                    "android:exported") == "false":
                                continue
            else:
                AttackSurfaceError("Services not loaded from XML (!)")

    def run(self):
        """
        Discover application's attack surface
        """
        if self.components.activities:
            self.activities()
        if self.components.services:
            self.services()
        if self.components.receivers:
            self.receivers()
        if self.components.providers:
            self.providers()
Exemplo n.º 12
0
class Run(SurgicalCmd):
    def __init__(self, vm, vmx):
        SurgicalCmd.__init__(self)
        self.logger = Logger()
        self.t = Terminal()
        self.u = Util()
        self.vm = vm
        self.vmx = vmx
        self.methods = self.vm.get_methods()
        self.intent = IntentModule()
        self.zip = ZipModule()
        self.socket = SocketModule()
        self.modules = [m for m in self.zip, self.intent, self.socket]
        self.target_module = None
        self.methods_api_usage = list()

    def do_modules(self, args):
        """
        List and select target API modules.

        := modules list
        := modules select
        """

        # Locals
        selection = None

        try:
            if args.split()[0] == "list":
                if self.modules:
                    print("\n")
                    for m in self.modules:
                        if m:
                            print(self.t.cyan("\t--> {}".format(m.name)))
                    print("\n")
            if args.split()[0] == "select":
                if self.modules:
                    selection = raw_input(self.t.yellow("[{}] ".format(datetime.now())) + "Select module : ")
                    for m in self.modules:
                        if m:
                            if selection == m.name:
                                self.target_module = m
                                self.logger.surgical_log("info", "{} module selected (!)".format(m.name))
        except Exception as e:
            SurgicalError(e.message)

    def do_api(self, args):
        """
        List and select methods from a given loaded API module

        := api list
        := api select
        := api analyzed list
        := api analyzed select
        """

        # Locals
        class_selection = None
        method_selection = None
        surgical_lib = None

        try:
            # List the available API methods from the target module
            if args.split()[0] == "list":
                if self.target_module:
                    print("\n")
                    for k, v in self.target_module.model.values.items():
                        print("\n")
                        for m in v:
                            print(self.t.cyan("\t--> {} : {} : {}"
                                              .format(self.target_module.name,
                                                      k.split(".")[-1], m)))
                    print("\n")
                else:
                    self.logger.surgical_log("info", "Target module has not been loaded (!)")
            # Select an API method from the target module
            elif args.split()[0] == "select":
                if self.target_module:
                    # TODO Consider building a wrapper around raw_input()
                    class_selection = raw_input(self.t.yellow("[{}] ".format(datetime.now())) + "Select class : ")
                    method_selection = raw_input(self.t.yellow("[{}] ".format(datetime.now())) + "Select method : ")
                    for k, v in self.target_module.model.values.items():
                        # This is so we can support classes with identical
                        # method names --> Ex: java.util.zip.ZipFile
                        if class_selection == k.split(".")[-1]:
                            for m in v:
                                if m == method_selection:
                                    self.logger.surgical_log("info",
                                                             "Analyzing ...")
                                    from core.brains.surgical.lib.libsurgical import SurgicalLib
                                    # Begin processing and return the results
                                    # from the selected api
                                    surgical_lib = SurgicalLib(self.target_module,
                                                               self.vmx,
                                                               self.vm,
                                                               k,
                                                               method_selection,
                                                               self.methods)
                                    # methods_api_usage will contain a list of
                                    # tuples
                                    self.methods_api_usage = surgical_lib.search()
                                else:
                                    self.logger.surgical_log("warn",
                                                             "Method not found (!)")
            # Analyze the processed method list
            elif args.split()[0] == "analyzed":
                # List the methods that have been processed
                if args.split()[1] == "list":
                    if self.methods_api_usage:
                        print("\n")
                        for m in self.methods_api_usage:
                            print(self.t.cyan("\t--> {} -> {} "
                                              .format(m[0].class_name,
                                                      m[0].name)))
                        print("\n")
                    else:
                        SurgicalError("API usage not found (!)")
                # Select from the processed method list
                elif args.split()[1] == "select":
                    if self.methods_api_usage:
                        selection = raw_input(self.t.yellow("[{}] ".format(datetime.now())) + "Select method : ")
                        for m in self.methods_api_usage:
                            if selection == m[0].name:
                                print("\n")
                                print(self.t.cyan("\t--> Class : {}"
                                                  .format(m[0].class_name)))
                                print(self.t.cyan("\t\t--> Method : {}"
                                                  .format(m[0].name)))
                                print(self.t.cyan("\t\t\t --> XREFS ###########"))
                                self.u.print_xref("T", m[1].method.XREFto.items)
                                self.u.print_xref("F", m[1].method.XREFfrom.items)
                                print("\n")
                                print(highlight(m[2],
                                                JavaLexer(),
                                                TerminalFormatter()))
                    else:
                        SurgicalError("API usage not found (!)")
        except Exception as e:
            SurgicalError(e.message)
Exemplo n.º 13
0
from selenium.webdriver.support import expected_conditions as EC

from blessings import Terminal

t = Terminal()

# Check for args, print logo and usage
if not len(sys.argv[1:]):
    print t.cyan("""
 ____          _   _____     _   
|    \ ___ ___| |_|   | |___| |_ 
|  |  | . |  _| '_| | | | -_|  _|
|____/|___|_| |_,_|_|___|___|_|  
                               
Welcome to DorkNet.

To start using this script please provide one or more command
line arguments and their corresponding value, where applicable.
To display all options available use -h or --help.

Example:
DorkNet.py -h
DorkNet.py -d inurl:show.php?id= --verbose\n""")

    sys.exit(0)

# Handle command line arguments
parser = argparse.ArgumentParser(
    description="Use this script and dorks to find vulnerable web applications."
)
group = parser.add_mutually_exclusive_group()
Exemplo n.º 14
0
from blessings import Terminal

t = Terminal()
c = pycurl.Curl()

edb = False
logging = False

# Print logo
print t.cyan("""
oo.ooooo.  oooo    ooo oo.ooooo.   .oooo.   oooo d8b  .oooo.o  .ooooo.   oooo d8b 
 888' `88b  `88.  .8'   888' `88b `P  )88b  `888""8P d88(  "8 d88' `88b `888""8P 
 888   888   `88..8'    888   888  .oP"888   888     `"Y88b.  888ooo888  888 
 888   888    `888'     888   888 d8(  888   888     o.  )88b 888    .o  888 
 888bod8P'     .8'      888bod8P' `Y888""8o d888b    8""888P' `Y8bod8P' d888b 
 888       .o..P'       888                                             
o888o      `Y8P'       o888o            				
 
						Common Vulnerabilities and Exploits
 																""")


# We'll just go ahead and steal ExploitDB's hard work for this part (<3)
def s_sploit():

    print "\n[" + t.green(
        "+"
    ) + "]Please provide a search query. Multiple terms are allowed in this module."
    query = raw_input("\n<" + t.cyan("SEARCHSPLOIT") + ">$ ")
Exemplo n.º 15
0
class Interact(object):
    def __init__(self, vm, vmx):
        self.t = Terminal()
        self.vm = vm
        self.vmx = vmx
        self.config = Config()

    def print_class_tree(self):
        for c in self.vm.get_classes():
            print("\n")
            print(self.t.yellow("\t--> class : {}".format(c.name)))
            for f in c.get_fields():
                print(self.t.white("\t\t--> field : {}".format(f.name)))
            for m in c.get_methods():
                print(self.t.cyan("\t\t\t--> method : {}".format(m.name)))

    def find_class(self, name):
        """
        Find class helper function.

        Args:
            param1: name
        Returns:
            return: androguard.core.bytecodes.dvm.ClassDefItem
        """
        try:
            if name:
                for c in self.vm.get_classes():
                    if name == c.name:
                        return c
                        break
                    elif name in c.name:
                        return c
                        break
        except Exception as e:
            raise e

    def print_methods(self, c):
        """
        Print methods from a target class helper function.

        Args:
            param1: androguard.core.bytecodes.dvm.ClassDefItem

        Returns:
            None
        """
        try:
            if c:
                for m in c.get_methods():
                    if m.code:
                        print(m.pretty_show())
            else:
                return
        except Exception as e:
            raise e

    def get_classes(self):
        """
        Args:
            None

        Returns:
            None
        """
        try:
            for c in self.vm.get_classes():
                print(c.name)
        except Exception as e:
            raise e

    def run(self):
        """
        Args:
            None

        Returns:
            None
        """
        ipshell = InteractiveShellEmbed(config=self.config, banner1="")
        ipshell()
Exemplo n.º 16
0
class AttackSurface(object):
    def __init__(self, apk, components):
        self.t = Terminal()
        self.logger = Logger()
        self.apk = apk
        self.xml = self.apk.get_AndroidManifest()
        # Populate XML elements
        self.xml_activities = self.xml.getElementsByTagName("activity")
        self.xml_services = self.xml.getElementsByTagName("service")
        self.xml_receivers = self.xml.getElementsByTagName("receiver")
        self.xml_providers = self.xml.getElementsByTagName("provider")
        self.components = components

    def activities(self):
        """
        Analyze the attack surface for activities
        """
        filters = None
        # TODO Enumerate the permission attribute for the activity element
        for a in self.components.activities:
            filters = self.apk.get_intent_filters("activity", a)
            if self.xml_activities:
                for activity in self.xml_activities:
                    # Match the element name with the component name
                    if activity.getAttribute("android:name") == a \
                            or activity.getAttribute("android.name").split(".")[-1] == a.split(".")[-1]:
                        # Find the android:exported element attribute
                        if activity.getAttribute("android:exported"):
                            # Determine if the attribute is set to true
                            if activity.getAttribute("android:exported") == "true":
                                print(self.t.yellow("\n\t--> activity : {}".format(a)))
                                if activity.getAttribute("android:permission"):
                                    print(self.t.red("\t\t--> permission : {}".format(activity.getAttribute("android:permission"))))
                                # Enumerate the intent filters for the give activity
                                filters = self.apk.get_intent_filters("activity", a)
                                if filters:
                                    # Enumerate the intent filter's action and category
                                    # elements
                                    for key, values in filters.items():
                                        if key == "action":
                                            for value in values:
                                                print(self.t.yellow("\t\t--> action : {}".format(value)))
                                        if key == "category":
                                            for value in values:
                                                print(self.t.yellow("\t\t--> category : {}".format(value)))
                                    # Pull data schemes from XML
                                    intents = activity.getElementsByTagName("intent-filter")
                                    schemes = list()
                                    mimes = list()
                                    hosts = list()
                                    paths = list()
                                    if intents:
                                        # Enumerate data schemes for the
                                        # intent filters
                                        for intent in intents:
                                            data = intent.getElementsByTagName("data")
                                            if data:
                                                for d in data:
                                                    if d.getAttribute("android:scheme"):
                                                        schemes.append(d.getAttribute("android:scheme"))
                                                    if d.getAttribute("android:mimeType"):
                                                        mimes.append(d.getAttribute("android:mimeType"))
                                                    if d.getAttribute("android:host"):
                                                        hosts.append(d.getAttribute("android:host"))
                                                    if d.getAttribute("android:path"):
                                                        paths.append(d.getAttribute("android:path"))
                                        schemes = list(set(schemes))
                                        mimes = list(set(mimes))
                                        hosts = list(set(hosts))
                                        paths = list(set(paths))
                                        for scheme in schemes:
                                            print(self.t.cyan("\t\t--> scheme : {}".format(scheme)))
                                        for mime in mimes:
                                            print(self.t.magenta("\t\t--> mime : {}".format(mime)))
                                        for host in hosts:
                                            print(self.t.white("\t\t--> host : {}".format(host)))
                                        for path in paths:
                                            print(self.t.white("\t\t--> path : {}".format(path)))
                                        print("\n")
                            elif activity.getAttribute("android:exported") == "false":
                                continue
                        else:
                            filters = self.apk.get_intent_filters("activity", a)
                            if filters:
                                # Enumerate the intent filter's action and category
                                # elements
                                print(self.t.yellow("\n\t--> activity : {}".format(a)))
                                if activity.getAttribute("android:permission"):
                                    print(self.t.red("\t\t--> permission : {}".format(activity.getAttribute("android:permission"))))
                                for key, values in filters.items():
                                    if key == "action":
                                        for value in values:
                                            print(self.t.yellow("\t\t--> action : {}".format(value)))
                                    if key == "category":
                                        for value in values:
                                            print(self.t.yellow("\t\t--> category : {}".format(value)))
                                # Pull data schemes from XML
                                intents = activity.getElementsByTagName("intent-filter")
                                schemes = list()
                                mimes = list()
                                hosts = list()
                                paths = list()
                                if intents:
                                    # Enumerate data schemes for the
                                    # intent filters
                                    for intent in intents:
                                        data = intent.getElementsByTagName("data")
                                        if data:
                                            for d in data:
                                                if d.getAttribute("android:scheme"):
                                                    schemes.append(d.getAttribute("android:scheme"))
                                                if d.getAttribute("android:mimeType"):
                                                    mimes.append(d.getAttribute("android:mimeType"))
                                                if d.getAttribute("android:host"):
                                                    hosts.append(d.getAttribute("android:host"))
                                                if d.getAttribute("android:path"):
                                                    paths.append(d.getAttribute("android:path"))
                                    schemes = list(set(schemes))
                                    mimes = list(set(mimes))
                                    hosts = list(set(hosts))
                                    paths = list(set(paths))
                                    for scheme in schemes:
                                        print(self.t.cyan("\t\t--> scheme : {}".format(scheme)))
                                    for mime in mimes:
                                        print(self.t.magenta("\t\t--> mime : {}".format(mime)))
                                    for host in hosts:
                                        print(self.t.white("\t\t--> host : {}".format(host)))
                                    for path in paths:
                                        print(self.t.white("\t\t--> path : {}".format(path)))
                                    print("\n")
            else:
                AttackSurfaceError("Activites not loaded from XML (!)")

    def receivers(self):
        """
        Analyze the attack surface for receivers
        """
        filters = None
        # TODO Enumerate the permission attribute for the activity element
        for r in self.components.receivers:
            if self.xml_receivers:
                for receiver in self.xml_receivers:
                    # Match the element name with the component name
                    if receiver.getAttribute("android:name") == r \
                            or receiver.getAttribute("android.name").split(".")[-1] == r.split(".")[-1]:
                        # Find the android:exported element attribute
                        if receiver.getAttribute("android:exported"):
                            # Determine if the attribute is set to true
                            if receiver.getAttribute("android:exported") == "true":
                                print(self.t.yellow("\n\t--> receiver : {}".format(r)))
                                if receiver.getAttribute("android:permission"):
                                    print(self.t.red("\t\t--> permission : {}".format(receiver.getAttribute("android:permission"))))
                                    # Enumerate the intent filters for the give receiver
                                filters = self.apk.get_intent_filters("receiver", r)
                                if filters:
                                    # Enumerate the intent filter's action and category
                                    # elements
                                    for key, values in filters.items():
                                        if key == "action":
                                            for value in values:
                                                print(self.t.yellow("\t\t--> action : {}".format(value)))
                                        if key == "category":
                                            for value in values:
                                                print(self.t.yellow("\t\t--> category : {}".format(value)))
                                    print("\n")
                            elif receiver.getAttribute("android:exported") == "false":
                                continue
                        else:
                            print(self.t.yellow("\n\t--> receiver : {}".format(r)))
                            if receiver.getAttribute("android:permission"):
                                print(self.t.red("\t\t--> permission : {}".format(receiver.getAttribute("android:permission"))))
                            filters = self.apk.get_intent_filters("receiver", r)
                            if filters:
                                # Enumerate the intent filter's action and category
                                # elements
                                for key, values in filters.items():
                                    if key == "action":
                                        for value in values:
                                            print(self.t.yellow("\t\t--> action : {}".format(value)))
                                    if key == "category":
                                        for value in values:
                                            print(self.t.yellow("\t\t--> category : {}".format(value)))
                                print("\n")
            else:
                AttackSurfaceError("Receivers not loaded from XML (!)")

    def services(self):
        """
        Analyze the attack surface for services
        """
        filters = None
        # TODO Enumerate the permission attribute for the service element
        for s in self.components.services:
            if self.xml_services:
                for service in self.xml_services:
                    # Match the element name with the component name
                    if service.getAttribute("android:name") == s \
                            or service.getAttribute("android.name").split(".")[-1] == s.split(".")[-1]:
                        # Find the android:exported element attribute
                        if service.getAttribute("android:exported"):
                            # Determine if the attribute is set to true
                            if service.getAttribute("android:exported") == "true":
                                print(self.t.yellow("\n\t--> service : {}".format(s)))
                                if service.getAttribute("android:permission"):
                                    print(self.t.red("\t\t--> permission : {}".format(service.getAttribute("android:permission"))))
                                    # Enumerate the intent filters for the give receiver
                                filters = self.apk.get_intent_filters("service", s)
                                if filters:
                                    # Enumerate the intent filter's action and category
                                    # elements
                                    for key, values in filters.items():
                                        if key == "action":
                                            for value in values:
                                                print(self.t.yellow("\t\t--> action : {}".format(value)))
                                    print("\n")
                            elif service.getAttribute("android:exported") == "false":
                                continue
                        else:
                            print(self.t.yellow("\n\t--> service : {}".format(s)))
                            if service.getAttribute("android:permission"):
                                print(self.t.red("\t\t--> permission : {}".format(service.getAttribute("android:permission"))))
                            filters = self.apk.get_intent_filters("service", s)
                            if filters:
                                # Enumerate the intent filter's action and category
                                # elements
                                for key, values in filters.items():
                                    if key == "action":
                                        for value in values:
                                            print(self.t.yellow("\t\t--> action : {}".format(value)))
                                print("\n")
            else:
                AttackSurfaceError("Services not loaded from XML (!)")

    def providers(self):
        """
        Analyze the attack surface for providers
        """
        filters = None
        # TODO Enumerate the permission attribute for the provider element
        for p in self.components.providers:
            if self.xml_providers:
                for provider in self.xml_providers:
                    # Match the element name with the component name
                    if provider.getAttribute("android:name") == p \
                            or provider.getAttribute("android.name").split(".")[-1] == p.split(".")[-1]:
                        # Find the android:exported element attribute
                        if provider.getAttribute("android:exported"):
                            # Determine if the attribute is set to true
                            if provider.getAttribute("android:exported") == "true":
                                print(self.t.yellow("\n\t--> provider : {}".format(p)))
                                if provider.getAttribute("android:permission"):
                                    print(self.t.red("\t\t--> provider : {}".format(provider.getAttribute("android:permission"))))
                            elif provider.getAttribute("android:exported") == "false":
                                continue
            else:
                AttackSurfaceError("Services not loaded from XML (!)")

    def run(self):
        """
        Discover application's attack surface
        """
        if self.components.activities:
            self.activities()
        if self.components.services:
            self.services()
        if self.components.receivers:
            self.receivers()
        if self.components.providers:
            self.providers()
Exemplo n.º 17
0
class Run(Lobotomy):
    def __init__(self, ROOT_DIR):
        Lobotomy.__init__(self)
        self.ROOT_DIR = ROOT_DIR
        self.t = Terminal()
        self.logger = Logger()
        self.util = Util()
        self.apk = None
        self.package = None
        self.vm = None
        self.vmx = None
        self.gmx = None
        self.components = None
        self.dex = None
        self.strings = None
        self.permissions = None
        self.permissions_details = None
        self.files = None
        self.attack_surface = None

    def _cmd_completer(self, name, text, line, begidx, endidx):
        fn = getattr(self, 'do_'+name)
        if not hasattr(fn.im_func, "_expected_args"):
            return []
        a = [arg for arg in fn.im_func._expected_args if arg.startswith(text)]
        return a

    def find_dex(self):
        """
        Return True is classes.dex is found within the target APK.

        Args:
            None

        Returns:
            None
        """
        if self.files:
            for f in self.files:
                if "classes" in f:
                    return True
                    break

    def process_vm(self, apk=False, dex=False):
        """
        Process the application's classes.dex

        Args:
            param1 = boolean
            param2 = boolean

        Results:
            None
        """
        try:
            if apk:
                # Make sure the APK contains a classes.dex file
                if self.find_dex():
                    self.dex = self.apk.get_dex()
                    if self.dex:
                        self.logger.log("info", "Loading classes.dex ...")
                        from androguard.core.bytecodes.dvm import DalvikVMFormat
                        from androguard.core.analysis.analysis import VMAnalysis
                        from androguard.core.analysis.ganalysis import GVMAnalysis
                        # Create a DalvikVMFormat instance ...
                        # In this case self.dex will be a file type
                        self.vm = DalvikVMFormat(self.dex)
                        if self.vm:
                            print(self.t.yellow("\n\t--> Loaded classes.dex (!)\n"))
                            self.logger.log("info", "Analyzing classes.dex ...")
                            # Analyze the DalvikVMFormat instance and return
                            # analysis instances of VMAnalysis and GVMAnalysis
                            self.vmx = VMAnalysis(self.vm)
                            self.gmx = GVMAnalysis(self.vmx, None)
                            if self.vmx and self.gmx:
                                print(self.t.yellow("\n\t--> Analyzed classes.dex (!)\n"))
                                # Set the analysis properties on the
                                # DalvikVMFormat instance
                                self.vm.set_vmanalysis(self.vmx)
                                self.vm.set_gvmanalysis(self.gmx)
                                # Generate xref(s) and dref(s)
                                self.vm.create_xref()
                                self.vm.create_dref()
                                return
                            else:
                                CommandError("process_vm : Cannot analyze VM instance (!)")
                                return
                        else:
                            CommandError("process_vm : Cannot load VM instance (!)")
                            return
                    else:
                        CommandError("process_vm : classes.dex not found (!)")
                        return
            if dex:
                if self.dex:
                    from androguard.core.bytecodes.dvm import DalvikVMFormat
                    from androguard.core.analysis.analysis import VMAnalysis
                    from androguard.core.analysis.ganalysis import GVMAnalysis
                    # Analyze the DalvikVMFormat instance and return
                    # analysis instances of VMAnalysis and GVMAnalysis
                    self.vm = DalvikVMFormat(self.util.read(self.dex))
                    if self.vm:
                        print(self.t.yellow("\n\t--> Loaded {} (!)\n"
                                            .format(self.dex
                                                    .split("/")[-1])))
                        self.logger.log("info", "Analyzing {} ..."
                                        .format(self.dex
                                                .split("/")[-1]))
                        # Set the analysis properties on the
                        # DalvikVMFormat instance
                        self.vmx = VMAnalysis(self.vm)
                        self.gmx = GVMAnalysis(self.vmx, None)
                        if self.vmx and self.gmx:
                            print(self.t.yellow("\n\t--> Analyzed {} (!)\n"
                                                .format(self.dex
                                                        .split("/")[-1])))
                            # Set the analysis properties on the
                            # DalvikVMFormat instance
                            self.vm.set_vmanalysis(self.vmx)
                            self.vm.set_gvmanalysis(self.gmx)
                            # Generate xref(s) and dref(s)
                            self.vm.create_xref()
                            self.vm.create_dref()
                            return
                        else:
                            CommandError("process_vm :" +
                                         "Cannot analyze VM instance (!)")
                            return
                    else:
                        CommandError("process_vm :" +
                                     "Cannot load VM instance (!)")
                        return
                else:
                    CommandError("process_vm : classes.dex not found (!)")
                    return
        except Exception as e:
            CommandError("process_vm : {}".format(e))

    def complete_operate(self, *args):
        return self._cmd_completer("operate", *args)

    @cmd_arguments(["apk", "dex"])
    def do_operate(self, *args):
        """
        := operate apk path_to_apk
        := operate dex path_to_classes.dex
        """
        # Locals
        arg0 = args[0].split(" ")[0]
        arg1 = args[0].split(" ")[1]

        try:
            if arg0 == "apk":
                if arg1:
                    self.logger.log("info", "Loading : {} ..."
                                    .format(arg1.split("/")[-1]))
                    from androguard.core.bytecodes.apk import APK
                    self.apk = APK(arg1)
                    if self.apk:
                        print(self.t.yellow("\n\t--> Loaded : {} (!)\n"
                                            .format(arg1.split("/")[-1])))
                        self.package = self.apk.get_package()
                        from core.brains.apk.components import Components
                        # Load activies, services, broadcast receivers, and
                        # content providers
                        self.components = Components(self.apk)
                        self.components.enumerate_components()
                        self.permissions = self.apk.get_permissions()
                        self.files = self.apk.get_files()
                        self.files_type = self.apk.get_files_types()
                        # Process DVM
                        self.process_vm(apk=True)
                    else:
                        CommandError("APK not loaded (!)")
            elif arg0 == "dex":
                if arg1:
                    self.logger.log("info", "Loading : {} ..."
                                    .format(arg1.split("/")[-1]))
                    self.dex = arg1
                    self.process_vm(dex=True)
        except ImportError as e:
            CommandError("operate : {}".format(e))

    def complete_surgical(self, *args):
        return self._cmd_completer("surgical", *args)

    def do_surgical(self, *args):
        """
        := surgical
        """
        try:
            if self.vm and self.vmx:
                from .surgical import Run
                run = Run(self.vm, self.vmx)
                run.prompt = self.t.yellow("(surgical) ")
                run.ruler = self.t.yellow("-")
                run.cmdloop()
            else:
                CommandError("classes.dex not loaded (!)")
        except Exception as e:
            CommandError("surgical : {}".format(e))

    def complete_attacksurface(self, *args):
        return self._cmd_completer("attacksurface", *args)

    def do_attacksurface(self, *args):
        """
        := attacksurface
        """
        try:
            if self.apk and self.components:
                self.logger.log("info", "Loading attacksurface module ...")
                from core.brains.apk.attacksurface import AttackSurface
                self.attack_surface = AttackSurface(self.apk, self.components)
                self.attack_surface.run()
                # Helps with visual spacing after the results are printed
                print("\n")
        except ImportError as e:
            CommandError("attacksurface : {}".format(e))

    def complete_permissions(self, *args):
        return self._cmd_completer("permissions", *args)

    @cmd_arguments(["list"])
    def do_permissions(self, *args):
        """
        := permissions list
        """
        # Locals
        arg0 = args[0]

        try:
            if self.permissions:
                if args[0] == "list":
                    self.logger.log("info", "Loading permissions ... \n")
                    for p in self.permissions:
                        print(self.t.yellow("\t--> {}".format(p)))
                    print("\n")
            else:
                CommandError("Permissions not found (!)")
        except Exception as e:
            CommandError("permissions : {}".format(e))

    def complete_binja(self, *args):
        return self._cmd_completer("binja", *args)

    def do_binja(self, *args):
        """
        := binja
        """
        try:
            from .binja import Run
            run = Run(self.files, self.apk)
            run.prompt = self.t.cyan("(binja) ")
            run.ruler = self.t.cyan("-")
            run.cmdloop()
        except Exception as e:
            CommandError("binja : {}".format(e))



    def complete_files(self, *args):
        return self._cmd_completer("files", *args)

    @cmd_arguments(["all", "assets", "libs", "res"])
    def do_files(self, *args):
        """
        := files all
        := files assets
        := files libs
        := files res
        """
        # Locals
        arg0 = args[0]

        try:
            if self.files:
                if arg0 == "assets":
                    self.logger.log("info", "Loading files ... \n")
                    for f in self.files:
                        if f.startswith("assets"):
                            print(self.t.yellow("\t--> {}".format(f)))
                    print("\n")
                elif arg0 == "libs":
                    self.logger.log("info", "Loading files ... \n")
                    for f in self.files:
                        if f.startswith("lib"):
                            print(self.t.yellow("\t--> {}".format(f)))
                    print("\n")
                elif arg0 == "res":
                    self.logger.log("info", "Loading files ... \n")
                    for f in self.files:
                        if f.startswith("res"):
                            print(self.t.yellow("\t--> {}".format(f)))
                    print("\n")
                elif arg0 == "all":
                    self.logger.log("info", "Loading files ... \n")
                    for f in self.files:
                        print(self.t.yellow("\t--> {}".format(f)))
                    print("\n")
            else:
                CommandError("Files not populated (!)")
        except Exception as e:
            CommandError("files : {}".format(e))

    def complete_strings(self, *args):
        return self._cmd_completer("strings", *args)

    @cmd_arguments(["list", "search"])
    def do_strings(self, *args):
        """
        List and search for strings found in classes.dex

        := strings list
        := strings search
        """
        # Locals
        arg0 = args[0]
        strings = None

        try:
            if arg0 == "list":
                if self.vm:
                    strings = self.vm.get_strings()
                    if strings:
                        for s in strings:
                            print(self.t.cyan("--> {}".format(s.encode("utf-8", errors="ignore"))))
                    else:
                        CommandError("Strings not found (!)")
                else:
                    CommandError("classes.dex not loaded (!)")
            elif arg0 == "search":
                if self.vm:
                    strings = self.vm.get_strings()
                    if strings:
                        target = raw_input(self.t.yellow("\n\t--> Enter string : "))
                        for s in strings:
                            if target in s:
                                print(self.t.cyan("\t\t --> {}".format(s.encode("utf-8", errors="ignore"))))
                        print("\n")
                    else:
                        CommandError("Strings not found (!)")
                else:
                    CommandError("classes.dex not loaded (!)")
        except Exception as e:
            CommandError("strings : {}".format(e))

    def complete_components(self, *args):
        return self._cmd_completer("components", *args)

    @cmd_arguments(["list"])
    def do_components(self, *args):
        """
        := components list
        """
        # Locals
        arg0 = args[0]

        try:
            if arg0 == "list":
                if self.apk:
                    self.logger.log("info", "Enumerating components ...\n")
                    if self.components.activities:
                        for a in self.components.activities:
                            print(self.t.yellow("\t--> activity : {}"
                                                .format(a)))
                        print("\n")
                    if self.components.services:
                        for s in self.components.services:
                            print(self.t.yellow("\t--> service : {}"
                                                .format(s)))
                        print("\n")
                    if self.components.receivers:
                        for r in self.components.receivers:
                            print(self.t.yellow("\t--> receiver : {}"
                                                .format(r)))
                        print("\n")
                    if self.components.providers:
                        for r in self.components.providers:
                            print(self.t.yellow("\t--> provider : {}"
                                                .format(s)))
                        print("\n")
                else:
                    CommandError("APK not loaded (!)")
        except Exception as e:
            CommandError("components : {}".format(e))

    def complete_interact(self, *args):
        return self._cmd_completer("interact", *args)

    def do_interact(self, *args):
        """
        Drop into an interactive IPython session.

        := interact
        """
        try:
            if self.vm and self.vmx:
                from core.brains.interact.interact import Interact
                i = Interact(self.vm, self.vmx)
                i.run()
            else:
                CommandError("classes.dex not loaded (!)")
        except Exception as e:
            CommandError("interact : {}".format(e.message))

    def complete_class_tree(self, *args):
        return self._cmd_completer("class_tree", *args)

    def do_class_tree(self, *args):
        """
        := class_tree
        """
        try:
            if self.vm:
                for c in self.vm.get_classes():
                    # We don't care about Android support classes or resource
                    # classes
                    if c.name.startswith("Landroid") or \
                            c.name.split("/")[-1].startswith("R"):
                        continue
                    print("\n")
                    print(self.t.yellow("\t--> class : {} {}".format(c.get_access_flags_string(), c.name)))
                    for f in c.get_fields():
                        print(self.t.white("\t\t--> field : {} {} {}".format(f.get_access_flags_string(), f.get_descriptor(), f.name)))
                    for m in c.get_methods():
                        print(self.t.cyan("\t\t\t--> method : {} {} {}".format(m.get_access_flags_string(), m.name, m.get_descriptor())))
                print("\n")
            else:
                CommandError("class_tree : classes.dex not loaded (!)")
        except Exception as e:
            CommandError("class_tree : {}".format(e))

    def complete_native(self, *args):
        return self._cmd_completer("native", *args)

    def do_native(self, *args):
        """
        := native
        """
        # Locals
        native_methods = list()

        try:
            if self.vm:
                for method in self.vm.get_methods():
                    if method.get_access_flags() & 0x100:
                        native_methods.append((method.get_class_name(),
                                               method.get_name()))
                if native_methods:
                    print("\n")
                    for n in native_methods:
                        print(self.t.cyan("\t--> {} : {}".format(n[0], n[1])))
                    print("\n")
            else:
                self.logger.log("info",
                                "class_tree : classes.dex not loaded (!)")
        except Exception as e:
            CommandError("native : {}".format(e))

    def complete_ui(self, *args):
        return self._cmd_completer("ui", *args)

    def do_ui(self, *args):
        """
        := ui
        """
        try:
            if self.vm and self.vmx:
                from core.brains.ui.terminal import TerminalApp
                ui = TerminalApp(self.vm, self.vmx)
                ui.run()
        except Exception as e:
            CommandError("ui : {}".format(e))

    def complete_macro(self, *args):
        return self._cmd_completer("macro", *args)

    def do_macro(self, args):
        """
        := macro
        """
        # Locals
        directory_items = None
        macro = path.join(self.ROOT_DIR, "macro")
        selection = None
        apk_path = None
        json = None

        try:
            print("\n")
            directory_items = listdir(macro)
            for i, item in enumerate(directory_items):
                print(self.t.cyan("\t--> [{}] {}"
                                  .format(i, item)))
            print("\n")
            selection = raw_input(self.t.yellow("[{}] Select config : ".format(datetime.now())))
            try:
                index = int(selection)
            except ValueError:
                index = -1
            print("\n")
            if selection:
                for i, item in enumerate(directory_items):
                    if selection == item or i == index:
                        selection = item
                        break
                with open("".join([macro, "/", selection]), "rb") as config:
                    # Load the config as JSON
                    json = loads(config.read())
                    if json:
                        for k, v in json.items():
                            if k == "apk":
                                if v:
                                    apk_path = str(v)
                                    # Call operate() with the path to apk
                                    self.do_operate("apk {}"
                                                    .format(apk_path))
                                    return
                                else:
                                    CommandError("macro : Path to APK not found in {}"
                                                 .format(selection))
                            else:
                                CommandError("macro : Error loading {} as JSON"
                                             .format(selection))
        except Exception as e:
            CommandError("macro : {}".format(e))
Exemplo n.º 18
0
from itunes.itunes_db import itunes_db
from organiser.itunes_cleaner import itunes_clean, clean_composer, clean_rating, clean_release_date
from organiser.itunes_bpm_detector import it_detect_bpm
from organiser.itunes_trimmer import it_trim_end
from organiser.tm_librosa import track_beats
from organiser.track_review import review_tracks

TERM = Terminal()

log_format = '[%(asctime)s] %(levelname)s - %(message)s'


@click.group()
@click.option('--itunes_file', '-i',
              help=TERM.cyan('iTunes library file'),
              default=os.environ.get("TM_ITUNES_LIBRARY"))
@click.option('--pandas_file', '-d',
              help=TERM.cyan('Where to pickle (save) the pandas based database'),
              default=os.environ.get("TM_PANDAS_LIBRARY"))
@click.option('--verbose/--quiet', '-v/-q', default=False)
@click.pass_context
def cli(ctx, itunes_file, pandas_file, verbose):

    if verbose:
        logging.basicConfig(level=logging.DEBUG,
                            format=log_format)
    else:
        logging.basicConfig(level=logging.INFO,
                            format=log_format)
    log = logging.getLogger(__name__)
Exemplo n.º 19
0
from nephos.helpers.k8s import ns_create
from nephos.fabric.settings import load_config
from nephos.fabric.ca import setup_ca
from nephos.fabric.crypto import admin_msp, genesis_block, channel_tx, setup_nodes
from nephos.fabric.ord import setup_ord
from nephos.fabric.peer import setup_peer, setup_channel
from nephos.composer.install import deploy_composer, install_network, setup_admin


TERM = Terminal()


@click.group(help=TERM.green('Nephos helps you install Hyperledger Fabric on Kubernetes'))
@click.option('--settings_file', '-f', required=True,
              help=TERM.cyan('YAML file containing HLF options'))
@click.option('--upgrade', '-u', is_flag=True, default=False,
              help=TERM.cyan('Do we wish to upgrade already installed components?'))
@click.option('--verbose/--quiet', '-v/-q', default=False,
              help=TERM.cyan('Do we want verbose output?'))
@click.pass_context
def cli(ctx, settings_file, upgrade, verbose):
    ctx.obj['settings_file'] = settings_file
    ctx.obj['upgrade'] = upgrade
    ctx.obj['verbose'] = verbose


@cli.command(help=TERM.cyan('Install Hyperledger Fabric Certificate Authorities'))
@click.pass_context
def ca(ctx):  # pragma: no cover
    opts = load_config(ctx.obj['settings_file'])