#!/usr/bin/env python3.4 
import socket

"""
Network Security Hacking Challenges 2014

Challenge: Enter your name into our database.
If you prefer to stay pseudonymous, you may instead enter your "tag".
Please use the same name/tag throughout the semester.

Rules:
1) Be fair! Do not DOS our systems.
2) Please try to enter your name/tag only once


Database at
$ nc netsec.net.in.tum.de 30003
"""
# WARNING:
# This is just a sample client.
# use at your own risk!
# The way we use recv is not advisable, but it works for our example.

#create socket and connect to server, sending the user credentials
HOST = '131.159.15.68' #netsec.net.in.tum.de
PORT = 20003            
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#Uncomment the  Following lines if you want to use IPv6 (not necessary)
#s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
#HOST = '2001:4ca0:2001:18:216:3eff:fef0:3933'
s.connect((HOST, PORT))

#This time, the server will leak the SHA256 hash of the password (hint: Server used hashlib to create the hash).
#To be able to enter your tag, you will need send the correct password back to the server.
#A username is not needed.
data = s.recv(1024)
#TODO did we get the full challenge? TODO recv may fail!
assert(data)
data = data.decode()
print("Ups, the server sent us a hashed password (hint: 6 digits): ", data)

password=input("Password: ")
password+="\n"
#IMPORTANT: If you want a string to be sent immediately, it should end with \n, otherwise it may be buffered
s.sendall(password.encode())

#if credentials were correct and the equation solved correctely, we receive a "login successfull" and the server waits for our tag
#otherwise he will close the connection and send us some information on what was wrong.
data = s.recv(1024) #TODO we may have received only partial data
assert(data)
data = data.decode()
print(data)
if data=="login successful":
    tag=input("Enter your Tag: ") #check if your tag was entered correctly via netsec.net.in.tum.de:30002
    s.sendall((tag+"\n").encode())

s.close()
