Exemplo n.º 1
0
def test_s3_sync():
    conn = boto3.resource("s3", region_name="us-east-1")
    conn.create_bucket(Bucket="bucket")

    app = create_kmactf()
    with app.app_context():
        app.config["UPLOAD_PROVIDER"] = "s3"
        app.config["AWS_ACCESS_KEY_ID"] = "AKIAIOSFODNN7EXAMPLE"
        app.config["AWS_SECRET_ACCESS_KEY"] = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
        app.config["AWS_S3_BUCKET"] = "bucket"

        uploader = S3Uploader()
        uploader.sync()

        fake_file = BytesIO("fakedfile".encode())
        path = uploader.upload(fake_file, "fake_file.txt")
        full_path = os.path.join(app.config["UPLOAD_FOLDER"], path)

        try:
            uploader.sync()
            with open(full_path) as f:
                assert f.read() == "fakedfile"
        finally:
            rmdir(os.path.dirname(full_path))
    destroy_kmactf(app)
Exemplo n.º 2
0
def test_team_size_limit():
    """Only team_size amount of members can join a team even via MLC"""
    app = create_kmactf(user_mode="teams")
    app.config.update({
        "OAUTH_CLIENT_ID": "kmactf_testing_client_id",
        "OAUTH_CLIENT_SECRET": "kmactf_testing_client_secret",
        "OAUTH_AUTHORIZATION_ENDPOINT":
        "http://auth.localhost/oauth/authorize",
        "OAUTH_TOKEN_ENDPOINT": "http://auth.localhost/oauth/token",
        "OAUTH_API_ENDPOINT": "http://api.localhost/user",
    })
    with app.app_context():
        set_config("team_size", 1)
        team = gen_team(app.db, member_count=1, oauth_id=1234)
        team_id = team.id
        login_with_mlc(app,
                       team_name="team_name",
                       team_oauth_id=1234,
                       raise_for_error=False)
        assert len(Teams.query.filter_by(id=team_id).first().members) == 1

        set_config("team_size", 2)
        login_with_mlc(app, team_name="team_name", team_oauth_id=1234)
        assert len(Teams.query.filter_by(id=team_id).first().members) == 2
    destroy_kmactf(app)
Exemplo n.º 3
0
def test_lookup_user_token():
    app = create_kmactf()
    with app.app_context():
        user = gen_user(app.db)
        # Good Token
        token = gen_token(app.db, user_id=user.id)
        user = lookup_user_token(token.value)
        assert user.id == token.user_id

        # Expired Token
        expiration = datetime.datetime.utcnow() + datetime.timedelta(days=-1)
        token = gen_token(app.db, user_id=user.id, expiration=expiration)
        try:
            lookup_user_token(token.value)
        except UserTokenExpiredException:
            pass
        except Exception as e:
            raise e

        # Nonexistant token
        try:
            lookup_user_token("wat")
        except UserNotFoundException:
            pass
        except Exception as e:
            raise e
    destroy_kmactf(app)
Exemplo n.º 4
0
def test_hidden_challenge_is_reachable():
    """Test that hidden challenges are visible for admins"""
    app = create_kmactf()
    with app.app_context():
        register_user(app)
        client = login_as_user(app, name="admin", password="******")
        chal = gen_challenge(app.db, state="hidden")
        gen_flag(app.db, challenge_id=chal.id, content="flag")
        chal_id = chal.id

        assert Challenges.query.count() == 1

        r = client.get("/api/v1/challenges", json="")
        data = r.get_json().get("data")
        assert data == []

        r = client.get("/api/v1/challenges/1", json="")
        assert r.status_code == 200
        data = r.get_json().get("data")
        assert data["name"] == "chal_name"

        data = {"submission": "flag", "challenge_id": chal_id}

        r = client.post("/api/v1/challenges/attempt", json=data)
        assert r.status_code == 404

        r = client.post("/api/v1/challenges/attempt?preview=true", json=data)
        assert r.status_code == 200
        resp = r.get_json()["data"]
        assert resp.get("status") == "correct"
    destroy_kmactf(app)
Exemplo n.º 5
0
def test_update_check_identifies_update(fake_get_request):
    """Update checks properly identify new versions"""
    app = create_kmactf()
    with app.app_context():
        app.config["UPDATE_CHECK"] = True
        fake_response = Mock()
        fake_get_request.return_value = fake_response
        fake_response.json = lambda: {
            "resource": {
                "download_url":
                "https://api.github.com/repos/KMActf/KMActf/zipball/9.9.9",
                "html_url":
                "https://github.com/KMActf/KMActf/releases/tag/9.9.9",
                "id": 12,
                "latest": True,
                "next": 1542212248,
                "prerelease": False,
                "published_at": "Wed, 25 Oct 2017 19:39:42 -0000",
                "tag": "9.9.9",
            }
        }
        update_check()
        assert (get_config("version_latest") ==
                "https://github.com/KMActf/KMActf/releases/tag/9.9.9")
        assert get_config("next_update_check") == 1542212248
    destroy_kmactf(app)
Exemplo n.º 6
0
def test_api_submissions_get_non_admin():
    app = create_kmactf()
    with app.app_context():
        gen_challenge(app.db)
        gen_solve(app.db, user_id=1)
        with app.test_client() as client:
            # test_api_submissions_get_non_admin
            """Can a user get /api/v1/submissions if not admin"""
            r = client.get("/api/v1/submissions", json="")
            assert r.status_code == 403

            # test_api_submissions_post_non_admin
            """Can a user post /api/v1/submissions if not admin"""
            r = client.post("/api/v1/submissions")
            assert r.status_code == 403

            # test_api_submission_get_non_admin
            """Can a user get /api/v1/submissions/<submission_id> if not admin"""
            r = client.get("/api/v1/submissions/1", json="")
            assert r.status_code == 403

            # test_api_submission_delete_non_admin
            """Can a user delete /api/v1/submissions/<submission_id> if not admin"""
            r = client.delete("/api/v1/submissions/1", json="")
            assert r.status_code == 403
    destroy_kmactf(app)
Exemplo n.º 7
0
def test_redis_event_manager_publish():
    """Test that RedisEventManager publishing to clients works."""
    class RedisConfig(TestingConfig):
        REDIS_URL = "redis://localhost:6379/3"
        CACHE_REDIS_URL = "redis://localhost:6379/3"
        CACHE_TYPE = "redis"

    try:
        app = create_kmactf(config=RedisConfig)
    except ConnectionError:
        print("Failed to connect to redis. Skipping test.")
    else:
        with app.app_context():
            saved_data = {
                "user_id": None,
                "title": "asdf",
                "content": "asdf",
                "team_id": None,
                "user": None,
                "team": None,
                "date": "2019-01-28T01:20:46.017649+00:00",
                "id": 10,
            }

            event_manager = RedisEventManager()
            event_manager.publish(data=saved_data,
                                  type="notification",
                                  channel="ctf")
        destroy_kmactf(app)
Exemplo n.º 8
0
def test_api_removing_members_deletes_information():
    """If an admin removes a user, their score information should also be removed"""
    app = create_kmactf(user_mode="teams")
    with app.app_context():
        team = gen_team(app.db)
        assert len(team.members) == 4
        app.db.session.commit()

        user = Users.query.filter_by(id=2).first()
        simulate_user_activity(app.db, user)
        assert Solves.query.filter_by(user_id=2).count() == 1
        assert Submissions.query.filter_by(user_id=2).count() == 6
        assert Awards.query.filter_by(user_id=2).count() == 1
        assert Unlocks.query.filter_by(user_id=2).count() == 1

        with login_as_user(app, name="admin") as client:
            r = client.delete("/api/v1/teams/1/members", json={"user_id": 2})
            assert r.status_code == 200

        user = Users.query.filter_by(id=2).first()
        assert Solves.query.filter_by(user_id=2).count() == 0
        assert Submissions.query.filter_by(user_id=2).count() == 0
        assert Awards.query.filter_by(user_id=2).count() == 0
        assert Unlocks.query.filter_by(user_id=2).count() == 0
    destroy_kmactf(app)
Exemplo n.º 9
0
def test_api_admin_can_change_captain():
    """Can admins/captains change captains for teams"""
    app = create_kmactf(user_mode="teams")
    with app.app_context():
        user1 = gen_user(app.db, name="user1", email="*****@*****.**")  # ID 2
        user2 = gen_user(app.db, name="user2", email="*****@*****.**")  # ID 3
        team = gen_team(app.db)
        team.members.append(user1)
        team.members.append(user2)
        team.captain_id = 2
        user1.team_id = team.id
        user2.team_id = team.id
        app.db.session.commit()

        # I am not the captain
        with login_as_user(app, name="user2") as client:
            r = client.patch("/api/v1/teams/1", json={"captain_id": 3})
            assert r.status_code == 403

        # Look at me, I'm the captain now
        with login_as_user(app, name="user1") as client:
            r = client.patch("/api/v1/teams/1", json={"captain_id": 3})
            # We should still receive a 403 because admins are the only people who can change captains for specific teams
            assert r.status_code == 403

        # Escalate to admin
        with login_as_user(app, name="admin") as client:
            r = client.patch("/api/v1/teams/1", json={"captain_id": 3})
            resp = r.get_json()
            assert resp["data"]["captain_id"] == 3
            assert r.status_code == 200
    destroy_kmactf(app)
Exemplo n.º 10
0
def test_api_users_can_change_captain_on_self_team():
    """Can admins/captains change captains for their own team"""
    app = create_kmactf(user_mode="teams")
    with app.app_context():
        user1 = gen_user(app.db, name="user1", email="*****@*****.**")  # ID 2
        user2 = gen_user(app.db, name="user2", email="*****@*****.**")  # ID 3
        team = gen_team(app.db)
        team.members.append(user1)
        team.members.append(user2)
        team.captain_id = 2
        user1.team_id = team.id
        user2.team_id = team.id
        app.db.session.commit()

        # I am not the captain
        with login_as_user(app, name="user2") as client:
            r = client.patch("/api/v1/teams/me", json={"captain_id": 3})
            assert r.status_code == 403

        # Look at me, I'm the captain now
        with login_as_user(app, name="user1") as client:
            r = client.patch("/api/v1/teams/me", json={"captain_id": 3})
            resp = r.get_json()
            assert resp["data"]["captain_id"] == 3
            assert r.status_code == 200
    destroy_kmactf(app)
Exemplo n.º 11
0
def test_api_team_remove_members():
    """Can a user remove /api/v1/teams/<team_id>/members only if admin"""
    app = create_kmactf(user_mode="teams")
    with app.app_context():
        team = gen_team(app.db)
        assert len(team.members) == 4
        app.db.session.commit()

        gen_user(app.db, name="user1")
        with login_as_user(app, name="user1") as client:
            r = client.delete("/api/v1/teams/1/members", json={"user_id": 2})
            assert r.status_code == 403

        with login_as_user(app, name="admin") as client:
            r = client.delete("/api/v1/teams/1/members", json={"user_id": 2})
            assert r.status_code == 200

            resp = r.get_json()
            # The following data is sorted b/c in Postgres data isn't necessarily returned ordered.
            assert sorted(resp["data"]) == sorted([3, 4, 5])

            r = client.delete("/api/v1/teams/1/members", json={"user_id": 2})

            resp = r.get_json()
            assert "User is not part of this team" in resp["errors"]["id"]
            assert r.status_code == 400
    destroy_kmactf(app)
Exemplo n.º 12
0
def test_unlocking_hints_with_cost_during_frozen_ctf():
    """Test that hints with a cost are unlocked if the CTF is frozen."""
    app = create_kmactf()
    with app.app_context():
        set_config(
            "freeze", "1507262400"
        )  # Friday, October 6, 2017 12:00:00 AM GMT-04:00 DST
        with freeze_time("2017-10-4"):
            register_user(app)
            chal = gen_challenge(app.db)
            chal_id = chal.id
            gen_hint(app.db, chal_id, cost=10)
            gen_award(app.db, user_id=2)

        with freeze_time("2017-10-8"):
            client = login_as_user(app)

            client.get("/api/v1/hints/1")

            client.post("/api/v1/unlocks", json={"target": 1, "type": "hints"})

            r = client.get("/api/v1/hints/1")

            resp = r.get_json()["data"]
            assert resp.get("content") == "This is a hint"

            user = Users.query.filter_by(id=2).first()
            assert user.score == 100
    destroy_kmactf(app)
Exemplo n.º 13
0
def test_unlocking_hints_with_cost_during_ended_ctf():
    """Test that hints with a cost are not unlocked if the CTF has ended"""
    app = create_kmactf()
    with app.app_context():
        register_user(app)
        chal = gen_challenge(app.db)
        chal_id = chal.id
        gen_hint(app.db, chal_id, cost=10)
        gen_award(app.db, user_id=2)

        set_config(
            "start", "1507089600"
        )  # Wednesday, October 4, 2017 12:00:00 AM GMT-04:00 DST
        set_config(
            "end", "1507262400"
        )  # Friday, October 6, 2017 12:00:00 AM GMT-04:00 DST

        with freeze_time("2017-11-4"):
            client = login_as_user(app)

            r = client.get("/api/v1/hints/1")
            assert r.get_json().get("data") is None
            assert r.status_code == 403

            r = client.post("/api/v1/unlocks", json={"target": 1, "type": "hints"})
            assert r.status_code == 403
            assert r.get_json()

            r = client.get("/api/v1/hints/1")
            assert r.status_code == 403

            user = Users.query.filter_by(id=2).first()
            assert user.score == 100
            assert Unlocks.query.count() == 0
    destroy_kmactf(app)
Exemplo n.º 14
0
def test_unlocking_hints_with_cost_during_ctf_without_points():
    """Test that hints with a cost are not unlocked if you don't have the points"""
    app = create_kmactf()
    with app.app_context():
        register_user(app)
        chal = gen_challenge(app.db)
        chal_id = chal.id
        gen_hint(app.db, chal_id, cost=10)

        client = login_as_user(app)

        r = client.get("/api/v1/hints/1")
        assert r.get_json()["data"].get("content") is None

        r = client.post("/api/v1/unlocks", json={"target": 1, "type": "hints"})
        assert (
            r.get_json()["errors"]["score"]
            == "You do not have enough points to unlock this hint"
        )

        r = client.get("/api/v1/hints/1")
        assert r.get_json()["data"].get("content") is None

        user = Users.query.filter_by(id=2).first()
        assert user.score == 0
    destroy_kmactf(app)
Exemplo n.º 15
0
def test_sendmail_with_smtp_from_db_config(mock_smtp):
    """Does sendmail work properly with simple SMTP mail servers using database configuration"""
    app = create_kmactf()
    with app.app_context():
        set_config("mail_server", "localhost")
        set_config("mail_port", 25)
        set_config("mail_useauth", True)
        set_config("mail_username", "username")
        set_config("mail_password", "password")

        ctf_name = get_config("ctf_name")
        from_addr = get_config("mailfrom_addr") or app.config.get(
            "MAILFROM_ADDR")
        from_addr = "{} <{}>".format(ctf_name, from_addr)

        to_addr = "*****@*****.**"
        msg = "this is a test"

        sendmail(to_addr, msg)

        ctf_name = get_config("ctf_name")
        email_msg = MIMEText(msg)
        email_msg["Subject"] = "Message from {0}".format(ctf_name)
        email_msg["From"] = from_addr
        email_msg["To"] = to_addr

        mock_smtp.return_value.sendmail.assert_called_once_with(
            from_addr, [to_addr], email_msg.as_string())
    destroy_kmactf(app)
Exemplo n.º 16
0
def test_api_users_post_admin_with_attributes():
    """Can a user post /api/v1/users with user settings"""
    app = create_kmactf()
    with app.app_context():
        with login_as_user(app, "admin") as client:
            # Create user
            r = client.post(
                "/api/v1/users",
                json={
                    "name": "user",
                    "email": "*****@*****.**",
                    "password": "******",
                    "banned": True,
                    "hidden": True,
                    "verified": True,
                },
            )
            assert r.status_code == 200

            # Make sure password was hashed properly
            user = Users.query.filter_by(email="*****@*****.**").first()
            assert user
            assert verify_password("password", user.password)
            assert user.banned
            assert user.hidden
            assert user.verified
    destroy_kmactf(app)
Exemplo n.º 17
0
def test_reset():
    app = create_kmactf()
    with app.app_context():
        base_user = "******"

        for x in range(10):
            chal = gen_challenge(app.db, name="chal_name{}".format(x))
            gen_flag(app.db, challenge_id=chal.id, content="flag")

        for x in range(10):
            user = base_user + str(x)
            user_email = user + "@kmactf.io"
            user_obj = gen_user(app.db, name=user, email=user_email)
            gen_award(app.db, user_id=user_obj.id)
            gen_solve(app.db, user_id=user_obj.id, challenge_id=random.randint(1, 10))
            gen_fail(app.db, user_id=user_obj.id, challenge_id=random.randint(1, 10))
            gen_tracking(app.db, user_id=user_obj.id)

        assert Users.query.count() == 11  # 11 because of the first admin user
        assert Challenges.query.count() == 10

        register_user(app)
        client = login_as_user(app, name="admin", password="******")

        with client.session_transaction() as sess:
            data = {"nonce": sess.get("nonce")}
            client.post("/admin/reset", data=data)

        assert Users.query.count() == 0
        assert Challenges.query.count() == 10
        assert Solves.query.count() == 0
        assert Fails.query.count() == 0
        assert Tracking.query.count() == 0
    destroy_kmactf(app)
Exemplo n.º 18
0
def test_api_user_change_name():
    """Can a user change their name via the API"""
    app = create_kmactf()
    with app.app_context():
        register_user(app)
        with login_as_user(app) as client:
            r = client.patch("/api/v1/users/me", json={"name": "user2"})
            assert r.status_code == 200
            resp = r.get_json()
            assert resp["data"]["name"] == "user2"
            assert resp["success"] is True

            r = client.patch("/api/v1/users/me", json={"name": None})
            resp = r.get_json()
            print(resp)
            assert r.status_code == 400
            assert resp["errors"]["name"] == ["Field may not be null."]
            assert resp["success"] is False

            set_config("name_changes", False)

            r = client.patch("/api/v1/users/me", json={"name": "new_name"})
            assert r.status_code == 400
            resp = r.get_json()
            assert "name" in resp["errors"]
            assert resp["success"] is False

            set_config("name_changes", True)
            r = client.patch("/api/v1/users/me", json={"name": "new_name"})
            assert r.status_code == 200
            resp = r.get_json()
            assert resp["data"]["name"] == "new_name"
            assert resp["success"] is True
    destroy_kmactf(app)
Exemplo n.º 19
0
def test_challenge_team_submit():
    """Is a user's solved challenge reflected by other team members"""
    app = create_kmactf(user_mode="teams")
    with app.app_context():
        user = gen_user(app.db)
        second_user = gen_user(app.db, name="user", email="*****@*****.**")
        team = gen_team(app.db)
        user.team_id = team.id
        second_user.team_id = team.id
        team.members.append(user)
        team.members.append(second_user)
        gen_challenge(app.db)
        gen_flag(app.db, 1)
        app.db.session.commit()
        with login_as_user(app, name="user_name") as client:
            flag = {"challenge_id": 1, "submission": "flag"}
            client.post("/api/v1/challenges/attempt", json=flag)
        with login_as_user(app) as second_client:
            flag = {"challenge_id": 1, "submission": "flag"}
            r = second_client.post("/api/v1/challenges/attempt", json=flag)
            assert r.json["data"]["status"] == "already_solved"
        standings = get_standings()
        assert standings[0][2] == "team_name"
        assert standings[0][3] == 100
    destroy_kmactf(app)
Exemplo n.º 20
0
def test_api_user_change_email():
    """Test that users can change their email via the API"""
    app = create_kmactf()
    with app.app_context():
        register_user(app)
        user = Users.query.filter_by(id=2).first()
        app.db.session.commit()
        with login_as_user(app) as client:
            # Test users can't submit null
            r = client.patch("/api/v1/users/me",
                             json={
                                 "email": None,
                                 "confirm": "password"
                             })
            resp = r.get_json()
            print(resp)
            assert r.status_code == 400
            assert resp["errors"]["email"] == ["Field may not be null."]

            # Test users can exercise the API
            r = client.patch(
                "/api/v1/users/me",
                json={
                    "email": "*****@*****.**",
                    "confirm": "password"
                },
            )
            assert r.status_code == 200
            resp = r.get_json()
            assert resp["data"]["email"] == "*****@*****.**"
            assert resp["success"] is True
            user = Users.query.filter_by(id=2).first()
            assert user.email == "*****@*****.**"
    destroy_kmactf(app)
Exemplo n.º 21
0
def test_hint_team_unlock():
    """Is a user's unlocked hint reflected on other team members"""
    app = create_kmactf(user_mode="teams")
    with app.app_context():
        user = gen_user(app.db)
        second_user = gen_user(app.db, name="user", email="*****@*****.**")
        team = gen_team(app.db)
        user.team_id = team.id
        second_user.team_id = team.id
        team.members.append(user)
        team.members.append(second_user)
        chal = gen_challenge(app.db)
        gen_hint(app.db, chal.id, content="hint", cost=1, type="standard")
        gen_award(app.db, 2, team.id)
        app.db.session.commit()
        with login_as_user(app, name="user_name") as client:
            client.get("/api/v1/hints/1")
            client.post("/api/v1/unlocks", json={"target": 1, "type": "hints"})
            client.get("/api/v1/hints/1")
        with login_as_user(app) as second_client:
            second_client.get("/api/v1/hints/1")
            second_client.post("/api/v1/unlocks",
                               json={
                                   "target": 1,
                                   "type": "hints"
                               })
            r = second_client.get("/api/v1/hints/1")
            assert r.json["data"]["content"] == "hint"
            standings = get_standings()
            assert standings[0][2] == "team_name"
            assert standings[0][3] == 99
    destroy_kmactf(app)
Exemplo n.º 22
0
def test_api_user_change_email_under_whitelist():
    """Test that users can only change emails to ones in the whitelist"""
    app = create_kmactf()
    with app.app_context():
        register_user(app)
        set_config("domain_whitelist",
                   "whitelisted.com, whitelisted.org, whitelisted.net")
        with login_as_user(app) as client:
            r = client.patch(
                "/api/v1/users/me",
                json={
                    "email": "*****@*****.**",
                    "confirm": "password"
                },
            )
            assert r.status_code == 400
            resp = r.get_json()
            assert resp["errors"]["email"]
            assert resp["success"] is False

            r = client.patch(
                "/api/v1/users/me",
                json={
                    "email": "*****@*****.**",
                    "confirm": "password"
                },
            )
            assert r.status_code == 200
            resp = r.get_json()
            assert resp["data"]["email"] == "*****@*****.**"
            assert resp["success"] is True
    destroy_kmactf(app)
Exemplo n.º 23
0
def test_api_configs_get_non_admin():
    """Can a user get /api/v1/configs if not admin"""
    app = create_kmactf()
    with app.app_context():
        with app.test_client() as client:
            r = client.get("/api/v1/configs")
            assert r.status_code == 302

            # test_api_configs_post_non_admin
            """Can a user post /api/v1/configs if not admin"""
            r = client.post("/api/v1/configs", json="")
            assert r.status_code == 403

            # test_api_configs_patch_non_admin
            """Can a user patch /api/v1/configs if not admin"""
            r = client.patch("/api/v1/configs", json="")
            assert r.status_code == 403

            # test_api_config_get_non_admin
            """Can a user get /api/v1/configs/<config_key> if not admin"""
            r = client.get("/api/v1/configs/ctf_name")
            assert r.status_code == 302

            # test_api_config_patch_non_admin
            """Can a user patch /api/v1/configs/<config_key> if not admin"""
            r = client.patch("/api/v1/configs/ctf_name", json="")
            assert r.status_code == 403

            # test_api_config_delete_non_admin
            """Can a user delete /api/v1/configs/<config_key> if not admin"""
            r = client.delete("/api/v1/configs/ctf_name", json="")
            assert r.status_code == 403
            assert get_config("ctf_name") == "KMActf"
    destroy_kmactf(app)
Exemplo n.º 24
0
def test_api_users_post_admin():
    """Can a user post /api/v1/users if admin"""
    app = create_kmactf()
    with app.app_context():
        with login_as_user(app, "admin") as client:
            # Create user
            r = client.post(
                "/api/v1/users",
                json={
                    "name": "user",
                    "email": "*****@*****.**",
                    "password": "******"
                },
            )
            assert r.status_code == 200

            # Make sure password was hashed properly
            user = Users.query.filter_by(email="*****@*****.**").first()
            assert user
            assert verify_password("password", user.password)

            # Make sure user can login with the creds
            client = login_as_user(app)
            r = client.get("/profile")
            assert r.status_code == 200
    destroy_kmactf(app)
Exemplo n.º 25
0
def test_api_files_get_non_admin():
    app = create_kmactf()
    with app.app_context():
        chal = gen_challenge(app.db)
        gen_file(
            app.db,
            location="0bf1a55a5cd327c07af15df260979668/bird.swf",
            challenge_id=chal.id,
        )

        with app.test_client() as client:
            # test_api_files_get_non_admin
            """Can a user get /api/v1/files if not admin"""
            r = client.get("/api/v1/files", json="")
            assert r.status_code == 403

            # test_api_files_post_non_admin
            """Can a user post /api/v1/files if not admin"""
            r = client.post("/api/v1/files")
            assert r.status_code == 403

            # test_api_file_get_non_admin
            """Can a user get /api/v1/files/<file_id> if not admin"""
            r = client.get("/api/v1/files/1", json="")
            assert r.status_code == 403

            # test_api_file_delete_non_admin
            """Can a user delete /api/v1/files/<file_id> if not admin"""
            r = client.delete("/api/v1/files/1", json="")
            assert r.status_code == 403
    destroy_kmactf(app)
Exemplo n.º 26
0
def test_sendmail_with_smtp_from_config_file(mock_smtp):
    """Does sendmail work properly with simple SMTP mail servers using file configuration"""
    app = create_kmactf()
    with app.app_context():
        app.config["MAIL_SERVER"] = "localhost"
        app.config["MAIL_PORT"] = "25"
        app.config["MAIL_USEAUTH"] = "True"
        app.config["MAIL_USERNAME"] = "******"
        app.config["MAIL_PASSWORD"] = "******"

        ctf_name = get_config("ctf_name")
        from_addr = get_config("mailfrom_addr") or app.config.get(
            "MAILFROM_ADDR")
        from_addr = "{} <{}>".format(ctf_name, from_addr)

        to_addr = "*****@*****.**"
        msg = "this is a test"

        sendmail(to_addr, msg)

        ctf_name = get_config("ctf_name")
        email_msg = MIMEText(msg)
        email_msg["Subject"] = "Message from {0}".format(ctf_name)
        email_msg["From"] = from_addr
        email_msg["To"] = to_addr

        mock_smtp.return_value.sendmail.assert_called_once_with(
            from_addr, [to_addr], email_msg.as_string())
    destroy_kmactf(app)
Exemplo n.º 27
0
def test_oauth_login_upgrade():
    """Test that users who use MLC after having registered will be associated with their MLC account"""
    app = create_kmactf(user_mode="teams")
    app.config.update({
        "OAUTH_CLIENT_ID": "kmactf_testing_client_id",
        "OAUTH_CLIENT_SECRET": "kmactf_testing_client_secret",
        "OAUTH_AUTHORIZATION_ENDPOINT":
        "http://auth.localhost/oauth/authorize",
        "OAUTH_TOKEN_ENDPOINT": "http://auth.localhost/oauth/token",
        "OAUTH_API_ENDPOINT": "http://api.localhost/user",
    })
    with app.app_context():
        register_user(app)
        assert Users.query.count() == 2
        set_config("registration_visibility", "private")

        # Users should still be able to login
        client = login_as_user(app)
        client.get("/logout")

        user = Users.query.filter_by(id=2).first()
        assert user.oauth_id is None
        assert user.team_id is None

        login_with_mlc(app)

        assert Users.query.count() == 2

        # Logging in with MLC should insert an OAuth ID and team ID
        user = Users.query.filter_by(id=2).first()
        assert user.oauth_id
        assert user.verified
        assert user.team_id
    destroy_kmactf(app)
Exemplo n.º 28
0
def test_successful_registration_email(mock_smtp):
    """Does successful_registration_notification send emails"""
    app = create_kmactf()
    with app.app_context():
        set_config("mail_server", "localhost")
        set_config("mail_port", 25)
        set_config("mail_useauth", True)
        set_config("mail_username", "username")
        set_config("mail_password", "password")
        set_config("verify_emails", True)

        ctf_name = get_config("ctf_name")
        from_addr = get_config("mailfrom_addr") or app.config.get(
            "MAILFROM_ADDR")
        from_addr = "{} <{}>".format(ctf_name, from_addr)

        to_addr = "*****@*****.**"

        successful_registration_notification(to_addr)

        msg = "You've successfully registered for KMActf!"

        email_msg = MIMEText(msg)
        email_msg["Subject"] = "Successfully registered for {ctf_name}".format(
            ctf_name=ctf_name)
        email_msg["From"] = from_addr
        email_msg["To"] = to_addr

        # Need to freeze time to predict the value of the itsdangerous token.
        # For now just assert that sendmail was called.
        mock_smtp.return_value.sendmail.assert_called_with(
            from_addr, [to_addr], email_msg.as_string())
    destroy_kmactf(app)
Exemplo n.º 29
0
def test_user_token_access():
    app = create_kmactf()
    with app.app_context():
        with app.test_client() as client:
            r = client.get("/api/v1/users/me", json="")
            assert r.status_code == 403

        with app.test_client() as client:
            user = gen_user(app.db, name="user2", email="*****@*****.**")
            expiration = datetime.datetime.utcnow() + datetime.timedelta(
                days=-1)
            token = generate_user_token(user, expiration=expiration)
            headers = {"Authorization": "token " + token.value}
            r = client.get("/api/v1/users/me", headers=headers, json="")
            assert r.status_code == 401

        with app.test_client() as client:
            headers = {"Authorization": "token invalid_token"}
            r = client.get("/api/v1/users/me", headers=headers, json="")
            assert r.status_code == 401

        with app.test_client() as client:
            user = gen_user(app.db, name="user1", email="*****@*****.**")
            token = generate_user_token(user, expiration=None)
            headers = {"Authorization": "token " + token.value}
            r = client.get("/api/v1/users/me", headers=headers, json="")
            assert r.status_code == 200
            resp = r.get_json()
            assert resp["data"]["email"] == "*****@*****.**"
            assert resp["data"]["name"] == "user1"
    destroy_kmactf(app)
Exemplo n.º 30
0
def test_email_cannot_be_changed_without_password():
    """Test that a user can't update their email address without current password"""
    app = create_kmactf()
    with app.app_context():
        register_user(app)
        client = login_as_user(app)

        data = {"name": "user", "email": "*****@*****.**"}

        r = client.patch("/api/v1/users/me", json=data)
        assert r.status_code == 400
        user = Users.query.filter_by(id=2).first()
        assert user.email == "*****@*****.**"

        data = {"name": "user", "email": "*****@*****.**", "confirm": "asdf"}

        r = client.patch("/api/v1/users/me", json=data)
        assert r.status_code == 400
        user = Users.query.filter_by(id=2).first()
        assert user.email == "*****@*****.**"

        data = {"name": "user", "email": "*****@*****.**", "confirm": "password"}

        r = client.patch("/api/v1/users/me", json=data)
        assert r.status_code == 200
        user = Users.query.filter_by(id=2).first()
        assert user.email == "*****@*****.**"
        assert verify_password(plaintext="password", ciphertext=user.password)
    destroy_kmactf(app)