-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcred_server.py
445 lines (313 loc) · 12.5 KB
/
cred_server.py
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
# This is a simple implementation of a credential server using
# the python 3 async framework. It is meant to be used as a
# backend to generate and clear credentials.
# The general imports
import sys
sys.path += ["../examples"]
import asyncio
from io import BytesIO
from msgpack import Unpacker
from petlib.pack import encode, decode, make_encoder, make_decoder
class SReader():
""" Define an asyncio msgpack stream decoder. """
def __init__(self, reader, writer):
""" Pass ina stream reader to unmarshall msgpack objects from. """
self.reader = reader
self.writer = writer
self.decoder = make_decoder()
self.unpacker = Unpacker(ext_hook=self.decoder, encoding="utf8")
self.obj_buf = []
@asyncio.coroutine
def get(self):
""" The co-routine providing objects. """
while len(self.obj_buf) == 0:
buf = yield from self.reader.read(1000)
self.unpacker.feed(buf)
for o in self.unpacker:
self.obj_buf.append(o)
return self.obj_buf.pop(0)
def put(self, obj):
""" Write an object to the channel. """
self.writer.write(encode(obj))
## The crypto imports
from amacscreds import cred_setup, cred_CredKeyge, cred_UserKeyge, cred_secret_issue_user, cred_secret_issue, cred_secret_issue_user_decrypt, cred_show, cred_show_check, cred_secret_issue_user_check
from genzkp import *
from petlib.pack import encode, decode
class CredentialServer():
def __init__(self, num_pub = 3, num_priv = 1):
self.n = num_pub + num_priv
self.params = cred_setup()
self.ipub, self.isec = cred_CredKeyge(self.params, self.n)
@asyncio.coroutine
def handle_cmd(self, reader, writer):
try:
sr = SReader(reader, writer)
CMD = yield from sr.get()
print("Executing: %s" % CMD)
if CMD == "INFO":
yield from self.handle_info(sr)
elif CMD == "ISSUE":
yield from self.handle_issue(sr)
elif CMD == "SHOW":
yield from self.handle_show(sr)
except Exception as e:
print(e)
sr.put("Error")
@asyncio.coroutine
def handle_info(self, sr):
try:
# Part 1. First we write the params and the ipub values
sr.put( (self.params, self.ipub) )
except Exception as e:
print(e)
sr.put("Error")
finally:
sr.writer.close()
@asyncio.coroutine
def handle_issue(self, sr):
try:
# Part 2. Get the public key an Encrypted cred from user
(pub, EGenc, sig_u), public_attr = yield from sr.get()
k, v, timeout = public_attr
# Part 3. Check and generate the credential
if not cred_secret_issue_user_check(self.params, pub, EGenc, sig_u):
raise Exception("Error: Issuing checks failed")
cred_issued = cred_secret_issue(self.params, pub, EGenc, self.ipub, self.isec, public_attr)
sr.put(cred_issued)
except Exception as e:
print(e)
sr.put("Error")
@asyncio.coroutine
def handle_show(self, sr):
try:
(G, g, h, o) = self.params
# Part 4. Get a blinded credential & check it
creds, sig_o, sig_openID, Service_name, Uid, public_attr = yield from sr.get()
(u, Cmis, Cup) = creds
[ key, value, timeout ] = public_attr
if not cred_show_check(self.params, self.ipub, self.isec, creds, sig_o):
raise Exception("Error: aMAC failed")
# Execute the verification on the proof 'sig'
Gid = G.hash_to_point(Service_name)
zk = define_proof(G)
env2 = ZKEnv(zk)
env2.u, env2.h = u, h
env2.Cm0p = Cmis[0] - (key * u)
env2.Cm1p = Cmis[1] - (value * u)
env2.Cm2p = Cmis[2] - (timeout * u)
env2.Cm3 = Cmis[3]
assert len(Cmis) == 4
env2.Uid, env2.Gid = Uid, Gid
if not zk.verify_proof(env2.get(), sig_openID):
raise Exception("Error: ZKP failed")
sr.put("SUCCESS")
yield from sr.writer.drain()
sr.writer.close()
except Exception as e:
import traceback
traceback.print_exc()
print(e)
sr.put("Error")
def define_proof(G):
zk = ZKProof(G)
u, h = zk.get(ConstGen, ["u", "h"])
LT_ID, z0, z1, z2, z3 = zk.get(Sec, ["LT_ID", "z0", "z1", "z2", "z3"])
Cm0p = zk.get(ConstGen, "Cm0p")
Cm1p = zk.get(ConstGen, "Cm1p")
Cm2p = zk.get(ConstGen, "Cm2p")
Cm3 = zk.get(ConstGen, "Cm3")
Uid = zk.get(ConstGen, "Uid")
Gid = zk.get(ConstGen, "Gid")
zk.add_proof(Cm0p, z0 * h)
zk.add_proof(Cm1p, z1 * h)
zk.add_proof(Cm2p, z2 * h)
zk.add_proof(Cm3, LT_ID*u + z3 * h)
zk.add_proof(Uid, LT_ID * Gid)
return zk
import pytest # requires pytest-asyncio!
@asyncio.coroutine
def info_client(ip, port, loop):
""" Implement a client for the INFO command. """
## Setup the channel
reader, writer = yield from asyncio.open_connection(
ip, port, loop=loop)
sr = SReader(reader, writer)
# Send the FULL command
sr.put("INFO")
# Part 1. Get the params and the ipub
(params, ipub) = yield from sr.get()
(G, g, h, o) = params
return params, ipub
@asyncio.coroutine
def issue_client(ip, port, params, ipub, keypair, public_attr, private_attr, loop):
""" Implements a client for the ISSUE protocol. """
## Setup the channel
reader, writer = yield from asyncio.open_connection(
ip, port, loop=loop)
sr = SReader(reader, writer)
# Send the FULL command
sr.put("ISSUE")
# Part 2. Send the encrypted attributes to server
user_token = cred_secret_issue_user(params, keypair, private_attr)
(pub, EGenc, sig_u) = user_token
sr.put( (user_token, public_attr) )
# Part 3. Get the credential back
cred = yield from sr.get()
(u, EncE, sig_s) = cred
mac = cred_secret_issue_user_decrypt(params, keypair, u, EncE, ipub, public_attr, EGenc, sig_s)
return mac, user_token, cred
@asyncio.coroutine
def show_client(ip, port, params, ipub, mac, sig_s, public_attr, private_attr, Service_name, loop):
""" Implements a client for the SHOW command. """
reader, writer = yield from asyncio.open_connection(
ip, port, loop=loop)
sr = SReader(reader, writer)
# Send the FULL command
sr.put("SHOW")
# Part 1. Get the params and the ipub
(G, g, h, o) = params
## User Shows back full credential to issuer
(creds, sig_o, zis) = cred_show(params, ipub, mac, sig_s, public_attr + private_attr, export_zi=True)
[ LT_user_ID ] = private_attr
[ key, value, timeout ] = public_attr
## The credential contains a number of commitments to the attributes
(u, Cmis, Cup) = creds
assert len(Cmis) == 4
assert Cmis[0] == key * u + zis[0] * h
assert Cmis[1] == value * u + zis[1] * h
assert Cmis[2] == timeout * u + zis[2] * h
assert Cmis[3] == LT_user_ID * u + zis[3] * h
# Derive a service specific User ID
Gid = G.hash_to_point(Service_name)
Uid = LT_user_ID * Gid
# Define the statements to be proved
zk = define_proof(G)
# Define the proof environemnt
env = ZKEnv(zk)
env.u, env.h = u, h
env.Cm0p = Cmis[0] - (key * u)
env.Cm1p = Cmis[1] - (value * u)
env.Cm2p = Cmis[2] - (timeout * u)
env.Cm3 = Cmis[3]
env.Uid, env.Gid = Uid, Gid
env.LT_ID = LT_user_ID
env.z0, env.z1, env.z2, env.z3 = zis[0], zis[1], zis[2], zis[3]
sig_openID = zk.build_proof(env.get())
sr.put( (creds, sig_o, sig_openID, Service_name, Uid , public_attr) )
# Check status
resp = yield from sr.get()
writer.close()
return resp
def test_info_server(event_loop, unused_tcp_port):
cs = CredentialServer()
coro = asyncio.start_server(cs.handle_cmd,
'127.0.0.1', unused_tcp_port, loop=event_loop)
event_loop.create_task(coro)
resp = event_loop.run_until_complete(info_client('127.0.0.1', unused_tcp_port, event_loop))
assert tuple(resp[0]) == tuple(cs.params)
def test_issue_server(event_loop, unused_tcp_port):
cs = CredentialServer()
coro = asyncio.start_server(cs.handle_cmd,
'127.0.0.1', unused_tcp_port, loop=event_loop)
event_loop.create_task(coro)
(G, g, h, o) = cs.params
# User creates a public / private key pair
keypair = cred_UserKeyge(cs.params)
# User packages credentials
LT_user_ID = o.random()
timeout = 100
key = 200
value = 300
public_attr = [ key, value, timeout ]
private_attr = [ LT_user_ID ]
resp = event_loop.run_until_complete(issue_client('127.0.0.1', unused_tcp_port,
cs.params, cs.ipub, keypair, public_attr, private_attr, event_loop))
def test_show_server(event_loop, unused_tcp_port):
cs = CredentialServer()
coro = asyncio.start_server(cs.handle_cmd,
'127.0.0.1', unused_tcp_port, loop=event_loop)
event_loop.create_task(coro)
(G, g, h, o) = cs.params
# User creates a public / private key pair
keypair = cred_UserKeyge(cs.params)
# User packages credentials
LT_user_ID = o.random()
timeout = 100
key = 200
value = 300
public_attr = [ key, value, timeout ]
private_attr = [ LT_user_ID ]
resp = event_loop.run_until_complete(issue_client('127.0.0.1', unused_tcp_port,
cs.params, cs.ipub, keypair, public_attr, private_attr, event_loop))
mac, user_token, cred = resp
pub, EGenc, sig_u = user_token
u, EncE, sig_s = cred
Service_name = b"TestService"
resp = event_loop.run_until_complete(show_client('127.0.0.1', unused_tcp_port,
cs.params, cs.ipub, mac, sig_s, public_attr, private_attr, Service_name,
event_loop))
assert resp == "SUCCESS"
def test__server_timing(event_loop, unused_tcp_port):
cs = CredentialServer()
coro = asyncio.start_server(cs.handle_cmd,
'127.0.0.1', unused_tcp_port, loop=event_loop)
event_loop.create_task(coro)
(G, g, h, o) = cs.params
# User creates a public / private key pair
keypair = cred_UserKeyge(cs.params)
# User packages credentials
LT_user_ID = o.random()
timeout = 100
key = 200
value = 300
public_attr = [ key, value, timeout ]
private_attr = [ LT_user_ID ]
import time
t0 = time.monotonic()
for _ in range(10):
resp = event_loop.run_until_complete(issue_client('127.0.0.1', unused_tcp_port,
cs.params, cs.ipub, keypair, public_attr, private_attr, event_loop))
t1 = time.monotonic()
print("ISSUE time (1): %.3f sec" % ((t1-t0) / 10))
t0 = time.monotonic()
coros = [issue_client('127.0.0.1', unused_tcp_port,
cs.params, cs.ipub, keypair, public_attr, private_attr, event_loop) for _ in range(10)]
G = asyncio.gather(loop=event_loop, *(tuple(coros)))
event_loop.run_until_complete(G)
t1 = time.monotonic()
print("ISSUE time (2): %.3f sec" % ((t1-t0) / 10))
mac, user_token, cred = resp
pub, EGenc, sig_u = user_token
u, EncE, sig_s = cred
Service_name = b"TestService"
t0 = time.monotonic()
for _ in range(10):
resp = event_loop.run_until_complete(show_client('127.0.0.1', unused_tcp_port,
cs.params, cs.ipub, mac, sig_s, public_attr, private_attr, Service_name,
event_loop))
t1 = time.monotonic()
print("SHOW time (1): %.3f sec" % ((t1-t0) / 10))
t0 = time.monotonic()
coros = [show_client('127.0.0.1', unused_tcp_port,
cs.params, cs.ipub, mac, sig_s, public_attr, private_attr, Service_name,
event_loop) for _ in range(10)]
G = asyncio.gather(loop=event_loop, *(tuple(coros)))
event_loop.run_until_complete(G)
t1 = time.monotonic()
print("SHOW time (2): %.3f sec" % ((t1-t0) / 10))
assert resp == "SUCCESS"
print(define_proof(G).render_proof_statement())
if __name__ == "__main__":
loop = asyncio.get_event_loop()
coro = asyncio.start_server(handle_cmd, '127.0.0.1', 8888, loop=loop)
server = loop.run_until_complete(coro)
# Serve requests until Ctrl+C is pressed
print('Serving on {}'.format(server.sockets[0].getsockname()))
try:
loop.run_forever()
except KeyboardInterrupt:
pass
# Close the server
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()