This repository has been archived by the owner on Nov 23, 2021. It is now read-only.
/
phttp.py
936 lines (745 loc) · 26.6 KB
/
phttp.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
#!/usr/bin/env python3
"""Pattoo HTTP data classes."""
# Standard libraries
import os
import sys
import json
import urllib
import collections
from time import time
# pip3 libraries
import requests
# Pattoo libraries
from pattoo_shared import log
from pattoo_shared.configuration import Config
from pattoo_shared import converter
from pattoo_shared import encrypt
# Save items needed for encrypted purging inside a named tuple
EncryptionSuite = collections.namedtuple(
'EncryptionSuite',
'encrypted_post encryption symmetric_key session')
_KeyExchange = collections.namedtuple(
'_KeyExchange',
'encryption session key_exchange_url symmetric_key_url symmetric_key')
_EncrypedPost = collections.namedtuple(
'_EncrypedPost',
'encryption session symmetric_key encryption_url data identifier')
class _Post():
"""Abstract class to prepare data for posting to remote pattoo server."""
def __init__(self, identifier, data):
"""Initialize the class.
Args:
identifier: Unique identifier for the source of the data. (AgentID)
data: dict of data to post
Returns:
None
"""
# Initialize key variables
self.config = Config()
# Get data and identifier
self._data = data
self._identifier = identifier
def post(self):
"""Post data to API server.
Args:
None
Returns:
None
"""
pass
def purge(self):
"""Delete cached data and post to API server.
Args:
None
Returns:
None
"""
pass
class Post(_Post):
"""Class to prepare data for posting to remote pattoo server."""
def __init__(self, identifier, data):
"""Initialize the class.
Args:
identifier: Agent identifier
data: Data from agent
Returns:
None
"""
_Post.__init__(self, identifier, data)
# URL to post to API server
self._url = self.config.agent_api_server_url(identifier)
def post(self):
"""Post data to central server.
Args:
None
Returns:
success: True: if successful
"""
# Initialize key variables
success = False
# Post data
if bool(self._data) is True:
success = post(self._url, self._data, self._identifier)
else:
log_message = ('''\
Blank data. No data to post from identifier {}.'''.format(self._identifier))
log.log2warning(1018, log_message)
return success
def purge(self):
"""Purge data from cache by posting to central server.
Args:
None
Returns:
None
"""
# Initialize key variables
purge(self._url, self._identifier)
class EncryptedPost(_Post):
"""Encrypted Post.
Class to exchange public keys, set symmetric key and
post symmetrically encrypted data to the API server
First, the agent's information is exchanged. That
information consists of the agent's email address
and public key in ASCII. That information is received
the the API server, the agent's public key is added to
the API server's keyring and the agent's email address
is stored in the API server's session to be used to
retrieve the public key later on. Cookies are used to
uniquely identity the agents. Secondly, the API
server then sends a nonce encrypted by the agent's
public key, the API sever's email address, and the
API server's public key in ASCII. Then, the agent
decrypts the nonce using its own private key. Having
the decrypted nonce, the agent generates a symmetric
key to symmetrically encrypt the nonce. The
symmetric key is then encrypted using the API server's
public key. Those two information are sent off to the
API server. Finally, the encrypted symmetric key is
decrypted using the API server's private key, then the
symmetric key is used to decrypt the nonce. Once the
nonce is verified to be the same that was sent off,
the symmetric is stored, and all other information the
API received is deleted. A response is sent to the
agent and the agent proceeds to send data encrypted by
the symmetric key. The data is decrypted once received
by the API server. See encrypt.py for more details on
the module.
"""
def __init__(self, identifier, data, encryption):
"""Initialize the class.
Args:
identifier: Agent identifier
data: Data from agent
encryption: encrypt.Encryption object
Returns:
None
"""
# Instantiate Post class
_Post.__init__(self, identifier, data)
# Get URLs for encryption
self._encryption = encryption
def purge(self):
"""Purge.
Purge data from cache by posting encrypted data
to the API server.
Args:
None
Returns:
None
"""
# Initialize key variables
success = False
key = encrypt.generate_key(20)
# Create a session and post data
with requests.Session() as session:
# Turn off HTTP Persistent connection
session.keep_alive = False
# Exchange keys
success = key_exchange(
_KeyExchange(
encryption=self._encryption,
session=session,
key_exchange_url=self.config.agent_api_key_url(),
symmetric_key_url=self.config.agent_api_validation_url(),
symmetric_key=key
)
)
# Purge data, encrypt and send to API
if success is True:
purge(
self.config.agent_api_encrypted_url(),
self._identifier,
suite=EncryptionSuite(
encrypted_post=encrypted_post,
encryption=self._encryption,
symmetric_key=key,
session=session
)
)
def post(self):
"""Send encrypted data to the API server.
Args:
None
Returns:
success: True if data was posted successfully
"""
# Initialize key variables
success = False
key = encrypt.generate_key(20)
# Create a session and post data
with requests.Session() as session:
# Turn off HTTP Persistent connection
session.keep_alive = False
# Exchange keys
result = key_exchange(
_KeyExchange(
encryption=self._encryption,
session=session,
key_exchange_url=self.config.agent_api_key_url(),
symmetric_key_url=self.config.agent_api_validation_url(),
symmetric_key=key
)
)
# Return if exchange failed
if result is False:
return success
# Post data
if bool(self._data) is True:
success = encrypted_post(
_EncrypedPost(
encryption=self._encryption,
session=session,
symmetric_key=key,
encryption_url=self.config.agent_api_encrypted_url(),
data=self._data,
identifier=self._identifier
)
)
else:
log_message = '''\
Blank data. No data to post from identifier {}.'''.format(self._identifier)
log.log2warning(1056, log_message)
return success
class PostAgent(Post):
"""Class to post AgentPolledData to remote pattoo server."""
def __init__(self, agentdata):
"""Initialize the class.
Args:
agentdata: AgentPolledData object
Returns:
None
"""
# Get extracted data
identifier = agentdata.agent_id
_data = converter.agentdata_to_post(agentdata)
data = converter.posting_data_points(_data)
# Log message that ties the identifier to an agent_program
_log(agentdata.agent_program, identifier)
# Don't post if agent data is invalid
if agentdata.valid is False:
data = None
# Initialize key variables
Post.__init__(self, identifier, data)
class EncryptedPostAgent(EncryptedPost):
"""Encrypted Post Agent.
Class to prepare data for posting encrypted
data to remote pattoo server."""
def __init__(self, agentdata, encryption):
"""Initialize the class.
Args:
agentdata: Agent data
encryption: encrypt.Encryption object
Returns:
None
"""
# Get extracted data
identifier = agentdata.agent_id
_data = converter.agentdata_to_post(agentdata)
data = converter.posting_data_points(_data)
# Log message that ties the identifier to an agent_program
_log(agentdata.agent_program, identifier)
# Don't post if agent data is invalid
if agentdata.valid is False:
data = None
# Initialize key variables
EncryptedPost.__init__(self, identifier, data, encryption)
class PassiveAgent():
"""Gets data from passive Pattoo Agents for relaying to pattoo API."""
def __init__(self, agent_program, identifier, url):
"""Initialize the class.
Args:
agent_program: Agent program name
identifier: Unique identifier for the source of the data. (AgentID)
url: URL of content to be retrieved from passive Pattoo agent
Returns:
None
"""
# Initialize key variables
self._url = url
self._identifier = identifier
self._agent_program = agent_program
def relay(self):
"""Forward data polled from remote pattoo passive agent.
Args:
None
Returns:
None
"""
# Get data
data = self.get()
identifier = self._identifier
# Post data
if bool(data) is True:
# Log message that ties the identifier to an agent_program
_log(self._agent_program, identifier)
# Post to remote server
server = Post(identifier, data)
success = server.post()
# Purge cache if success is True
if success is True:
server.purge()
def get(self):
"""Get JSON from remote URL.
Args:
None
Returns:
result: dict of JSON retrieved.
"""
# Initialize key variables
result = {}
url = self._url
# Get URL
try:
with urllib.request.urlopen(url) as u_handle:
try:
result = json.loads(u_handle.read().decode())
except:
(etype, evalue, etraceback) = sys.exc_info()
log_message = (
'Error reading JSON from URL {}: [{}, {}, {}]'
''.format(url, etype, evalue, etraceback))
log.log2info(1008, log_message)
except:
# Most likely no connectivity or the TCP port is unavailable
(etype, evalue, etraceback) = sys.exc_info()
log_message = (
'Error contacting URL {}: [{}, {}, {}]'
''.format(url, etype, evalue, etraceback))
log.log2info(1186, log_message)
# Return
return result
def post(url, data, identifier, save=True):
"""Post data to central server.
Args:
url: URL to receive posted data
identifier: Unique identifier for the source of the data. (AgentID)
data: Data dict to post. If None, then uses self._post_data (
Used for testing and cache purging)
save: When True, save data to cache directory if posting fails
Returns:
success: True: if successful
"""
# Initialize key variables
success = False
response = False
# Fail if nothing to post
if isinstance(data, dict) is False or bool(data) is False:
return success
# Post data save to cache if this fails
try:
result = requests.post(url, json=data)
response = True
except:
_exception = sys.exc_info()
log_message = ('Data posting failure')
log.log2exception(1097, _exception, message=log_message)
if save is True:
# Save data to cache
_save_data(data, identifier)
else:
# Proceed normally if there is a failure.
# This will be logged later
pass
# Define success
if response is True:
if result.status_code == 200:
success = True
else:
log_message = ('''\
HTTP {} error for identifier "{}" posted to server {}\
'''.format(result.status_code, identifier, url))
log.log2warning(1017, log_message)
# Save data to cache, remote webserver isn't
# working properly
_save_data(data, identifier)
# Log message
if success is True:
log_message = ('''\
Data for identifier "{}" posted to server {}\
'''.format(identifier, url))
log.log2debug(1027, log_message)
else:
log_message = ('''\
Data for identifier "{}" failed to post to server {}\
'''.format(identifier, url))
log.log2warning(1028, log_message)
# Return
return success
def key_exchange(metadata):
"""Exchange point for API and Agent public keys.
Process:
1) Post agent's email address and ASCII public key to API server.
2) API server responds with its email address, ASCII pubic
key and a nonce encrypted by the agent's public key.
3) The agent decrypts the nonce and re-encrypts it with a randomly
generated symmetric key.
4) The symmetric key is then encrypted by the API server's public key.
5) The encrypted nonce and encrypted symmetric key are sent to the API
server.
6) The API server decrypts this data and checks if nonce that was sent
is the same as the nonce decrypted.
7) If both nonces match, the server sends an OK signal to the agent.
8) The symmetric key is used to encrypt data sent to the API server.
Args:
metadata: _KeyExchange object where:
encryption: encrypt.Encryption object
session: Requests session object
symmetric_key: Symmetric key
symmetric_key_url: API URL for symmetric key validation
key_exchange_url: URL for key exchanges with the API server
identifier: Agent identifier
Returns:
success: True if successful
"""
# Predefine failure response
success = False
# Send the public key
status = _send_agent_public_key(
metadata.session,
metadata.encryption,
metadata.key_exchange_url
)
if status is False:
return success
# Get get API server's public key
data = _get_api_public_key(
metadata.session,
metadata.key_exchange_url
)
if bool(data) is False:
return success
# Exchange symmetric key
success = _send_symmetric_key(
metadata.session,
metadata.encryption,
metadata.symmetric_key_url,
metadata.symmetric_key,
data
)
return success
def _send_agent_public_key(session, encryption, exchange_url):
"""Send public key to the remote API server.
Args:
session: Request Session object
encryption: Encryption object
exchange_url: URL to use for key exchange
Returns:
success: True is successful
"""
# Predefine failure response
success = False
status = None
# Data for POST
send_data = {
'pattoo_agent_email': encryption.email,
'pattoo_agent_key': encryption.pexport()
}
# Convert dict to str
send_data = json.dumps(send_data)
try:
# Send over data
response = session.post(exchange_url, json=send_data)
status = response.status_code
except:
_exception = sys.exc_info()
log_message = ('Key exchange failure')
log.log2exception(1077, _exception, message=log_message)
# Checks that sent data was accepted
if status in [202, 208]:
success = True
else:
log_message = (
'Cannot send public key to API server. Status: {}'.format(status))
log.log2info(1069, log_message)
return success
def _get_api_public_key(session, exchange_url):
"""Use previously established session to get the API server's public key.
Args:
session: Request Session object
exchange_url: URL to use for key exchange
Returns:
result: JSON key data from API server
"""
# Predefine failure response
result = None
status = None
# Get API information
try:
response = session.get(exchange_url)
status = response.status_code
except:
_exception = sys.exc_info()
log_message = ('Key exchange failure')
log.log2exception(1106, _exception, message=log_message)
# Checks that the API sent over information
if status == 200:
# Process API server response
result = response.json()
else:
log_message = (
'Cannot get public key from API server. Status: {}'.format(status))
log.log2info(1057, log_message)
return result
def _send_symmetric_key(
session, encryption, url, symmetric_key, data):
"""Send symmetric_key to the remote API server.
Args:
session: Request Session object
encryption: Encryption object
url: URL to use for exchanging the symmetric key
symmetric_key: Symmetric key
data: Data to post
Returns:
success: True if successful
"""
# Predefine failure response
success = False
status = None
# Process API server information
api_email = data['api_email']
api_key = data['api_key']
encrypted_nonce = data['encrypted_nonce']
# Import API public key
encryption.pimport(api_key)
api_fingerprint = encryption.fingerprint(api_email)
encryption.trust(api_fingerprint)
# Decrypt nonce
decrypted_nonce = encryption.decrypt(encrypted_nonce)
# Create JSON to post
data_ = json.dumps(
{
'encrypted_nonce': encryption.sencrypt(
decrypted_nonce, symmetric_key),
'encrypted_sym_key': encryption.encrypt(
symmetric_key, api_fingerprint)
}
)
# POST data to API
try:
response = session.post(url, json=data_)
status = response.status_code
except:
_exception = sys.exc_info()
log_message = ('Symmetric key exchange failure')
log.log2exception(1098, _exception, message=log_message)
# Check that the transaction was validated
if status == 200:
success = True
else:
log_message = '''\
Cannot exchange symmetric keys with API server. Status: {}'''.format(status)
log.log2info(1099, log_message)
return success
def encrypted_post(metadata, save=True):
"""Post encrypted data to the API server.
First, the data is checked for its validity. Sencondly,
the data and agent ID is stored in a dictionary with
the key value pairs. The dictionary is converted to a
string so that is can be encrypted. The encrypted data
is then paired with a key, as a dictionary, distinguishing
the data as encrypted. The dictionary is then converted
to a string so it can be added to the request method
as json. A response from the API server tells if the data
was received and decrypted successfully.
Args:
metadata: _EncrypedPost object where:
encryption: encrypt.Encryption object
session: Requests session object
symmetric_key: Symmetric key
encryption_url: API URL to post the data to
data: Data to post as a dict
identifier: Agent identifier
save: If True, save data to cache if API server is inaccessible
Returns:
success: True if successful
"""
# Initialize key variables
success = False
status = None
# Fail if nothing to post
if isinstance(metadata.data, dict) is False or bool(
metadata.data) is False:
return success
# Prepare data for posting
data = json.dumps(
{
'data': metadata.data,
'source': metadata.identifier
}
)
# Symmetrically encrypt data
encrypted_data = metadata.encryption.sencrypt(data, metadata.symmetric_key)
# Post data save to cache if this fails
try:
response = metadata.session.post(
metadata.encryption_url,
json=json.dumps({'encrypted_data': encrypted_data})
)
status = response.status_code
except:
_exception = sys.exc_info()
log_message = ('Encrypted posting failure')
log.log2exception(1075, _exception, message=log_message)
if save is True:
# Save data to cache
_save_data(metadata.data, metadata.identifier)
else:
# Proceed normally if there is a failure.
# This will be logged later
pass
# Checks if data was posted successfully
if status == 202:
log_message = 'Posted to API. Response "{}" from URL: "{}"'.format(
status, metadata.encryption_url)
log.log2debug(1059, log_message)
# The data was accepted successfully
success = True
else:
log_message = 'Error posting. Response "{}" from URL: "{}"'.format(
status, metadata.encryption_url)
log.log2warning(1058, log_message)
return success
def purge(url, identifier, suite=post):
"""Purge data from cache by posting to central server.
Args:
url: URL to receive posted data
identifier: Unique identifier for the source of the data. (AgentID)
suite: If a function, this will proceed to use the normal post function
for unencrypted posting. If EncryptionSuite, the necessary
variables from the named tuple will be used along with the
encrypted_post function for encrypted posting
Returns:
None
"""
# Initialize key variables
config = Config()
cache_dir = config.agent_cache_directory(identifier)
# Add files in cache directory to list only if they match the
# cache suffix
all_filenames = [filename for filename in os.listdir(
cache_dir) if os.path.isfile(
os.path.join(cache_dir, filename))]
filenames = [
filename for filename in all_filenames if filename.endswith(
'.json')]
# Read cache file
for filename in filenames:
# Only post files for our own UID value
if identifier not in filename:
continue
# Get the full filepath for the cache file and post
filepath = os.path.join(cache_dir, filename)
with open(filepath, 'r') as f_handle:
try:
data = json.load(f_handle)
except:
# Log removal
log_message = ('''\
Error reading previously cached agent data file {} for identifier {}. May be \
corrupted.'''.format(filepath, identifier))
log.log2warning(1064, log_message)
# Delete file
if os.path.isfile(filepath) is True:
os.remove(filepath)
log_message = ('''\
Deleting corrupted cache file {} for identifier {}.\
'''.format(filepath, identifier))
log.log2warning(1036, log_message)
# Go to the next file.
continue
# Post file
if callable(suite): # Is it a function?
# Post unencrypted data
success = suite(url, data, identifier, save=False)
elif isinstance(suite, EncryptionSuite): # Is it EncryptionSuite?
# Post encrypted data
success = suite.encrypted_post(
_EncrypedPost(
encryption=suite.encryption,
session=suite.session,
symmetric_key=suite.symmetric_key,
encryption_url=url,
data=data,
identifier=identifier
)
)
# Delete file if successful
if success is True:
if os.path.exists(filepath) is True:
os.remove(filepath)
# Log removal
log_message = ('''\
Purging cache file {} after successfully contacting server {}\
'''.format(filepath, url))
log.log2info(1007, log_message)
def _save_data(data, identifier):
"""Save data to cache file.
Args:
data: Dict to save
identifier: Unique identifier for the source of the data. (AgentID)
Returns:
success: True: if successful
"""
# Initialize key variables
success = False
config = Config()
cache_dir = config.agent_cache_directory(identifier)
timestamp = int(time() * 1000)
# Create a unique very long filename to reduce risk of
filename = ('''{}{}{}_{}.json\
'''.format(cache_dir, os.sep, timestamp, identifier))
# Save data
try:
with open(filename, 'w') as f_handle:
json.dump(data, f_handle)
success = True
except Exception as err:
log_message = '{}'.format(err)
log.log2warning(1030, log_message)
except:
(etype, evalue, etraceback) = sys.exc_info()
log_message = ('''\
Cache-file save error: [{}, {}, {}]'''.format(etype, evalue, etraceback))
log.log2warning(1031, log_message)
# Delete file if there is a failure.
# Helps to protect against full file systems.
if os.path.isfile(filename) is True and success is False:
os.remove(filename)
log_message = ('''\
Deleting corrupted cache file {} for identifier {}.\
'''.format(filename, identifier))
log.log2warning(1037, log_message)
# Return
return success
def _log(agent_program, identifier):
"""Create a standardized log message for posting.
Args:
agent_program: Agent program name
identifier: Unique identifier for the source of the data. (AgentID)
Returns:
None
"""
# Log message that ties the identifier to an agent_program
log_message = ('''\
Agent program {} posting data as {}'''.format(agent_program, identifier))
log.log2debug(1038, log_message)