-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.py
226 lines (180 loc) · 5.94 KB
/
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
import ecdsa
import json
import hashlib
import os
from flask import Flask, request
import threading
import twisted.internet.reactor as reactor
from twisted.web.wsgi import WSGIResource
from twisted.web.server import Site
global global_result
def deleteBadKey(key):
# Not yet implemented
pass
def verifyECDSA(payload,sig,key_string):
vk = ecdsa.VerifyingKey.from_string(key_string[1:], curve=ecdsa.NIST521p)
tocheck = hashlib.sha256(payload).digest()
sig = sig.decode('hex')
assert sig[0] == '\x04'
sig = sig[1:]
try:
vk.verify(sig,payload, hashfunc=hashlib.sha256) #last element , extract everything except from the last element
print "Good data"
return True
except ecdsa.BadSignatureError:
print "Bad data"
return False
def ls(obj):
cprint("\n".join([x for x in dir(obj) if x[0] != "_"]))
def post(key,value):
cprint("Mock post: %s : %s" % (key,value))
def get(key_list,event):
global global_result
cprint("in get function event.wait is" + str(event.isSet()))
global_result = "Mock global_result"
event.set()
if checkValid(key_list,None):
return "Mock Data"
else:
return "Error: Invalid Request"
def start(getter,poster,web_port):
global get
global post
get = getter
post = poster
port = web_port
app.debug = True
resource = WSGIResource(reactor, reactor.getThreadPool(), app)
site = Site(resource)
reactor.listenTCP(port, site)
reactor.run()
def cprint(string):
OKGREEN = '\033[92m'
ENDC = '\033[0m'
print "%s%s%s" % (OKGREEN,string,ENDC)
def makeKey(user_value, user_data):
#JSON Object as a key
# HCID = Hash Content Identifier
# HKID = Hash Key Identifier
# Type : Purpose
# Blob : Static; contains data
# List : Static; exclusive map from next name segment to HID type
# Commit : Versioned; exclusive map from HKID to HCID
# Tag : Versioned; non-exclusive map from HKID to HID
key_list = list()
try:
hcid = user_value["hcid"]
except KeyError:
hcid = hashlib.sha256(str(user_data)).hexdigest()
else:
pass
finally:
pass
if user_value["type"] == "blob":
cprint("Type Blob")
key_list.append(json.dumps({"type":"blob","hcid":hcid}, sort_keys = True))
# key = json.dumps({"type":"blob","hcid":user_data["hcid"]}, sort_keys = True)
elif user_value["type"] == "commit": # verify before post/respond data
cprint("Type Commit")
key_list.append(json.dumps({"type":"blob","hcid":hcid}, sort_keys = True))
key_list.append(json.dumps({"type":"commit","hkid":user_value["hkid"]}, sort_keys = True))
elif user_value["type"] == "tag": # verify before post/respond data
cprint("Type Tag")
key_list.append(json.dumps({"type":"blob","hcid":hcid}, sort_keys = True))
key_list.append(json.dumps({"type":"tag","hkid":user_value["hkid"],"namesegment":user_data["namesegment"]}, sort_keys = True))
elif user_value["type"] == "key":
cprint("Type Key")
key_list.append(json.dumps({"type":"blob","hcid":hcid}, sort_keys = True))
key_list.append(json.dumps({"type":"key","hkid":user_value["hkid"]}, sort_keys = True))
else:
cprint("Invalid Type")
key_list = None
return key_list
def verifyblob(hkid,data):
return hashlib.sha256(str(data)).hexdigest() == data
def verifytagcommit(hkid,data):
if len(values["hkid"]) != (256/4):
return False
payload, sig = data.rsplit(',\n', 1)
_, obHKID = payload.rsplit(',\n',1)
if obHKID != hkid:
return False
event = threading.Event()
retrievedKey = json.dumps({"type":"blob","hcid":user_value["hcid"]}, sort_keys = True)
thread_object = threading.Thread(group=None, target = get, name=None, args=(retrievedKey,event), kwargs={})
thread_object.start()
if event.wait():
if (len(global_result) > 0):
data_string = global_result[0]
else:
return(str(global_result))
else:
cprint("Fail... Time out")
return verifyECDSA(payload,sig,data_string)
def checkValid(values,data):
if str(values["type"]) == "blob":
return verifyblob(values["hcid"],data)
if (str(values["type"]) == "commit") or (str(values["type"]) == "tag"):
return verifytagcommit(values["hkid"],data)
if (str(values["type"]) == "key") and (len(values["hkid"]) == 256/4):
return True
return False
#################################
app = Flask(__name__)
@app.route('/test',methods=['GET'])
def testSign():
MSG = "Hello World"
#Create signing key
sk = ecdsa.SigningKey.generate(ecdsa.NIST256p)
#Create verifying key
vk = sk.get_verifying_key()
topost = MSG+","+vk.to_pem()+","+sk.sign(MSG).encode("hex")
# post("storage_key",topost)
# #################################################
# event = threading.Event()
# thread_object = threading.Thread(group=None, target = get, name=None, args=("storage_key",event), kwargs={})
# thread_object.start()
# #if event.wait(2):
# return "TestSign" + global_result
# return "Time-out occured"
# #################################################
#got = topost.split(',')
got = topost.split(',')
msg_tocheck = got[0]
try:
vk.verify(got[2].decode("hex"),msg_tocheck)
return("Good Message: " + got[0])
except ecdsa.BadSignatureError:
return("Bad signature")
@app.route('/',methods=['GET', 'POST'])
def getorpost():
global global_result
event = threading.Event()
if request.method == 'POST':
#if type(request.value) is list
key_list = makeKey(request.values,request.data)
#key = makeKeyList(request.values)
data = request.data
if checkValid(request.values,request.data):
for key in key_list:
post(key,data)
return "key is valid:\n %s" % key_list
else:
return "Invalid Input: \n %s" % key_list
elif request.method == 'GET':
global_result = None
key_list = makeKey(request.values,None)
#key = makeKeyList(request.values)
thread_object = threading.Thread(group=None, target = get, name=None, args=(key_list,event), kwargs={})
thread_object.start()
if event.wait():
if (len(global_result) > 0):
return global_result[0]
else:
return(str(global_result))
else:
cprint("Fail... Time out")
return "Time-out occured"
if __name__ == "__main__":
app.debug = True
app.run(host='0.0.0.0')