Skip to content

Commit 03ed69a

Browse files
user authentication complete
1 parent 0b23afa commit 03ed69a

File tree

4 files changed

+115
-33
lines changed

4 files changed

+115
-33
lines changed

MISC/playGround.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
import pickle
44
import socket
55
import json
6-
import handelConnection
76
import hashlib
87
import pymongo
8+
from datetime import datetime
99

1010
# ***************************
1111
# Part of opening connection and sending i am online
@@ -58,6 +58,6 @@
5858
# Tests to connect to mongo client
5959
# ***************************
6060
client = pymongo.MongoClient()
61-
db = client.superTest
62-
db.log_events.create_index("date", expireAfterSeconds=15)
63-
db.log_events.insert({"hahaha":"hello world", "date": utc_timestamp})
61+
db = client.MongoLabs
62+
db.test.create_index("date", expireAfterSeconds=15)
63+
db.test.insert({"hahaha":"hello world", "date": datetime.utcnow()})

Server/Auth.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Auth:
2+
def __init__(self,quiz):
3+
self.__challenge = True
4+
self.__response = False
5+
self.__sha384 = ""
6+
self.__quizz = quiz
7+
self.__sharedSecret = ""
8+
9+
def isChallengeComplete(self):
10+
return self.__challenge
11+
12+
def isResponseComplete(self):
13+
return self.__response
14+
15+
def getSha384(self):
16+
return self.__sha384
17+
18+
def getQuizz(self):
19+
return self.__quizz
20+
21+
def getSharedSecret(self):
22+
return self.__sharedSecret
23+
24+
def setSharedSecret(self,secret):
25+
self.__sharedSecret = secret
26+
27+
def setSha348(self,sha348):
28+
self.__sha384 = sha348
29+
30+
def setResponse(self):
31+
self.__response = True

Server/handelConnection.py

+78-27
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os,sys,DH,pickle,binascii
22
import hashlib,zlib,json
3+
from Auth import Auth
34
from random import randint
45
from cryptography.hazmat.primitives import serialization,hashes
56
from cryptography.hazmat.primitives.asymmetric import padding
@@ -20,7 +21,9 @@ def __init__(self):
2021
Purpose : 1) Initialise Connection object
2122
2) Read server private key for future use
2223
'''
23-
self.diffiObj = DH.DiffieHellman()
24+
self.__diffiObj = DH.DiffieHellman()
25+
self.__authDict = {}
26+
self.__sessionKeyDict = {}
2427
with open("private_key.pem", "rb") as key_file:
2528
try:
2629
self.__privateKey = serialization.load_pem_private_key(
@@ -32,7 +35,7 @@ def __init__(self):
3235
sys.exit(0)
3336

3437

35-
def __nowOnlineResponse(self):
38+
def __nowOnlineResponse(self,senderObj):
3639
'''
3740
__nowOnlineResponse(None):
3841
Input : None
@@ -47,11 +50,20 @@ def __nowOnlineResponse(self):
4750
sha = hashlib.sha256()
4851
sha.update(rand+str(t))
4952
guess = sha.digest()
53+
self.__authDict[senderObj["user"]] = Auth(str(t))
5054
obj = {"message-type":"quiz","challange":rand,"answer":guess}
5155
ret = pickle.dumps(obj)
5256
return ret
5357

5458
def __findPasswordHashForUser(self,user):
59+
'''
60+
__findPasswordHashForUser(String):
61+
Input : (String) UserName
62+
Output : False -> If username not found
63+
String -> Password hash
64+
Purpose : Given a username searches if the user is registerd
65+
and returns the username
66+
'''
5567
with open("SERVER.conf") as json_file:
5668
json_data = json.load(json_file)
5769
if user.lower() in json_data:
@@ -64,30 +76,60 @@ def __challangeResponse(self,senderObj):
6476
__challangeResponse(Object):
6577
Input : Object {messageType:"quiz-response", encoded } (Response from server to challenge)
6678
encoded -> {g^a mod p,response}s
67-
Output : Object {}
79+
Output : String
6880
Message format :
6981
{messageType:"initiageSecret", sha256(g^ab mod p + g^bw mod p), g^b mod p}
7082
Purpose : Send server public secret and augmented information
7183
7284
'''
7385

74-
pubKey = self.diffiObj.gen_public_key() # This is (gb mod p)
75-
self.__sharedSecret = self.diffiObj.gen_shared_key(long(senderObj["pubKey"])) # This is (gab mop p)
76-
print "Shared Secret is : ", self.__sharedSecret
86+
if senderObj["user"] in self.__authDict:
87+
authInfo = self.__authDict[senderObj["user"]]
88+
print "Server side quizz",authInfo.getQuizz()
89+
print "Client Side", senderObj["answer"]
90+
if authInfo.getQuizz() == str(senderObj["answer"]):
91+
return self.__challangeResponseHelper(senderObj, authInfo)
92+
else :
93+
self.__authDict.pop(senderObj["user"])
94+
return False
95+
96+
def __challangeResponseHelper(self,senderObj,authInfo):
97+
'''
98+
__challangeResponseHelper(Object,Object):
99+
Input : The Objectified stream data from user
100+
and Authentication info on server
101+
Output : String (Data to be send on wire)
102+
Message format :
103+
{messageType:"initiageSecret", sha256(g^ab mod p + g^bw mod p), g^b mod p}
104+
105+
'''
106+
pubKey = self.__diffiObj.gen_public_key() # This is (gb mod p)
107+
sharedSecret = self.__diffiObj.gen_shared_key(long(senderObj["pubKey"])) # This is (gab mop p)
108+
authInfo.setResponse()
109+
authInfo.setSharedSecret(sharedSecret)
77110
userPassHash = self.__findPasswordHashForUser(senderObj["user"])
78111
if userPassHash:
79-
gpowbw = self.diffiObj.gen_gpowxw(pubKey,userPassHash)
80-
sha = hashlib.sha256()
81-
sha.update(str(gpowbw)+str(self.__sharedSecret))
82-
hash = int(binascii.hexlify(sha.digest()), base=16)
112+
gpowbw = self.__diffiObj.gen_gpowxw(pubKey, userPassHash)
113+
hash256 = self.__genShaX(hashlib.sha256(),str(gpowbw) + str(sharedSecret))
114+
hash384 = self.__genShaX(hashlib.sha384(),str(gpowbw) + str(sharedSecret))
115+
authInfo.setSha348(hash384)
83116
return pickle.dumps({
84-
"messageType" : "initiateSecret",
85-
"hash" :hash,
86-
"pubKey" :pubKey,
87-
})
117+
"messageType": "initiateSecret",
118+
"hash": hash256,
119+
"pubKey": pubKey,
120+
})
88121
return False
89122

123+
def __genShaX(self,sha,message):
124+
'''
125+
__genShaX(Object,String):
126+
Input : Object,Strint (THe sha object ie.sha256,384,512 and the message
127+
to be encrypted)
128+
Output : String (Returns the digest of the message)
90129
130+
'''
131+
sha.update(message)
132+
return int(binascii.hexlify(sha.digest()), base=16)
91133

92134
def __decryptMessageUsingPrivateKey(self, message):
93135
'''
@@ -134,20 +176,31 @@ def __gen384Hash(self,gpowbw,sharedSecret):
134176
hash = int(binascii.hexlify(sha.digest()), base=16)
135177
return hash
136178

137-
def __completeAuth(self,data):
179+
def __completeAuth(self,senderObj):
138180
'''
139181
__completeAuth(Object) :
140-
Input : Object
141-
Output :
142-
143-
'''
144-
hash = data["hash"]
145-
#TODO : Verify if sha384 is same
146-
#TODO : Store sesssion key and complete this whole process
147-
print "Hurray Hurry"
182+
Input : Object (The sender Objectified stream data from user
183+
and Authentication info on server)
184+
Output : False -> If sha384 doesnt match
185+
True -> Password is verified and session key is established
186+
187+
'''
188+
if senderObj["user"] in self.__authDict:
189+
if senderObj["hash"] == self.__authDict[senderObj["user"]].getSha384() :
190+
print "User " + senderObj["user"] + " Connected"
191+
self.__sessionKeyDict[senderObj["user"]] = self.__authDict[senderObj["user"]].getSharedSecret()
192+
return True
193+
else:
194+
self.__authDict.pop(senderObj["user"])
148195
return False
149196

150197
def __loadPickledData(self,message):
198+
'''
199+
__loadPickledData(String):
200+
Input : String (Stream data from socket)
201+
Output : Object
202+
Purpose : Convert the stream data to object
203+
'''
151204
try:
152205
return pickle.loads(message)
153206
except Exception as e:
@@ -182,13 +235,11 @@ def parseData(self,data,address):
182235
decryptedResponse = self.__parseStreamData(data)
183236
ret = False
184237
if decryptedResponse["messageType"] == "now-online":
185-
ret = self.__nowOnlineResponse()
238+
ret = self.__nowOnlineResponse(decryptedResponse)
186239
elif decryptedResponse["messageType"] == "quiz-response":
187240
ret = self.__challangeResponse(decryptedResponse)
188241
elif decryptedResponse["messageType"] == "complete":
189242
ret = self.__completeAuth(decryptedResponse)
190243
if not ret:
191244
self.__logErrors("Response from sender",address)
192-
return "unknownMessage"
193-
else :
194-
return ret
245+
return ret

Server/server.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ def run(self,connectionHandel):
6969
while True:
7070
data , address = self.sock.recvfrom(4096)
7171
data = connectionHandel.parseData(data,address)
72-
if data:
72+
if not isinstance(data, (int)):
7373
self.__sendData(data,address)
7474

7575
def signal_handler(self, signal, frame):
@@ -87,4 +87,4 @@ def signal_handler(self, signal, frame):
8787
if __name__ == "__main__":
8888
c = handelConnection.Connection()
8989
s = server()
90-
s.run(c)
90+
s.run(c)

0 commit comments

Comments
 (0)