moth/bin/in.flagd

97 lines
2.3 KiB
Python
Executable File

#! /usr/bin/python
import sys
import optparse
import hmac
import time
import select
from ctf import teams, pointscli
import os
from urllib import quote
basedir = None
flagsdir = None
key = 'My First Shared Secret (tm)'
def hexdigest(s):
return hmac.new(key, s.encode('utf-8')).hexdigest()
def auth():
# Pretend to be in.tcpmuxd
while True:
line = sys.stdin.readline()
if not line:
return
line = line.strip().lower()
if line == 'tcpmux':
sys.stdout.write('+Okay, fine.\r\n')
sys.stdout.flush()
continue
elif line == 'help':
sys.stdout.write('tcpmux\r\n')
elif ':::' in line:
# Authentication
cat, passwd = line.split(':::')
if passwd == hexdigest(cat):
return cat
else:
sys.stdout.write('-Blow me.\r\n')
else:
sys.stdout.write('-Blow me.\r\n')
return
def award(cat, team):
qcat = quote(cat, '')
fn = os.path.join(flagsdir, qcat)
f = open(fn, 'w')
f.write(team)
f.close()
pointscli.award(cat, team, 1)
print('+%s' % team)
sys.stdout.flush()
def run():
cat = auth()
if not cat:
return
now = time.time()
next_award = now - (now % 60)
flag = teams.house
while True:
now = time.time()
while now >= next_award:
next_award += 60
award(cat, flag)
timeout = next_award - now
r, w, x = select.select([sys.stdin], [], [], timeout)
if r:
line = sys.stdin.readline()
if not line:
break
new_flag = line.strip() or teams.house
if new_flag != flag:
# Award a point if the flag is captured
flag = new_flag
award(cat, flag)
def main():
p = optparse.OptionParser(usage='%prog [options] FLAGSDIR')
p.add_option('-a', '--auth', dest='cat', default=None,
help='Generate authentication for the given category')
opts, args = p.parse_args()
if opts.cat:
print('%s:::%s' % (opts.cat, hexdigest(opts.cat.encode('utf-8'))))
elif len(args) != 1:
p.error('Wrong number of arguments')
else:
global flagsdir
flagsdir = args[0]
run()
if __name__ == '__main__':
main()