Path: blob/master/Discrete-Logarithm-Problem/Elliptic-Curve-DLP/Algo-Pollard-Rho/Challenges/Multiplayer-2/server.sage.py
1403 views
1# This file was *autogenerated* from the file server.sage2from sage.all_cmdline import * # import sage library34_sage_const_3 = Integer(3); _sage_const_2 = Integer(2); _sage_const_1 = Integer(1); _sage_const_200 = Integer(200); _sage_const_5 = Integer(5); _sage_const_4 = Integer(4); _sage_const_8192 = Integer(8192); _sage_const_0 = Integer(0)5import asyncore, socket, json, sqlite3, time67FLAG1 = "flag{XXXXXXXXXXX}"8POINT_TRESHOLD = _sage_const_200910def json_response(code, additional_parameter=""):11response_codes = {12_sage_const_0 : "Point added",13_sage_const_1 : "Collision found",14_sage_const_2 : "Point already included",15_sage_const_3 : 'Wrong input format. Please provide a string like this: {"x": val, "y": val, "c": val, "d": val, "groupID": val})',16_sage_const_4 : "Value mismatch! X != c*P + d*Q",17_sage_const_5 : "Server Error"18}19return '{"Response": "%d", "Message": "%s"%s}' % (code, response_codes[code], additional_parameter)202122# Teams should choose a non-guessable groupID23def get_response(x, y, c, d, groupID):24# open connection to database25conn = sqlite3.connect("points.db")26conn.row_factory = sqlite3.Row27conn_cursor = conn.cursor()2829# convert sage integers to string to avoid "Python int too large for SQLite INTEGER"30x = str(x)31y = str(y)32c = str(c)33d = str(d)3435# Select records that map to the same X value36conn_cursor.execute("SELECT * FROM points WHERE x = :x", {"x": x})37query = conn_cursor.fetchall()3839# No record found -> Point is not yet included40if len(query) == _sage_const_0 :41# Insert point into database42conn_cursor.execute("INSERT INTO points (x, y, c, d, groupID) VALUES (?, ?, ?, ?, ?)",43(x, y, c, d, groupID))44# Get number of points added by this group45conn_cursor.execute("SELECT x FROM points WHERE groupID = :gID", {"gID": groupID})46points_found = conn_cursor.fetchall()47add_param = ', "points_found": %d' % len(points_found)48# When they found POINT_TRESHOLD distinguished points and a collision occured, return the colliding values as well49if len(points_found) > POINT_TRESHOLD:50add_param += ', "flag1": "%s"' % FLAG151if server.collision_found:52# compute x from the collision, second flag is just x (not in flag format)53add_param += ', "collision": %s' % (server.collision)54response = json_response(_sage_const_0 , add_param)55else:56# One (or more) records found -> check if they have the same exponents57is_included = False58for row in query:59if row["c"] == c and row["d"] == d:60is_included = True61response = json_response(_sage_const_2 )62break6364if not is_included:65# Exponents are different -> Collision found, add this point66conn_cursor.execute("INSERT INTO points (x, y, c, d, groupID, collision) VALUES (?, ?, ?, ?, ?, 1)",67(x, y, c, d, groupID))68# Get number of points added by this group69conn_cursor.execute("SELECT x FROM points WHERE groupID = :gID", {"gID": groupID})70points_found = conn_cursor.fetchall()71add_param = ', "points_found": %d' % len(points_found)72# add collision73server.collision_found = True74server.collision = '{"c_1": %s, "d_1": %s, "c_2": %s, "d_2": %s}' % (c, d, row["c"], row["d"])75if len(points_found) > POINT_TRESHOLD:76add_param += ', "collision": %s' % (server.collision)77else:78add_param += ', "collision": "collision found but not enough distinguished points submitted yet"'7980response = json_response(_sage_const_1 , add_param + ', "c": %s, "d": %s' % (row["c"], row["d"]))8182# close db connection and return response83conn.commit()84conn_cursor.close()85conn.close()86return response878889class DLogHandler(asyncore.dispatcher_with_send):9091def handle_read(self):92try:93json_data = self.recv(_sage_const_8192 )94if not json_data:95return9697data = json.loads(json_data)98# check if the format is correct99if not ("x" in data and "y" in data and "c" in data and "d" in data and "groupID" in data):100response = json_response(_sage_const_3 )101else:102c = Integer(data["c"])103d = Integer(data["d"])104x = Integer(data["x"])105y = Integer(data["y"])106X = E((x, y))107if X == c*P + d*Q:108response = get_response(data["x"], data["y"], data["c"], data["d"], data["groupID"])109else:110print("expected %s = %d*%s + %d*%s, but got %s" % (c*P + d*Q, c, P, d, Q, X))111response = json_response(_sage_const_4 )112113self.send(response)114115except Exception as e:116response = json_response(_sage_const_5 , ', "Error Message": "%s"' % e)117118119class Server(asyncore.dispatcher_with_send):120121def __init__(self, host, port):122asyncore.dispatcher.__init__(self)123self.create_socket(socket.AF_INET, socket.SOCK_STREAM)124self.set_reuse_addr()125self.bind((host, port))126self.listen(_sage_const_5 )127# variable to store some collision128self.collision_found = False129self.collision = {}130131def handle_accept(self):132pair = self.accept()133if pair is not None:134sock, addr = pair135print("incoming connection from %s" % repr(addr))136DLogHandler(sock)137138139if __name__ == '__main__':140141load("parameters.sage")142server = Server(serverAdress, serverPort)143asyncore.loop()144145146147