HC's CTF site

The simplest testscript

Below is the testscript for the simplest CTF service.

 #!/usr/bin/python2.5
 from sys import argv, exit
 from socket import *
 from time import time
 from sha import sha
 from time import sleep
 import sys
 MY_IP = 'localhost'
 def bindsock():
     s = socket(AF_INET, SOCK_DGRAM)
     pwu = -1
     for i in range(1985, 65000):
         try:
             s.bind(('0.0.0.0', i))
             pwu = i
             break
         except:
             pass
     if pwu == -1:
         return -1, None
     return pwu, s
 def store(ip, flagid, flag):
     print "Sending %s to %s" % (flag, ip)
     s = socket(AF_INET, SOCK_DGRAM)
     pwu, locsoc = bindsock()
     if pwu == -1:
         print "Can't bind local socket"
         exit(1)
     locsoc.sendto("add %s %d %s %s" % (MY_IP, pwu, flagid, flag), (ip, 1984))
     locsoc.setblocking(False)
     sleep(5)
     try:
         answer = locsoc.recvfrom(1024)[0]
     except:
         sys.stderr.write("Service did not respond: %s" % str(e))
         exit(1)
     if answer == 'OK':
         sys.stderr.write("Service responded according to procotol.")
         print "OK"
         exit(0)
     sys.stderr.write("Service did not respond OK: %s" % repr(answer))
     exit(1)
 def retrieve(ip, flagid, flag):
     s = socket(AF_INET, SOCK_DGRAM)
     pwu, locsoc = bindsock()
     if pwu == -1:
         print "no port avail!? WTF!!1!"
         exit(2)
     print "using port %d" % pwu
     locsoc.sendto("get %s %d %s" % (MY_IP, pwu, flagid), (ip, 1984))
     locsoc.setblocking(False)
     sleep(5)
     try:
         answer = locsoc.recvfrom(1024)[0]
     except Exception, e:
         sys.stderr.write("Service did not respond: %s" % str(e))
         exit(2)
     print answer
     if answer == flag:
         print "Flag successfully retrieved!"
         sys.stderr.write("Service returned the correct flag")
         exit(0)
     print "Flag *not* successfully retrieved!"
     sys.stderr.write("Service returned the wrong flag")
     exit(1)
 fncts = {
     'store': store,
     'retrieve': retrieve
 }
 if argv[1] == 'test': sys.exit(0)
 [e, f, a, fid, i] = argv
 fncts[f](a, fid, i)