forked from SeattleTestbed/seattlelib_v2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
secureadvertise_client.r2py
246 lines (183 loc) · 6.85 KB
/
secureadvertise_client.r2py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
"""
<Program Name>
secureadvertise.r2py
<Started>
July 24, 2008
<Author>
Sebastian Morgan [email protected]
<Purpose>
PUT/GET advertisements to the central server. GET advertisements are
unchanged from previous versions of the advertise server, but PUT
advertisements are now signed with the user's private key and encrypted.
"""
dy_import_module_symbols('session.r2py')
dy_import_module_symbols('sockettimeout.r2py')
dy_import_module_symbols('serialize.r2py')
dy_import_module_symbols('rsa.r2py')
class CentralAdvertiseError(Exception):
pass
# Public variables. Feel free to modify these if using a nonstandard server.
servername = "128.208.4.96"
serverport = 49010
localip = getmyip()
localport = 49030 # Arbitrary.
def secureadvertise_announce(public_key, private_key, value, ttlval):
"""
<Purpose>
Place a value in the centralized advertise server. Places a key:value
dictionary entry in the server for ttlval seconds if successful.
<Arguments>
public_key
User's public key
private_key
User's private key
key
The dictionary entry key. This is how the entry can be retrieved
in a lookup.
value
The dictionary value associated with the key.
ttlval
Time until the advertise server should expire this entry, in seconds.
<Exceptions>
[TODO : POPULATE]
<Side Effects>
If the connection fails or is slow, this will block code execution
in the calling thread.
<Returns>
None
"""
value = str(value)
# Type checking
if not type(ttlval) is int and not type(ttlval) is long:
raise TypeError("Invalid argument! ttlval must be an integer!")
if ttlval < 1:
raise ValueError("Invalid argument! ttlval must be greater than zero!")
# Request server's public key
packet = serialize_serializedata(('KEY', 0))
server_pubkey = None
# Open a connection with the server.
sockobj = timeout_openconn(servername,serverport, localip, localport, timeout=10)
try:
session_sendmessage(sockobj, packet)
response = _wait_for_message(sockobj)
server_pubkey = serialize_deserializedata(response)
sockobj.close()
except Exception:
log("::ERROR:: Couldn't resolve server public key!\n")
# Serialize data payload
serialized_data = serialize_serializedata((value, ttlval))
# Sign serialized data
signed_data = rsa_sign(serialized_data, private_key)
# Encrypt signed data with server's public key.
cypher = rsa_encrypt(signed_data, server_pubkey)
# Construct the packet
data_to_send = ('PUT', public_key, cypher)
# And prepare it for sending
formatted_datastring = serialize_serializedata(data_to_send)
sockobj = timeout_openconn(servername, serverport, localip, localport, timeout=10)
try:
# Attempt to send the packet.
session_sendmessage(sockobj, formatted_datastring)
# We're expecting a confirmation from the server.
response = _wait_for_message(sockobj)
# response = session_recvmessage(sockobj)
finally:
# Could crash.
sockobj.close()
# Verify integrity of returned packet.
try:
# Decode response.
response = serialize_deserializedata(response)
# If we successfully decoded, anything other than 'OK' indicates a failure.
if response != 'OK':
raise CentralAdvertiseError("Centralized announce failed with '" + str(response) + "'")
except ValueError, e:
raise CentralAdvertiseError("Received unknown response from server '" + str(response) + "'")
def secureadvertise_lookup(key, maxvals=100):
"""
<Purpose>
Retrieve a value associated with the given key from the centralized
advertise server. Returns a list of values if successful.
<Arguments>
key
The key to look up in the advertise database.
maxvals
The maximum number of values to return.
<Exceptions>
[TODO : POPULATE]
<Side Effects>
This will block in the calling thread until complete or timed out.
<Returns>
An array of values from the central advertise server.
"""
key = rsa_publickey_to_string(key)
# Type checking.
if not type(maxvals) is int and not type(maxvals) is long:
raise TypeError("Invalid argument! maxvals must be a positive integer!")
if maxvals < 1:
raise ValueError("Invalid argument! maxvals must be positive!")
# Construct the packet.
message_to_send = ('GET', key, maxvals)
formatted_datastring = serialize_serializedata(message_to_send)
# Open a connection with the server.
sockobj = timeout_openconn(servername,serverport, localip, localport, timeout=10)
try:
# Send packet.
session_sendmessage(sockobj, formatted_datastring)
# We expect a response from the server with our data in it.
raw_received_data = _wait_for_message(sockobj)
# raw_received_data = session_recvmessage(sockobj)
finally:
# Could crash.
sockobj.close()
try:
# Try to decode the response.
response_tuple = serialize_deserializedata(raw_received_data)
except ValueError, e:
raise CentralAdvertiseError("Received unknown response from server '" + str(raw_received_data) + "'")
# If it isn't a tuple, something is grossly wrong here.
if not type(response_tuple) is tuple:
raise CentralAdvertiseError("Received data is not a tuple '" + str(raw_received_data) + "'")
# We expect exactly two elements in the response: A confirmation and a list.
if len(response_tuple) != 2:
raise CentralAdvertiseError("Response tuple did not contain exactly two elements '" + str(raw_received_data) + "'")
# If the confirmation is not 'OK', the server met with an error.
if response_tuple[0] != 'OK':
raise CentralAdvertiseError("Central server returned error: " + str(response_tuple) + "'")
# If the response is not a list, something is wrong.
if not type(response_tuple[1]) is list:
raise CentralAdvertiseError("Received item is not a list '" + str(raw_received_data) + "'")
# All entries in the list should be strings.
for responseitem in response_tuple[1]:
if not type(responseitem) is str:
raise CentralAdvertiseError("Received item '" + str(responseitem) + "' is not a string in '" + str(raw_received_data) + "'")
# End result.
return response_tuple
def _wait_for_message(sockobj, timeout = 0.3):
"""
<Purpose>
Attempts to call session_recv until it works or times out.
<Arguments>
sockobj
The socket object to listen on.
timeout
How long to wait before giving up. (In seconds)
<Exceptions>
CentralAdvertiseError
This will be raised if the attempt times out.
<Side Effects>
Blocks until success or timeout.
<Returns>
A string, if successful.
"""
success = False
data = None
start_time = getruntime()
while not success:
try:
data = session_recvmessage(sockobj)
return data
except SocketWouldBlockError:
if getruntime() - start_time > timeout:
raise CentralAdvertiseError("session_recvmessage timed out!")
pass