Exemplo n.º 1
0
def setup():
    # with app.app_context():
        # admin = Teams.query.filter_by(admin=True).first()

    if not is_setup():
        if not session.get('nonce'):
            session['nonce'] = sha512(os.urandom(10))
        if request.method == 'POST':
            ctf_name = request.form['ctf_name']
            ctf_name = Config('ctf_name', ctf_name)

            ## CSS
            css = Config('start', '')

            ## Admin user
            name = request.form['name']
            email = request.form['email']
            password = request.form['password']
            admin = Teams(name, email, password)
            admin.admin = True
            admin.banned = True

            ## Index page
            html = request.form['html']
            page = Pages('index', html)

            #max attempts per challenge
            max_tries = Config("max_tries",0)


            ## Start time
            start = Config('start', None)
            end = Config('end', None)

            ## Challenges cannot be viewed by unregistered users
            view_challenges_unregistered = Config('view_challenges_unregistered', None)

            ## Allow/Disallow registration
            prevent_registration = Config('prevent_registration', None)

            setup = Config('setup', True)

            db.session.add(ctf_name)
            db.session.add(admin)
            db.session.add(page)
            db.session.add(max_tries)
            db.session.add(start)
            db.session.add(end)
            db.session.add(view_challenges_unregistered)
            db.session.add(prevent_registration)
            db.session.add(css)
            db.session.add(setup)
            db.session.commit()
            app.setup = False
            return redirect('/')
        print(session.get('nonce'))
        return render_template('setup.html', nonce=session.get('nonce'))
    return redirect('/')
Exemplo n.º 2
0
Arquivo: views.py Projeto: mcanv/CTFd
def setup():
    # with app.app_context():
    # admin = Teams.query.filter_by(admin=True).first()

    if not is_setup():
        if not session.get("nonce"):
            session["nonce"] = sha512(os.urandom(10))
        if request.method == "POST":
            ctf_name = request.form["ctf_name"]
            ctf_name = Config("ctf_name", ctf_name)

            ## CSS
            css = Config("start", "")

            ## Admin user
            name = request.form["name"]
            email = request.form["email"]
            password = request.form["password"]
            admin = Teams(name, email, password)
            admin.admin = True
            admin.banned = True

            ## Index page
            html = request.form["html"]
            page = Pages("index", html)

            # max attempts per challenge
            max_tries = Config("max_tries", 0)

            ## Start time
            start = Config("start", None)
            end = Config("end", None)

            ## Challenges cannot be viewed by unregistered users
            view_challenges_unregistered = Config("view_challenges_unregistered", None)

            ## Allow/Disallow registration
            prevent_registration = Config("prevent_registration", None)

            setup = Config("setup", True)

            db.session.add(ctf_name)
            db.session.add(admin)
            db.session.add(page)
            db.session.add(max_tries)
            db.session.add(start)
            db.session.add(end)
            db.session.add(view_challenges_unregistered)
            db.session.add(prevent_registration)
            db.session.add(css)
            db.session.add(setup)
            db.session.commit()
            app.setup = False
            return redirect("/")
        print(session.get("nonce"))
        return render_template("setup.html", nonce=session.get("nonce"))
    return redirect("/")
Exemplo n.º 3
0
def setup():
    # with app.app_context():
        # admin = Teams.query.filter_by(admin=True).first()

    if not is_setup():
        if not session.get('nonce'):
            session['nonce'] = sha512(os.urandom(10))
        if request.method == 'POST':
            ctf_name = request.form['ctf_name']
            ctf_name = set_config('ctf_name', ctf_name)

            ## CSS
            css = set_config('start', '')

            ## Admin user
            name = request.form['name']
            email = request.form['email']
            password = request.form['password']
            admin = Teams(name, email, password)
            admin.admin = True
            admin.banned = True


            #max attempts per challenge
            max_tries = set_config("max_tries",0)

            ## Start time
            start = set_config('start', None)
            end = set_config('end', None)

            ## Challenges cannot be viewed by unregistered users
            view_challenges_unregistered = set_config('view_challenges_unregistered', None)

            ## Allow/Disallow registration
            prevent_registration = set_config('prevent_registration', None)

            ## Verify emails
            verify_emails = set_config('verify_emails', None)

            mail_server = set_config('mail_server', None)
            mail_port = set_config('mail_port', None)
            mail_tls = set_config('mail_tls', None)
            mail_ssl = set_config('mail_ssl', None)
            mail_username = set_config('mail_username', None)
            mail_password = set_config('mail_password', None)

            setup = set_config('setup', True)

            db.session.add(page)
            db.session.add(admin)
            db.session.commit()
            app.setup = False
            return redirect('/')
        return render_template('setup.html', nonce=session.get('nonce'))
    return redirect('/')
Exemplo n.º 4
0
    def setup():
        # with app.app_context():
            # admin = Teams.query.filter_by(admin=True).first()

        if not is_setup():
            if request.method == 'POST':
                ctf_name = request.form['ctf_name']
                ctf_name = Config('ctf_name', ctf_name)

                ## Admin user
                name = request.form['name']
                email = request.form['email']
                password = request.form['password']
                admin = Teams(name, email, password)
                admin.admin = True

                ## Index page
                html = request.form['html']
                page = Pages('index', html)

                ## Start time
                start = Config('start', None)
                end = Config('end', None)

                ## Challenges cannot be viewed by unregistered users
                view_challenges_unregistered = Config('view_challenges_unregistered', None)

                ## Allow/Disallow registration
                prevent_registration = Config('prevent_registration', None)

                setup = Config('setup', True)

                db.session.add(ctf_name)
                db.session.add(admin)
                db.session.add(page)
                db.session.add(start)
                db.session.add(end)
                db.session.add(view_challenges_unregistered)
                db.session.add(prevent_registration)
                db.session.add(setup)
                db.session.commit()
                app.setup = False
                return redirect('/')
            return render_template('setup.html')
        return redirect('/')
Exemplo n.º 5
0
            db.session.add(
                Challenges(get_name(x), get_desc(x), get_value(x),
                           get_category(x), get_hint(x)))
            db.session.commit()
            db.session.add(Keys(x, get_flag(x), 0))
            db.session.commit()
        db.session.close()
        # Generating Users
        print("Inserting users")
        for _ in xrange(50):
            user = random.choice(girls_names)
            girls_names.pop(girls_names.index(user))
            univ = random.choice(univ_names)
            year = random.choice([1, 4])
            db.session.add(
                Teams(user, univ[0], year, univ[1], "M", user,
                      user + '@gmail.com', user, "S"))

        for _ in xrange(50):
            user = random.choice(boys_names)
            boys_names.pop(boys_names.index(user))
            univ = random.choice(univ_names)
            year = random.choice([1, 4])
            db.session.add(
                Teams(user, univ[0], year, univ[1], "F", user,
                      user + '@gmail.com', user, "S"))

        for _ in xrange(5):
            user = random.choice(boys_names)
            boys_names.pop(boys_names.index(user))
            univ = random.choice(univ_names)
            db.session.add(
Exemplo n.º 6
0
def register():
    logger = logging.getLogger('regs')
    if not utils.can_register():
        return redirect(url_for('auth.login'))
    if request.method == 'POST':
        errors = []
        name = request.form['name']
        email = request.form['email']
        password = request.form['password']

        name_len = len(name) == 0
        names = Teams.query.add_columns('name',
                                        'id').filter_by(name=name).first()
        emails = Teams.query.add_columns('email',
                                         'id').filter_by(email=email).first()
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = utils.check_email_format(request.form['email'])
        team_name_email_check = utils.check_email_format(name)

        if not valid_email:
            errors.append("Please enter a valid email address")
        if names:
            errors.append('That team name is already taken')
        if team_name_email_check is True:
            errors.append('Your team name cannot be an email address')
        if emails:
            errors.append('That email has already been used')
        if pass_short:
            errors.append('Pick a longer password')
        if pass_long:
            errors.append('Pick a shorter password')
        if name_len:
            errors.append('Pick a longer team name')

        if len(errors) > 0:
            return render_template('register.html',
                                   errors=errors,
                                   name=request.form['name'],
                                   email=request.form['email'],
                                   password=request.form['password'])
        else:
            with app.app_context():
                team = Teams(name, email.lower(), password)
                db.session.add(team)
                db.session.commit()
                db.session.flush()

                session['username'] = team.name
                session['id'] = team.id
                session['admin'] = team.admin
                session['nonce'] = utils.sha512(os.urandom(10))

                if utils.can_send_mail() and utils.get_config(
                        'verify_emails'
                ):  # Confirming users is enabled and we can send email.
                    logger = logging.getLogger('regs')
                    logger.warn(
                        "[{date}] {ip} - {username} registered (UNCONFIRMED) with {email}"
                        .format(date=time.strftime("%m/%d/%Y %X"),
                                ip=utils.get_ip(),
                                username=request.form['name'].encode('utf-8'),
                                email=request.form['email'].encode('utf-8')))
                    utils.verify_email(team.email)
                    db.session.close()
                    return redirect(url_for('auth.confirm_user'))
                else:  # Don't care about confirming users
                    if utils.can_send_mail(
                    ):  # We want to notify the user that they have registered.
                        utils.sendmail(
                            request.form['email'],
                            "You've successfully registered for {}".format(
                                utils.get_config('ctf_name')))

        logger.warn(
            "[{date}] {ip} - {username} registered with {email}".format(
                date=time.strftime("%m/%d/%Y %X"),
                ip=utils.get_ip(),
                username=request.form['name'].encode('utf-8'),
                email=request.form['email'].encode('utf-8')))
        db.session.close()
        return redirect(url_for('challenges.challenges_view'))
    else:
        return render_template('register.html')
Exemplo n.º 7
0
def oauth_redirect():
    oauth_code = request.args.get("code")
    state = request.args.get("state")
    if session["nonce"] != state:
        log("logins", "[{date}] {ip} - OAuth State validation mismatch")
        error_for(endpoint="auth.login",
                  message="OAuth State validation mismatch.")
        return redirect(url_for("auth.login"))

    if oauth_code:
        url = (get_app_config("OAUTH_TOKEN_ENDPOINT")
               or get_config("oauth_token_endpoint")
               or "https://auth.majorleaguecyber.org/oauth/token")

        client_id = get_app_config("OAUTH_CLIENT_ID") or get_config(
            "oauth_client_id")
        client_secret = get_app_config("OAUTH_CLIENT_SECRET") or get_config(
            "oauth_client_secret")
        headers = {"content-type": "application/x-www-form-urlencoded"}
        data = {
            "code": oauth_code,
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
        }
        token_request = requests.post(url, data=data, headers=headers)

        if token_request.status_code == requests.codes.ok:
            token = token_request.json()["access_token"]
            user_url = (get_app_config("OAUTH_API_ENDPOINT")
                        or get_config("oauth_api_endpoint")
                        or "https://api.majorleaguecyber.org/user")

            headers = {
                "Authorization": "Bearer " + str(token),
                "Content-type": "application/json",
            }
            api_data = requests.get(url=user_url, headers=headers).json()

            user_id = api_data["id"]
            user_name = api_data[
                "username"]  #<---- CHANGE FOR DISCORD OAUTH FORMATTING
            user_email = api_data["email"]

            user = Users.query.filter_by(email=user_email).first()
            if user is None:
                # Check if we are allowing registration before creating users
                # if registration_visible(): # < - FIX FOR LHC DISCORD OAUTH TO ALLOW NEW USERS WITHOUT ALLOWING MANUAL REG
                user = Users(
                    name=user_name,
                    email=user_email,
                    oauth_id=user_id,
                    verified=True,
                )
                db.session.add(user)
                db.session.commit()
                #else: # < - FIX FOR LHC DISCORD OAUTH TO ALLOW NEW USERS VIA OAUTH BUT NOT USERNAME
                #    log("logins", "[{date}] {ip} - Public registration via MLC blocked")
                #    error_for(
                #        endpoint="auth.login",
                #        message="Public registration is disabled. Please try again later.",
                #    )
                #    return redirect(url_for("auth.login"))

            if get_config("user_mode") == TEAMS_MODE:
                team_id = api_data["team"]["id"]
                team_name = api_data["team"]["name"]

                team = Teams.query.filter_by(oauth_id=team_id).first()
                if team is None:
                    team = Teams(name=team_name,
                                 oauth_id=team_id,
                                 captain_id=user.id)
                    db.session.add(team)
                    db.session.commit()

                team.members.append(user)
                db.session.commit()

            if user.oauth_id is None:
                user.oauth_id = user_id
                user.verified = True
                db.session.commit()

            login_user(user)

            return redirect(url_for("challenges.listing"))
        else:
            log("logins", "[{date}] {ip} - OAuth token retrieval failure")
            error_for(endpoint="auth.login",
                      message="OAuth token retrieval failure.")
            return redirect(url_for("auth.login"))
    else:
        log("logins", "[{date}] {ip} - Received redirect without OAuth code")
        error_for(endpoint="auth.login",
                  message="Received redirect without OAuth code.")
        return redirect(url_for("auth.login"))
Exemplo n.º 8
0
Arquivo: auth.py Projeto: tsg-ut/CTFd
def oauth_redirect():
    oauth_code = request.args.get("code")
    state = request.args.get("state")
    if session["nonce"] != state:
        log("logins", "[{date}] {ip} - OAuth State validation mismatch")
        error_for(endpoint="auth.login",
                  message="OAuth State validation mismatch.")
        return redirect(url_for("auth.login"))

    if oauth_code:
        url = get_app_config("OAUTH_TOKEN_ENDPOINT") or get_config(
            "oauth_token_endpoint")

        client_id = get_app_config("OAUTH_CLIENT_ID") or get_config(
            "oauth_client_id")
        client_secret = get_app_config("OAUTH_CLIENT_SECRET") or get_config(
            "oauth_client_secret")
        headers = {"content-type": "application/x-www-form-urlencoded"}
        data = {
            "code": oauth_code,
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
        }
        token_request = requests.post(url, data=data, headers=headers)

        if token_request.status_code == requests.codes.ok:
            token = token_request.json()["access_token"]
            user_url = get_app_config("OAUTH_API_ENDPOINT") or get_config(
                "oauth_api_endpoint")

            headers = {
                "Authorization": "Bearer " + str(token),
                "Content-type": "application/json",
            }
            api_data = requests.get(url=user_url, headers=headers).json()

            user_id = api_data["id"]
            user_name = api_data["name"]
            user_email = api_data["email"]

            if user_email is None or len(user_email) == 0:
                error_for(
                    endpoint="auth.login",
                    message="Email field is empty. Please contact admin",
                )
                return redirect(url_for("auth.login"))

            user = Users.query.filter_by(email=user_email).first()
            if user is None:
                # Check if we are allowing registration before creating users
                if registration_visible() or oauth_registration():
                    user = Users(
                        name=user_name,
                        email=user_email,
                        oauth_id=user_id,
                        verified=True,
                    )
                    db.session.add(user)
                    db.session.commit()
                else:
                    log(
                        "logins",
                        "[{date}] {ip} - Public registration via OAuth blocked",
                    )
                    error_for(
                        endpoint="auth.login",
                        message=
                        "Public registration is disabled. Please try again later.",
                    )
                    return redirect(url_for("auth.login"))

            if get_config("user_mode") == TEAMS_MODE:
                team_id = api_data["team"]["id"]
                team_name = api_data["team"]["name"]

                team = Teams.query.filter_by(oauth_id=team_id).first()
                if team is None:
                    num_teams_limit = int(get_config("num_teams", default=0))
                    num_teams = Teams.query.filter_by(banned=False,
                                                      hidden=False).count()
                    if num_teams_limit and num_teams >= num_teams_limit:
                        abort(
                            403,
                            description=
                            f"Reached the maximum number of teams ({num_teams_limit}). Please join an existing team.",
                        )

                    team = Teams(name=team_name,
                                 oauth_id=team_id,
                                 captain_id=user.id)
                    db.session.add(team)
                    db.session.commit()
                    clear_team_session(team_id=team.id)

                team_size_limit = get_config("team_size", default=0)
                if team_size_limit and len(team.members) >= team_size_limit:
                    plural = "" if team_size_limit == 1 else "s"
                    size_error = "Teams are limited to {limit} member{plural}.".format(
                        limit=team_size_limit, plural=plural)
                    error_for(endpoint="auth.login", message=size_error)
                    return redirect(url_for("auth.login"))

                team.members.append(user)
                db.session.commit()

            if user.oauth_id is None:
                user.oauth_id = user_id
                user.verified = True
                db.session.commit()
                clear_user_session(user_id=user.id)

            login_user(user)

            return redirect(url_for("challenges.listing"))
        else:
            log("logins", "[{date}] {ip} - OAuth token retrieval failure")
            error_for(endpoint="auth.login",
                      message="OAuth token retrieval failure.")
            return redirect(url_for("auth.login"))
    else:
        log("logins", "[{date}] {ip} - Received redirect without OAuth code")
        error_for(endpoint="auth.login",
                  message="Received redirect without OAuth code.")
        return redirect(url_for("auth.login"))
Exemplo n.º 9
0
def setup():
    # with app.app_context():
    # admin = Teams.query.filter_by(admin=True).first()

    if not utils.is_setup():
        if not session.get('nonce'):
            session['nonce'] = utils.sha512(os.urandom(10))
        if request.method == 'POST':
            ctf_name = request.form['ctf_name']
            ctf_name = utils.set_config('ctf_name', ctf_name)

            # CSS
            css = utils.set_config('start', '')

            # Admin user
            name = request.form['name']
            email = request.form['email']
            password = request.form['password']
            admin = Teams(name, email, password)
            admin.admin = True
            admin.banned = True

            # Index page

            index = """<div class="row">
    <div class="col-md-6 offset-md-3">
        <img class="w-100 mx-auto d-block" style="max-width: 500px;padding: 50px;padding-top: 14vh;" src="themes/core/static/img/logo.png" />
        <h3 class="text-center">

        </h3>
        <br>
        <h4 class="text-center">
            <a href="admin">Click here</a> to login and setup your CTF
        </h4>
    </div>
</div>""".format(request.script_root)

            page = Pages(title=None, route='index', html=index, draft=False)

            # max attempts per challenge
            max_tries = utils.set_config('max_tries', 0)

            # Start time
            start = utils.set_config('start', None)
            end = utils.set_config('end', None)
            freeze = utils.set_config('freeze', None)

            # Challenges cannot be viewed by unregistered users
            view_challenges_unregistered = utils.set_config(
                'view_challenges_unregistered', None)

            # Allow/Disallow registration
            prevent_registration = utils.set_config('prevent_registration',
                                                    None)

            # Verify emails
            verify_emails = utils.set_config('verify_emails', None)

            mail_server = utils.set_config('mail_server', None)
            mail_port = utils.set_config('mail_port', None)
            mail_tls = utils.set_config('mail_tls', None)
            mail_ssl = utils.set_config('mail_ssl', None)
            mail_username = utils.set_config('mail_username', None)
            mail_password = utils.set_config('mail_password', None)
            mail_useauth = utils.set_config('mail_useauth', None)

            setup = utils.set_config('setup', True)

            db.session.add(page)
            db.session.add(admin)
            db.session.commit()

            session['username'] = admin.name
            session['id'] = admin.id
            session['admin'] = admin.admin
            session['nonce'] = utils.sha512(os.urandom(10))

            db.session.close()
            app.setup = False
            with app.app_context():
                cache.clear()

            return redirect(url_for('views.static_html'))
        return render_template('setup.html', nonce=session.get('nonce'))
    return redirect(url_for('views.static_html'))
Exemplo n.º 10
0
def setup():
    # with app.app_context():
        # admin = Teams.query.filter_by(admin=True).first()

    if not is_setup():
        if not session.get('nonce'):
            session['nonce'] = sha512(os.urandom(10))
        if request.method == 'POST':
            ctf_name = request.form['ctf_name']
            ctf_name = set_config('ctf_name', ctf_name)

            ## CSS
            css = set_config('start', '')

            ## Admin user
            name = request.form['name']
            email = request.form['email']
            schoolCode = '12345'
            password = request.form['password']
            admin = Teams(name, email, schoolCode, password)
            admin.admin = True
            admin.banned = True

            ## Index page
            page = Pages('index', """<div class="container main-container">
    <img class="logo" src="/static/img/logo.png" />
    <h3 class="text-center">
        Welcome to the <span class="main-name">NeverLAN CTF</span>
    </h3>

    <h4 class="text-center">
        <a href="/login">Click here</a> to login or <a href="/register">here</a> to register
    </h4>
</div>""")

            #max attempts per challenge
            max_tries = set_config("max_tries",0)

            ## Start time
            start = set_config('start', None)
            end = set_config('end', None)

            ## Challenges cannot be viewed by unregistered users
            view_challenges_unregistered = set_config('view_challenges_unregistered', None)

            ## Allow/Disallow registration
            prevent_registration = set_config('prevent_registration', None)

            ## Verify emails
            verify_emails = set_config('verify_emails', None)

            mail_server = set_config('mail_server', None)
            mail_port = set_config('mail_port', None)
            mail_tls = set_config('mail_tls', None)
            mail_ssl = set_config('mail_ssl', None)
            mail_username = set_config('mail_username', None)
            mail_password = set_config('mail_password', None)

            setup = set_config('setup', True)

            db.session.add(page)
            db.session.add(admin)
            db.session.commit()
            app.setup = False
            return redirect('/')
        return render_template('setup.html', nonce=session.get('nonce'))
    return redirect('/')
Exemplo n.º 11
0
            chal = random.randint(1, CHAL_AMOUNT)
            filename = gen_file()
            md5hash = hashlib.md5(filename.encode('utf-8')).hexdigest()
            db.session.add(Files(chal, md5hash + '/' + filename))

        db.session.commit()

        # Generating Users
        print("GENERATING USERS")
        used = []
        count = 0
        while count < USER_AMOUNT:
            name = gen_name()
            if name not in used:
                used.append(name)
                team = Teams(name,
                             name.lower() + gen_email(), 'password', '', '')
                team.verified = True
                db.session.add(team)
                count += 1

        db.session.commit()

        # Generating Solves
        print("GENERATING SOLVES")
        for x in range(USER_AMOUNT):
            used = []
            base_time = datetime.datetime.utcnow() + datetime.timedelta(
                minutes=-10000)
            for y in range(random.randint(1, CHAL_AMOUNT)):
                chalid = random.randint(1, CHAL_AMOUNT)
                if chalid not in used:
Exemplo n.º 12
0
            filename = gen_file()
            md5hash = hashlib.md5(filename).hexdigest()
            db.session.add(
                Files(chal, os.path.join('static/uploads', md5hash, filename)))
        db.session.commit()

        ### Generating Users
        print "GENERATING USERS"
        used = []
        count = 0
        while count < USER_AMOUNT:
            name = gen_name()
            if name not in used:
                used.append(name)
                db.session.add(
                    Teams(name,
                          name.lower() + gen_email(), 'password'))
                count += 1
        db.session.commit()

        ### Generating Solves
        print "GENERATING SOLVES"
        for x in range(USER_AMOUNT):
            used = []
            base_time = datetime.datetime.utcnow() + datetime.timedelta(
                minutes=-10000)
            for y in range(random.randint(1, CHAL_AMOUNT)):
                chalid = random.randint(1, CHAL_AMOUNT)
                if chalid not in used:
                    used.append(chalid)
                    solve = Solves(chalid, x + 1, '127.0.0.1', gen_word())
Exemplo n.º 13
0
    AMT_CHALS_WITH_FILES = int(CHAL_AMOUNT * (3.0/4.0))
    for x in range(AMT_CHALS_WITH_FILES):
        chal = random.randint(1, CHAL_AMOUNT)
        filename = gen_file()
        md5hash = hashlib.md5(filename).hexdigest()
        db.session.add( Files(chal, os.path.join('static/uploads', md5hash, filename)) )
    db.session.commit()

    ### Generating Users
    print "GENERATING USERS"
    used = []
    while len(used) < USER_AMOUNT:
        name = gen_name()
        if name not in used:
            used.append(name)
            db.session.add( Teams(name , name.lower() + gen_email(), 'password') )
    db.session.commit()
        
    ### Generating Solves
    print "GENERATING SOLVES"
    base_time = datetime.datetime.utcnow() + datetime.timedelta(minutes=-2880)
    for x in range(USER_AMOUNT):
        used = []
        for y in range(random.randint(1,CHAL_AMOUNT)):
            chalid = random.randint(1,CHAL_AMOUNT)
            if chalid not in used:
                used.append(chalid)
                solve = Solves(chalid, x+1, '127.0.0.1')

                new_base = random_date(base_time, base_time + datetime.timedelta(minutes=60))
                solve.date = new_base
Exemplo n.º 14
0
def login():
    logger = logging.getLogger('logins')
    if request.method == 'POST':
        errors = []
        name = request.form['name'].strip()
        password = request.form['password']

        # Check if email or password is empty
        if not name or not password:
            errors.append("Please enter your email and password")
            db.session.close()
            return render_template('login.html', errors=errors)

        # Check if the user submitted a valid email address
        if utils.check_email_format(name) is False:
            errors.append("Your email is not in a valid format")
            db.session.close()
            return render_template('login.html', errors=errors)

        # Send POST request to NCL SIO authentication API
        base64creds = base64.b64encode(name + ':' + password)
        headers = {'Authorization': 'Basic ' + base64creds}
        sio_url = utils.ncl_sio_url()

        try:
            r = requests.post(sio_url + '/authentications', headers=headers, timeout=30)
        except requests.exceptions.RequestException as e:
            logger.warn("[{date}] {ip} - error connecting to SIO authentication service: {exception}".format(
                date=time.strftime("%m/%d/%Y %X"),
                ip=utils.get_ip(),
                exception=e
            ))
            errors.append("There is a problem with your login request. Please contact the website administrator")
            db.session.close()
            return render_template('login.html', errors=errors)

        if r.status_code == 200:    # Successful login
            # Check if this user has permission to login (i.e. is in this CTF NCL team)
            ncl_team_name = utils.ncl_team_name()
            is_user_in_ncl_team = False
            user_id = r.json()['id']

            # Send GET request to NCL SIO teams API
            try:
                teams_r = requests.get(sio_url + '/teams?name=' + ncl_team_name, timeout=30)
            except requests.exceptions.RequestException as teams_re:
                logger.warn("[{date}] {ip} - error connecting to SIO teams service: {exception}".format(
                    date=time.strftime("%m/%d/%Y %X"),
                    ip=utils.get_ip(),
                    exception=teams_re
                ))
                errors.append("There is a problem with connecting to login service. Please contact the website administrator")
                db.session.close()
                return render_template('login.html', errors=errors)

            if teams_r.status_code == 200:  # teams GET success
                team_members = teams_r.json()['members']
                for member in team_members:
                    if member['userId'] == user_id:
                        is_user_in_ncl_team = True
                        break
            else:   # teams GET failed
                logger.warn("[{date}] {ip} - invalid response status code: {status}".format(
                    date=time.strftime("%m/%d/%Y %X"),
                    ip=utils.get_ip(),
                    status=str(teams_r.status_code)
                ))
                errors.append("Unknown response from login service. Please contact the website administrator")
                db.session.close()
                return render_template('login.html', errors=errors)

            if not is_user_in_ncl_team:
                # User is not part of NCL team, deny login!
                logger.warn("[{date}] {ip} - not in this CTF NCL team for {username}".format(
                    date=time.strftime("%m/%d/%Y %X"),
                    ip=utils.get_ip(),
                    username=name.encode('utf-8')
                ))
                errors.append("You do not have permissions to login to this site")
                db.session.close()
                return render_template('login.html', errors=errors)

            # User is now allowed to login

            # Try to get info from DB
            team = Teams.query.filter_by(email=name).first()

            # Add to DB if it does not exist
            if not team:
                team = Teams(name.lower(), name.lower(), "unused_password")
                db.session.add(team)
                db.session.commit()
                db.session.flush()
            
            # Get info from DB
            session['username'] = team.name
            session['id'] = team.id
            session['admin'] = team.admin
            session['nonce'] = utils.sha512(os.urandom(10))
            db.session.close()

            logger.warn("[{date}] {ip} - {username} logged in".format(
                date=time.strftime("%m/%d/%Y %X"),
                ip=utils.get_ip(),
                username=session['username'].encode('utf-8')
            ))

            if request.args.get('next') and utils.is_safe_url(request.args.get('next')):
                return redirect(request.args.get('next'))
            return redirect(url_for('challenges.challenges_view'))

        elif r.status_code == 404:  # This user does not exist
            logger.warn("[{date}] {ip} - submitted invalid user email".format(
                date=time.strftime("%m/%d/%Y %X"),
                ip=utils.get_ip()
            ))
            errors.append("Your email or password is incorrect")
            db.session.close()
            return render_template('login.html', errors=errors)

        elif r.status_code == 500:  # This user exists but the password is wrong
            logger.warn("[{date}] {ip} - submitted invalid password for {username}".format(
                date=time.strftime("%m/%d/%Y %X"),
                ip=utils.get_ip(),
                username=name.encode('utf-8')
            ))
            errors.append("Your email or password is incorrect")
            db.session.close()
            return render_template('login.html', errors=errors)

        else:   # Unknown response status code
            logger.warn("[{date}] {ip} - unknown response status code: {status}".format(
                date=time.strftime("%m/%d/%Y %X"),
                ip=utils.get_ip(),
                status=str(r.status_code)
            ))
            errors.append("Unknown login error. Please contact the website administrator")
            db.session.close()
            return render_template('login.html', errors=errors)

    else:
        db.session.close()
        return render_template('login.html')
Exemplo n.º 15
0
def register():
    logger = logging.getLogger('regs')
    if not utils.can_register():
        return redirect(url_for('auth.login'))
    if request.method == 'POST':
        errors = []
        name = request.form['name']
        email = request.form['email']
        password = request.form['password']
	number = request.form['number']

        name_len = len(name) == 0
        names = Teams.query.add_columns('name', 'id').filter_by(name=name).first()
        emails = Teams.query.add_columns('email', 'id').filter_by(email=email).first()
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", request.form['email'])
	valid_card = re.match(r"^2[1-3]\d{7}$",request.form['card'])
        valid_number = re.match(r"^\d{2}\w\d{5}$",request.form['number'])
        match = request.form['card'][4:6] == request.form['number'][4:6]


        if not valid_email:
            errors.append("That email doesn't look right")
        if names:
            errors.append('That team name is already taken')
        if emails:
            errors.append('That email has already been used')
        if pass_short:
            errors.append('Pick a longer password')
        if pass_long:
            errors.append('Pick a shorter password')
        if name_len:
            errors.append('Pick a longer team name')
	if (not valid_card) or (not valid_number):
            errors.append("The School Card or Student Number doesn't look right")
            if match:
                errors.append("The School Card or Student Number doesn't look right")

        if len(errors) > 0:
            return render_template('register.html', errors=errors, name=request.form['name'], email=request.form['email'], password=request.form['password'])
        else:
            with app.app_context():
                team = Teams(name, email.lower(), password,number)
                db.session.add(team)
                db.session.commit()
                db.session.flush()

                session['username'] = team.name
                session['id'] = team.id
                session['admin'] = team.admin
                session['nonce'] = utils.sha512(os.urandom(10))

                if utils.can_send_mail() and utils.get_config('verify_emails'):  # Confirming users is enabled and we can send email.
                    logger = logging.getLogger('regs')
                    logger.warn("[{date}] {ip} - {username} registered (UNCONFIRMED) with {email}".format(
                        date=time.strftime("%m/%d/%Y %X"),
                        ip=utils.get_ip(),
                        username=request.form['name'].encode('utf-8'),
                        email=request.form['email'].encode('utf-8')
                    ))
                    utils.verify_email(team.email)
                    db.session.close()
                    return redirect(url_for('auth.confirm_user'))
                else:  # Don't care about confirming users
                    if utils.can_send_mail():  # We want to notify the user that they have registered.
                        utils.sendmail(request.form['email'], "You've successfully registered for {}".format(utils.get_config('ctf_name')))

        logger.warn("[{date}] {ip} - {username} registered with {email}".format(
            date=time.strftime("%m/%d/%Y %X"),
            ip=utils.get_ip(),
            username=request.form['name'].encode('utf-8'),
            email=request.form['email'].encode('utf-8')
        ))
        db.session.close()
        return redirect(url_for('challenges.challenges_view'))
    else:
        return render_template('register.html')
Exemplo n.º 16
0
def setup():
    # with app.app_context():
    # admin = Teams.query.filter_by(admin=True).first()

    if not is_setup():
        if not session.get('nonce'):
            session['nonce'] = sha512(os.urandom(10))
        if request.method == 'POST':
            ctf_name = request.form['ctf_name']
            ctf_name = set_config('ctf_name', ctf_name)

            ## CSS
            css = set_config('start', '')

            ## Admin user
            name = request.form['name']
            email = request.form['email']
            password = request.form['password']
            admin = Teams(name, email, password)
            admin.admin = True
            admin.banned = True

            ## Index page
            page = Pages(
                'index', """<div class="container main-container">
    <img class="logo" src="{0}/static/original/img/logo.jpg" />
    <h3 class="text-center">
        Welcome to pogTeam's recruiting CTF! Keep in touch through our IRC chan ##pogTeam (freenode) or our <a href="https://t.me/pogTeamPublico">Telegram chan</a>!
    </h3>

    <h4 class="text-center">
        <a href="{0}/admin">Click here</a> to login and setup your CTF
    </h4>
</div>""".format(request.script_root))

            #max attempts per challenge
            max_tries = set_config("max_tries", 0)

            ## Start time
            start = set_config('start', None)
            end = set_config('end', None)

            ## Challenges cannot be viewed by unregistered users
            view_challenges_unregistered = set_config(
                'view_challenges_unregistered', None)

            ## Allow/Disallow registration
            prevent_registration = set_config('prevent_registration', None)

            ## Verify emails
            verify_emails = set_config('verify_emails', None)

            mail_server = set_config('mail_server', None)
            mail_port = set_config('mail_port', None)
            mail_tls = set_config('mail_tls', None)
            mail_ssl = set_config('mail_ssl', None)
            mail_username = set_config('mail_username', None)
            mail_password = set_config('mail_password', None)

            setup = set_config('setup', True)

            db.session.add(page)
            db.session.add(admin)
            db.session.commit()
            db.session.close()
            app.setup = False
            with app.app_context():
                cache.clear()
            return redirect(url_for('views.static_html'))
        return render_template('setup.html', nonce=session.get('nonce'))
    return redirect(url_for('views.static_html'))
Exemplo n.º 17
0
def setup():
    # with app.app_context():
    # admin = Teams.query.filter_by(admin=True).first()

    if not utils.is_setup():
        if not session.get('nonce'):
            session['nonce'] = utils.sha512(os.urandom(10))
        if request.method == 'POST':
            ctf_name = request.form['ctf_name']
            ctf_name = utils.set_config('ctf_name', ctf_name)

            # CSS
            css = utils.set_config('start', '')

            # Admin user
            name = request.form['name']
            email = request.form['email']
            password = request.form['password']
            admin = Teams(name, email, password)
            admin.admin = True
            admin.banned = True

            # Index page

            index = """<div class="row">
  <style>
   .col-container:after { content: ""; display: table; clear: both; }
   .col { float: left; }
   .clearfix::after {
  content: "";
  display: table;
  clear: both;
    }
    .footer-nav{
      float: left;
    }
    .logo{
      float: right;
    }
    .footer-nav,
    .footer-nav li{
      display: inline;
    }
  </style>
  <div class="col-md-6 offset-md-3">
<h1 class="text-center" style="padding-top: 10vh; font-size: 50px;">
    <b>Haaukins</b>
</h1>
<p class="text-center">
    A platform for Cyber Security Exercises 
</p>
<p class="text-center">
    Founded by <a href="http://danishcybersecurityclusters.dk/">Danish Cyber Security Clusters</a> and supported by
</p>
<a href="https://www.industriensfond.dk/">
    <img class="w-100 mx-auto d-block" style="max-width: 300px; padding: 3vh 0 4vh 0;" src="/themes/core/static/img/logo_industrienfond.jpg">
</a>
<p class="text-center">
    <p class="text-center">
  Developed at <a href="http://es.aau.dk/">Aalborg University</a> (Department of Electronic Systems) by:
    </p>
    <div class="col-container" style="margin-top: 40px;">
  <div class="col" style="width: 40%">
          <img src="/themes/core/static/img/haaukins_logo_blue240px.png" style="margin-left: 20px; max-width: 170px;">
    </div>
  <div class="col" style="width: 60%; font-size:14px;">
      <p><a href="https://mrturkmen.com">Ahmet Turkmen</a> (Research Assistant)</p>
      <p><a href="https://github.com/eyJhb">Gian Marco Mennecozzi</a> (Research Assistant)</p>
      <p><a href="https://github.com/kdhageman">Kaspar Hageman</a> (Ph.D. Student)</p>
      <p><a href="https://github.com/tpanum">Thomas Kobber Panum</a> (Ph.D. Student)</p>
      <p><a href="https://github.com/eyJhb">Johan Hempel Bengtson</a> (Student Helper)</p>
    </div>
    </div>
</p>
<div class="card-deck py-4">
      <div class="card">
          <div class="card-body">
              <h5 class="card-title">Tips and tricks</h5>
              <div class="card-text">
                  Stuck at a certain challenge? Or do you just want to know more about a certain topic?
              </div>
          </div>
          <div class="card-footer">
              <a href="https://aau-network-security.github.io/tips-and-tricks/" target="_blank">Vist the tips & tricks page</a>
          </div>
      </div>
      <div class="card">
          <div class="card-body">
              <h5 class="card-title">Survey</h5>
              <p>You can help us improve the platform by taking our survey to let us know about your experiences!</p>
          </div>
          <div class="card-footer">
              <a href="https://www.survey-xact.dk/LinkCollector?key=KDRVSTDJJN15" target="_blank">Fill out the survey here</a>
          </div>
      </div>
  </div>
<p class="text-center">
    Feel free to join our local Facebook Group:
</p>
<p class="text-center">
    <a href="https://www.facebook.com/groups/957517617737780"><i class="fab fa-facebook" aria-hidden="true"></i>&nbsp;AAU Hackers &amp; Friends</a>
</p>
  <div class="container">
      <footer>
          <ul class="footer-nav">
              <li><a href="https://eadania.dk/"> <img src="/themes/core/static/img/da-90.png" style= "width:90px; height:75px;" ></a></li>
              <li><a href="https://www.dtu.dk/"><img src="/themes/core/static/img/dtu-90.png" style= "width:90px; height:75px;"></a></li>
              <li><a href="https://kea.dk/"> <img src="/themes/core/static/img/kea-90.jpg" style= "width:90px; height:75px;" ></a></li>
              <li><a href="https://happy42.dk/"> <img src="/themes/core/static/img/happy-90.png" style= "width:90px; height:75px;" ></a></li>
               <li><a href="https://www.eaaa.dk/"><img src="/themes/core/static/img/eaa-90.png" style= "width:90px; height:75px;"></a></li>
         </ul>
      </footer>
      </div>
  </div>    
</div>"""

            page = Pages(title=None, route='index', html=index, draft=False)

            # max attempts per challenge
            max_tries = utils.set_config('max_tries', 0)

            # Start time
            start = utils.set_config('start', None)
            end = utils.set_config('end', None)
            freeze = utils.set_config('freeze', None)

            # Challenges cannot be viewed by unregistered users
            view_challenges_unregistered = utils.set_config(
                'view_challenges_unregistered', None)

            # Allow/Disallow registration
            prevent_registration = utils.set_config('prevent_registration',
                                                    None)

            # Verify emails
            verify_emails = utils.set_config('verify_emails', None)

            mail_server = utils.set_config('mail_server', None)
            mail_port = utils.set_config('mail_port', None)
            mail_tls = utils.set_config('mail_tls', None)
            mail_ssl = utils.set_config('mail_ssl', None)
            mail_username = utils.set_config('mail_username', None)
            mail_password = utils.set_config('mail_password', None)
            mail_useauth = utils.set_config('mail_useauth', None)

            setup = utils.set_config('setup', True)

            db.session.add(page)
            db.session.add(admin)
            db.session.commit()

            session['username'] = admin.name
            session['id'] = admin.id
            session['admin'] = admin.admin
            session['nonce'] = utils.sha512(os.urandom(10))

            db.session.close()
            app.setup = False
            with app.app_context():
                cache.clear()

            return redirect(url_for('views.static_html'))
        return render_template('setup.html', nonce=session.get('nonce'))
    return redirect(url_for('views.static_html'))
Exemplo n.º 18
0
    def oauth_redirect():
        oauth_code = request.args.get("code")
        state = request.args.get("state")
        if session["nonce"] != state:
            log("logins", "[{date}] {ip} - OAuth State validation mismatch")
            error_for(endpoint="auth.login",
                      message="OAuth State validation mismatch.")
            return redirect(url_for("auth.login"))

        if oauth_code:
            url = (get_app_config("REDDIT_TOKEN_ENDPOINT")
                   or get_config("reddit_token_endpoint")
                   or "https://ssl.reddit.com/api/v1/access_token")

            client_id = get_app_config("REDDIT_CLIENT_ID") or get_config(
                "reddit_client_id")
            client_secret = get_app_config(
                "REDDIT_CLIENT_SECRET") or get_config("reddit_client_secret")
            reddit_user_agent = get_app_config(
                "REDDIT_USER_AGENT") or get_config("reddit_user_agent")
            callback_url = get_app_config("REDDIT_CALLBACK_URL") or get_config(
                "reddit_callback_url")
            client_auth = requests.auth.HTTPBasicAuth(client_id, client_secret)

            headers = {
                "content-type": "application/x-www-form-urlencoded",
                "User-Agent": reddit_user_agent
            }

            token_request = requests.post(url,
                                          auth=client_auth,
                                          data={
                                              "grant_type":
                                              "authorization_code",
                                              "code": oauth_code,
                                              "redirect_uri": callback_url
                                          },
                                          headers=headers)

            if token_request.status_code == requests.codes.ok:
                token = token_request.json()["access_token"]
                user_url = (get_app_config("REDDIT_API_ENDPOINT")
                            or get_config("reddit_api_endpoint")
                            or "https://oauth.reddit.com/api/v1/me")

                headers = {
                    "Authorization": "Bearer " + str(token),
                    "User-Agent": reddit_user_agent
                }
                api_response = requests.get(url=user_url, headers=headers)
                log("logins", str(api_response))
                api_data = api_response.json()

                user_id = api_data["id"]
                user_name = api_data["name"]
                user_email = api_data["name"] + "@reddit.com"

                user = Users.query.filter_by(name=user_name).first()
                if user is None:
                    # Check if we are allowing registration before creating users
                    if registration_visible():
                        user = Users(
                            name=user_name,
                            email=user_email,
                            oauth_id=user_id,
                            verified=True,
                        )
                        db.session.add(user)
                        db.session.commit()
                    else:
                        log(
                            "logins",
                            "[{date}] {ip} - Public registration via Reddit blocked"
                        )
                        error_for(
                            endpoint="auth.login",
                            message=
                            "Public registration is disabled. Please try again later.",
                        )
                        return redirect(url_for("auth.login"))

                if get_config("user_mode") == TEAMS_MODE:
                    team_id = api_data["team"]["id"]
                    team_name = api_data["team"]["name"]

                    team = Teams.query.filter_by(oauth_id=team_id).first()
                    if team is None:
                        team = Teams(name=team_name,
                                     oauth_id=team_id,
                                     captain_id=user.id)
                        db.session.add(team)
                        db.session.commit()

                    team_size_limit = get_config("team_size", default=0)
                    if team_size_limit and len(
                            team.members) >= team_size_limit:
                        plural = "" if team_size_limit == 1 else "s"
                        size_error = "Teams are limited to {limit} member{plural}.".format(
                            limit=team_size_limit, plural=plural)
                        error_for(endpoint="auth.login", message=size_error)
                        return redirect(url_for("auth.login"))

                    team.members.append(user)
                    db.session.commit()

                if user.oauth_id is None:
                    user.oauth_id = user_id
                    user.verified = True
                    db.session.commit()

                login_user(user)

                return redirect(url_for("challenges.listing"))
            else:
                log("logins", "[{date}] {ip} - OAuth token retrieval failure")
                log("logins", str(token_request))
                log("logins", str(token_request.status_code))
                log("logins", token_request.json()["access_token"])
                error_for(endpoint="auth.login",
                          message="OAuth token retrieval failure.")
                return redirect(url_for("auth.login"))
        else:
            log("logins",
                "[{date}] {ip} - Received redirect without OAuth code")
            error_for(endpoint="auth.login",
                      message="Received redirect without OAuth code.")
            return redirect(url_for("auth.login"))
Exemplo n.º 19
0
def setup():
    # with app.app_context():
    # admin = Teams.query.filter_by(admin=True).first()

    if not utils.is_setup():
        if not session.get('nonce'):
            session['nonce'] = utils.sha512(os.urandom(10))
        if request.method == 'POST':
            ctf_name = request.form['ctf_name']
            ctf_name = utils.set_config('ctf_name', ctf_name)

            # CSS
            css = utils.set_config('start', '')

            # Admin user
            name = request.form['name']
            email = request.form['email']
            password = request.form['password']
            admin = Teams(name, email, password)
            admin.admin = True
            admin.banned = True

            # Index page

            index = """<div class="row">
                <div class="intro">
                    <img width=30 src="themes/arg/static/img/logo.png" />
                    <br>
                    <br>
                    <p>
                        the console will set you free
                    </p>
                    <script>
                        console_message('ef98fe223e630bbb82dd9c41323e3290')
                    </script>
                    <br>
                </div>
            </div>""".format(request.script_root)

            page = Pages(title=None, route='index', html=index, draft=False)

            # max attempts per challenge
            max_tries = utils.set_config('max_tries', 0)

            # Start time
            start = utils.set_config('start', None)
            end = utils.set_config('end', None)
            freeze = utils.set_config('freeze', None)

            # Challenges cannot be viewed by unregistered users
            view_challenges_unregistered = utils.set_config(
                'view_challenges_unregistered', None)

            # Allow/Disallow registration
            prevent_registration = utils.set_config('prevent_registration',
                                                    None)

            # Verify emails
            verify_emails = utils.set_config('verify_emails', None)

            mail_server = utils.set_config('mail_server', None)
            mail_port = utils.set_config('mail_port', None)
            mail_tls = utils.set_config('mail_tls', None)
            mail_ssl = utils.set_config('mail_ssl', None)
            mail_username = utils.set_config('mail_username', None)
            mail_password = utils.set_config('mail_password', None)
            mail_useauth = utils.set_config('mail_useauth', None)

            setup = utils.set_config('setup', True)

            db.session.add(page)
            db.session.add(admin)
            db.session.commit()

            session['username'] = admin.name
            session['id'] = admin.id
            session['admin'] = admin.admin
            session['nonce'] = utils.sha512(os.urandom(10))

            db.session.close()
            app.setup = False
            with app.app_context():
                cache.clear()

            return redirect(url_for('views.static_html'))
        return render_template('setup.html', nonce=session.get('nonce'))
    return redirect(url_for('views.static_html'))
Exemplo n.º 20
0
            db.session.add(section)
            count += 1

        db.session.commit()

        # Generating Teams
        print("GENERATING TEAMS")
        used = []
        count = 0
        teamIDS = []
        while count < TEAMS_AMOUNT:
            name = gen_team_name()
            if name not in used:
                used.append(name)
                sectNum = get_sect_number()
                team = Teams(name, sectNum)
                db.session.add(team)
                count += 1
                teamIDS.append(sectNum)

        db.session.commit()

        # Generating Users
        print("GENERATING USERS")
        used = []
        count = 0
        while count < USER_AMOUNT:
            name = gen_name()
            if name not in used:
                used.append(name)
                teamid = random.randrange(1, TEAMS_AMOUNT + 1)
Exemplo n.º 21
0
def new():
    infos = get_infos()
    errors = get_errors()

    user = get_current_user_attrs()
    if user.team_id:
        errors.append("You are already in a team. You cannot join another.")

    if request.method == "GET":
        team_size_limit = get_config("team_size", default=0)
        if team_size_limit:
            plural = "" if team_size_limit == 1 else "s"
            infos.append("Teams are limited to {limit} member{plural}".format(
                limit=team_size_limit, plural=plural))
        return render_template("teams/new_team.html",
                               infos=infos,
                               errors=errors)

    elif request.method == "POST":
        teamname = request.form.get("name", "").strip()
        passphrase = request.form.get("password", "").strip()

        website = request.form.get("website")
        affiliation = request.form.get("affiliation")

        user = get_current_user()

        existing_team = Teams.query.filter_by(name=teamname).first()
        if existing_team:
            errors.append("That team name is already taken")
        if not teamname:
            errors.append("That team name is invalid")

        # Process additional user fields
        fields = {}
        for field in TeamFields.query.all():
            fields[field.id] = field

        entries = {}
        for field_id, field in fields.items():
            value = request.form.get(f"fields[{field_id}]", "").strip()
            if field.required is True and (value is None or value == ""):
                errors.append("Please provide all required fields")
                break

            # Handle special casing of existing profile fields
            if field.name.lower() == "affiliation":
                affiliation = value
                break
            elif field.name.lower() == "website":
                website = value
                break

            if field.field_type == "boolean":
                entries[field_id] = bool(value)
            else:
                entries[field_id] = value

        if website:
            valid_website = validators.validate_url(website)
        else:
            valid_website = True

        if affiliation:
            valid_affiliation = len(affiliation) < 128
        else:
            valid_affiliation = True

        if valid_website is False:
            errors.append(
                "Websites must be a proper URL starting with http or https")
        if valid_affiliation is False:
            errors.append("Please provide a shorter affiliation")

        if errors:
            return render_template("teams/new_team.html", errors=errors), 403

        team = Teams(name=teamname, password=passphrase, captain_id=user.id)

        if website:
            team.website = website
        if affiliation:
            team.affiliation = affiliation

        db.session.add(team)
        db.session.commit()

        for field_id, value in entries.items():
            entry = TeamFieldEntries(field_id=field_id,
                                     value=value,
                                     team_id=team.id)
            db.session.add(entry)
        db.session.commit()

        user.team_id = team.id
        db.session.commit()

        clear_user_session(user_id=user.id)
        clear_team_session(team_id=team.id)

        return redirect(url_for("challenges.listing"))
Exemplo n.º 22
0
def invite():
    infos = get_infos()
    errors = get_errors()
    code = request.args.get("code")

    if code is None:
        abort(404)

    user = get_current_user_attrs()
    if user.team_id:
        errors.append("You are already in a team. You cannot join another.")

    try:
        team = Teams.load_invite_code(code)
    except TeamTokenExpiredException:
        abort(403, description="This invite URL has expired")
    except TeamTokenInvalidException:
        abort(403, description="This invite URL is invalid")

    team_size_limit = get_config("team_size", default=0)

    if request.method == "GET":
        if team_size_limit:
            infos.append("Teams are limited to {limit} member{plural}".format(
                limit=team_size_limit,
                plural=pluralize(number=team_size_limit)))

        return render_template("teams/invite.html",
                               team=team,
                               infos=infos,
                               errors=errors)

    if request.method == "POST":
        if errors:
            return (
                render_template("teams/invite.html",
                                team=team,
                                infos=infos,
                                errors=errors),
                403,
            )

        if team_size_limit and len(team.members) >= team_size_limit:
            errors.append(
                "{name} has already reached the team size limit of {limit}".
                format(name=team.name, limit=team_size_limit))
            return (
                render_template("teams/invite.html",
                                team=team,
                                infos=infos,
                                errors=errors),
                403,
            )

        user = get_current_user()
        user.team_id = team.id
        db.session.commit()

        clear_user_session(user_id=user.id)
        clear_team_session(team_id=team.id)

        return redirect(url_for("challenges.listing"))
Exemplo n.º 23
0
def load_teams_csv(dict_reader):
    for line in dict_reader:
        result = Teams(**line)
        db.session.add(result)
        db.session.commit()
    return True
Exemplo n.º 24
0
def admin_create_team_custom():
    name = request.form.get('name', None)
    password = request.form.get('password', None)
    email = request.form.get('email', None)
    color = request.form.get('color', None)
    image = request.form.get('image', None)
    school = request.form.get('school', None)
    if not color in teamColors:
        color = "RED"
    if not image in teamImages:
        image = "HULK"

    admin_user = True if request.form.get('admin', None) == 'on' else False
    verified = True if request.form.get('verified', None) == 'on' else False
    hidden = True if request.form.get('hidden', None) == 'on' else False

    smart_color = SmartCityTeam.query.add_columns('color').filter_by(
        color=color).first()
    smart_image = SmartCityTeam.query.add_columns('image').filter_by(
        image=image).first()

    errors = []

    if not name:
        errors.append('The team requires a name')
    elif Teams.query.filter(Teams.name == name).first():
        errors.append('That name is taken')

    if utils.check_email_format(name) is True:
        errors.append('Team name cannot be an email address')

    if not email:
        errors.append('The team requires an email')
    elif Teams.query.filter(Teams.email == email).first():
        errors.append('That email is taken')

    if email:
        valid_email = utils.check_email_format(email)
        if not valid_email:
            errors.append("That email address is invalid")

    if not password:
        errors.append('The team requires a password')

    if smart_color:
        errors.append('Color was taken. Available Colors: ' +
                      getAvailableColors())
    if smart_image:
        errors.append('Imagge already taken')
    if errors:
        db.session.close()
        return jsonify({'data': errors})

    team = Teams(name, email, password)

    #team.website = website
    #team.affiliation = affiliation
    #team.country = country

    team.admin = admin_user
    team.verified = verified
    team.hidden = hidden

    db.session.add(team)
    db.session.commit()

    smart_team = SmartCityTeam(team.id, name, color, image, school)
    db.session.add(smart_team)
    db.session.commit()
    db.session.close()

    return jsonify({'data': ['success']})
Exemplo n.º 25
0
def setup():
    # with app.app_context():
        # admin = Teams.query.filter_by(admin=True).first()

    if not is_setup():
        if not session.get('nonce'):
            session['nonce'] = sha512(os.urandom(10))
        if request.method == 'POST':
            ctf_name = request.form['ctf_name']
            ctf_name = Config('ctf_name', ctf_name)

            ## CSS
            css = Config('start', '')

            ## Admin user
            name = request.form['name']
            email = request.form['email']
            password = request.form['password']
            admin = Teams(name, email, password)
            admin.admin = True
            admin.banned = True

            ## Index page
            html = request.form['html']
            page = Pages('index', html)

            #max attempts per challenge
            max_tries = Config("max_tries",0)


            ## Start time
            start = Config('start', None)
            end = Config('end', None)

            ## Challenges cannot be viewed by unregistered users
            view_challenges_unregistered = Config('view_challenges_unregistered', None)

            ## Allow/Disallow registration
            prevent_registration = Config('prevent_registration', None)

            setup = Config('setup', True)

            evidence = [
                ["sample1", "Encrypted Zip", "{N3xt_l3v3l_encryption}"],
                ["sample2", "Caesar Cipher Sample", "{c1pherz_are_kewl}"],
                ["police_profile", "Police Profile", "{and_so_1t_begins}"],
                ["caesar_cipher", "Phone Pattern Clue", "{i_love_caesar_sal4ds}"],
                ["gesture_key_hash", "Gesture Key Hash", "{they_were_to0_young_to_d1e}"],
                ["victims_contacts", "Victim's Contacts", "{I_just_w4nt_To_phone_home}"],
                ["victims_history", "Victim's History", "{Back_to_the_H1story}"],
                ["sd_card", "SD Card", "{m0unting_has_never_b33n_3asier}"],
                ["sd_card_hidden", "SD Card Hidden Image", "{h1dden_files_4re_soooooo_s3cret}"],
                ["sd_card_deleted", "SD Card Deleted Image", "{ur_da7a_doesnt_go_away}"],
                ["agents_wallet", "Agents Wallet", "{h3_h3_m3_c01n5_1n_B175}"],
                ["emails", "Victim's Emails", "{7his_15_n0t_th3_3m41l_u_w4nt}"],
                ["hacktivists_website", "Hacktivist's Website", "{t3h_h4ckers_sp4c3}"],
                ["consulting_company_it_portal", "Consulting Company IT Portal", "{SYS_4DM11111111N_P0RTAAAAL}"],
                ["hacktivists_login", "Hacktivist Login", "{h4ck3r5_log1n_700}"],
                ["voting_database_corrupt", "Voting Database", "{17_corrup73d_:-(}"],
                ["personnel_database", "Personnel Database", "{4uthor1zed_per50nnel_0nly}"],
                ["hacktivists_pcap", "Hacktivist's PCAP", "{much_sh3llsh0ck_m4ny_pack3t_7oo_FTP}"],
                ["encrypted_zip", "Encrypted Zip", "{7ooo_much_Encryption_b4d_four_health}"],
                ["construct_qr", "Construct QR Code", "{carpet_weaving_grandmaster}"],
                ["irc_logs", "IRC Logs", "{700_much_3ncrypted_1337_sp3ak}"]
            ]

            for e in evidence:
                exec "{0} = Evidence(\"{1}\", \"{2}\")".format(e[0], e[1], e[2])
                db.session.add(eval(e[0]))
            db.session.commit()

            '''
            connections = [
                [police_profile, victims_phone],
                [police_profile, sd_card],
                [victims_phone, agents_wallet],
                [victims_phone, emails],
                [victims_phone, browser_history],
                [victims_phone, contacts],
                [browser_history, hacktivists_website],
                [browser_history, consulting_company_it_portal],
                [hacktivists_website, hacktivists_login],
                [hacktivists_login, seeded_torrent],
                [hacktivists_login, irc_logs],
                [seeded_torrent, stolen_personnel_database],
                [seeded_torrent, stolen_voting_database],
                [seeded_torrent, hacktivists_pcap],
                [irc_logs, seeded_torrent],
                [consulting_company_it_portal, voting_database_corrupt],
                [consulting_company_it_portal, personnel_database]
            ]

            for c in connections:
                c = [_.eid for _ in c]
                db.session.add(EvidenceConnection(*c))
            db.session.commit()
            '''

            db.session.add(ctf_name)
            db.session.add(admin)
            db.session.add(page)
            db.session.add(max_tries)
            db.session.add(start)
            db.session.add(end)
            db.session.add(view_challenges_unregistered)
            db.session.add(prevent_registration)
            db.session.add(css)
            db.session.add(setup)
            db.session.commit()
            app.setup = False
            return redirect('/')
        print(session.get('nonce'))
        return render_template('setup.html', nonce=session.get('nonce'))
    return redirect('/')
Exemplo n.º 26
0
def private_register():
    if not utils.can_register():
        return redirect(url_for('auth.login'))
    if request.method == 'POST':
        selected_option = utils.get_config('private_registration_option')

        errors = []

        if selected_option == 'token':
            token = request.form['token']
            invited_team = InvitedTeams.query.add_columns(
                'name', 'email').filter_by(token=token).first()
            if not invited_team:
                errors.append('Invalid token')
        elif selected_option == 'email':
            email = request.form['email']
            invited_team = InvitedTeams.query.add_columns(
                'name', 'email').filter_by(email=email).first()
            if not invited_team:
                errors.append('Your email is not invited')
        else:
            errors.append('Something strange happened')

        if len(errors) == 0:
            team = Teams.query.add_columns('id').filter_by(
                name=invited_team.name).first()
            if team:
                errors.append('Already registered')

        password = request.form['password']

        pass_short = len(password) == 0
        pass_long = len(password) > 128

        if pass_short:
            errors.append('Pick a longer password')
        if pass_long:
            errors.append('Pick a shorter password')

        if len(errors) > 0:
            if selected_option == 'token':
                return render_template('register.html',
                                       errors=errors,
                                       token=request.form['token'],
                                       password=request.form['password'])
            elif selected_option == 'email':
                return render_template('register.html',
                                       errors=errors,
                                       email=request.form['email'],
                                       password=request.form['password'])
            else:
                return render_template('register.html')
        else:
            with app.app_context():
                name = invited_team.name
                email = invited_team.email
                team = Teams(name, email.lower(), password)
                db.session.add(team)
                db.session.commit()
                db.session.flush()

                session['username'] = team.name
                session['id'] = team.id
                session['admin'] = team.admin
                session['nonce'] = utils.sha512(urandom(10))

                if (utils.can_send_mail()
                        and utils.get_config('verify_emails')):
                    db.session.close()
                    logger = logging.getLogger('regs')
                    logger.warn('[{0}] {1} registered (UNCONFIRMED) ' \
                                'with {2}'.format(
                                    time.strftime('%m/%d/%Y %X'),
                                    name.encode('utf-8'),
                                    email.encode('utf-8')))

                    utils.verify_email(team.email)

                    return redirect(url_for('auth.confirm_user'))
                else:
                    if utils.can_send_mail():
                        utils.sendmail(email, "You've successfully " \
                                       "registered for {}".format(
                                           utils.get_config('ctf_name')))

        db.session.close()

        logger = logging.getLogger('regs')
        logger.warn('[{0}] {1} registered with {2}'.format(
            time.strftime('%m/%d/%Y %X'), name.encode('utf-8'),
            email.encode('utf-8')))
        return redirect(url_for('challenges.challenges_view'))
    else:
        return render_template('register.html')
Exemplo n.º 27
0
def oauth_redirect():
    oauth_code = request.args.get("code")
    state = request.args.get("state")
    if session["nonce"] != state:
        log("logins", "[{date}] {ip} - OAuth State validation mismatch")
        error_for(endpoint="auth.login",
                  message="OAuth State validation mismatch.")
        return redirect(url_for("auth.login"))

    if oauth_code:
        url = (get_app_config("OAUTH_TOKEN_ENDPOINT")
               or get_config("oauth_token_endpoint")
               or "https://auth.majorleaguecyber.org/oauth/token")

        client_id = get_app_config("OAUTH_CLIENT_ID") or get_config(
            "oauth_client_id")
        client_secret = get_app_config("OAUTH_CLIENT_SECRET") or get_config(
            "oauth_client_secret")
        headers = {"content-type": "application/x-www-form-urlencoded"}
        data = {
            "code": oauth_code,
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
        }
        token_request = requests.post(url, data=data, headers=headers)
        print(token_request.text)
        if token_request.status_code == requests.codes.ok:
            token = token_request.json()["access_token"]
            user_url = (get_app_config("OAUTH_API_ENDPOINT")
                        or get_config("oauth_api_endpoint")
                        or "https://api.majorleaguecyber.org/user")

            headers = {
                "Authorization": "Bearer " + str(token),
                "Content-type": "application/json",
            }
            api_data = requests.get(url=user_url, headers=headers).json()
            print('>', api_data)
            user_id = api_data["id"]
            user_name = api_data["username"]
            user_email = api_data["email"]

            user = Users.query.filter_by(email=user_email).first()
            if user is None:
                # Check if we are allowing registration before creating users
                if registration_visible() or mlc_registration():
                    user = Users(
                        name=user_name,
                        email=user_email,
                        oauth_id=user_id,
                        verified=True,
                    )
                    db.session.add(user)
                    db.session.commit()
                else:
                    log("logins",
                        "[{date}] {ip} - Public registration via MLC blocked")
                    error_for(
                        endpoint="auth.login",
                        message=
                        "Public registration is disabled. Please try again later.",
                    )
                    return redirect(url_for("auth.login"))

            if get_config("user_mode") == TEAMS_MODE:
                team_id = api_data["team"]["id"]
                team_name = api_data["team"]["name"]

                team = Teams.query.filter_by(oauth_id=team_id).first()
                if team is None:
                    team = Teams(name=team_name,
                                 oauth_id=team_id,
                                 captain_id=user.id)
                    db.session.add(team)
                    db.session.commit()

                team_size_limit = get_config("team_size", default=0)
                if team_size_limit and len(team.members) >= team_size_limit:
                    plural = "" if team_size_limit == 1 else "s"
                    size_error = "Teams are limited to {limit} member{plural}.".format(
                        limit=team_size_limit, plural=plural)
                    error_for(endpoint="auth.login", message=size_error)
                    return redirect(url_for("auth.login"))

                team.members.append(user)
                db.session.commit()

            if user.oauth_id is None:
                user.oauth_id = user_id
                user.verified = True
                db.session.commit()

            login_user(user)

            return redirect(url_for("challenges.listing"))
        else:
            log("logins", "[{date}] {ip} - OAuth token retrieval failure")
            error_for(endpoint="auth.login",
                      message="OAuth token retrieval failure.")
            return redirect(url_for("auth.login"))
    else:
        log("logins", "[{date}] {ip} - Received redirect without OAuth code")
        error_for(endpoint="auth.login",
                  message="Received redirect without OAuth code.")
        return redirect(url_for("auth.login"))
Exemplo n.º 28
0
                challenge_id=chal, location=md5hash + "/" + filename
            )
            db.session.add(chal_file)

        db.session.commit()

        # Generating Teams
        print("GENERATING TEAMS")
        used = []
        used_oauth_ids = []
        count = 0
        while count < TEAM_AMOUNT:
            name = gen_team_name()
            if name not in used:
                used.append(name)
                team = Teams(name=name, password="******")
                if random_chance():
                    team.affiliation = gen_affiliation()
                if random_chance():
                    oauth_id = random.randint(1, 1000)
                    while oauth_id in used_oauth_ids:
                        oauth_id = random.randint(1, 1000)
                    used_oauth_ids.append(oauth_id)
                    team.oauth_id = oauth_id
                db.session.add(team)
                count += 1

        db.session.commit()

        # Generating Users
        print("GENERATING USERS")
Exemplo n.º 29
0
def setup():
    # with app.app_context():
    # admin = Teams.query.filter_by(admin=True).first()

    if not is_setup():
        if not session.get('nonce'):
            session['nonce'] = sha512(os.urandom(10))
        if request.method == 'POST':
            ctf_name = request.form['ctf_name']
            ctf_name = set_config('ctf_name', ctf_name)

            # CSS
            css = set_config('start', '')

            # Admin user
            name = request.form['name']
            email = request.form['email']
            password = request.form['password']
            admin = Teams(name, email, password)
            admin.admin = True
            admin.banned = True

            # Index page
            page = Pages(
                'index', """<div class="container main-container">
    <img class="logo" src="{0}/static/original/img/logo.png" />
    <h3 class="text-center">
        Welcome to a cool CTF framework written by <a href="https://github.com/ColdHeat">Kevin Chung</a> of <a href="https://github.com/isislab">@isislab</a>
    </h3>

    <h4 class="text-center">
        <a href="{0}/admin">Click here</a> to login and setup your CTF
    </h4>
</div>""".format(request.script_root))

            # max attempts per challenge
            max_tries = set_config("max_tries", 0)

            # Start time
            start = set_config('start', None)
            end = set_config('end', None)

            # Challenges cannot be viewed by unregistered users
            view_challenges_unregistered = set_config(
                'view_challenges_unregistered', None)

            # Allow/Disallow registration
            prevent_registration = set_config('prevent_registration', None)

            # Verify emails
            verify_emails = set_config('verify_emails', None)

            mail_server = set_config('mail_server', None)
            mail_port = set_config('mail_port', None)
            mail_tls = set_config('mail_tls', None)
            mail_ssl = set_config('mail_ssl', None)
            mail_username = set_config('mail_username', None)
            mail_password = set_config('mail_password', None)

            setup = set_config('setup', True)

            db.session.add(page)
            db.session.add(admin)
            db.session.commit()

            session['username'] = admin.name
            session['id'] = admin.id
            session['admin'] = admin.admin
            session['nonce'] = sha512(os.urandom(10))

            db.session.close()
            app.setup = False
            with app.app_context():
                cache.clear()

            return redirect(url_for('views.static_html'))
        return render_template('setup.html', nonce=session.get('nonce'))
    return redirect(url_for('views.static_html'))
Exemplo n.º 30
0
def oauth_redirect():
    oauth_code = request.args.get('code')
    state = request.args.get('state')
    if session['nonce'] != state:
        log('logins', "[{date}] {ip} - OAuth State validation mismatch")
        error_for(endpoint='auth.login',
                  message='OAuth State validation mismatch.')
        return redirect(url_for('auth.login'))

    if oauth_code:
        url = get_app_config('OAUTH_TOKEN_ENDPOINT') \
            or get_config('oauth_token_endpoint') \
            or 'https://auth.majorleaguecyber.org/oauth/token'

        client_id = get_app_config('OAUTH_CLIENT_ID') or get_config(
            'oauth_client_id')
        client_secret = get_app_config('OAUTH_CLIENT_SECRET') or get_config(
            'oauth_client_secret')
        headers = {'content-type': 'application/x-www-form-urlencoded'}
        data = {
            'code': oauth_code,
            'client_id': client_id,
            'client_secret': client_secret,
            'grant_type': 'authorization_code'
        }
        token_request = requests.post(url, data=data, headers=headers)

        if token_request.status_code == requests.codes.ok:
            token = token_request.json()['access_token']
            user_url = get_app_config('OAUTH_API_ENDPOINT') \
                or get_config('oauth_api_endpoint') \
                or 'https://api.majorleaguecyber.org/user'

            headers = {
                'Authorization': 'Bearer ' + str(token),
                'Content-type': 'application/json'
            }
            api_data = requests.get(url=user_url, headers=headers).json()

            user_id = api_data['id']
            user_name = api_data['name']
            user_email = api_data['email']

            user = Users.query.filter_by(email=user_email).first()
            if user is None:
                # Check if we are allowing registration before creating users
                if registration_visible():
                    user = Users(name=user_name,
                                 email=user_email,
                                 oauth_id=user_id,
                                 verified=True)
                    db.session.add(user)
                    db.session.commit()
                else:
                    log('logins',
                        "[{date}] {ip} - Public registration via MLC blocked")
                    error_for(
                        endpoint='auth.login',
                        message=
                        'Public registration is disabled. Please try again later.'
                    )
                    return redirect(url_for('auth.login'))

            if get_config('user_mode') == TEAMS_MODE:
                team_id = api_data['team']['id']
                team_name = api_data['team']['name']

                team = Teams.query.filter_by(oauth_id=team_id).first()
                if team is None:
                    team = Teams(name=team_name, oauth_id=team_id)
                    db.session.add(team)
                    db.session.commit()

                team.members.append(user)
                db.session.commit()

            if user.oauth_id is None:
                user.oauth_id = user_id
                user.verified = True
                db.session.commit()

            login_user(user)

            return redirect(url_for('challenges.listing'))
        else:
            log('logins', "[{date}] {ip} - OAuth token retrieval failure")
            error_for(endpoint='auth.login',
                      message='OAuth token retrieval failure.')
            return redirect(url_for('auth.login'))
    else:
        log('logins', "[{date}] {ip} - Received redirect without OAuth code")
        error_for(endpoint='auth.login',
                  message='Received redirect without OAuth code.')
        return redirect(url_for('auth.login'))
Exemplo n.º 31
0
def new():
    infos = get_infos()
    errors = get_errors()
    if request.method == "GET":
        team_size_limit = get_config("team_size", default=0)
        if team_size_limit:
            plural = "" if team_size_limit == 1 else "s"
            infos.append("Teams are limited to {limit} member{plural}".format(
                limit=team_size_limit, plural=plural))

        return render_template("teams/new_team.html",
                               infos=infos,
                               errors=errors)
    elif request.method == "POST":
        teamname = request.form.get("name", "").strip()
        passphrase = request.form.get("password", "").strip()
        errors = get_errors()

        website = request.form.get("website")
        affiliation = request.form.get("affiliation")

        user = get_current_user()

        existing_team = Teams.query.filter_by(name=teamname).first()
        if existing_team:
            errors.append("Такое имя команды уже занято")
        if not teamname:
            errors.append("Имя команды неправильное")

        # Process additional user fields
        fields = {}
        for field in TeamFields.query.all():
            fields[field.id] = field

        entries = {}
        for field_id, field in fields.items():
            value = request.form.get(f"fields[{field_id}]", "").strip()
            if field.required is True and (value is None or value == ""):
                errors.append("Пожалуйста, укажите все обязательные поля")
                break

            # Handle special casing of existing profile fields
            if field.name.lower() == "affiliation":
                affiliation = value
                break
            elif field.name.lower() == "website":
                website = value
                break

            if field.field_type == "boolean":
                entries[field_id] = bool(value)
            else:
                entries[field_id] = value

        if website:
            valid_website = validators.validate_url(website)
        else:
            valid_website = True

        if affiliation:
            valid_affiliation = len(affiliation) < 128
        else:
            valid_affiliation = True

        if valid_website is False:
            errors.append(
                "Вебсайт должен быть правильной ссылкой, начинающейся с http или https"
            )
        if valid_affiliation is False:
            errors.append("Пожалуйста, укажите учреждение покороче")

        if errors:
            return render_template("teams/new_team.html", errors=errors)

        team = Teams(name=teamname, password=passphrase, captain_id=user.id)

        if website:
            team.website = website
        if affiliation:
            team.affiliation = affiliation

        db.session.add(team)
        db.session.commit()

        for field_id, value in entries.items():
            entry = TeamFieldEntries(field_id=field_id,
                                     value=value,
                                     team_id=team.id)
            db.session.add(entry)
        db.session.commit()

        user.team_id = team.id
        db.session.commit()

        clear_user_session(user_id=user.id)
        clear_team_session(team_id=team.id)

        return redirect(url_for("challenges.listing"))
Exemplo n.º 32
0
def register():
    if not can_register():
        return redirect(url_for('auth.login', _external=True))
    if request.method == 'POST':
        errors = []
        name = request.form['name']
        email = request.form['email']
        password = request.form['password']

        name_len = len(name) == 0
        names = Teams.query.add_columns('name',
                                        'id').filter_by(name=name).first()
        emails = Teams.query.add_columns('email',
                                         'id').filter_by(email=email).first()
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = re.match("[^@]+@[^@]+\.[^@]+", request.form['email'])

        if not valid_email:
            errors.append("That email doesn't look right")
        if names:
            errors.append('That team name is already taken')
        if emails:
            errors.append('That email has already been used')
        if pass_short:
            errors.append('Pick a longer password')
        if pass_long:
            errors.append('Pick a shorter password')
        if name_len:
            errors.append('Pick a longer team name')

        if len(errors) > 0:
            return render_template('register.html',
                                   errors=errors,
                                   name=request.form['name'],
                                   email=request.form['email'],
                                   password=request.form['password'])
        else:
            with app.app_context():
                team = Teams(name, email.lower(), password)
                db.session.add(team)
                db.session.commit()
                db.session.flush()

                session['username'] = team.name
                session['id'] = team.id
                session['admin'] = team.admin
                session['nonce'] = sha512(os.urandom(10))

                if can_send_mail() and get_config('verify_emails'):
                    verify_email(team.email)
                else:
                    if can_send_mail():
                        sendmail(
                            request.form['email'],
                            "You've successfully registered for {}".format(
                                get_config('ctf_name')))

        db.session.close()

        logger = logging.getLogger('regs')
        logger.warn("[{0}] {1} registered with {2}".format(
            time.strftime("%m/%d/%Y %X"), request.form['name'].encode('utf-8'),
            request.form['email'].encode('utf-8')))
        return redirect(url_for('challenges.challenges_view', _external=True))
    else:
        return render_template('register.html')
Exemplo n.º 33
0
def setup():
    # with app.app_context():
    # admin = Teams.query.filter_by(admin=True).first()

    if not utils.is_setup():
        if not session.get('nonce'):
            session['nonce'] = utils.sha512(os.urandom(10))
        if request.method == 'POST':
            ctf_name = request.form['ctf_name']
            ctf_name = utils.set_config('ctf_name', ctf_name)

            # CSS
            css = utils.set_config('start', '')

            # Admin user
            name = request.form['name']
            email = request.form['email']
            password = request.form['password']
            admin = Teams(name, email, password, "000000")
            admin.admin = True
            admin.banned = True

            # Index page
            page = Pages(
                'index', """<div class="container main-container">
    <img class="logo" src="themes/original/static/img/logo.png" />
    <h3 class="text-center">
        <p>A cool CTF platform from <a href="https://ctfd.io">ctfd.io</a></p>
        <p>Follow us on social media:</p>
        <a href="https://twitter.com/ctfdio"><i class="fa fa-twitter fa-2x" aria-hidden="true"></i></a>&nbsp;
        <a href="https://facebook.com/ctfdio"><i class="fa fa-facebook-official fa-2x" aria-hidden="true"></i></a>&nbsp;
        <a href="https://github.com/ctfd"><i class="fa fa-github fa-2x" aria-hidden="true"></i></a>
    </h3>
    <br>
    <h4 class="text-center">
        <a href="admin">Click here</a> to login and setup your CTF
    </h4>
</div>""".format(request.script_root))

            # max attempts per challenge
            max_tries = utils.set_config('max_tries', 0)

            # Start time
            start = utils.set_config('start', None)
            end = utils.set_config('end', None)
            freeze = utils.set_config('freeze', None)

            # Challenges cannot be viewed by unregistered users
            view_challenges_unregistered = utils.set_config(
                'view_challenges_unregistered', None)

            # Allow/Disallow registration
            prevent_registration = utils.set_config('prevent_registration',
                                                    None)

            # Verify emails
            verify_emails = utils.set_config('verify_emails', None)

            mail_server = utils.set_config('mail_server', None)
            mail_port = utils.set_config('mail_port', None)
            mail_tls = utils.set_config('mail_tls', None)
            mail_ssl = utils.set_config('mail_ssl', None)
            mail_username = utils.set_config('mail_username', None)
            mail_password = utils.set_config('mail_password', None)
            mail_useauth = utils.set_config('mail_useauth', None)

            setup = utils.set_config('setup', True)

            db.session.add(page)
            db.session.add(admin)
            db.session.commit()

            session['username'] = admin.name
            session['id'] = admin.id
            session['admin'] = admin.admin
            session['nonce'] = utils.sha512(os.urandom(10))

            db.session.close()
            app.setup = False
            with app.app_context():
                cache.clear()

            return redirect(url_for('views.static_html'))
        return render_template('setup.html', nonce=session.get('nonce'))
    return redirect(url_for('views.static_html'))
Exemplo n.º 34
0
def setup():
    # with app.app_context():
    # admin = Teams.query.filter_by(admin=True).first()

    if not utils.is_setup():
        if not session.get('nonce'):
            session['nonce'] = utils.sha512(os.urandom(10))
        if request.method == 'POST':
            ctf_name = request.form['ctf_name']
            ctf_name = utils.set_config('ctf_name', ctf_name)

            # CSS
            css = utils.set_config('start', '')

            # Admin user
            name = request.form['name']
            email = request.form['email']
            password = request.form['password']
            admin = Teams(name, email, password)
            admin.admin = True
            admin.banned = True

            # Index page

            index = """<div class="row">
    <div class="col-md-12">
        <img class="w-100 mx-auto d-block" style="max-width: 500px;padding: 50px;padding-top: 14vh;" src="themes/core/static/img/logo.png" />
        <br>
        <h3 class="text-center">
            <div style='font-size:0;'>
                <div style='width:100%; margin:0 auto 0 auto; text-align:center; display:inline-block;'>
                    <a href='https://interferencias.tech/'><img src='themes/core/static/img/interferencias.png' height="200px" alt='Logo Interferencias'></a>
                    <a href='http://www.hackingdesdecero.org/'><img src='themes/core/static/img/hdc.png' height="190px" alt='Logo HDC'></a>
                </div>
            </div>
        </h3>
    </div>
</div>""".format(request.script_root)

            page = Pages(title=None, route='index', html=index, draft=False)

            # max attempts per challenge
            max_tries = utils.set_config('max_tries', 0)

            # Start time
            start = utils.set_config('start', None)
            end = utils.set_config('end', None)
            freeze = utils.set_config('freeze', None)

            # Challenges cannot be viewed by unregistered users
            view_challenges_unregistered = utils.set_config(
                'view_challenges_unregistered', None)

            # Allow/Disallow registration
            prevent_registration = utils.set_config('prevent_registration',
                                                    None)

            # Verify emails
            verify_emails = utils.set_config('verify_emails', None)

            mail_server = utils.set_config('mail_server', None)
            mail_port = utils.set_config('mail_port', None)
            mail_tls = utils.set_config('mail_tls', None)
            mail_ssl = utils.set_config('mail_ssl', None)
            mail_username = utils.set_config('mail_username', None)
            mail_password = utils.set_config('mail_password', None)
            mail_useauth = utils.set_config('mail_useauth', None)

            setup = utils.set_config('setup', True)

            db.session.add(page)
            db.session.add(admin)
            db.session.commit()

            session['username'] = admin.name
            session['id'] = admin.id
            session['admin'] = admin.admin
            session['nonce'] = utils.sha512(os.urandom(10))

            db.session.close()
            app.setup = False
            with app.app_context():
                cache.clear()

            return redirect(url_for('views.static_html'))
        return render_template('setup.html', nonce=session.get('nonce'))
    return redirect(url_for('views.static_html'))
Exemplo n.º 35
0
def setup():
    # with app.app_context():
        # admin = Teams.query.filter_by(admin=True).first()

    if not is_setup():
        if not session.get('nonce'):
            session['nonce'] = sha512(os.urandom(10))
        if request.method == 'POST':
            ctf_name = request.form['ctf_name']
            ctf_name = set_config('ctf_name', ctf_name)

            ## CSS
            css = set_config('start', '')

            ## Admin user
            name = request.form['name']
            email = request.form['email']
            password = request.form['password']
            admin = Teams(name, email, password)
            admin.admin = True
            admin.banned = True

            ## Index page
            page = Pages('index', """<div class="container main-container">
    <img class="logo" src="/static/img/logo.png" />
    <h3 class="text-center">
        Welcome to a cool CTF framework written by <a href="https://github.com/ColdHeat">Kevin Chung</a> of <a href="https://github.com/isislab">@isislab</a>
    </h3>

    <h4 class="text-center">
        <a href="/admin">Click here</a> to login and setup your CTF
    </h4>
</div>""")

            #max attempts per challenge
            max_tries = set_config("max_tries",0)

            ## Start time
            start = set_config('start', None)
            end = set_config('end', None)

            ## Challenges cannot be viewed by unregistered users
            view_challenges_unregistered = set_config('view_challenges_unregistered', None)

            ## Allow/Disallow registration
            prevent_registration = set_config('prevent_registration', None)

            ## Verify emails
            verify_emails = set_config('verify_emails', None)

            mail_server = set_config('mail_server', None)
            mail_port = set_config('mail_port', None)
            mail_tls = set_config('mail_tls', None)
            mail_ssl = set_config('mail_ssl', None)
            mail_username = set_config('mail_username', None)
            mail_password = set_config('mail_password', None)

            setup = set_config('setup', True)

            db.session.add(page)
            db.session.add(admin)
            db.session.commit()
            app.setup = False
            return redirect('/')
        return render_template('setup.html', nonce=session.get('nonce'))
    return redirect('/')
Exemplo n.º 36
0
Arquivo: auth.py Projeto: TUCTF/CTFd
def register():
    if not can_register():
        return redirect(url_for('auth.login'))
    if request.method == 'POST':
        errors = []
        name = request.form['name']
        email = request.form['email']
        password = request.form['password']
        affiliation = request.form['affiliation']
        bracket = request.form['bracket']
        country = request.form['country']
        website = request.form['website']

        name_len = len(name) == 0
        names = Teams.query.add_columns('name',
                                        'id').filter_by(name=name).first()
        emails = Teams.query.add_columns('email',
                                         'id').filter_by(email=email).first()
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = re.match(
            r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)",
            request.form['email'])

        if not valid_email:
            errors.append("That email doesn't look right")
        if names:
            errors.append('That team name is already taken')
        if emails:
            errors.append('That email has already been used')
        if pass_short:
            errors.append('Pick a longer password')
        if pass_long:
            errors.append('Pick a shorter password')
        if name_len:
            errors.append('Pick a longer team name')

        if len(errors) > 0:
            return render_template('register.html',
                                   errors=errors,
                                   name=request.form['name'],
                                   email=request.form['email'],
                                   password=request.form['password'],
                                   affiliation=request.form['affiliation'],
                                   bracket=request.form['bracket'],
                                   country=request.form['country'],
                                   website=request.form['website'])
        else:
            with app.app_context():
                team = Teams(name, email.lower(), password, affiliation,
                             bracket, country, website)
                db.session.add(team)
                db.session.commit()
                db.session.flush()

                session['username'] = team.name
                session['id'] = team.id
                session['admin'] = team.admin
                session['nonce'] = sha512(os.urandom(10))

                if can_send_mail() and get_config(
                        'verify_emails'
                ):  ## Confirming users is enabled and we can send email.
                    db.session.close()
                    logger = logging.getLogger('regs')
                    logger.warn(
                        "[{0}] {1} registered (UNCONFIRMED) with {2}".format(
                            time.strftime("%m/%d/%Y %X"),
                            request.form['name'].encode('utf-8'),
                            request.form['email'].encode('utf-8')))
                    return redirect(url_for('auth.confirm_user'))
                else:  ## Don't care about confirming users
                    if can_send_mail(
                    ):  ## We want to notify the user that they have registered.
                        sendmail(
                            request.form['email'],
                            "You've successfully registered for {}".format(
                                get_config('ctf_name')))

        db.session.close()

        logger = logging.getLogger('regs')
        logger.warn("[{0}] {1} registered with {2}".format(
            time.strftime("%m/%d/%Y %X"), request.form['name'].encode('utf-8'),
            request.form['email'].encode('utf-8')))
        return redirect(url_for('challenges.challenges_view'))
    else:
        return render_template('register.html')
Exemplo n.º 37
0
        for x in range(AMT_CHALS_WITH_FILES):
            chal = random.randint(1, CHAL_AMOUNT)
            filename = gen_file()
            md5hash = hashlib.md5(filename).hexdigest()
            db.session.add(Files(chal, os.path.join("static/uploads", md5hash, filename)))
        db.session.commit()

        ### Generating Users
        print("GENERATING USERS")
        used = []
        count = 0
        while count < USER_AMOUNT:
            name = gen_name()
            if name not in used:
                used.append(name)
                team = Teams(name, name.lower() + gen_email(), "password")
                team.verified = True
                db.session.add(team)
                count += 1
        db.session.commit()

        ### Generating Solves
        print("GENERATING SOLVES")
        for x in range(USER_AMOUNT):
            used = []
            base_time = datetime.datetime.utcnow() + datetime.timedelta(minutes=-10000)
            for y in range(random.randint(1, CHAL_AMOUNT)):
                chalid = random.randint(1, CHAL_AMOUNT)
                if chalid not in used:
                    used.append(chalid)
                    solve = Solves(chalid, x + 1, "127.0.0.1", gen_word())
Exemplo n.º 38
0
def setup():
    # with app.app_context():
        # admin = Teams.query.filter_by(admin=True).first()

    if not utils.is_setup():
        if not session.get('nonce'):
            session['nonce'] = utils.sha512(os.urandom(10))
        if request.method == 'POST':
            ctf_name = request.form['ctf_name']
            ctf_name = utils.set_config('ctf_name', ctf_name)

            # CSS
            css = utils.set_config('start', '')

            # Admin user
            name = request.form['name']
            email = request.form['email']
            password = request.form['password']
            admin = Teams(name, email, password)
            admin.admin = True
            admin.banned = True

            # Index page
            page = Pages('index', """<div class="container main-container">
    <img class="logo" src="themes/original/static/img/logo.png" />
    <h3 class="text-center">
        <p>A cool CTF platform from <a href="https://ctfd.io">ctfd.io</a></p>
        <p>Follow us on social media:</p>
        <a href="https://twitter.com/ctfdio"><i class="fa fa-twitter fa-2x" aria-hidden="true"></i></a>&nbsp;
        <a href="https://facebook.com/ctfdio"><i class="fa fa-facebook-official fa-2x" aria-hidden="true"></i></a>&nbsp;
        <a href="https://github.com/ctfd"><i class="fa fa-github fa-2x" aria-hidden="true"></i></a>
    </h3>
    <br>
    <h4 class="text-center">
        <a href="admin">Click here</a> to login and setup your CTF
    </h4>
</div>""".format(request.script_root))

            # max attempts per challenge
            max_tries = utils.set_config('max_tries', 0)

            # Start time
            start = utils.set_config('start', None)
            end = utils.set_config('end', None)
            freeze = utils.set_config('freeze', None)

            # Challenges cannot be viewed by unregistered users
            view_challenges_unregistered = utils.set_config('view_challenges_unregistered', None)

            # Allow/Disallow registration
            prevent_registration = utils.set_config('prevent_registration', None)

            # Verify emails
            verify_emails = utils.set_config('verify_emails', None)

            mail_server = utils.set_config('mail_server', None)
            mail_port = utils.set_config('mail_port', None)
            mail_tls = utils.set_config('mail_tls', None)
            mail_ssl = utils.set_config('mail_ssl', None)
            mail_username = utils.set_config('mail_username', None)
            mail_password = utils.set_config('mail_password', None)

            setup = utils.set_config('setup', True)

            db.session.add(page)
            db.session.add(admin)
            db.session.commit()

            session['username'] = admin.name
            session['id'] = admin.id
            session['admin'] = admin.admin
            session['nonce'] = utils.sha512(os.urandom(10))

            db.session.close()
            app.setup = False
            with app.app_context():
                cache.clear()

            return redirect(url_for('views.static_html'))
        return render_template('setup.html', nonce=session.get('nonce'))
    return redirect(url_for('views.static_html'))