-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuc-v1.1.8-dev.py
1797 lines (1568 loc) · 69.5 KB
/
uc-v1.1.8-dev.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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
# version 1.1.8
# import required modules
import os
import shutil
import socket
import sys
import threading
import time
from datetime import datetime
from getpass import getpass
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, padding, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
client_version = 'v1.1.8'
class colors:
"""class for coloured output
"""
GREEN = '\033[92m'
RED = '\033[91m'
WHITE = '\033[97m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
class cOP:
"""necessary oparands for communication between client and server
"""
FILE = "334"
DIR = "336"
TRANSFER = "340"
OK = "200"
FORBIDDEN = "403"
NOT_FOUND = "404"
UPLOAD = "300"
REMOVE = "299"
DOWNLOAD = "301"
SERVERUPDATE = "302"
PING = "303"
BACKUP = "304"
LISTFS = "306"
GREP = "307"
USERTOKEN = "100"
RST = "RST"
PACKAGE = "310"
LISTALL = "311"
ENCRPYT = "000"
DECRYPT = "999"
SEARCH = "876"
LOCK = "503"
class Debug:
"""debug class
"""
def __init__(self, enabled=True):
self.enabled = enabled
def debug(self, message):
if self.enabled:
print(f"[DEBUG]: {message}")
class EncryptionStub:
"""encryption stub
"""
def __init__(self, debugger):
self.key = ""
self.iv = 0
self.debugger = debugger
def generate_ecdh_keys(self):
client_private_key = ec.generate_private_key(
ec.SECP256R1(), default_backend())
client_public_key = client_private_key.public_key()
return client_private_key, client_public_key
def generate_key_iv(self):
key = os.urandom(32) # Generate a 256-bit (32-byte) key
iv = os.urandom(16) # Generate a 128-bit (16-byte) IV
return key, iv
def encrypt_data(self, plaintext, text=True):
if text:
plaintext = plaintext.encode('utf-8')
# self.debugger.debug(f"Plaintext before encryption: {plaintext}")
cipher = Cipher(
algorithms.AES(
self.key), modes.CBC(
self.iv), backend=default_backend())
padder = padding.PKCS7(algorithms.AES.block_size).padder()
padded_plaintext = padder.update(plaintext) + padder.finalize()
# self.debugger.debug(f"Padded plaintext: {padded_plaintext}")
encryptor = cipher.encryptor()
ciphertext = encryptor.update(padded_plaintext) + encryptor.finalize()
# self.debugger.debug(f"Ciphertext: {ciphertext}")
return ciphertext
def decrypt_data(self, ciphertext, text=True):
# self.debugger.debug(f"Ciphertext before decryption: {ciphertext}")
cipher = Cipher(
algorithms.AES(
self.key), modes.CBC(
self.iv), backend=default_backend())
decryptor = cipher.decryptor()
padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize()
# self.debugger.debug(
# f"Padded plaintext after decryption: {padded_plaintext}")
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
plaintext = unpadder.update(padded_plaintext) + unpadder.finalize()
# self.debugger.debug(f"Plaintext after unpadding: {plaintext}")
if text:
return plaintext.decode('utf-8')
return plaintext
def setup_encryption(self, conn):
self.debugger.debug(f"[{threading.get_ident()}] Start of encryption setup")
server_public_bytes = conn.recv(1024)
server_public_key = serialization.load_pem_public_key(
server_public_bytes,
backend=default_backend()
)
client_private_key, client_public_key = self.generate_ecdh_keys()
self.debugger.debug(f"[{threading.get_ident()}] Serializing key pair to pem format done")
client_public_bytes = client_public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
self.debugger.debug(f"[{threading.get_ident()}] Sending client public key bytes to server")
conn.sendall(client_public_bytes)
shared_secret = client_private_key.exchange(
ec.ECDH(), server_public_key)
derived_key = HKDF(
algorithm=hashes.SHA256(),
length=32 + 16, # 32 bytes for AES-256 key, 16 bytes for IV
salt=None,
info=b'handshake data',
backend=default_backend()
).derive(shared_secret)
self.key = derived_key[:32]
self.iv = derived_key[32:48]
class TCPClient:
"""client implementation
"""
# initializes TCPClient
def __init__(self, host, port, debugger):
# defines address and port
self.serverAddr = host
self.serverPort = port
self.crypt_stub = EncryptionStub(debugger)
self.debugger = debugger
# defines file paths
self.download = '/home/' + os.getlogin() + '/Documents/ultron-server/downloads/'
self.package_path = '/etc/ultron-server/packages/'
self.set_trigger = '/usr/bin/'
# defines class variables for communication and output
self.token = None
self.key = 0
self.iv = 0
self.clientSock = None
self.stop_thread = False
self.thread_alive = False
self.currSize = None
self.currDownloadSize = 0
self.percStatus = '0.00 %'
self.current_date_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.time_buffer = 0.2
# prints output to stdout
def print_log(self, msg):
self.current_date_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(f'[{self.current_date_time}] {msg}')
# tries to connect to the configured server
def check_conn(self, serverAddr, serverPort):
time.sleep(self.time_buffer)
if self.connection_success:
pass
else:
sys.exit()
time.sleep(10)
if self.connection_success:
msg = 'connecting to server [' + str(serverAddr) + ']::[' + str(
serverPort) + '] ' + colors.RED + 'failed' + colors.WHITE
self.print_log(msg)
self.print_log('ERROR: connection timed out')
msg = 'server [' + colors.RED + 'offline' + colors.WHITE + ']'
self.print_log(msg)
sys.exit()
else:
pass
# requests connection from server and returns True or False depending on
# the server message
def request_connection(self, serverAddr, serverPort):
# creating socket
self.current_date_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.clientSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('[' +
str(self.current_date_time) +
'] connecting to server [' +
str(serverAddr) +
']::[' +
str(serverPort) +
'] ...', end='\r')
try:
# connecting to server
self.clientSock.connect((serverAddr, serverPort))
msg = 'connecting to server [' + str(serverAddr) + ']::[' + str(
serverPort) + '] ' + colors.GREEN + 'done' + colors.WHITE
self.print_log(msg)
self.print_log(f'welcome to ultron server!')
# connection established --> returning True
return True
except ConnectionRefusedError:
# printing connection failed to stdout and closing socket
msg = 'connecting to server [' + str(serverAddr) + ']::[' + str(
serverPort) + '] ' + colors.RED + 'failed' + colors.WHITE
self.print_log(msg)
msg = 'server [' + colors.RED + 'offline' + colors.WHITE + ']'
self.print_log(msg)
self.clientSock.close()
sys.exit()
except Exception as error:
# printing error to stdout and closing socket
msg = 'connecting to server [' + str(serverAddr) + ']::[' + str(
serverPort) + '] ' + colors.RED + 'failed' + colors.WHITE
self.print_log(msg)
self.print_log(error)
self.clientSock.close()
sys.exit()
# returns size of directory
def get_size(self, dir1):
total_size = 0
try:
if os.listdir(dir1):
for dirpath, dirnames, filenames in os.walk(dir1):
for f in filenames:
fp = os.path.join(dirpath, f)
# skip if it is symbolic link
if not os.path.islink(fp):
total_size += os.path.getsize(fp)
else:
pass
except FileNotFoundError:
pass
return total_size
# checks if some content is missing
def end_check(self, dirSizeBefore, backupSize, destDir):
currSize = self.get_size(destDir)
self.debugger.debug("end_check: dir_size[%s], backup_size[%s], dest_dir_size[%s]"
% (dirSizeBefore, backupSize, currSize))
if currSize == dirSizeBefore:
actSize = backupSize
else:
actSize = currSize - dirSizeBefore
if int(backupSize) == int(actSize):
return True
else:
return False
# rotating animation output while downloading
# can be disabled to improve performance
def exec_rotation(self, i, h):
c1 = '/'
c2 = '|'
c3 = '\\'
c4 = '—'
rotation = ''
c1i = i % 2
cl3 = h % 4
if int(cl3) == 0:
return c4
elif float(i).is_integer():
return c2
elif int(c1i) == 0:
return c1
else:
return c3
# progress bar when downloading files
def print_load_filestatus(self, byteSize, fileSize):
self.current_date_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
percSize = int(byteSize) / int(fileSize)
percSize *= 100
percSize = round(percSize)
hashtagCount = ''
proccessOutput = ''
percProccess = ''
for i in range(101):
if int(percSize) <= i:
hashtagCount = i * '#'
iCount = 100 - i
proccessOutput = hashtagCount + iCount * '.'
percProccess = f'{i}%'
break
output = f'[{self.current_date_time}] loading [{proccessOutput}] {percProccess}'
print(output, end='\r')
# progress bar when downloading directories
def print_load_status(self, byteSize, fileSize,
destDir, dirSizeBefore, backupSize):
self.current_date_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
currSize = self.get_size(destDir)
actSize = int(currSize) - int(dirSizeBefore)
percSize = int(byteSize) / int(fileSize)
percSize *= 100
percSize = round(percSize)
hashtagCount = ''
proccessOutput = ''
percProccess = ''
for i in range(101):
if int(percSize) <= i:
hashtagCount = i * '#'
iCount = 100 - i
proccessOutput = hashtagCount + iCount * '.'
percProccess = f'{i}%'
break
output = f'[{self.current_date_time}] loading [{proccessOutput}] {percProccess} || {self.percStatus}'
print(output, end='\r')
# returns server status
def ping_request(self):
self.crypt_stub.setup_encryption(self.clientSock)
self.print_log(
f'''requesting ping from [{
self.serverAddr}]::[{
self.serverPort}]''')
self.clientSock.send(self.crypt_stub.encrypt_data(cOP.PING))
answ = self.clientSock.recv(16)
ping = self.crypt_stub.decrypt_data(answ)
if ping == cOP.OK:
self.print_log(
'server [' +
colors.GREEN +
'online' +
colors.WHITE +
']')
self.clientSock.close()
sys.exit
else:
self.print_log(
'server [' + colors.RED + 'offline' + colors.WHITE + ']')
self.clientSock.close()
# downloads content from server
def download_script(self, downloadType, downloadName, clientToken):
self.crypt_stub.setup_encryption(self.clientSock)
# requesting transfer
self.print_log(
f'''requesting transfer from [{
self.serverAddr}]::[{
self.serverPort}]''')
self.clientSock.send(self.crypt_stub.encrypt_data(cOP.DOWNLOAD))
time.sleep(self.time_buffer)
# authentication
# sending client token
self.debugger.debug("sending client token.")
clientToken = clientToken
clientToken = self.crypt_stub.encrypt_data(clientToken)
self.clientSock.send(clientToken)
resp = self.clientSock.recv(1024)
resp = self.crypt_stub.decrypt_data(resp)
# receiving message from server
if resp == cOP.OK:
# authentification OK
# downloading file
if downloadType == 0:
# sending file operand
self.debugger.debug("sending file operand.")
self.clientSock.send(self.crypt_stub.encrypt_data(cOP.FILE))
answ = self.clientSock.recv(16)
answ = self.crypt_stub.decrypt_data(answ)
if answ == cOP.OK:
# transfer accepted
# sendig filename
self.debugger.debug("sending filename.")
fileNameEncr = downloadName
fileNameEncr = self.crypt_stub.encrypt_data(fileNameEncr)
self.clientSock.send(fileNameEncr)
resp = self.clientSock.recv(1024)
resp = self.crypt_stub.decrypt_data(resp)
if resp == cOP.OK:
skip = False
# sending filesize
self.debugger.debug("receiving filesize.")
filesize = self.clientSock.recv(1024)
filesize = self.crypt_stub.decrypt_data(filesize)
filesize = int(filesize)
# checking size of file
# if < 1024 then file will be send in one package
if filesize < 1024:
skip = True
fileData = b''
# if filesize higher than 1024, algorithm fetches all
# packages
self.debugger.debug("receiving bytes.")
while True:
if skip is True:
fileBytes = self.clientSock.recv(filesize)
else:
fileBytes = self.clientSock.recv(1024)
fileData += fileBytes
self.print_load_filestatus(len(fileData), filesize)
if int(filesize) == int(len(fileData)):
print('')
break
else:
pass
# decoding and decrypting content from server
self.debugger.debug("decrypting bytes.")
fileData = fileData
fileData = self.crypt_stub.decrypt_data(fileData, False)
download = self.download + downloadName
# writing download to file
self.debugger.debug("writing file.")
check_dir(self.download)
with open(download, 'wb') as file:
file.write(fileData)
file.close()
self.print_log(
f'file written to {download}. closing connection')
self.clientSock.send(self.crypt_stub.encrypt_data(cOP.OK))
self.clientSock.close()
# closing socket if file could not be found
elif resp == cOP.RST:
self.print_log(
f'''file_not_found_error: closing connection to [{
self.serverAddr}]::[{
self.serverPort}]''')
self.clientSock.close()
# closing socket if selected operand is not available
else:
self.print_log(
'ERROR: wrong operand. permission denied from server')
self.clientSock.close()
# downloads directoriy and its subdirectories
elif downloadType == 1:
# sending directory operand
self.clientSock.send(self.crypt_stub.encrypt_data(cOP.DIR))
# variable to handle transfer
transferDone = False
# receieving answer from server
answ = self.clientSock.recv(16)
answ = self.crypt_stub.decrypt_data(answ)
self.print_log(f'writing changes to {self.download}')
# handling answer
if answ == cOP.OK:
# transfer accepted
# sending directory name
dirNameEncr = downloadName
dirNameEncr = self.crypt_stub.encrypt_data(dirNameEncr)
self.clientSock.send(dirNameEncr)
found = self.clientSock.recv(1024)
found = self.crypt_stub.decrypt_data(found)
# directory found?
if found == cOP.OK:
# yes
# receiving size of directory
backupSize = self.clientSock.recv(1024)
backupSize = self.crypt_stub.decrypt_data(backupSize)
# variables to handle download in the next step
dirSizeBefore = 0
pathName = None
transferVar = False
# receieving content
while not transferDone:
# receiev answer form server if download is
# finished
if not transferVar:
answ = self.clientSock.recv(16)
answ = self.crypt_stub.decrypt_data(answ)
else:
answ = cOP.TRANSFER
transferVar = False
# transfer is still going on
self.debugger.debug("[%s] Received transfer status %s"
% (threading.get_ident(), answ))
if answ == cOP.TRANSFER or answ == cOP.FILE:
# receieving directory name
if answ == cOP.TRANSFER:
self.debugger.debug("[%s] Receiving pathName"
% (threading.get_ident()))
pathName = self.clientSock.recv(1024)
pathName = self.crypt_stub.decrypt_data(pathName)
fileStatus = self.clientSock.recv(1024)
fileStatus = self.crypt_stub.decrypt_data(fileStatus)
else:
fileStatus = cOP.FILE
# receieving file
if fileStatus == cOP.FILE:
skip = False
# receieving file name
fileName = self.clientSock.recv(1024)
fileName = self.crypt_stub.decrypt_data(fileName)
self.debugger.debug("[%s] Received file name %s"
% (threading.get_ident(), fileName))
destDir = self.download + pathName
check_dir(destDir)
dirSizeBefore = self.get_size(destDir)
# receieving file size
filesize = self.clientSock.recv(1024)
filesize = self.crypt_stub.decrypt_data(filesize)
filesize = int(filesize)
# checking size of file
if filesize < 1024:
skip = True
fileData = b''
time.sleep(self.time_buffer)
self.clientSock.send(
self.crypt_stub.encrypt_data(cOP.OK))
# if filesize higher than 1024, algorithm
# fetches all packages
while True:
if skip is True:
fileBytes = self.clientSock.recv(
filesize)
else:
fileBytes = self.clientSock.recv(
1024)
fileData += fileBytes
self.print_load_status(
len(fileData), filesize, destDir,
dirSizeBefore, backupSize)
if int(filesize) == int(len(fileData)):
break
else:
pass
# decrypting bytes from server
fileData = fileData
fileData = self.crypt_stub.decrypt_data(fileData, False)
download = self.download + pathName + fileName
# writing files
with open(download, 'wb') as file:
file.write(fileData)
file.close()
# printing log to stdout
logName = pathName + fileName
self.currDownloadSize = self.currDownloadSize + \
len(fileData)
self.percStatus = self.currDownloadSize / \
int(backupSize)
self.percStatus *= 100
self.percStatus = '{:.2f}'.format(
self.percStatus)
self.percStatus = f'{self.percStatus}%'
self.current_date_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
log = f'[{self.current_date_time}] file written to {logName}.'
lengthPath = len(log)
if lengthPath > 150:
count = 0
else:
count = 150 - lengthPath
space = count * ' '
log += space
print(log)
self.current_date_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
log = f'[{self.current_date_time}] download progress [{self.percStatus}]'
print(log, end='\r')
# sending "file received" message to server
self.clientSock.send(
self.crypt_stub.encrypt_data(cOP.OK))
# transfer goes on
elif fileStatus == cOP.RST:
# download finished
# checking if content is missing
if self.end_check(
dirSizeBefore, backupSize, destDir):
# all fine
self.print_log(
'job done. quitting ')
transferDone = True
self.clientSock.close()
else:
# something is missing
self.print_log(
'\r\nERROR: end_check failed: download incomplete')
self.clientSock.close()
else:
transferVar = True
# download finished
elif answ == cOP.RST:
# checking if content is missing
if self.end_check(
dirSizeBefore, backupSize, destDir):
# all fine
self.print_log(
'job done. quitting ')
transferDone = True
self.clientSock.close()
else:
# something is missing
self.print_log(
'\r\nERROR: end_check failed: download incomplete')
self.clientSock.close()
# connection interrupted
else:
self.print_log(
'\r\nSERVER_SIDE_ERROR: closing connection.')
self.clientSock.close()
transferDone = True
# directory not found
else:
self.print_log(
f'''directory_not_found_error: closing connection to [{
self.serverAddr}]::[{
self.serverPort}]''')
self.clientSock.close()
# authentification failure
elif resp == cOP.FORBIDDEN:
self.print_log('403 forbidden: invalid token')
self.clientSock.close()
# server offline
else:
self.print_log(
'server [' + colors.RED + 'offline' + colors.WHITE + ']')
self.clientSock.close()
# script to perform a complete scan of the client filesystem on the server
def listfs(self, clientToken, oFile):
self.crypt_stub.setup_encryption(self.clientSock)
# requesting list and sending operand
self.print_log(
f'''requesting listfs from [{
self.serverAddr}]::[{
self.serverPort}]''')
self.clientSock.send(self.crypt_stub.encrypt_data(cOP.LISTFS))
time.sleep(self.time_buffer)
# sending client token
clientToken = str(clientToken)
clientToken = self.crypt_stub.encrypt_data(clientToken)
self.clientSock.send(clientToken)
# receiving answer from server
answ = self.clientSock.recv(16)
answ = self.crypt_stub.decrypt_data(answ)
# answer OK?
if answ == cOP.RST:
# no
# closing socket
self.print_log(
f'''connection refused by [{
self.serverAddr}]::[{
self.serverPort}]''')
self.clientSock.close()
elif answ == cOP.OK:
# yes
# sending operands depending on outputfile
if oFile == 'NULL':
# no output file
self.clientSock.send(self.crypt_stub.encrypt_data(cOP.LISTFS))
else:
# output file
self.clientSock.send(self.crypt_stub.encrypt_data(cOP.GREP))
# algorithm to receive all packages
fragmentCount = 0
filesize = self.clientSock.recv(1024)
filesize = self.crypt_stub.decrypt_data(filesize)
filesize = int(filesize)
fileData = b''
current_date_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
if filesize > 1448:
fragmentCount = filesize / 1448
fragmentCount += 1
else:
fragmentCount = 1
for i in range(int(fragmentCount)):
fileBytes = self.clientSock.recv(1500)
fileData += fileBytes
self.print_load_filestatus(len(fileData), filesize)
if filesize == len(fileData):
print(
f'[{current_date_time}] recieved bytes successfully ', end='\r')
break
# decoding and decrypting received data
fileData = fileData
fileData = self.crypt_stub.decrypt_data(fileData)
# handling output
if oFile == "NULL":
# no output file
# printing to stdout
self.print_log('recieved filesystem:\r\n')
print(fileData)
else:
# writing data to output file
with open(self.download + oFile, 'w') as file:
file.write(fileData)
file.close()
space = 120 * " "
self.print_log(
f'''filesystem written to {
self.download +
oFile}{space}''')
# sending operation done and closing socket
self.clientSock.send(self.crypt_stub.encrypt_data(cOP.OK))
self.clientSock.close()
# script to verify authentification token
def test_authtoken(self, clientToken):
self.crypt_stub.setup_encryption(self.clientSock)
# requesting token validation
self.print_log(
f'''requesting token validation from [{
self.serverAddr}]::[{
self.serverPort}]''')
self.clientSock.send(self.crypt_stub.encrypt_data(cOP.USERTOKEN))
time.sleep(self.time_buffer)
# sending user token
clientToken = str(clientToken)
clientToken = self.crypt_stub.encrypt_data(clientToken)
self.clientSock.send(clientToken)
# revceiving answer from server
integrity = self.crypt_stub.decrypt_data(self.clientSock.recv(1024))
# token valid?
if integrity == cOP.OK:
# yes
# printing to stdout and closing socket
self.print_log('auth_token valid')
self.clientSock.close()
elif integrity == cOP.RST:
# no
# printing to stdout and closing socket
self.print_log(
'auth_token invalid. Please contact the administrator for a new token')
self.clientSock.close()
else:
# something went wrong. closing socket
self.print_log(
'could not resolve answer from server. closing connection')
self.clientSock.close()
# script to update client
def updateuc(self):
self.crypt_stub.setup_encryption(self.clientSock)
# requesting update
self.print_log(
f'''updating uc from [{
self.serverAddr}]::[{
self.serverPort}]''')
self.clientSock.send(self.crypt_stub.encrypt_data(cOP.SERVERUPDATE))
# receieving file size
filesize = self.clientSock.recv(1024)
filesize = self.crypt_stub.decrypt_data(filesize)
filesize = int(filesize)
fileData = b''
# reveiving bytes
while True:
fileBytes = self.clientSock.recv(1024)
fileData += fileBytes
self.print_load_filestatus(len(fileData), filesize)
if int(filesize) == int(len(fileData)):
break
else:
pass
# decoding and decrypting bytes
fileData = fileData
fileData = self.crypt_stub.decrypt_data(fileData)
# writing update to file
with open('/usr/bin/uc', 'w') as file:
file.write(fileData)
file.close()
# printing to stdout and closing socket
self.print_log('\nupdated successfully')
self.clientSock.close()
# script to upload a single file
def upload_script(self, fileDirectory, userFile, userToken):
self.crypt_stub.setup_encryption(self.clientSock)
# requesting file upload
current_date_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.print_log(f'''requesting file transfer from
[{self.serverAddr}]::[{self.serverPort}]''')
self.clientSock.send(self.crypt_stub.encrypt_data(cOP.UPLOAD))
time.sleep(self.time_buffer)
# sending user token
userToken = str(userToken)
userToken = self.crypt_stub.encrypt_data(userToken)
self.clientSock.send(userToken)
# receiving ansewer from server
answ = self.clientSock.recv(16)
answ = self.crypt_stub.decrypt_data(answ)
# trying to acquire write access to the client data
if answ == cOP.LOCK:
self.print_log(
f'WARNING: acquiring lock failed. Client resources already in use. Please wait.')
answ = self.clientSock.recv(16)
answ = self.crypt_stub.decrypt_data(answ)
if answ == cOP.OK:
answ = True
elif answ == cOP.OK:
answ = True
else:
self.print_log("ERROR: backup failed: ", answ)
self.clientSock.close()
sys.exit()
# analysing answer
self.debugger.debug(f"Received answer : {answ}")
if answ:
# yes
# upload approved
print(f'[{current_date_time}] sending file...', end='\r')
# sending fileDirectory
time.sleep(self.time_buffer)
fileDirectory = str(fileDirectory)
fileDirectory = self.crypt_stub.encrypt_data(fileDirectory)
self.clientSock.send(fileDirectory)
with open(userFile, 'rb') as file:
data = file.read()
file.close()
data = self.crypt_stub.encrypt_data(data, False)
# sending filesize
fileSize = len(data)
fileSize = str(fileSize)
fileSize = self.crypt_stub.encrypt_data(fileSize)
self.clientSock.send(fileSize)
time.sleep(self.time_buffer)
# reveiving answer from server
self.clientSock.send(data)
answ = self.clientSock.recv(16)
answ = self.crypt_stub.decrypt_data(answ)
# analyse answer
if answ == cOP.OK:
self.print_log('sending file done')
self.clientSock.close()
elif answ == cOP.RST:
self.print_log('sending file failed')
else:
self.print_log(
'could not resolve answer from server. quitting')
self.clientSock.close()
else:
self.print_log('ERROR: could not upload file: ', answ)
self.clientSock.close()
# script to remove content from server
def remove_script(self, removeName, userToken):
self.crypt_stub.setup_encryption(self.clientSock)
# sending request to server
self.print_log(
f'''requesting removal from [{
self.serverAddr}]::[{
self.serverPort}]''')
self.clientSock.send(self.crypt_stub.encrypt_data(cOP.REMOVE))
time.sleep(self.time_buffer)
# sending user token for authentification
userToken = str(userToken)
userToken = self.crypt_stub.encrypt_data(userToken)
self.clientSock.send(userToken)
# reveiving answer from server
answ = self.clientSock.recv(16)
answ = self.crypt_stub.decrypt_data(answ)
# analyse answer
if answ == cOP.OK:
# sending file or directory name to remove
removePath = removeName
removeName = removeName
removeName = self.crypt_stub.encrypt_data(removeName)
# receiving answer
self.clientSock.send(removeName)
answ = self.clientSock.recv(16)
answ = self.crypt_stub.decrypt_data(answ)
# analysing answer
if answ == cOP.OK:
self.print_log(f'removed {removePath}')
self.clientSock.close()
elif answ == cOP.NOT_FOUND:
self.print_log(
f'ERROR: file_not_found_error: could not locate {removePath}')
self.clientSock.close()
# script to backup directory to server
def backup_script(self, srcDirectory, dstDirectory, clientToken):
self.crypt_stub.setup_encryption(self.clientSock)
# function to count size directory
def get_size(dir1):
total_size = 0
for dirpath, dirnames, filenames in os.walk(dir1):
for f in filenames:
fp = os.path.join(dirpath, f)
# skip if it is symbolic link
if not os.path.islink(fp):
total_size += os.path.getsize(fp)
return total_size
# loading animation while backup is pending
def print_loading_backup():
h = 4
i = 2.5
while True:
rot = self.exec_rotation(i, h)
h += 1
i += 0.5
self.current_date_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(
'[' +
self.current_date_time +
'] preparing backup ',
rot,
end='\r')
if self.stop_thread:
break
# progress status in percent while sending content
def print_punct():
while True:
self.current_date_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
if self.stop_thread:
break
print(f'[{self.current_date_time}]',
'sending files . (', self.currSize, '%)', end='\r')
time.sleep(0.5)
print(f'[{self.current_date_time}]',
'sending files .. (', self.currSize, '%)', end='\r')
time.sleep(0.5)
print(f'[{self.current_date_time}]',
'sending files ... (', self.currSize, '%)', end='\r')