예제 #1
0
파일: cli.py 프로젝트: bfellman/cortex
def get_result(host, port, user_id, snapshot_id, result_name):
    """get detailed result, from the available results presented by get-snapshot"""
    req_url = f"http://{host}:{port}/users/{user_id}/snapshots/{snapshot_id}/{result_name}"
    resp = get_from_server(req_url)
    if resp:
        for k, v in resp.items():
            if isinstance(v, str) and hyperlink.parse(v).scheme == "http":
                resp[k] = hyperlink.parse(v).to_text()
        print(f"# {result_name} for {user_id=} {snapshot_id=}:")
        print(tabulate([resp], headers="keys"))
예제 #2
0
    def process_scandetail(self, scan, test, dupes):
        for item in scan.findall('item'):
            # Title
            titleText = None
            description = item.findtext("description")
            # Cut the title down to the first sentence
            sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s',
                                 description)
            if len(sentences) > 0:
                titleText = sentences[0][:900]
            else:
                titleText = description[:900]

            # Description
            description = "\n".join([
                f"**Host:** `{item.findtext('iplink')}`",
                f"**Description:** `{item.findtext('description')}`",
                f"**HTTP Method:** `{item.attrib.get('method')}`",
            ])

            # Manage severity the same way with JSON
            severity = "Info"  # Nikto doesn't assign severity, default to Info
            if item.get('osvdbid') is not None and "0" != item.get('osvdbid'):
                severity = "Medium"

            finding = Finding(
                title=titleText,
                test=test,
                description=description,
                severity=severity,
                dynamic_finding=True,
                static_finding=False,
                vuln_id_from_tool=item.attrib.get('id'),
                nb_occurences=1,
            )

            # endpoint
            try:
                ip = item.findtext("iplink")
                url = hyperlink.parse(ip)
                endpoint = Endpoint(
                    protocol=url.scheme,
                    host=url.host,
                    port=url.port,
                    path="/".join(url.path),
                )
                finding.unsaved_endpoints = [endpoint]
            except ValueError as exce:
                logger.warn("Invalid iplink in the report")

            dupe_key = hashlib.sha256(description.encode("utf-8")).hexdigest()

            if dupe_key in dupes:
                find = dupes[dupe_key]
                find.description += "\n-----\n" + finding.description
                find.unsaved_endpoints.extend(finding.unsaved_endpoints)
                find.nb_occurences += 1

            else:
                dupes[dupe_key] = finding
예제 #3
0
def admin_action(request, model_name, fields):
    action = request.POST["action"]
    field = request.POST["field"]

    assert field in fields
    if field not in fields.split(","):
        return  # pragma: no cover

    params = hyperlink.parse(request.get_full_path()).query
    query = Query.from_request(model_name, field, params)

    orm_models = get_models(request)
    if query.model_name not in orm_models:
        raise http.Http404(
            f"{query.model_name} does not exist")  # pragma: no cover

    bound_query = BoundQuery.bind(query, orm_models)

    results = get_results(request, bound_query, orm_models, False)

    pks = {row.get(field)
           for row in results["rows"]
           } | {col.get(field)
                for col in results["cols"]}
    pks -= {None}

    model_name = bound_query.fields[0].orm_bound_field.field.model_name
    return orm_models[model_name].do_action(request, action, pks)
예제 #4
0
def admin_action(request, model_name, fields):
    data = json.loads(request.body)
    action = data["action"]
    field = data["field"]

    if field not in fields:
        raise http.Http404(f"bad field '{field}'")  # pragma: no cover

    params = hyperlink.parse(request.get_full_path()).query
    query = Query.from_request(model_name, field, params)

    orm_models = get_models(request)
    if query.model_name not in orm_models:
        raise http.Http404(
            f"'{query.model_name}' does not exist")  # pragma: no cover

    bound_query = BoundQuery.bind(query, orm_models)

    results = get_results(request, bound_query, orm_models, False)

    pks = {row.get(field)
           for row in results["rows"]
           } | {col.get(field)
                for col in results["cols"]}
    pks -= {None}

    model_name = bound_query.fields[0].orm_bound_field.field.model_name
    return orm_models[model_name].get_action_request(request, action, pks)
예제 #5
0
def admin_action(request, model_name, fields):
    data = json.loads(request.body)
    action = data["action"]
    field = data["field"]

    if field not in fields:
        raise http.Http404(f"bad field '{field}'")  # pragma: no cover

    params = hyperlink.parse(request.get_full_path()).query
    query = Query.from_request(model_name, field, params)

    orm_models = get_models(request)
    if query.model_name not in orm_models:
        raise http.Http404(
            f"'{query.model_name}' does not exist")  # pragma: no cover

    bound_query = BoundQuery.bind(query, orm_models)
    bound_field = bound_query.fields[0].orm_bound_field

    if not bound_field.field.actions or action not in bound_field.field.actions:
        raise http.Http404(f"bad action '{action}'")  # pragma: no cover

    results = get_result_list(request, bound_query)

    pks = {row[bound_field.queryset_path_str] for row in results}
    pks -= {None}

    model_name = bound_field.field.model_name
    return orm_models[model_name].get_http_request_for_action(
        request, action, pks)
예제 #6
0
    def __init__(self, item_node):
        self.node = item_node

        self.id = self.get_text_from_subnode('pluginid')
        self.name = self.get_text_from_subnode('alert')

        self.severity = self.get_text_from_subnode('riskcode')
        self.riskdesc = self.get_text_from_subnode('riskdesc')
        self.desc = self.get_text_from_subnode('desc')
        self.resolution = self.get_text_from_subnode(
            'solution') if self.get_text_from_subnode('solution') else ""
        self.desc += "\n\nReference: " + self.get_text_from_subnode(
            'reference') if self.get_text_from_subnode('reference') else ""
        self.ref = []
        if self.get_text_from_subnode('cweid'):
            self.ref.append("CWE-" + self.get_text_from_subnode('cweid'))
            self.cwe = self.get_text_from_subnode('cweid')
        else:
            self.cwe = 0

        description_detail = "\n"
        for instance in item_node.findall('instances/instance'):
            for node in instance.iter():
                if node.tag == "uri":
                    if node.text != "":
                        description_detail += "URL: " + node.text
                if node.tag == "method":
                    if node.text != "":
                        description_detail += "Method: " + node.text
                if node.tag == "param":
                    if node.text != "":
                        description_detail += "Parameter: " + node.text
                if node.tag == "evidence":
                    if node.text != "":
                        description_detail += "Evidence: " + escape(node.text)
                description_detail += "\n"

        self.desc += description_detail

        if self.get_text_from_subnode('wascid'):
            self.ref.append("WASC-" + self.get_text_from_subnode('wascid'))

        self.items = []

        for instance in item_node.findall('instances/instance'):
            n = instance.findtext("uri")
            n2 = instance.findtext("param")
            url = hyperlink.parse(n)
            item = {
                'uri': n,
                'param': n2 if n2 else "",
                'host': url.host,
                'protocol': url.scheme,
                'port': url.port
            }
            self.items.append(item)

        self.requests = "\n".join([i['uri'] for i in self.items])
예제 #7
0
    def process_scandetail(self, scan, test, dupes):
        for item in scan.findall('item'):
            # Title
            titleText = None
            description = item.find("description").text
            # Cut the title down to the first sentence
            sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s',
                                 description)
            if len(sentences) > 0:
                titleText = sentences[0][:900]
            else:
                titleText = description[:900]

            # Url
            ip = item.find("iplink").text
            # Remove the port numbers for 80/443
            ip = ip.replace(r":['80']{2}\/?$", "")
            ip = ip.replace(r":['443']{3}\/?$", "")

            # Severity
            severity = "Info"  # Nikto doesn't assign severity, default to Info

            # Description
            description = "\n".join([
                f"**Host:** `{ip}`",
                f"**Description:** `{item.find('description').text}`",
                f"**HTTP Method:** `{item.attrib['method']}`",
            ])

            url = hyperlink.parse(ip)
            endpoint = Endpoint(
                protocol=url.scheme,
                host=url.host,
                port=url.port,
                path="/".join(url.path),
            )

            dupe_key = hashlib.sha256(description.encode("utf-8")).hexdigest()

            if dupe_key in dupes:
                finding = dupes[dupe_key]
                if finding.description:
                    finding.description = finding.description + "\nHost:" + ip + "\n" + description
                finding.unsaved_endpoints.append(endpoint)
                finding.nb_occurences += 1

            else:
                finding = Finding(
                    title=titleText,
                    test=test,
                    description=description,
                    severity=severity,
                    dynamic_finding=True,
                    nb_occurences=1,
                )
                finding.unsaved_endpoints = [endpoint]

                dupes[dupe_key] = finding
예제 #8
0
    def test_parse(self):
        # type: () -> None
        purl = parse(TOTAL_URL)
        assert isinstance(purl, DecodedURL)
        assert purl.user == 'user'
        assert purl.get('zot') == ['23%']
        assert purl.fragment == 'frég'

        purl2 = parse(TOTAL_URL, decoded=False)
        assert isinstance(purl2, EncodedURL)
        assert purl2.get('zot') == ['23%25']

        with self.assertRaises(UnicodeDecodeError):
            purl3 = parse(UNDECODABLE_FRAG_URL)

        purl3 = parse(UNDECODABLE_FRAG_URL, lazy=True)

        with self.assertRaises(UnicodeDecodeError):
            purl3.fragment
예제 #9
0
    def test_parse(self):
        # type: () -> None
        purl = parse(TOTAL_URL)
        assert isinstance(purl, DecodedURL)
        assert purl.user == "user"
        assert purl.get("zot") == ["23%"]
        assert purl.fragment == "frég"

        purl2 = parse(TOTAL_URL, decoded=False)
        assert isinstance(purl2, EncodedURL)
        assert purl2.get("zot") == ["23%25"]

        with self.assertRaises(UnicodeDecodeError):
            purl3 = parse(UNDECODABLE_FRAG_URL)

        purl3 = parse(UNDECODABLE_FRAG_URL, lazy=True)

        with self.assertRaises(UnicodeDecodeError):
            purl3.fragment
예제 #10
0
def query(request, *, model_name, fields="", media):
    _add_request_info(request)

    params = hyperlink.parse(request.get_full_path()).query

    if media.startswith("profile") or media.startswith("pstats"):
        if "_" in media:
            prof_media, media = media.split("_")
        else:
            prof_media = media
            media = "json"

        profiler = cProfile.Profile()
        try:
            profiler.enable()

            query = Query.from_request(model_name, fields, params)
            for x in _data_response(request, query, media, privileged=True):
                pass

            profiler.disable()

            if prof_media == "profile":
                buffer = io.StringIO()
                stats = pstats.Stats(profiler, stream=buffer)
                stats.sort_stats("cumulative").print_stats(50)
                stats.sort_stats("time").print_stats(50)
                buffer.seek(0)
                return HttpResponse(buffer, content_type="text/plain")
            elif prof_media == "pstats":
                buffer = io.BytesIO()
                marshal.dump(pstats.Stats(profiler).stats, buffer)
                buffer.seek(0)
                response = HttpResponse(
                    buffer, content_type="application/octet-stream")
                response["Content-Disposition"] = (
                    "attachment;"
                    f" filename={query.model_name}-{timezone.now().isoformat()}.pstats"
                )
                return response
            else:
                raise http.Http404(f"Bad file format {prof_media} requested")
        finally:
            if profiler:  # pragma: no branch
                profiler.disable()
    else:
        query = Query.from_request(model_name, fields, params)
        return _data_response(request, query, media, privileged=True)
예제 #11
0
    def _create_client_service(self, nodeurl, api_token):
        url = parse(nodeurl)
        wsurl = url.replace(scheme="ws").child("private", "logs", "v1")

        factory = WebSocketClientFactory(
            url=wsurl.to_uri().to_text(),
            headers={
                "Authorization": "{} {}".format("tahoe-lafs", api_token),
            },
        )
        factory.protocol = TahoeLogReader
        factory.streamedlogs = self

        endpoint = TCP4ClientEndpoint(self._reactor, url.host, url.port)
        client_service = ClientService(endpoint, factory, clock=self._reactor)
        return client_service
예제 #12
0
    def get_findings(self, filename, test):

        data = json.load(filename)

        dupes = {}
        for item in data:
            url = hyperlink.parse(item["url"])
            payload = item["payload"]
            return_code = str(item["code"])
            severity = self.SEVERITY[return_code]
            description = f"The URL {url.to_text()} must not be exposed\n Please review your configuration\n"

            dupe_key = hashlib.sha256(
                (url.to_text() + return_code).encode("utf-8")).hexdigest()

            if dupe_key in dupes:
                finding = dupes[dupe_key]
                finding.nb_occurences += 1
            else:
                finding = Finding(
                    title=f"Found {url.to_text()}",
                    test=test,
                    severity=severity,
                    numerical_severity=Finding.get_numerical_severity(
                        severity),
                    description=description,
                    mitigation="N/A",
                    static_finding=False,
                    dynamic_finding=True,
                    cwe=200,
                    nb_occurences=1,
                )
                finding.unsaved_endpoints = [
                    Endpoint(
                        path="/".join(url.path),
                        host=url.host,
                        protocol=url.scheme,
                        port=url.port,
                    )
                ]
                finding.unsaved_req_resp = [{
                    "req": item["payload"],
                    "resp": str(item["code"])
                }]
                dupes[dupe_key] = finding
        return list(dupes.values())
예제 #13
0
    def send_mail(self,
                  subject_template_name,
                  email_template_name,
                  context,
                  from_email,
                  to_email,
                  html_email_template_name=None):

        from_email = get_system_setting('email_from')

        url = hyperlink.parse(settings.SITE_URL)
        context['site_name'] = url.host
        context['protocol'] = url.scheme
        context['domain'] = settings.SITE_URL[len(url.scheme + '://'):]

        super().send_mail(subject_template_name, email_template_name, context,
                          from_email, to_email, html_email_template_name)
예제 #14
0
def get_reader_url(url: str) -> str:
    """ This converst the document URL and converts to url that 
    provide all the reader data """
    link = hyperlink.parse(url)

    reader_path = []
    for p in link.path:
        if p != 'docs':
            reader_path.append(p)
    reader_path.append('reader3_4.json')
    reader_link = link.replace(
        host="reader3.isu.pub",
        path=reader_path,
        query=[],
    )

    log('URL with no GET Query Params: {u}'.format(u=reader_link))
    return str(reader_link)
예제 #15
0
파일: _dihttp.py 프로젝트: dimabe/klein
def urlFromRequest(request):
    # type: (IRequest) -> DecodedURL
    sentHeader = request.getHeader(b"host")
    if sentHeader is not None:
        sentHeader = sentHeader.decode("charmap")
        if ":" in sentHeader:
            host, port = sentHeader.split(":")
            port = int(port)
        else:
            host = sentHeader
            port = None
    else:
        host = request.client.host
        port = request.client.port
        if not isinstance(host, text_type):
            host = host.decode("ascii")

    return parse(request.uri.decode("charmap")).replace(
        scheme=u"https" if request.isSecure() else u"http",
        host=host,
        port=port,
    )
예제 #16
0
    def get_findings(self, xml_output, test):
        root = parse(xml_output).getroot()

        dupes = dict()
        for scan in root.findall("Scan"):
            start_url = scan.findtext("StartURL")
            if ":" not in start_url:
                start_url = "//" + start_url
            # get report date
            if scan.findtext("StartTime") and "" != scan.findtext("StartTime"):
                report_date = dateutil.parser.parse(
                    scan.findtext("StartTime")).date()

            for item in scan.findall("ReportItems/ReportItem"):

                finding = Finding(
                    test=test,
                    title=item.findtext("Name"),
                    severity=self.get_severity(item.findtext("Severity")),
                    description=html2text.html2text(
                        item.findtext("Description")).strip(),
                    false_p=self.get_false_positive(
                        item.findtext("IsFalsePositive")),
                    static_finding=True,
                    dynamic_finding=False,
                    nb_occurences=1,
                )

                if item.findtext("Impact") and "" != item.findtext("Impact"):
                    finding.impact = item.findtext("Impact")

                if item.findtext("Recommendation"
                                 ) and "" != item.findtext("Recommendation"):
                    finding.mitigation = item.findtext("Recommendation")

                if report_date:
                    finding.date = report_date

                if item.findtext("CWEList/CWE"):
                    finding.cwe = self.get_cwe_number(
                        item.findtext("CWEList/CWE"))

                references = []
                for reference in item.findall("References/Reference"):
                    url = reference.findtext("URL")
                    db = reference.findtext("Database") or url
                    references.append(" * [{}]({})".format(db, url))
                if len(references) > 0:
                    finding.references = "\n".join(references)

                if item.findtext("CVSS3/Descriptor"):
                    finding.cvssv3 = item.findtext("CVSS3/Descriptor")

                # more description are in "Details"
                if item.findtext("Details") and len(
                        item.findtext("Details").strip()) > 0:
                    finding.description += "\n\n**Details:**\n{}".format(
                        html2text.html2text(item.findtext("Details")))
                if item.findtext("TechnicalDetails") and len(
                        item.findtext("TechnicalDetails").strip()) > 0:
                    finding.description += "\n\n**TechnicalDetails:**\n\n{}".format(
                        item.findtext("TechnicalDetails"))

                # add requests
                finding.unsaved_req_resp = list()
                if len(item.findall("TechnicalDetails/Request")):
                    finding.dynamic_finding = True  # if there is some requests it's dynamic
                    finding.static_finding = False  # if there is some requests it's dynamic
                    for request in item.findall("TechnicalDetails/Request"):
                        finding.unsaved_req_resp.append({
                            "req": (request.text or ""),
                            "resp":
                            ""
                        })

                # manage the endpoint
                url = hyperlink.parse(start_url)
                endpoint = Endpoint(
                    host=url.host,
                    port=url.port,
                    path=item.findtext("Affects"),
                )
                if url.scheme is not None and "" != url.scheme:
                    endpoint.protocol = url.scheme
                finding.unsaved_endpoints = [endpoint]

                dupe_key = hashlib.sha256("|".join([
                    finding.title,
                    str(finding.impact),
                    str(finding.mitigation),
                ]).encode("utf-8")).hexdigest()

                if dupe_key in dupes:
                    find = dupes[dupe_key]
                    # add details for the duplicate finding
                    if item.findtext("Details") and len(
                            item.findtext("Details").strip()) > 0:
                        find.description += "\n-----\n\n**Details:**\n{}".format(
                            html2text.html2text(item.findtext("Details")))
                    find.unsaved_endpoints.extend(finding.unsaved_endpoints)
                    find.unsaved_req_resp.extend(finding.unsaved_req_resp)
                    find.nb_occurences += finding.nb_occurences
                    logger.debug(
                        "Duplicate finding : {defectdojo_title}".format(
                            defectdojo_title=finding.title))
                else:
                    dupes[dupe_key] = finding

        return list(dupes.values())
예제 #17
0
import attr
import treq

from txacme.interfaces import IResponder
from txacme.challenges._libcloud import _validation
from zope.interface import implementer
from twisted.internet.defer import inlineCallbacks
from twisted.internet.task import deferLater

from hyperlink import parse

base = parse("https://api.cloudflare.com/client/v4/")


def global_reactor():
    from twisted.internet import reactor
    return reactor


@attr.s(hash=False)
@implementer(IResponder)
class CloudflareV4Responder(object):
    """
    Cloudflare API V4 responder.
    """
    _email = attr.ib()
    _api_key = attr.ib()
    _zone_name = attr.ib()
    _settle_delay = attr.ib(default=60.0)
    _reactor = attr.ib(default=attr.Factory(global_reactor))
예제 #18
0
async def on_message(message):
    if message.author == client.user:
        return

    elif message.content == bot_tag:
        return

    elif message.content == bot_tag + " help" or message.content == bot_tag + " h":
        embed = discord.Embed(
            title = "UniteBot Helper",
            description = """\
            Ask me to convert stuff like this: ```!u [value] [unit1] to [unit2] (rounder)```The rounder is optional, and defaults to 2 decimal places.
            Example Input: ```!u 10 m to cm```Output: ```1000.0 centimeter```
            """,
            color = pink
        )
        embed.add_field(name="Unit Type", value="""\
        Time Zone
        Angle
        Length/Distance
        Mass/Weight
        Time
        Temperature
        Area
        Volume
        Velocity
        Acceleration
        Energy
        Density
        ...and more!""", inline=True)
        embed.add_field(name="Help Command", value="""\
        `!u h(elp) timezone`
        `!u h(elp) angle`
        `!u h(elp) length/distance`
        `!u h(elp) mass/weight`
        `!u h(elp) time`
        `!u h(elp) temperature`
        `...you get the idea.`""", inline=True)

        embed.add_field(name="Sources", value="`!u sources`", inline=False)

        await message.channel.send(embed=embed)
    elif message.content == bot_tag + " help timezone" or message.content == bot_tag + " h timezone":
        embed = discord.Embed(
            title = "UniteBot Helper",
            description = """\
            I can convert times to different time zones!
            Example Input: ```!u 10:30 am est to pst```Output: ```7:30 AM```
            If you don't include AM/PM, I will use 24 hour time. There are some time zones that share abbreviations. Below are all of them listed, along with how to use them with me.""",
            color = pink
        )
        embed.add_field(name="Time Zone Name", value="""\
            Arabia Daylight Time (ADT)
            Atlantic Daylight TIme (ADT)
            Amazon Summer Time (AMST)
            Armenia Summer Time (AMST)
            Amazon Time (AMT)
            Armenia Time (AMT)
            Arabia Standard Time (AST)
            Atlantic Standard Time (AST)
            Bangladesh Standard Time (BST)
            Bougainville Standard Time (BST)
            British Summer Time (BST)
            Central Daylight Time (CDT)
            Cuba Daylight Time (CDT)
            Central Standard Time (CST)
            China Standard Time (CST)
            Cuba Standard Time (CST)
            Gulf Standard Time (GST)
            South Georgia Time (GST)
            India Standard Time (IST)
            Irish Standard Time (IST)
            Israel Standard Time (IST)
            Paraguay Time (PYT)
            Pyongyang Time (PYT)
            West Samoa Time (WST)
            Western Sahara Summer Time (WST)
            """, inline=True)
        embed.add_field(name="Abbreviation", value="""\
            ADT-UTC+4
            ADT-UTC-3
            AMST-UTC-3
            AMST-UTC+5
            AMT-UTC-4
            AMT-UTC+4
            AST-UTC+3
            AST-UTC-4
            BST-UTC+6
            BST-UTC+11
            BST-UTC+1
            CDT-UTC-5
            CDT-UTC-4
            CST-UTC-6
            CST-UTC+8
            CST-UTC-5
            GST-UTC+4
            GST-UTC-2
            IST-UTC+5:30
            IST-UTC+1
            IST-UTC+2
            PYT-UTC-4
            PYT-UTC+8:30
            WST-UTC+14
            WST-UTC+1
            """, inline=True)
            
        await message.channel.send(embed=embed)
    elif message.content == bot_tag + " help angle" or message.content == bot_tag + " h angle":
        embed = discord.Embed(
            title = "UniteBot Helper",
            description = """\
            I can convert angle measurements! 
            Example Input: ```!u pi radians to degrees```Output: ```180.0 degree```""",
            color = pink
        )
        await message.channel.send(embed=embed)
    elif message.content == bot_tag + " help length" or message.content == bot_tag + " h length" or message.content == bot_tag + " help distance" or message.content == bot_tag + " h distance":
        embed = discord.Embed(
            title = "UniteBot Helper",
            description = """\
            I can convert length/distance measurements! 
            Example Input: ```!u 12 m to in 3```Output: ```472.441 inch```""",
            color = pink
        )
        await message.channel.send(embed=embed)
    elif message.content == bot_tag + " help mass" or message.content == bot_tag + " h mass" or message.content == bot_tag + " help weight" or message.content == bot_tag + " h weight":
        embed = discord.Embed(
            title = "UniteBot Helper",
            description = """\
            I can convert mass/weight measurements! 
            Example Input: ```!u 52 tons to kg 5```Output: ```47173.60648 kilogram```""",
            color = pink
        )
        await message.channel.send(embed=embed)
    elif message.content == bot_tag + " help time" or message.content == bot_tag + " h time":
        embed = discord.Embed(
            title = "UniteBot Helper",
            description = """\
            I can convert time measurements! 
            Example Input: ```!u 1 minute to attoseconds```Output: ```5.999999999999999×10¹⁹ attosecond```""",
            color = pink
        )
        await message.channel.send(embed=embed)
    elif message.content == bot_tag + " help temperature" or message.content == bot_tag + " h temperature":
        embed = discord.Embed(
            title = "UniteBot Helper",
            description = """\
            I can convert temperature measurements! 
            Example Input: ```!u 32 degF to degC```Output: ```0.0 °C```""",
            color = pink
        )
        await message.channel.send(embed=embed)
    elif message.content == bot_tag + " help area" or message.content == bot_tag + " h area":
        embed = discord.Embed(
            title = "UniteBot Helper",
            description = """\
            I can convert area measurements! 
            Example Input: ```!u 14 square meters to square feet```Output: ```150.69 foot²```""",
            color = pink
        )
        await message.channel.send(embed=embed)
    elif message.content == bot_tag + " help volume" or message.content == bot_tag + " h volume":
        embed = discord.Embed(
            title = "UniteBot Helper",
            description = """\
            I can convert volume measurements! 
            Example Input: ```!u 10 gallons to pints```Output: ```80.0 pint```""",
            color = pink
        )
        await message.channel.send(embed=embed)
    elif message.content == bot_tag + " help velocity" or message.content == bot_tag + " h velocity":
        embed = discord.Embed(
            title = "UniteBot Helper",
            description = """\
            I can convert velocity measurements! 
            Example Input: ```!u 120 km/hr to miles/hr 7```Output: ```74.5645431 mile/hour```""",
            color = pink
        )
        await message.channel.send(embed=embed)
    elif message.content == bot_tag + " help acceleration" or message.content == bot_tag + " h acceleration":
        embed = discord.Embed(
            title = "UniteBot Helper",
            description = """\
            I can convert acceleration measurements! 
            Example Input: ```!u 120 km/hr squared to miles/hr squared 7```Output: ```74.5645431 mile/hour²```""",
            color = pink
        )
        await message.channel.send(embed=embed)
    elif message.content == bot_tag + " help energy" or message.content == bot_tag + " h energy":
        embed = discord.Embed(
            title = "UniteBot Helper",
            description = """\
            I can convert energy measurements! 
            Example Input: ```!u 2100 kcal to joules```Output: ```8786400.0 joule```""",
            color = pink
        )
        await message.channel.send(embed=embed)
    elif message.content == bot_tag + " help density" or message.content == bot_tag + " h density":
        embed = discord.Embed(
            title = "UniteBot Helper",
            description = """\
            I can convert density measurements! 
            Example Input: ```!u g/cm**3 to kg/m**3```Output: ```1000.0 kilogram/meter³```""",
            color = pink
        )
        await message.channel.send(embed=embed)
    elif message.content == bot_tag + " sources":
        embed = discord.Embed(
            title = "UniteBot Helper",
            description = "I primarily use the Pint Python unit conversion library to help you convert units. Links to this and more can be found below.",
            color = pink
        )
        embed.add_field(name = "Logo Artist: algooddevils", value = hyperlink.parse("https://twitter.com/algooddevils"), inline=False)
        embed.add_field(name = "Pint", value = hyperlink.parse("https://pint.readthedocs.io/en/0.11/"), inline=False)
        embed.add_field(name = "Time Zone Data", value = hyperlink.parse("https://www.timeanddate.com/time/zones/"), inline=False)
        await message.channel.send(embed=embed)

    elif message.content.startswith(bot_tag):

        output = unite.convertInput(message.content)

        #check if time zone conversion
        try:
            if ':' in output:
                await message.channel.send(output)
        except:
            print("Not a time zone conversion.")
        #need abbreviated format for temperatures
        if output.dimensionality == "[temperature]":
            await message.channel.send("{:~P}".format(output))

        else:
            await message.channel.send("{:P}".format(output))
예제 #19
0
파일: models.py 프로젝트: BigCet/Teszt2
    def get_query(self):
        from .query import Query

        params = hyperlink.parse(f"?{self.query}").query
        return Query.from_request(self.model_name, self.fields, params)
예제 #20
0
import sys
import pygame
import random
import time
import pygame.draw
import hyperlink
import tkinter as tk

url = hyperlink.parse(
    u"https://en.wikipedia.org/wiki/Conway's_Game_of_Life#Rules")
size = width, height = 500, 600
#Cell is 20x20 giving a 25x25 grid
dead_color = 0, 0, 0  #black
alive_color = 255, 255, 255  #white
dark_gray = 50, 50, 50
gray = 127, 127, 127
blue = 0, 0, 255
navy_blue = 0, 0, 100


class Game:
    def __init__(self):
        self.count = 0
        self.pause = False
        self.start = False
        self.speed = 0.5
        pygame.init()
        pygame.display.set_caption("Conway's Game of Life")
        self.screen = pygame.display.set_mode(size)
        #opens window 500x500
        self.clear_screen()
acousticWords = "acoustic instrumental".split()
acousticResponses = [
    "Here are some songs with high acousticness:\n" +
    (spotify_info.printSongList(spotify_info.high_acousticness)) +
    "\nWhat other kinds of music do you like?"
]

lessacousticWords = "electronic electric".split()
lessAcousticResponses = [
    "Here are some songs with high acousticness:\n" +
    (spotify_info.printSongList(spotify_info.low_acousticness)) +
    "\nWhat other kinds of music do you like?"
]

import hyperlink
url = hyperlink.parse(
    u'https://open.spotify.com/playlist/452xDxHeGps1mqg6j0MmOz')
secure_url = url.replace(scheme=u'https')

playlistWords = "playlist url link spotify".split()
playlistResponses = [
    "Here's a link to a playlist of all these songs:\n" +
    (secure_url.to_text())
]

generalResponses = [
    "What genre of music is your favorite?",
    "Do you mainly listen to short songs or long songs?",
    "Do you like short songs or long songs?",
    "Do you prefer songs with a positive or negative mood?",
    "Do you like songs with spoken word or with more of a musical quality?",
    "Do you prefer to listen to more energetic or calmer music?",
예제 #22
0
def check_url(url_str):
    url = parse(unicode(url_str))
    assert url.scheme in ('http', 'https')
    return url
예제 #23
0
    def get_query(self):
        from .query import Query

        params = list(hyperlink.parse(f"?{self.query}").query)
        params.append(("limit", str(self.limit)))
        return Query.from_request(self.model_name, self.fields, params)
예제 #24
0
    def get_findings(self, filename, test, active=None, verified=None):

        content = filename.read()
        if type(content) is bytes:
            content = content.decode('utf-8')
        reader = csv.DictReader(io.StringIO(content),
                                delimiter=',',
                                quotechar='"')

        dupes = dict()
        for row in reader:
            finding = Finding(
                test=test,
                title=row['Title'],
                description=row['Description'],
                date=parse(row['Date']).date(),
                severity=row['Severity'],
                duplicate=self._convert_bool(row.get(
                    'Duplicate', 'FALSE')),  # bool False by default
                nb_occurences=1,
            )
            # manage active
            if 'Active' in row:
                finding.active = self._convert_bool(row.get(
                    'Active', 'FALSE'))  # bool False by default
            # manage mitigation
            if 'Mitigation' in row:
                finding.mitigation = row['Mitigation']
            # manage impact
            if 'Impact' in row:
                finding.impact = row['Impact']
            # manage impact
            if 'References' in row:
                finding.references = row['References']
            # manage verified
            if 'Verified' in row:
                finding.verified = self._convert_bool(
                    row.get('Verified', 'FALSE'))  # bool False by default
            # manage false positives
            if 'FalsePositive' in row:
                finding.false_p = self._convert_bool(
                    row.get('FalsePositive', 'FALSE'))  # bool False by default
            # manage CVE
            if 'CVE' in row:
                finding.cve = row['CVE']
            # manage CWE
            if 'CweId' in row:
                finding.cwe = int(row['CweId'])
            # FIXME remove this severity hack
            if finding.severity == 'Unknown':
                finding.severity = 'Info'

            # manage active/verified overrride
            if active:
                finding.active = active
            if verified:
                finding.verified = verified

            # manage endpoints
            if 'Url' in row:
                url = hyperlink.parse(row['Url'])
                endpoint = Endpoint(
                    protocol=url.scheme,
                    host=url.host +
                    (":" + str(url.port)) if url.port is not None else "",
                    path="/".join(url.path),
                )
                if url.query:
                    endpoint.query = url.query
                if url.fragment:
                    endpoint.fragment = url.fragment
                finding.unsaved_endpoints = [endpoint]

            # manage internal de-duplication
            key = hashlib.sha256("|".join([
                finding.severity,
                finding.title,
                finding.description,
            ]).encode("utf-8")).hexdigest()
            if key in dupes:
                find = dupes[key]
                find.unsaved_endpoints.extend(finding.unsaved_endpoints)
                find.nb_occurences += 1
            else:
                dupes[key] = finding

        return list(dupes.values())
예제 #25
0
                        value=result.tm_mday,
                        inline=True)  #what day of the month
    TimeEmbed.add_field(name="Day of the Week",
                        value=result.tm_wday,
                        inline=True)  # what day of the week
    TimeEmbed.add_field(name="Hour", value=result.tm_hour,
                        inline=True)  # what hour
    TimeEmbed.add_field(name="Minute", value=result.tm_min,
                        inline=True)  #what minute
    TimeEmbed.add_field(name="Second", value=result.tm_sec,
                        inline=True)  #what second

    await ctx.send(embed=TimeEmbed)  #send embed when command is typed


url = hyperlink.parse(
    u"https://github.com/Kguy693/BestBotEver/blob/main/BestBot.py")


@client.command()
async def code(ctx):
    CodeEmbed = discord.Embed(title="Github Repository",
                              description=url.to_text(),
                              color=0x00ff00)

    await ctx.send(embed=CodeEmbed)


'''@client.command(pass_context=True, aliases=['j', 'joi'])
async def join(ctx):
    channel = ctx.message.author.voice.channel
    voice = get(client.voice_clients, guild=ctx.guild)
예제 #26
0
    def get_findings(self, file, test):
        tree = json.load(file)

        report_date = None
        if 'start_time' in tree:
            report_date = datetime.utcfromtimestamp(tree.get('start_time'))

        dupes = dict()
        for plugin in tree.get('plugins', []):
            node = tree['plugins'][plugin]
            for vul in node.get('vulnerabilities'):

                description = "\n".join([
                    '**Title:** `' + vul['title'] + "`\n",
                    '**Location:** `' + node['location'] + "`\n",
                    '**Plugin:** `' + plugin + "`\n",
                ])

                finding = Finding(
                    title=vul['title'],
                    description=description,
                    severity='Medium',
                    numerical_severity=Finding.get_numerical_severity(
                        'Medium'),
                    cwe=1035,
                    references=self.generate_references(vul['references']),
                    dynamic_finding=True,
                    static_finding=False,
                    unique_id_from_tool=vul['references']['wpvulndb'][0],
                    nb_occurences=1,
                )
                # manage version
                finding.component_name = plugin
                if 'version' in node and node['version'] is not None:
                    finding.component_version = node['version'].get('number')
                # manage date of finding with report date
                if report_date:
                    finding.date = report_date
                # if there is a fixed version fill mitigation
                if 'fixed_in' in vul:
                    finding.mitigation = 'fixed in : ' + vul['fixed_in']
                # manage CVE
                if 'cve' in vul['references']:
                    finding.cve = "CVE-" + vul['references']['cve'][0]

                # internal de-duplication
                dupe_key = hashlib.sha256(
                    str(finding.unique_id_from_tool).encode(
                        'utf-8')).hexdigest()
                if dupe_key in dupes:
                    find = dupes[dupe_key]
                    if finding.references:
                        dupes[dupe_key].references += finding.references
                    find.nb_occurences += finding.nb_occurences
                else:
                    dupes[dupe_key] = finding

        # manage interesting interesting_findings
        for interesting_finding in tree.get('interesting_findings', []):
            references = self.generate_references(
                interesting_finding['references'])
            description = "\n".join([
                '**Type:** `' + interesting_finding.get('type') + "`\n",
                '**Url:** `' + interesting_finding['url'] + "`\n",
            ])
            finding = Finding(
                title=f"Interesting finding: {interesting_finding.get('to_s')}",
                description=description,
                severity='Info',
                numerical_severity=Finding.get_numerical_severity('Info'),
                dynamic_finding=True,
                static_finding=False,
            )
            # manage endpoint
            url = hyperlink.parse(interesting_finding['url'])
            endpoint = Endpoint(
                path="/".join(url.path),
                host=url.host,
                port=url.port,
                protocol=url.scheme,
            )
            finding.unsaved_endpoints = [endpoint]
            # manage date of finding with report date
            if report_date:
                finding.date = report_date

            # internal de-duplication
            dupe_key = hashlib.sha256(
                str("interesting_findings" + finding.title +
                    interesting_finding['url']).encode('utf-8')).hexdigest()
            if dupe_key in dupes:
                find = dupes[dupe_key]
                if finding.references:
                    dupes[dupe_key].references += finding.references
                find.nb_occurences += finding.nb_occurences
            else:
                dupes[dupe_key] = finding

        return list(dupes.values())
                            Logged = True

            self._set_headers()
            self.wfile.write(
                bytes(
                    json.dumps({
                        "loginSuccesful": Logged,
                        "username": postData['data']['username']
                    }), 'utf-8'))


class bcolors:
    OK = '\033[92m'  #GREEN
    RESET = '\033[0m'  #RESET COLOR


# Set server settings
host = '10.0.0.8'
port = 3000

# Set terminal message for developer
url = hyperlink.parse(u'http://' + host)
better_url = url.replace(scheme=u'http', port=port)
org_url = better_url.click(u'.')

print('The Server Started on: ' + bcolors.OK + org_url.to_text() +
      bcolors.RESET)

# Initialize server
httpd = HTTPServer((host, port), Serv)
httpd.serve_forever()