Example #1
0
 def create_flag(self):
     ''' Create a flag '''
     form = Form(
         box_uuid="Please select a box",
         flag_name="Please enter a name",
         token="Please enter a token value",
         reward="Please enter a reward value",
         is_file="Please select a file setting",
         description="Please enter a flag description",
     )
     if form.validate(self.request.arguments):
         try:
             if Flag.by_name(self.get_argument('flag_name')) is not None:
                 self.render('admin/create/flag.html',
                     errors=["Name already exists"]
                 )
             elif Flag.by_token(self.get_argument('token')) is not None:
                 self.render('admin/create/flag.html',
                     errors=["Token value is not unique"]
                 )
             elif Box.by_uuid(self.get_argument('box_uuid')) is None:
                 self.render('admin/create/flag.html',
                     errors=["Box does not exist"]
                 )
             else:
                 reward = int(self.get_argument('reward', 'NaN'))
                 self.__mkflag__(reward)
                 self.redirect('/admin/view/game_objects')
         except ValueError:
             self.render('admin/create/flag.html',
                 errors=["Invalid reward value"]
             )
     else:
         self.render("admin/create/flag.html", errors=form.errors)
Example #2
0
def create_flag(name, token, value, box, description="No description", is_file=False):
    if Flag.by_name(name) is not None:
        logging.info("Flag with name '%s' already exists, skipping" % (name))
        return Flag.by_name(name)
    if Flag.by_token(token) is not None:
        logging.info("Flag with token '%s' already exists, skipping" % (token))
        return Flag.by_token(token)
    if is_file and os.path.exists(token):
        with open(token) as favatar:
            _token = Flag.digest(favatar.read())
    elif is_file and 40 == len(token):
        _token = unicode(token)  # Just assume it's a SHA1
    elif is_file:
        raise ValueError("Flag token file does not exist, and is not a hash.")
    else:
        _token = unicode(token[:256])
    logging.info("Create Flag: %s" % name)
    flag = Flag(
        name=unicode(name[:32]),
        token=_token,
        is_file=is_file,
        description=unicode(description[:256]),
        value=abs(int(value)),
        box_id=box.id,
    )
    dbsession.add(flag)
    dbsession.flush()
    return flag
Example #3
0
 def create_flag(self):
     ''' Create a flag '''
     form = Form(
         box_uuid="Please select a box",
         flag_name="Please enter a name",
         token="Please enter a token value",
         reward="Please enter a reward value",
         is_file="Please select a file setting",
         description="Please enter a flag description",
     )
     if form.validate(self.request.arguments):
         try:
             if Flag.by_name(self.get_argument('flag_name')) is not None:
                 self.render('admin/create/flag.html',
                             errors=["Name already exists"])
             elif Flag.by_token(self.get_argument('token')) is not None:
                 self.render('admin/create/flag.html',
                             errors=["Token value is not unique"])
             elif Box.by_uuid(self.get_argument('box_uuid')) is None:
                 self.render('admin/create/flag.html',
                             errors=["Box does not exist"])
             else:
                 reward = int(self.get_argument('reward', 'NaN'))
                 self.__mkflag__(reward)
                 self.redirect('/admin/view/game_objects')
         except ValueError:
             self.render('admin/create/flag.html',
                         errors=["Invalid reward value"])
     else:
         self.render("admin/create/flag.html", errors=form.errors)
Example #4
0
def flag_beat(request, beatid):
    try:
        beat = Beat.objects.only('id').get(id=beatid)
    except Beat.DoesNotExist:
        return HttpResponseForbidden({'error': 'beat not exist'})

    flag = Flag(creator=request.user, beat=beat)
    flag.save()
    return HttpResponseOK()
Example #5
0
def index(request):
    if request.method == "POST":
        form = FlagForm(request.POST, request.FILES)
        if form.is_valid() and (form.cleaned_data['image']
                                or form.cleaned_data['tagline']):
            newflag = Flag()
            newflag.original = form.cleaned_data['image']
            newflag.name = form.cleaned_data['name']
            newflag.email = form.cleaned_data['email']
            newflag.location = form.cleaned_data['location']
            newflag.tagline = form.cleaned_data['tagline']

            newflag.save()

            return HttpResponseRedirect(reverse('flags.views.index'))
    else:
        form = FlagForm()

    flags = Flag.objects.order_by("-id")

    return render_to_response('flags/index.html', {
        'flags': flags,
        'form': form
    },
                              context_instance=RequestContext(request))
Example #6
0
async def post_flag(request, *, text):
    names = text
    for name in names.split():
        print(name)
        flag = Flag(nick=name, tradeId='')
        await flag.save()
    return 'redirect:/flag'
Example #7
0
 def _make_26_flags(self):
     keys = []
     fields = ['author_name', 'author_links', 'author_g_plus', 'author_fb', 'author_twitter', 'author_location']
     for c in 'abcdefghijklmnopqrstuvwxyz':
         data = {k: k + '_' + c for k in fields}
         blob_info = self.get_blob_info()
         keys.append(Flag.make_flag(blob_info, data))
     return keys
Example #8
0
 def post(self, *args, **kwargs):
     ''' Check validity of flag submissions '''
     flag = Flag.by_uuid(self.get_argument('uuid', ''))
     if flag is not None:
         if flag.is_file:
             self.validate_file(flag)
         else:
             self.validate_text(flag)
     else:
         self.render('public/404.html')
Example #9
0
 def post(self):
     id = request.args['id']
     try:
         hacker = Hacker.get_by_id(id)
     except:
         abort(404, message = "Hacker not found")
     if hacker.next_proj.table == int(request.args['table']):
         try:
             View.create(hacker = hacker, project = hacker.next_proj)
             Flag.create(hacker = hacker, project = hacker.next_proj, description = request.data)
             hacker.next_proj = None
             hacker.save()
             res = jsonify({"status" : "Flag recorded"})
             res.status_code = 201
             return res
         except:
             abort(409, message = "Unable to submit flag")
     else:
         abort(409, message = "Submission and database mismatch")
Example #10
0
 def post(self, *args, **kwargs):
     ''' Check validity of flag submissions '''
     flag = Flag.by_uuid(self.get_argument('uuid', ''))
     if flag is not None:
         if flag.is_file:
             self.validate_file(flag)
         else:
             self.validate_text(flag)
     else:
         self.render('public/404.html')
Example #11
0
 def validate_file(self, flag):
     ''' Check a file submission '''
     if 0 < len(self.request.files['flag'][0]['body']):
         file_data = self.request.files['flag'][0]['body']
         digest = Flag.digest(file_data)
         if self.capture(flag, digest):
             self.render_page(flag)
         else:
             self.render_page(flag, errors=["Invalid flag submission."])
     else:
         self.render_page(flag, errors=["Missing flag data."])
Example #12
0
 def validate_file(self, flag):
     ''' Check a file submission '''
     if 0 < len(self.request.files['flag'][0]['body']):
         file_data = self.request.files['flag'][0]['body']
         digest = Flag.digest(file_data)
         if self.attempt_capture(flag, digest):
             self.render_page(flag)
         else:
             self.render_page(flag, errors=["Invalid flag submission."])
     else:
         self.render_page(flag, errors=["Missing flag data."])
Example #13
0
 def flag(self):
     '''
     Accepts flag submissions, a flag can be either a string or a file,
     if the flag submission is a file the MD5 hexdigest is used.
     '''
     form = Form(flag_type="Missing flag type")
     user = self.get_current_user()
     if form.validate(self.request.arguments):
         flag = Flag.by_uuid(self.get_argument('uuid', ''))
         if flag is not None:
             if self.get_argument('flag_type').lower() == 'text':
                 token = self.get_argument('token', None)
                 errors = self.__chkflag__(flag, token)
                 if len(errors) == 0:
                     self.flag_captured()
                 else:
                     self.render("missions/view.html",
                         team=user.team,
                         errors=errors
                     )
             elif self.get_argument('flag_type').lower() == 'file':
                 if 0 < len(self.request.files['flag'][0]['body']):
                     file_data = self.request.files['flag'][0]['body']
                     errors = self.__chkflag__(flag, file_data)
                     if len(errors) == 0:
                         self.flag_captured()
                     else:
                         self.render("missions/view.html",
                             team=user.team,
                             errors=errors
                         )
                 else:
                     logging.info("No file data in flag submission.")
                     self.render("missions/view.html",
                         team=user.team,
                         errors=["No file data"]
                     )
             else:
                 self.render("missions/view.html",
                     team=user.team,
                     errors=["Invalid flag type"]
                 )
         else:
             self.render("missions/view.html",
                 team=user.team,
                 errors=["Flag does not exist"]
             )
     else:
         self.render("missions/view.html",
             team=user.team,
             errors=form.errors
         )
Example #14
0
    def test_make_flags(self):
        self._make_26_flags()
        flags = Flag.query().fetch(50)
        self.assertEqual(len(flags), 26)
        flag_a = next(f for f in flags if f.flag_message.author_name.endswith('a'))
        fm = flag_a.flag_message
        self.assertEqual(fm.author_name, 'author_name_a')
        self.assertEqual(fm.author_links, ['author_links_a'])
        self.assertEqual(fm.author_name, 'author_name_a')
        self.assertEqual(fm.author_g_plus, 'author_g_plus_a')
        self.assertEqual(fm.author_fb, 'author_fb_a')
        self.assertEqual(fm.author_twitter, 'author_twitter_a')
        self.assertEqual(fm.author_location, 'author_location_a')

        req = FlagListRequestMessage(
            max_results=20,
            order=FlagListRequestMessage.Order.up_votes
        )
        flag_list = Flag.flag_list(req).items
        self.assertEqual(len(flag_list), 20)
        for a, b in zip(flag_list, flag_list[1:]):
            self.assertLessEqual(b.up_votes, a.up_votes)
Example #15
0
 def del_flag(self):
     ''' Delete a flag object from the database '''
     flag = Flag.by_uuid(self.get_argument('uuid', ''))
     if flag is not None:
         logging.info("Deleted flag: %s " % flag.name)
         dbsession.delete(flag)
         dbsession.flush()
         self.redirect('/admin/view/game_objects')
     else:
         logging.info("Flag (%r) does not exist in the database" %
                      self.get_argument('uuid', ''))
         self.render("admin/view/game_objects.html",
                     errors=["Flag does not exist in database"])
Example #16
0
 def __mkflag__(self, reward):
     ''' Creates a flag in the database '''
     box = Box.by_uuid(self.get_argument('box_uuid'))
     flag = Flag(
         name=unicode(self.get_argument('flag_name')),
         token=unicode(self.get_argument('token')),
         description=unicode(self.get_argument('description')),
         is_file=bool(self.get_argument('is_file', 'false') == 'true'),
         box_id=box.id,
         value=reward,
     )
     dbsession.add(flag)
     dbsession.flush()
Example #17
0
def create_flag(name, token, reward, box, description="No description",
                is_file=False):
    if is_file:
        if not os.path.exists(token):
            raise ValueError("Path to flag file does not exist: %s" % token)
        f = open(token, 'r')
        data = f.read()
        f.close()
        _token = Flag.digest(data)
        print(INFO + "Create Flag: " + bold + name + W + " (%s)" % _token)
    else:
        print(INFO + "Create Flag: " + bold + name + W)
        _token = unicode(token)
    flag = Flag(
        name=unicode(name),
        token=_token,
        is_file=is_file,
        description=unicode(description),
        value=reward,
        box_id=box.id,
    )
    dbsession.add(flag)
    dbsession.flush()
Example #18
0
def create_flag(msg_id):
    """need to hook this up properly to the db"""
    user_id = g.user.id
    flag = Flag.query.filter_by(msg_id=msg_id, user_id=user_id).first()
    if flag:
        db.session.delete(flag)
        db.session.commit()

    else:
        new_flag = Flag(msg_id=msg_id, user_id=user_id)
        db.session.add(new_flag)
        db.session.commit()

    return redirect('/flag/new')
Example #19
0
def process_flag_json(flag):
    flag['raw'] = str(flag)
    flag['flagid'] = int(flag['path'].split('.')[0].split('/')[-1])
    flag['userid'] = fetch_userid(flag['username'])
    del flag['username']

    already_fetched = session.query(exists().where(Flag.flagid==flag['flagid'])).scalar()

    session.merge(Flag(**flag))
    session.commit()

    if not already_fetched:
        flag = session.query(Flag).filter(Flag.flagid==flag['flagid']).first()
        process_flag(flag)
        print(flag, session.query(User).count(), session.query(Flag).count())
Example #20
0
 def del_flag(self):
     ''' Delete a flag object from the database '''
     flag = Flag.by_uuid(self.get_argument('uuid', ''))
     if flag is not None:
         logging.info("Deleted flag: %s " % flag.name)
         dbsession.delete(flag)
         dbsession.flush()
         self.redirect('/admin/view/game_objects')
     else:
         logging.info("Flag (%r) does not exist in the database" %
             self.get_argument('uuid', '')
         )
         self.render("admin/view/game_objects.html",
             errors=["Flag does not exist in database"]
         )
Example #21
0
    def post(self):
        upload_files = self.get_uploads('file')  # 'file' is file upload field in the form
        try:
            blob_info = upload_files[0]
        except IndexError:
            return self.response.write('Error: No flag images selected or uploaded')

        flag_message_fields = ['author_name', 'author_links', 'author_g_plus', 'author_fb', 'author_twitter', 'author_location']
        data = {k: self.request.get(k) for k in flag_message_fields}
        try:
            flag_key = Flag.make_flag(blob_info, data)
        except messages.ValidationError:
            logging.error('invalid flag')
            logging.info(data)
            self.response.write('invalid flag')
        self.response.write('{"flagKey": %s"}' % flag_key.urlsafe())
Example #22
0
 def post(self, *args, **kwargs):
     ''' Check validity of flag submissions '''
     flag = Flag.by_uuid(self.get_argument('uuid', ''))
     if flag is not None:
         if flag.is_file and 'flag' in self.request.files:
             submission = self.request.files['flag'][0]['body']
         elif not flag.is_file:
             submission = self.get_argument('token')
         else:
             submission = None
         old_reward = int(flag.value)
         if self.attempt_capture(flag, submission):
             self.render('missions/captured.html', flag=flag, reward=old_reward)
         else:
             self.render_page(flag, errors=["Invalid flag submission"])
     else:
         self.render('public/404.html')
Example #23
0
def create_flag(name,
                token,
                value,
                box,
                description="No description",
                is_file=False,
                is_regex=False,
                is_hash=False):
    print(INFO + "Create flag: " + bold + name + W)
    flag = Flag(
        name=unicode(name),
        token=unicode(token),
        is_file=is_file,
        is_regex=is_regex,
        is_hash=is_hash,
        description=unicode(description),
        value=value,
        box_id=box.id,
    )
    dbsession.add(flag)
    dbsession.flush()
Example #24
0
 def edit_flags(self):
     ''' Super ugly code, yes - Edit existing flags in the database '''
     form = Form(
         uuid="Object not selected",
         name="Please enter a name",
         token="Please enter a toke value",
         description="Please provide a description",
         value="Please enter a reward value",
         box_uuid="Please select a box",
     )
     if form.validate(self.request.arguments):
         flag = Flag.by_uuid(self.get_argument('uuid'))
         if flag is not None:
             errors = []
             if flag.name != self.get_argument('name'):
                 if Flag.by_name(unicode(
                         self.get_argument('name'))) is None:
                     logging.info("Updated flag name %s -> %s" % (
                         flag.name,
                         self.get_argument('name'),
                     ))
                     flag.name = unicode(self.get_argument('name'))
                 else:
                     errors.append("Flag name already exists")
             if flag.token != self.get_argument('token'):
                 if Flag.by_token(unicode(
                         self.get_argument('token'))) is None:
                     logging.info("Updated %s's token %s -> %s" % (
                         flag.name,
                         flag.token,
                         self.get_argument('token'),
                     ))
                     flag.token = unicode(self.get_argument('token'))
                 else:
                     errors.append("Token is not unique")
             if flag.description != self.get_argument('description'):
                 logging.info("Updated %s's description %s -> %s" % (
                     flag.name,
                     flag.description,
                     self.get_argument('description'),
                 ))
                 flag.description = unicode(
                     self.get_argument('description'))
             try:
                 reward_value = int(self.get_argument('value'))
                 if reward_value != flag.value:
                     logging.info("Updated %s's value %d -> %d" % (
                         flag.name,
                         flag.value,
                         reward_value,
                     ))
                     flag.value = reward_value
             except ValueError:
                 errors.append("Invalid reward amount")
             box = Box.by_uuid(self.get_argument('box_uuid'))
             if box is not None and box.id != flag.box_id:
                 logging.info("Updated %s's box %d -> %d" %
                              (flag.name, flag.box_id, box.id))
                 flag.box_id = box.id
             elif box is None:
                 errors.append("Box does not exist")
             dbsession.add(flag)
             dbsession.flush()
             self.render("admin/view/game_objects.html", errors=errors)
         else:
             self.render("admin/view/game_objects.html",
                         errors=["Flag does not exist"])
     else:
         self.render("admin/view/game_objects.html", errors=form.errors)
Example #25
0
 def flags(self, request):
     return Flag.flag_list(request)
Example #26
0
 def flag(self, request):
     return Flag.get_flag(urlsafe=request.s).flag_message
Example #27
0
 def delete_flag(self, request):
     Flag.delete_flag(request.s)
     return message_types.VoidMessage()
Example #28
0
 def vote(self, request):
     # TODO: MAke this POST not GET.
     Flag.vote(request)
     return message_types.VoidMessage()
Example #29
0
 def edit_flags(self):
     ''' Super ugly code, yes - Edit existing flags in the database '''
     form = Form(
         uuid="Object not selected",
         name="Please enter a name",
         token="Please enter a toke value",
         description="Please provide a description",
         value="Please enter a reward value",
         box_uuid="Please select a box",
     )
     if form.validate(self.request.arguments):
         flag = Flag.by_uuid(self.get_argument('uuid'))
         if flag is not None:
             errors = []
             if flag.name != self.get_argument('name'):
                 if Flag.by_name(unicode(self.get_argument('name'))) is None:
                     logging.info("Updated flag name %s -> %s" %
                         (flag.name, self.get_argument('name'),)
                     )
                     flag.name = unicode(self.get_argument('name'))
                 else:
                     errors.append("Flag name already exists")
             if flag.token != self.get_argument('token'):
                 if Flag.by_token(unicode(self.get_argument('token'))) is None:
                     logging.info("Updated %s's token %s -> %s" %
                         (flag.name, flag.token, self.get_argument('token'),)
                     )
                     flag.token = unicode(self.get_argument('token'))
                 else:
                     errors.append("Token is not unique")
             if flag.description != self.get_argument('description'):
                 logging.info("Updated %s's description %s -> %s" %
                     (flag.name, flag.description, self.get_argument('description'),)
                 )
                 flag.description = unicode(self.get_argument('description'))
             try:
                 reward_value = int(self.get_argument('value'))
                 if reward_value != flag.value:
                     logging.info("Updated %s's value %d -> %d" %
                         (flag.name, flag.value, reward_value,)
                     )
                     flag.value = reward_value
             except ValueError:
                 errors.append("Invalid reward amount")
             box = Box.by_uuid(self.get_argument('box_uuid'))
             if box is not None and box.id != flag.box_id:
                 logging.info("Updated %s's box %d -> %d" %
                     (flag.name, flag.box_id, box.id)
                 )
                 flag.box_id = box.id
             elif box is None:
                 errors.append("Box does not exist")
             dbsession.add(flag)
             dbsession.flush()
             self.render("admin/view/game_objects.html", errors=errors)
         else:
             self.render("admin/view/game_objects.html",
                 errors=["Flag does not exist"]
             )
     else:
         self.render("admin/view/game_objects.html", errors=form.errors)