Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ashutosh1206
GitHub Repository: ashutosh1206/crypton
Path: blob/master/Discrete-Logarithm-Problem/Elliptic-Curve-DLP/Algo-Pollard-Rho/Challenges/Multiplayer-2/server.sage
1403 views
1
import asyncore, socket, json, sqlite3, time
2
3
FLAG1 = "flag{XXXXXXXXXXX}"
4
POINT_TRESHOLD = 200
5
6
def json_response(code, additional_parameter=""):
7
response_codes = {
8
0 : "Point added",
9
1 : "Collision found",
10
2 : "Point already included",
11
3 : 'Wrong input format. Please provide a string like this: {"x": val, "y": val, "c": val, "d": val, "groupID": val})',
12
4 : "Value mismatch! X != c*P + d*Q",
13
5 : "Server Error"
14
}
15
return '{"Response": "%d", "Message": "%s"%s}' % (code, response_codes[code], additional_parameter)
16
17
18
# Teams should choose a non-guessable groupID
19
def get_response(x, y, c, d, groupID):
20
# open connection to database
21
conn = sqlite3.connect("points.db")
22
conn.row_factory = sqlite3.Row
23
conn_cursor = conn.cursor()
24
25
# convert sage integers to string to avoid "Python int too large for SQLite INTEGER"
26
x = str(x)
27
y = str(y)
28
c = str(c)
29
d = str(d)
30
31
# Select records that map to the same X value
32
conn_cursor.execute("SELECT * FROM points WHERE x = :x", {"x": x})
33
query = conn_cursor.fetchall()
34
35
# No record found -> Point is not yet included
36
if len(query) == 0:
37
# Insert point into database
38
conn_cursor.execute("INSERT INTO points (x, y, c, d, groupID) VALUES (?, ?, ?, ?, ?)",
39
(x, y, c, d, groupID))
40
# Get number of points added by this group
41
conn_cursor.execute("SELECT x FROM points WHERE groupID = :gID", {"gID": groupID})
42
points_found = conn_cursor.fetchall()
43
add_param = ', "points_found": %d' % len(points_found)
44
# When they found POINT_TRESHOLD distinguished points and a collision occured, return the colliding values as well
45
if len(points_found) > POINT_TRESHOLD:
46
add_param += ', "flag1": "%s"' % FLAG1
47
if server.collision_found:
48
# compute x from the collision, second flag is just x (not in flag format)
49
add_param += ', "collision": %s' % (server.collision)
50
response = json_response(0, add_param)
51
else:
52
# One (or more) records found -> check if they have the same exponents
53
is_included = False
54
for row in query:
55
if row["c"] == c and row["d"] == d:
56
is_included = True
57
response = json_response(2)
58
break
59
60
if not is_included:
61
# Exponents are different -> Collision found, add this point
62
conn_cursor.execute("INSERT INTO points (x, y, c, d, groupID, collision) VALUES (?, ?, ?, ?, ?, 1)",
63
(x, y, c, d, groupID))
64
# Get number of points added by this group
65
conn_cursor.execute("SELECT x FROM points WHERE groupID = :gID", {"gID": groupID})
66
points_found = conn_cursor.fetchall()
67
add_param = ', "points_found": %d' % len(points_found)
68
# add collision
69
server.collision_found = True
70
server.collision = '{"c_1": %s, "d_1": %s, "c_2": %s, "d_2": %s}' % (c, d, row["c"], row["d"])
71
if len(points_found) > POINT_TRESHOLD:
72
add_param += ', "collision": %s' % (server.collision)
73
else:
74
add_param += ', "collision": "collision found but not enough distinguished points submitted yet"'
75
76
response = json_response(1, add_param + ', "c": %s, "d": %s' % (row["c"], row["d"]))
77
78
# close db connection and return response
79
conn.commit()
80
conn_cursor.close()
81
conn.close()
82
return response
83
84
85
class DLogHandler(asyncore.dispatcher_with_send):
86
87
def handle_read(self):
88
try:
89
json_data = self.recv(8192)
90
if not json_data:
91
return
92
93
data = json.loads(json_data)
94
# check if the format is correct
95
if not ("x" in data and "y" in data and "c" in data and "d" in data and "groupID" in data):
96
response = json_response(3)
97
else:
98
c = Integer(data["c"])
99
d = Integer(data["d"])
100
x = Integer(data["x"])
101
y = Integer(data["y"])
102
X = E((x, y))
103
if X == c*P + d*Q:
104
response = get_response(data["x"], data["y"], data["c"], data["d"], data["groupID"])
105
else:
106
print("expected %s = %d*%s + %d*%s, but got %s" % (c*P + d*Q, c, P, d, Q, X))
107
response = json_response(4)
108
109
self.send(response)
110
111
except Exception as e:
112
response = json_response(5, ', "Error Message": "%s"' % e)
113
114
115
class Server(asyncore.dispatcher_with_send):
116
117
def __init__(self, host, port):
118
asyncore.dispatcher.__init__(self)
119
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
120
self.set_reuse_addr()
121
self.bind((host, port))
122
self.listen(5)
123
# variable to store some collision
124
self.collision_found = False
125
self.collision = {}
126
127
def handle_accept(self):
128
pair = self.accept()
129
if pair is not None:
130
sock, addr = pair
131
print("incoming connection from %s" % repr(addr))
132
DLogHandler(sock)
133
134
135
if __name__ == '__main__':
136
137
load("parameters.sage")
138
server = Server(serverAdress, serverPort)
139
asyncore.loop()
140
141