Exemple #1
0
    def login():
        if request.method == 'POST':
            errors = []
            # team = Teams.query.filter_by(name=request.form['name'], password=sha512(request.form['password'])).first()
            team = Teams.query.filter_by(name=request.form['name']).first()
            if team and bcrypt_sha256.verify(request.form['password'],
                                             team.password):
                # session.regenerate() # NO SESSION FIXATION FOR YOU
                session['username'] = team.name
                session['id'] = team.id
                session['admin'] = team.admin
                session['nonce'] = sha512(os.urandom(10))
                db.session.close()

                logger = logging.getLogger('logins')
                logger.warn("[{0}] {1} logged in".format(
                    time.strftime("%m/%d/%Y %X"),
                    session['username'].encode('utf-8')))

                # if request.args.get('next') and is_safe_url(request.args.get('next')):
                #     return redirect(request.args.get('next'))
                return redirect('/team/{0}'.format(team.id))
            else:
                errors.append("That account doesn't seem to exist")
                db.session.close()
                return render_template('login.html', errors=errors)
        else:
            db.session.close()
            return render_template('login.html')
Exemple #2
0
    def reset_password(data=None):
        if data is not None and request.method == "GET":
            return render_template('reset_password.html', mode='set')
        if data is not None and request.method == "POST":
            try:
                s = TimedSerializer(app.config['SECRET_KEY'])
                name = s.loads(data.decode('base64'), max_age=1800)
            except BadTimeSignature:
                return render_template('reset_password.html', errors=['Your link has expired'])
            team = Teams.query.filter_by(name=name).first()
            team.password = sha512(request.form['password'].strip())
            db.session.commit()
            db.session.close()
            return redirect('/login')

        if request.method == 'POST':
            email = request.form['email'].strip()
            team = Teams.query.filter_by(email=email).first()
            if not team:
                return render_template('reset_password.html', errors=['Check your email'])
            s = TimedSerializer(app.config['SECRET_KEY'])
            token = s.dumps(team.name)
            text = """
Did you initiate a password reset? 

{0}/reset_password/{1}

    """.format(app.config['HOST'], token.encode('base64'))

            sendmail(email, text)

            return render_template('reset_password.html', errors=['Check your email'])
        return render_template('reset_password.html')
Exemple #3
0
    def reset_password(data=None):
        if data is not None and request.method == "GET":
            return render_template('reset_password.html', mode='set')
        if data is not None and request.method == "POST":
            try:
                s = TimedSerializer(app.config['SECRET_KEY'])
                name = s.loads(data.decode('base64'), max_age=1800)
            except BadTimeSignature:
                return render_template('reset_password.html', errors=['Your link has expired'])
            team = Teams.query.filter_by(name=name).first()
            team.password = sha512(request.form['password'].strip())
            db.session.commit()
            db.session.close()
            return redirect('/login')

        if request.method == 'POST':
            email = request.form['email'].strip()
            team = Teams.query.filter_by(email=email).first()
            if not team:
                return render_template('reset_password.html', errors=['Check your email'])
            s = TimedSerializer(app.config['SECRET_KEY'])
            token = s.dumps(team.name)
            text = """
Did you initiate a password reset? 

{0}/reset_password/{1}

    """.format(app.config['HOST'], token.encode('base64'))

            sendmail(email, text)

            return render_template('reset_password.html', errors=['Check your email'])
        return render_template('reset_password.html')
Exemple #4
0
def loginAndroid():
    errors = []
    name = request.form['name']
    student = Students.query.filter_by(name=name).first()
    if student:
        if student and bcrypt_sha256.verify(request.form['password'], student.password):
            try:
                session.regenerate() # NO SESSION FIXATION FOR YOU
            except:
                pass # TODO: Some session objects don't implement regenerate :(
            session['username'] = student.name
            session['id'] = student.id
            session['admin'] = student.admin
            session['nonce'] = sha512(os.urandom(10))
            session.modified = True
            db.session.close()

            logger = logging.getLogger('logins')
            logger.warn("[{0}] {1} logged in".format(time.strftime("%m/%d/%Y %X"), session['username'].encode('utf-8')))

            if request.args.get('next') and is_safe_url(request.args.get('next')):
                return redirect(request.args.get('next'))
            return jsonify({'status': '200', 'nonce': session['nonce']})
        else: # This user exists but the password is wrong
            errors.append("Your username or password is incorrect")
            db.session.close()
            return jsonify({'status': '400', 'message': 'Invalid Login'})
    else:  # This user just doesn't exist
        errors.append("Your username or password is incorrect")
        db.session.close()
        return render_template('login.html', errors=errors)
Exemple #5
0
def login():
    if request.method == 'POST':
        errors = []
        name = request.form['name']
        team = Teams.query.filter_by(name=name).first()
        if team and bcrypt_sha256.verify(request.form['password'], team.password):
            try:
                session.regenerate() # NO SESSION FIXATION FOR YOU
            except:
                pass # TODO: Some session objects don't implement regenerate :(
            session['username'] = team.name
            session['id'] = team.id
            session['admin'] = team.admin
            session['nonce'] = sha512(os.urandom(10))
            db.session.close()

            logger = logging.getLogger('logins')
            logger.warn("[{0}] {1} logged in".format(time.strftime("%m/%d/%Y %X"), session['username'].encode('utf-8')))

            if request.args.get('next') and is_safe_url(request.args.get('next')):
                return redirect(request.args.get('next'))
            return redirect(url_for('challenges.challenges_view'))
        else:
            errors.append("That account doesn't seem to exist")
            db.session.close()
            return render_template('login.html', errors=errors)
    else:
        db.session.close()
        return render_template('login.html')
Exemple #6
0
 def setup():
     #if not is_setup():
     if request.method == 'POST':
         errors = []
         ## Admin user
         name = request.form['name']
         adminname = app.config['ADMINNAME']
         adminpassword = app.config['ADMINPASSWORD']
         epassword = request.form['epassword']
         password = base64.decodestring(epassword)
         if name == adminname and bcrypt_sha256.verify(
                 password, adminpassword):
             session.parmanent = False
             session['username'] = adminname
             session['password'] = adminpassword
             session['admin'] = 0
             session['nonce'] = sha512(os.urandom(10))
             flag = Flag.query.first()
             if flag == None:
                 addlmflag = 0
                 createkeyflag = 0
                 exportlmcertflag = 0
                 configIPflag = 0
                 restartflag = 0
                 configrouteflag = 0
                 importCAflag = 0
                 importsyscertflag = 0
                 initialUSBKeyflag = 0
                 importUSBKeyflag = 0
                 flag = Flag(addlmflag, createkeyflag, exportlmcertflag,
                             restartflag, configIPflag, configrouteflag,
                             importCAflag, importsyscertflag,
                             initialUSBKeyflag, importUSBKeyflag)
                 db.session.add(flag)
                 db.session.commit()
                 flag = Flag.query.first()
             count = flag.addlmflag + flag.createkeyflag + flag.exportlmcertflag + flag.restartflag + flag.configIPflag + flag.configrouteflag + flag.importCAflag + flag.importsyscertflag + flag.initialUSBKeyflag + flag.importUSBKeyflag
             if count < 1:
                 return redirect('/initial1')
             elif count < 4:
                 return redirect('/initial2')
             elif count < 5:
                 return redirect('/initial3')
             elif count < 6:
                 return redirect('/initial4')
             elif count < 7:
                 return redirect('/initial5')
             elif count < 8:
                 return redirect('/initial6')
             elif count < 10:
                 return redirect('/initial8')
             else:
                 return redirect('/initial1')
         else:
             errors.append("用户名或者密码错误。")
             db.session.close()
         return render_template('setup.html', errors=errors)
     else:
         db.session.close()
         return render_template('setup.html')
Exemple #7
0
def login():
    logger = logging.getLogger('logins')
    if request.method == 'POST':
        errors = []
        name = request.form['name']

        # Check if the user submitted an email address or a team name
        if utils.check_email_format(name) is True:
            team = Teams.query.filter_by(email=name).first()
        elif utils.check_sno_format(name) is True:
            team = Teams.query.filter_by(sno=name).first()
        else:
            team = Teams.query.filter_by(name=name).first()

        if team:
            if team and bcrypt_sha256.verify(request.form['password'],
                                             team.password):
                try:
                    session.regenerate()  # NO SESSION FIXATION FOR YOU
                except:
                    pass  # TODO: Some session objects don't implement regenerate :(
                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'))

            else:  # 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=team.name.encode('utf-8')))
                errors.append("Your username or password is incorrect")
                db.session.close()
                return render_template('login.html', errors=errors)

        else:  # This user just doesn't exist
            logger.warn(
                "[{date}] {ip} - submitted invalid account information".format(
                    date=time.strftime("%m/%d/%Y %X"), ip=utils.get_ip()))
            errors.append("Your username or password is incorrect")
            db.session.close()
            return render_template('login.html', errors=errors)

    else:
        db.session.close()
        return render_template('login.html')
Exemple #8
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('/')
Exemple #9
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('/')
Exemple #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 = 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("/")
Exemple #11
0
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']
        schoolCode = request.form['schoolCode']
        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'], schoolCode=request.form['schoolCode'], password=request.form['password'])
        else:
            with app.app_context():
                team = Teams(name, email.lower(), schoolCode, 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 mailserver() and get_config('verify_emails'):
                    verify_email(team.email)
                else:
                    if mailserver():
                        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')
Exemple #12
0
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']

        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'))
    else:
        return render_template('register.html')
Exemple #13
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('/')
Exemple #14
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('/')
Exemple #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']
        password = request.form['password']

        name_len = len(name) == 0
        names = Teams.query.add_columns('name',
                                        'id').filter_by(name=name).first()
        pass_short = len(password) == 0
        pass_long = len(password) > 128

        if names:
            errors.append('That team name is already taken')
        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'],
                                   password=request.form['password'])
        else:
            with app.app_context():
                team = Teams(name, 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))

        logger.warn("[{date}] {ip} - {username} registered".format(
            date=time.strftime("%m/%d/%Y %X"),
            ip=utils.get_ip(),
            username=request.form['name'].encode('utf-8')))
        db.session.close()
        return redirect(url_for('challenges.challenges_view'))
    else:
        return render_template('register.html')
Exemple #16
0
    def admin():
        if request.method == 'POST':
            username = request.form.get('name')
            password = request.form.get('password')

            admin = Teams.query.filter_by(name=request.form['name'],
                                          admin=True).first()
            if admin and bcrypt_sha256.verify(request.form['password'],
                                              admin.password):
                session.regenerate()  # NO SESSION FIXATION FOR YOU
                session['username'] = admin.name
                session['id'] = admin.id
                session['admin'] = True
                session['nonce'] = sha512(os.urandom(10))
                db.session.close()
                return redirect('/admin/graphs')

        if is_admin():
            return redirect('/admin/graphs')

        return render_template('admin/login.html')
Exemple #17
0
def admin_view():
    if request.method == 'POST':
        username = request.form.get('name')
        password = request.form.get('password')

        admin_user= Teams.query.filter_by(name=request.form['name'], admin=True).first()
        if admin_user and bcrypt_sha256.verify(request.form['password'], admin_user.password):
            try:
                session.regenerate() # NO SESSION FIXATION FOR YOU
            except:
                pass # TODO: Some session objects dont implement regenerate :(
            session['username'] = admin_user.name
            session['id'] = admin_user.id
            session['admin'] = True
            session['nonce'] = sha512(os.urandom(10))
            db.session.close()
            return redirect('/admin/graphs')

    if is_admin():
        return redirect('/admin/graphs')

    return render_template('admin/login.html')
Exemple #18
0
def admin_view():
    if request.method == 'POST':
        username = request.form.get('name')
        password = request.form.get('password')

        admin_user = Teams.query.filter_by(name=request.form['name'],
                                           admin=True).first()
        if admin_user and bcrypt_sha256.verify(request.form['password'],
                                               admin_user.password):
            try:
                session.regenerate()  # NO SESSION FIXATION FOR YOU
            except:
                pass  # TODO: Some session objects dont implement regenerate :(
            session['username'] = admin_user.name
            session['id'] = admin_user.id
            session['admin'] = True
            session['nonce'] = sha512(os.urandom(10))
            db.session.close()
            return redirect(url_for('admin.admin_graphs'))

    if is_admin():
        return redirect(url_for('admin.admin_graphs'))

    return render_template('admin/login.html')
Exemple #19
0
def login():
    if request.method == 'POST':
        errors = []
        name = request.form['name']
        team = Teams.query.filter_by(name=name).first()
        if team:
            if team and bcrypt_sha256.verify(request.form['password'], team.password):
                try:
                    session.regenerate() # NO SESSION FIXATION FOR YOU
                except:
                    pass # TODO: Some session objects don't implement regenerate :(
                session['username'] = team.name
                session['id'] = team.id
                session['admin'] = team.admin
                session['mentor'] = team.mentor
                print team.mentor
                session['nonce'] = utils.sha512(os.urandom(10))
                db.session.close()

                logger = logging.getLogger('logins')
                logger.warn("[{0}] {1} logged in".format(time.strftime("%m/%d/%Y %X"), 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('views.index', welcome=1))
            else: # This user exists but the password is wrong
                errors.append("Your username or password is incorrect")
                db.session.close()
                return render_template('login.html', errors=errors)
        else:  # This user just doesn't exist
            errors.append("Your username or password is incorrect")
            db.session.close()
            return render_template('login.html', errors=errors)
    else:
        db.session.close()
        return render_template('login.html')
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>Demon CTF <a href="http://demonteam.org">demonteam.org</a></p>
    </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'))
Exemple #21
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)

            flag_format = request.form['flag_format']
            flag_format = set_config('flag_format', flag_format)

            # 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', """
    <img class="logo" src="{0}/static/original/img/logo.png" />

    <h3 class="text-center">
        Welcome to the THC CTF 2017 !
    </h3>

    <br/>

    <h6 class="text-center">
        <a href="https://github.com/ToulouseHackingConvention/CTFd/">scoreboard</a> based on <a href="https://github.com/isislab/CTFd">CTFd</a> and modified by <a href="https://github.com/arthaud">maxima</a>, <a href="https://github.com/palkeo">palkeo</a> and <a href="https://github.com/zadlg">zadig</a>.
    </h6>""".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.index'))
        return render_template('setup.html', nonce=session.get('nonce'))
    return redirect(url_for('views.index'))
Exemple #22
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('/')
Exemple #23
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'))
Exemple #24
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.jpg" />
        <h3 class="text-center">
            一个正经的CTF平台
        </h3>
        <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'))
Exemple #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 = 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']
            section = Sections(0, 123)
            db.session.add(section)
            db.session.commit()

            team = Teams("admin", section.sectionNumber)
            db.session.add(team)
            db.session.commit()

            admin = Students(name, email, password, team.id, section.sectionNumber)
            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>
        <br>
        Modified for educational use by <a href="https://github.com/camgeehr">Cameron Geehr</a>, <a href="https://github.com/jaboyles">Jacob Boyles</a>, and <a href="https://github.com/bgoulds">Brian Gouldsberry</a>
    </h3>
</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'), setup=True)
    return redirect(url_for('views.static_html'))
Exemple #26
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 = 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'])
        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('contests.contests_view'))
    else:
        return render_template('register.html')
Exemple #27
0
def register_smart():
    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']
        color = request.form['color']
        school = request.form['school']
        image = request.form['image']
        #school = request.form['school']
        if not color in teamColors:
            color = "RED"
        if not image in teamImages:
            image = "HULK"
        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()
        smart_color = SmartCityTeam.query.filter_by(color=color).first()
        smart_image = SmartCityTeam.query.filter_by(image=image).first()
        #challenge = SmartCityChallenge.query.filter_by(id=challenge.id).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 smart_color:
            if not Teams.query.filter_by(id=smart_color.teamId).first().admin:
                errors.append(
                    'Color unavailable. The following colors are available:  \n'
                    + getAvailableColors())
        if smart_image:
            if not Teams.query.filter_by(id=smart_image.teamId).first().admin:
                errors.append('That image is already taken')

        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()

                smart_team = SmartCityTeam(team.id, team.name, color, image,
                                           school)
                db.session.add(smart_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')
Exemple #28
0
def register():
    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 = 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'])
        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.
                    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')))

                    utils.verify_email(team.email)

                    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')))

        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')
Exemple #29
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']
        sno = request.form['sno']
        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()
        valid_sno = utils.check_sno_format(request.form['sno'])
        snos = Teams.query.add_columns('sno', 'id').filter_by(sno=sno).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_sno:
            errors.append("Please enter a valid student ID")
        if not valid_email:
            errors.append("Please enter a valid email address")
        if names or snos:
            errors.append('That nick/user 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, sno, email.lower(), password)
                db.session.add(team)
                db.session.commit()
                db.session.flush()

                session['username'] = team.name
                session['sno'] = team.sno
                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}/{sno} registered (UNCONFIRMED) with {email}"
                        .format(date=time.strftime("%m/%d/%Y %X"),
                                ip=utils.get_ip(),
                                username=request.form['name'].encode('utf-8'),
                                sno=request.form['sno'].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}/{sno} registered with {email}".format(
                date=time.strftime("%m/%d/%Y %X"),
                ip=utils.get_ip(),
                username=request.form['name'].encode('utf-8'),
                sno=request.form['sno'].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')
Exemple #30
0
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"]
        bracket = request.form["bracket"]
        country = request.form["country"]
        affiliation = request.form["affiliation"]

        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"])
        bracket_exists = bracket in brackets
        country_exists = country in countries
        print country_exists
        print country

        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 bracket_exists:
            errors.append("Please select a valid bracket")
        if not country_exists:
            errors.append("Please select a valid country")

        if len(errors) > 0:
            return render_template(
                "register.html",
                errors=errors,
                name=request.form["name"],
                email=request.form["email"],
                password=request.form["password"],
                brackets=brackets,
                countries=countries,
            )
        else:
            with app.app_context():
                team = Teams(name, email.lower(), password, bracket, country, affiliation)
                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 mailserver() and get_config("verify_emails"):
                    verify_email(team.email)
                else:
                    if mailserver():
                        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", brackets=brackets, countries=countries)
Exemple #31
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("邮箱格式不正确")
        if names:
            errors.append('用户名已被其他用户使用')
        if team_name_email_check is True:
            errors.append('用户名不能和邮箱一样')
        if emails:
            errors.append('邮箱已被其他用户使用')
        if pass_short:
            errors.append('密码长度不够')
        if pass_long:
            errors.append('密码长度超过上限')
        if name_len:
            errors.append('用户名长度不够')

        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'], "您已经成功过注册了 {}".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')
Exemple #32
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">
            <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="fab fa-twitter fa-2x" aria-hidden="true"></i></a>&nbsp;
            <a href="https://facebook.com/ctfdio"><i class="fab fa-facebook fa-2x" aria-hidden="true"></i></a>&nbsp;
            <a href="https://github.com/ctfd"><i class="fab 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>
</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'))
Exemple #33
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('/')
Exemple #34
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()
            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'))
Exemple #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 = 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('/')
Exemple #36
0
def register():
    if not can_register():
        return redirect(url_for('auth.login'))
    if request.method == 'POST':
        errors = []
        name = request.form.get('name', '')
        email = request.form.get('email', '')
        password = request.form.get('password', '')
        password_confirm = request.form.get('password-confirm', '')
        website = request.form.get('website', '')
        affiliation = request.form.get('affiliation', '')
        country = request.form.get('country', '')

        if not name:
            errors.append('Pick a longer team name')
        else:
            names = Teams.query.filter_by(name=name).first()
            if names:
                errors.append('That team name is already taken')

        if not email:
            errors.append('Pick a longer email')
        elif not re.match(
                r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email):
            errors.append("That email doesn't look right")
        else:
            emails = Teams.query.filter_by(email=email).first()
            if emails:
                errors.append('That email has already been used')

        if not password:
            errors.append('Pick a longer password')
            password = password_confirm = ''
        elif len(password) > 128:
            errors.append('Pick a shorter password')
            password = password_confirm = ''
        elif password != password_confirm:
            errors.append("These passwords don't match")
            password = password_confirm = ''

        if website.strip() and not validate_url(website):
            errors.append("That doesn't look like a valid URL")

        if country not in countries.keys:
            errors.append('Invalid country')

        if len(errors) > 0:
            return render_template('register.html',
                                   errors=errors,
                                   name=name,
                                   email=email,
                                   password=password,
                                   password_confirm=password_confirm,
                                   website=website,
                                   affiliation=affiliation,
                                   country=country,
                                   countries=countries)
        else:
            with app.app_context():
                team = Teams(name, email.lower(), password, website,
                             affiliation, country)
                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',
            country='wo',  # default: Multiple Countries
            countries=countries)
Exemple #37
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')
Exemple #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

            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'))
Exemple #39
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'))
Exemple #40
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'))
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')