Example #1
0
 def test_metadata_unsupported_version(self):
     password = b"fooobarr"
     data = b"#bellavita"
     version = len(crypto.pack_versions).to_bytes(1, "big")
     pack = crypto.encode(password, data, b"")
     offset = crypto.PackVersion.hash_len
     pack = pack[:offset] + version + pack[offset + 1 :]
     with self.assertRaises(ValueError):
         crypto.metadata(pack)
Example #2
0
 def test_encode_metadata_too_long_version_bigger_than_0(self):
     password = b"fooobarr"
     data = b"#bellavita"
     original_metadata = b"A" * 123456
     pack = crypto.encode(password, data, original_metadata)
     metadata = crypto.metadata(pack)
     self.assertEqual(metadata, original_metadata)
Example #3
0
 def test_metadata(self):
     for version in range(len(crypto.pack_versions)):
         with self.subTest():
             password = b"fooobarr"
             data = b"#bellavita"
             encrypted = crypto.encode(password, data, b"metadata", version=version)
             metadata = crypto.metadata(encrypted)
             self.assertEqual(metadata.strip(b"\x00"), b"metadata")
Example #4
0
 def pack_status(self):
     """
     POST /admin/pack_status
     """
     if not os.path.exists(Config.encrypted_file):
         return {"uploaded": False}
     with open(Config.encrypted_file, "rb") as f:
         raw_meta = crypto.metadata(f.read(crypto.DATA_OFFSET))
     metadata = yaml.safe_load(raw_meta.strip(b"\x00"))
     if metadata is None:
         metadata = dict()
     metadata["uploaded"] = True
     return metadata
Example #5
0
def get_metadata_main():
    parser = argparse.ArgumentParser(description="Validate and get a file metadata")
    parser.add_argument("input_file", help="input file", nargs="?", default="-")
    parser.add_argument("output_file", help="output file", nargs="?", default="-")
    args = parser.parse_args()
    input_file = (
        open(args.input_file, "rb") if args.input_file != "-" else sys.stdin.buffer
    )
    output_file = (
        open(args.output_file, "wb") if args.output_file != "-" else sys.stdout.buffer
    )
    input_data = input_file.read()
    assert validate(input_data)
    output_file.write(metadata(input_data).strip(b"\x00"))
def main(args):
    with open(args.pack, "rb") as pack:
        pack = pack.read()
    if not validate(pack):
        raise AssertionError("Corrupted pack")
    meta = ruamel.yaml.safe_load(metadata(pack).strip(b"\x00"))
    if meta.get("deletable"):
        print(Fore.YELLOW, "WARNING: The pack is marked as deletable",
              Fore.RESET)
    if not meta.get("name"):
        print(Fore.YELLOW,
              "WARNING: The pack metadata does not include 'name'", Fore.RESET)
    if not meta.get("description"):
        print(Fore.YELLOW,
              "WARNING: The pack metadata does not include 'description'",
              Fore.RESET)
    decoded = decode(bytes.fromhex(args.password), pack)

    tasks = args.tasks.split(",")
    if args.solutions:
        solutions = [
            list(map(os.path.abspath, s.split(",")))
            for s in args.solutions.split(";")
        ]
    else:
        solutions = [[]] * len(tasks)

    extract_dir = tempfile.mkdtemp()
    os.chdir(extract_dir)
    print("Working in %s" % extract_dir)

    with open("pack.zip", "wb") as f:
        f.write(decoded)
    with zipfile.ZipFile("pack.zip") as zip_file:
        zip_file.extractall(".")
    if args.sedi:
        validate_sedi(args.sedi)
    if args.admin:
        validate_admin(args.admin, args.password)
    for i, task in enumerate(tasks):
        if not os.path.exists(task):
            raise AssertionError("Task %s not included in the pack" % task)
        sols = solutions[i] if i < len(solutions) else []
        validate_task(task, args.fuzz, args.iterations, sols)

    shutil.rmtree(extract_dir)
def get_metadata_main():
    parser = argparse.ArgumentParser(
        description='Validate and get a file metadata')
    parser.add_argument('input_file',
                        help='input file',
                        nargs='?',
                        default='-')
    parser.add_argument('output_file',
                        help='output file',
                        nargs='?',
                        default='-')
    args = parser.parse_args()
    input_file = open(args.input_file,
                      'rb') if args.input_file != '-' else sys.stdin.buffer
    output_file = open(args.output_file,
                       'wb') if args.output_file != '-' else sys.stdout.buffer
    input_data = input_file.read()
    assert validate(input_data)
    output_file.write(metadata(input_data).strip(b'\x00'))
Example #8
0
    def drop_contest(self, admin_token):
        """
        POST /admin/drop_contest
        """
        if not os.path.exists(Config.encrypted_file):
            self.raise_exc(NotFound, "NOT_FOUND", "No packs found")
        Logger.warning("DROP_CONTEST", "Started dropping contest")
        with open(Config.encrypted_file, "rb") as f:
            pack = f.read()

        db_token = Database.get_meta("admin_token")
        # contest has been extracted but the token is wrong
        if db_token is not None and db_token != admin_token:
            self.raise_exc(Forbidden, "FORBIDDEN", "Wrong token")
        # contest has not been extracted
        if db_token is None:
            try:
                password = crypto.recover_file_password_from_token(admin_token)
                crypto.decode(password, pack)
            except nacl.exceptions.CryptoError:
                # pack password is wrong
                self.raise_exc(Forbidden, "FORBIDDEN", "Wrong pack token")

        metadata = ruamel.yaml.safe_load(crypto.metadata(pack).strip(b"\x00"))
        if not metadata.get("deletable"):
            self.raise_exc(Forbidden, "FORBIDDEN", "Contest not deletable")

        shutil.rmtree(Config.storedir, ignore_errors=True)
        shutil.rmtree(Config.statementdir, ignore_errors=True)
        shutil.rmtree(Config.contest_path, ignore_errors=True)
        for f in (Config.encrypted_file, Config.decrypted_file):
            try:
                os.remove(f)
            except FileNotFoundError:
                pass

        Database.disconnect_database()
        for f in glob.glob(Config.db + "*"):
            os.remove(f)
        Database.connect_to_database()
        Logger.warning("DROP_CONTEST", "Contest dropped")
        return {}
Example #9
0
 def test_metadata(self):
     password = b"fooobarr"
     data = b"#bellavita"
     encrypted = crypto.encode(password, data, b"metadata")
     metadata = crypto.metadata(encrypted)
     self.assertEqual(metadata.strip(b"\x00"), b"metadata")