class GameSummaryScreen(MenuScreen): """ Class representing summary of the game screen, inherited class MenuScreen """ def __init__(self, click_count, board_size): self.click_count = click_count self.board_size = board_size self.user_name = "" self.board_name = f"{self.board_size}x{self.board_size}" self._scale_factor = Settings.get_scale_factor() self.scores = Scores(self.board_name) self.show_input = self.scores.is_score_rated(self.click_count) menu_button = Button(Localization.get_text('menu')) menu_button.click_method = lambda: MainMenuScreen() buttons = [menu_button] super().__init__(buttons, Localization.get_text('congratulations')) def show(self, game): text_ = str.format("{0} {1}.", Localization.get_text('score'), self.click_count) text = CenteredText(text_, 40, (0, 0, 0)) text.write(game.window, y=game.window.get_height() / 2 - 4 * text.size) if self.show_input: text = CenteredText(Localization.get_text('enter_name'), 20 * self._scale_factor, (0, 0, 0)) text.write(game.window, y=game.window.get_height() / 2 - 2 * text.size) rect_width = int(300 * self._scale_factor) rect_height = int(50 * self._scale_factor) rect_location = ((game.window.get_width() - rect_width) / 2, (game.window.get_height() + 1.5 * rect_height) / 2) rect = Rect(rect_location, (rect_width, rect_height)) pygame.draw.rect(game.window, (255, 255, 255), rect) user_name_text = CenteredText(self.user_name, 20 * self._scale_factor, (0, 0, 0)) user_name_text.write(game.window, rect) for event in game.events: if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: if len(self.user_name) > 0: self.scores.add_score(self.user_name, self.click_count) return ScoresScreen(self.board_name) elif event.key == pygame.K_BACKSPACE: self.user_name = self.user_name[:-1] elif event.key != pygame.K_COMMA and len( self.user_name) <= 16: self.user_name += event.unicode return super().show(game)
def __init__(self, teamname, hostname, value, dns_servers, msgqueue, BToqueue, BTequeue, timeout=180): ''' Constructor ''' threading.Thread.__init__(self) self.hostname = hostname self.dns_servers = dns_servers self.basename = "%s-%s" % (teamname, hostname) self.BToqueue = BToqueue self.BTequeue = BTequeue self.logger = ThreadedLogger(self.basename) self.equeue = self.logger.get_equeue() self.oqueue = self.logger.get_oqueue() self.logger.start() self.ipaddress = None self.compromised = False self.services = {} self.service_queues = {} self.service_rounds = {} self.service_scores = {} self.value = value self.scores = Scores() self.timeout = timeout self.msgqueue = msgqueue self.latest_round = 1
def __init__(self, port, protocol, value, logger, uri="index.html", \ content=None, username=None, password=None): ''' Constructor ''' self.logger = logger self.port = port self.protocol = protocol self.value = float(value) self.scores = Scores() self.uri = "GET /%s\r\n\r\n" % uri self.up = False self.functional = False self.content = content if self.content: self.content_re = re.compile(str(self.content)) else: self.content_re = None if password: self.password = password else: self.password = "******" if username: self.username = username else: self.username = "******" self.mail_re = re.compile("220")
def __init__(self, teamname, hostname, value, logger, dns_servers, msgqueue, timeout=180): ''' Constructor ''' threading.Thread.__init__(self) self.hostname = hostname self.dns_servers = dns_servers basename = "%s-%s" % (teamname, hostname) self.logger = Logger(basename) self.ipaddress = None self.compromised = False self.services = {} self.service_queues = {} self.service_rounds = {} self.value = value self.scores = Scores() self.timeout = timeout self.msgqueue = msgqueue
def chooseBest(self, img, refDigits, erd, dlt): '''Given the reference digits and the single digit from th imput img, choose the best candidate.''' start = time.perf_counter() # initialize a list of template matching scores high = -9999999.99 d = -1 # loop over the reference digit name and digit ROI for (digit, digitROI) in refDigits.all().items(): # apply correlation-based template matching, take the result = cv.matchTemplate(img, digitROI, cv.TM_CCOEFF) (_, score, _, _) = cv.minMaxLoc(result) scores = Scores(self.number) scores.result[scores.cnt][digit] = score # print('score: {:10.1f}'.format(score) ) if score > high and score > 0: high = score d = digit # print('digit :{:02d}, score: {:0.2f}'.format(digit, score)) # scores.append(score) lap = time.perf_counter() # print('chooseBest processing time: {:4.2f}'.format(lap-start)) scores.cnt = scores.cnt + 1 print( 'number: {:3d} erd: {:2d} dlt: {:2d} digit: {:3d} score: {:10.1f} time: {:4.2f}' .format(self.number, erd, dlt, d, high, (lap - start))) print('scores: '.format(scores)) return d
def initUI(self): # перемещение self.move(300, 300) # фиксируем ширину и высоту поля self.setFixedSize(Arkanoid.W, Arkanoid.H) # задаём имя программы self.setWindowTitle('Арканоид') # загружаем фоновое изображение self.background = QImage('background.jpg') # создаём кубики self.cubes = Cubes() # созаём ракетку self.racket = Racket(Arkanoid.W / 2 - Racket.W / 2) # создаём шарик self.ball = Ball(Arkanoid.W / 2, Racket.Y - Ball.R, 60) # создаём надпись self.label = Label(150, Arkanoid.H // 2, Arkanoid.W - 300, 60) # создаем очки self.scores = Scores(0, 9, Arkanoid.W, 30) # создаём таймер self.timer = QtCore.QTimer() # заканчиваем время self.timer.timeout.connect(self.tick) # задаём начало счётчика self.timer.start(2) # включаем отслеживание мыши self.setMouseTracking(1) # переходим в состояние запуска self.restart()
class NetworkMultiplayer: def __init__(self): self.server = Server("",12345) self.scores = Scores() def Game(self): self.scores.openForRead() self.server.waiting_room()
def test_clarity(self): scores = Scores(102) a = list('102') self.load(scores) scores.clarity() s = len(scores.clardicts) for d in range(s): self.assertEqual(1.0, max(scores.clardicts[d].values())) for x, y in scores.clardicts[d].items(): if y == 1.0: self.assertEqual(a[d], str(x))
def __init__(self, teamname, start_time, flags, this_round=1, current_score=0, id=None, db=None, queue=None, interval=300): ''' Constructor ''' threading.Thread.__init__(self) self.id = id self.db = db self.queue_obj = queue self.dns_servers = [] self.teamname = teamname self.logger = ThreadedLogger(self.teamname) self.equeue = self.logger.get_equeue() self.oqueue = self.logger.get_equeue() self.logger.start() self.hosts = {} self.hosts_rounds = {} self.host_queues = {} self.start_time = start_time self.go_time = self.start_time self.interval = interval self.did_time = None # Number of rounds finished self.this_round = this_round self.flag_store = flags self.current_score = current_score self.last_flag_score = 0 self.last_ticket_score = 0 self.nets = [] self.pp = pprint.PrettyPrinter(indent=2) self.email = "" self.ticket_obj = None self.inround = False self.game_queue = None # Score variables self.scores = Scores() self.ticket_scores = {} self.flag_scores = {} self.beacon_scores = {} self.service_scores = {}
def __init__(self, teamname, start_time, flags, this_round=1, current_score=0, id=None, db=None, queue=None, interval=300): ''' Constructor ''' threading.Thread.__init__(self) self.id = id self.db = db self.queue_obj = queue now = time.strftime("%Y %b %d %H:%M:%S", time.localtime(time.time())) self.dns = dns.resolver.Resolver() self.del_dns("8.8.8.8") #self.add_dns("10.0.1.50") self.teamname = teamname self.logger = Logger(self.teamname) self.logger.err("\n" + globalvars.sep + "\n") self.logger.err("| Starting run for Blueteam %s\n" % self.teamname) self.logger.err("| Start time: %s\n" % now) self.logger.out(globalvars.sep + "\n") self.logger.out("| Starting run for Blueteam %s\n" % self.teamname) self.logger.out("| Start time: %s\n" % now) self.hosts = {} self.scores = Scores() self.start_time = start_time self.go_time = self.start_time self.interval = interval self.did_time = None # Number of rounds finished self.this_round = this_round self.flag_store = flags self.current_score = current_score self.last_flag_score = 0
def __init__(self, teamname, start_time, flags, this_round=1, current_score=0, id=None, db=None, queue=None, interval=300): ''' Constructor ''' threading.Thread.__init__(self) self.id = id self.db = db self.queue_obj = queue now = time.strftime("%Y %b %d %H:%M:%S", time.localtime(time.time())) self.dns_servers = [] self.teamname = teamname self.logger = Logger(self.teamname) self.logger.err("\n" + globalvars.sep + "\n") self.logger.err("| Starting run for Blueteam %s\n" % self.teamname) self.logger.err("| Start time: %s\n" % now) self.logger.out(globalvars.sep + "\n") self.logger.out("| Starting run for Blueteam %s\n" % self.teamname) self.logger.out("| Start time: %s\n" % now) self.hosts = {} self.scores = Scores() self.start_time = start_time self.go_time = self.start_time self.interval = interval self.did_time = None # Number of rounds finished self.this_round = this_round self.flag_store = flags self.current_score = current_score self.last_flag_score = 0 self.last_ticket_score = 0 self.nets = [] self.pp = pprint.PrettyPrinter(indent=2) self.email = "" self.ticket_obj = None
def __init__(self, click_count, board_size): self.click_count = click_count self.board_size = board_size self.user_name = "" self.board_name = f"{self.board_size}x{self.board_size}" self._scale_factor = Settings.get_scale_factor() self.scores = Scores(self.board_name) self.show_input = self.scores.is_score_rated(self.click_count) menu_button = Button(Localization.get_text('menu')) menu_button.click_method = lambda: MainMenuScreen() buttons = [menu_button] super().__init__(buttons, Localization.get_text('congratulations'))
def __init__(self, port, protocol, value, teamname, queue, hostname, \ oqueue, equeue, BToqueue, BTequeue, \ uri="index.html", content=None, username=None, password=None): ''' Constructor ''' threading.Thread.__init__(self) self.hostname = hostname basename = "%s-%s:%s_%s" % (teamname, hostname, port, protocol) #self.logger = Logger(basename) self.oqueue = oqueue self.equeue = equeue self.BToqueue = BToqueue self.BTequeue = BTequeue self.olog = "" self.elog = "" self.port = int(port) self.protocol = protocol self.value = float(value) self.scores = Scores() self.uri = "GET /%s\r\n\r\n" % uri self.up = False self.functional = False self.redcell_here = False self.content = content self.teamname = teamname if self.content: if self.port != 80: self.content_re = re.compile(str(self.content)) else: self.content_re = None if password: self.password = password else: self.password = "******" if username: self.username = username else: self.username = "******" if isinstance(content, dict): self.loginpage = content.get("loginpage") self.user_param = content.get("user_param") self.pwd_param = content.get("pwd_param") self.pages = content.get("pages") self.mail_re = re.compile("220") self.msg_queue = queue
def __init__(self, hostname, value, logger, dns=None, timeout=300): ''' Constructor ''' self.hostname = hostname if dns: self.dns = dns else: self.dns = dns.resolver.Resolver() self.logger = logger self.dns.lifetime = 3 self.ipaddress = None self.compromised = False self.services = {} self.value = value self.scores = Scores() self.timeout = timeout
def __init__(self, board_name): self.board_name = board_name scores = Scores(board_name) self.scores = scores._get_scores_for_board() self._scale_factor = Settings.get_scale_factor() self._font_size = int(20 * self._scale_factor) self._user_name_x_shift = int(200 * self._scale_factor) self._score_x_shift = int(350 * self._scale_factor) clear_scores_button = Button(Localization.get_text('clear_scores')) clear_scores_button.click_method = lambda: (scores.clear_scores(), ScoresScreen(self.board_name))[1] back_button = Button(Localization.get_text('back')) back_button.click_method = lambda: GameTypePickerScreen('best_scores', lambda x: ScoresScreen(x)) buttons = (clear_scores_button, back_button) super().__init__(buttons, f"{Localization.get_text('best_scores')} {self.board_name}")
def __init__(self, teamname, start_time, flags, this_round=1, current_score=0, id=None, db=None, queue=None, interval=300): ''' Constructor ''' threading.Thread.__init__(self) self.id = id self.db = db self.queue_obj = queue now = time.strftime("%Y %b %d %H:%M:%S", time.localtime(time.time())) self.dns_servers = [] self.teamname = teamname self.logger = Logger(self.teamname) self.logger.err("\n" + globalvars.sep + "\n") self.logger.err("| Starting run for Blueteam %s\n" % self.teamname) self.logger.err("| Start time: %s\n" % now) self.logger.out(globalvars.sep + "\n") self.logger.out("| Starting run for Blueteam %s\n" % self.teamname) self.logger.out("| Start time: %s\n" % now) self.hosts = {} self.hosts_rounds = {} self.host_queues = {} self.start_time = start_time self.go_time = self.start_time self.interval = interval self.did_time = None # Number of rounds finished self.this_round = this_round self.flag_store = flags self.current_score = current_score self.last_flag_score = 0 self.last_ticket_score = 0 self.nets = [] self.pp = pprint.PrettyPrinter(indent=2) self.email = "" self.ticket_obj = None self.inround = False self.game_queue = None # Score variables self.scores = Scores() self.ticket_scores = {} self.flag_scores = {} self.beacon_scores = {} self.service_scores = {}
def __init__(self, hostname, value, logger, dns_servers, timeout=300): ''' Constructor ''' self.hostname = hostname self.dns_servers = dns_servers self.logger = logger self.ipaddress = None self.compromised = False self.services = {} self.value = value self.scores = Scores() self.timeout = timeout
def __init__(self, name, value, duration): ''' Constructor ''' self.name = name self.value = int(value) self.duration = int(duration) * 60 self.challenge = "" self.response = "" self.end_time = None self.delivery = "\r\n\r\nThis task is to be completed by %s today." self.subject = "" self.scores = Scores()
def test_addscore(self): scores = Scores(102) scores.addscore(0, 1, 1000001) scores.addscore(1, 0, 1000001) scores.addscore(2, 2, 1000001) self.assertEqual(scores.result[0][1], 1000001) self.assertEqual(scores.result[1][0], 1000001) self.assertEqual(scores.result[2][2], 1000001)
def File(): userName, className, score, classScores = Scores() # Check if user wishes to re-try quiz while True: try: endProgram = input("Do you wish to exit the quiz? Y or N: ") break except ValueError: endProgram = input("Enter a valid answer: ") break # Writing to file if endProgram == "Y": with open("Class Scores.csv", "a+") as f: FileWriter = csv.writer(f) FileWriter.writerows(classScores.items()) print("You can now exit the quiz, have a great day!") elif endProgram == "N": print("Good luck!") File() else: print("Error, file not created!")
class BlueTeam(threading.Thread): ''' classdocs ''' def __init__(self, teamname, start_time, flags, this_round=1, current_score=0, id=None, db=None, queue=None, interval=300): ''' Constructor ''' threading.Thread.__init__(self) self.id = id self.db = db self.queue_obj = queue self.dns_servers = [] self.teamname = teamname self.logger = ThreadedLogger(self.teamname) self.equeue = self.logger.get_equeue() self.oqueue = self.logger.get_equeue() self.logger.start() self.hosts = {} self.hosts_rounds = {} self.host_queues = {} self.start_time = start_time self.go_time = self.start_time self.interval = interval self.did_time = None # Number of rounds finished self.this_round = this_round self.flag_store = flags self.current_score = current_score self.last_flag_score = 0 self.last_ticket_score = 0 self.nets = [] self.pp = pprint.PrettyPrinter(indent=2) self.email = "" self.ticket_obj = None self.inround = False self.game_queue = None # Score variables self.scores = Scores() self.ticket_scores = {} self.flag_scores = {} self.beacon_scores = {} self.service_scores = {} def set_ticket_interface(self, ticket_obj): self.ticket_obj = ticket_obj def set_email(self, email): self.email = email def get_email(self): return self.email def get_teamname(self): return self.teamname def add_flag(self, name, value, score=1, answer=""): self.flag_store.add(self.teamname, name, value, score, answer) def add_net(self, net): if net in self.nets: pass else: self.nets.append(net) def has_ip(self, ip): for net in self.nets: if net in ip: return True return False def run(self): now = time.strftime("%Y %b %d %H:%M:%S", time.localtime(time.time())) self.equeue.put("\n" + globalvars.sep + "\n") self.equeue.put("| Starting run for Blueteam %s\n" % self.teamname) self.equeue.put("| Start time: %s\n" % now) self.oqueue.put(globalvars.sep + "\n") self.oqueue.put("| Starting run for Blueteam %s\n" % self.teamname) self.oqueue.put("| Start time: %s\n" % now) print "Firing up Blueteam %s, go time is %s" % \ (self.teamname, self.go_time) if globalvars.quick: self.go_time = time.time() + 5 for host in self.hosts: self.hosts[host].start() self.inround = False while True: # Check to see if we have any messages from our hosts for host in self.host_queues: try: item = self.host_queues[host].get(False) if item == "score": #process the host message if host in self.hosts_rounds: #print "Found message from host %s" % host self.hosts_rounds[host] = True else: raise Exception("Unknown host %s\n" % host) else: self.host_queues[host].put(item) except Queue.Empty: pass except: errstr = traceback.format_exc() self.equeue.put(errstr) score_round = True # Check to see if all hosts have finished the last round donemsg = "" finished = [] not_finished = [] for host in self.hosts_rounds: if self.hosts_rounds[host]: donemsg += "%s, " % host finished.append(host) else: score_round = False not_finished.append(host) statfile = open("status/%s.status" % self.teamname, "w") statfile.write("Team %s round %s not finished: \n\t%s\n" % (self.teamname, self.this_round, "\n\t".join(not_finished))) statfile.write("Team %s round %s finished: \n\t%s\n" % (self.teamname, self.this_round, "\n\t".join(finished))) statfile.close() if donemsg: failmsg = "Failed: " for host in self.hosts_rounds: if not self.hosts_rounds[host]: failmsg += host #sys.stdout.write("Done: %s\n" % donemsg) #sys.stdout.write(failmsg) if score_round: #print "Scoring round for %s" % self.teamname self.inround = False for host in self.hosts_rounds: self.hosts_rounds[host] = False self.set_score() self.game_queue.put("Done") now = time.time() # Check to see if it's tme to start the new round, but only if the last is done item = "" try: item = self.game_queue.get(False) if item: #sys.stdout.write("\nGot item for team %s " % self.teamname) #print item if len(item) == 2: if item[0] == "Go": self.this_round = item[1] # Report times so that we know whether or not the last round ran too long self.inround = True print "Starting Service check for Blueteam %s. Go time was %s, now is %s." % \ (self.teamname, self.go_time, now) for host in self.host_queues: self.host_queues[host].put(["Go", self.this_round], 1) else: raise Exception("Unknown queue message %s!" % item[0]) else: self.game_queue.put(item) item = False except Queue.Empty: pass except: errstr = traceback.format_exc() self.equeue.put(errstr) else: time.sleep(0.1) def add_dns(self, dnssvr): if dnssvr in self.dns_servers: pass else: self.oqueue.put("Adding DNS %s to %s\n" % (dnssvr, self.teamname)) self.dns_servers.append(dnssvr) for host in self.hosts: self.hosts[host].add_dns(dnssvr) def del_dns(self, dnssvr): if dnssvr in self.dns_servers: index = self.dns_servers.index(dnssvr) self.dns_servers.pop(index) else: pass for host in self.hosts: self.hosts[host].del_dns(dnssvr) def add_queue(self, queue): self.queue_obj = queue def set_queue(self, queue): self.game_queue = queue def add_host(self, hostname, value): # Have to strip "." because MongoDB doesn't like them for key names clean_hostname = hostname.replace(".", "___") if self.hosts.has_key(clean_hostname): self.equeue.put(clobber_host_blue_str % (self.teamname, hostname)) else: self.equeue.put(add_host_blue_str % (self.teamname, hostname)) this_queue = Queue.Queue() self.hosts[clean_hostname] = Host(self.teamname, hostname, value, self.dns_servers, this_queue, \ self.oqueue, self.equeue) self.hosts_rounds[clean_hostname] = False self.host_queues[clean_hostname] = this_queue def del_host(self, hostname): # Have to strip "." because MongoDB doesn't like them for key names clean_hostname = hostname.replace(".", "___") if self.hosts.has_key(clean_hostname): self.equeue.put(del_host_blue_str % (self.teamname, hostname)) del(self.hosts[clean_hostname]) del(self.host_queues[clean_hostname]) else: self.equeue.put(del_host_blue_err_str % (self.teamname, hostname)) def add_service(self, hostname, port, proto, value, uri=None, content=None, username=None, password=None): # Have to strip "." because MongoDB doesn't like them for key names clean_hostname = hostname.replace(".", "___") if self.hosts.has_key(clean_hostname): self.equeue.put(add_srvc_blue_str % \ (self.teamname, port, proto, value, hostname)) self.hosts[clean_hostname].add_service(self.teamname, port, proto, value, uri, content, \ username, password) else: self.equeue.put(add_srvc_blue_err_str % \ (self.teamname, port, proto, hostname)) def del_service(self, hostname, port, proto): # Have to strip "." because MongoDB doesn't like them for key names clean_hostname = hostname.replace(".", "___") if self.hosts.has_key(clean_hostname): self.equeue.put(add_srvc_blue_str % \ (self.teamname, port, proto, hostname)) self.hosts[clean_hostname].del_service(port, proto, app, value) else: self.equeue.put(add_srvc_blue_err_str % \ (self.teamname, port, proto, hostname)) def get_score(self, this_round=None): if not this_round: if self.inround: this_round = self.this_round - 1 else: this_round = self.this_round #this_score = self.scores.get_score(this_round) this_score = self.scores.total() return [this_round, this_score] def get_score_detail(self): scores = {} if self.inround: current_round = self.this_round - 1 else: current_round = self.this_round scores["round"] = current_round scores["services"] = 0 scores["tickets"] = 0 scores["flags"] = 0 scores["beacons"] = 0 scores["total"] = 0 for round in range(1,current_round+1): if round in self.service_scores: scores["services"] += self.service_scores[round] if round in self.ticket_scores: scores["tickets"] += self.ticket_scores[round] if round in self.flag_scores: scores["flags"] += self.flag_scores[round] if round in self.beacon_scores: scores["beacons"] += self.beacon_scores[round] scores["total"] = self.scores.total() return scores def get_all_rounds(self): scores = {} for round, score in self.scores: scores[round] = score return scores def get_scores(self): team_scores = {} team_scores["hosts"] = {} team_scores["teamscore"] = self.scores for host in self.hosts: host_score = self.hosts[host].get_scores() team_scores["hosts"][host] = host_score team_scores["round"] = self.this_round return team_scores def set_scores(self, team_scores): """ Function to import and process the json object exported by get_scores() """ if "teamscore" in team_scores: self.scores = team_scores["teamscore"] if globalvars.debug: print "Set team score for %s to %s" % (self.teamname, self.scores) json_obj = jsonpickle.encode(self.scores) self.pp.pprint(json_obj) else: json_obj = jsonpickle.encode(team_scores) raise Exception ("Invalid team_scores hash, missing team score! \n%s\n" % json_obj) if "round" in team_scores: self.this_round = team_scores["round"] if globalvars.debug: print "Set round for %s to %s" % (self.teamname, self.this_round) else: json_obj = jsonpickle.encode(team_scores) raise Exception ("Invalid team_scores hash, missing round! \n%s\n" % json_obj) if "hosts" in team_scores: for host in self.hosts: if host in team_scores["hosts"]: self.hosts[host].set_scores(team_scores["hosts"][host]) else: json_obj = jsonpickle.encode(team_scores) raise Exception ("Invalid team_scores hash! \n%s\n" % json_obj) else: json_obj = jsonpickle.encode(team_scores) raise Exception ("Invalid team_scores hash, missing hosts! \n%s\n" % json_obj) def set_score(self, this_round=None, value=None): if this_round and value: this_round = self.this_round self.scores.set_score(this_round, value) return # Service scoring raw_service_score = 0 for host in self.hosts: raw_service_score += self.hosts[host].get_score(self.this_round) service_score = raw_service_score / 10 self.service_scores[self.this_round] = service_score # Ticket scoring (open_tickets, closed_tickets) = self.get_tickets() closed_tickets = int(closed_tickets) open_tickets = int(open_tickets) all_tickets = closed_tickets + open_tickets ticket_score = 0 if closed_tickets > open_tickets else (closed_tickets - open_tickets) * 50 if all_tickets < closed_tickets: self.equeue.put("There are more closed tickets than all for %s!" % self.teamname) self.ticket_scores[self.this_round] = ticket_score # Flag scoring flag_score = self.flag_store.score(self.teamname, self.this_round) * 100 if flag_score != self.last_flag_score: this_flag_score = flag_score - self.last_flag_score self.last_flag_score = flag_score else: this_flag_score = 0 self.flag_scores[self.this_round] = this_flag_score # Beacon scoring beacons = self.flag_store.get_beacons() beacon_count = 0 for bandit in beacons: for ip_addr in beacons[bandit]: if self.has_ip(ip_addr): beacon_count += 1 else: pass beacon_score = 0 - (beacon_count * 100) self.beacon_scores[self.this_round] = beacon_score print self.beacon_scores # Final tally round_score = service_score + ticket_score + this_flag_score + beacon_score self.scores.set_score(self.this_round, round_score) total = self.scores.total() msg = "Blueteam %s round %s scored %s for a new total of %s\n" % \ (self.teamname, self.this_round, round_score, total) self.oqueue.put(msg) print msg msg = "Blueteam %s: tally: %s services: %s tickets: %s flags: %s beacons: %s\n" % \ (self.teamname, self.get_score(), service_score, ticket_score, \ this_flag_score, beacon_score) self.oqueue.put(msg) print msg def get_health(self): host_hash = {} for host in self.hosts: name = self.hosts[host].hostname clean_name = host_re.match(name).groups()[0] service_hash = self.hosts[host].get_health() if host_hash.has_key(clean_name): self.equeue.put("Found duplicate host %s" % name) else: host_hash[clean_name] = service_hash return host_hash def get_tickets(self): all_tickets = self.ticket_obj.get_team_tickets(self.teamname) closed_tickets = self.ticket_obj.get_team_closed(self.teamname) open_tickets = int(all_tickets) - int(closed_tickets) return str(open_tickets), closed_tickets
class Service: ''' classdocs ''' def __init__(self, port, protocol, value, logger, uri="index.html", \ content=None, username=None, password=None): ''' Constructor ''' self.logger = logger self.port = port self.protocol = protocol self.value = float(value) self.scores = Scores() self.uri = "GET /%s\r\n\r\n" % uri self.up = False self.functional = False self.content = content if self.content: self.content_re = re.compile(str(self.content)) else: self.content_re = None if password: self.password = password else: self.password = "******" if username: self.username = username else: self.username = "******" self.mail_re = re.compile("220") def check(self, this_round, ipaddress, timeout): service_name = "%s/%s" % (self.port, self.protocol) myscore = self.value if tcp_80_re.match(service_name): ############################################ try: if globalvars.verbose: self.logger.err("\t\tChecking for service %s/%s..." \ % (self.port, self.protocol)) addrport = [ipaddress, self.port] mysock = socket.create_connection(addrport, timeout) mysock.settimeout(timeout) if globalvars.verbose: self.logger.err("connected!\n") except: if globalvars.verbose: self.logger.err("there was a problem...\n") myscore = self.value * 1 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore ############################################ try: if globalvars.verbose: self.logger.err("\t\t\tTrying to fetch %s..." % self.uri) mysock.send(self.uri) if globalvars.verbose: self.logger.err("requested...\n") except: if globalvars.verbose: self.logger.err("there was a problem:\n") myscore = self.value * .75 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore ############################################ try: if globalvars.verbose: self.logger.err("\t\t\tGetting data...") data = mysock.recv(4098) if globalvars.verbose: self.logger.err("fetched\n") except: if globalvars.verbose: self.logger.err("there was a problem...\n") myscore = self.value * .50 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore ############################################ if globalvars.verbose: self.logger.err("\t\t\tChecking data...") if self.content_re: if self.content_re.search(data): if globalvars.verbose: self.logger.err("good\n") self.set_score(this_round, self.value * 0) return myscore else: if globalvars.verbose: self.logger.err("bad: %s\n" % data) self.set_score(this_round, self.value * .25) return myscore elif score_str_re.search(data): if globalvars.verbose: self.logger.err("good\n") self.set_score(this_round, self.value * 0) return myscore elif html1_str_re.search(data): if globalvars.verbose: self.logger.err("good\n") self.set_score(this_round, self.value * 0) return myscore elif html2_str_re.search(data): if globalvars.verbose: self.logger.err("good\n") self.set_score(this_round, self.value * 0) return myscore elif html3_str_re.search(data): if globalvars.verbose: self.logger.err("good\n") self.set_score(this_round, self.value * 0) return myscore elif html4_str_re.search(data): if globalvars.verbose: self.logger.err("good\n") self.set_score(this_round, self.value * 0) return myscore else: if globalvars.verbose: self.logger.err("bad: %s\n" % data) self.set_score(this_round, self.value * .25) return myscore elif tcp_21_re.match(service_name): ############################################ try: if globalvars.verbose: self.logger.err("\t\tChecking for service %s/%s..." \ % (self.port, self.protocol)) myftp = ftplib.FTP(timeout=timeout) myftp.connect(ipaddress, self.port) if globalvars.verbose: self.logger.err("connected!\n") except: if globalvars.verbose: self.logger.err("there was a problem...\n") myscore = self.value * 1 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore ############################################ try: if globalvars.verbose: self.logger.err("\t\t\tTrying to login with %s and %s..." % \ (self.username, self.password)) myftp.login(self.username, self.password) if globalvars.verbose: self.logger.err("success!\n") except: if globalvars.verbose: self.logger.err("there was a problem...\n") myscore = self.value * 0.75 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore ############################################ try: if globalvars.verbose: self.logger.err("\t\t\tTrying to fetch %s..." % self.uri) filename = "%s.%s" % (ipaddress, self.port) file_obj = open(filename, "w") myftp.set_pasv(False) myftp.retrbinary("RETR scoring_file.txt", file_obj.write) if globalvars.verbose: self.logger.err("requested...\n") except: if globalvars.verbose: self.logger.err("there was a problem...\n") myscore = self.value * 0.50 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore ############################################ try: if globalvars.verbose: self.logger.err("\t\t\tChecking data...") file_obj = open(filename) for line in file_obj: if score_str_re.match(line): myscore = self.value * 0 if globalvars.verbose: self.logger.err("good\n") else: myscore = self.value * 0.25 self.set_score(this_round, myscore) return myscore except: if globalvars.verbose: self.logger.err("bad: %s\n" % data) myscore = self.value * 0.333 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore elif tcp_25_re.match(service_name): #self.set_score(this_round, 0) #self.logger.err("NEED TO IMPLEMENT 25/TCP SCORE CHECKING!!\n") ############################################ try: if globalvars.verbose: self.logger.err("\t\tChecking for service %s/%s..." \ % (self.port, self.protocol)) addrport = [ipaddress, self.port] mysock = socket.create_connection(addrport, timeout) mysock.settimeout(timeout) if globalvars.verbose: self.logger.err("connected!\n") except: if globalvars.verbose: self.logger.err("there was a problem...\n") myscore = self.value * 1 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore ############################################ try: if globalvars.verbose: self.logger.err("\t\tSending HELO...") mysock.send("HELO mail") if globalvars.verbose: self.logger.err("sent...\n") except: if globalvars.verbose: self.logger.err("there was a problem:\n") myscore = self.value * .75 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore ############################################ try: if globalvars.verbose: self.logger.err("\t\t\tGetting data...") data = mysock.recv(1024) if globalvars.verbose: self.logger.err("fetched\n") except: if globalvars.verbose: self.logger.err("there was a problem...\n") myscore = self.value * .50 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore ############################################ if globalvars.verbose: self.logger.err("\t\t\tChecking data...") if self.mail_re.search(data): if globalvars.verbose: self.logger.err("good\n") self.set_score(this_round, self.value * 0) return myscore else: if globalvars.verbose: self.logger.err("bad: %s\n" % data) self.set_score(this_round, self.value * .25) return myscore ############################################ else: try: if globalvars.verbose: self.logger.err("\t\tChecking for service %s/%s..." \ % (self.port, self.protocol)) addrport = [ipaddress, self.port] mysock = socket.create_connection(addrport, timeout) mysock.settimeout(timeout) if globalvars.verbose: self.logger.err("connected!\n") myscore = self.value * 0 self.set_score(this_round, myscore) return myscore except: if globalvars.verbose: self.logger.err("there was a problem...\n") myscore = self.value * 1 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore service_name = "%s/%s" % (str(self.port), str(self.protocol)) self.set_score(this_round, myscore) def get_score(self, this_round): return self.scores.get_score(this_round) def set_score(self, this_round, value=None): if value == None: value = self.value service_name = "%s/%s" % (str(self.port), str(self.protocol)) if (value == self.value): self.up = False self.functional = False elif (value > 0): self.up = True self.functional = False else: self.up = True self.functional = True if globalvars.binjitsu: this_value = self.value - value else: this_value = value self.logger.out("Round %s service %s score %s\n" % \ (this_round, service_name, this_value)) self.logger.err("Round %s service %s score %s\n" % \ (this_round, service_name, this_value)) self.scores.set_score(this_round, this_value) def get_state(self): # Returns 2 if up and functional # Returns 1 if up but not functional # Returns 0 if down return self.up + self.functional
class Host(threading.Thread): ''' classdocs ''' def __init__(self, teamname, hostname, value, dns_servers, msgqueue, BToqueue, BTequeue, timeout=180): ''' Constructor ''' threading.Thread.__init__(self) self.hostname = hostname self.dns_servers = dns_servers self.basename = "%s-%s" % (teamname, hostname) self.BToqueue = BToqueue self.BTequeue = BTequeue self.logger = ThreadedLogger(self.basename) self.equeue = self.logger.get_equeue() self.oqueue = self.logger.get_oqueue() self.logger.start() self.ipaddress = None self.compromised = False self.services = {} self.service_queues = {} self.service_rounds = {} self.service_scores = {} self.value = value self.scores = Scores() self.timeout = timeout self.msgqueue = msgqueue self.latest_round = 1 def add_dns(self, dnssvr): if dnssvr in self.dns_servers: pass else: self.dns_servers.append(dnssvr) def del_dns(self, dnssvr): if dnssvr in self.dns_servers: index = self.dns_servers.index(dnssvr) self.dns_servers.pop(index) else: pass def lookup(self, record="A"): if globalvars.verbose: mydns = ", ".join(self.dns_servers) self.equeue.put("Looking up %s with %s\n" % (self.hostname, mydns)) try: ipaddress = None for svr in self.dns_servers: # We set a short timeout because life moves too fast...so does the game! r = DNS.DnsRequest(self.hostname, qtype="A", server=[svr], protocol='udp', timeout=60) res = r.req() for answer in res.answers: if answer["data"]: ipaddress = answer["data"] break else: self.equeue.put("Failed to get DNS!") if ipaddress: if ctfnet_re.search(ipaddress): if globalvars.verbose: self.equeue.put("got %s\n" % self.ipaddress) self.ipaddress = ipaddress return True else: self.equeue.put("Got non RFC1918: %s\n" % ipaddress) return False else: return False except: traceback.print_exc(file=self.equeue) self.ipaddress = None return False def add_service(self, teamname, port, proto, value, uri=None, content=None, \ username=None, password=None): service_name = "%s/%s" % (port, proto) if self.services.has_key(service_name): pass this_queue = Queue.Queue() self.services[service_name] = Service(port, proto, value, teamname , this_queue, self.hostname, \ self.oqueue, self.equeue, self.BToqueue, self.BTequeue, \ uri, content, username, password) self.service_rounds[service_name] = False self.service_queues[service_name] = this_queue def run(self): for service in self.services: self.services[service].start() while True: # Check to see if we have any messages from our services for service in self.service_queues: try: item = self.service_queues[service].get(False) if item == "Done": # process the service message if service in self.service_rounds: self.service_rounds[service] = True else: raise Exception("Unknown service %s" % service) else: self.service_queues[service].put(item) except Queue.Empty: pass except: traceback.print_exc(file=self.equeue) score_round = True # Check to see if all our services have finished the last round finished = [] not_finished = [] for service in self.service_rounds: if self.service_rounds[service]: #sys.stdout.write("Host %s service %s done\n" % (self.hostname, service)) finished.append(service) else: #self.equeue.put("Host %s service %s not done\n" % (self.hostname, service)) score_round = False not_finished.append(service) try: statfile = open("status/%s.status" % self.basename, "w") except IOError: os.makedirs("status/") statfile = open("status/%s.status" % self.basename, "w") statfile = open("status/%s.status" % self.basename, "w") statfile.write("%s finished: \n\t%s\n" % (self.basename, "\n\t".join(finished))) statfile.write("%s not finished: \n\t%s\n" % (self.basename, "\n\t".join(not_finished))) statfile.close() if score_round: for service in self.service_rounds: self.service_rounds[service] = False self.msgqueue.put("score") # Check to see if we have any messages from our team object item = None try: item = self.msgqueue.get(False) except Queue.Empty: continue # Evaluate the result if len(item) == 2: #print "Found ", item # The round has begun! if item[0] == "Go": this_round = item[1] else: raise Exception("Unknown queue message %s!" % item[0]) score = int(self.value) try: if self.lookup(): if globalvars.verbose: self.equeue.put("Checking for %s(%s) with ping...\n" \ % (self.hostname, self.ipaddress)) myping = Ping.Ping() count = 3 while count: try: results = myping.quiet_ping(self.ipaddress) count = 0 except: msg = "Had a problem: %s\n" % sys.exc_info()[0] msg += traceback.format_exc() if count: msg += "\nTrying again...\n" else: count -= 1 self.equeue.write(msg) percent_failed = int(results[0]) if percent_failed < 100: # The host seems up, check the services self.check_services(this_round) else: self.fail_services(this_round) score = int(self.value) - (int(self.value) * percent_failed / 100) if globalvars.verbose: if score: self.equeue.put("%s failed: %s\n" % (self.hostname, score)) else: self.equeue.put("%s scored: %s\n" % (self.hostname, score)) else: pass else: self.fail_services(this_round) except: traceback.print_exc(file=self.equeue) self.set_score(this_round, score) elif item: # This isn't for me... self.msgqueue.put(item) else: # Didn't get back anything! Naptime... time.sleep(0.1) def check_services(self, this_round): if globalvars.verbose: self.equeue.put("Checking services for %s:\n" % self.hostname) for service_name in self.service_queues: if globalvars.verbose: self.equeue.put("\tHost %s queueing Service Check %s\n" % (self.name, service_name)) self.service_queues[service_name].put( [this_round, self.ipaddress, self.timeout]) def set_score(self, this_round, value=None): if value == None: this_value = self.value else: this_value = value self.oqueue.put("Round %s host %s score %s\n" % \ (this_round, self.hostname, this_value)) self.BToqueue.put("Round %s host %s score %s\n" % \ (this_round, self.hostname, this_value)) self.equeue.put("Round %s host %s score %s\n" % \ (this_round, self.hostname, this_value)) self.BTequeue.put("Round %s host %s score %s\n" % \ (this_round, self.hostname, this_value)) self.scores.set_score(this_round, this_value) def fail_services(self, this_round): if globalvars.verbose: self.equeue.put("Failing service scores for %s:\n" % self.hostname) services = self.services.keys() for service in services: if globalvars.verbose: self.equeue.put("\tFailing for %s:" % service) self.services[service].set_score(this_round) self.service_rounds[service] = True def get_score(self, this_round): try: score = 0 score += self.scores.get_score(this_round) services = self.services.keys() for service in services: score += self.services[service].get_score(this_round) return score except: self.equeue.put("Had a problem with host %s:\n" % self.hostname) traceback.print_exc(file=self.equeue) return False def get_health(self): service_hash = {} for service in self.services: name = "%s/%s" % (self.services[service].port, \ self.services[service].protocol) state = self.services[service].get_state() if service_hash.has_key(name): self.equeue.put("Found duplicate service %s" % name) else: service_hash[name] = state return service_hash def get_scores(self): services_scores = {} for service in self.services: services_scores[service] = self.services[service].get_scores() host_total_scores = {"host": self.scores, "services": services_scores} return host_total_scores def set_scores(self, host_total_scores): """ Function to import and process the json object exported by get_scores() """ if "host" in host_total_scores: self.scores = host_total_scores["host"] else: json_obj = jsonpickle.encode(host_total_scores) raise Exception( "Invalid team_scores hash, missing host score! \n%s\n" % json_obj) if "services" in host_total_scores: for service in self.services: if service in host_total_scores["services"]: self.services[service].set_scores( host_total_scores["services"][service]) else: json_obj = jsonpickle.encode(host_total_scores) raise Exception( "Invalid service score hash in scores! \n%s\n" % json_obj) else: json_obj = jsonpickle.encode(host_total_scores) raise Exception( "Invalid team_scores hash, missing services scores! \n%s\n" % json_obj)
class Host: ''' classdocs ''' def __init__(self, hostname, value, logger, dns=None, timeout=300): ''' Constructor ''' self.hostname = hostname if dns: self.dns = dns else: self.dns = dns.resolver.Resolver() self.logger = logger self.dns.lifetime = 3 self.ipaddress = None self.compromised = False self.services = {} self.value = value self.scores = Scores() self.timeout = timeout def add_dns(self, dnssvr): if self.dns.nameservers.count(dnssvr): pass else: self.dns.nameservers.append(dnssvr) def del_dns(self, dnssvr): if self.dns.nameservers.count(dnssvr): index = self.dns.nameservers.index(dnssvr) self.dns.nameservers.pop(index) else: pass def lookup(self, record="A"): if globalvars.verbose: mydns = "" mydns = mydns.join(self.dns.nameservers) self.logger.err("Looking up %s with %s\n" % (self.hostname, mydns)) try: answer = self.dns.query(self.hostname, record) ipaddress = answer[0].address if ctfnet_re.search(ipaddress): if globalvars.verbose: self.logger.err("got %s\n" % self.ipaddress) self.ipaddress = ipaddress return True else: self.logger.err("Got non RFC1918: %s\n" % ipaddress) return False except dns.exception.Timeout: if globalvars.verbose: self.logger.err("Request timed out\n") self.ipaddress = None return False except: traceback.print_exc(file=self.logger) return False def add_service(self, port, proto, value, uri=None, content=None, \ username=None, password=None): service_name = "%s/%s" % (port, proto) if self.services.has_key(service_name): pass self.services[service_name] = Service(port, proto, value, \ self.logger, uri, content, username, password) def check(self, this_round): score = int(self.value) try: if self.lookup(): if globalvars.verbose: self.logger.err("Checking for %s(%s) with ping...\n" \ % (self.hostname, self.ipaddress)) myping = Ping.Ping() results = myping.quiet_ping(self.ipaddress) percent_failed = int(results[0]) if percent_failed < 100: self.check_services(this_round) else: self.fail_services(this_round) if globalvars.binjitsu: score = int( self.value) - (int(self.value) * percent_failed / 100) else: score = int(self.value) * percent_failed / 100 if globalvars.verbose: if score: self.logger.err("%s failed: %s\n" % (self.hostname, score)) else: self.logger.err("%s scored: %s\n" % (self.hostname, score)) pass else: self.fail_services(this_round) except: traceback.print_exc(file=self.logger) self.set_score(this_round, score) return score def check_services(self, this_round): if globalvars.verbose: self.logger.err("Checking services for %s:\n" % self.hostname) services = self.services.keys() for service in services: if globalvars.verbose: self.logger.err("\tChecking %s\n" % service) self.services[service].check(this_round, \ self.ipaddress, self.timeout) def set_score(self, this_round, value=None): if value == None: this_value = self.value else: this_value = value self.logger.out("Round %s host %s score %s\n" % \ (this_round, self.hostname, this_value)) self.logger.err("Round %s host %s score %s\n" % \ (this_round, self.hostname, this_value)) self.scores.set_score(this_round, this_value) def fail_services(self, this_round): if globalvars.verbose: self.logger.err("Failing service scores for %s:\n" % self.hostname) services = self.services.keys() for service in services: if globalvars.verbose: self.logger.err("\tFailing for %s:" % service) self.services[service].set_score(this_round) def get_score(self, this_round): try: score = 0 score += self.scores.get_score(this_round) services = self.services.keys() for service in services: score += self.services[service].get_score(this_round) return score except: self.logger.err("Had a problem with host %s:\n" % self.hostname) traceback.print_exc(file=self.logger) return False def get_health(self): service_hash = {} for service in self.services: name = "%s/%s" % (self.services[service].port, \ self.services[service].protocol) state = self.services[service].get_state() if service_hash.has_key(name): self.logger.err("Found duplicate service %s" % name) else: service_hash[name] = state return service_hash
def test_detect(self): scores = Scores(102) self.load(scores) scores.detect() self.assertEqual(scores.detected, 102)
def __init__(self): self.server = Server("",12345) self.scores = Scores()
class BlueTeam(threading.Thread): ''' classdocs ''' def __init__(self, teamname, start_time, flags, this_round=1, current_score=0, id=None, db=None, queue=None, interval=300): ''' Constructor ''' threading.Thread.__init__(self) self.id = id self.db = db self.queue_obj = queue now = time.strftime("%Y %b %d %H:%M:%S", time.localtime(time.time())) self.dns_servers = [] self.teamname = teamname self.logger = Logger(self.teamname) self.logger.err("\n" + globalvars.sep + "\n") self.logger.err("| Starting run for Blueteam %s\n" % self.teamname) self.logger.err("| Start time: %s\n" % now) self.logger.out(globalvars.sep + "\n") self.logger.out("| Starting run for Blueteam %s\n" % self.teamname) self.logger.out("| Start time: %s\n" % now) self.hosts = {} self.hosts_rounds = {} self.host_queues = {} self.start_time = start_time self.go_time = self.start_time self.interval = interval self.did_time = None # Number of rounds finished self.this_round = this_round self.flag_store = flags self.current_score = current_score self.last_flag_score = 0 self.last_ticket_score = 0 self.nets = [] self.pp = pprint.PrettyPrinter(indent=2) self.email = "" self.ticket_obj = None self.inround = False self.game_queue = None # Score variables self.scores = Scores() self.ticket_scores = {} self.flag_scores = {} self.beacon_scores = {} self.service_scores = {} def set_ticket_interface(self, ticket_obj): self.ticket_obj = ticket_obj def set_email(self, email): self.email = email def get_email(self): return self.email def get_teamname(self): return self.teamname def add_flag(self, name, value, score=1, answer=""): self.flag_store.add(self.teamname, name, value, score, answer) def add_net(self, net): if net in self.nets: pass else: self.nets.append(net) def has_ip(self, ip): for net in self.nets: if net in ip: return True return False def run(self): print "Firing up Blueteam %s, go time is %s" % \ (self.teamname, self.go_time) if globalvars.quick: self.go_time = time.time() + 5 for host in self.hosts: self.hosts[host].start() self.inround = False while True: # Check to see if we have any messages from our hosts for host in self.host_queues: try: item = self.host_queues[host].get(False) if item == "score": #process the host message if host in self.hosts_rounds: #print "Found message from host %s" % host self.hosts_rounds[host] = True else: raise Exception("Unknown host %s\n" % host) else: self.host_queues[host].put(item) except Queue.Empty: pass except: traceback.print_exc(file=self.logger) score_round = True # Check to see if all hosts have finished the last round donemsg = "" for host in self.hosts_rounds: if self.hosts_rounds[host]: donemsg += "%s, " % host continue else: score_round = False break if donemsg: failmsg = "Failed: " for host in self.hosts_rounds: if not self.hosts_rounds[host]: failmsg += host #sys.stdout.write("Done: %s\n" % donemsg) #sys.stdout.write(failmsg) if score_round: #print "Scoring round for %s" % self.teamname self.inround = False for host in self.hosts_rounds: self.hosts_rounds[host] = False self.set_score() self.game_queue.put("Done") now = time.time() # Check to see if it's tme to start the new round, but only if the last is done item = "" try: item = self.game_queue.get(False) if item: #sys.stdout.write("\nGot item for team %s " % self.teamname) #print item if len(item) == 2: if item[0] == "Go": self.this_round = item[1] # Report times so that we know whether or not the last round ran too long self.inround = True print "Starting Service check for Blueteam %s. Go time was %s, now is %s." % \ (self.teamname, self.go_time, now) for host in self.host_queues: self.host_queues[host].put(["Go", self.this_round], 1) else: raise Exception("Unknown queue message %s!" % item[0]) else: self.game_queue.put(item) item = False except Queue.Empty: pass except: traceback.print_exc(file=self.logger) else: time.sleep(0.1) def add_dns(self, dnssvr): if dnssvr in self.dns_servers: pass else: self.logger.out("Adding DNS %s to %s\n" % (dnssvr, self.teamname)) self.dns_servers.append(dnssvr) for host in self.hosts: self.hosts[host].add_dns(dnssvr) def del_dns(self, dnssvr): if dnssvr in self.dns_servers: index = self.dns_servers.index(dnssvr) self.dns_servers.pop(index) else: pass for host in self.hosts: self.hosts[host].del_dns(dnssvr) def add_queue(self, queue): self.queue_obj = queue def set_queue(self, queue): self.game_queue = queue def add_host(self, hostname, value): # Have to strip "." because MongoDB doesn't like them for key names clean_hostname = hostname.replace(".", "___") if self.hosts.has_key(clean_hostname): self.logger.err(clobber_host_blue_str % (self.teamname, hostname)) else: self.logger.err(add_host_blue_str % (self.teamname, hostname)) this_queue = Queue.Queue() self.hosts[clean_hostname] = Host(self.teamname, hostname, value, self.logger, self.dns_servers, this_queue) self.hosts_rounds[clean_hostname] = False self.host_queues[clean_hostname] = this_queue def del_host(self, hostname): # Have to strip "." because MongoDB doesn't like them for key names clean_hostname = hostname.replace(".", "___") if self.hosts.has_key(clean_hostname): self.logger.err(del_host_blue_str % (self.teamname, hostname)) del(self.hosts[clean_hostname]) del(self.host_queues[clean_hostname]) else: self.logger.err(del_host_blue_err_str % (self.teamname, hostname)) def add_service(self, hostname, port, proto, value, uri=None, content=None, username=None, password=None): # Have to strip "." because MongoDB doesn't like them for key names clean_hostname = hostname.replace(".", "___") if self.hosts.has_key(clean_hostname): self.logger.err(add_srvc_blue_str % \ (self.teamname, port, proto, value, hostname)) self.hosts[clean_hostname].add_service(self.teamname, port, proto, value, uri, content, \ username, password) else: self.logger.err(add_srvc_blue_err_str % \ (self.teamname, port, proto, hostname)) def del_service(self, hostname, port, proto): # Have to strip "." because MongoDB doesn't like them for key names clean_hostname = hostname.replace(".", "___") if self.hosts.has_key(clean_hostname): self.logger.err(add_srvc_blue_str % \ (self.teamname, port, proto, hostname)) self.hosts[clean_hostname].del_service(port, proto, app, value) else: self.logger.err(add_srvc_blue_err_str % \ (self.teamname, port, proto, hostname)) def get_score(self, this_round=None): if not this_round: if self.inround: this_round = self.this_round - 1 else: this_round = self.this_round #this_score = self.scores.get_score(this_round) this_score = self.scores.total() return [this_round, this_score] def get_score_detail(self): scores = {} if self.inround: current_round = self.this_round - 1 else: current_round = self.this_round scores["round"] = current_round scores["services"] = 0 scores["tickets"] = 0 scores["flags"] = 0 scores["beacons"] = 0 scores["total"] = 0 for round in range(1,current_round+1): scores["services"] += self.service_scores[round] scores["tickets"] += self.ticket_scores[round] scores["flags"] += self.flag_scores[round] scores["beacons"] += self.beacon_scores[round] scores["total"] = self.scores.total() return scores def get_all_rounds(self): scores = {} for round, score in self.scores: scores[round] = score return scores def get_scores(self): team_scores = {} team_scores["hosts"] = {} team_scores["teamscore"] = self.scores for host in self.hosts: host_score = self.hosts[host].get_scores() team_scores["hosts"][host] = host_score team_scores["round"] = self.this_round return team_scores def set_scores(self, team_scores): """ Function to import and process the json object exported by get_scores() """ if "teamscore" in team_scores: self.scores = team_scores["teamscore"] if globalvars.debug: print "Set team score for %s to %s" % (self.teamname, self.scores) json_obj = jsonpickle.encode(self.scores) self.pp.pprint(json_obj) else: json_obj = jsonpickle.encode(team_scores) raise Exception ("Invalid team_scores hash, missing team score! \n%s\n" % json_obj) if "round" in team_scores: self.this_round = team_scores["round"] if globalvars.debug: print "Set round for %s to %s" % (self.teamname, self.this_round) else: json_obj = jsonpickle.encode(team_scores) raise Exception ("Invalid team_scores hash, missing round! \n%s\n" % json_obj) if "hosts" in team_scores: for host in self.hosts: if host in team_scores["hosts"]: self.hosts[host].set_scores(team_scores["hosts"][host]) else: json_obj = jsonpickle.encode(team_scores) raise Exception ("Invalid team_scores hash! \n%s\n" % json_obj) else: json_obj = jsonpickle.encode(team_scores) raise Exception ("Invalid team_scores hash, missing hosts! \n%s\n" % json_obj) def set_score(self, this_round=None, value=None): if this_round and value: this_round = self.this_round self.scores.set_score(this_round, value) return # Service scoring raw_service_score = 0 for host in self.hosts: raw_service_score += self.hosts[host].get_score(self.this_round) service_score = raw_service_score / 10 self.service_scores[self.this_round] = service_score # Ticket scoring (all_tickets, closed_tickets) = self.get_tickets() open_tickets = int(all_tickets) - int(closed_tickets) ticket_score = (int(closed_tickets) - int(open_tickets)) * 100 if int(all_tickets) < int(closed_tickets): self.logger.err("There are more closed tickets than all for %s!" % self.teamname) self.ticket_scores[self.this_round] = ticket_score # Flag scoring flag_score = self.flag_store.score(self.teamname, self.this_round) * 100 if flag_score != self.last_flag_score: this_flag_score = flag_score - self.last_flag_score self.last_flag_score = flag_score else: this_flag_score = 0 self.flag_scores[self.this_round] = this_flag_score # Beacon scoring beacons = self.flag_store.get_beacons() beacon_count = 0 for bandit in beacons: for ip_addr in beacons[bandit]: if self.has_ip(ip_addr): beacon_count += 1 else: pass beacon_score = 0 - (beacon_count * 100) self.beacon_scores[self.this_round] = beacon_score print self.beacon_scores # Final tally round_score = service_score + ticket_score + this_flag_score + beacon_score self.scores.set_score(self.this_round, round_score) total = self.scores.total() print "Blueteam %s round %s scored %s for a new total of %s\n" % \ (self.teamname, self.this_round, round_score, total) print "Blueteam %s: tally: %s services: %s tickets: %s flags: %s beacons: %s\n" % \ (self.teamname, self.get_score(), service_score, ticket_score, this_flag_score, beacon_score) def get_health(self): host_hash = {} for host in self.hosts: name = self.hosts[host].hostname clean_name = host_re.match(name).groups()[0] service_hash = self.hosts[host].get_health() if host_hash.has_key(clean_name): self.logger.err("Found duplicate host %s" % name) else: host_hash[clean_name] = service_hash return host_hash def get_tickets(self): all_tickets = self.ticket_obj.get_team_tickets(self.teamname) closed_tickets = self.ticket_obj.get_team_closed(self.teamname) open_tickets = int(all_tickets) - int(closed_tickets) return str(open_tickets), closed_tickets
class Service: ''' classdocs ''' def __init__(self, port, protocol, value, logger, uri="index.html", \ content=None, username=None, password=None): ''' Constructor ''' self.logger = logger self.port = port self.protocol = protocol self.value = float(value) self.scores = Scores() self.uri = "GET /%s\r\n\r\n" % uri self.up = False self.functional = False self.content = content if self.content: self.content_re = re.compile(str(self.content)) else: self.content_re = None if password: self.password = password else: self.password = "******" if username: self.username = username else: self.username = "******" self.mail_re = re.compile("220") def check(self, this_round, ipaddress, timeout): service_name = "%s/%s" % (self.port, self.protocol) myscore = self.value if tcp_80_re.match(service_name): ############################################ try: if globalvars.verbose: self.logger.err("\t\tChecking for service %s/%s..." \ % (self.port, self.protocol)) addrport = [ipaddress, self.port] mysock = socket.create_connection(addrport, timeout) mysock.settimeout(timeout) if globalvars.verbose: self.logger.err("connected!\n") except: if globalvars.verbose: self.logger.err("there was a problem...\n") myscore = self.value * 1 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore ############################################ try: if globalvars.verbose: self.logger.err("\t\t\tTrying to fetch %s..." % self.uri) mysock.send(self.uri) if globalvars.verbose: self.logger.err("requested...\n") except: if globalvars.verbose: self.logger.err("there was a problem:\n") myscore = self.value * .75 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore ############################################ try: if globalvars.verbose: self.logger.err("\t\t\tGetting data...") data = mysock.recv(4098) if globalvars.verbose: self.logger.err("fetched\n") except: if globalvars.verbose: self.logger.err("there was a problem...\n") myscore = self.value * .50 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore ############################################ if globalvars.verbose: self.logger.err("\t\t\tChecking data...") if self.content_re: if self.content_re.search(data): if globalvars.verbose: self.logger.err("good\n") self.set_score(this_round, self.value * 0) return myscore else: if globalvars.verbose: self.logger.err("bad: %s\n" % data) self.set_score(this_round, self.value * .25) return myscore elif score_str_re.search(data): if globalvars.verbose: self.logger.err("good\n") self.set_score(this_round, self.value * 0) return myscore elif html1_str_re.search(data): if globalvars.verbose: self.logger.err("good\n") self.set_score(this_round, self.value * 0) return myscore elif html2_str_re.search(data): if globalvars.verbose: self.logger.err("good\n") self.set_score(this_round, self.value * 0) return myscore elif html3_str_re.search(data): if globalvars.verbose: self.logger.err("good\n") self.set_score(this_round, self.value * 0) return myscore elif html4_str_re.search(data): if globalvars.verbose: self.logger.err("good\n") self.set_score(this_round, self.value * 0) return myscore else: if globalvars.verbose: self.logger.err("bad: %s\n" % data) self.set_score(this_round, self.value * .25) return myscore elif tcp_21_re.match(service_name): ############################################ try: if globalvars.verbose: self.logger.err("\t\tChecking for service %s/%s..." \ % (self.port, self.protocol)) myftp = ftplib.FTP(timeout=timeout) myftp.connect(ipaddress, self.port) if globalvars.verbose: self.logger.err("connected!\n") except: if globalvars.verbose: self.logger.err("there was a problem...\n") myscore = self.value * 1 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore ############################################ try: if globalvars.verbose: self.logger.err("\t\t\tTrying to login with %s and %s..." % \ (self.username, self.password)) myftp.login(self.username, self.password) if globalvars.verbose: self.logger.err("success!\n") except: if globalvars.verbose: self.logger.err("there was a problem...\n") myscore = self.value * 0.75 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore ############################################ try: if globalvars.verbose: self.logger.err("\t\t\tTrying to fetch %s..." % self.uri) filename = "%s.%s" % (ipaddress, self.port) file_obj = open(filename, "w") myftp.set_pasv(False) myftp.retrbinary("RETR scoring_file.txt", file_obj.write) if globalvars.verbose: self.logger.err("requested...\n") except: if globalvars.verbose: self.logger.err("there was a problem...\n") myscore = self.value * 0.50 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore ############################################ try: if globalvars.verbose: self.logger.err("\t\t\tChecking data...") file_obj = open(filename) for line in file_obj: if score_str_re.match(line): myscore = self.value * 0 if globalvars.verbose: self.logger.err("good\n") else: myscore = self.value * 0.25 self.set_score(this_round, myscore) return myscore except: if globalvars.verbose: self.logger.err("bad: %s\n" % data) myscore = self.value * 0.333 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore elif tcp_25_re.match(service_name): #self.set_score(this_round, 0) #self.logger.err("NEED TO IMPLEMENT 25/TCP SCORE CHECKING!!\n") ############################################ try: if globalvars.verbose: self.logger.err("\t\tChecking for service %s/%s..." \ % (self.port, self.protocol)) addrport = [ipaddress, self.port] mysock = socket.create_connection(addrport, timeout) mysock.settimeout(timeout) if globalvars.verbose: self.logger.err("connected!\n") except: if globalvars.verbose: self.logger.err("there was a problem...\n") myscore = self.value * 1 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore ############################################ try: if globalvars.verbose: self.logger.err("\t\tSending HELO..." ) mysock.send("HELO mail") if globalvars.verbose: self.logger.err("sent...\n") except: if globalvars.verbose: self.logger.err("there was a problem:\n") myscore = self.value * .75 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore ############################################ try: if globalvars.verbose: self.logger.err("\t\t\tGetting data...") data = mysock.recv(1024) if globalvars.verbose: self.logger.err("fetched\n") except: if globalvars.verbose: self.logger.err("there was a problem...\n") myscore = self.value * .50 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore ############################################ if globalvars.verbose: self.logger.err("\t\t\tChecking data...") if self.mail_re.search(data): if globalvars.verbose: self.logger.err("good\n") self.set_score(this_round, self.value * 0) return myscore else: if globalvars.verbose: self.logger.err("bad: %s\n" % data) self.set_score(this_round, self.value * .25) return myscore ############################################ else: try: if globalvars.verbose: self.logger.err("\t\tChecking for service %s/%s..." \ % (self.port, self.protocol)) addrport = [ipaddress, self.port] mysock = socket.create_connection(addrport, timeout) mysock.settimeout(timeout) if globalvars.verbose: self.logger.err("connected!\n") myscore = self.value * 0 self.set_score(this_round, myscore) return myscore except: if globalvars.verbose: self.logger.err("there was a problem...\n") myscore = self.value * 1 traceback.print_exc(file=self.logger) self.set_score(this_round, myscore) return myscore service_name = "%s/%s" % (str(self.port), str(self.protocol)) self.set_score(this_round, myscore) def get_score(self, this_round): return self.scores.get_score(this_round) def set_score(self, this_round, value=None): if value == None: value = self.value service_name = "%s/%s" % (str(self.port), str(self.protocol)) if (value == self.value): self.up = False self.functional = False elif (value > 0): self.up = True self.functional = False else: self.up = True self.functional = True if globalvars.binjitsu: this_value = self.value - value else: this_value = value self.logger.out("Round %s service %s score %s\n" % \ (this_round, service_name, this_value)) self.logger.err("Round %s service %s score %s\n" % \ (this_round, service_name, this_value)) self.scores.set_score(this_round, this_value) def get_state(self): # Returns 2 if up and functional # Returns 1 if up but not functional # Returns 0 if down return self.up + self.functional
class Host(threading.Thread): ''' classdocs ''' def __init__(self, teamname, hostname, value, dns_servers, msgqueue, BToqueue, BTequeue, timeout=180): ''' Constructor ''' threading.Thread.__init__(self) self.hostname = hostname self.dns_servers = dns_servers self.basename = "%s-%s" % (teamname, hostname) self.oqueue = QueueP() self.equeue = QueueP() self.BToqueue = BToqueue self.BTequeue = BTequeue self.logger = ThreadedLogger(self.basename, self.oqueue, self.equeue) self.logger.start() self.ipaddress = None self.compromised = False self.services = {} self.service_queues = {} self.service_rounds = {} self.value = value self.scores = Scores() self.timeout = timeout self.msgqueue = msgqueue def add_dns(self, dnssvr): if dnssvr in self.dns_servers: pass else: self.dns_servers.append(dnssvr) def del_dns(self, dnssvr): if dnssvr in self.dns_servers: index = self.dns.nameservers.index(dnssvr) self.dns_servers.pop(index) else: pass def lookup(self, record="A"): if globalvars.verbose: mydns = ", ".join(self.dns_servers) self.equeue.put("Looking up %s with %s\n" % (self.hostname, mydns)) try: for svr in self.dns_servers: # We set a short timeout because life moves too fast...so does the game! r = DNS.DnsRequest(self.hostname, qtype="A", server=[svr], protocol='udp', timeout=60) res = r.req() for answer in res.answers: if answer["data"]: ipaddress = answer["data"] break else: self.equeue.put("Failed to get DNS!") if ctfnet_re.search(ipaddress): if globalvars.verbose: self.equeue.put("got %s\n" % self.ipaddress) self.ipaddress = ipaddress return True else: self.equeue.put("Got non RFC1918: %s\n" % ipaddress) return False except: traceback.print_exc(file=self.equeue) self.ipaddress = None return False def add_service(self, teamname, port, proto, value, uri=None, content=None, \ username=None, password=None): service_name = "%s/%s" % (port, proto) if self.services.has_key(service_name): pass this_queue = Queue.Queue() self.services[service_name] = Service(port, proto, value, teamname , this_queue, self.hostname, \ self.oqueue, self.equeue, self.BToqueue, self.BTequeue, \ uri, content, username, password) self.service_rounds[service_name] = False self.service_queues[service_name] = this_queue def run(self): for service in self.services: self.services[service].start() while True: # Check to see if we have any messages from our services for service in self.service_queues: try: item = self.service_queues[service].get(False) if item == "Done": # process the service message if service in self.service_rounds: self.service_rounds[service] = True else: raise Exception("Unknown service %s" % service) else: self.service_queues[service].put(item) except Queue.Empty: pass except: traceback.print_exc(file=self.equeue) score_round = True # Check to see if all our services have finished the last round finished = [] not_finished = [] for service in self.service_rounds: if self.service_rounds[service]: #sys.stdout.write("Host %s service %s done\n" % (self.hostname, service)) finished.append(service) else: #self.equeue.put("Host %s service %s not done\n" % (self.hostname, service)) score_round = False not_finished.append(service) statfile = open("%s.status" % self.basename, "w") statfile.write("%s finished: \n\t%s\n" % (self.basename, "\n\t".join(finished))) statfile.write("%s not finished: \n\t%s\n" % (self.basename, "\n\t".join(not_finished))) statfile.close() if score_round: for service in self.service_rounds: self.service_rounds[service] = False self.msgqueue.put("score") # Check to see if we have any messages from our team object item = None try: item = self.msgqueue.get(False) except Queue.Empty: continue # Evaluate the result if len(item) == 2: #print "Found ", item # The round has begun! if item[0] == "Go": this_round = item[1] else: raise Exception("Unknown queue message %s!" % item[0]) score = int(self.value) try: if self.lookup(): if globalvars.verbose: self.equeue.put("Checking for %s(%s) with ping...\n" \ % (self.hostname, self.ipaddress)) myping = Ping.Ping() count = 3 while count: try: results = myping.quiet_ping(self.ipaddress) count = 0 except: msg = "Had a problem: %s\n" % sys.exc_info()[0] msg += traceback.format_exc() if count: msg += "\nTrying again...\n" else: count -= 1 self.equeue.write(msg) percent_failed = int(results[0]) if percent_failed < 100: # The host seems up, check the services self.check_services(this_round) else: self.fail_services(this_round) score = int(self.value) - (int(self.value)*percent_failed/100) if globalvars.verbose: if score: self.equeue.put("%s failed: %s\n" % (self.hostname,score)) else: self.equeue.put("%s scored: %s\n" % (self.hostname,score)) else: pass else: self.fail_services(this_round) except: traceback.print_exc(file=self.equeue) self.set_score(this_round, score) elif item: # This isn't for me... self.msgqueue.put(item) else: # Didn't get back anything! Naptime... time.sleep(0.1) def check_services(self, this_round): if globalvars.verbose: self.equeue.put("Checking services for %s:\n" % self.hostname) for service_name in self.service_queues: if globalvars.verbose: self.equeue.put("\tHost %s queueing Service Check %s\n" % (self.name, service_name)) self.service_queues[service_name].put([this_round, self.ipaddress, self.timeout]) def set_score(self, this_round, value=None): if value == None: this_value = self.value else: this_value = value self.oqueue.put("Round %s host %s score %s\n" % \ (this_round, self.hostname, this_value)) self.BToqueue.put("Round %s host %s score %s\n" % \ (this_round, self.hostname, this_value)) self.equeue.put("Round %s host %s score %s\n" % \ (this_round, self.hostname, this_value)) self.BTequeue.put("Round %s host %s score %s\n" % \ (this_round, self.hostname, this_value)) self.scores.set_score(this_round, this_value) def fail_services(self, this_round): if globalvars.verbose: self.equeue.put("Failing service scores for %s:\n" % self.hostname) services = self.services.keys() for service in services: if globalvars.verbose: self.equeue.put("\tFailing for %s:" % service) self.services[service].set_score(this_round) self.service_rounds[service] = True def get_score(self, this_round): try: score = 0 score += self.scores.get_score(this_round) services = self.services.keys() for service in services: score += self.services[service].get_score(this_round) return score except: self.equeue.put("Had a problem with host %s:\n" % self.hostname) traceback.print_exc(file=self.equeue) return False def get_health(self): service_hash = {} for service in self.services: name = "%s/%s" % (self.services[service].port, \ self.services[service].protocol) state = self.services[service].get_state() if service_hash.has_key(name): self.equeue.put("Found duplicate service %s" % name) else: service_hash[name] = state return service_hash def get_scores(self): services_scores = {} for service in self.services: services_scores[service] = self.services[service].get_scores() host_total_scores = {"host":self.scores, "services": services_scores} return host_total_scores def set_scores(self, host_total_scores): """ Function to import and process the json object exported by get_scores() """ if "host" in host_total_scores: self.scores = host_total_scores["host"] else: json_obj = jsonpickle.encode(host_total_scores) raise Exception ("Invalid team_scores hash, missing host score! \n%s\n" % json_obj) if "services" in host_total_scores: for service in self.services: if service in host_total_scores["services"]: self.services[service].set_scores(host_total_scores["services"][service]) else: json_obj = jsonpickle.encode(host_total_scores) raise Exception ("Invalid service score hash in scores! \n%s\n" % json_obj) else: json_obj = jsonpickle.encode(host_total_scores) raise Exception ("Invalid team_scores hash, missing services scores! \n%s\n" % json_obj)
class Host: ''' classdocs ''' def __init__(self, hostname, value, logger, dns=None, timeout=300): ''' Constructor ''' self.hostname = hostname if dns: self.dns = dns else: self.dns = dns.resolver.Resolver() self.logger = logger self.dns.lifetime = 3 self.ipaddress = None self.compromised = False self.services = {} self.value = value self.scores = Scores() self.timeout = timeout def add_dns(self, dnssvr): if self.dns.nameservers.count(dnssvr): pass else: self.dns.nameservers.append(dnssvr) def del_dns(self, dnssvr): if self.dns.nameservers.count(dnssvr): index = self.dns.nameservers.index(dnssvr) self.dns.nameservers.pop(index) else: pass def lookup(self, record="A"): if globalvars.verbose: mydns= "" mydns = mydns.join(self.dns.nameservers) self.logger.err("Looking up %s with %s\n" % (self.hostname, mydns)) try: answer = self.dns.query(self.hostname, record) ipaddress = answer[0].address if ctfnet_re.search(ipaddress): if globalvars.verbose: self.logger.err("got %s\n" % self.ipaddress) self.ipaddress = ipaddress return True else: self.logger.err("Got non RFC1918: %s\n" % ipaddress) return False except dns.exception.Timeout: if globalvars.verbose: self.logger.err("Request timed out\n") self.ipaddress = None return False except: traceback.print_exc(file=self.logger) return False def add_service(self, port, proto, value, uri=None, content=None, \ username=None, password=None): service_name = "%s/%s" % (port, proto) if self.services.has_key(service_name): pass self.services[service_name] = Service(port, proto, value, \ self.logger, uri, content, username, password) def check(self, this_round): score = int(self.value) try: if self.lookup(): if globalvars.verbose: self.logger.err("Checking for %s(%s) with ping...\n" \ % (self.hostname, self.ipaddress)) myping = Ping.Ping() results = myping.quiet_ping(self.ipaddress) percent_failed = int(results[0]) if percent_failed < 100: self.check_services(this_round) else: self.fail_services(this_round) if globalvars.binjitsu: score = int(self.value) - (int(self.value)*percent_failed/100) else: score = int(self.value) * percent_failed / 100 if globalvars.verbose: if score: self.logger.err("%s failed: %s\n" % (self.hostname,score)) else: self.logger.err("%s scored: %s\n" % (self.hostname,score)) pass else: self.fail_services(this_round) except: traceback.print_exc(file=self.logger) self.set_score(this_round, score) return score def check_services(self, this_round): if globalvars.verbose: self.logger.err("Checking services for %s:\n" % self.hostname) services = self.services.keys() for service in services: if globalvars.verbose: self.logger.err("\tChecking %s\n" % service) self.services[service].check(this_round, \ self.ipaddress, self.timeout) def set_score(self, this_round, value=None): if value == None: this_value = self.value else: this_value = value self.logger.out("Round %s host %s score %s\n" % \ (this_round, self.hostname, this_value)) self.logger.err("Round %s host %s score %s\n" % \ (this_round, self.hostname, this_value)) self.scores.set_score(this_round, this_value) def fail_services(self, this_round): if globalvars.verbose: self.logger.err("Failing service scores for %s:\n" % self.hostname) services = self.services.keys() for service in services: if globalvars.verbose: self.logger.err("\tFailing for %s:" % service) self.services[service].set_score(this_round) def get_score(self, this_round): try: score = 0 score += self.scores.get_score(this_round) services = self.services.keys() for service in services: score += self.services[service].get_score(this_round) return score except: self.logger.err("Had a problem with host %s:\n" % self.hostname) traceback.print_exc(file=self.logger) return False def get_health(self): service_hash = {} for service in self.services: name = "%s/%s" % (self.services[service].port, \ self.services[service].protocol) state = self.services[service].get_state() if service_hash.has_key(name): self.logger.err("Found duplicate service %s" % name) else: service_hash[name] = state return service_hash
class BlueTeam(threading.Thread): ''' classdocs ''' def __init__(self, teamname, start_time, flags, this_round=1, current_score=0, id=None, db=None, queue=None, interval=300): ''' Constructor ''' threading.Thread.__init__(self) self.id = id self.db = db self.queue_obj = queue now = time.strftime("%Y %b %d %H:%M:%S", time.localtime(time.time())) self.dns_servers = [] self.teamname = teamname self.logger = Logger(self.teamname) self.logger.err("\n" + globalvars.sep + "\n") self.logger.err("| Starting run for Blueteam %s\n" % self.teamname) self.logger.err("| Start time: %s\n" % now) self.logger.out(globalvars.sep + "\n") self.logger.out("| Starting run for Blueteam %s\n" % self.teamname) self.logger.out("| Start time: %s\n" % now) self.hosts = {} self.scores = Scores() self.start_time = start_time self.go_time = self.start_time self.interval = interval self.did_time = None # Number of rounds finished self.this_round = this_round self.flag_store = flags self.current_score = current_score self.last_flag_score = 0 self.last_ticket_score = 0 self.nets = [] self.pp = pprint.PrettyPrinter(indent=2) self.email = "" self.ticket_obj = None def set_ticket_interface(self, ticket_obj): self.ticket_obj = ticket_obj def set_email(self, email): self.email = email def get_email(self): return self.email def get_teamname(self): return self.teamname def add_flag(self, name, value, score=1, answer=""): self.flag_store.add(self.teamname, name, value, score, answer) def add_net(self, net): if net in self.nets: pass else: self.nets.append(net) def has_ip(self, ip): for net in self.nets: if net in ip: return True return False def run(self): print "Firing up Blueteam %s, go time is %s" % \ (self.teamname, self.go_time) if globalvars.quick: self.go_time = time.time() + 5 while True: go_time_lt = time.localtime(self.go_time) if self.did_time: did_time_lt = time.localtime(self.did_time) if go_time_lt.tm_min == did_time_lt.tm_min: continue else: pass else: pass rightnow = time.time() rightnow_lt = time.localtime(rightnow) if go_time_lt.tm_mday == rightnow_lt.tm_mday: if go_time_lt.tm_hour == rightnow_lt.tm_hour: if go_time_lt.tm_min == rightnow_lt.tm_min: try: print "Now is %s" % rightnow self.did_time = self.go_time self.check() queue_str = self.teamname+"|"+str(self.this_round) self.queue_obj.put(queue_str) now = time.time() new_go = self.go_time + self.interval if new_go < now: self.go_time = now + 60 else: self.go_time = new_go self.set_score() except: traceback.print_exc(file=self.logger) elif go_time_lt.tm_min == (rightnow_lt.tm_min + 1): print "Counting down for %s: %s to %s..." % \ (self.teamname, self.go_time, rightnow) time.sleep(1) else: print "Counting down for %s: %s to %s..." % \ (self.teamname, self.go_time, rightnow) time.sleep(60) else: print "Counting down for %s: %s to %s..." % \ (self.teamname, self.go_time, rightnow) time.sleep(60) else: time.sleep(60) def add_dns(self, dnssvr): if dnssvr in self.dns_servers: pass else: self.logger.out("Adding DNS %s to %s\n" % (dnssvr, self.teamname)) self.dns_servers.append(dnssvr) for host in self.hosts: self.hosts[host].add_dns(dnssvr) def del_dns(self, dnssvr): if dnssvr in self.dns_servers: index = self.dns_servers.index(dnssvr) self.dns_servers.pop(index) else: pass for host in self.hosts: self.hosts[host].del_dns(dnssvr) def add_queue(self, queue): self.queue_obj = queue def check(self): hostlist = self.hosts.keys() for host in hostlist: hostscore = self.hosts[host].check(self.this_round) def add_host(self, hostname, value): # Have to strip "." because MongoDB doesn't like them for key names clean_hostname = hostname.replace(".", "___") if self.hosts.has_key(clean_hostname): self.logger.err(clobber_host_blue_str % (self.teamname, hostname)) else: self.logger.err(add_host_blue_str % (self.teamname, hostname)) self.hosts[clean_hostname] = Host(hostname, value, self.logger, self.dns_servers) def del_host(self, hostname): # Have to strip "." because MongoDB doesn't like them for key names clean_hostname = hostname.replace(".", "___") if self.hosts.has_key(clean_hostname): self.logger.err(del_host_blue_str % (self.teamname, hostname)) del(self.hosts[clean_hostname]) else: self.logger.err(del_host_blue_err_str % (self.teamname, hostname)) def add_service(self, hostname, port, proto, value, uri=None, content=None, username=None, password=None): # Have to strip "." because MongoDB doesn't like them for key names clean_hostname = hostname.replace(".", "___") if self.hosts.has_key(clean_hostname): self.logger.err(add_srvc_blue_str % \ (self.teamname, port, proto, value, hostname)) self.hosts[clean_hostname].add_service(port, proto, value, uri, content, \ username, password) else: self.logger.err(add_srvc_blue_err_str % \ (self.teamname, port, proto, hostname)) def del_service(self, hostname, port, proto): # Have to strip "." because MongoDB doesn't like them for key names clean_hostname = hostname.replace(".", "___") if self.hosts.has_key(clean_hostname): self.logger.err(add_srvc_blue_str % \ (self.teamname, port, proto, hostname)) self.hosts[clean_hostname].del_service(port, proto, app, value) else: self.logger.err(add_srvc_blue_err_str % \ (self.teamname, port, proto, hostname)) def get_score(self, this_round=None): if not this_round: this_round = self.this_round - 1 #this_score = self.scores.get_score(this_round) this_score = self.scores.total() return [this_round, this_score] def get_all_rounds(self): scores = {} for round, score in self.scores: scores[round] = score return scores def get_scores(self): team_scores = {} team_scores["hosts"] = {} team_scores["teamscore"] = self.scores for host in self.hosts: host_score = self.hosts[host].get_scores() team_scores["hosts"][host] = host_score team_scores["round"] = self.this_round return team_scores def set_scores(self, team_scores): """ Function to import and process the json object exported by get_scores() """ if "teamscore" in team_scores: self.scores = team_scores["teamscore"] if globalvars.debug: print "Set team score for %s to %s" % (self.teamname, self.scores) json_obj = jsonpickle.encode(self.scores) self.pp.pprint(json_obj) else: json_obj = jsonpickle.encode(team_scores) raise Exception ("Invalid team_scores hash, missing team score! \n%s\n" % json_obj) if "round" in team_scores: self.this_round = team_scores["round"] if globalvars.debug: print "Set round for %s to %s" % (self.teamname, self.this_round) else: json_obj = jsonpickle.encode(team_scores) raise Exception ("Invalid team_scores hash, missing round! \n%s\n" % json_obj) if "hosts" in team_scores: for host in self.hosts: if host in team_scores["hosts"]: self.hosts[host].set_scores(team_scores["hosts"][host]) else: json_obj = jsonpickle.encode(team_scores) raise Exception ("Invalid team_scores hash! \n%s\n" % json_obj) else: json_obj = jsonpickle.encode(team_scores) raise Exception ("Invalid team_scores hash, missing hosts! \n%s\n" % json_obj) def set_score(self, this_round=None, value=None): if this_round and value: this_round = self.this_round self.scores.set_score(this_round, value) return service_score = 0 for host in self.hosts: service_score += self.hosts[host].get_score(self.this_round) (all_tickets, closed_tickets) = self.get_tickets() ticket_score = int(closed_tickets) * 1000 if ticket_score == self.last_ticket_score: ticket_score = 0 else: self.last_ticket_score = ticket_score if int(all_tickets) < int(closed_tickets): self.logger.err("There are more closed tickets than all for %s!" % self.teamname) if globalvars.binjitsu: flag_score = self.flag_store.score(self.teamname, self.this_round) if flag_score != self.last_flag_score: this_flag_score = flag_score - self.last_flag_score self.last_flag_score = flag_score * 1000 else: this_flag_score = 0 round_score = (this_flag_score - service_score ) else: flag_score = self.flag_store.score(self.teamname, self.this_round) if flag_score != self.last_flag_score: this_flag_score = flag_score - self.last_flag_score round_score = (service_score + (this_flag_score * 1000)) self.last_flag_score = flag_score else: round_score = service_score round_score += ticket_score self.scores.set_score(self.this_round, round_score) total = self.scores.total() print "Blueteam %s round %s scored %s for a new total of %s\n" % \ (self.teamname, self.this_round, round_score, total) print "Blueteam %s tally: %s\n" % (self.teamname, self.get_score()) self.this_round += 1 def get_health(self): host_hash = {} for host in self.hosts: name = self.hosts[host].hostname clean_name = host_re.match(name).groups()[0] service_hash = self.hosts[host].get_health() if host_hash.has_key(clean_name): self.logger.err("Found duplicate host %s" % name) else: host_hash[clean_name] = service_hash return host_hash def get_tickets(self): all_tickets = self.ticket_obj.get_team_tickets(self.teamname) closed_tickets = self.ticket_obj.get_team_closed(self.teamname) return all_tickets, closed_tickets
class BlueTeam(threading.Thread): ''' classdocs ''' def __init__(self, teamname, start_time, flags, this_round=1, current_score=0, id=None, db=None, queue=None, interval=300): ''' Constructor ''' threading.Thread.__init__(self) self.id = id self.db = db self.queue_obj = queue now = time.strftime("%Y %b %d %H:%M:%S", time.localtime(time.time())) self.dns = dns.resolver.Resolver() self.del_dns("8.8.8.8") #self.add_dns("10.0.1.50") self.teamname = teamname self.logger = Logger(self.teamname) self.logger.err("\n" + globalvars.sep + "\n") self.logger.err("| Starting run for Blueteam %s\n" % self.teamname) self.logger.err("| Start time: %s\n" % now) self.logger.out(globalvars.sep + "\n") self.logger.out("| Starting run for Blueteam %s\n" % self.teamname) self.logger.out("| Start time: %s\n" % now) self.hosts = {} self.scores = Scores() self.start_time = start_time self.go_time = self.start_time self.interval = interval self.did_time = None # Number of rounds finished self.this_round = this_round self.flag_store = flags self.current_score = current_score self.last_flag_score = 0 def add_flag(self, name, value): self.flag_store.add(self.teamname, name, value) def run(self): print "Firing up Blueteam %s, go time is %s" % \ (self.teamname, self.go_time) if globalvars.quick: self.go_time = time.time() + 5 while True: go_time_lt = time.localtime(self.go_time) if self.did_time: did_time_lt = time.localtime(self.did_time) if go_time_lt.tm_min == did_time_lt.tm_min: continue else: pass else: pass rightnow = time.time() rightnow_lt = time.localtime(rightnow) if go_time_lt.tm_mday == rightnow_lt.tm_mday: if go_time_lt.tm_hour == rightnow_lt.tm_hour: if go_time_lt.tm_min == rightnow_lt.tm_min: try: print "Now is %s" % rightnow self.did_time = self.go_time self.check() queue_str = self.teamname+"|"+str(self.this_round) self.queue_obj.put(queue_str) now = time.time() new_go = self.go_time + self.interval if new_go < now: self.go_time = now + 60 else: self.go_time = new_go self.set_score() except: traceback.print_exc(file=self.logger) elif go_time_lt.tm_min == (rightnow_lt.tm_min + 1): print "Counting down for %s: %s to %s..." % \ (self.teamname, self.go_time, rightnow) time.sleep(1) else: print "Counting down for %s: %s to %s..." % \ (self.teamname, self.go_time, rightnow) time.sleep(60) else: print "Counting down for %s: %s to %s..." % \ (self.teamname, self.go_time, rightnow) time.sleep(60) else: time.sleep(60) def add_dns(self, dnssvr): if self.dns.nameservers.count(dnssvr): pass else: self.logger.out("Adding DNS %s to %s\n" % (dnssvr, self.teamname)) self.dns.nameservers.append(dnssvr) def del_dns(self, dnssvr): if self.dns.nameservers.count(dnssvr): index = self.dns.nameservers.index(dnssvr) self.dns.nameservers.pop(index) else: pass def add_queue(self, queue): self.queue_obj = queue def check(self): hostlist = self.hosts.keys() for host in hostlist: hostscore = self.hosts[host].check(self.this_round) def add_host(self, hostname, value): if self.hosts.has_key(hostname): self.logger.err(clobber_host_blue_str % (self.teamname, hostname)) else: self.logger.err(add_host_blue_str % (self.teamname, hostname)) self.hosts[hostname] = Host(hostname, value, self.logger, self.dns) def del_host(self, hostname): if self.hosts.has_key(hostname): self.logger.err(del_host_blue_str % (self.teamname, hostname)) del(self.hosts[hostname]) else: self.logger.err(del_host_blue_err_str % (self.teamname, hostname)) def add_service(self, hostname, port, proto, value, uri=None, content=None, username=None, password=None): if self.hosts.has_key(hostname): self.logger.err(add_srvc_blue_str % \ (self.teamname, port, proto, value, hostname)) self.hosts[hostname].add_service(port, proto, value, uri, content, \ username, password) else: self.logger.err(add_srvc_blue_err_str % \ (self.teamname, port, proto, hostname)) def del_service(self, host, port, proto): if self.hosts.has_key(hostname): self.logger.err(add_srvc_blue_str % \ (self.teamname, port, proto, hostname)) self.hosts[hostname].del_service(port, proto, app, value) else: self.logger.err(add_srvc_blue_err_str % \ (self.teamname, port, proto, hostname)) def get_score(self, this_round=None): if not this_round: this_round = self.this_round - 1 this_score = self.scores.get_score(this_round) return [this_round, this_score] def set_score(self, this_round=None, value=None): if this_round and value: this_round = self.this_round self.scores.set_score(this_round, value) return myscore = 0 hostlist = self.hosts.keys() for host in hostlist: myscore += self.hosts[host].get_score(self.this_round) if globalvars.binjitsu: this_score = self.scores.get_score(self.this_round) flag_score = self.flag_store.score(self.teamname, self.this_round) if flag_score != self.last_flag_score: this_flag_score = flag_score - self.last_flag_score self.last_flag_score = flag_score else: this_flag_score = 0 round_score = (myscore * this_flag_score) self.current_score += round_score else: this_score = self.scores.get_score(self.this_round) flag_score = self.flag_store.score(self.teamname, self.this_round) if flag_score != self.last_flag_score: this_flag_score = flag_score - self.last_flag_score round_score = (myscore + (this_flag_score * 1000)) self.last_flag_score = flag_score else: round_score = myscore self.current_score += round_score print "Blueteam %s round %s scored %s for a new total of %s\n" % \ (self.teamname, self.this_round, round_score, self.current_score) self.scores.set_score(self.this_round, self.current_score) print "Blueteam %s tally: %s\n" % (self.teamname, self.get_score()) self.this_round += 1 self.db.update({"_id": self.id}, {"$set": {"current_round": self.this_round}}) self.db.update({"_id": self.id}, {"$set": {"team_score": self.current_score}}) def get_health(self): host_hash = {} for host in self.hosts: name = self.hosts[host].hostname service_hash = self.hosts[host].get_health() if host_hash.has_key(name): self.logger.err("Found duplicate host %s" % name) else: host_hash[name] = service_hash return host_hash
class BlueTeam(threading.Thread): ''' classdocs ''' def __init__(self, teamname, start_time, flags, this_round=1, current_score=0, id=None, db=None, queue=None, interval=300): ''' Constructor ''' threading.Thread.__init__(self) self.id = id self.db = db self.queue_obj = queue now = time.strftime("%Y %b %d %H:%M:%S", time.localtime(time.time())) self.dns = dns.resolver.Resolver() self.del_dns("8.8.8.8") #self.add_dns("10.0.1.50") self.teamname = teamname self.logger = Logger(self.teamname) self.logger.err("\n" + globalvars.sep + "\n") self.logger.err("| Starting run for Blueteam %s\n" % self.teamname) self.logger.err("| Start time: %s\n" % now) self.logger.out(globalvars.sep + "\n") self.logger.out("| Starting run for Blueteam %s\n" % self.teamname) self.logger.out("| Start time: %s\n" % now) self.hosts = {} self.scores = Scores() self.start_time = start_time self.go_time = self.start_time self.interval = interval self.did_time = None # Number of rounds finished self.this_round = this_round self.flag_store = flags self.current_score = current_score self.last_flag_score = 0 def add_flag(self, name, value): self.flag_store.add(self.teamname, name, value) def run(self): print "Firing up Blueteam %s, go time is %s" % \ (self.teamname, self.go_time) if globalvars.quick: self.go_time = time.time() + 5 while True: go_time_lt = time.localtime(self.go_time) if self.did_time: did_time_lt = time.localtime(self.did_time) if go_time_lt.tm_min == did_time_lt.tm_min: continue else: pass else: pass rightnow = time.time() rightnow_lt = time.localtime(rightnow) if go_time_lt.tm_mday == rightnow_lt.tm_mday: if go_time_lt.tm_hour == rightnow_lt.tm_hour: if go_time_lt.tm_min == rightnow_lt.tm_min: try: print "Now is %s" % rightnow self.did_time = self.go_time self.check() queue_str = self.teamname + "|" + str( self.this_round) self.queue_obj.put(queue_str) now = time.time() new_go = self.go_time + self.interval if new_go < now: self.go_time = now + 60 else: self.go_time = new_go self.set_score() except: traceback.print_exc(file=self.logger) elif go_time_lt.tm_min == (rightnow_lt.tm_min + 1): print "Counting down for %s: %s to %s..." % \ (self.teamname, self.go_time, rightnow) time.sleep(1) else: print "Counting down for %s: %s to %s..." % \ (self.teamname, self.go_time, rightnow) time.sleep(60) else: print "Counting down for %s: %s to %s..." % \ (self.teamname, self.go_time, rightnow) time.sleep(60) else: time.sleep(60) def add_dns(self, dnssvr): if self.dns.nameservers.count(dnssvr): pass else: self.logger.out("Adding DNS %s to %s\n" % (dnssvr, self.teamname)) self.dns.nameservers.append(dnssvr) def del_dns(self, dnssvr): if self.dns.nameservers.count(dnssvr): index = self.dns.nameservers.index(dnssvr) self.dns.nameservers.pop(index) else: pass def add_queue(self, queue): self.queue_obj = queue def check(self): hostlist = self.hosts.keys() for host in hostlist: hostscore = self.hosts[host].check(self.this_round) def add_host(self, hostname, value): if self.hosts.has_key(hostname): self.logger.err(clobber_host_blue_str % (self.teamname, hostname)) else: self.logger.err(add_host_blue_str % (self.teamname, hostname)) self.hosts[hostname] = Host(hostname, value, self.logger, self.dns) def del_host(self, hostname): if self.hosts.has_key(hostname): self.logger.err(del_host_blue_str % (self.teamname, hostname)) del (self.hosts[hostname]) else: self.logger.err(del_host_blue_err_str % (self.teamname, hostname)) def add_service(self, hostname, port, proto, value, uri=None, content=None, username=None, password=None): if self.hosts.has_key(hostname): self.logger.err(add_srvc_blue_str % \ (self.teamname, port, proto, value, hostname)) self.hosts[hostname].add_service(port, proto, value, uri, content, \ username, password) else: self.logger.err(add_srvc_blue_err_str % \ (self.teamname, port, proto, hostname)) def del_service(self, host, port, proto): if self.hosts.has_key(hostname): self.logger.err(add_srvc_blue_str % \ (self.teamname, port, proto, hostname)) self.hosts[hostname].del_service(port, proto, app, value) else: self.logger.err(add_srvc_blue_err_str % \ (self.teamname, port, proto, hostname)) def get_score(self, this_round=None): if not this_round: this_round = self.this_round - 1 this_score = self.scores.get_score(this_round) return [this_round, this_score] def set_score(self, this_round=None, value=None): if this_round and value: this_round = self.this_round self.scores.set_score(this_round, value) return myscore = 0 hostlist = self.hosts.keys() for host in hostlist: myscore += self.hosts[host].get_score(self.this_round) if globalvars.binjitsu: this_score = self.scores.get_score(self.this_round) flag_score = self.flag_store.score(self.teamname, self.this_round) if flag_score != self.last_flag_score: this_flag_score = flag_score - self.last_flag_score self.last_flag_score = flag_score else: this_flag_score = 0 round_score = (myscore * this_flag_score) self.current_score += round_score else: this_score = self.scores.get_score(self.this_round) flag_score = self.flag_store.score(self.teamname, self.this_round) if flag_score != self.last_flag_score: this_flag_score = flag_score - self.last_flag_score round_score = (myscore + (this_flag_score * 1000)) self.last_flag_score = flag_score else: round_score = myscore self.current_score += round_score print "Blueteam %s round %s scored %s for a new total of %s\n" % \ (self.teamname, self.this_round, round_score, self.current_score) self.scores.set_score(self.this_round, self.current_score) print "Blueteam %s tally: %s\n" % (self.teamname, self.get_score()) self.this_round += 1 self.db.update({"_id": self.id}, {"$set": { "current_round": self.this_round }}) self.db.update({"_id": self.id}, {"$set": { "team_score": self.current_score }}) def get_health(self): host_hash = {} for host in self.hosts: name = self.hosts[host].hostname service_hash = self.hosts[host].get_health() if host_hash.has_key(name): self.logger.err("Found duplicate host %s" % name) else: host_hash[name] = service_hash return host_hash
class Service(threading.Thread): ''' classdocs ''' def __init__(self, port, protocol, value, teamname, queue, hostname, \ oqueue, equeue, BToqueue, BTequeue, \ uri="index.html", content=None, username=None, password=None): ''' Constructor ''' threading.Thread.__init__(self) self.hostname = hostname basename = "%s-%s:%s_%s" % (teamname, hostname, port, protocol) #self.logger = Logger(basename) self.oqueue = oqueue self.equeue = equeue self.BToqueue = BToqueue self.BTequeue = BTequeue self.olog = "" self.elog = "" self.port = int(port) self.protocol = protocol self.value = float(value) self.scores = Scores() self.uri = "GET /%s\r\n\r\n" % uri self.up = False self.functional = False self.redcell_here = False self.content = content self.teamname = teamname if self.content: if self.port != 80: self.content_re = re.compile(str(self.content)) else: self.content_re = None if password: self.password = password else: self.password = "******" if username: self.username = username else: self.username = "******" if isinstance(content, dict): self.loginpage = content.get("loginpage") self.user_param = content.get("user_param") self.pwd_param = content.get("pwd_param") self.pages = content.get("pages") self.mail_re = re.compile("220") self.msg_queue = queue def run(self): while True: item = self.msg_queue.get() if len(item) == 3: this_round = item[0] ipaddress = item[1] timeout = item[2] results = self.check(this_round, ipaddress, timeout) self.set_score(results[0], results[1]) #print "Putting done for %s:%s/%s" % (self.hostname, self.port, self.protocol) self.msg_queue.put("Done") else: self.msg_queue.put(item) time.sleep(0.1) def check(self, this_round, ipaddress, timeout): service_name = "%s/%s" % (self.port, self.protocol) penalty = self.value data = "" if tcp_80_re.match(service_name): ############################################ try: if globalvars.verbose: self.elog += "\t\tChecking for service %s/%s..." \ % (self.port, self.protocol) addrport = [ipaddress, self.port] mysock = socket.create_connection(addrport, timeout) mysock.settimeout(timeout) if globalvars.verbose: self.elog += "connected!\n" self.elog += "good\n" except: if globalvars.verbose: self.elog += "there was a problem...\n" penalty = self.value * 1 self.elog += traceback.format_exc() return this_round, penalty try: pageindex = random.randint(0, len(self.pages) - 1) current_page = self.pages[pageindex] if globalvars.verbose: self.elog += "\t\t\tTrying to fetch %s..." % self.uri web_session = requests.Session() if self.loginpage: payload = { self.user_param: self.username, self.pwd_param: self.password } web_session.post("http://{}{}".format( ipaddress, self.loginpage), data=payload, timeout=timeout) url = "http://{}{}".format(ipaddress, current_page.get("url")) result = web_session.get(url, timeout=timeout) if redcell_str_re.search(result.text) is not None: self.redcell_here = True self.elog += "#Redcell tag was detected..\n" return this_round, self.value * 0 else: self.redcell_here = False try: content_length = int(result.headers.get('content_length')) except: content_length = len(result.text) content_min = current_page.get("size") - 100 content_max = current_page.get("size") + 100 if content_length >= content_min or content_length <= content_max: if globalvars.verbose: self.elog += "content length matched!\n" self.elog += "good\n" else: self.elog += "Content-length: {} did not current_page size: {}.\n".format( content_length, current_page.get("size")) raise Exception('Content-length did not match size') if "keywords" in current_page.keys(): for keyword in current_page.get("keywords"): if keyword not in result.text: raise Exception( 'Keywords {} not matched'.format(keyword)) return this_round, self.value * 0 except Exception as e: if globalvars.verbose: self.elog += "there was a problem...{}\n".format(e) penalty = self.value * 0.25 self.elog += traceback.format_exc() return this_round, penalty ############################################ elif tcp_21_re.match(service_name): ############################################ try: if globalvars.verbose: self.elog += "\t\tChecking for service %s/%s..." \ % (self.port, self.protocol) myftp = ftplib.FTP(timeout=timeout) myftp.connect(ipaddress, self.port) if globalvars.verbose: self.elog += "connected!\n" except: if globalvars.verbose: self.elog += "there was a problem...\n" penalty = self.value * 1 self.elog += traceback.format_exc() return this_round, penalty ############################################ try: if globalvars.verbose: self.elog += "\t\t\tTrying to login with %s and %s..." % \ (self.username, self.password) myftp.login(self.username, self.password) if globalvars.verbose: self.elog += "success!\n" except: if globalvars.verbose: self.elog += "there was a problem...\n" penalty = self.value * 0.75 self.elog += traceback.format_exc() return this_round, penalty ############################################ try: if globalvars.verbose: self.elog += "\t\t\tTrying to fetch %s..." % self.uri filename = "status/%s-%s.%s" % (self.teamname, ipaddress, self.port) file_obj = open(filename, "w") myftp.set_pasv(False) myftp.retrbinary("RETR scoring_file.txt", file_obj.write) if globalvars.verbose: self.elog += "requested...\n" except: if globalvars.verbose: self.elog += "there was a problem...\n" penalty = self.value * 0.50 self.elog += traceback.format_exc() return this_round, penalty ############################################ try: if globalvars.verbose: self.elog += "\t\t\tChecking data..." file_obj = open(filename) penalty = 0 for line in file_obj: if score_str_re.match(line): penalty = self.value * 0 self.redcell_here = False elif redcell_str_re.search(line): penalty = self.value * 0.25 self.redcell_here = True else: self.redcell_here = False penalty = self.value * 0.25 if globalvars.verbose: self.elog += "good\n" return this_round, penalty except: if globalvars.verbose: self.elog += "bad: %s\n" % data penalty = self.value * 0.333 self.elog += traceback.format_exc() return this_round, penalty elif tcp_25_re.match(service_name): #self.set_score(this_round, 0) #self.elog += "NEED TO IMPLEMENT 25/TCP SCORE CHECKING!!\n" ############################################ try: if globalvars.verbose: self.elog += "\t\tChecking for service %s/%s..." \ % (self.port, self.protocol) addrport = [ipaddress, self.port] mysock = socket.create_connection(addrport, timeout) mysock.settimeout(timeout) if globalvars.verbose: self.elog += "connected!\n" except: if globalvars.verbose: self.elog += "there was a problem...\n" penalty = self.value * 1 self.elog += traceback.format_exc() return this_round, penalty ############################################ try: if globalvars.verbose: self.elog += "\t\tSending HELO..." mysock.send("HELO mail") if globalvars.verbose: self.elog += "sent...\n" except: if globalvars.verbose: self.elog += "there was a problem:\n" penalty = self.value * .75 self.elog += traceback.format_exc() return this_round, penalty ############################################ try: if globalvars.verbose: self.elog += "\t\t\tGetting data..." data = mysock.recv(1024) if globalvars.verbose: self.elog += "fetched\n" except: if globalvars.verbose: self.elog += "there was a problem...\n" penalty = self.value * .50 self.elog += traceback.format_exc() return this_round, penalty ############################################ if globalvars.verbose: self.elog += "\t\t\tChecking data..." if self.mail_re.search(data): if globalvars.verbose: self.elog += "good\n" return this_round, self.value * 0 else: if globalvars.verbose: self.elog += "bad: %s\n" % data return this_round, self.value * .25 ############################################ else: try: if globalvars.verbose: self.elog += "\t\tChecking for service %s/%s..." \ % (self.port, self.protocol) addrport = [ipaddress, self.port] mysock = socket.create_connection(addrport, timeout) mysock.settimeout(timeout) if globalvars.verbose: self.elog += "connected!\n" penalty = self.value * 0 return this_round, penalty except: if globalvars.verbose: self.elog += "there was a problem...\n" penalty = self.value * 1 self.elog += traceback.format_exc() return this_round, penalty def get_score(self, this_round): return self.scores.get_score(this_round) def set_score(self, this_round, penalty=None): if penalty == None: penalty = self.value service_name = "%s/%s" % (str(self.port), str(self.protocol)) if (penalty == self.value): self.up = False self.functional = False elif (penalty > 0): self.up = True self.functional = False else: self.up = True self.functional = True this_penalty = penalty this_value = self.value - this_penalty this_time = time.strftime('%X %x %Z') self.equeue.put(self.elog) self.oqueue.put(self.olog) msg = "%s Round %s host %s service %s score %s\n" % \ (this_time, this_round, self.hostname, service_name, this_value) print msg self.BToqueue.put(msg) self.scores.set_score(this_round, this_value) def get_state(self): # Returns 3 if up and fucntional, but redcell has taken it over # Returns 2 if up and functional # Returns 1 if up but not functional # Returns 0 if down if self.redcell_here == True: return 3 else: return self.up + self.functional def get_scores(self): return self.scores def set_scores(self, scores): if isinstance(scores, Scores): self.scores = scores else: raise Exception("Invalid score object given!")
class Arkanoid(QWidget): # ширина поля W = 800 # высота поля H = 600 # конструктор def __init__(self): # вызов конструктора базового класса super().__init__() # инициализация поля self.initUI() # подготовка поля def initUI(self): # перемещение self.move(300, 300) # фиксируем ширину и высоту поля self.setFixedSize(Arkanoid.W, Arkanoid.H) # задаём имя программы self.setWindowTitle('Арканоид') # загружаем фоновое изображение self.background = QImage('background.jpg') # создаём кубики self.cubes = Cubes() # созаём ракетку self.racket = Racket(Arkanoid.W / 2 - Racket.W / 2) # создаём шарик self.ball = Ball(Arkanoid.W / 2, Racket.Y - Ball.R, 60) # создаём надпись self.label = Label(150, Arkanoid.H // 2, Arkanoid.W - 300, 60) # создаем очки self.scores = Scores(0, 9, Arkanoid.W, 30) # создаём таймер self.timer = QtCore.QTimer() # заканчиваем время self.timer.timeout.connect(self.tick) # задаём начало счётчика self.timer.start(2) # включаем отслеживание мыши self.setMouseTracking(1) # переходим в состояние запуска self.restart() # запуск или перезапуск арканоида def restart(self): # заполняем кубики self.cubes.initCubes() # сбрасываем позицию и угол шарика self.ball.cx = Arkanoid.W / 2 self.ball.cy = Racket.Y - Ball.R self.ball.angle = random.randint(60, 120) # переходим в состояние запуска self.state = STATE_START # перекрытие функции рисования на окне def paintEvent(self, e): # обработка ошибок try: # создаём рисовальщик qp = QPainter() # начало рисования qp.begin(self) # рисуем фоновую картинку qp.drawImage(0, 0, self.background) # рисуем кубики self.cubes.draw(qp) # рисуем ракетку self.racket.draw(qp) # рисуем шарик self.ball.draw(qp) # рисуем надпись self.drawState(qp) # рисуем очки self.scores.draw(qp) # завершение рисования qp.end() except Exception as e: # печать ошибок print(str(e)) # взависимости от текущего состояния # выводим на экран ту или иную запись def drawState(self, qp: QPainter): if self.state == STATE_START: self.label.draw(qp, "Добро пожаловать в Арканоид!") elif self.state == STATE_PAUSE: self.label.draw(qp, "Пауза") elif self.state == STATE_WIN_LEVEL: self.label.draw( qp, "Вы перешли на уровень " + str(self.cubes.level) + ". Поздравляю!") elif self.state == STATE_WIN_GAME: self.label.draw(qp, "Вы прошли игру! Поздравляю!") elif self.state == STATE_LOSE: self.label.draw(qp, "Вы проиграли") # обработка клавиатуры def keyPressEvent(self, event): if self.state == STATE_GAME: # если во время игры нажали Влево if event.key() == KEY_LEFT: # то смещаем рокетку Влево self.moveRocketTo(self.racket.x - Racket.DX) # если во время игры нажали Вправо elif event.key() == KEY_RIGHT: # то смещаем ракетку Вправо self.moveRacketTo(self.racket.x + Racket.DX) # если во время игры нажали Пробел if event.key() == KEY_SPACE: # то переходим в сотояние паузы self.state = STATE_PAUSE # обновляем окно self.update() else: # если нажат Пробел if event.key() == KEY_SPACE: # если выиграли игру или проиграли if self.state == STATE_WIN_GAME or self.state == STATE_LOSE: # сбрасываем уровень self.cubes.level = 1 # сбрасываем очки self.scores.count = 0 # если не на паузе if self.state != STATE_PAUSE: # то перезапуск self.restart() # переходим в состояние игры self.state = STATE_GAME # обновляем окно self.update() # обработка перемещения мыши def mouseMoveEvent(self, event): # если во время игры перемещаем мышь if self.state == STATE_GAME: # то перемещаем ракетку self.moveRacketTo(event.pos().x() - Racket.W / 2) # перемещение ракетки def moveRacketTo(self, x: int): # ракетку нельзя выводить за левый край экрана if x < 1: x = 1 # ракетку нельзя выводить за правый край экрана if x + Racket.W >= Arkanoid.W - 2: x = Arkanoid.W - 2 - Racket.W # если позиция ракетки изменилась if self.racket.x != x: # то перемещаем ракетку self.racket.x = x # обновляем экран self.update() # обработчик таймера def tick(self): try: # если не в состоянии игры, то таймер игнорируем if self.state != STATE_GAME: return # перемещение шарика self.ball.move() # обработка касания шариком ракетки if self.ball.touched(self.racket.x, Racket.Y, self.racket.x + Racket.W, Racket.Y): # в зависимости от того, куда шарик попал по ракетке # устанавливаем разный угол # если в левый край - то 160 градусов # ecли в правый - то 30 градусов # если по центру - то 90 градусов dx = self.racket.x + Racket.W - self.ball.cx self.ball.angle = dx / Racket.W * (160 - 30) + 30 # обработка касания шариком краев экрана self.ball.touchedRect(0, 0, Arkanoid.W, Arkanoid.H) # обработка касания шариком кубиков for cube in self.cubes: # если мяч коснулся куба if self.ball.touchedRect(cube.x, cube.y, cube.x + Cube.W, cube.y + Cube.H): # изменение номера цвета куба cube.collor_number += 1 self.scores.count += 1 # если цвет куба больше количества цветов if cube.collor_number >= len(Cube.RAINBOW): # убираем кубик self.cubes.remove(cube) # если мяч ниже рокетки if self.ball.cy > Racket.Y + Racket.H + 20: # переходим в состояние пройгрыша self.state = STATE_LOSE # если кубики закончились if len(self.cubes) == 0: # переходим в состояние выйгрыша self.state = STATE_WIN_LEVEL # поднимаем уровень self.cubes.level += 1 # если прошли все цвета радуги if self.cubes.level > len(Cube.RAINBOW): # то считаем, что прошли игру self.state = STATE_WIN_GAME # обновляем экран self.update() except Exception as e: # печать ошибок print(e)
class Service(threading.Thread): ''' classdocs ''' def __init__(self, port, protocol, value, teamname, queue, hostname, uri="index.html", \ content=None, username=None, password=None): ''' Constructor ''' threading.Thread.__init__(self) self.hostname = hostname basename = "%s-%s:%s_%s" % (teamname, hostname, port, protocol) self.logger = Logger(basename) self.port = int(port) self.protocol = protocol self.value = float(value) self.scores = Scores() self.uri = "GET /%s\r\n\r\n" % uri self.up = False self.functional = False self.content = content if self.content: if self.port != 80: self.content_re = re.compile(str(self.content)) else: self.content_re = None if password: self.password = password else: self.password = "******" if username: self.username = username else: self.username = "******" if isinstance(content, dict): self.loginpage = content.get("loginpage") self.user_param = content.get("user_param") self.pwd_param = content.get("pwd_param") self.pages = content.get("pages") self.mail_re = re.compile("220") self.msg_queue = queue def run(self): while True: item = self.msg_queue.get() if len(item) == 3: this_round = item[0] ipaddress = item[1] timeout = item[2] self.check(this_round, ipaddress, timeout) #print "Putting done for %s:%s/%s" % (self.hostname, self.port, self.protocol) self.msg_queue.put("Done") else: self.msg_queue.put(item) time.sleep(0.1) def check(self, this_round, ipaddress, timeout): service_name = "%s/%s" % (self.port, self.protocol) penalty = self.value data = "" if tcp_80_re.match(service_name): ############################################ try: if globalvars.verbose: self.logger.err("\t\tChecking for service %s/%s..." \ % (self.port, self.protocol)) addrport = [ipaddress, self.port] mysock = socket.create_connection(addrport, timeout) mysock.settimeout(timeout) if globalvars.verbose: self.logger.err("connected!\n") self.logger.err("good\n") except: if globalvars.verbose: self.logger.err("there was a problem...\n") penalty = self.value * 1 traceback.print_exc(file=self.logger) try: check_amount = random.randint(0, len(self.pages)-1) for _i in xrange(0, check_amount): pageindex = random.randint(0, len(self.pages)-1) current_page = self.pages[pageindex] if globalvars.verbose: self.logger.err("\t\t\tTrying to fetch %s..." % self.uri) web_session = requests.Session() if self.loginpage: payload = { self.user_param: self.username, self.pwd_param: self.password } web_session.post( "http://{}{}".format(ipaddress, self.loginpage), data=payload, timeout=timeout ) url = "http://{}{}".format(ipaddress, current_page.get("url")) result = web_session.get(url, timeout=timeout) try: content_length = int(result.headers.get('content_length')) except: content_length = len(result.text) content_min = current_page.get("size") - 100 content_max = current_page.get("size") + 100 if content_length >= content_min or content_length <= content_max: if globalvars.verbose: self.logger.err("content length matched!\n") self.logger.err("good\n") else: self.logger.err("Content-length: {} did not current_page size: {}.\n".format(content_length, current_page.get("size"))) raise Exception('Content-length did not match size') if "keywords" in current_page.keys(): for keyword in current_page.get("keywords"): if keyword not in result.text: raise Exception( 'Keywords {} not matched'.format(keyword) ) self.set_score(this_round, self.value * 0) except Exception as e: if globalvars.verbose: self.logger.err("there was a problem...{}\n".format(e)) penalty = self.value * 0.25 traceback.print_exc(file=self.logger) elif tcp_21_re.match(service_name): ############################################ try: if globalvars.verbose: self.logger.err("\t\tChecking for service %s/%s..." \ % (self.port, self.protocol)) myftp = ftplib.FTP(timeout=timeout) myftp.connect(ipaddress, self.port) if globalvars.verbose: self.logger.err("connected!\n") except: if globalvars.verbose: self.logger.err("there was a problem...\n") penalty = self.value * 1 traceback.print_exc(file=self.logger) self.set_score(this_round, penalty) ############################################ try: if globalvars.verbose: self.logger.err("\t\t\tTrying to login with %s and %s..." % \ (self.username, self.password)) myftp.login(self.username, self.password) if globalvars.verbose: self.logger.err("success!\n") except: if globalvars.verbose: self.logger.err("there was a problem...\n") penalty = self.value * 0.75 traceback.print_exc(file=self.logger) self.set_score(this_round, penalty) ############################################ try: if globalvars.verbose: self.logger.err("\t\t\tTrying to fetch %s..." % self.uri) filename = "%s.%s" % (ipaddress, self.port) file_obj = open(filename, "w") myftp.set_pasv(False) myftp.retrbinary("RETR scoring_file.txt", file_obj.write) if globalvars.verbose: self.logger.err("requested...\n") except: if globalvars.verbose: self.logger.err("there was a problem...\n") penalty = self.value * 0.50 traceback.print_exc(file=self.logger) self.set_score(this_round, penalty) ############################################ try: if globalvars.verbose: self.logger.err("\t\t\tChecking data...") file_obj = open(filename) for line in file_obj: if score_str_re.match(line): penalty = self.value * 0 if globalvars.verbose: self.logger.err("good\n") else: penalty = self.value * 0.25 self.set_score(this_round, penalty) except: if globalvars.verbose: self.logger.err("bad: %s\n" % data) penalty = self.value * 0.333 traceback.print_exc(file=self.logger) self.set_score(this_round, penalty) elif tcp_25_re.match(service_name): #self.set_score(this_round, 0) #self.logger.err("NEED TO IMPLEMENT 25/TCP SCORE CHECKING!!\n") ############################################ try: if globalvars.verbose: self.logger.err("\t\tChecking for service %s/%s..." \ % (self.port, self.protocol)) addrport = [ipaddress, self.port] mysock = socket.create_connection(addrport, timeout) mysock.settimeout(timeout) if globalvars.verbose: self.logger.err("connected!\n") except: if globalvars.verbose: self.logger.err("there was a problem...\n") penalty = self.value * 1 traceback.print_exc(file=self.logger) self.set_score(this_round, penalty) ############################################ try: if globalvars.verbose: self.logger.err("\t\tSending HELO..." ) mysock.send("HELO mail") if globalvars.verbose: self.logger.err("sent...\n") except: if globalvars.verbose: self.logger.err("there was a problem:\n") penalty = self.value * .75 traceback.print_exc(file=self.logger) self.set_score(this_round, penalty) ############################################ try: if globalvars.verbose: self.logger.err("\t\t\tGetting data...") data = mysock.recv(1024) if globalvars.verbose: self.logger.err("fetched\n") except: if globalvars.verbose: self.logger.err("there was a problem...\n") penalty = self.value * .50 traceback.print_exc(file=self.logger) self.set_score(this_round, penalty) ############################################ if globalvars.verbose: self.logger.err("\t\t\tChecking data...") if self.mail_re.search(data): if globalvars.verbose: self.logger.err("good\n") self.set_score(this_round, self.value * 0) else: if globalvars.verbose: self.logger.err("bad: %s\n" % data) self.set_score(this_round, self.value * .25) ############################################ else: try: if globalvars.verbose: self.logger.err("\t\tChecking for service %s/%s..." \ % (self.port, self.protocol)) addrport = [ipaddress, self.port] mysock = socket.create_connection(addrport, timeout) mysock.settimeout(timeout) if globalvars.verbose: self.logger.err("connected!\n") penalty = self.value * 0 self.set_score(this_round, penalty) except: if globalvars.verbose: self.logger.err("there was a problem...\n") penalty = self.value * 1 traceback.print_exc(file=self.logger) self.set_score(this_round, penalty) service_name = "%s/%s" % (str(self.port), str(self.protocol)) self.set_score(this_round, penalty) def get_score(self, this_round): return self.scores.get_score(this_round) def set_score(self, this_round, penalty=None): if penalty == None: penalty = self.value service_name = "%s/%s" % (str(self.port), str(self.protocol)) if (penalty == self.value): self.up = False self.functional = False elif (penalty > 0): self.up = True self.functional = False else: self.up = True self.functional = True this_penalty = penalty this_value = self.value - this_penalty this_time = time.strftime('%X %x %Z') self.logger.out("%s Round %s host %s service %s score %s\n" % \ (this_time, this_round, self.hostname, service_name, this_value)) self.logger.err("Round %s service %s score %s\n" % \ (this_round, service_name, this_value)) self.scores.set_score(this_round, this_value) def get_state(self): # Returns 2 if up and functional # Returns 1 if up but not functional # Returns 0 if down return self.up + self.functional def get_scores(self): return self.scores def set_scores(self, scores): if isinstance(scores, Scores): self.scores = scores else: raise Exception("Invalid score object given!")
class Host(object): ''' classdocs ''' def __init__(self, hostname, value, logger, dns_servers, timeout=300): ''' Constructor ''' self.hostname = hostname self.dns_servers = dns_servers self.logger = logger self.ipaddress = None self.compromised = False self.services = {} self.value = value self.scores = Scores() self.timeout = timeout def add_dns(self, dnssvr): if dnssvr in self.dns_servers: pass else: self.dns_servers.append(dnssvr) def del_dns(self, dnssvr): if dnssvr in self.dns_servers: index = self.dns.nameservers.index(dnssvr) self.dns_servers.pop(index) else: pass def lookup(self, record="A"): if globalvars.verbose: mydns = ", ".join(self.dns_servers) self.logger.err("Looking up %s with %s\n" % (self.hostname, mydns)) try: for svr in self.dns_servers: # We set a short timeout because life moves too fast...so does the game! r = DNS.DnsRequest(self.hostname, qtype="A", server=[svr], protocol='udp', timeout=30) res = r.req() for answer in res.answers: if answer["data"]: ipaddress = answer["data"] break if ctfnet_re.search(ipaddress): if globalvars.verbose: self.logger.err("got %s\n" % self.ipaddress) self.ipaddress = ipaddress return True else: self.logger.err("Got non RFC1918: %s\n" % ipaddress) return False except: traceback.print_exc(file=self.logger) self.ipaddress = None return False def add_service(self, port, proto, value, uri=None, content=None, \ username=None, password=None): service_name = "%s/%s" % (port, proto) if self.services.has_key(service_name): pass self.services[service_name] = Service(port, proto, value, \ self.logger, uri, content, username, password) def check(self, this_round): score = int(self.value) try: if self.lookup(): if globalvars.verbose: self.logger.err("Checking for %s(%s) with ping...\n" \ % (self.hostname, self.ipaddress)) myping = Ping.Ping() results = myping.quiet_ping(self.ipaddress) percent_failed = int(results[0]) if percent_failed < 100: self.check_services(this_round) else: self.fail_services(this_round) if globalvars.binjitsu: score = int(self.value) - (int(self.value)*percent_failed/100) else: score = int(self.value) * percent_failed / 100 if globalvars.verbose: if score: self.logger.err("%s failed: %s\n" % (self.hostname,score)) else: self.logger.err("%s scored: %s\n" % (self.hostname,score)) pass else: self.fail_services(this_round) except: traceback.print_exc(file=self.logger) self.set_score(this_round, score) return score def check_services(self, this_round): if globalvars.verbose: self.logger.err("Checking services for %s:\n" % self.hostname) services = self.services.keys() for service in services: if globalvars.verbose: self.logger.err("\tChecking %s\n" % service) self.services[service].check(this_round, \ self.ipaddress, self.timeout) def set_score(self, this_round, value=None): if value == None: this_value = self.value else: this_value = value self.logger.out("Round %s host %s score %s\n" % \ (this_round, self.hostname, this_value)) self.logger.err("Round %s host %s score %s\n" % \ (this_round, self.hostname, this_value)) self.scores.set_score(this_round, this_value) def fail_services(self, this_round): if globalvars.verbose: self.logger.err("Failing service scores for %s:\n" % self.hostname) services = self.services.keys() for service in services: if globalvars.verbose: self.logger.err("\tFailing for %s:" % service) self.services[service].set_score(this_round) def get_score(self, this_round): try: score = 0 score += self.scores.get_score(this_round) services = self.services.keys() for service in services: score += self.services[service].get_score(this_round) return score except: self.logger.err("Had a problem with host %s:\n" % self.hostname) traceback.print_exc(file=self.logger) return False def get_health(self): service_hash = {} for service in self.services: name = "%s/%s" % (self.services[service].port, \ self.services[service].protocol) state = self.services[service].get_state() if service_hash.has_key(name): self.logger.err("Found duplicate service %s" % name) else: service_hash[name] = state return service_hash def get_scores(self): services_scores = {} for service in self.services: services_scores[service] = self.services[service].get_scores() host_total_scores = {"host":self.scores, "services": services_scores} return host_total_scores def set_scores(self, host_total_scores): """ Function to import and process the json object exported by get_scores() """ if "host" in host_total_scores: self.scores = host_total_scores["host"] else: json_obj = jsonpickle.encode(host_total_scores) raise Exception ("Invalid team_scores hash, missing host score! \n%s\n" % json_obj) if "services" in host_total_scores: for service in self.services: if service in host_total_scores["services"]: self.services[service].set_scores(host_total_scores["services"][service]) else: json_obj = jsonpickle.encode(host_total_scores) raise Exception ("Invalid service score hash in scores! \n%s\n" % json_obj) else: json_obj = jsonpickle.encode(host_total_scores) raise Exception ("Invalid team_scores hash, missing services scores! \n%s\n" % json_obj)