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