def capture(self, attacker): if attacker is None: raise ValueError('Parameter "attacker" cannot be None!') if isinstance(attacker, GameTeam): api_info( 'SCORING-ASYNC', 'Flag "%s" was captured by "%s"!' % (self.get_canonical_name(), attacker.get_canonical_name())) with atomic(): self.captured = attacker flag_stolen_value = int( self.team.game.get_option('flag_stolen_rate')) if flag_stolen_value > 0: self.team.set_flags(-1 * flag_stolen_value) else: multiplier = self.team.game.get_option( 'flag_captured_multiplier') self.team.set_flags(-1 * self.value * multiplier) api_score(self.id, 'FLAG-STOLEN', self.get_canonical_name(), -1 * self.value * multiplier, self.team.get_canonical_name()) attacker.set_flags(self.value * multiplier) api_score(self.id, 'FLAG-STOLEN-ATTCKER', self.get_canonical_name(), self.value * multiplier, attacker.get_canonical_name()) del multiplier api_event( self.team.game, 'A Flag from %s was stolen by %s!' % (self.team.name, attacker.name)) self.save() else: raise ValueError( 'Parameter "attacker" must be a "GameTeam" object type!')
def close_ticket(self): if self.closed: return with atomic(): self.closed = True if self.type == 1: self.team.set_tickets(self.total) api_debug( 'SCORING-ASYNC', 'Giving Team "%s" back "%d" points for closing a Ticket "%s"!' % (self.team.get_canonical_name(), self.total, self.name)) api_score(self.id, 'TICKET-CLOSE', self.team.get_canonical_name(), self.total) else: self.team.set_tickets(self.total / 2) api_debug( 'SCORING-ASYNC', 'Giving Team "%s" back "%d" points for closing a Ticket "%s"!' % (self.team.get_canonical_name(), self.total / 2, self.name)) api_score(self.id, 'TICKET-CLOSE', self.team.get_canonical_name(), self.total / 2) api_info( 'SCORING-ASYNC', 'Team "%s" closed Ticket "%s" type "%s"!' % (self.team.get_canonical_name(), self.name, self.get_type_display())) api_event( self.team.game, 'Team %s just closed a Ticket "%s"!' % (self.team.name, self.name)) self.save()
def round_score(self): self.scored = None api_debug("SCORING", 'Host "%s" is being scored!' % self.get_canonical_name()) score = self.get_score() api_score(self.id, "HOST", self.get_canonical_name(), score) self.team.set_uptime(score) del score self.save()
def score_job(self, job, job_data): api_debug( 'SCORING', 'Begin Host scoring on Host "%s"' % self.get_canonical_name()) with atomic(): if self.ping_min == 0: ping_ratio = int(self.team.game.get_option('host_ping_ratio')) else: ping_ratio = self.ping_min try: ping_sent = int(job_data['ping_sent']) ping_respond = int(job_data['ping_respond']) try: self.ping_last = math.floor( (float(ping_respond) / float(ping_sent)) * 100) self.online = (self.ping_last >= ping_ratio) except ZeroDivisionError: self.online = False self.ping_last = 0 api_debug( 'SCORING', 'Host "%s" was set "%s" by Job "%d".' % (self.fqdn, ('Online' if self.online else 'Offline'), job.id)) self.save() except ValueError: api_error( 'SCORING', 'Error translating ping responses from Job "%d"!' % job.id) self.online = False self.ping_last = 0 self.save() if 'services' not in job_data and self.online: api_error( 'SCORING', 'Host "%s" was set online by Job "%d" but is missing services!' % (self.fqdn, job.id)) return for service in self.services.all(): if not self.online: service.status = 2 service.save() else: for job_service in job_data['services']: try: if service.port == int(job_service['port']) and \ service.get_protocol_display().lower() == job_service['protocol'].lower(): service.score_job(job, job_service) break except ValueError: pass api_debug( 'SCORING', 'Finished scoring Host "%s" by Job "%d".' % (self.fqdn, job.id)) api_score(self.id, 'HOST-JOB', self.get_canonical_name(), 0)
def score_job(self, job, job_data): if 'status' not in job_data: api_error( 'SCORING', 'Invalid Service "%s" JSON data by Job "%d"!' % (self.get_canonical_name(), job.id)) return with atomic(): service_status = self.status job_status = job_data['status'].lower() for status_value in CONST_GRID_SERVICE_STATUS_CHOICES: if status_value[1].lower() == job_status: service_status = status_value[0] break if service_status == 0 and self.bonus and not self.bonus_started: self.bonus_started = True self.status = service_status self.save() api_debug( 'SCORING', 'Service "%s" was set "%s" by Job "%d".' % (self.get_canonical_name(), self.get_status_display(), job.id)) if 'content' in job_data and self.content is not None: if 'status' in job_data['content']: try: self.content.status = int(job_data['content']['status']) api_debug( 'SCORING', 'Service Content for "%s" was set to "%d" by Job "%d".' % (self.get_canonical_name(), self.content.status, job.id)) except ValueError: self.content.status = 0 api_error( 'SCORING', 'Service Content for "%s" was invalid in Job "%d".' % (self.get_canonical_name(), job.id)) else: self.content.status = 0 api_error( 'SCORING', 'Service Content for "%s" was invalid in Job "%d".' % (self.get_canonical_name(), job.id)) self.content.save() elif self.content is not None: self.content.status = 0 self.content.save() api_error( 'SCORING', 'Service Content for "%s" was ignored by Job "%d".' % (self.get_canonical_name(), job.id)) api_debug( 'SCORING', 'Finished scoring Service "%s" by Job "%d".' % (self.get_canonical_name(), job.id)) api_score(self.id, 'SERVICE-JOB', self.get_canonical_name(), 0)
def round_score(self): if self.__bool__(): api_debug( 'SCORING', 'Beacon "%d" by "%s" is still on Host "%s"!' % (self.id, self.attacker.get_canonical_name(), self.host.get_fqdn())) beacon_value = -1 * int( self.host.team.game.get_option('beacon_value')) api_score(self.id, 'BEACON', self.host.team.get_canonical_name(), beacon_value, self.attacker.get_canonical_name()) self.host.team.set_beacons(beacon_value) del beacon_value
def round_score(self, score_time): if self.can_score(score_time): api_debug('SCORING', 'Scoring Tickect "%s"..' % self.get_canonical_name()) if self.total < int(self.team.game.get_option('ticket_max_score')): with atomic(): ticket_score = int( self.team.game.get_option('ticket_cost')) self.total = self.total + ticket_score self.team.set_tickets(-1 * ticket_score) api_score(self.id, 'TICKET', self.team.get_canonical_name(), -1 * ticket_score) api_info( 'SCORING', 'Team "%s" lost "%d" points to open Ticket "%s"!' % (self.team.get_canonical_name(), ticket_score, self.name)) self.save()
def reopen_ticket(self): if not self.closed: return with atomic(): self.closed = False reopen_cost = float( float(self.team.game.get_option('ticket_reopen_multiplier')) / 100) score_value = -1 * (reopen_cost * self.total) self.team.set_tickets(score_value) api_score(self.id, 'TICKET-REOPEN', self.team.get_canonical_name(), score_value) api_info( 'SCORING-ASYNC', 'Team "%s" had the Ticket "%s" reopened, negating "%d" points!' % (self.team.get_canonical_name(), self.name, score_value)) del score_value api_event( self.team.game, 'Ticket "%s" for %s was reopened!' % (self.name, self.team.name)) self.save()
def api_purchase(request, team_id=None): if request.method == METHOD_GET: api_debug('STORE', 'Requesting the exchange rate for Team "%s"' % team_id, request) if team_id is None: api_error('STORE', 'Attempted to use Null Team ID!', request) return HttpResponseNotFound( '{"message": "SBE API: Team could not be found!"}') try: team = GameTeam.objects.get( store=int(team_id), game__status=CONST_GAME_GAME_RUNNING) except ValueError: api_error( 'STORE', 'Attempted to use an invalid Team ID "%s"!' % str(team_id), request) return HttpResponseNotFound( '{"message": "SBE API: Invalid Team ID!"}') except GameTeam.DoesNotExist: api_error( 'STORE', 'Attempted to use an non-existent Team ID "%s"!' % str(team_id), request) return HttpResponseNotFound( '{"message": "SBE API: Team could not be found!"}') except GameTeam.MultipleObjectsReturned: api_error( 'STORE', 'Attempted to use a Team ID which returned multiple Teams!', request) return HttpResponseNotFound( '{"message": "SBE API: Team could not be found!"}') rate = float(team.game.get_option('score_exchange_rate')) / 100.0 api_debug( 'STORE', 'The exchange rate for Team "%s" is "%.2f"!' % (team.get_canonical_name(), rate), request) return HttpResponse(status=200, content='{"rate": %.2f}' % rate) if request.method == METHOD_POST: try: decoded_data = request.body.decode('UTF-8') except UnicodeDecodeError: api_error('STORE', 'Data submitted is not encoded properly!', request) return HttpResponseBadRequest( content= '{"message": "SBE API: Incorrect encoding, please use UTF-8!"}' ) try: json_data = json.loads(decoded_data) del decoded_data except json.decoder.JSONDecodeError: api_error('STORE', 'Data submitted is not in correct JSON format!', request) return HttpResponseBadRequest( content= '{"message": "SBE API: Not in a valid JSON format!"]') if 'team' not in json_data or 'order' not in json_data: api_error('STORE', 'Data submitted is missing JSON fields!', request) return HttpResponseBadRequest( content= '{"message": "SBE API: Not in a valid JSON format!"}') try: team = GameTeam.objects.get( store=int(json_data['team']), game__status=CONST_GAME_GAME_RUNNING) except ValueError: api_error( 'STORE', 'Attempted to use an invalid Team ID "%s"!' % str(team_id), request) return HttpResponseNotFound( '{"message": "SBE API: Invalid Team ID!"}') except GameTeam.DoesNotExist: api_error( 'STORE', 'Attempted to use an non-existent Team ID "%s"!' % str(team_id), request) return HttpResponseNotFound( '{"message": "SBE API: Team could not be found!"}') except GameTeam.MultipleObjectsReturned: api_error( 'STORE', 'Attempted to use a Team ID which returned multiple Teams!', request) return HttpResponseNotFound( '{"message": "SBE API: Team could not be found!"}') api_info( 'STORE', 'Attempting to add Purchase records for Team "%s".' % team.get_canonical_name(), request) if not isinstance(json_data['order'], list): api_error('STORE', 'Data submitted is missing the "oreer" array!', request) return HttpResponseBadRequest( content='{"message": "SBE API: Not in valid JSON format!"}' ) for order in json_data['order']: if 'item' in order and 'price' in order: try: with atomic(): purchase = Purchase() purchase.team = team purchase.amount = int( float(order['price']) * (float( team.game.get_option( 'score_exchange_rate')) / 100.0)) purchase.item = (order['item'] if len(order['item']) < 150 else order['item'][:150]) team.set_uptime(-1 * purchase.amount) purchase.save() api_score(team.id, 'PURCHASE', team.get_canonical_name(), purchase.amount, purchase.item) api_debug( 'STORE', 'Processed order of "%s" "%d" for team "%s"!' % (purchase.item, purchase.amount, team.get_canonical_name()), request) del purchase except ValueError: api_warning( 'STORE', 'Order "%s" has invalid integers for amount!!' % str(order), request) else: api_warning( 'STORE', 'Order "%s" does not have the correct format!' % str(order), request) return HttpResponse(status=200, content='{"message": "processed"}') return HttpResponseBadRequest( content='{"message": "SBE API: Not a supported method type!"}')
def api_transfer(request): if request.method == METHOD_POST: try: decoded_data = request.body.decode('UTF-8') except UnicodeDecodeError: api_error('TRANSFER', 'Data submitted is not encoded properly!', request) return HttpResponseBadRequest( content= '{"message": "SBE API: Incorrect encoding, please use UTF-8!"}' ) try: json_data = json.loads(decoded_data) del decoded_data except json.decoder.JSONDecodeError: api_error('TRANSFER', 'Data submitted is not in correct JSON format!', request) return HttpResponseBadRequest( content= '{"message": "SBE API: Not in a valid JSON format!"]') if 'target' not in json_data or 'dest' not in json_data or 'amount' not in json_data: api_error('TRANSFER', 'Data submitted is missing JSON fields!', request) return HttpResponseBadRequest( content= '{"message": "SBE API: Not in a valid JSON format!"}') if json_data['target'] is None and json_data['dest'] is None: api_error('TRANSFER', 'Cannot transfer from Gold to Gold!', request) return HttpResponseBadRequest( content= '{"message": "SBE API: Cannot transfer from Gold to Gold!"}' ) team_to = None team_from = None try: amount = int(json_data['amount']) except ValueError: api_error('TRANSFER', 'Amount submitted is is invalid!', request) return HttpResponseBadRequest( content='{"message": "SBE API: Invalid amount!"}') if amount <= 0: api_error('TRANSFER', 'Amount submitted is is invalid!', request) return HttpResponseBadRequest( content='{"message": "SBE API: Invalid amount!"}') if json_data['dest'] is not None: try: team_token = Token.objects.get( uuid=uuid.UUID(json_data['dest'])) team_to = GameTeam.objects.get(token=team_token) del team_token except ValueError: api_error('TRANSFER', 'Token given for Destination is invalid!', request) return HttpResponseBadRequest( content= '{"message": "SBE API: Invalid Destination Token!"}') except Token.DoesNotExist: api_error('TRANSFER', 'Token given for Destination is invalid!', request) return HttpResponseBadRequest( content= '{"message": "SBE API: Invalid Destination Token!"}') except GameTeam.DoesNotExist: api_error('TRANSFER', 'Team given for Destination does not exist!', request) return HttpResponseBadRequest( content= '{"message": "SBE API: Destination Team does not exist!"}' ) if json_data['target'] is not None: try: team_token = Token.objects.get( uuid=uuid.UUID(json_data['target'])) team_from = GameTeam.objects.get(token=team_token) del team_token except ValueError: api_error('TRANSFER', 'Token given for Source is invalid!', request) return HttpResponseBadRequest( content='{"message": "SBE API: Invalid Source Token!"}' ) except Token.DoesNotExist: api_error('TRANSFER', 'Token given for Source is invalid!', request) return HttpResponseBadRequest( content='{"message": "SBE API: Invalid Source Token!"}' ) except GameTeam.DoesNotExist: api_error('TRANSFER', 'Team given for Source does not exist!', request) return HttpResponseBadRequest( content= '{"message": "SBE API: Source Team does not exist!"}') if team_to is not None and team_to.game.status != CONST_GAME_GAME_RUNNING: api_error( 'TRANSFER', 'Game "%s" submitted is not Running!' % team_to.gane.name, request) return HttpResponseBadRequest( content='{"message": "SBE API: Team Game ius not running!"}' ) if team_from is not None and team_from.game.status != CONST_GAME_GAME_RUNNING: api_error( 'TRANSFER', 'Game "%s" submitted is not Running!' % team_from.gane.name, request) return HttpResponseBadRequest( content='{"message": "SBE API: Team Game ius not running!"}' ) if team_to is not None and team_from is not None and team_to.game.id != team_from.game.id: api_error('TRANSFER', 'Transfer teams are not in the same Game!', request) return HttpResponseBadRequest( content= '{"message": "SBE API: Teams are not in the same Game!"}') with atomic(): if team_from is not None: team_from.set_uptime(-1 * amount) api_score(team_from.id, 'TRANSFER', team_from.get_canonical_name(), -1 * amount, ('GoldTeam' if team_to is None else team_to.get_canonical_name())) if team_to is not None: team_to.set_uptime(amount) api_score(team_to.id, 'TRANSFER', team_to.get_canonical_name(), amount, ('GoldTeam' if team_from is None else team_from.get_canonical_name())) return HttpResponse(status=200, content='{"message": "transferred"}') return HttpResponseBadRequest( content='{"message": "SBE API: Not a supported method type!"}')
def api_beacon(request): if request.method == METHOD_POST: team, token, data, exception = game_team_from_token( request, 'CLI', 'token', beacon=True, fields=['address']) if exception is not None: return exception address_raw = data['address'] try: address = IPAddress(address_raw) except AddrFormatError: api_error( 'BEACON', 'IP Reported by Team "%s" is invalid!' % team.get_canonical_name(), request) return HttpResponseBadRequest( content='{"message": "SBE API: Invalid IP Address!"}') target_team = None for sel_target_team in team.game.teams.all(): try: target_subnet = IPNetwork(sel_target_team.subnet) except AddrFormatError: api_warning( 'BEACON', 'Team "%s" subnet is invalid, skipping Team!' % team.get_canonical_name(), request) continue if address in target_subnet: api_debug( 'BEACON', 'Beacon from Team "%s" to Team "%s"\'s subnet!' % (team.get_canonical_name(), sel_target_team.get_canonical_name()), request) target_team = sel_target_team del target_subnet break del target_subnet del address try: host = Host.objects.get( ip=address_raw, team__game__status=CONST_GAME_GAME_RUNNING) if host.team.game.id != team.game.id: api_error( 'BEACON', 'Host accessed by Team "%s" is not in the same game as "%s"!' % (team.get_canonical_name(), host.team.get_canonical_name()), request) return HttpResponseForbidden( '{"message": "SBE API: Host is not in the same Game!"}' ) try: beacon = host.beacons.get(beacon__finish__isnull=True, beacon__attacker=team, beacon__token=token) beacon.checkin = timezone.now() beacon.save() api_info( 'BEACON', 'Team "%s" updated the Beacon on Host "%s"!' % (team.get_canonical_name(), host.get_canonical_name()), request) return HttpResponse() except GameCompromiseHost.MultipleObjectsReturned: api_warning( 'BEACON', 'Team "%s" attempted to create multiple Beacons on a Host "%s"!' % (team.get_canonical_name(), host.get_canonical_name()), request) del host del address_raw return HttpResponseForbidden( '{"message": "SBE API: Already a Beacon on that Host!"}' ) except GameCompromiseHost.DoesNotExist: if host.beacons.filter( beacon__finish__isnull=True).count() > 1: api_warning( 'BEACON', 'Team "%s" attempted to create multiple Beacons on a Host "%s"!' % (team.get_canonical_name(), host.get_canonical_name()), request) del host del address_raw return HttpResponseForbidden( '{"message": "SBE API: Already a Beacon on that Host!"}' ) with atomic(): beacon = GameCompromise() beacon_host = GameCompromiseHost() beacon_host.ip = address_raw beacon_host.team = host.team beacon_host.host = host beacon.token = token beacon.attacker = team beacon.save() beacon_host.beacon = beacon beacon_host.save() api_event( team.game, 'A Host on %s\'s network was compromised by "%s" #PvJCTF #CTF #BSidesLV!' % (host.team.name, team.name)) beacon_value = int( team.game.get_option('beacon_value')) team.set_beacons(beacon_value) api_info( 'SCORING-ASYNC', 'Beacon score was applied to Team "%s"!' % team.get_canonical_name(), request) api_score(beacon.id, 'BEACON-ATTACKER', team.get_canonical_name(), beacon_value, beacon_host.get_fqdn()) del beacon_value del beacon del beacon_host del address_raw api_info( 'BEACON', 'Team "%s" added a Beacon to Host "%s"!' % (team.get_canonical_name(), host.get_canonical_name()), request) return HttpResponse(status=201) except Host.DoesNotExist: if target_team is not None: api_info( 'BEACON', 'Host accessed by Team "%s" does not exist! Attempting to create a faux Host!' % team.get_canonical_name(), request) if GameCompromiseHost.objects.filter( ip=address_raw, beacon__finish__isnull=True).count() > 0: api_warning( 'BEACON', 'Team "%s" attempted to create multiple Beacons on a Host "%s"!' % (team.get_canonical_name(), address_raw), request) del address_raw return HttpResponseForbidden( '{"message": "SBE API: Already a Beacon on that Host!"}' ) with atomic(): beacon_host = GameCompromiseHost() beacon_host.ip = address_raw beacon_host.team = target_team beacon = GameCompromise() beacon.token = token beacon.attacker = team beacon.save() beacon_host.beacon = beacon beacon_host.save() api_event( team.game, 'A Host on %s\'s network was compromised by "%s" #PvJCTF #CTF #BSidesLV!' % (target_team.name, team.name)) beacon_value = int( team.game.get_option('beacon_value')) team.set_beacons(beacon_value) api_info( 'SCORING-ASYNC', 'Beacon score was applied to Team "%s"!' % team.get_canonical_name(), request) api_score(beacon.id, 'BEACON-ATTACKER', team.get_canonical_name(), beacon_value, beacon_host.get_fqdn()) del beacon_value del beacon del beacon_host api_info( 'BEACON', 'Team "%s" added a Beacon to Host "%s"!' % (team.get_canonical_name(), address_raw), request) del address_raw return HttpResponse(status=201) del address_raw api_error( 'BEACON', 'Host accessed by Team "%s" does not exist and a hosting team cannot be found!' % team.get_canonical_name(), request) return HttpResponseNotFound( '{"message": "SBE API: Host does not exist!"}') except Host.MultipleObjectsReturned: api_error( 'BEACON', 'Host accessed by Team "%s" returned multiple Hosts, invalid!' % team.get_canonical_name(), request) return HttpResponseNotFound( '{"message": "SBE API: Host does not exist!"}') return HttpResponseBadRequest( content='{"message": "SBE API: Not a supported method type!"}')