#!/usr/bin/python
# Codegate 2010 challenge 17 - StalkR
import socket
host, port = "ctf3.codegate.org", 10909

# working LCG parameters
# multiplier (a), increment (c), modulus (m) and original seed (s)
a, c, m, s = 65, 7, 256, 1

# Linear Congruential Generator of parameters a,c,m and global seed s
def lcg():
    global s
    s = (a*s+c)%m
    return s

def main():
    k = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    k.connect((host, port))
    # Send valid a,c,m Linear Congruential Generator parameters
    k.recv(4), k.send(str(a)+"\n")
    k.recv(4), k.send(str(c)+"\n")
    k.recv(4), k.send(str(m)+"\n")
    # Receive confirmation of parameters, seed and ciphered text
    d = k.recv(1024)
    k.close()
    # Extract ciphered text (store integers)
    t = [int(i,16) for i in d.split('\n')[1].split('\\x')[1:]]
    # XOR it with running LCG and display result
    print "".join([chr(i^lcg()) for i in t])

if __name__ == '__main__':
    main()
