-
Notifications
You must be signed in to change notification settings - Fork 0
/
Client.py
237 lines (194 loc) · 8.58 KB
/
Client.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------------#
# Security - Challenge Response Client / Server #
# ============================================================================ #
# Developer: Chavaillaz Johan #
# Filename: ChallengeResponseClient.py #
# Version: 1.0 #
# #
# Licensed to the Apache Software Foundation (ASF) under one #
# or more contributor license agreements. See the NOTICE file #
# distributed with this work for additional information #
# regarding copyright ownership. The ASF licenses this file #
# to you under the Apache License, Version 2.0 (the #
# "License"); you may not use this file except in compliance #
# with the License. You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, #
# software distributed under the License is distributed on an #
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #
# KIND, either express or implied. See the License for the #
# specific language governing permissions and limitations #
# under the License. #
# #
#------------------------------------------------------------------------------#
#------------------------------------------------------------------------------#
# #
# LIBRARIES IMPORT #
# #
#------------------------------------------------------------------------------#
import socket
import sys
import threading
import argparse
import re
import hashlib
from collections import OrderedDict
#------------------------------------------------------------------------------#
# #
# UTILITIES FUNCTIONS #
# #
#------------------------------------------------------------------------------#
def prepareString(content):
return bytes(content + "\n", 'UTF-8')
def getArguments(message):
return message.split(" ")[1:]
def hash(message):
hashObject = hashlib.sha512(message.encode('UTF-8'))
return hashObject.hexdigest()
#------------------------------------------------------------------------------#
# #
# RESPONSE FUNCTIONS #
# #
#------------------------------------------------------------------------------#
def messageResponse(thread):
print(thread.message.replace("MSG ", ""))
def challengeResponse(thread):
print("Challenge received.")
message = getArguments(thread.message)[0] + Settings.data['password']
thread.connection.send(prepareString("CHALLENGE " + hash(message)))
print("Challenge response sent.")
def closeConnectionResponse(thread):
thread.closeConnection = True
print("The connection to the server has been closed.")
#------------------------------------------------------------------------------#
# #
# RESPONSE FUNCTIONS #
# #
#------------------------------------------------------------------------------#
def messageRequest(thread):
thread.connection.send(prepareString(thread.message))
def loginRequest(thread):
arguments = getArguments(thread.message)
if (len(arguments) == 2):
Settings.data['login'] = arguments[0]
Settings.data['password'] = arguments[1]
thread.connection.send(prepareString("LOGIN " + Settings.data['login']))
else:
print("Missing parameters : LOGIN username password")
def closeRequest(thread):
messageRequest(thread)
thread.closeConnection = True
#------------------------------------------------------------------------------#
# #
# CLASSES #
# #
#------------------------------------------------------------------------------#
class Settings:
"""Store settings of the client"""
data = {}
class ThreadReception(threading.Thread):
"""Manages the reception of messages"""
functionArray = OrderedDict([
(r"MSG .*", messageResponse),
(r"CHALLENGE .*", challengeResponse),
(r"CLOSE CONFIRM", closeConnectionResponse),
])
def __init__(self, connection, sendingThread):
threading.Thread.__init__(self)
self.connection = connection
self.message = ""
self.sendingThread = sendingThread
self.closeConnection = False
def run(self):
while not self.closeConnection:
try:
character = self.connection.recv(1)
if character == b'\n':
for regex, function in ThreadReception.functionArray.items():
if re.match(regex, self.message):
function(self)
break
self.message = ""
else:
self.message += character.decode("UTF-8")
except ConnectionResetError:
print("connection dropped by the server.")
break
except KeyboardInterrupt:
print("Client shut down (Keyboard interrupt)")
break
# Force closing sending thread
self.sendingThread._stop()
self.connection.close()
class ThreadSending(threading.Thread):
"""Manages the sending of messages"""
functionArray = OrderedDict([
(r"LOGIN .*", loginRequest),
(r"CLOSE", closeRequest),
(r".*", messageRequest),
])
def __init__(self, connection):
threading.Thread.__init__(self)
self.connection = connection
self.closeConnection = False
self.message = ""
def run(self):
while not self.closeConnection:
try:
self.message = input()
for regex, function in ThreadSending.functionArray.items():
if re.match(regex, self.message):
function(self)
break
except KeyboardInterrupt:
print("Client shut down")
break
#------------------------------------------------------------------------------#
# #
# "MAIN" FUNCTION #
# #
#------------------------------------------------------------------------------#
# If this is the main module, run this
if __name__ == '__main__':
argsCount = len(sys.argv)
# Create argument parser to help user
parser = argparse.ArgumentParser(
description='Server instance for challenge response application.'
)
parser.add_argument(
'server',
type=str,
help='IP server with which to communicate.'
)
parser.add_argument(
'port',
nargs='+',
type=str,
help='Port to use to communicate with the server (Default: 1991).'
)
# Show help if one of the arguments is missing
if argsCount not in [2, 3]:
parser.print_help()
sys.exit()
# Get configuration
host = sys.argv[1]
port = int(sys.argv[2]) if argsCount == 3 else 1991
# Connection establishment
connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
connection.connect((host, port))
except socket.error:
print("Can't connect to server host.")
sys.exit(0)
else:
print("Connection established with the server.")
# Launches two threads to independently manage
# transmission and reception of messages
threadSending = ThreadSending(connection)
threadReception = ThreadReception(connection, threadSending)
threadSending.start()
threadReception.start()